]> code.delx.au - gnu-emacs/blob - lisp/org/org.el
2009-01-27 Carsten Dominik <carsten.dominik@gmail.com>
[gnu-emacs] / lisp / org / org.el
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, 2009
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.19e
10 ;;
11 ;; This file is part of GNU Emacs.
12 ;;
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;
27 ;;; Commentary:
28 ;;
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
31 ;;
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
46 ;;
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
50 ;;
51 ;; http://orgmode.org/org.html#Installation
52 ;;
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
60 ;;
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
63 ;;
64 ;;; Code:
65
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
70
71 ;;;; Require other packages
72
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
86
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-footnote)
92
93 ;;;; Customization variables
94
95 ;;; Version
96
97 (defconst org-version "6.19e"
98 "The version number of the file org.el.")
99
100 (defun org-version (&optional here)
101 "Show the org-mode version in the echo area.
102 With prefix arg HERE, insert it at point."
103 (interactive "P")
104 (let ((version (format "Org-mode version %s" org-version)))
105 (message version)
106 (if here
107 (insert version))))
108
109 ;;; Compatibility constants
110
111 ;;; The custom variables
112
113 (defgroup org nil
114 "Outline-based notes management and organizer."
115 :tag "Org"
116 :group 'outlines
117 :group 'hypermedia
118 :group 'calendar)
119
120 (defcustom org-load-hook nil
121 "Hook that is run after org.el has been loaded."
122 :group 'org
123 :type 'hook)
124
125 (defvar org-modules) ; defined below
126 (defvar org-modules-loaded nil
127 "Have the modules been loaded already?")
128
129 (defun org-load-modules-maybe (&optional force)
130 "Load all extensions listed in `org-modules'."
131 (when (or force (not org-modules-loaded))
132 (mapc (lambda (ext)
133 (condition-case nil (require ext)
134 (error (message "Problems while trying to load feature `%s'" ext))))
135 org-modules)
136 (setq org-modules-loaded t)))
137
138 (defun org-set-modules (var value)
139 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
140 (set var value)
141 (when (featurep 'org)
142 (org-load-modules-maybe 'force)))
143
144 (when (org-bound-and-true-p org-modules)
145 (let ((a (member 'org-infojs org-modules)))
146 (and a (setcar a 'org-jsinfo))))
147
148 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
149 "Modules that should always be loaded together with org.el.
150 If a description starts with <C>, the file is not part of Emacs
151 and loading it will require that you have downloaded and properly installed
152 the org-mode distribution.
153
154 You can also use this system to load external packages (i.e. neither Org
155 core modules, not modules from the CONTRIB directory). Just add symbols
156 to the end of the list. If the package is called org-xyz.el, then you need
157 to add the symbol `xyz', and the package must have a call to
158
159 (provide 'org-xyz)"
160 :group 'org
161 :set 'org-set-modules
162 :type
163 '(set :greedy t
164 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
165 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
166 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
167 (const :tag " id: Global IDs for identifying entries" org-id)
168 (const :tag " info: Links to Info nodes" org-info)
169 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
170 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
171 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
172 (const :tag " mew Links to Mew folders/messages" org-mew)
173 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
174 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
175 (const :tag " vm: Links to VM folders/messages" org-vm)
176 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
177 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
178 (const :tag " mouse: Additional mouse support" org-mouse)
179
180 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
181 (const :tag "C annotation-helper: Call Remember directly from Browser" org-annotation-helper)
182 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
183 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
184 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
185 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
186 (const :tag "C eval: Include command output as text" org-eval)
187 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
188 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
189 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
190 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
191 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
192 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
193 (const :tag "C mtags: Support for muse-like tags" org-mtags)
194 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
195 (const :tag "C registry: A registry for Org links" org-registry)
196 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
197 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
198 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
199 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
200 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
201
202 (defcustom org-support-shift-select nil
203 "Non-nil means, make shift-cursor commands select text when possible.
204
205 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
206 selecting a region, or enlarge thusly regions started in this way.
207 In Org-mode, in special contexts, these same keys are used for other
208 purposes, important enough to compete with shift selection. Org tries
209 to balance these needs by supporting `shift-select-mode' outside these
210 special contexts, under control of this variable.
211
212 The default of this variable is nil, to avoid confusing behavior. Shifted
213 cursor keys will then execute Org commands in the following contexts:
214 - on a headline, changing TODO state (left/right) and priority (up/down)
215 - on a time stamp, changing the time
216 - in a plain list item, changing the bullet type
217 - in a property definition line, switching between allowed values
218 - in the BEGIN line of a clock table (changing the time block).
219 Outside these contexts, the commands will throw an error.
220
221 When this variable is t and the cursor is not in a special context,
222 Org-mode will support shift-selection for making and enlarging regions.
223 To make this more effective, the bullet cycling will no longer happen
224 anywhere in an item line, but only if the cursor is exactly on the bullet.
225
226 If you set this variable to the symbol `always', then the keys
227 will not be special in headlines, property lines, and item lines, to make
228 shift selection work there as well. If this is what you want, you can
229 use the following alternative commands: `C-c C-t' and `C-c ,' to
230 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
231 TODO sets, `C-c -' to cycle item bullet types, and properties can be
232 edited by hand or in column view.
233
234 However, when the cursor is on a timestamp, shift-cursor commands
235 will still edit the time stamp - this is just too good to give up.
236
237 XEmacs user should have this variable set to nil, because shift-select-mode
238 is Emacs 23 only."
239 :group 'org
240 :type '(choice
241 (const :tag "Never" nil)
242 (const :tag "When outside special context" t)
243 (const :tag "Everywhere except timestamps" always)))
244
245 (defgroup org-startup nil
246 "Options concerning startup of Org-mode."
247 :tag "Org Startup"
248 :group 'org)
249
250 (defcustom org-startup-folded t
251 "Non-nil means, entering Org-mode will switch to OVERVIEW.
252 This can also be configured on a per-file basis by adding one of
253 the following lines anywhere in the buffer:
254
255 #+STARTUP: fold
256 #+STARTUP: nofold
257 #+STARTUP: content"
258 :group 'org-startup
259 :type '(choice
260 (const :tag "nofold: show all" nil)
261 (const :tag "fold: overview" t)
262 (const :tag "content: all headlines" content)))
263
264 (defcustom org-startup-truncated t
265 "Non-nil means, entering Org-mode will set `truncate-lines'.
266 This is useful since some lines containing links can be very long and
267 uninteresting. Also tables look terrible when wrapped."
268 :group 'org-startup
269 :type 'boolean)
270
271 (defcustom org-startup-align-all-tables nil
272 "Non-nil means, align all tables when visiting a file.
273 This is useful when the column width in tables is forced with <N> cookies
274 in table fields. Such tables will look correct only after the first re-align.
275 This can also be configured on a per-file basis by adding one of
276 the following lines anywhere in the buffer:
277 #+STARTUP: align
278 #+STARTUP: noalign"
279 :group 'org-startup
280 :type 'boolean)
281
282 (defcustom org-insert-mode-line-in-empty-file nil
283 "Non-nil means insert the first line setting Org-mode in empty files.
284 When the function `org-mode' is called interactively in an empty file, this
285 normally means that the file name does not automatically trigger Org-mode.
286 To ensure that the file will always be in Org-mode in the future, a
287 line enforcing Org-mode will be inserted into the buffer, if this option
288 has been set."
289 :group 'org-startup
290 :type 'boolean)
291
292 (defcustom org-replace-disputed-keys nil
293 "Non-nil means use alternative key bindings for some keys.
294 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
295 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
296 If you want to use Org-mode together with one of these other modes,
297 or more generally if you would like to move some Org-mode commands to
298 other keys, set this variable and configure the keys with the variable
299 `org-disputed-keys'.
300
301 This option is only relevant at load-time of Org-mode, and must be set
302 *before* org.el is loaded. Changing it requires a restart of Emacs to
303 become effective."
304 :group 'org-startup
305 :type 'boolean)
306
307 (defcustom org-use-extra-keys nil
308 "Non-nil means use extra key sequence definitions for certain
309 commands. This happens automatically if you run XEmacs or if
310 window-system is nil. This variable lets you do the same
311 manually. You must set it before loading org.
312
313 Example: on Carbon Emacs 22 running graphically, with an external
314 keyboard on a Powerbook, the default way of setting M-left might
315 not work for either Alt or ESC. Setting this variable will make
316 it work for ESC."
317 :group 'org-startup
318 :type 'boolean)
319
320 (if (fboundp 'defvaralias)
321 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
322
323 (defcustom org-disputed-keys
324 '(([(shift up)] . [(meta p)])
325 ([(shift down)] . [(meta n)])
326 ([(shift left)] . [(meta -)])
327 ([(shift right)] . [(meta +)])
328 ([(control shift right)] . [(meta shift +)])
329 ([(control shift left)] . [(meta shift -)]))
330 "Keys for which Org-mode and other modes compete.
331 This is an alist, cars are the default keys, second element specifies
332 the alternative to use when `org-replace-disputed-keys' is t.
333
334 Keys can be specified in any syntax supported by `define-key'.
335 The value of this option takes effect only at Org-mode's startup,
336 therefore you'll have to restart Emacs to apply it after changing."
337 :group 'org-startup
338 :type 'alist)
339
340 (defun org-key (key)
341 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
342 Or return the original if not disputed."
343 (if org-replace-disputed-keys
344 (let* ((nkey (key-description key))
345 (x (org-find-if (lambda (x)
346 (equal (key-description (car x)) nkey))
347 org-disputed-keys)))
348 (if x (cdr x) key))
349 key))
350
351 (defun org-find-if (predicate seq)
352 (catch 'exit
353 (while seq
354 (if (funcall predicate (car seq))
355 (throw 'exit (car seq))
356 (pop seq)))))
357
358 (defun org-defkey (keymap key def)
359 "Define a key, possibly translated, as returned by `org-key'."
360 (define-key keymap (org-key key) def))
361
362 (defcustom org-ellipsis nil
363 "The ellipsis to use in the Org-mode outline.
364 When nil, just use the standard three dots. When a string, use that instead,
365 When a face, use the standard 3 dots, but with the specified face.
366 The change affects only Org-mode (which will then use its own display table).
367 Changing this requires executing `M-x org-mode' in a buffer to become
368 effective."
369 :group 'org-startup
370 :type '(choice (const :tag "Default" nil)
371 (face :tag "Face" :value org-warning)
372 (string :tag "String" :value "...#")))
373
374 (defvar org-display-table nil
375 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
376
377 (defgroup org-keywords nil
378 "Keywords in Org-mode."
379 :tag "Org Keywords"
380 :group 'org)
381
382 (defcustom org-deadline-string "DEADLINE:"
383 "String to mark deadline entries.
384 A deadline is this string, followed by a time stamp. Should be a word,
385 terminated by a colon. You can insert a schedule keyword and
386 a timestamp with \\[org-deadline].
387 Changes become only effective after restarting Emacs."
388 :group 'org-keywords
389 :type 'string)
390
391 (defcustom org-scheduled-string "SCHEDULED:"
392 "String to mark scheduled TODO entries.
393 A schedule is this string, followed by a time stamp. Should be a word,
394 terminated by a colon. You can insert a schedule keyword and
395 a timestamp with \\[org-schedule].
396 Changes become only effective after restarting Emacs."
397 :group 'org-keywords
398 :type 'string)
399
400 (defcustom org-closed-string "CLOSED:"
401 "String used as the prefix for timestamps logging closing a TODO entry."
402 :group 'org-keywords
403 :type 'string)
404
405 (defcustom org-clock-string "CLOCK:"
406 "String used as prefix for timestamps clocking work hours on an item."
407 :group 'org-keywords
408 :type 'string)
409
410 (defcustom org-comment-string "COMMENT"
411 "Entries starting with this keyword will never be exported.
412 An entry can be toggled between COMMENT and normal with
413 \\[org-toggle-comment].
414 Changes become only effective after restarting Emacs."
415 :group 'org-keywords
416 :type 'string)
417
418 (defcustom org-quote-string "QUOTE"
419 "Entries starting with this keyword will be exported in fixed-width font.
420 Quoting applies only to the text in the entry following the headline, and does
421 not extend beyond the next headline, even if that is lower level.
422 An entry can be toggled between QUOTE and normal with
423 \\[org-toggle-fixed-width-section]."
424 :group 'org-keywords
425 :type 'string)
426
427 (defconst org-repeat-re
428 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
429 "Regular expression for specifying repeated events.
430 After a match, group 1 contains the repeat expression.")
431
432 (defgroup org-structure nil
433 "Options concerning the general structure of Org-mode files."
434 :tag "Org Structure"
435 :group 'org)
436
437 (defgroup org-reveal-location nil
438 "Options about how to make context of a location visible."
439 :tag "Org Reveal Location"
440 :group 'org-structure)
441
442 (defconst org-context-choice
443 '(choice
444 (const :tag "Always" t)
445 (const :tag "Never" nil)
446 (repeat :greedy t :tag "Individual contexts"
447 (cons
448 (choice :tag "Context"
449 (const agenda)
450 (const org-goto)
451 (const occur-tree)
452 (const tags-tree)
453 (const link-search)
454 (const mark-goto)
455 (const bookmark-jump)
456 (const isearch)
457 (const default))
458 (boolean))))
459 "Contexts for the reveal options.")
460
461 (defcustom org-show-hierarchy-above '((default . t))
462 "Non-nil means, show full hierarchy when revealing a location.
463 Org-mode often shows locations in an org-mode file which might have
464 been invisible before. When this is set, the hierarchy of headings
465 above the exposed location is shown.
466 Turning this off for example for sparse trees makes them very compact.
467 Instead of t, this can also be an alist specifying this option for different
468 contexts. Valid contexts are
469 agenda when exposing an entry from the agenda
470 org-goto when using the command `org-goto' on key C-c C-j
471 occur-tree when using the command `org-occur' on key C-c /
472 tags-tree when constructing a sparse tree based on tags matches
473 link-search when exposing search matches associated with a link
474 mark-goto when exposing the jump goal of a mark
475 bookmark-jump when exposing a bookmark location
476 isearch when exiting from an incremental search
477 default default for all contexts not set explicitly"
478 :group 'org-reveal-location
479 :type org-context-choice)
480
481 (defcustom org-show-following-heading '((default . nil))
482 "Non-nil means, show following heading when revealing a location.
483 Org-mode often shows locations in an org-mode file which might have
484 been invisible before. When this is set, the heading following the
485 match is shown.
486 Turning this off for example for sparse trees makes them very compact,
487 but makes it harder to edit the location of the match. In such a case,
488 use the command \\[org-reveal] to show more context.
489 Instead of t, this can also be an alist specifying this option for different
490 contexts. See `org-show-hierarchy-above' for valid contexts."
491 :group 'org-reveal-location
492 :type org-context-choice)
493
494 (defcustom org-show-siblings '((default . nil) (isearch t))
495 "Non-nil means, show all sibling heading when revealing a location.
496 Org-mode often shows locations in an org-mode file which might have
497 been invisible before. When this is set, the sibling of the current entry
498 heading are all made visible. If `org-show-hierarchy-above' is t,
499 the same happens on each level of the hierarchy above the current entry.
500
501 By default this is on for the isearch context, off for all other contexts.
502 Turning this off for example for sparse trees makes them very compact,
503 but makes it harder to edit the location of the match. In such a case,
504 use the command \\[org-reveal] to show more context.
505 Instead of t, this can also be an alist specifying this option for different
506 contexts. See `org-show-hierarchy-above' for valid contexts."
507 :group 'org-reveal-location
508 :type org-context-choice)
509
510 (defcustom org-show-entry-below '((default . nil))
511 "Non-nil means, show the entry below a headline when revealing a location.
512 Org-mode often shows locations in an org-mode file which might have
513 been invisible before. When this is set, the text below the headline that is
514 exposed is also shown.
515
516 By default this is off for all contexts.
517 Instead of t, this can also be an alist specifying this option for different
518 contexts. See `org-show-hierarchy-above' for valid contexts."
519 :group 'org-reveal-location
520 :type org-context-choice)
521
522 (defcustom org-indirect-buffer-display 'other-window
523 "How should indirect tree buffers be displayed?
524 This applies to indirect buffers created with the commands
525 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
526 Valid values are:
527 current-window Display in the current window
528 other-window Just display in another window.
529 dedicated-frame Create one new frame, and re-use it each time.
530 new-frame Make a new frame each time. Note that in this case
531 previously-made indirect buffers are kept, and you need to
532 kill these buffers yourself."
533 :group 'org-structure
534 :group 'org-agenda-windows
535 :type '(choice
536 (const :tag "In current window" current-window)
537 (const :tag "In current frame, other window" other-window)
538 (const :tag "Each time a new frame" new-frame)
539 (const :tag "One dedicated frame" dedicated-frame)))
540
541 (defgroup org-cycle nil
542 "Options concerning visibility cycling in Org-mode."
543 :tag "Org Cycle"
544 :group 'org-structure)
545
546 (defcustom org-drawers '("PROPERTIES" "CLOCK")
547 "Names of drawers. Drawers are not opened by cycling on the headline above.
548 Drawers only open with a TAB on the drawer line itself. A drawer looks like
549 this:
550 :DRAWERNAME:
551 .....
552 :END:
553 The drawer \"PROPERTIES\" is special for capturing properties through
554 the property API.
555
556 Drawers can be defined on the per-file basis with a line like:
557
558 #+DRAWERS: HIDDEN STATE PROPERTIES"
559 :group 'org-structure
560 :type '(repeat (string :tag "Drawer Name")))
561
562 (defcustom org-cycle-global-at-bob nil
563 "Cycle globally if cursor is at beginning of buffer and not at a headline.
564 This makes it possible to do global cycling without having to use S-TAB or
565 C-u TAB. For this special case to work, the first line of the buffer
566 must not be a headline - it may be empty ot some other text. When used in
567 this way, `org-cycle-hook' is disables temporarily, to make sure the
568 cursor stays at the beginning of the buffer.
569 When this option is nil, don't do anything special at the beginning
570 of the buffer."
571 :group 'org-cycle
572 :type 'boolean)
573
574 (defcustom org-cycle-emulate-tab t
575 "Where should `org-cycle' emulate TAB.
576 nil Never
577 white Only in completely white lines
578 whitestart Only at the beginning of lines, before the first non-white char
579 t Everywhere except in headlines
580 exc-hl-bol Everywhere except at the start of a headline
581 If TAB is used in a place where it does not emulate TAB, the current subtree
582 visibility is cycled."
583 :group 'org-cycle
584 :type '(choice (const :tag "Never" nil)
585 (const :tag "Only in completely white lines" white)
586 (const :tag "Before first char in a line" whitestart)
587 (const :tag "Everywhere except in headlines" t)
588 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
589 ))
590
591 (defcustom org-cycle-separator-lines 2
592 "Number of empty lines needed to keep an empty line between collapsed trees.
593 If you leave an empty line between the end of a subtree and the following
594 headline, this empty line is hidden when the subtree is folded.
595 Org-mode will leave (exactly) one empty line visible if the number of
596 empty lines is equal or larger to the number given in this variable.
597 So the default 2 means, at least 2 empty lines after the end of a subtree
598 are needed to produce free space between a collapsed subtree and the
599 following headline.
600
601 Special case: when 0, never leave empty lines in collapsed view."
602 :group 'org-cycle
603 :type 'integer)
604 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
605
606 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
607 org-cycle-hide-drawers
608 org-cycle-show-empty-lines
609 org-optimize-window-after-visibility-change)
610 "Hook that is run after `org-cycle' has changed the buffer visibility.
611 The function(s) in this hook must accept a single argument which indicates
612 the new state that was set by the most recent `org-cycle' command. The
613 argument is a symbol. After a global state change, it can have the values
614 `overview', `content', or `all'. After a local state change, it can have
615 the values `folded', `children', or `subtree'."
616 :group 'org-cycle
617 :type 'hook)
618
619 (defgroup org-edit-structure nil
620 "Options concerning structure editing in Org-mode."
621 :tag "Org Edit Structure"
622 :group 'org-structure)
623
624 (defcustom org-odd-levels-only nil
625 "Non-nil means, skip even levels and only use odd levels for the outline.
626 This has the effect that two stars are being added/taken away in
627 promotion/demotion commands. It also influences how levels are
628 handled by the exporters.
629 Changing it requires restart of `font-lock-mode' to become effective
630 for fontification also in regions already fontified.
631 You may also set this on a per-file basis by adding one of the following
632 lines to the buffer:
633
634 #+STARTUP: odd
635 #+STARTUP: oddeven"
636 :group 'org-edit-structure
637 :group 'org-font-lock
638 :type 'boolean)
639
640 (defcustom org-adapt-indentation t
641 "Non-nil means, adapt indentation when promoting and demoting.
642 When this is set and the *entire* text in an entry is indented, the
643 indentation is increased by one space in a demotion command, and
644 decreased by one in a promotion command. If any line in the entry
645 body starts at column 0, indentation is not changed at all."
646 :group 'org-edit-structure
647 :type 'boolean)
648
649 (defcustom org-special-ctrl-a/e nil
650 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
651 When t, `C-a' will bring back the cursor to the beginning of the
652 headline text, i.e. after the stars and after a possible TODO keyword.
653 In an item, this will be the position after the bullet.
654 When the cursor is already at that position, another `C-a' will bring
655 it to the beginning of the line.
656 `C-e' will jump to the end of the headline, ignoring the presence of tags
657 in the headline. A second `C-e' will then jump to the true end of the
658 line, after any tags.
659 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
660 and only a directly following, identical keypress will bring the cursor
661 to the special positions."
662 :group 'org-edit-structure
663 :type '(choice
664 (const :tag "off" nil)
665 (const :tag "after bullet first" t)
666 (const :tag "border first" reversed)))
667
668 (if (fboundp 'defvaralias)
669 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
670
671 (defcustom org-special-ctrl-k nil
672 "Non-nil means `C-k' will behave specially in headlines.
673 When nil, `C-k' will call the default `kill-line' command.
674 When t, the following will happen while the cursor is in the headline:
675
676 - When the cursor is at the beginning of a headline, kill the entire
677 line and possible the folded subtree below the line.
678 - When in the middle of the headline text, kill the headline up to the tags.
679 - When after the headline text, kill the tags."
680 :group 'org-edit-structure
681 :type 'boolean)
682
683 (defcustom org-yank-folded-subtrees t
684 "Non-nil means, when yanking subtrees, fold them.
685 If the kill is a single subtree, or a sequence of subtrees, i.e. if
686 it starts with a heading and all other headings in it are either children
687 or siblings, then fold all the subtrees. However, do this only if no
688 text after the yank would be swallowed into a folded tree by this action."
689 :group 'org-edit-structure
690 :type 'boolean)
691
692 (defcustom org-yank-adjusted-subtrees t
693 "Non-nil means, when yanking subtrees, adjust the level.
694 With this setting, `org-paste-subtree' is used to insert the subtree, see
695 this function for details."
696 :group 'org-edit-structure
697 :type 'boolean)
698
699 (defcustom org-M-RET-may-split-line '((default . t))
700 "Non-nil means, M-RET will split the line at the cursor position.
701 When nil, it will go to the end of the line before making a
702 new line.
703 You may also set this option in a different way for different
704 contexts. Valid contexts are:
705
706 headline when creating a new headline
707 item when creating a new item
708 table in a table field
709 default the value to be used for all contexts not explicitly
710 customized"
711 :group 'org-structure
712 :group 'org-table
713 :type '(choice
714 (const :tag "Always" t)
715 (const :tag "Never" nil)
716 (repeat :greedy t :tag "Individual contexts"
717 (cons
718 (choice :tag "Context"
719 (const headline)
720 (const item)
721 (const table)
722 (const default))
723 (boolean)))))
724
725
726 (defcustom org-insert-heading-respect-content nil
727 "Non-nil means, insert new headings after the current subtree.
728 When nil, the new heading is created directly after the current line.
729 The commands \\[org-insert-heading-respect-content] and
730 \\[org-insert-todo-heading-respect-content] turn this variable on
731 for the duration of the command."
732 :group 'org-structure
733 :type 'boolean)
734
735 (defcustom org-blank-before-new-entry '((heading . auto)
736 (plain-list-item . auto))
737 "Should `org-insert-heading' leave a blank line before new heading/item?
738 The value is an alist, with `heading' and `plain-list-item' as car,
739 and a boolean flag as cdr."
740 :group 'org-edit-structure
741 :type '(list
742 (cons (const heading)
743 (choice (const :tag "Never" nil)
744 (const :tag "Always" t)
745 (const :tag "Auto" auto)))
746 (cons (const plain-list-item)
747 (choice (const :tag "Never" nil)
748 (const :tag "Always" t)
749 (const :tag "Auto" auto)))))
750
751 (defcustom org-insert-heading-hook nil
752 "Hook being run after inserting a new heading."
753 :group 'org-edit-structure
754 :type 'hook)
755
756 (defcustom org-enable-fixed-width-editor t
757 "Non-nil means, lines starting with \":\" are treated as fixed-width.
758 This currently only means, they are never auto-wrapped.
759 When nil, such lines will be treated like ordinary lines.
760 See also the QUOTE keyword."
761 :group 'org-edit-structure
762 :type 'boolean)
763
764 (defcustom org-edit-src-region-extra nil
765 "Additional regexps to identify regions for editing with `org-edit-src-code'.
766 For examples see the function `org-edit-src-find-region-and-lang'.
767 The regular expression identifying the begin marker should end with a newline,
768 and the regexp marking the end line should start with a newline, to make sure
769 there are kept outside the narrowed region."
770 :group 'org-edit-structure
771 :type '(repeat
772 (list
773 (regexp :tag "begin regexp")
774 (regexp :tag "end regexp")
775 (choice :tag "language"
776 (string :tag "specify")
777 (integer :tag "from match group")
778 (const :tag "from `lang' element")
779 (const :tag "from `style' element")))))
780
781 (defcustom org-coderef-label-format "(ref:%s)"
782 "The default coderef format.
783 This format string will be used to search for coderef labels in literal
784 examples (EXAMPLE and SRC blocks). The format can be overwritten
785 an individual literal example with the -f option, like
786
787 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
788 ...
789 #+END_SRC
790
791 If you want to use this for HTML export, make sure that the format does
792 not introduce special font-locking, and avoid the HTML special
793 characters `<', `>', and `&'. The reason for this restriction is that
794 the labels are searched for only after htmlize has done its job."
795 :group 'org-edit-structure ; FIXME this is not in the right group
796 :type 'string)
797
798 (defcustom org-edit-fixed-width-region-mode 'artist-mode
799 "The mode that should be used to edit fixed-width regions.
800 These are the regions where each line starts with a colon."
801 :group 'org-edit-structure
802 :type '(choice
803 (const artist-mode)
804 (const picture-mode)
805 (const fundamental-mode)
806 (function :tag "Other (specify)")))
807
808 (defcustom org-goto-auto-isearch t
809 "Non-nil means, typing characters in org-goto starts incremental search."
810 :group 'org-edit-structure
811 :type 'boolean)
812
813 (defgroup org-sparse-trees nil
814 "Options concerning sparse trees in Org-mode."
815 :tag "Org Sparse Trees"
816 :group 'org-structure)
817
818 (defcustom org-highlight-sparse-tree-matches t
819 "Non-nil means, highlight all matches that define a sparse tree.
820 The highlights will automatically disappear the next time the buffer is
821 changed by an edit command."
822 :group 'org-sparse-trees
823 :type 'boolean)
824
825 (defcustom org-remove-highlights-with-change t
826 "Non-nil means, any change to the buffer will remove temporary highlights.
827 Such highlights are created by `org-occur' and `org-clock-display'.
828 When nil, `C-c C-c needs to be used to get rid of the highlights.
829 The highlights created by `org-preview-latex-fragment' always need
830 `C-c C-c' to be removed."
831 :group 'org-sparse-trees
832 :group 'org-time
833 :type 'boolean)
834
835
836 (defcustom org-occur-hook '(org-first-headline-recenter)
837 "Hook that is run after `org-occur' has constructed a sparse tree.
838 This can be used to recenter the window to show as much of the structure
839 as possible."
840 :group 'org-sparse-trees
841 :type 'hook)
842
843 (defgroup org-imenu-and-speedbar nil
844 "Options concerning imenu and speedbar in Org-mode."
845 :tag "Org Imenu and Speedbar"
846 :group 'org-structure)
847
848 (defcustom org-imenu-depth 2
849 "The maximum level for Imenu access to Org-mode headlines.
850 This also applied for speedbar access."
851 :group 'org-imenu-and-speedbar
852 :type 'number)
853
854 (defgroup org-table nil
855 "Options concerning tables in Org-mode."
856 :tag "Org Table"
857 :group 'org)
858
859 (defcustom org-enable-table-editor 'optimized
860 "Non-nil means, lines starting with \"|\" are handled by the table editor.
861 When nil, such lines will be treated like ordinary lines.
862
863 When equal to the symbol `optimized', the table editor will be optimized to
864 do the following:
865 - Automatic overwrite mode in front of whitespace in table fields.
866 This makes the structure of the table stay in tact as long as the edited
867 field does not exceed the column width.
868 - Minimize the number of realigns. Normally, the table is aligned each time
869 TAB or RET are pressed to move to another field. With optimization this
870 happens only if changes to a field might have changed the column width.
871 Optimization requires replacing the functions `self-insert-command',
872 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
873 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
874 very good at guessing when a re-align will be necessary, but you can always
875 force one with \\[org-ctrl-c-ctrl-c].
876
877 If you would like to use the optimized version in Org-mode, but the
878 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
879
880 This variable can be used to turn on and off the table editor during a session,
881 but in order to toggle optimization, a restart is required.
882
883 See also the variable `org-table-auto-blank-field'."
884 :group 'org-table
885 :type '(choice
886 (const :tag "off" nil)
887 (const :tag "on" t)
888 (const :tag "on, optimized" optimized)))
889
890 (defcustom org-table-tab-recognizes-table.el t
891 "Non-nil means, TAB will automatically notice a table.el table.
892 When it sees such a table, it moves point into it and - if necessary -
893 calls `table-recognize-table'."
894 :group 'org-table-editing
895 :type 'boolean)
896
897 (defgroup org-link nil
898 "Options concerning links in Org-mode."
899 :tag "Org Link"
900 :group 'org)
901
902 (defvar org-link-abbrev-alist-local nil
903 "Buffer-local version of `org-link-abbrev-alist', which see.
904 The value of this is taken from the #+LINK lines.")
905 (make-variable-buffer-local 'org-link-abbrev-alist-local)
906
907 (defcustom org-link-abbrev-alist nil
908 "Alist of link abbreviations.
909 The car of each element is a string, to be replaced at the start of a link.
910 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
911 links in Org-mode buffers can have an optional tag after a double colon, e.g.
912
913 [[linkkey:tag][description]]
914
915 If REPLACE is a string, the tag will simply be appended to create the link.
916 If the string contains \"%s\", the tag will be inserted there. Alternatively,
917 the placeholder \"%h\" will cause a url-encoded version of the tag to
918 be inserted at that point (see the function `url-hexify-string').
919
920 REPLACE may also be a function that will be called with the tag as the
921 only argument to create the link, which should be returned as a string.
922
923 See the manual for examples."
924 :group 'org-link
925 :type '(repeat
926 (cons
927 (string :tag "Protocol")
928 (choice
929 (string :tag "Format")
930 (function)))))
931
932 (defcustom org-descriptive-links t
933 "Non-nil means, hide link part and only show description of bracket links.
934 Bracket links are like [[link][description]]. This variable sets the initial
935 state in new org-mode buffers. The setting can then be toggled on a
936 per-buffer basis from the Org->Hyperlinks menu."
937 :group 'org-link
938 :type 'boolean)
939
940 (defcustom org-link-file-path-type 'adaptive
941 "How the path name in file links should be stored.
942 Valid values are:
943
944 relative Relative to the current directory, i.e. the directory of the file
945 into which the link is being inserted.
946 absolute Absolute path, if possible with ~ for home directory.
947 noabbrev Absolute path, no abbreviation of home directory.
948 adaptive Use relative path for files in the current directory and sub-
949 directories of it. For other files, use an absolute path."
950 :group 'org-link
951 :type '(choice
952 (const relative)
953 (const absolute)
954 (const noabbrev)
955 (const adaptive)))
956
957 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
958 "Types of links that should be activated in Org-mode files.
959 This is a list of symbols, each leading to the activation of a certain link
960 type. In principle, it does not hurt to turn on most link types - there may
961 be a small gain when turning off unused link types. The types are:
962
963 bracket The recommended [[link][description]] or [[link]] links with hiding.
964 angular Links in angular brackets that may contain whitespace like
965 <bbdb:Carsten Dominik>.
966 plain Plain links in normal text, no whitespace, like http://google.com.
967 radio Text that is matched by a radio target, see manual for details.
968 tag Tag settings in a headline (link to tag search).
969 date Time stamps (link to calendar).
970 footnote Footnote labels.
971
972 Changing this variable requires a restart of Emacs to become effective."
973 :group 'org-link
974 :type '(set :greedy t
975 (const :tag "Double bracket links (new style)" bracket)
976 (const :tag "Angular bracket links (old style)" angular)
977 (const :tag "Plain text links" plain)
978 (const :tag "Radio target matches" radio)
979 (const :tag "Tags" tag)
980 (const :tag "Timestamps" date)
981 (const :tag "Footnotes" footnote)))
982
983 (defcustom org-make-link-description-function nil
984 "Function to use to generate link descriptions from links. If
985 nil the link location will be used. This function must take two
986 parameters; the first is the link and the second the description
987 org-insert-link has generated, and should return the description
988 to use."
989 :group 'org-link
990 :type 'function)
991
992 (defgroup org-link-store nil
993 "Options concerning storing links in Org-mode."
994 :tag "Org Store Link"
995 :group 'org-link)
996
997 (defcustom org-email-link-description-format "Email %c: %.30s"
998 "Format of the description part of a link to an email or usenet message.
999 The following %-escapes will be replaced by corresponding information:
1000
1001 %F full \"From\" field
1002 %f name, taken from \"From\" field, address if no name
1003 %T full \"To\" field
1004 %t first name in \"To\" field, address if no name
1005 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1006 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1007 %s subject
1008 %m message-id.
1009
1010 You may use normal field width specification between the % and the letter.
1011 This is for example useful to limit the length of the subject.
1012
1013 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1014 :group 'org-link-store
1015 :type 'string)
1016
1017 (defcustom org-from-is-user-regexp
1018 (let (r1 r2)
1019 (when (and user-mail-address (not (string= user-mail-address "")))
1020 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1021 (when (and user-full-name (not (string= user-full-name "")))
1022 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1023 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1024 "Regexp matched against the \"From:\" header of an email or usenet message.
1025 It should match if the message is from the user him/herself."
1026 :group 'org-link-store
1027 :type 'regexp)
1028
1029 (defcustom org-link-to-org-use-id 'create-if-interactive
1030 "Non-nil means, storing a link to an Org file will use entry IDs.
1031
1032 Note that before this variable is even considered, org-id must be loaded,
1033 to please customize `org-modules' and turn it on.
1034
1035 The variable can have the following values:
1036
1037 t Create an ID if needed to make a link to the current entry.
1038
1039 create-if-interactive
1040 If `org-store-link' is called directly (interactively, as a user
1041 command), do create an ID to support the link. But when doing the
1042 job for remember, only use the ID if it already exists. The
1043 purpose of this setting is to avoid proliferation of unwanted
1044 IDs, just because you happen to be in an Org file when you
1045 call `org-remember' that automatically and preemptively
1046 creates a link. If you do want to get an ID link in a remember
1047 template to an entry not having an ID, create it first by
1048 explicitly creating a link to it, using `C-c C-l' first.
1049
1050 use-existing
1051 Use existing ID, do not create one.
1052
1053 nil Never use an ID to make a link, instead link using a text search for
1054 the headline text."
1055 :group 'org-link-store
1056 :type '(choice
1057 (const :tag "Create ID to make link" t)
1058 (const :tag "Create if string link interactively"
1059 'create-if-interactive)
1060 (const :tag "Only use existing" 'use-existing)
1061 (const :tag "Do not use ID to create link" nil)))
1062
1063 (defcustom org-context-in-file-links t
1064 "Non-nil means, file links from `org-store-link' contain context.
1065 A search string will be added to the file name with :: as separator and
1066 used to find the context when the link is activated by the command
1067 `org-open-at-point'.
1068 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1069 negates this setting for the duration of the command."
1070 :group 'org-link-store
1071 :type 'boolean)
1072
1073 (defcustom org-keep-stored-link-after-insertion nil
1074 "Non-nil means, keep link in list for entire session.
1075
1076 The command `org-store-link' adds a link pointing to the current
1077 location to an internal list. These links accumulate during a session.
1078 The command `org-insert-link' can be used to insert links into any
1079 Org-mode file (offering completion for all stored links). When this
1080 option is nil, every link which has been inserted once using \\[org-insert-link]
1081 will be removed from the list, to make completing the unused links
1082 more efficient."
1083 :group 'org-link-store
1084 :type 'boolean)
1085
1086 (defgroup org-link-follow nil
1087 "Options concerning following links in Org-mode."
1088 :tag "Org Follow Link"
1089 :group 'org-link)
1090
1091 (defcustom org-link-translation-function nil
1092 "Function to translate links with different syntax to Org syntax.
1093 This can be used to translate links created for example by the Planner
1094 or emacs-wiki packages to Org syntax.
1095 The function must accept two parameters, a TYPE containing the link
1096 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1097 which is everything after the link protocol. It should return a cons
1098 with possibly modified values of type and path.
1099 Org contains a function for this, so if you set this variable to
1100 `org-translate-link-from-planner', you should be able follow many
1101 links created by planner."
1102 :group 'org-link-follow
1103 :type 'function)
1104
1105 (defcustom org-follow-link-hook nil
1106 "Hook that is run after a link has been followed."
1107 :group 'org-link-follow
1108 :type 'hook)
1109
1110 (defcustom org-tab-follows-link nil
1111 "Non-nil means, on links TAB will follow the link.
1112 Needs to be set before org.el is loaded."
1113 :group 'org-link-follow
1114 :type 'boolean)
1115
1116 (defcustom org-return-follows-link nil
1117 "Non-nil means, on links RET will follow the link.
1118 Needs to be set before org.el is loaded."
1119 :group 'org-link-follow
1120 :type 'boolean)
1121
1122 (defcustom org-mouse-1-follows-link
1123 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1124 "Non-nil means, mouse-1 on a link will follow the link.
1125 A longer mouse click will still set point. Does not work on XEmacs.
1126 Needs to be set before org.el is loaded."
1127 :group 'org-link-follow
1128 :type 'boolean)
1129
1130 (defcustom org-mark-ring-length 4
1131 "Number of different positions to be recorded in the ring
1132 Changing this requires a restart of Emacs to work correctly."
1133 :group 'org-link-follow
1134 :type 'integer)
1135
1136 (defcustom org-link-frame-setup
1137 '((vm . vm-visit-folder-other-frame)
1138 (gnus . gnus-other-frame)
1139 (file . find-file-other-window))
1140 "Setup the frame configuration for following links.
1141 When following a link with Emacs, it may often be useful to display
1142 this link in another window or frame. This variable can be used to
1143 set this up for the different types of links.
1144 For VM, use any of
1145 `vm-visit-folder'
1146 `vm-visit-folder-other-frame'
1147 For Gnus, use any of
1148 `gnus'
1149 `gnus-other-frame'
1150 `org-gnus-no-new-news'
1151 For FILE, use any of
1152 `find-file'
1153 `find-file-other-window'
1154 `find-file-other-frame'
1155 For the calendar, use the variable `calendar-setup'.
1156 For BBDB, it is currently only possible to display the matches in
1157 another window."
1158 :group 'org-link-follow
1159 :type '(list
1160 (cons (const vm)
1161 (choice
1162 (const vm-visit-folder)
1163 (const vm-visit-folder-other-window)
1164 (const vm-visit-folder-other-frame)))
1165 (cons (const gnus)
1166 (choice
1167 (const gnus)
1168 (const gnus-other-frame)
1169 (const org-gnus-no-new-news)))
1170 (cons (const file)
1171 (choice
1172 (const find-file)
1173 (const find-file-other-window)
1174 (const find-file-other-frame)))))
1175
1176 (defcustom org-display-internal-link-with-indirect-buffer nil
1177 "Non-nil means, use indirect buffer to display infile links.
1178 Activating internal links (from one location in a file to another location
1179 in the same file) normally just jumps to the location. When the link is
1180 activated with a C-u prefix (or with mouse-3), the link is displayed in
1181 another window. When this option is set, the other window actually displays
1182 an indirect buffer clone of the current buffer, to avoid any visibility
1183 changes to the current buffer."
1184 :group 'org-link-follow
1185 :type 'boolean)
1186
1187 (defcustom org-open-non-existing-files nil
1188 "Non-nil means, `org-open-file' will open non-existing files.
1189 When nil, an error will be generated."
1190 :group 'org-link-follow
1191 :type 'boolean)
1192
1193 (defcustom org-open-directory-means-index-dot-org nil
1194 "Non-nil means, a link to a directory really means to index.org.
1195 When nil, following a directory link will run dired or open a finder/explorer
1196 window on that directory."
1197 :group 'org-link-follow
1198 :type 'boolean)
1199
1200 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1201 "Function and arguments to call for following mailto links.
1202 This is a list with the first element being a lisp function, and the
1203 remaining elements being arguments to the function. In string arguments,
1204 %a will be replaced by the address, and %s will be replaced by the subject
1205 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1206 :group 'org-link-follow
1207 :type '(choice
1208 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1209 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1210 (const :tag "message-mail" (message-mail "%a" "%s"))
1211 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1212
1213 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1214 "Non-nil means, ask for confirmation before executing shell links.
1215 Shell links can be dangerous: just think about a link
1216
1217 [[shell:rm -rf ~/*][Google Search]]
1218
1219 This link would show up in your Org-mode document as \"Google Search\",
1220 but really it would remove your entire home directory.
1221 Therefore we advise against setting this variable to nil.
1222 Just change it to `y-or-n-p' of you want to confirm with a
1223 single keystroke rather than having to type \"yes\"."
1224 :group 'org-link-follow
1225 :type '(choice
1226 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1227 (const :tag "with y-or-n (faster)" y-or-n-p)
1228 (const :tag "no confirmation (dangerous)" nil)))
1229
1230 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1231 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1232 Elisp links can be dangerous: just think about a link
1233
1234 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1235
1236 This link would show up in your Org-mode document as \"Google Search\",
1237 but really it would remove your entire home directory.
1238 Therefore we advise against setting this variable to nil.
1239 Just change it to `y-or-n-p' of you want to confirm with a
1240 single keystroke rather than having to type \"yes\"."
1241 :group 'org-link-follow
1242 :type '(choice
1243 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1244 (const :tag "with y-or-n (faster)" y-or-n-p)
1245 (const :tag "no confirmation (dangerous)" nil)))
1246
1247 (defconst org-file-apps-defaults-gnu
1248 '((remote . emacs)
1249 (system . mailcap)
1250 (t . mailcap))
1251 "Default file applications on a UNIX or GNU/Linux system.
1252 See `org-file-apps'.")
1253
1254 (defconst org-file-apps-defaults-macosx
1255 '((remote . emacs)
1256 (t . "open %s")
1257 (system . "open %s")
1258 ("ps.gz" . "gv %s")
1259 ("eps.gz" . "gv %s")
1260 ("dvi" . "xdvi %s")
1261 ("fig" . "xfig %s"))
1262 "Default file applications on a MacOS X system.
1263 The system \"open\" is known as a default, but we use X11 applications
1264 for some files for which the OS does not have a good default.
1265 See `org-file-apps'.")
1266
1267 (defconst org-file-apps-defaults-windowsnt
1268 (list
1269 '(remote . emacs)
1270 (cons t
1271 (list (if (featurep 'xemacs)
1272 'mswindows-shell-execute
1273 'w32-shell-execute)
1274 "open" 'file))
1275 (cons 'system
1276 (list (if (featurep 'xemacs)
1277 'mswindows-shell-execute
1278 'w32-shell-execute)
1279 "open" 'file)))
1280 "Default file applications on a Windows NT system.
1281 The system \"open\" is used for most files.
1282 See `org-file-apps'.")
1283
1284 (defcustom org-file-apps
1285 '(
1286 (auto-mode . emacs)
1287 ("\\.x?html?\\'" . default)
1288 ("\\.pdf\\'" . default)
1289 )
1290 "External applications for opening `file:path' items in a document.
1291 Org-mode uses system defaults for different file types, but
1292 you can use this variable to set the application for a given file
1293 extension. The entries in this list are cons cells where the car identifies
1294 files and the cdr the corresponding command. Possible values for the
1295 file identifier are
1296 \"regex\" Regular expression matched against the file name. For backward
1297 compatibility, this can also be a string with only alphanumeric
1298 characters, which is then interpreted as an extension.
1299 `directory' Matches a directory
1300 `remote' Matches a remote file, accessible through tramp or efs.
1301 Remote files most likely should be visited through Emacs
1302 because external applications cannot handle such paths.
1303 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1304 so all files Emacs knows how to handle. Using this with
1305 command `emacs' will open most files in Emacs. Beware that this
1306 will also open html files inside Emacs, unless you add
1307 (\"html\" . default) to the list as well.
1308 t Default for files not matched by any of the other options.
1309 `system' The system command to open files, like `open' on Windows
1310 and Mac OS X, and mailcap under GNU/Linux. This is the command
1311 that will be selected if you call `C-c C-o' with a double
1312 `C-u C-u' prefix.
1313
1314 Possible values for the command are:
1315 `emacs' The file will be visited by the current Emacs process.
1316 `default' Use the default application for this file type, which is the
1317 association for t in the list, most likely in the system-specific
1318 part.
1319 This can be used to overrule an unwanted setting in the
1320 system-specific variable.
1321 `system' Use the system command for opening files, like \"open\".
1322 This command is specified by the entry whose car is `system'.
1323 Most likely, the system-specific version of this variable
1324 does define this command, but you can overrule/replace it
1325 here.
1326 string A command to be executed by a shell; %s will be replaced
1327 by the path to the file.
1328 sexp A Lisp form which will be evaluated. The file path will
1329 be available in the Lisp variable `file'.
1330 For more examples, see the system specific constants
1331 `org-file-apps-defaults-macosx'
1332 `org-file-apps-defaults-windowsnt'
1333 `org-file-apps-defaults-gnu'."
1334 :group 'org-link-follow
1335 :type '(repeat
1336 (cons (choice :value ""
1337 (string :tag "Extension")
1338 (const :tag "System command to open files" system)
1339 (const :tag "Default for unrecognized files" t)
1340 (const :tag "Remote file" remote)
1341 (const :tag "Links to a directory" directory)
1342 (const :tag "Any files that have Emacs modes"
1343 auto-mode))
1344 (choice :value ""
1345 (const :tag "Visit with Emacs" emacs)
1346 (const :tag "Use default" default)
1347 (const :tag "Use the system command" system)
1348 (string :tag "Command")
1349 (sexp :tag "Lisp form")))))
1350
1351 (defgroup org-refile nil
1352 "Options concerning refiling entries in Org-mode."
1353 :tag "Org Refile"
1354 :group 'org)
1355
1356 (defcustom org-directory "~/org"
1357 "Directory with org files.
1358 This directory will be used as default to prompt for org files.
1359 Used by the hooks for remember.el."
1360 :group 'org-refile
1361 :group 'org-remember
1362 :type 'directory)
1363
1364 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1365 "Default target for storing notes.
1366 Used by the hooks for remember.el. This can be a string, or nil to mean
1367 the value of `remember-data-file'.
1368 You can set this on a per-template basis with the variable
1369 `org-remember-templates'."
1370 :group 'org-refile
1371 :group 'org-remember
1372 :type '(choice
1373 (const :tag "Default from remember-data-file" nil)
1374 file))
1375
1376 (defcustom org-goto-interface 'outline
1377 "The default interface to be used for `org-goto'.
1378 Allowed values are:
1379 outline The interface shows an outline of the relevant file
1380 and the correct heading is found by moving through
1381 the outline or by searching with incremental search.
1382 outline-path-completion Headlines in the current buffer are offered via
1383 completion. This is the interface also used by
1384 the refile command."
1385 :group 'org-refile
1386 :type '(choice
1387 (const :tag "Outline" outline)
1388 (const :tag "Outline-path-completion" outline-path-completion)))
1389
1390 (defcustom org-goto-max-level 5
1391 "Maximum level to be considered when running org-goto with refile interface."
1392 :group 'org-refile
1393 :type 'number)
1394
1395 (defcustom org-reverse-note-order nil
1396 "Non-nil means, store new notes at the beginning of a file or entry.
1397 When nil, new notes will be filed to the end of a file or entry.
1398 This can also be a list with cons cells of regular expressions that
1399 are matched against file names, and values."
1400 :group 'org-remember
1401 :group 'org-refile
1402 :type '(choice
1403 (const :tag "Reverse always" t)
1404 (const :tag "Reverse never" nil)
1405 (repeat :tag "By file name regexp"
1406 (cons regexp boolean))))
1407
1408 (defcustom org-refile-targets nil
1409 "Targets for refiling entries with \\[org-refile].
1410 This is list of cons cells. Each cell contains:
1411 - a specification of the files to be considered, either a list of files,
1412 or a symbol whose function or variable value will be used to retrieve
1413 a file name or a list of file names. If you use `org-agenda-files' for
1414 that, all agenda files will be scanned for targets. Nil means, consider
1415 headings in the current buffer.
1416 - A specification of how to select find candidate refile targets. This
1417 may be any of
1418 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1419 This tag has to be present in all target headlines, inheritance will
1420 not be considered.
1421 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1422 todo keyword.
1423 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1424 headlines that are refiling targets.
1425 - a cons cell (:level . N). Any headline of level N is considered a target.
1426 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1427
1428 When this variable is nil, all top-level headlines in the current buffer
1429 are used, equivalent to the value `((nil . (:level . 1))'."
1430 :group 'org-refile
1431 :type '(repeat
1432 (cons
1433 (choice :value org-agenda-files
1434 (const :tag "All agenda files" org-agenda-files)
1435 (const :tag "Current buffer" nil)
1436 (function) (variable) (file))
1437 (choice :tag "Identify target headline by"
1438 (cons :tag "Specific tag" (const :value :tag) (string))
1439 (cons :tag "TODO keyword" (const :value :todo) (string))
1440 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1441 (cons :tag "Level number" (const :value :level) (integer))
1442 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1443
1444 (defcustom org-refile-use-outline-path nil
1445 "Non-nil means, provide refile targets as paths.
1446 So a level 3 headline will be available as level1/level2/level3.
1447 When the value is `file', also include the file name (without directory)
1448 into the path. When `full-file-path', include the full file path."
1449 :group 'org-refile
1450 :type '(choice
1451 (const :tag "Not" nil)
1452 (const :tag "Yes" t)
1453 (const :tag "Start with file name" file)
1454 (const :tag "Start with full file path" full-file-path)))
1455
1456 (defcustom org-outline-path-complete-in-steps t
1457 "Non-nil means, complete the outline path in hierarchical steps.
1458 When Org-mode uses the refile interface to select an outline path
1459 \(see variable `org-refile-use-outline-path'), the completion of
1460 the path can be done is a single go, or if can be done in steps down
1461 the headline hierarchy. Going in steps is probably the best if you
1462 do not use a special completion package like `ido' or `icicles'.
1463 However, when using these packages, going in one step can be very
1464 fast, while still showing the whole path to the entry."
1465 :group 'org-refile
1466 :type 'boolean)
1467
1468 (defgroup org-todo nil
1469 "Options concerning TODO items in Org-mode."
1470 :tag "Org TODO"
1471 :group 'org)
1472
1473 (defgroup org-progress nil
1474 "Options concerning Progress logging in Org-mode."
1475 :tag "Org Progress"
1476 :group 'org-time)
1477
1478 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1479 "List of TODO entry keyword sequences and their interpretation.
1480 \\<org-mode-map>This is a list of sequences.
1481
1482 Each sequence starts with a symbol, either `sequence' or `type',
1483 indicating if the keywords should be interpreted as a sequence of
1484 action steps, or as different types of TODO items. The first
1485 keywords are states requiring action - these states will select a headline
1486 for inclusion into the global TODO list Org-mode produces. If one of
1487 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1488 signify that no further action is necessary. If \"|\" is not found,
1489 the last keyword is treated as the only DONE state of the sequence.
1490
1491 The command \\[org-todo] cycles an entry through these states, and one
1492 additional state where no keyword is present. For details about this
1493 cycling, see the manual.
1494
1495 TODO keywords and interpretation can also be set on a per-file basis with
1496 the special #+SEQ_TODO and #+TYP_TODO lines.
1497
1498 Each keyword can optionally specify a character for fast state selection
1499 \(in combination with the variable `org-use-fast-todo-selection')
1500 and specifiers for state change logging, using the same syntax
1501 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1502 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1503 indicates to record a time stamp each time this state is selected.
1504
1505 Each keyword may also specify if a timestamp or a note should be
1506 recorded when entering or leaving the state, by adding additional
1507 characters in the parenthesis after the keyword. This looks like this:
1508 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1509 record only the time of the state change. With X and Y being either
1510 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1511 Y when leaving the state if and only if the *target* state does not
1512 define X. You may omit any of the fast-selection key or X or /Y,
1513 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1514
1515 For backward compatibility, this variable may also be just a list
1516 of keywords - in this case the interpretation (sequence or type) will be
1517 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1518 :group 'org-todo
1519 :group 'org-keywords
1520 :type '(choice
1521 (repeat :tag "Old syntax, just keywords"
1522 (string :tag "Keyword"))
1523 (repeat :tag "New syntax"
1524 (cons
1525 (choice
1526 :tag "Interpretation"
1527 (const :tag "Sequence (cycling hits every state)" sequence)
1528 (const :tag "Type (cycling directly to DONE)" type))
1529 (repeat
1530 (string :tag "Keyword"))))))
1531
1532 (defvar org-todo-keywords-1 nil
1533 "All TODO and DONE keywords active in a buffer.")
1534 (make-variable-buffer-local 'org-todo-keywords-1)
1535 (defvar org-todo-keywords-for-agenda nil)
1536 (defvar org-done-keywords-for-agenda nil)
1537 (defvar org-todo-keyword-alist-for-agenda nil)
1538 (defvar org-tag-alist-for-agenda nil)
1539 (defvar org-agenda-contributing-files nil)
1540 (defvar org-not-done-keywords nil)
1541 (make-variable-buffer-local 'org-not-done-keywords)
1542 (defvar org-done-keywords nil)
1543 (make-variable-buffer-local 'org-done-keywords)
1544 (defvar org-todo-heads nil)
1545 (make-variable-buffer-local 'org-todo-heads)
1546 (defvar org-todo-sets nil)
1547 (make-variable-buffer-local 'org-todo-sets)
1548 (defvar org-todo-log-states nil)
1549 (make-variable-buffer-local 'org-todo-log-states)
1550 (defvar org-todo-kwd-alist nil)
1551 (make-variable-buffer-local 'org-todo-kwd-alist)
1552 (defvar org-todo-key-alist nil)
1553 (make-variable-buffer-local 'org-todo-key-alist)
1554 (defvar org-todo-key-trigger nil)
1555 (make-variable-buffer-local 'org-todo-key-trigger)
1556
1557 (defcustom org-todo-interpretation 'sequence
1558 "Controls how TODO keywords are interpreted.
1559 This variable is in principle obsolete and is only used for
1560 backward compatibility, if the interpretation of todo keywords is
1561 not given already in `org-todo-keywords'. See that variable for
1562 more information."
1563 :group 'org-todo
1564 :group 'org-keywords
1565 :type '(choice (const sequence)
1566 (const type)))
1567
1568 (defcustom org-use-fast-todo-selection 'prefix
1569 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1570 This variable describes if and under what circumstances the cycling
1571 mechanism for TODO keywords will be replaced by a single-key, direct
1572 selection scheme.
1573
1574 When nil, fast selection is never used.
1575
1576 When the symbol `prefix', it will be used when `org-todo' is called with
1577 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1578 in an agenda buffer.
1579
1580 When t, fast selection is used by default. In this case, the prefix
1581 argument forces cycling instead.
1582
1583 In all cases, the special interface is only used if access keys have actually
1584 been assigned by the user, i.e. if keywords in the configuration are followed
1585 by a letter in parenthesis, like TODO(t)."
1586 :group 'org-todo
1587 :type '(choice
1588 (const :tag "Never" nil)
1589 (const :tag "By default" t)
1590 (const :tag "Only with C-u C-c C-t" prefix)))
1591
1592 (defcustom org-provide-todo-statistics t
1593 "Non-nil means, update todo statistics after insert and toggle.
1594 When this is set, todo statistics is updated in the parent of the current
1595 entry each time a todo state is changed."
1596 :group 'org-todo
1597 :type 'boolean)
1598
1599 (defcustom org-after-todo-state-change-hook nil
1600 "Hook which is run after the state of a TODO item was changed.
1601 The new state (a string with a TODO keyword, or nil) is available in the
1602 Lisp variable `state'."
1603 :group 'org-todo
1604 :type 'hook)
1605
1606 (defcustom org-todo-state-tags-triggers nil
1607 "Tag changes that should be triggered by TODO state changes.
1608 This is a list. Each entry is
1609
1610 (state-change (tag . flag) .......)
1611
1612 State-change can be a string with a state, and empty string to indicate the
1613 state that has no TODO keyword, or it can be one of the symbols `todo'
1614 or `done', meaning any not-done or done state, respectively."
1615 :group 'org-todo
1616 :group 'org-tags
1617 :type '(repeat
1618 (cons (choice :tag "When changing to"
1619 (const :tag "Not-done state" todo)
1620 (const :tag "Done state" done)
1621 (string :tag "State"))
1622 (repeat
1623 (cons :tag "Tag action"
1624 (string :tag "Tag")
1625 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1626
1627 (defcustom org-log-done nil
1628 "Information to record when a task moves to the DONE state.
1629
1630 Possible values are:
1631
1632 nil Don't add anything, just change the keyword
1633 time Add a time stamp to the task
1634 note Prompt a closing note and add it with template `org-log-note-headings'
1635
1636 This option can also be set with on a per-file-basis with
1637
1638 #+STARTUP: nologdone
1639 #+STARTUP: logdone
1640 #+STARTUP: lognotedone
1641
1642 You can have local logging settings for a subtree by setting the LOGGING
1643 property to one or more of these keywords."
1644 :group 'org-todo
1645 :group 'org-progress
1646 :type '(choice
1647 (const :tag "No logging" nil)
1648 (const :tag "Record CLOSED timestamp" time)
1649 (const :tag "Record CLOSED timestamp with closing note." note)))
1650
1651 ;; Normalize old uses of org-log-done.
1652 (cond
1653 ((eq org-log-done t) (setq org-log-done 'time))
1654 ((and (listp org-log-done) (memq 'done org-log-done))
1655 (setq org-log-done 'note)))
1656
1657 (defcustom org-log-note-clock-out nil
1658 "Non-nil means, record a note when clocking out of an item.
1659 This can also be configured on a per-file basis by adding one of
1660 the following lines anywhere in the buffer:
1661
1662 #+STARTUP: lognoteclock-out
1663 #+STARTUP: nolognoteclock-out"
1664 :group 'org-todo
1665 :group 'org-progress
1666 :type 'boolean)
1667
1668 (defcustom org-log-done-with-time t
1669 "Non-nil means, the CLOSED time stamp will contain date and time.
1670 When nil, only the date will be recorded."
1671 :group 'org-progress
1672 :type 'boolean)
1673
1674 (defcustom org-log-note-headings
1675 '((done . "CLOSING NOTE %t")
1676 (state . "State %-12s %t")
1677 (note . "Note taken on %t")
1678 (clock-out . ""))
1679 "Headings for notes added to entries.
1680 The value is an alist, with the car being a symbol indicating the note
1681 context, and the cdr is the heading to be used. The heading may also be the
1682 empty string.
1683 %t in the heading will be replaced by a time stamp.
1684 %s will be replaced by the new TODO state, in double quotes.
1685 %u will be replaced by the user name.
1686 %U will be replaced by the full user name."
1687 :group 'org-todo
1688 :group 'org-progress
1689 :type '(list :greedy t
1690 (cons (const :tag "Heading when closing an item" done) string)
1691 (cons (const :tag
1692 "Heading when changing todo state (todo sequence only)"
1693 state) string)
1694 (cons (const :tag "Heading when just taking a note" note) string)
1695 (cons (const :tag "Heading when clocking out" clock-out) string)))
1696
1697 (unless (assq 'note org-log-note-headings)
1698 (push '(note . "%t") org-log-note-headings))
1699
1700 (defcustom org-log-state-notes-insert-after-drawers nil
1701 "Non-nil means, insert state change notes after any drawers in entry.
1702 Only the drawers that *immediately* follow the headline and the
1703 deadline/scheduled line are skipped.
1704 When nil, insert notes right after the heading and perhaps the line
1705 with deadline/scheduling if present."
1706 :group 'org-todo
1707 :group 'org-progress
1708 :type 'boolean)
1709
1710 (defcustom org-log-states-order-reversed t
1711 "Non-nil means, the latest state change note will be directly after heading.
1712 When nil, the notes will be orderer according to time."
1713 :group 'org-todo
1714 :group 'org-progress
1715 :type 'boolean)
1716
1717 (defcustom org-log-repeat 'time
1718 "Non-nil means, record moving through the DONE state when triggering repeat.
1719 An auto-repeating tasks is immediately switched back to TODO when marked
1720 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1721 the TODO keyword definition, or recording a closing note by setting
1722 `org-log-done', there will be no record of the task moving through DONE.
1723 This variable forces taking a note anyway. Possible values are:
1724
1725 nil Don't force a record
1726 time Record a time stamp
1727 note Record a note
1728
1729 This option can also be set with on a per-file-basis with
1730
1731 #+STARTUP: logrepeat
1732 #+STARTUP: lognoterepeat
1733 #+STARTUP: nologrepeat
1734
1735 You can have local logging settings for a subtree by setting the LOGGING
1736 property to one or more of these keywords."
1737 :group 'org-todo
1738 :group 'org-progress
1739 :type '(choice
1740 (const :tag "Don't force a record" nil)
1741 (const :tag "Force recording the DONE state" time)
1742 (const :tag "Force recording a note with the DONE state" note)))
1743
1744
1745 (defgroup org-priorities nil
1746 "Priorities in Org-mode."
1747 :tag "Org Priorities"
1748 :group 'org-todo)
1749
1750 (defcustom org-highest-priority ?A
1751 "The highest priority of TODO items. A character like ?A, ?B etc.
1752 Must have a smaller ASCII number than `org-lowest-priority'."
1753 :group 'org-priorities
1754 :type 'character)
1755
1756 (defcustom org-lowest-priority ?C
1757 "The lowest priority of TODO items. A character like ?A, ?B etc.
1758 Must have a larger ASCII number than `org-highest-priority'."
1759 :group 'org-priorities
1760 :type 'character)
1761
1762 (defcustom org-default-priority ?B
1763 "The default priority of TODO items.
1764 This is the priority an item get if no explicit priority is given."
1765 :group 'org-priorities
1766 :type 'character)
1767
1768 (defcustom org-priority-start-cycle-with-default t
1769 "Non-nil means, start with default priority when starting to cycle.
1770 When this is nil, the first step in the cycle will be (depending on the
1771 command used) one higher or lower that the default priority."
1772 :group 'org-priorities
1773 :type 'boolean)
1774
1775 (defgroup org-time nil
1776 "Options concerning time stamps and deadlines in Org-mode."
1777 :tag "Org Time"
1778 :group 'org)
1779
1780 (defcustom org-insert-labeled-timestamps-at-point nil
1781 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1782 When nil, these labeled time stamps are forces into the second line of an
1783 entry, just after the headline. When scheduling from the global TODO list,
1784 the time stamp will always be forced into the second line."
1785 :group 'org-time
1786 :type 'boolean)
1787
1788 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1789 "Formats for `format-time-string' which are used for time stamps.
1790 It is not recommended to change this constant.")
1791
1792 (defcustom org-time-stamp-rounding-minutes '(0 5)
1793 "Number of minutes to round time stamps to.
1794 These are two values, the first applies when first creating a time stamp.
1795 The second applies when changing it with the commands `S-up' and `S-down'.
1796 When changing the time stamp, this means that it will change in steps
1797 of N minutes, as given by the second value.
1798
1799 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1800 numbers should be factors of 60, so for example 5, 10, 15.
1801
1802 When this is larger than 1, you can still force an exact time-stamp by using
1803 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1804 and by using a prefix arg to `S-up/down' to specify the exact number
1805 of minutes to shift."
1806 :group 'org-time
1807 :get '(lambda (var) ; Make sure all entries have 5 elements
1808 (if (integerp (default-value var))
1809 (list (default-value var) 5)
1810 (default-value var)))
1811 :type '(list
1812 (integer :tag "when inserting times")
1813 (integer :tag "when modifying times")))
1814
1815 ;; Normalize old customizations of this variable.
1816 (when (integerp org-time-stamp-rounding-minutes)
1817 (setq org-time-stamp-rounding-minutes
1818 (list org-time-stamp-rounding-minutes
1819 org-time-stamp-rounding-minutes)))
1820
1821 (defcustom org-display-custom-times nil
1822 "Non-nil means, overlay custom formats over all time stamps.
1823 The formats are defined through the variable `org-time-stamp-custom-formats'.
1824 To turn this on on a per-file basis, insert anywhere in the file:
1825 #+STARTUP: customtime"
1826 :group 'org-time
1827 :set 'set-default
1828 :type 'sexp)
1829 (make-variable-buffer-local 'org-display-custom-times)
1830
1831 (defcustom org-time-stamp-custom-formats
1832 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1833 "Custom formats for time stamps. See `format-time-string' for the syntax.
1834 These are overlayed over the default ISO format if the variable
1835 `org-display-custom-times' is set. Time like %H:%M should be at the
1836 end of the second format."
1837 :group 'org-time
1838 :type 'sexp)
1839
1840 (defun org-time-stamp-format (&optional long inactive)
1841 "Get the right format for a time string."
1842 (let ((f (if long (cdr org-time-stamp-formats)
1843 (car org-time-stamp-formats))))
1844 (if inactive
1845 (concat "[" (substring f 1 -1) "]")
1846 f)))
1847
1848 (defcustom org-time-clocksum-format "%d:%02d"
1849 "The format string used when creating CLOCKSUM lines, or when
1850 org-mode generates a time duration."
1851 :group 'org-time
1852 :type 'string)
1853
1854 (defcustom org-deadline-warning-days 14
1855 "No. of days before expiration during which a deadline becomes active.
1856 This variable governs the display in sparse trees and in the agenda.
1857 When 0 or negative, it means use this number (the absolute value of it)
1858 even if a deadline has a different individual lead time specified."
1859 :group 'org-time
1860 :group 'org-agenda-daily/weekly
1861 :type 'number)
1862
1863 (defcustom org-read-date-prefer-future t
1864 "Non-nil means, assume future for incomplete date input from user.
1865 This affects the following situations:
1866 1. The user gives a day, but no month.
1867 For example, if today is the 15th, and you enter \"3\", Org-mode will
1868 read this as the third of *next* month. However, if you enter \"17\",
1869 it will be considered as *this* month.
1870 2. The user gives a month but not a year.
1871 For example, if it is april and you enter \"feb 2\", this will be read
1872 as feb 2, *next* year. \"May 5\", however, will be this year.
1873
1874 Currently this does not work for ISO week specifications.
1875
1876 When this option is nil, the current month and year will always be used
1877 as defaults."
1878 :group 'org-time
1879 :type 'boolean)
1880
1881 (defcustom org-read-date-display-live t
1882 "Non-nil means, display current interpretation of date prompt live.
1883 This display will be in an overlay, in the minibuffer."
1884 :group 'org-time
1885 :type 'boolean)
1886
1887 (defcustom org-read-date-popup-calendar t
1888 "Non-nil means, pop up a calendar when prompting for a date.
1889 In the calendar, the date can be selected with mouse-1. However, the
1890 minibuffer will also be active, and you can simply enter the date as well.
1891 When nil, only the minibuffer will be available."
1892 :group 'org-time
1893 :type 'boolean)
1894 (if (fboundp 'defvaralias)
1895 (defvaralias 'org-popup-calendar-for-date-prompt
1896 'org-read-date-popup-calendar))
1897
1898 (defcustom org-extend-today-until 0
1899 "The hour when your day really ends. Must be an integer.
1900 This has influence for the following applications:
1901 - When switching the agenda to \"today\". It it is still earlier than
1902 the time given here, the day recognized as TODAY is actually yesterday.
1903 - When a date is read from the user and it is still before the time given
1904 here, the current date and time will be assumed to be yesterday, 23:59.
1905 Also, timestamps inserted in remember templates follow this rule.
1906
1907 IMPORTANT: This is a feature whose implementation is and likely will
1908 remain incomplete. Really, it is only here because past midnight seems to
1909 be the favorite working time of John Wiegley :-)"
1910 :group 'org-time
1911 :type 'number)
1912
1913 (defcustom org-edit-timestamp-down-means-later nil
1914 "Non-nil means, S-down will increase the time in a time stamp.
1915 When nil, S-up will increase."
1916 :group 'org-time
1917 :type 'boolean)
1918
1919 (defcustom org-calendar-follow-timestamp-change t
1920 "Non-nil means, make the calendar window follow timestamp changes.
1921 When a timestamp is modified and the calendar window is visible, it will be
1922 moved to the new date."
1923 :group 'org-time
1924 :type 'boolean)
1925
1926 (defgroup org-tags nil
1927 "Options concerning tags in Org-mode."
1928 :tag "Org Tags"
1929 :group 'org)
1930
1931 (defcustom org-tag-alist nil
1932 "List of tags allowed in Org-mode files.
1933 When this list is nil, Org-mode will base TAG input on what is already in the
1934 buffer.
1935 The value of this variable is an alist, the car of each entry must be a
1936 keyword as a string, the cdr may be a character that is used to select
1937 that tag through the fast-tag-selection interface.
1938 See the manual for details."
1939 :group 'org-tags
1940 :type '(repeat
1941 (choice
1942 (cons (string :tag "Tag name")
1943 (character :tag "Access char"))
1944 (const :tag "Start radio group" (:startgroup))
1945 (const :tag "End radio group" (:endgroup)))))
1946
1947 (defvar org-file-tags nil
1948 "List of tags that can be inherited by all entries in the file.
1949 The tags will be inherited if the variable `org-use-tag-inheritance'
1950 says they should be.
1951 This variable is populated from #+TAG lines.")
1952
1953 (defcustom org-use-fast-tag-selection 'auto
1954 "Non-nil means, use fast tag selection scheme.
1955 This is a special interface to select and deselect tags with single keys.
1956 When nil, fast selection is never used.
1957 When the symbol `auto', fast selection is used if and only if selection
1958 characters for tags have been configured, either through the variable
1959 `org-tag-alist' or through a #+TAGS line in the buffer.
1960 When t, fast selection is always used and selection keys are assigned
1961 automatically if necessary."
1962 :group 'org-tags
1963 :type '(choice
1964 (const :tag "Always" t)
1965 (const :tag "Never" nil)
1966 (const :tag "When selection characters are configured" 'auto)))
1967
1968 (defcustom org-fast-tag-selection-single-key nil
1969 "Non-nil means, fast tag selection exits after first change.
1970 When nil, you have to press RET to exit it.
1971 During fast tag selection, you can toggle this flag with `C-c'.
1972 This variable can also have the value `expert'. In this case, the window
1973 displaying the tags menu is not even shown, until you press C-c again."
1974 :group 'org-tags
1975 :type '(choice
1976 (const :tag "No" nil)
1977 (const :tag "Yes" t)
1978 (const :tag "Expert" expert)))
1979
1980 (defvar org-fast-tag-selection-include-todo nil
1981 "Non-nil means, fast tags selection interface will also offer TODO states.
1982 This is an undocumented feature, you should not rely on it.")
1983
1984 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1985 "The column to which tags should be indented in a headline.
1986 If this number is positive, it specifies the column. If it is negative,
1987 it means that the tags should be flushright to that column. For example,
1988 -80 works well for a normal 80 character screen."
1989 :group 'org-tags
1990 :type 'integer)
1991
1992 (defcustom org-auto-align-tags t
1993 "Non-nil means, realign tags after pro/demotion of TODO state change.
1994 These operations change the length of a headline and therefore shift
1995 the tags around. With this options turned on, after each such operation
1996 the tags are again aligned to `org-tags-column'."
1997 :group 'org-tags
1998 :type 'boolean)
1999
2000 (defcustom org-use-tag-inheritance t
2001 "Non-nil means, tags in levels apply also for sublevels.
2002 When nil, only the tags directly given in a specific line apply there.
2003 This may also be a list of tags that should be inherited, or a regexp that
2004 matches tags that should be inherited. Additional control is possible
2005 with the variable `org-tags-exclude-from-inheritance' which gives an
2006 explicit list of tags to be excluded from inheritance., even if the value of
2007 `org-use-tag-inheritance' would select it for inheritance.
2008
2009 If this option is t, a match early-on in a tree can lead to a large
2010 number of matches in the subtree when constructing the agenda or creating
2011 a sparse tree. If you only want to see the first match in a tree during
2012 a search, check out the variable `org-tags-match-list-sublevels'."
2013 :group 'org-tags
2014 :type '(choice
2015 (const :tag "Not" nil)
2016 (const :tag "Always" t)
2017 (repeat :tag "Specific tags" (string :tag "Tag"))
2018 (regexp :tag "Tags matched by regexp")))
2019
2020 (defcustom org-tags-exclude-from-inheritance nil
2021 "List of tags that should never be inherited.
2022 This is a way to exclude a few tags from inheritance. For way to do
2023 the opposite, to actively allow inheritance for selected tags,
2024 see the variable `org-use-tag-inheritance'."
2025 :group 'org-tags
2026 :type '(repeat (string :tag "Tag")))
2027
2028 (defun org-tag-inherit-p (tag)
2029 "Check if TAG is one that should be inherited."
2030 (cond
2031 ((member tag org-tags-exclude-from-inheritance) nil)
2032 ((eq org-use-tag-inheritance t) t)
2033 ((not org-use-tag-inheritance) nil)
2034 ((stringp org-use-tag-inheritance)
2035 (string-match org-use-tag-inheritance tag))
2036 ((listp org-use-tag-inheritance)
2037 (member tag org-use-tag-inheritance))
2038 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2039
2040 (defcustom org-tags-match-list-sublevels t
2041 "Non-nil means list also sublevels of headlines matching tag search.
2042 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2043 the sublevels of a headline matching a tag search often also match
2044 the same search. Listing all of them can create very long lists.
2045 Setting this variable to nil causes subtrees of a match to be skipped.
2046 This option is off by default, because inheritance in on. If you turn
2047 inheritance off, you very likely want to turn this option on.
2048
2049 As a special case, if the tag search is restricted to TODO items, the
2050 value of this variable is ignored and sublevels are always checked, to
2051 make sure all corresponding TODO items find their way into the list.
2052
2053 This variable is semi-obsolete and probably should always be true. It
2054 is better to limit inheritance to certain tags using the variables
2055 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2056 :group 'org-tags
2057 :type 'boolean)
2058
2059 (defvar org-tags-history nil
2060 "History of minibuffer reads for tags.")
2061 (defvar org-last-tags-completion-table nil
2062 "The last used completion table for tags.")
2063 (defvar org-after-tags-change-hook nil
2064 "Hook that is run after the tags in a line have changed.")
2065
2066 (defgroup org-properties nil
2067 "Options concerning properties in Org-mode."
2068 :tag "Org Properties"
2069 :group 'org)
2070
2071 (defcustom org-property-format "%-10s %s"
2072 "How property key/value pairs should be formatted by `indent-line'.
2073 When `indent-line' hits a property definition, it will format the line
2074 according to this format, mainly to make sure that the values are
2075 lined-up with respect to each other."
2076 :group 'org-properties
2077 :type 'string)
2078
2079 (defcustom org-use-property-inheritance nil
2080 "Non-nil means, properties apply also for sublevels.
2081
2082 This setting is chiefly used during property searches. Turning it on can
2083 cause significant overhead when doing a search, which is why it is not
2084 on by default.
2085
2086 When nil, only the properties directly given in the current entry count.
2087 When t, every property is inherited. The value may also be a list of
2088 properties that should have inheritance, or a regular expression matching
2089 properties that should be inherited.
2090
2091 However, note that some special properties use inheritance under special
2092 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2093 and the properties ending in \"_ALL\" when they are used as descriptor
2094 for valid values of a property.
2095
2096 Note for programmers:
2097 When querying an entry with `org-entry-get', you can control if inheritance
2098 should be used. By default, `org-entry-get' looks only at the local
2099 properties. You can request inheritance by setting the inherit argument
2100 to t (to force inheritance) or to `selective' (to respect the setting
2101 in this variable)."
2102 :group 'org-properties
2103 :type '(choice
2104 (const :tag "Not" nil)
2105 (const :tag "Always" t)
2106 (repeat :tag "Specific properties" (string :tag "Property"))
2107 (regexp :tag "Properties matched by regexp")))
2108
2109 (defun org-property-inherit-p (property)
2110 "Check if PROPERTY is one that should be inherited."
2111 (cond
2112 ((eq org-use-property-inheritance t) t)
2113 ((not org-use-property-inheritance) nil)
2114 ((stringp org-use-property-inheritance)
2115 (string-match org-use-property-inheritance property))
2116 ((listp org-use-property-inheritance)
2117 (member property org-use-property-inheritance))
2118 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2119
2120 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2121 "The default column format, if no other format has been defined.
2122 This variable can be set on the per-file basis by inserting a line
2123
2124 #+COLUMNS: %25ITEM ....."
2125 :group 'org-properties
2126 :type 'string)
2127
2128 (defcustom org-columns-ellipses ".."
2129 "The ellipses to be used when a field in column view is truncated.
2130 When this is the empty string, as many characters as possible are shown,
2131 but then there will be no visual indication that the field has been truncated.
2132 When this is a string of length N, the last N characters of a truncated
2133 field are replaced by this string. If the column is narrower than the
2134 ellipses string, only part of the ellipses string will be shown."
2135 :group 'org-properties
2136 :type 'string)
2137
2138 (defcustom org-columns-modify-value-for-display-function nil
2139 "Function that modifies values for display in column view.
2140 For example, it can be used to cut out a certain part from a time stamp.
2141 The function must take 2 arguments:
2142
2143 column-title The title of the column (*not* the property name)
2144 value The value that should be modified.
2145
2146 The function should return the value that should be displayed,
2147 or nil if the normal value should be used."
2148 :group 'org-properties
2149 :type 'function)
2150
2151 (defcustom org-effort-property "Effort"
2152 "The property that is being used to keep track of effort estimates.
2153 Effort estimates given in this property need to have the format H:MM."
2154 :group 'org-properties
2155 :group 'org-progress
2156 :type '(string :tag "Property"))
2157
2158 (defconst org-global-properties-fixed
2159 '(("VISIBILITY_ALL" . "folded children content all"))
2160 "List of property/value pairs that can be inherited by any entry.
2161 These are fixed values, for the preset properties.")
2162
2163
2164 (defcustom org-global-properties nil
2165 "List of property/value pairs that can be inherited by any entry.
2166 You can set buffer-local values for the same purpose in the variable
2167 `org-file-properties' this by adding lines like
2168
2169 #+PROPERTY: NAME VALUE"
2170 :group 'org-properties
2171 :type '(repeat
2172 (cons (string :tag "Property")
2173 (string :tag "Value"))))
2174
2175 (defvar org-file-properties nil
2176 "List of property/value pairs that can be inherited by any entry.
2177 Valid for the current buffer.
2178 This variable is populated from #+PROPERTY lines.")
2179 (make-variable-buffer-local 'org-file-properties)
2180
2181 (defgroup org-agenda nil
2182 "Options concerning agenda views in Org-mode."
2183 :tag "Org Agenda"
2184 :group 'org)
2185
2186 (defvar org-category nil
2187 "Variable used by org files to set a category for agenda display.
2188 Such files should use a file variable to set it, for example
2189
2190 # -*- mode: org; org-category: \"ELisp\"
2191
2192 or contain a special line
2193
2194 #+CATEGORY: ELisp
2195
2196 If the file does not specify a category, then file's base name
2197 is used instead.")
2198 (make-variable-buffer-local 'org-category)
2199 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2200
2201 (defcustom org-agenda-files nil
2202 "The files to be used for agenda display.
2203 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2204 \\[org-remove-file]. You can also use customize to edit the list.
2205
2206 If an entry is a directory, all files in that directory that are matched by
2207 `org-agenda-file-regexp' will be part of the file list.
2208
2209 If the value of the variable is not a list but a single file name, then
2210 the list of agenda files is actually stored and maintained in that file, one
2211 agenda file per line."
2212 :group 'org-agenda
2213 :type '(choice
2214 (repeat :tag "List of files and directories" file)
2215 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2216
2217 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2218 "Regular expression to match files for `org-agenda-files'.
2219 If any element in the list in that variable contains a directory instead
2220 of a normal file, all files in that directory that are matched by this
2221 regular expression will be included."
2222 :group 'org-agenda
2223 :type 'regexp)
2224
2225 (defcustom org-agenda-text-search-extra-files nil
2226 "List of extra files to be searched by text search commands.
2227 These files will be search in addition to the agenda files by the
2228 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2229 Note that these files will only be searched for text search commands,
2230 not for the other agenda views like todo lists, tag searches or the weekly
2231 agenda. This variable is intended to list notes and possibly archive files
2232 that should also be searched by these two commands.
2233 In fact, if the first element in the list is the symbol `agenda-archives',
2234 than all archive files of all agenda files will be added to the search
2235 scope."
2236 :group 'org-agenda
2237 :type '(set :greedy t
2238 (const :tag "Agenda Archives" agenda-archives)
2239 (repeat :inline t (file))))
2240
2241 (if (fboundp 'defvaralias)
2242 (defvaralias 'org-agenda-multi-occur-extra-files
2243 'org-agenda-text-search-extra-files))
2244
2245 (defcustom org-agenda-skip-unavailable-files nil
2246 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2247 A nil value means to remove them, after a query, from the list."
2248 :group 'org-agenda
2249 :type 'boolean)
2250
2251 (defcustom org-calendar-to-agenda-key [?c]
2252 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2253 The command `org-calendar-goto-agenda' will be bound to this key. The
2254 default is the character `c' because then `c' can be used to switch back and
2255 forth between agenda and calendar."
2256 :group 'org-agenda
2257 :type 'sexp)
2258
2259 (defcustom org-calendar-agenda-action-key [?k]
2260 "The key to be installed in `calendar-mode-map' for agenda-action.
2261 The command `org-agenda-action' will be bound to this key. The
2262 default is the character `k' because we use the same key in the agenda."
2263 :group 'org-agenda
2264 :type 'sexp)
2265
2266 (eval-after-load "calendar"
2267 '(progn
2268 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2269 'org-calendar-goto-agenda)
2270 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2271 'org-agenda-action)))
2272
2273 (defgroup org-latex nil
2274 "Options for embedding LaTeX code into Org-mode."
2275 :tag "Org LaTeX"
2276 :group 'org)
2277
2278 (defcustom org-format-latex-options
2279 '(:foreground default :background default :scale 1.0
2280 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2281 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2282 "Options for creating images from LaTeX fragments.
2283 This is a property list with the following properties:
2284 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2285 `default' means use the foreground of the default face.
2286 :background the background color, or \"Transparent\".
2287 `default' means use the background of the default face.
2288 :scale a scaling factor for the size of the images.
2289 :html-foreground, :html-background, :html-scale
2290 the same numbers for HTML export.
2291 :matchers a list indicating which matchers should be used to
2292 find LaTeX fragments. Valid members of this list are:
2293 \"begin\" find environments
2294 \"$1\" find single characters surrounded by $.$
2295 \"$\" find math expressions surrounded by $...$
2296 \"$$\" find math expressions surrounded by $$....$$
2297 \"\\(\" find math expressions surrounded by \\(...\\)
2298 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2299 :group 'org-latex
2300 :type 'plist)
2301
2302 (defcustom org-format-latex-header "\\documentclass{article}
2303 \\usepackage{fullpage} % do not remove
2304 \\usepackage{amssymb}
2305 \\usepackage[usenames]{color}
2306 \\usepackage{amsmath}
2307 \\usepackage{latexsym}
2308 \\usepackage[mathscr]{eucal}
2309 \\pagestyle{empty} % do not remove"
2310 "The document header used for processing LaTeX fragments."
2311 :group 'org-latex
2312 :type 'string)
2313
2314
2315 (defgroup org-font-lock nil
2316 "Font-lock settings for highlighting in Org-mode."
2317 :tag "Org Font Lock"
2318 :group 'org)
2319
2320 (defcustom org-level-color-stars-only nil
2321 "Non-nil means fontify only the stars in each headline.
2322 When nil, the entire headline is fontified.
2323 Changing it requires restart of `font-lock-mode' to become effective
2324 also in regions already fontified."
2325 :group 'org-font-lock
2326 :type 'boolean)
2327
2328 (defcustom org-hide-leading-stars nil
2329 "Non-nil means, hide the first N-1 stars in a headline.
2330 This works by using the face `org-hide' for these stars. This
2331 face is white for a light background, and black for a dark
2332 background. You may have to customize the face `org-hide' to
2333 make this work.
2334 Changing it requires restart of `font-lock-mode' to become effective
2335 also in regions already fontified.
2336 You may also set this on a per-file basis by adding one of the following
2337 lines to the buffer:
2338
2339 #+STARTUP: hidestars
2340 #+STARTUP: showstars"
2341 :group 'org-font-lock
2342 :type 'boolean)
2343
2344 (defcustom org-fontify-done-headline nil
2345 "Non-nil means, change the face of a headline if it is marked DONE.
2346 Normally, only the TODO/DONE keyword indicates the state of a headline.
2347 When this is non-nil, the headline after the keyword is set to the
2348 `org-headline-done' as an additional indication."
2349 :group 'org-font-lock
2350 :type 'boolean)
2351
2352 (defcustom org-fontify-emphasized-text t
2353 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2354 Changing this variable requires a restart of Emacs to take effect."
2355 :group 'org-font-lock
2356 :type 'boolean)
2357
2358 (defcustom org-highlight-latex-fragments-and-specials nil
2359 "Non-nil means, fontify what is treated specially by the exporters."
2360 :group 'org-font-lock
2361 :type 'boolean)
2362
2363 (defcustom org-hide-emphasis-markers nil
2364 "Non-nil mean font-lock should hide the emphasis marker characters."
2365 :group 'org-font-lock
2366 :type 'boolean)
2367
2368 (defvar org-emph-re nil
2369 "Regular expression for matching emphasis.")
2370 (defvar org-verbatim-re nil
2371 "Regular expression for matching verbatim text.")
2372 (defvar org-emphasis-regexp-components) ; defined just below
2373 (defvar org-emphasis-alist) ; defined just below
2374 (defun org-set-emph-re (var val)
2375 "Set variable and compute the emphasis regular expression."
2376 (set var val)
2377 (when (and (boundp 'org-emphasis-alist)
2378 (boundp 'org-emphasis-regexp-components)
2379 org-emphasis-alist org-emphasis-regexp-components)
2380 (let* ((e org-emphasis-regexp-components)
2381 (pre (car e))
2382 (post (nth 1 e))
2383 (border (nth 2 e))
2384 (body (nth 3 e))
2385 (nl (nth 4 e))
2386 (body1 (concat body "*?"))
2387 (markers (mapconcat 'car org-emphasis-alist ""))
2388 (vmarkers (mapconcat
2389 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2390 org-emphasis-alist "")))
2391 ;; make sure special characters appear at the right position in the class
2392 (if (string-match "\\^" markers)
2393 (setq markers (concat (replace-match "" t t markers) "^")))
2394 (if (string-match "-" markers)
2395 (setq markers (concat (replace-match "" t t markers) "-")))
2396 (if (string-match "\\^" vmarkers)
2397 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2398 (if (string-match "-" vmarkers)
2399 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2400 (if (> nl 0)
2401 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2402 (int-to-string nl) "\\}")))
2403 ;; Make the regexp
2404 (setq org-emph-re
2405 (concat "\\([" pre "]\\|^\\)"
2406 "\\("
2407 "\\([" markers "]\\)"
2408 "\\("
2409 "[^" border "]\\|"
2410 "[^" border "]"
2411 body1
2412 "[^" border "]"
2413 "\\)"
2414 "\\3\\)"
2415 "\\([" post "]\\|$\\)"))
2416 (setq org-verbatim-re
2417 (concat "\\([" pre "]\\|^\\)"
2418 "\\("
2419 "\\([" vmarkers "]\\)"
2420 "\\("
2421 "[^" border "]\\|"
2422 "[^" border "]"
2423 body1
2424 "[^" border "]"
2425 "\\)"
2426 "\\3\\)"
2427 "\\([" post "]\\|$\\)")))))
2428
2429 (defcustom org-emphasis-regexp-components
2430 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2431 "Components used to build the regular expression for emphasis.
2432 This is a list with 6 entries. Terminology: In an emphasis string
2433 like \" *strong word* \", we call the initial space PREMATCH, the final
2434 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2435 and \"trong wor\" is the body. The different components in this variable
2436 specify what is allowed/forbidden in each part:
2437
2438 pre Chars allowed as prematch. Beginning of line will be allowed too.
2439 post Chars allowed as postmatch. End of line will be allowed too.
2440 border The chars *forbidden* as border characters.
2441 body-regexp A regexp like \".\" to match a body character. Don't use
2442 non-shy groups here, and don't allow newline here.
2443 newline The maximum number of newlines allowed in an emphasis exp.
2444
2445 Use customize to modify this, or restart Emacs after changing it."
2446 :group 'org-font-lock
2447 :set 'org-set-emph-re
2448 :type '(list
2449 (sexp :tag "Allowed chars in pre ")
2450 (sexp :tag "Allowed chars in post ")
2451 (sexp :tag "Forbidden chars in border ")
2452 (sexp :tag "Regexp for body ")
2453 (integer :tag "number of newlines allowed")
2454 (option (boolean :tag "Please ignore this button"))))
2455
2456 (defcustom org-emphasis-alist
2457 `(("*" bold "<b>" "</b>")
2458 ("/" italic "<i>" "</i>")
2459 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2460 ("=" org-code "<code>" "</code>" verbatim)
2461 ("~" org-verbatim "<code>" "</code>" verbatim)
2462 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2463 "<del>" "</del>")
2464 )
2465 "Special syntax for emphasized text.
2466 Text starting and ending with a special character will be emphasized, for
2467 example *bold*, _underlined_ and /italic/. This variable sets the marker
2468 characters, the face to be used by font-lock for highlighting in Org-mode
2469 Emacs buffers, and the HTML tags to be used for this.
2470 Use customize to modify this, or restart Emacs after changing it."
2471 :group 'org-font-lock
2472 :set 'org-set-emph-re
2473 :type '(repeat
2474 (list
2475 (string :tag "Marker character")
2476 (choice
2477 (face :tag "Font-lock-face")
2478 (plist :tag "Face property list"))
2479 (string :tag "HTML start tag")
2480 (string :tag "HTML end tag")
2481 (option (const verbatim)))))
2482
2483 ;;; Miscellaneous options
2484
2485 (defgroup org-completion nil
2486 "Completion in Org-mode."
2487 :tag "Org Completion"
2488 :group 'org)
2489
2490 (defcustom org-completion-use-ido nil
2491 "Non-nil means, use ido completion wherever possible.
2492 Note that `ido-mode' must be active for this variable to be relevant.
2493 If you decide to turn this variable on, you might well want to turn off
2494 `org-outline-path-complete-in-steps'."
2495 :group 'org-completion
2496 :type 'boolean)
2497
2498 (defcustom org-completion-fallback-command 'hippie-expand
2499 "The expansion command called by \\[org-complete] in normal context.
2500 Normal means, no org-mode-specific context."
2501 :group 'org-completion
2502 :type 'function)
2503
2504 ;;; Functions and variables from ther packages
2505 ;; Declared here to avoid compiler warnings
2506
2507 ;; XEmacs only
2508 (defvar outline-mode-menu-heading)
2509 (defvar outline-mode-menu-show)
2510 (defvar outline-mode-menu-hide)
2511 (defvar zmacs-regions) ; XEmacs regions
2512
2513 ;; Emacs only
2514 (defvar mark-active)
2515
2516 ;; Various packages
2517 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2518 (declare-function calendar-forward-day "cal-move" (arg))
2519 (declare-function calendar-goto-date "cal-move" (date))
2520 (declare-function calendar-goto-today "cal-move" ())
2521 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2522 (defvar calc-embedded-close-formula)
2523 (defvar calc-embedded-open-formula)
2524 (declare-function cdlatex-tab "ext:cdlatex" ())
2525 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2526 (defvar font-lock-unfontify-region-function)
2527 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2528 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2529 (defvar iswitchb-temp-buflist)
2530 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2531 (defvar org-agenda-tags-todo-honor-ignore-options)
2532 (declare-function org-agenda-skip "org-agenda" ())
2533 (declare-function org-format-agenda-item "org-agenda"
2534 (extra txt &optional category tags dotime noprefix remove-re))
2535 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2536 (declare-function org-agenda-change-all-lines "org-agenda"
2537 (newhead hdmarker &optional fixface just-this))
2538 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2539 (declare-function org-agenda-maybe-redo "org-agenda" ())
2540 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2541 (beg end))
2542 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2543 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2544 "org-agenda" (&optional end))
2545
2546 (declare-function parse-time-string "parse-time" (string))
2547 (declare-function remember "remember" (&optional initial))
2548 (declare-function remember-buffer-desc "remember" ())
2549 (declare-function remember-finalize "remember" ())
2550 (defvar remember-save-after-remembering)
2551 (defvar remember-data-file)
2552 (defvar remember-register)
2553 (defvar remember-buffer)
2554 (defvar remember-handler-functions)
2555 (defvar remember-annotation-functions)
2556 (defvar texmathp-why)
2557 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2558 (declare-function table--at-cell-p "table" (position &optional object at-column))
2559
2560 (defvar w3m-current-url)
2561 (defvar w3m-current-title)
2562
2563 (defvar org-latex-regexps)
2564
2565 ;;; Autoload and prepare some org modules
2566
2567 ;; Some table stuff that needs to be defined here, because it is used
2568 ;; by the functions setting up org-mode or checking for table context.
2569
2570 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2571 "Detects an org-type or table-type table.")
2572 (defconst org-table-line-regexp "^[ \t]*|"
2573 "Detects an org-type table line.")
2574 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2575 "Detects an org-type table line.")
2576 (defconst org-table-hline-regexp "^[ \t]*|-"
2577 "Detects an org-type table hline.")
2578 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2579 "Detects a table-type table hline.")
2580 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2581 "Searching from within a table (any type) this finds the first line
2582 outside the table.")
2583
2584 ;; Autoload the functions in org-table.el that are needed by functions here.
2585
2586 (eval-and-compile
2587 (org-autoload "org-table"
2588 '(org-table-align org-table-begin org-table-blank-field
2589 org-table-convert org-table-convert-region org-table-copy-down
2590 org-table-copy-region org-table-create
2591 org-table-create-or-convert-from-region
2592 org-table-create-with-table.el org-table-current-dline
2593 org-table-cut-region org-table-delete-column org-table-edit-field
2594 org-table-edit-formulas org-table-end org-table-eval-formula
2595 org-table-export org-table-field-info
2596 org-table-get-stored-formulas org-table-goto-column
2597 org-table-hline-and-move org-table-import org-table-insert-column
2598 org-table-insert-hline org-table-insert-row org-table-iterate
2599 org-table-justify-field-maybe org-table-kill-row
2600 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2601 org-table-move-column org-table-move-column-left
2602 org-table-move-column-right org-table-move-row
2603 org-table-move-row-down org-table-move-row-up
2604 org-table-next-field org-table-next-row org-table-paste-rectangle
2605 org-table-previous-field org-table-recalculate
2606 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2607 org-table-toggle-coordinate-overlays
2608 org-table-toggle-formula-debugger org-table-wrap-region
2609 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2610
2611 (defun org-at-table-p (&optional table-type)
2612 "Return t if the cursor is inside an org-type table.
2613 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2614 (if org-enable-table-editor
2615 (save-excursion
2616 (beginning-of-line 1)
2617 (looking-at (if table-type org-table-any-line-regexp
2618 org-table-line-regexp)))
2619 nil))
2620 (defsubst org-table-p () (org-at-table-p))
2621
2622 (defun org-at-table.el-p ()
2623 "Return t if and only if we are at a table.el table."
2624 (and (org-at-table-p 'any)
2625 (save-excursion
2626 (goto-char (org-table-begin 'any))
2627 (looking-at org-table1-hline-regexp))))
2628 (defun org-table-recognize-table.el ()
2629 "If there is a table.el table nearby, recognize it and move into it."
2630 (if org-table-tab-recognizes-table.el
2631 (if (org-at-table.el-p)
2632 (progn
2633 (beginning-of-line 1)
2634 (if (looking-at org-table-dataline-regexp)
2635 nil
2636 (if (looking-at org-table1-hline-regexp)
2637 (progn
2638 (beginning-of-line 2)
2639 (if (looking-at org-table-any-border-regexp)
2640 (beginning-of-line -1)))))
2641 (if (re-search-forward "|" (org-table-end t) t)
2642 (progn
2643 (require 'table)
2644 (if (table--at-cell-p (point))
2645 t
2646 (message "recognizing table.el table...")
2647 (table-recognize-table)
2648 (message "recognizing table.el table...done")))
2649 (error "This should not happen..."))
2650 t)
2651 nil)
2652 nil))
2653
2654 (defun org-at-table-hline-p ()
2655 "Return t if the cursor is inside a hline in a table."
2656 (if org-enable-table-editor
2657 (save-excursion
2658 (beginning-of-line 1)
2659 (looking-at org-table-hline-regexp))
2660 nil))
2661
2662 (defvar org-table-clean-did-remove-column nil)
2663
2664 (defun org-table-map-tables (function)
2665 "Apply FUNCTION to the start of all tables in the buffer."
2666 (save-excursion
2667 (save-restriction
2668 (widen)
2669 (goto-char (point-min))
2670 (while (re-search-forward org-table-any-line-regexp nil t)
2671 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2672 (beginning-of-line 1)
2673 (if (looking-at org-table-line-regexp)
2674 (save-excursion (funcall function)))
2675 (re-search-forward org-table-any-border-regexp nil 1))))
2676 (message "Mapping tables: done"))
2677
2678 ;; Declare and autoload functions from org-exp.el
2679
2680 (declare-function org-default-export-plist "org-exp")
2681 (declare-function org-infile-export-plist "org-exp")
2682 (declare-function org-get-current-options "org-exp")
2683 (eval-and-compile
2684 (org-autoload "org-exp"
2685 '(org-export org-export-as-ascii org-export-visible
2686 org-insert-export-options-template org-export-as-html-and-open
2687 org-export-as-html-batch org-export-as-html-to-buffer
2688 org-replace-region-by-html org-export-region-as-html
2689 org-export-as-html org-export-icalendar-this-file
2690 org-export-icalendar-all-agenda-files
2691 org-table-clean-before-export
2692 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2693
2694 ;; Declare and autoload functions from org-agenda.el
2695
2696 (eval-and-compile
2697 (org-autoload "org-agenda"
2698 '(org-agenda org-agenda-list org-search-view
2699 org-todo-list org-tags-view org-agenda-list-stuck-projects
2700 org-diary org-agenda-to-appt
2701 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2702
2703 ;; Autoload org-remember
2704
2705 (eval-and-compile
2706 (org-autoload "org-remember"
2707 '(org-remember-insinuate org-remember-annotation
2708 org-remember-apply-template org-remember org-remember-handler)))
2709
2710 ;; Autoload org-clock.el
2711
2712
2713 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2714 (beg end))
2715 (declare-function org-clock-update-mode-line "org-clock" ())
2716 (defvar org-clock-start-time)
2717 (defvar org-clock-marker (make-marker)
2718 "Marker recording the last clock-in.")
2719
2720 (eval-and-compile
2721 (org-autoload
2722 "org-clock"
2723 '(org-clock-in org-clock-out org-clock-cancel
2724 org-clock-goto org-clock-sum org-clock-display
2725 org-clock-remove-overlays org-clock-report
2726 org-clocktable-shift org-dblock-write:clocktable
2727 org-get-clocktable)))
2728
2729 (defun org-clock-update-time-maybe ()
2730 "If this is a CLOCK line, update it and return t.
2731 Otherwise, return nil."
2732 (interactive)
2733 (save-excursion
2734 (beginning-of-line 1)
2735 (skip-chars-forward " \t")
2736 (when (looking-at org-clock-string)
2737 (let ((re (concat "[ \t]*" org-clock-string
2738 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2739 "\\([ \t]*=>.*\\)?\\)?"))
2740 ts te h m s neg)
2741 (cond
2742 ((not (looking-at re))
2743 nil)
2744 ((not (match-end 2))
2745 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2746 (> org-clock-marker (point))
2747 (<= org-clock-marker (point-at-eol)))
2748 ;; The clock is running here
2749 (setq org-clock-start-time
2750 (apply 'encode-time
2751 (org-parse-time-string (match-string 1))))
2752 (org-clock-update-mode-line)))
2753 (t
2754 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2755 (end-of-line 1)
2756 (setq ts (match-string 1)
2757 te (match-string 3))
2758 (setq s (- (time-to-seconds
2759 (apply 'encode-time (org-parse-time-string te)))
2760 (time-to-seconds
2761 (apply 'encode-time (org-parse-time-string ts))))
2762 neg (< s 0)
2763 s (abs s)
2764 h (floor (/ s 3600))
2765 s (- s (* 3600 h))
2766 m (floor (/ s 60))
2767 s (- s (* 60 s)))
2768 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2769 t))))))
2770
2771 (defun org-check-running-clock ()
2772 "Check if the current buffer contains the running clock.
2773 If yes, offer to stop it and to save the buffer with the changes."
2774 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2775 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2776 (buffer-name))))
2777 (org-clock-out)
2778 (when (y-or-n-p "Save changed buffer?")
2779 (save-buffer))))
2780
2781 (defun org-clocktable-try-shift (dir n)
2782 "Check if this line starts a clock table, if yes, shift the time block."
2783 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2784 (org-clocktable-shift dir n)))
2785
2786 ;; Autoload org-timer.el
2787
2788 ;(declare-function org-timer "org-timer")
2789
2790 (eval-and-compile
2791 (org-autoload
2792 "org-timer"
2793 '(org-timer-start org-timer org-timer-item
2794 org-timer-change-times-in-region)))
2795
2796
2797 ;; Autoload archiving code
2798 ;; The stuff that is needed for cycling and tags has to be defined here.
2799
2800 (defgroup org-archive nil
2801 "Options concerning archiving in Org-mode."
2802 :tag "Org Archive"
2803 :group 'org-structure)
2804
2805 (defcustom org-archive-location "%s_archive::"
2806 "The location where subtrees should be archived.
2807
2808 The value of this variable is a string, consisting of two parts,
2809 separated by a double-colon. The first part is a filename and
2810 the second part is a headline.
2811
2812 When the filename is omitted, archiving happens in the same file.
2813 %s in the filename will be replaced by the current file
2814 name (without the directory part). Archiving to a different file
2815 is useful to keep archived entries from contributing to the
2816 Org-mode Agenda.
2817
2818 The archived entries will be filed as subtrees of the specified
2819 headline. When the headline is omitted, the subtrees are simply
2820 filed away at the end of the file, as top-level entries. Also in
2821 the heading you can use %s to represent the file name, this can be
2822 useful when using the same archive for a number of different files.
2823
2824 Here are a few examples:
2825 \"%s_archive::\"
2826 If the current file is Projects.org, archive in file
2827 Projects.org_archive, as top-level trees. This is the default.
2828
2829 \"::* Archived Tasks\"
2830 Archive in the current file, under the top-level headline
2831 \"* Archived Tasks\".
2832
2833 \"~/org/archive.org::\"
2834 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2835
2836 \"~/org/archive.org::From %s\"
2837 Archive in file ~/org/archive.org (absolute path), und headlines
2838 \"From FILENAME\" where file name is the current file name.
2839
2840 \"basement::** Finished Tasks\"
2841 Archive in file ./basement (relative path), as level 3 trees
2842 below the level 2 heading \"** Finished Tasks\".
2843
2844 You may set this option on a per-file basis by adding to the buffer a
2845 line like
2846
2847 #+ARCHIVE: basement::** Finished Tasks
2848
2849 You may also define it locally for a subtree by setting an ARCHIVE property
2850 in the entry. If such a property is found in an entry, or anywhere up
2851 the hierarchy, it will be used."
2852 :group 'org-archive
2853 :type 'string)
2854
2855 (defcustom org-archive-tag "ARCHIVE"
2856 "The tag that marks a subtree as archived.
2857 An archived subtree does not open during visibility cycling, and does
2858 not contribute to the agenda listings.
2859 After changing this, font-lock must be restarted in the relevant buffers to
2860 get the proper fontification."
2861 :group 'org-archive
2862 :group 'org-keywords
2863 :type 'string)
2864
2865 (defcustom org-agenda-skip-archived-trees t
2866 "Non-nil means, the agenda will skip any items located in archived trees.
2867 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2868 variable is no longer recommended, you should leave it at the value t.
2869 Instead, use the key `v' to cycle the archives-mode in the agenda."
2870 :group 'org-archive
2871 :group 'org-agenda-skip
2872 :type 'boolean)
2873
2874 (defcustom org-cycle-open-archived-trees nil
2875 "Non-nil means, `org-cycle' will open archived trees.
2876 An archived tree is a tree marked with the tag ARCHIVE.
2877 When nil, archived trees will stay folded. You can still open them with
2878 normal outline commands like `show-all', but not with the cycling commands."
2879 :group 'org-archive
2880 :group 'org-cycle
2881 :type 'boolean)
2882
2883 (defcustom org-sparse-tree-open-archived-trees nil
2884 "Non-nil means sparse tree construction shows matches in archived trees.
2885 When nil, matches in these trees are highlighted, but the trees are kept in
2886 collapsed state."
2887 :group 'org-archive
2888 :group 'org-sparse-trees
2889 :type 'boolean)
2890
2891 (defun org-cycle-hide-archived-subtrees (state)
2892 "Re-hide all archived subtrees after a visibility state change."
2893 (when (and (not org-cycle-open-archived-trees)
2894 (not (memq state '(overview folded))))
2895 (save-excursion
2896 (let* ((globalp (memq state '(contents all)))
2897 (beg (if globalp (point-min) (point)))
2898 (end (if globalp (point-max) (org-end-of-subtree t))))
2899 (org-hide-archived-subtrees beg end)
2900 (goto-char beg)
2901 (if (looking-at (concat ".*:" org-archive-tag ":"))
2902 (message "%s" (substitute-command-keys
2903 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2904
2905 (defun org-force-cycle-archived ()
2906 "Cycle subtree even if it is archived."
2907 (interactive)
2908 (setq this-command 'org-cycle)
2909 (let ((org-cycle-open-archived-trees t))
2910 (call-interactively 'org-cycle)))
2911
2912 (defun org-hide-archived-subtrees (beg end)
2913 "Re-hide all archived subtrees after a visibility state change."
2914 (save-excursion
2915 (let* ((re (concat ":" org-archive-tag ":")))
2916 (goto-char beg)
2917 (while (re-search-forward re end t)
2918 (and (org-on-heading-p) (hide-subtree))
2919 (org-end-of-subtree t)))))
2920
2921 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2922
2923 (eval-and-compile
2924 (org-autoload "org-archive"
2925 '(org-add-archive-files org-archive-subtree
2926 org-archive-to-archive-sibling org-toggle-archive-tag)))
2927
2928 ;; Autoload Column View Code
2929
2930 (declare-function org-columns-number-to-string "org-colview")
2931 (declare-function org-columns-get-format-and-top-level "org-colview")
2932 (declare-function org-columns-compute "org-colview")
2933
2934 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2935 '(org-columns-number-to-string org-columns-get-format-and-top-level
2936 org-columns-compute org-agenda-columns org-columns-remove-overlays
2937 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2938
2939 ;; Autoload ID code
2940
2941 (declare-function org-id-store-link "org-id")
2942 (org-autoload "org-id"
2943 '(org-id-get-create org-id-new org-id-copy org-id-get
2944 org-id-get-with-outline-path-completion
2945 org-id-get-with-outline-drilling
2946 org-id-goto org-id-find org-id-store-link))
2947
2948 ;;; Variables for pre-computed regular expressions, all buffer local
2949
2950 (defvar org-drawer-regexp nil
2951 "Matches first line of a hidden block.")
2952 (make-variable-buffer-local 'org-drawer-regexp)
2953 (defvar org-todo-regexp nil
2954 "Matches any of the TODO state keywords.")
2955 (make-variable-buffer-local 'org-todo-regexp)
2956 (defvar org-not-done-regexp nil
2957 "Matches any of the TODO state keywords except the last one.")
2958 (make-variable-buffer-local 'org-not-done-regexp)
2959 (defvar org-todo-line-regexp nil
2960 "Matches a headline and puts TODO state into group 2 if present.")
2961 (make-variable-buffer-local 'org-todo-line-regexp)
2962 (defvar org-complex-heading-regexp nil
2963 "Matches a headline and puts everything into groups:
2964 group 1: the stars
2965 group 2: The todo keyword, maybe
2966 group 3: Priority cookie
2967 group 4: True headline
2968 group 5: Tags")
2969 (make-variable-buffer-local 'org-complex-heading-regexp)
2970 (defvar org-todo-line-tags-regexp nil
2971 "Matches a headline and puts TODO state into group 2 if present.
2972 Also put tags into group 4 if tags are present.")
2973 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2974 (defvar org-nl-done-regexp nil
2975 "Matches newline followed by a headline with the DONE keyword.")
2976 (make-variable-buffer-local 'org-nl-done-regexp)
2977 (defvar org-looking-at-done-regexp nil
2978 "Matches the DONE keyword a point.")
2979 (make-variable-buffer-local 'org-looking-at-done-regexp)
2980 (defvar org-ds-keyword-length 12
2981 "Maximum length of the Deadline and SCHEDULED keywords.")
2982 (make-variable-buffer-local 'org-ds-keyword-length)
2983 (defvar org-deadline-regexp nil
2984 "Matches the DEADLINE keyword.")
2985 (make-variable-buffer-local 'org-deadline-regexp)
2986 (defvar org-deadline-time-regexp nil
2987 "Matches the DEADLINE keyword together with a time stamp.")
2988 (make-variable-buffer-local 'org-deadline-time-regexp)
2989 (defvar org-deadline-line-regexp nil
2990 "Matches the DEADLINE keyword and the rest of the line.")
2991 (make-variable-buffer-local 'org-deadline-line-regexp)
2992 (defvar org-scheduled-regexp nil
2993 "Matches the SCHEDULED keyword.")
2994 (make-variable-buffer-local 'org-scheduled-regexp)
2995 (defvar org-scheduled-time-regexp nil
2996 "Matches the SCHEDULED keyword together with a time stamp.")
2997 (make-variable-buffer-local 'org-scheduled-time-regexp)
2998 (defvar org-closed-time-regexp nil
2999 "Matches the CLOSED keyword together with a time stamp.")
3000 (make-variable-buffer-local 'org-closed-time-regexp)
3001
3002 (defvar org-keyword-time-regexp nil
3003 "Matches any of the 4 keywords, together with the time stamp.")
3004 (make-variable-buffer-local 'org-keyword-time-regexp)
3005 (defvar org-keyword-time-not-clock-regexp nil
3006 "Matches any of the 3 keywords, together with the time stamp.")
3007 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3008 (defvar org-maybe-keyword-time-regexp nil
3009 "Matches a timestamp, possibly preceeded by a keyword.")
3010 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3011 (defvar org-planning-or-clock-line-re nil
3012 "Matches a line with planning or clock info.")
3013 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3014
3015 (defconst org-plain-time-of-day-regexp
3016 (concat
3017 "\\(\\<[012]?[0-9]"
3018 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3019 "\\(--?"
3020 "\\(\\<[012]?[0-9]"
3021 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3022 "\\)?")
3023 "Regular expression to match a plain time or time range.
3024 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3025 groups carry important information:
3026 0 the full match
3027 1 the first time, range or not
3028 8 the second time, if it is a range.")
3029
3030 (defconst org-plain-time-extension-regexp
3031 (concat
3032 "\\(\\<[012]?[0-9]"
3033 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3034 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3035 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3036 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3037 groups carry important information:
3038 0 the full match
3039 7 hours of duration
3040 9 minutes of duration")
3041
3042 (defconst org-stamp-time-of-day-regexp
3043 (concat
3044 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3045 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3046 "\\(--?"
3047 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3048 "Regular expression to match a timestamp time or time range.
3049 After a match, the following groups carry important information:
3050 0 the full match
3051 1 date plus weekday, for backreferencing to make sure both times on same day
3052 2 the first time, range or not
3053 4 the second time, if it is a range.")
3054
3055 (defconst org-startup-options
3056 '(("fold" org-startup-folded t)
3057 ("overview" org-startup-folded t)
3058 ("nofold" org-startup-folded nil)
3059 ("showall" org-startup-folded nil)
3060 ("content" org-startup-folded content)
3061 ("hidestars" org-hide-leading-stars t)
3062 ("showstars" org-hide-leading-stars nil)
3063 ("odd" org-odd-levels-only t)
3064 ("oddeven" org-odd-levels-only nil)
3065 ("align" org-startup-align-all-tables t)
3066 ("noalign" org-startup-align-all-tables nil)
3067 ("customtime" org-display-custom-times t)
3068 ("logdone" org-log-done time)
3069 ("lognotedone" org-log-done note)
3070 ("nologdone" org-log-done nil)
3071 ("lognoteclock-out" org-log-note-clock-out t)
3072 ("nolognoteclock-out" org-log-note-clock-out nil)
3073 ("logrepeat" org-log-repeat state)
3074 ("lognoterepeat" org-log-repeat note)
3075 ("nologrepeat" org-log-repeat nil)
3076 ("fninline" org-footnote-define-inline t)
3077 ("nofninline" org-footnote-define-inline nil)
3078 ("fnlocal" org-footnote-section nil)
3079 ("fnauto" org-footnote-auto-label t)
3080 ("fnprompt" org-footnote-auto-label nil)
3081 ("fnconfirm" org-footnote-auto-label confirm)
3082 ("fnplain" org-footnote-auto-label plain)
3083 ("constcgs" constants-unit-system cgs)
3084 ("constSI" constants-unit-system SI))
3085 "Variable associated with STARTUP options for org-mode.
3086 Each element is a list of three items: The startup options as written
3087 in the #+STARTUP line, the corresponding variable, and the value to
3088 set this variable to if the option is found. An optional forth element PUSH
3089 means to push this value onto the list in the variable.")
3090
3091 (defun org-set-regexps-and-options ()
3092 "Precompute regular expressions for current buffer."
3093 (when (org-mode-p)
3094 (org-set-local 'org-todo-kwd-alist nil)
3095 (org-set-local 'org-todo-key-alist nil)
3096 (org-set-local 'org-todo-key-trigger nil)
3097 (org-set-local 'org-todo-keywords-1 nil)
3098 (org-set-local 'org-done-keywords nil)
3099 (org-set-local 'org-todo-heads nil)
3100 (org-set-local 'org-todo-sets nil)
3101 (org-set-local 'org-todo-log-states nil)
3102 (org-set-local 'org-file-properties nil)
3103 (org-set-local 'org-file-tags nil)
3104 (let ((re (org-make-options-regexp
3105 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3106 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3107 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3108 (splitre "[ \t]+")
3109 kwds kws0 kwsa key log value cat arch tags const links hw dws
3110 tail sep kws1 prio props ftags drawers
3111 ext-setup-or-nil setup-contents (start 0))
3112 (save-excursion
3113 (save-restriction
3114 (widen)
3115 (goto-char (point-min))
3116 (while (or (and ext-setup-or-nil
3117 (string-match re ext-setup-or-nil start)
3118 (setq start (match-end 0)))
3119 (and (setq ext-setup-or-nil nil start 0)
3120 (re-search-forward re nil t)))
3121 (setq key (upcase (match-string 1 ext-setup-or-nil))
3122 value (org-match-string-no-properties 2 ext-setup-or-nil))
3123 (cond
3124 ((equal key "CATEGORY")
3125 (if (string-match "[ \t]+$" value)
3126 (setq value (replace-match "" t t value)))
3127 (setq cat value))
3128 ((member key '("SEQ_TODO" "TODO"))
3129 (push (cons 'sequence (org-split-string value splitre)) kwds))
3130 ((equal key "TYP_TODO")
3131 (push (cons 'type (org-split-string value splitre)) kwds))
3132 ((equal key "TAGS")
3133 (setq tags (append tags (org-split-string value splitre))))
3134 ((equal key "COLUMNS")
3135 (org-set-local 'org-columns-default-format value))
3136 ((equal key "LINK")
3137 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3138 (push (cons (match-string 1 value)
3139 (org-trim (match-string 2 value)))
3140 links)))
3141 ((equal key "PRIORITIES")
3142 (setq prio (org-split-string value " +")))
3143 ((equal key "PROPERTY")
3144 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3145 (push (cons (match-string 1 value) (match-string 2 value))
3146 props)))
3147 ((equal key "FILETAGS")
3148 (when (string-match "\\S-" value)
3149 (setq ftags
3150 (append
3151 ftags
3152 (apply 'append
3153 (mapcar (lambda (x) (org-split-string x ":"))
3154 (org-split-string value)))))))
3155 ((equal key "DRAWERS")
3156 (setq drawers (org-split-string value splitre)))
3157 ((equal key "CONSTANTS")
3158 (setq const (append const (org-split-string value splitre))))
3159 ((equal key "STARTUP")
3160 (let ((opts (org-split-string value splitre))
3161 l var val)
3162 (while (setq l (pop opts))
3163 (when (setq l (assoc l org-startup-options))
3164 (setq var (nth 1 l) val (nth 2 l))
3165 (if (not (nth 3 l))
3166 (set (make-local-variable var) val)
3167 (if (not (listp (symbol-value var)))
3168 (set (make-local-variable var) nil))
3169 (set (make-local-variable var) (symbol-value var))
3170 (add-to-list var val))))))
3171 ((equal key "ARCHIVE")
3172 (string-match " *$" value)
3173 (setq arch (replace-match "" t t value))
3174 (remove-text-properties 0 (length arch)
3175 '(face t fontified t) arch))
3176 ((equal key "SETUPFILE")
3177 (setq setup-contents (org-file-contents
3178 (expand-file-name
3179 (org-remove-double-quotes value))
3180 'noerror))
3181 (if (not ext-setup-or-nil)
3182 (setq ext-setup-or-nil setup-contents start 0)
3183 (setq ext-setup-or-nil
3184 (concat (substring ext-setup-or-nil 0 start)
3185 "\n" setup-contents "\n"
3186 (substring ext-setup-or-nil start)))))
3187 ))))
3188 (when cat
3189 (org-set-local 'org-category (intern cat))
3190 (push (cons "CATEGORY" cat) props))
3191 (when prio
3192 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3193 (setq prio (mapcar 'string-to-char prio))
3194 (org-set-local 'org-highest-priority (nth 0 prio))
3195 (org-set-local 'org-lowest-priority (nth 1 prio))
3196 (org-set-local 'org-default-priority (nth 2 prio)))
3197 (and props (org-set-local 'org-file-properties (nreverse props)))
3198 (and ftags (org-set-local 'org-file-tags ftags))
3199 (and drawers (org-set-local 'org-drawers drawers))
3200 (and arch (org-set-local 'org-archive-location arch))
3201 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3202 ;; Process the TODO keywords
3203 (unless kwds
3204 ;; Use the global values as if they had been given locally.
3205 (setq kwds (default-value 'org-todo-keywords))
3206 (if (stringp (car kwds))
3207 (setq kwds (list (cons org-todo-interpretation
3208 (default-value 'org-todo-keywords)))))
3209 (setq kwds (reverse kwds)))
3210 (setq kwds (nreverse kwds))
3211 (let (inter kws kw)
3212 (while (setq kws (pop kwds))
3213 (setq inter (pop kws) sep (member "|" kws)
3214 kws0 (delete "|" (copy-sequence kws))
3215 kwsa nil
3216 kws1 (mapcar
3217 (lambda (x)
3218 ;; 1 2
3219 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3220 (progn
3221 (setq kw (match-string 1 x)
3222 key (and (match-end 2) (match-string 2 x))
3223 log (org-extract-log-state-settings x))
3224 (push (cons kw (and key (string-to-char key))) kwsa)
3225 (and log (push log org-todo-log-states))
3226 kw)
3227 (error "Invalid TODO keyword %s" x)))
3228 kws0)
3229 kwsa (if kwsa (append '((:startgroup))
3230 (nreverse kwsa)
3231 '((:endgroup))))
3232 hw (car kws1)
3233 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3234 tail (list inter hw (car dws) (org-last dws)))
3235 (add-to-list 'org-todo-heads hw 'append)
3236 (push kws1 org-todo-sets)
3237 (setq org-done-keywords (append org-done-keywords dws nil))
3238 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3239 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3240 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3241 (setq org-todo-sets (nreverse org-todo-sets)
3242 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3243 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3244 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3245 ;; Process the constants
3246 (when const
3247 (let (e cst)
3248 (while (setq e (pop const))
3249 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3250 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3251 (setq org-table-formula-constants-local cst)))
3252
3253 ;; Process the tags.
3254 (when tags
3255 (let (e tgs)
3256 (while (setq e (pop tags))
3257 (cond
3258 ((equal e "{") (push '(:startgroup) tgs))
3259 ((equal e "}") (push '(:endgroup) tgs))
3260 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3261 (push (cons (match-string 1 e)
3262 (string-to-char (match-string 2 e)))
3263 tgs))
3264 (t (push (list e) tgs))))
3265 (org-set-local 'org-tag-alist nil)
3266 (while (setq e (pop tgs))
3267 (or (and (stringp (car e))
3268 (assoc (car e) org-tag-alist))
3269 (push e org-tag-alist)))))
3270
3271 ;; Compute the regular expressions and other local variables
3272 (if (not org-done-keywords)
3273 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3274 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3275 (length org-scheduled-string)
3276 (length org-clock-string)
3277 (length org-closed-string)))
3278 org-drawer-regexp
3279 (concat "^[ \t]*:\\("
3280 (mapconcat 'regexp-quote org-drawers "\\|")
3281 "\\):[ \t]*$")
3282 org-not-done-keywords
3283 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3284 org-todo-regexp
3285 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3286 "\\|") "\\)\\>")
3287 org-not-done-regexp
3288 (concat "\\<\\("
3289 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3290 "\\)\\>")
3291 org-todo-line-regexp
3292 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3293 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3294 "\\)\\>\\)?[ \t]*\\(.*\\)")
3295 org-complex-heading-regexp
3296 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3297 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3298 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3299 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3300 org-nl-done-regexp
3301 (concat "\n\\*+[ \t]+"
3302 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3303 "\\)" "\\>")
3304 org-todo-line-tags-regexp
3305 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3306 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3307 (org-re
3308 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3309 org-looking-at-done-regexp
3310 (concat "^" "\\(?:"
3311 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3312 "\\>")
3313 org-deadline-regexp (concat "\\<" org-deadline-string)
3314 org-deadline-time-regexp
3315 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3316 org-deadline-line-regexp
3317 (concat "\\<\\(" org-deadline-string "\\).*")
3318 org-scheduled-regexp
3319 (concat "\\<" org-scheduled-string)
3320 org-scheduled-time-regexp
3321 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3322 org-closed-time-regexp
3323 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3324 org-keyword-time-regexp
3325 (concat "\\<\\(" org-scheduled-string
3326 "\\|" org-deadline-string
3327 "\\|" org-closed-string
3328 "\\|" org-clock-string "\\)"
3329 " *[[<]\\([^]>]+\\)[]>]")
3330 org-keyword-time-not-clock-regexp
3331 (concat "\\<\\(" org-scheduled-string
3332 "\\|" org-deadline-string
3333 "\\|" org-closed-string
3334 "\\)"
3335 " *[[<]\\([^]>]+\\)[]>]")
3336 org-maybe-keyword-time-regexp
3337 (concat "\\(\\<\\(" org-scheduled-string
3338 "\\|" org-deadline-string
3339 "\\|" org-closed-string
3340 "\\|" org-clock-string "\\)\\)?"
3341 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3342 org-planning-or-clock-line-re
3343 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3344 "\\|" org-deadline-string
3345 "\\|" org-closed-string "\\|" org-clock-string
3346 "\\)\\>\\)")
3347 )
3348 (org-compute-latex-and-specials-regexp)
3349 (org-set-font-lock-defaults))))
3350
3351 (defun org-file-contents (file &optional noerror)
3352 "Return the contents of FILE, as a string."
3353 (if (or (not file)
3354 (not (file-readable-p file)))
3355 (if noerror
3356 (progn
3357 (message "Cannot read file %s" file)
3358 (ding) (sit-for 2)
3359 "")
3360 (error "Cannot read file %s" file))
3361 (with-temp-buffer
3362 (insert-file-contents file)
3363 (buffer-string))))
3364
3365 (defun org-extract-log-state-settings (x)
3366 "Extract the log state setting from a TODO keyword string.
3367 This will extract info from a string like \"WAIT(w@/!)\"."
3368 (let (kw key log1 log2)
3369 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3370 (setq kw (match-string 1 x)
3371 key (and (match-end 2) (match-string 2 x))
3372 log1 (and (match-end 3) (match-string 3 x))
3373 log2 (and (match-end 4) (match-string 4 x)))
3374 (and (or log1 log2)
3375 (list kw
3376 (and log1 (if (equal log1 "!") 'time 'note))
3377 (and log2 (if (equal log2 "!") 'time 'note)))))))
3378
3379 (defun org-remove-keyword-keys (list)
3380 "Remove a pair of parenthesis at the end of each string in LIST."
3381 (mapcar (lambda (x)
3382 (if (string-match "(.*)$" x)
3383 (substring x 0 (match-beginning 0))
3384 x))
3385 list))
3386
3387 ;; FIXME: this could be done much better, using second characters etc.
3388 (defun org-assign-fast-keys (alist)
3389 "Assign fast keys to a keyword-key alist.
3390 Respect keys that are already there."
3391 (let (new e k c c1 c2 (char ?a))
3392 (while (setq e (pop alist))
3393 (cond
3394 ((equal e '(:startgroup)) (push e new))
3395 ((equal e '(:endgroup)) (push e new))
3396 (t
3397 (setq k (car e) c2 nil)
3398 (if (cdr e)
3399 (setq c (cdr e))
3400 ;; automatically assign a character.
3401 (setq c1 (string-to-char
3402 (downcase (substring
3403 k (if (= (string-to-char k) ?@) 1 0)))))
3404 (if (or (rassoc c1 new) (rassoc c1 alist))
3405 (while (or (rassoc char new) (rassoc char alist))
3406 (setq char (1+ char)))
3407 (setq c2 c1))
3408 (setq c (or c2 char)))
3409 (push (cons k c) new))))
3410 (nreverse new)))
3411
3412 ;;; Some variables used in various places
3413
3414 (defvar org-window-configuration nil
3415 "Used in various places to store a window configuration.")
3416 (defvar org-finish-function nil
3417 "Function to be called when `C-c C-c' is used.
3418 This is for getting out of special buffers like remember.")
3419
3420
3421 ;; FIXME: Occasionally check by commenting these, to make sure
3422 ;; no other functions uses these, forgetting to let-bind them.
3423 (defvar entry)
3424 (defvar state)
3425 (defvar last-state)
3426 (defvar date)
3427 (defvar description)
3428
3429 ;; Defined somewhere in this file, but used before definition.
3430 (defvar org-html-entities)
3431 (defvar org-struct-menu)
3432 (defvar org-org-menu)
3433 (defvar org-tbl-menu)
3434 (defvar org-agenda-keymap)
3435
3436 ;;;; Define the Org-mode
3437
3438 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3439 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22."))
3440
3441
3442 ;; We use a before-change function to check if a table might need
3443 ;; an update.
3444 (defvar org-table-may-need-update t
3445 "Indicates that a table might need an update.
3446 This variable is set by `org-before-change-function'.
3447 `org-table-align' sets it back to nil.")
3448 (defun org-before-change-function (beg end)
3449 "Every change indicates that a table might need an update."
3450 (setq org-table-may-need-update t))
3451 (defvar org-mode-map)
3452 (defvar org-mode-hook nil
3453 "Mode hook for Org-mode, run after the mode was turned on.")
3454 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3455 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3456 (defvar org-table-buffer-is-an nil)
3457 (defconst org-outline-regexp "\\*+ ")
3458
3459 ;;;###autoload
3460 (define-derived-mode org-mode outline-mode "Org"
3461 "Outline-based notes management and organizer, alias
3462 \"Carsten's outline-mode for keeping track of everything.\"
3463
3464 Org-mode develops organizational tasks around a NOTES file which
3465 contains information about projects as plain text. Org-mode is
3466 implemented on top of outline-mode, which is ideal to keep the content
3467 of large files well structured. It supports ToDo items, deadlines and
3468 time stamps, which magically appear in the diary listing of the Emacs
3469 calendar. Tables are easily created with a built-in table editor.
3470 Plain text URL-like links connect to websites, emails (VM), Usenet
3471 messages (Gnus), BBDB entries, and any files related to the project.
3472 For printing and sharing of notes, an Org-mode file (or a part of it)
3473 can be exported as a structured ASCII or HTML file.
3474
3475 The following commands are available:
3476
3477 \\{org-mode-map}"
3478
3479 ;; Get rid of Outline menus, they are not needed
3480 ;; Need to do this here because define-derived-mode sets up
3481 ;; the keymap so late. Still, it is a waste to call this each time
3482 ;; we switch another buffer into org-mode.
3483 (if (featurep 'xemacs)
3484 (when (boundp 'outline-mode-menu-heading)
3485 ;; Assume this is Greg's port, it used easymenu
3486 (easy-menu-remove outline-mode-menu-heading)
3487 (easy-menu-remove outline-mode-menu-show)
3488 (easy-menu-remove outline-mode-menu-hide))
3489 (define-key org-mode-map [menu-bar headings] 'undefined)
3490 (define-key org-mode-map [menu-bar hide] 'undefined)
3491 (define-key org-mode-map [menu-bar show] 'undefined))
3492
3493 (org-load-modules-maybe)
3494 (easy-menu-add org-org-menu)
3495 (easy-menu-add org-tbl-menu)
3496 (org-install-agenda-files-menu)
3497 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3498 (org-add-to-invisibility-spec '(org-cwidth))
3499 (when (featurep 'xemacs)
3500 (org-set-local 'line-move-ignore-invisible t))
3501 (org-set-local 'outline-regexp org-outline-regexp)
3502 (org-set-local 'outline-level 'org-outline-level)
3503 (when (and org-ellipsis
3504 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3505 (fboundp 'make-glyph-code))
3506 (unless org-display-table
3507 (setq org-display-table (make-display-table)))
3508 (set-display-table-slot
3509 org-display-table 4
3510 (vconcat (mapcar
3511 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3512 org-ellipsis)))
3513 (if (stringp org-ellipsis) org-ellipsis "..."))))
3514 (setq buffer-display-table org-display-table))
3515 (org-set-regexps-and-options)
3516 (when (and org-tag-faces (not org-tags-special-faces-re))
3517 ;; tag faces set outside customize.... force initialization.
3518 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3519 ;; Calc embedded
3520 (org-set-local 'calc-embedded-open-mode "# ")
3521 (modify-syntax-entry ?# "<")
3522 (modify-syntax-entry ?@ "w")
3523 (if org-startup-truncated (setq truncate-lines t))
3524 (org-set-local 'font-lock-unfontify-region-function
3525 'org-unfontify-region)
3526 ;; Activate before-change-function
3527 (org-set-local 'org-table-may-need-update t)
3528 (org-add-hook 'before-change-functions 'org-before-change-function nil
3529 'local)
3530 ;; Check for running clock before killing a buffer
3531 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3532 ;; Paragraphs and auto-filling
3533 (org-set-autofill-regexps)
3534 (setq indent-line-function 'org-indent-line-function)
3535 (org-update-radio-target-regexp)
3536
3537 ;; Comment characters
3538 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3539 (org-set-local 'comment-padding " ")
3540
3541 ;; Align options lines
3542 (org-set-local
3543 'align-mode-rules-list
3544 '((org-in-buffer-settings
3545 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3546 (modes . '(org-mode)))))
3547
3548 ;; Imenu
3549 (org-set-local 'imenu-create-index-function
3550 'org-imenu-get-tree)
3551
3552 ;; Make isearch reveal context
3553 (if (or (featurep 'xemacs)
3554 (not (boundp 'outline-isearch-open-invisible-function)))
3555 ;; Emacs 21 and XEmacs make use of the hook
3556 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3557 ;; Emacs 22 deals with this through a special variable
3558 (org-set-local 'outline-isearch-open-invisible-function
3559 (lambda (&rest ignore) (org-show-context 'isearch))))
3560
3561 ;; If empty file that did not turn on org-mode automatically, make it to.
3562 (if (and org-insert-mode-line-in-empty-file
3563 (interactive-p)
3564 (= (point-min) (point-max)))
3565 (insert "# -*- mode: org -*-\n\n"))
3566
3567 (unless org-inhibit-startup
3568 (when org-startup-align-all-tables
3569 (let ((bmp (buffer-modified-p)))
3570 (org-table-map-tables 'org-table-align)
3571 (set-buffer-modified-p bmp)))
3572 (org-set-startup-visibility)))
3573
3574 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3575
3576 (defun org-current-time ()
3577 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3578 (if (> (car org-time-stamp-rounding-minutes) 1)
3579 (let ((r (car org-time-stamp-rounding-minutes))
3580 (time (decode-time)))
3581 (apply 'encode-time
3582 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3583 (nthcdr 2 time))))
3584 (current-time)))
3585
3586 ;;;; Font-Lock stuff, including the activators
3587
3588 (defvar org-mouse-map (make-sparse-keymap))
3589 (org-defkey org-mouse-map
3590 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3591 (org-defkey org-mouse-map
3592 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3593 (when org-mouse-1-follows-link
3594 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3595 (when org-tab-follows-link
3596 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3597 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3598 (when org-return-follows-link
3599 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3600 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3601
3602 (require 'font-lock)
3603
3604 (defconst org-non-link-chars "]\t\n\r<>")
3605 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3606 "shell" "elisp"))
3607 (defvar org-link-types-re nil
3608 "Matches a link that has a url-like prefix like \"http:\"")
3609 (defvar org-link-re-with-space nil
3610 "Matches a link with spaces, optional angular brackets around it.")
3611 (defvar org-link-re-with-space2 nil
3612 "Matches a link with spaces, optional angular brackets around it.")
3613 (defvar org-link-re-with-space3 nil
3614 "Matches a link with spaces, only for internal part in bracket links.")
3615 (defvar org-angle-link-re nil
3616 "Matches link with angular brackets, spaces are allowed.")
3617 (defvar org-plain-link-re nil
3618 "Matches plain link, without spaces.")
3619 (defvar org-bracket-link-regexp nil
3620 "Matches a link in double brackets.")
3621 (defvar org-bracket-link-analytic-regexp nil
3622 "Regular expression used to analyze links.
3623 Here is what the match groups contain after a match:
3624 1: http:
3625 2: http
3626 3: path
3627 4: [desc]
3628 5: desc")
3629 (defvar org-bracket-link-analytic-regexp++ nil
3630 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3631 (defvar org-any-link-re nil
3632 "Regular expression matching any link.")
3633
3634 (defun org-make-link-regexps ()
3635 "Update the link regular expressions.
3636 This should be called after the variable `org-link-types' has changed."
3637 (setq org-link-types-re
3638 (concat
3639 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3640 org-link-re-with-space
3641 (concat
3642 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3643 "\\([^" org-non-link-chars " ]"
3644 "[^" org-non-link-chars "]*"
3645 "[^" org-non-link-chars " ]\\)>?")
3646 org-link-re-with-space2
3647 (concat
3648 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3649 "\\([^" org-non-link-chars " ]"
3650 "[^\t\n\r]*"
3651 "[^" org-non-link-chars " ]\\)>?")
3652 org-link-re-with-space3
3653 (concat
3654 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3655 "\\([^" org-non-link-chars " ]"
3656 "[^\t\n\r]*\\)")
3657 org-angle-link-re
3658 (concat
3659 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3660 "\\([^" org-non-link-chars " ]"
3661 "[^" org-non-link-chars "]*"
3662 "\\)>")
3663 org-plain-link-re
3664 (concat
3665 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3666 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3667 org-bracket-link-regexp
3668 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3669 org-bracket-link-analytic-regexp
3670 (concat
3671 "\\[\\["
3672 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3673 "\\([^]]+\\)"
3674 "\\]"
3675 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3676 "\\]")
3677 org-bracket-link-analytic-regexp++
3678 (concat
3679 "\\[\\["
3680 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3681 "\\([^]]+\\)"
3682 "\\]"
3683 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3684 "\\]")
3685 org-any-link-re
3686 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3687 org-angle-link-re "\\)\\|\\("
3688 org-plain-link-re "\\)")))
3689
3690 (org-make-link-regexps)
3691
3692 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3693 "Regular expression for fast time stamp matching.")
3694 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3695 "Regular expression for fast time stamp matching.")
3696 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3697 "Regular expression matching time strings for analysis.
3698 This one does not require the space after the date, so it can be used
3699 on a string that terminates immediately after the date.")
3700 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3701 "Regular expression matching time strings for analysis.")
3702 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3703 "Regular expression matching time stamps, with groups.")
3704 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3705 "Regular expression matching time stamps (also [..]), with groups.")
3706 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3707 "Regular expression matching a time stamp range.")
3708 (defconst org-tr-regexp-both
3709 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3710 "Regular expression matching a time stamp range.")
3711 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3712 org-ts-regexp "\\)?")
3713 "Regular expression matching a time stamp or time stamp range.")
3714 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3715 org-ts-regexp-both "\\)?")
3716 "Regular expression matching a time stamp or time stamp range.
3717 The time stamps may be either active or inactive.")
3718
3719 (defvar org-emph-face nil)
3720
3721 (defun org-do-emphasis-faces (limit)
3722 "Run through the buffer and add overlays to links."
3723 (let (rtn)
3724 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3725 (if (not (= (char-after (match-beginning 3))
3726 (char-after (match-beginning 4))))
3727 (progn
3728 (setq rtn t)
3729 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3730 'face
3731 (nth 1 (assoc (match-string 3)
3732 org-emphasis-alist)))
3733 (add-text-properties (match-beginning 2) (match-end 2)
3734 '(font-lock-multiline t))
3735 (when org-hide-emphasis-markers
3736 (add-text-properties (match-end 4) (match-beginning 5)
3737 '(invisible org-link))
3738 (add-text-properties (match-beginning 3) (match-end 3)
3739 '(invisible org-link)))))
3740 (backward-char 1))
3741 rtn))
3742
3743 (defun org-emphasize (&optional char)
3744 "Insert or change an emphasis, i.e. a font like bold or italic.
3745 If there is an active region, change that region to a new emphasis.
3746 If there is no region, just insert the marker characters and position
3747 the cursor between them.
3748 CHAR should be either the marker character, or the first character of the
3749 HTML tag associated with that emphasis. If CHAR is a space, the means
3750 to remove the emphasis of the selected region.
3751 If char is not given (for example in an interactive call) it
3752 will be prompted for."
3753 (interactive)
3754 (let ((eal org-emphasis-alist) e det
3755 (erc org-emphasis-regexp-components)
3756 (prompt "")
3757 (string "") beg end move tag c s)
3758 (if (org-region-active-p)
3759 (setq beg (region-beginning) end (region-end)
3760 string (buffer-substring beg end))
3761 (setq move t))
3762
3763 (while (setq e (pop eal))
3764 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3765 c (aref tag 0))
3766 (push (cons c (string-to-char (car e))) det)
3767 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3768 (substring tag 1)))))
3769 (setq det (nreverse det))
3770 (unless char
3771 (message "%s" (concat "Emphasis marker or tag:" prompt))
3772 (setq char (read-char-exclusive)))
3773 (setq char (or (cdr (assoc char det)) char))
3774 (if (equal char ?\ )
3775 (setq s "" move nil)
3776 (unless (assoc (char-to-string char) org-emphasis-alist)
3777 (error "No such emphasis marker: \"%c\"" char))
3778 (setq s (char-to-string char)))
3779 (while (and (> (length string) 1)
3780 (equal (substring string 0 1) (substring string -1))
3781 (assoc (substring string 0 1) org-emphasis-alist))
3782 (setq string (substring string 1 -1)))
3783 (setq string (concat s string s))
3784 (if beg (delete-region beg end))
3785 (unless (or (bolp)
3786 (string-match (concat "[" (nth 0 erc) "\n]")
3787 (char-to-string (char-before (point)))))
3788 (insert " "))
3789 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3790 (char-to-string (char-after (point))))
3791 (insert " ") (backward-char 1))
3792 (insert string)
3793 (and move (backward-char 1))))
3794
3795 (defconst org-nonsticky-props
3796 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3797
3798
3799 (defun org-activate-plain-links (limit)
3800 "Run through the buffer and add overlays to links."
3801 (catch 'exit
3802 (let (f)
3803 (while (re-search-forward org-plain-link-re limit t)
3804 (setq f (get-text-property (match-beginning 0) 'face))
3805 (if (or (eq f 'org-tag)
3806 (and (listp f) (memq 'org-tag f)))
3807 nil
3808 (add-text-properties (match-beginning 0) (match-end 0)
3809 (list 'mouse-face 'highlight
3810 'rear-nonsticky org-nonsticky-props
3811 'keymap org-mouse-map
3812 ))
3813 (throw 'exit t))))))
3814
3815 (defun org-activate-code (limit)
3816 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3817 (progn
3818 (remove-text-properties (match-beginning 0) (match-end 0)
3819 '(display t invisible t intangible t))
3820 t)))
3821
3822 (defun org-activate-angle-links (limit)
3823 "Run through the buffer and add overlays to links."
3824 (if (re-search-forward org-angle-link-re limit t)
3825 (progn
3826 (add-text-properties (match-beginning 0) (match-end 0)
3827 (list 'mouse-face 'highlight
3828 'rear-nonsticky org-nonsticky-props
3829 'keymap org-mouse-map
3830 ))
3831 t)))
3832
3833 (defun org-activate-footnote-links (limit)
3834 "Run through the buffer and add overlays to links."
3835 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
3836 limit t)
3837 (progn
3838 (add-text-properties (match-beginning 2) (match-end 2)
3839 (list 'mouse-face 'highlight
3840 'rear-nonsticky org-nonsticky-props
3841 'keymap org-mouse-map
3842 'help-echo
3843 (if (= (point-at-bol) (match-beginning 2))
3844 "Footnote definition"
3845 "Footnote reference")
3846 ))
3847 t)))
3848
3849 (defun org-activate-bracket-links (limit)
3850 "Run through the buffer and add overlays to bracketed links."
3851 (if (re-search-forward org-bracket-link-regexp limit t)
3852 (let* ((help (concat "LINK: "
3853 (org-match-string-no-properties 1)))
3854 ;; FIXME: above we should remove the escapes.
3855 ;; but that requires another match, protecting match data,
3856 ;; a lot of overhead for font-lock.
3857 (ip (org-maybe-intangible
3858 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3859 'keymap org-mouse-map 'mouse-face 'highlight
3860 'font-lock-multiline t 'help-echo help)))
3861 (vp (list 'rear-nonsticky org-nonsticky-props
3862 'keymap org-mouse-map 'mouse-face 'highlight
3863 ' font-lock-multiline t 'help-echo help)))
3864 ;; We need to remove the invisible property here. Table narrowing
3865 ;; may have made some of this invisible.
3866 (remove-text-properties (match-beginning 0) (match-end 0)
3867 '(invisible nil))
3868 (if (match-end 3)
3869 (progn
3870 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3871 (add-text-properties (match-beginning 3) (match-end 3) vp)
3872 (add-text-properties (match-end 3) (match-end 0) ip))
3873 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3874 (add-text-properties (match-beginning 1) (match-end 1) vp)
3875 (add-text-properties (match-end 1) (match-end 0) ip))
3876 t)))
3877
3878 (defun org-activate-dates (limit)
3879 "Run through the buffer and add overlays to dates."
3880 (if (re-search-forward org-tsr-regexp-both limit t)
3881 (progn
3882 (add-text-properties (match-beginning 0) (match-end 0)
3883 (list 'mouse-face 'highlight
3884 'rear-nonsticky org-nonsticky-props
3885 'keymap org-mouse-map))
3886 (when org-display-custom-times
3887 (if (match-end 3)
3888 (org-display-custom-time (match-beginning 3) (match-end 3)))
3889 (org-display-custom-time (match-beginning 1) (match-end 1)))
3890 t)))
3891
3892 (defvar org-target-link-regexp nil
3893 "Regular expression matching radio targets in plain text.")
3894 (make-variable-buffer-local 'org-target-link-regexp)
3895 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3896 "Regular expression matching a link target.")
3897 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3898 "Regular expression matching a radio target.")
3899 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3900 "Regular expression matching any target.")
3901
3902 (defun org-activate-target-links (limit)
3903 "Run through the buffer and add overlays to target matches."
3904 (when org-target-link-regexp
3905 (let ((case-fold-search t))
3906 (if (re-search-forward org-target-link-regexp limit t)
3907 (progn
3908 (add-text-properties (match-beginning 0) (match-end 0)
3909 (list 'mouse-face 'highlight
3910 'rear-nonsticky org-nonsticky-props
3911 'keymap org-mouse-map
3912 'help-echo "Radio target link"
3913 'org-linked-text t))
3914 t)))))
3915
3916 (defun org-update-radio-target-regexp ()
3917 "Find all radio targets in this file and update the regular expression."
3918 (interactive)
3919 (when (memq 'radio org-activate-links)
3920 (setq org-target-link-regexp
3921 (org-make-target-link-regexp (org-all-targets 'radio)))
3922 (org-restart-font-lock)))
3923
3924 (defun org-hide-wide-columns (limit)
3925 (let (s e)
3926 (setq s (text-property-any (point) (or limit (point-max))
3927 'org-cwidth t))
3928 (when s
3929 (setq e (next-single-property-change s 'org-cwidth))
3930 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3931 (goto-char e)
3932 t)))
3933
3934 (defvar org-latex-and-specials-regexp nil
3935 "Regular expression for highlighting export special stuff.")
3936 (defvar org-match-substring-regexp)
3937 (defvar org-match-substring-with-braces-regexp)
3938 (defvar org-export-html-special-string-regexps)
3939
3940 (defun org-compute-latex-and-specials-regexp ()
3941 "Compute regular expression for stuff treated specially by exporters."
3942 (if (not org-highlight-latex-fragments-and-specials)
3943 (org-set-local 'org-latex-and-specials-regexp nil)
3944 (require 'org-exp)
3945 (let*
3946 ((matchers (plist-get org-format-latex-options :matchers))
3947 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3948 org-latex-regexps)))
3949 (options (org-combine-plists (org-default-export-plist)
3950 (org-infile-export-plist)))
3951 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3952 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3953 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3954 (org-export-html-expand (plist-get options :expand-quoted-html))
3955 (org-export-with-special-strings (plist-get options :special-strings))
3956 (re-sub
3957 (cond
3958 ((equal org-export-with-sub-superscripts '{})
3959 (list org-match-substring-with-braces-regexp))
3960 (org-export-with-sub-superscripts
3961 (list org-match-substring-regexp))
3962 (t nil)))
3963 (re-latex
3964 (if org-export-with-LaTeX-fragments
3965 (mapcar (lambda (x) (nth 1 x)) latexs)))
3966 (re-macros
3967 (if org-export-with-TeX-macros
3968 (list (concat "\\\\"
3969 (regexp-opt
3970 (append (mapcar 'car org-html-entities)
3971 (if (boundp 'org-latex-entities)
3972 org-latex-entities nil))
3973 'words))) ; FIXME
3974 ))
3975 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3976 (re-special (if org-export-with-special-strings
3977 (mapcar (lambda (x) (car x))
3978 org-export-html-special-string-regexps)))
3979 (re-rest
3980 (delq nil
3981 (list
3982 (if org-export-html-expand "@<[^>\n]+>")
3983 ))))
3984 (org-set-local
3985 'org-latex-and-specials-regexp
3986 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3987 re-rest) "\\|")))))
3988
3989 (defun org-do-latex-and-special-faces (limit)
3990 "Run through the buffer and add overlays to links."
3991 (when org-latex-and-specials-regexp
3992 (let (rtn d)
3993 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3994 limit t))
3995 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3996 'face))
3997 '(org-code org-verbatim underline)))
3998 (progn
3999 (setq rtn t
4000 d (cond ((member (char-after (1+ (match-beginning 0)))
4001 '(?_ ?^)) 1)
4002 (t 0)))
4003 (font-lock-prepend-text-property
4004 (+ d (match-beginning 0)) (match-end 0)
4005 'face 'org-latex-and-export-specials)
4006 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4007 '(font-lock-multiline t)))))
4008 rtn)))
4009
4010 (defun org-restart-font-lock ()
4011 "Restart font-lock-mode, to force refontification."
4012 (when (and (boundp 'font-lock-mode) font-lock-mode)
4013 (font-lock-mode -1)
4014 (font-lock-mode 1)))
4015
4016 (defun org-all-targets (&optional radio)
4017 "Return a list of all targets in this file.
4018 With optional argument RADIO, only find radio targets."
4019 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4020 rtn)
4021 (save-excursion
4022 (goto-char (point-min))
4023 (while (re-search-forward re nil t)
4024 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4025 rtn)))
4026
4027 (defun org-make-target-link-regexp (targets)
4028 "Make regular expression matching all strings in TARGETS.
4029 The regular expression finds the targets also if there is a line break
4030 between words."
4031 (and targets
4032 (concat
4033 "\\<\\("
4034 (mapconcat
4035 (lambda (x)
4036 (while (string-match " +" x)
4037 (setq x (replace-match "\\s-+" t t x)))
4038 x)
4039 targets
4040 "\\|")
4041 "\\)\\>")))
4042
4043 (defun org-activate-tags (limit)
4044 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4045 (progn
4046 (add-text-properties (match-beginning 1) (match-end 1)
4047 (list 'mouse-face 'highlight
4048 'rear-nonsticky org-nonsticky-props
4049 'keymap org-mouse-map))
4050 t)))
4051
4052 (defun org-outline-level ()
4053 (save-excursion
4054 (looking-at outline-regexp)
4055 (if (match-beginning 1)
4056 (+ (org-get-string-indentation (match-string 1)) 1000)
4057 (1- (- (match-end 0) (match-beginning 0))))))
4058
4059 (defvar org-font-lock-keywords nil)
4060
4061 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4062 "Regular expression matching a property line.")
4063
4064 (defvar org-font-lock-hook nil
4065 "Functions to be called for special font lock stuff.")
4066
4067 (defun org-font-lock-hook (limit)
4068 (run-hook-with-args 'org-font-lock-hook limit))
4069
4070 (defun org-set-font-lock-defaults ()
4071 (let* ((em org-fontify-emphasized-text)
4072 (lk org-activate-links)
4073 (org-font-lock-extra-keywords
4074 (list
4075 ;; Call the hook
4076 '(org-font-lock-hook)
4077 ;; Headlines
4078 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4079 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4080 ;; Table lines
4081 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4082 (1 'org-table t))
4083 ;; Table internals
4084 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4085 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4086 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4087 ;; Drawers
4088 (list org-drawer-regexp '(0 'org-special-keyword t))
4089 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4090 ;; Properties
4091 (list org-property-re
4092 '(1 'org-special-keyword t)
4093 '(3 'org-property-value t))
4094 (if org-format-transports-properties-p
4095 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4096 ;; Links
4097 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4098 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4099 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4100 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4101 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4102 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4103 (if (memq 'footnote lk) '(org-activate-footnote-links
4104 (2 'org-footnote t)))
4105 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4106 '(org-hide-wide-columns (0 nil append))
4107 ;; TODO lines
4108 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4109 '(1 (org-get-todo-face 1) t))
4110 ;; DONE
4111 (if org-fontify-done-headline
4112 (list (concat "^[*]+ +\\<\\("
4113 (mapconcat 'regexp-quote org-done-keywords "\\|")
4114 "\\)\\(.*\\)")
4115 '(2 'org-headline-done t))
4116 nil)
4117 ;; Priorities
4118 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4119 ;; Tags
4120 '(org-font-lock-add-tag-faces)
4121 ;; Special keywords
4122 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4123 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4124 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4125 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4126 ;; Emphasis
4127 (if em
4128 (if (featurep 'xemacs)
4129 '(org-do-emphasis-faces (0 nil append))
4130 '(org-do-emphasis-faces)))
4131 ;; Checkboxes
4132 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4133 2 'bold prepend)
4134 (if org-provide-checkbox-statistics
4135 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4136 (0 (org-get-checkbox-statistics-face) t)))
4137 ;; Description list items
4138 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4139 2 'bold prepend)
4140 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4141 '(1 'org-archived prepend))
4142 ;; Specials
4143 '(org-do-latex-and-special-faces)
4144 ;; Code
4145 '(org-activate-code (1 'org-code t))
4146 ;; COMMENT
4147 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4148 "\\|" org-quote-string "\\)\\>")
4149 '(1 'org-special-keyword t))
4150 '("^#.*" (0 'font-lock-comment-face t))
4151 )))
4152 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4153 ;; Now set the full font-lock-keywords
4154 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4155 (org-set-local 'font-lock-defaults
4156 '(org-font-lock-keywords t nil nil backward-paragraph))
4157 (kill-local-variable 'font-lock-keywords) nil))
4158
4159 (defvar org-m nil)
4160 (defvar org-l nil)
4161 (defvar org-f nil)
4162 (defun org-get-level-face (n)
4163 "Get the right face for match N in font-lock matching of headlines."
4164 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4165 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4166 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4167 (cond
4168 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4169 ((eq n 2) org-f)
4170 (t (if org-level-color-stars-only nil org-f))))
4171
4172 (defun org-get-todo-face (kwd)
4173 "Get the right face for a TODO keyword KWD.
4174 If KWD is a number, get the corresponding match group."
4175 (if (numberp kwd) (setq kwd (match-string kwd)))
4176 (or (cdr (assoc kwd org-todo-keyword-faces))
4177 (and (member kwd org-done-keywords) 'org-done)
4178 'org-todo))
4179
4180 (defun org-font-lock-add-tag-faces (limit)
4181 "Add the special tag faces."
4182 (when (and org-tag-faces org-tags-special-faces-re)
4183 (while (re-search-forward org-tags-special-faces-re limit t)
4184 (add-text-properties (match-beginning 1) (match-end 1)
4185 (list 'face (org-get-tag-face 1)
4186 'font-lock-fontified t))
4187 (backward-char 1))))
4188
4189 (defun org-get-tag-face (kwd)
4190 "Get the right face for a TODO keyword KWD.
4191 If KWD is a number, get the corresponding match group."
4192 (if (numberp kwd) (setq kwd (match-string kwd)))
4193 (or (cdr (assoc kwd org-tag-faces))
4194 'org-tag))
4195
4196 (defun org-unfontify-region (beg end &optional maybe_loudly)
4197 "Remove fontification and activation overlays from links."
4198 (font-lock-default-unfontify-region beg end)
4199 (let* ((buffer-undo-list t)
4200 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4201 (inhibit-modification-hooks t)
4202 deactivate-mark buffer-file-name buffer-file-truename)
4203 (remove-text-properties beg end
4204 '(mouse-face t keymap t org-linked-text t
4205 invisible t intangible t))))
4206
4207 ;;;; Visibility cycling, including org-goto and indirect buffer
4208
4209 ;;; Cycling
4210
4211 (defvar org-cycle-global-status nil)
4212 (make-variable-buffer-local 'org-cycle-global-status)
4213 (defvar org-cycle-subtree-status nil)
4214 (make-variable-buffer-local 'org-cycle-subtree-status)
4215
4216 ;;;###autoload
4217 (defun org-cycle (&optional arg)
4218 "Visibility cycling for Org-mode.
4219
4220 - When this function is called with a prefix argument, rotate the entire
4221 buffer through 3 states (global cycling)
4222 1. OVERVIEW: Show only top-level headlines.
4223 2. CONTENTS: Show all headlines of all levels, but no body text.
4224 3. SHOW ALL: Show everything.
4225 When called with two C-u C-u prefixes, switch to the startup visibility,
4226 determined by the variable `org-startup-folded', and by any VISIBILITY
4227 properties in the buffer.
4228 When called with three C-u C-u C-u prefixed, show the entire buffer,
4229 including drawers.
4230
4231 - When point is at the beginning of a headline, rotate the subtree started
4232 by this line through 3 different states (local cycling)
4233 1. FOLDED: Only the main headline is shown.
4234 2. CHILDREN: The main headline and the direct children are shown.
4235 From this state, you can move to one of the children
4236 and zoom in further.
4237 3. SUBTREE: Show the entire subtree, including body text.
4238
4239 - When there is a numeric prefix, go up to a heading with level ARG, do
4240 a `show-subtree' and return to the previous cursor position. If ARG
4241 is negative, go up that many levels.
4242
4243 - When point is not at the beginning of a headline, execute the global
4244 binding for TAB, which is re-indenting the line. See the option
4245 `org-cycle-emulate-tab' for details.
4246
4247 - Special case: if point is at the beginning of the buffer and there is
4248 no headline in line 1, this function will act as if called with prefix arg.
4249 But only if also the variable `org-cycle-global-at-bob' is t."
4250 (interactive "P")
4251 (org-load-modules-maybe)
4252 (let* ((outline-regexp
4253 (if (and (org-mode-p) org-cycle-include-plain-lists)
4254 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4255 outline-regexp))
4256 (bob-special (and org-cycle-global-at-bob (bobp)
4257 (not (looking-at outline-regexp))))
4258 (org-cycle-hook
4259 (if bob-special
4260 (delq 'org-optimize-window-after-visibility-change
4261 (copy-sequence org-cycle-hook))
4262 org-cycle-hook))
4263 (pos (point)))
4264
4265 (if (or bob-special (equal arg '(4)))
4266 ;; special case: use global cycling
4267 (setq arg t))
4268
4269 (cond
4270
4271 ((equal arg '(16))
4272 (org-set-startup-visibility)
4273 (message "Startup visibility, plus VISIBILITY properties"))
4274
4275 ((equal arg '(64))
4276 (show-all)
4277 (message "Entire buffer visible, including drawers"))
4278
4279 ((org-at-table-p 'any)
4280 ;; Enter the table or move to the next field in the table
4281 (or (org-table-recognize-table.el)
4282 (progn
4283 (if arg (org-table-edit-field t)
4284 (org-table-justify-field-maybe)
4285 (call-interactively 'org-table-next-field)))))
4286
4287 ((eq arg t) ;; Global cycling
4288
4289 (cond
4290 ((and (eq last-command this-command)
4291 (eq org-cycle-global-status 'overview))
4292 ;; We just created the overview - now do table of contents
4293 ;; This can be slow in very large buffers, so indicate action
4294 (message "CONTENTS...")
4295 (org-content)
4296 (message "CONTENTS...done")
4297 (setq org-cycle-global-status 'contents)
4298 (run-hook-with-args 'org-cycle-hook 'contents))
4299
4300 ((and (eq last-command this-command)
4301 (eq org-cycle-global-status 'contents))
4302 ;; We just showed the table of contents - now show everything
4303 (show-all)
4304 (message "SHOW ALL")
4305 (setq org-cycle-global-status 'all)
4306 (run-hook-with-args 'org-cycle-hook 'all))
4307
4308 (t
4309 ;; Default action: go to overview
4310 (org-overview)
4311 (message "OVERVIEW")
4312 (setq org-cycle-global-status 'overview)
4313 (run-hook-with-args 'org-cycle-hook 'overview))))
4314
4315 ((and org-drawers org-drawer-regexp
4316 (save-excursion
4317 (beginning-of-line 1)
4318 (looking-at org-drawer-regexp)))
4319 ;; Toggle block visibility
4320 (org-flag-drawer
4321 (not (get-char-property (match-end 0) 'invisible))))
4322
4323 ((integerp arg)
4324 ;; Show-subtree, ARG levels up from here.
4325 (save-excursion
4326 (org-back-to-heading)
4327 (outline-up-heading (if (< arg 0) (- arg)
4328 (- (funcall outline-level) arg)))
4329 (org-show-subtree)))
4330
4331 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4332 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4333 ;; At a heading: rotate between three different views
4334 (org-back-to-heading)
4335 (let ((goal-column 0) eoh eol eos)
4336 ;; First, some boundaries
4337 (save-excursion
4338 (org-back-to-heading)
4339 (save-excursion
4340 (beginning-of-line 2)
4341 (while (and (not (eobp)) ;; this is like `next-line'
4342 (get-char-property (1- (point)) 'invisible))
4343 (beginning-of-line 2)) (setq eol (point)))
4344 (outline-end-of-heading) (setq eoh (point))
4345 (org-end-of-subtree t)
4346 (unless (eobp)
4347 (skip-chars-forward " \t\n")
4348 (beginning-of-line 1) ; in case this is an item
4349 )
4350 (setq eos (1- (point))))
4351 ;; Find out what to do next and set `this-command'
4352 (cond
4353 ((= eos eoh)
4354 ;; Nothing is hidden behind this heading
4355 (message "EMPTY ENTRY")
4356 (setq org-cycle-subtree-status nil)
4357 (save-excursion
4358 (goto-char eos)
4359 (outline-next-heading)
4360 (if (org-invisible-p) (org-flag-heading nil))))
4361 ((or (>= eol eos)
4362 (not (string-match "\\S-" (buffer-substring eol eos))))
4363 ;; Entire subtree is hidden in one line: open it
4364 (org-show-entry)
4365 (show-children)
4366 (message "CHILDREN")
4367 (save-excursion
4368 (goto-char eos)
4369 (outline-next-heading)
4370 (if (org-invisible-p) (org-flag-heading nil)))
4371 (setq org-cycle-subtree-status 'children)
4372 (run-hook-with-args 'org-cycle-hook 'children))
4373 ((and (eq last-command this-command)
4374 (eq org-cycle-subtree-status 'children))
4375 ;; We just showed the children, now show everything.
4376 (org-show-subtree)
4377 (message "SUBTREE")
4378 (setq org-cycle-subtree-status 'subtree)
4379 (run-hook-with-args 'org-cycle-hook 'subtree))
4380 (t
4381 ;; Default action: hide the subtree.
4382 (hide-subtree)
4383 (message "FOLDED")
4384 (setq org-cycle-subtree-status 'folded)
4385 (run-hook-with-args 'org-cycle-hook 'folded)))))
4386
4387 ;; TAB emulation and template completion
4388 (buffer-read-only (org-back-to-heading))
4389
4390 ((org-try-structure-completion))
4391
4392 ((org-try-cdlatex-tab))
4393
4394 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4395 (or (not (bolp))
4396 (not (looking-at outline-regexp))))
4397 (call-interactively (global-key-binding "\t")))
4398
4399 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4400 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4401 (or (and (eq org-cycle-emulate-tab 'white)
4402 (= (match-end 0) (point-at-eol)))
4403 (and (eq org-cycle-emulate-tab 'whitestart)
4404 (>= (match-end 0) pos))))
4405 t
4406 (eq org-cycle-emulate-tab t))
4407 (call-interactively (global-key-binding "\t")))
4408
4409 (t (save-excursion
4410 (org-back-to-heading)
4411 (org-cycle))))))
4412
4413 ;;;###autoload
4414 (defun org-global-cycle (&optional arg)
4415 "Cycle the global visibility. For details see `org-cycle'.
4416 With C-u prefix arg, switch to startup visibility.
4417 With a numeric prefix, show all headlines up to that level."
4418 (interactive "P")
4419 (let ((org-cycle-include-plain-lists
4420 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4421 (cond
4422 ((integerp arg)
4423 (show-all)
4424 (hide-sublevels arg)
4425 (setq org-cycle-global-status 'contents))
4426 ((equal arg '(4))
4427 (org-set-startup-visibility)
4428 (message "Startup visibility, plus VISIBILITY properties."))
4429 (t
4430 (org-cycle '(4))))))
4431
4432 (defun org-set-startup-visibility ()
4433 "Set the visibility required by startup options and properties."
4434 (cond
4435 ((eq org-startup-folded t)
4436 (org-cycle '(4)))
4437 ((eq org-startup-folded 'content)
4438 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4439 (org-cycle '(4)) (org-cycle '(4)))))
4440 (org-set-visibility-according-to-property 'no-cleanup)
4441 (org-cycle-hide-archived-subtrees 'all)
4442 (org-cycle-hide-drawers 'all)
4443 (org-cycle-show-empty-lines 'all))
4444
4445 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4446 "Switch subtree visibilities according to :VISIBILITY: property."
4447 (interactive)
4448 (let (org-show-entry-below state)
4449 (save-excursion
4450 (goto-char (point-min))
4451 (while (re-search-forward
4452 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4453 nil t)
4454 (setq state (match-string 1))
4455 (save-excursion
4456 (org-back-to-heading t)
4457 (hide-subtree)
4458 (org-reveal)
4459 (cond
4460 ((equal state '("fold" "folded"))
4461 (hide-subtree))
4462 ((equal state "children")
4463 (org-show-hidden-entry)
4464 (show-children))
4465 ((equal state "content")
4466 (save-excursion
4467 (save-restriction
4468 (org-narrow-to-subtree)
4469 (org-content))))
4470 ((member state '("all" "showall"))
4471 (show-subtree)))))
4472 (unless no-cleanup
4473 (org-cycle-hide-archived-subtrees 'all)
4474 (org-cycle-hide-drawers 'all)
4475 (org-cycle-show-empty-lines 'all)))))
4476
4477 (defun org-overview ()
4478 "Switch to overview mode, showing only top-level headlines.
4479 Really, this shows all headlines with level equal or greater than the level
4480 of the first headline in the buffer. This is important, because if the
4481 first headline is not level one, then (hide-sublevels 1) gives confusing
4482 results."
4483 (interactive)
4484 (let ((level (save-excursion
4485 (goto-char (point-min))
4486 (if (re-search-forward (concat "^" outline-regexp) nil t)
4487 (progn
4488 (goto-char (match-beginning 0))
4489 (funcall outline-level))))))
4490 (and level (hide-sublevels level))))
4491
4492 (defun org-content (&optional arg)
4493 "Show all headlines in the buffer, like a table of contents.
4494 With numerical argument N, show content up to level N."
4495 (interactive "P")
4496 (save-excursion
4497 ;; Visit all headings and show their offspring
4498 (and (integerp arg) (org-overview))
4499 (goto-char (point-max))
4500 (catch 'exit
4501 (while (and (progn (condition-case nil
4502 (outline-previous-visible-heading 1)
4503 (error (goto-char (point-min))))
4504 t)
4505 (looking-at outline-regexp))
4506 (if (integerp arg)
4507 (show-children (1- arg))
4508 (show-branches))
4509 (if (bobp) (throw 'exit nil))))))
4510
4511
4512 (defun org-optimize-window-after-visibility-change (state)
4513 "Adjust the window after a change in outline visibility.
4514 This function is the default value of the hook `org-cycle-hook'."
4515 (when (get-buffer-window (current-buffer))
4516 (cond
4517 ; ((eq state 'overview) (org-first-headline-recenter 1))
4518 ; ((eq state 'overview) (org-beginning-of-line))
4519 ((eq state 'content) nil)
4520 ((eq state 'all) nil)
4521 ((eq state 'folded) nil)
4522 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4523 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4524
4525 (defun org-compact-display-after-subtree-move ()
4526 "Show a compacter version of the tree of the entry's parent."
4527 (save-excursion
4528 (if (org-up-heading-safe)
4529 (progn
4530 (hide-subtree)
4531 (show-entry)
4532 (show-children)
4533 (org-cycle-show-empty-lines 'children)
4534 (org-cycle-hide-drawers 'children))
4535 (org-overview))))
4536
4537 (defun org-cycle-show-empty-lines (state)
4538 "Show empty lines above all visible headlines.
4539 The region to be covered depends on STATE when called through
4540 `org-cycle-hook'. Lisp program can use t for STATE to get the
4541 entire buffer covered. Note that an empty line is only shown if there
4542 are at least `org-cycle-separator-lines' empty lines before the headline."
4543 (when (> org-cycle-separator-lines 0)
4544 (save-excursion
4545 (let* ((n org-cycle-separator-lines)
4546 (re (cond
4547 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4548 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4549 (t (let ((ns (number-to-string (- n 2))))
4550 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4551 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4552 beg end)
4553 (cond
4554 ((memq state '(overview contents t))
4555 (setq beg (point-min) end (point-max)))
4556 ((memq state '(children folded))
4557 (setq beg (point) end (progn (org-end-of-subtree t t)
4558 (beginning-of-line 2)
4559 (point)))))
4560 (when beg
4561 (goto-char beg)
4562 (while (re-search-forward re end t)
4563 (if (not (get-char-property (match-end 1) 'invisible))
4564 (outline-flag-region
4565 (match-beginning 1) (match-end 1) nil)))))))
4566 ;; Never hide empty lines at the end of the file.
4567 (save-excursion
4568 (goto-char (point-max))
4569 (outline-previous-heading)
4570 (outline-end-of-heading)
4571 (if (and (looking-at "[ \t\n]+")
4572 (= (match-end 0) (point-max)))
4573 (outline-flag-region (point) (match-end 0) nil))))
4574
4575 (defun org-show-empty-lines-in-parent ()
4576 "Move to the parent and re-show empty lines before visible headlines."
4577 (save-excursion
4578 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4579 (org-cycle-show-empty-lines context))))
4580
4581 (defun org-cycle-hide-drawers (state)
4582 "Re-hide all drawers after a visibility state change."
4583 (when (and (org-mode-p)
4584 (not (memq state '(overview folded))))
4585 (save-excursion
4586 (let* ((globalp (memq state '(contents all)))
4587 (beg (if globalp (point-min) (point)))
4588 (end (if globalp (point-max) (org-end-of-subtree t))))
4589 (goto-char beg)
4590 (while (re-search-forward org-drawer-regexp end t)
4591 (org-flag-drawer t))))))
4592
4593 (defun org-flag-drawer (flag)
4594 (save-excursion
4595 (beginning-of-line 1)
4596 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4597 (let ((b (match-end 0))
4598 (outline-regexp org-outline-regexp))
4599 (if (re-search-forward
4600 "^[ \t]*:END:"
4601 (save-excursion (outline-next-heading) (point)) t)
4602 (outline-flag-region b (point-at-eol) flag)
4603 (error ":END: line missing"))))))
4604
4605 (defun org-subtree-end-visible-p ()
4606 "Is the end of the current subtree visible?"
4607 (pos-visible-in-window-p
4608 (save-excursion (org-end-of-subtree t) (point))))
4609
4610 (defun org-first-headline-recenter (&optional N)
4611 "Move cursor to the first headline and recenter the headline.
4612 Optional argument N means, put the headline into the Nth line of the window."
4613 (goto-char (point-min))
4614 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4615 (beginning-of-line)
4616 (recenter (prefix-numeric-value N))))
4617
4618 ;;; Org-goto
4619
4620 (defvar org-goto-window-configuration nil)
4621 (defvar org-goto-marker nil)
4622 (defvar org-goto-map
4623 (let ((map (make-sparse-keymap)))
4624 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4625 (while (setq cmd (pop cmds))
4626 (substitute-key-definition cmd cmd map global-map)))
4627 (suppress-keymap map)
4628 (org-defkey map "\C-m" 'org-goto-ret)
4629 (org-defkey map [(return)] 'org-goto-ret)
4630 (org-defkey map [(left)] 'org-goto-left)
4631 (org-defkey map [(right)] 'org-goto-right)
4632 (org-defkey map [(control ?g)] 'org-goto-quit)
4633 (org-defkey map "\C-i" 'org-cycle)
4634 (org-defkey map [(tab)] 'org-cycle)
4635 (org-defkey map [(down)] 'outline-next-visible-heading)
4636 (org-defkey map [(up)] 'outline-previous-visible-heading)
4637 (if org-goto-auto-isearch
4638 (if (fboundp 'define-key-after)
4639 (define-key-after map [t] 'org-goto-local-auto-isearch)
4640 nil)
4641 (org-defkey map "q" 'org-goto-quit)
4642 (org-defkey map "n" 'outline-next-visible-heading)
4643 (org-defkey map "p" 'outline-previous-visible-heading)
4644 (org-defkey map "f" 'outline-forward-same-level)
4645 (org-defkey map "b" 'outline-backward-same-level)
4646 (org-defkey map "u" 'outline-up-heading))
4647 (org-defkey map "/" 'org-occur)
4648 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4649 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4650 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4651 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4652 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4653 map))
4654
4655 (defconst org-goto-help
4656 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4657 RET=jump to location [Q]uit and return to previous location
4658 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4659
4660 (defvar org-goto-start-pos) ; dynamically scoped parameter
4661
4662 ;; FIXME: Docstring doe not mention both interfaces
4663 (defun org-goto (&optional alternative-interface)
4664 "Look up a different location in the current file, keeping current visibility.
4665
4666 When you want look-up or go to a different location in a document, the
4667 fastest way is often to fold the entire buffer and then dive into the tree.
4668 This method has the disadvantage, that the previous location will be folded,
4669 which may not be what you want.
4670
4671 This command works around this by showing a copy of the current buffer
4672 in an indirect buffer, in overview mode. You can dive into the tree in
4673 that copy, use org-occur and incremental search to find a location.
4674 When pressing RET or `Q', the command returns to the original buffer in
4675 which the visibility is still unchanged. After RET is will also jump to
4676 the location selected in the indirect buffer and expose the
4677 the headline hierarchy above."
4678 (interactive "P")
4679 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4680 (org-refile-use-outline-path t)
4681 (interface
4682 (if (not alternative-interface)
4683 org-goto-interface
4684 (if (eq org-goto-interface 'outline)
4685 'outline-path-completion
4686 'outline)))
4687 (org-goto-start-pos (point))
4688 (selected-point
4689 (if (eq interface 'outline)
4690 (car (org-get-location (current-buffer) org-goto-help))
4691 (nth 3 (org-refile-get-location "Goto: ")))))
4692 (if selected-point
4693 (progn
4694 (org-mark-ring-push org-goto-start-pos)
4695 (goto-char selected-point)
4696 (if (or (org-invisible-p) (org-invisible-p2))
4697 (org-show-context 'org-goto)))
4698 (message "Quit"))))
4699
4700 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4701 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4702 (defvar org-goto-local-auto-isearch-map) ; defined below
4703
4704 (defun org-get-location (buf help)
4705 "Let the user select a location in the Org-mode buffer BUF.
4706 This function uses a recursive edit. It returns the selected position
4707 or nil."
4708 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4709 (isearch-hide-immediately nil)
4710 (isearch-search-fun-function
4711 (lambda () 'org-goto-local-search-headings))
4712 (org-goto-selected-point org-goto-exit-command))
4713 (save-excursion
4714 (save-window-excursion
4715 (delete-other-windows)
4716 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4717 (switch-to-buffer
4718 (condition-case nil
4719 (make-indirect-buffer (current-buffer) "*org-goto*")
4720 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4721 (with-output-to-temp-buffer "*Help*"
4722 (princ help))
4723 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4724 (setq buffer-read-only nil)
4725 (let ((org-startup-truncated t)
4726 (org-startup-folded nil)
4727 (org-startup-align-all-tables nil))
4728 (org-mode)
4729 (org-overview))
4730 (setq buffer-read-only t)
4731 (if (and (boundp 'org-goto-start-pos)
4732 (integer-or-marker-p org-goto-start-pos))
4733 (let ((org-show-hierarchy-above t)
4734 (org-show-siblings t)
4735 (org-show-following-heading t))
4736 (goto-char org-goto-start-pos)
4737 (and (org-invisible-p) (org-show-context)))
4738 (goto-char (point-min)))
4739 (org-beginning-of-line)
4740 (message "Select location and press RET")
4741 (use-local-map org-goto-map)
4742 (recursive-edit)
4743 ))
4744 (kill-buffer "*org-goto*")
4745 (cons org-goto-selected-point org-goto-exit-command)))
4746
4747 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4748 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4749 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4750 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4751
4752 (defun org-goto-local-search-headings (string bound noerror)
4753 "Search and make sure that any matches are in headlines."
4754 (catch 'return
4755 (while (if isearch-forward
4756 (search-forward string bound noerror)
4757 (search-backward string bound noerror))
4758 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4759 (and (member :headline context)
4760 (not (member :tags context))))
4761 (throw 'return (point))))))
4762
4763 (defun org-goto-local-auto-isearch ()
4764 "Start isearch."
4765 (interactive)
4766 (goto-char (point-min))
4767 (let ((keys (this-command-keys)))
4768 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4769 (isearch-mode t)
4770 (isearch-process-search-char (string-to-char keys)))))
4771
4772 (defun org-goto-ret (&optional arg)
4773 "Finish `org-goto' by going to the new location."
4774 (interactive "P")
4775 (setq org-goto-selected-point (point)
4776 org-goto-exit-command 'return)
4777 (throw 'exit nil))
4778
4779 (defun org-goto-left ()
4780 "Finish `org-goto' by going to the new location."
4781 (interactive)
4782 (if (org-on-heading-p)
4783 (progn
4784 (beginning-of-line 1)
4785 (setq org-goto-selected-point (point)
4786 org-goto-exit-command 'left)
4787 (throw 'exit nil))
4788 (error "Not on a heading")))
4789
4790 (defun org-goto-right ()
4791 "Finish `org-goto' by going to the new location."
4792 (interactive)
4793 (if (org-on-heading-p)
4794 (progn
4795 (setq org-goto-selected-point (point)
4796 org-goto-exit-command 'right)
4797 (throw 'exit nil))
4798 (error "Not on a heading")))
4799
4800 (defun org-goto-quit ()
4801 "Finish `org-goto' without cursor motion."
4802 (interactive)
4803 (setq org-goto-selected-point nil)
4804 (setq org-goto-exit-command 'quit)
4805 (throw 'exit nil))
4806
4807 ;;; Indirect buffer display of subtrees
4808
4809 (defvar org-indirect-dedicated-frame nil
4810 "This is the frame being used for indirect tree display.")
4811 (defvar org-last-indirect-buffer nil)
4812
4813 (defun org-tree-to-indirect-buffer (&optional arg)
4814 "Create indirect buffer and narrow it to current subtree.
4815 With numerical prefix ARG, go up to this level and then take that tree.
4816 If ARG is negative, go up that many levels.
4817 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4818 indirect buffer previously made with this command, to avoid proliferation of
4819 indirect buffers. However, when you call the command with a `C-u' prefix, or
4820 when `org-indirect-buffer-display' is `new-frame', the last buffer
4821 is kept so that you can work with several indirect buffers at the same time.
4822 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4823 requests that a new frame be made for the new buffer, so that the dedicated
4824 frame is not changed."
4825 (interactive "P")
4826 (let ((cbuf (current-buffer))
4827 (cwin (selected-window))
4828 (pos (point))
4829 beg end level heading ibuf)
4830 (save-excursion
4831 (org-back-to-heading t)
4832 (when (numberp arg)
4833 (setq level (org-outline-level))
4834 (if (< arg 0) (setq arg (+ level arg)))
4835 (while (> (setq level (org-outline-level)) arg)
4836 (outline-up-heading 1 t)))
4837 (setq beg (point)
4838 heading (org-get-heading))
4839 (org-end-of-subtree t) (setq end (point)))
4840 (if (and (buffer-live-p org-last-indirect-buffer)
4841 (not (eq org-indirect-buffer-display 'new-frame))
4842 (not arg))
4843 (kill-buffer org-last-indirect-buffer))
4844 (setq ibuf (org-get-indirect-buffer cbuf)
4845 org-last-indirect-buffer ibuf)
4846 (cond
4847 ((or (eq org-indirect-buffer-display 'new-frame)
4848 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4849 (select-frame (make-frame))
4850 (delete-other-windows)
4851 (switch-to-buffer ibuf)
4852 (org-set-frame-title heading))
4853 ((eq org-indirect-buffer-display 'dedicated-frame)
4854 (raise-frame
4855 (select-frame (or (and org-indirect-dedicated-frame
4856 (frame-live-p org-indirect-dedicated-frame)
4857 org-indirect-dedicated-frame)
4858 (setq org-indirect-dedicated-frame (make-frame)))))
4859 (delete-other-windows)
4860 (switch-to-buffer ibuf)
4861 (org-set-frame-title (concat "Indirect: " heading)))
4862 ((eq org-indirect-buffer-display 'current-window)
4863 (switch-to-buffer ibuf))
4864 ((eq org-indirect-buffer-display 'other-window)
4865 (pop-to-buffer ibuf))
4866 (t (error "Invalid value.")))
4867 (if (featurep 'xemacs)
4868 (save-excursion (org-mode) (turn-on-font-lock)))
4869 (narrow-to-region beg end)
4870 (show-all)
4871 (goto-char pos)
4872 (and (window-live-p cwin) (select-window cwin))))
4873
4874 (defun org-get-indirect-buffer (&optional buffer)
4875 (setq buffer (or buffer (current-buffer)))
4876 (let ((n 1) (base (buffer-name buffer)) bname)
4877 (while (buffer-live-p
4878 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4879 (setq n (1+ n)))
4880 (condition-case nil
4881 (make-indirect-buffer buffer bname 'clone)
4882 (error (make-indirect-buffer buffer bname)))))
4883
4884 (defun org-set-frame-title (title)
4885 "Set the title of the current frame to the string TITLE."
4886 ;; FIXME: how to name a single frame in XEmacs???
4887 (unless (featurep 'xemacs)
4888 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4889
4890 ;;;; Structure editing
4891
4892 ;;; Inserting headlines
4893
4894 (defun org-previous-line-empty-p ()
4895 (save-excursion
4896 (and (not (bobp))
4897 (or (beginning-of-line 0) t)
4898 (save-match-data
4899 (looking-at "[ \t]*$")))))
4900
4901 (defun org-insert-heading (&optional force-heading)
4902 "Insert a new heading or item with same depth at point.
4903 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4904 If point is at the beginning of a headline, insert a sibling before the
4905 current headline. If point is not at the beginning, do not split the line,
4906 but create the new headline after the current line."
4907 (interactive "P")
4908 (if (= (buffer-size) 0)
4909 (insert "\n* ")
4910 (when (or force-heading (not (org-insert-item)))
4911 (let* ((empty-line-p nil)
4912 (head (save-excursion
4913 (condition-case nil
4914 (progn
4915 (org-back-to-heading)
4916 (setq empty-line-p (org-previous-line-empty-p))
4917 (match-string 0))
4918 (error "*"))))
4919 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
4920 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
4921 pos hide-previous previous-pos)
4922 (cond
4923 ((and (org-on-heading-p) (bolp)
4924 (or (bobp)
4925 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4926 ;; insert before the current line
4927 (open-line (if blank 2 1)))
4928 ((and (bolp)
4929 (or (bobp)
4930 (save-excursion
4931 (backward-char 1) (not (org-invisible-p)))))
4932 ;; insert right here
4933 nil)
4934 (t
4935 ;; somewhere in the line
4936 (save-excursion
4937 (setq previous-pos (point-at-bol))
4938 (end-of-line)
4939 (setq hide-previous (org-invisible-p)))
4940 (and org-insert-heading-respect-content (org-show-subtree))
4941 (let ((split
4942 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4943 (save-excursion
4944 (let ((p (point)))
4945 (goto-char (point-at-bol))
4946 (and (looking-at org-complex-heading-regexp)
4947 (> p (match-beginning 4)))))))
4948 tags pos)
4949 (cond
4950 (org-insert-heading-respect-content
4951 (org-end-of-subtree nil t)
4952 (or (bolp) (newline))
4953 (or (org-previous-line-empty-p)
4954 (and blank (newline)))
4955 (open-line 1))
4956 ((org-on-heading-p)
4957 (when hide-previous
4958 (show-children)
4959 (org-show-entry))
4960 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4961 (setq tags (and (match-end 2) (match-string 2)))
4962 (and (match-end 1)
4963 (delete-region (match-beginning 1) (match-end 1)))
4964 (setq pos (point-at-bol))
4965 (or split (end-of-line 1))
4966 (delete-horizontal-space)
4967 (newline (if blank 2 1))
4968 (when tags
4969 (save-excursion
4970 (goto-char pos)
4971 (end-of-line 1)
4972 (insert " " tags)
4973 (org-set-tags nil 'align))))
4974 (t
4975 (or split (end-of-line 1))
4976 (newline (if blank 2 1)))))))
4977 (insert head) (just-one-space)
4978 (setq pos (point))
4979 (end-of-line 1)
4980 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4981 (when (and org-insert-heading-respect-content hide-previous)
4982 (save-excursion
4983 (goto-char previous-pos)
4984 (hide-subtree)))
4985 (run-hooks 'org-insert-heading-hook)))))
4986
4987 (defun org-get-heading (&optional no-tags)
4988 "Return the heading of the current entry, without the stars."
4989 (save-excursion
4990 (org-back-to-heading t)
4991 (if (looking-at
4992 (if no-tags
4993 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4994 "\\*+[ \t]+\\([^\r\n]*\\)"))
4995 (match-string 1) "")))
4996
4997 (defun org-heading-components ()
4998 "Return the components of the current heading.
4999 This is a list with the following elements:
5000 - the level as an integer
5001 - the reduced level, different if `org-odd-levels-only' is set.
5002 - the TODO keyword, or nil
5003 - the priority character, like ?A, or nil if no priority is given
5004 - the headline text itself, or the tags string if no headline text
5005 - the tags string, or nil."
5006 (save-excursion
5007 (org-back-to-heading t)
5008 (if (looking-at org-complex-heading-regexp)
5009 (list (length (match-string 1))
5010 (org-reduced-level (length (match-string 1)))
5011 (org-match-string-no-properties 2)
5012 (and (match-end 3) (aref (match-string 3) 2))
5013 (org-match-string-no-properties 4)
5014 (org-match-string-no-properties 5)))))
5015
5016 (defun org-insert-heading-after-current ()
5017 "Insert a new heading with same level as current, after current subtree."
5018 (interactive)
5019 (org-back-to-heading)
5020 (org-insert-heading)
5021 (org-move-subtree-down)
5022 (end-of-line 1))
5023
5024 (defun org-insert-heading-respect-content ()
5025 (interactive)
5026 (let ((org-insert-heading-respect-content t))
5027 (org-insert-heading t)))
5028
5029 (defun org-insert-todo-heading-respect-content (&optional force-state)
5030 (interactive "P")
5031 (let ((org-insert-heading-respect-content t))
5032 (org-insert-todo-heading force-state t)))
5033
5034 (defun org-insert-todo-heading (arg &optional force-heading)
5035 "Insert a new heading with the same level and TODO state as current heading.
5036 If the heading has no TODO state, or if the state is DONE, use the first
5037 state (TODO by default). Also with prefix arg, force first state."
5038 (interactive "P")
5039 (when (or force-heading (not (org-insert-item 'checkbox)))
5040 (org-insert-heading force-heading)
5041 (save-excursion
5042 (org-back-to-heading)
5043 (outline-previous-heading)
5044 (looking-at org-todo-line-regexp))
5045 (if (or arg
5046 (not (match-beginning 2))
5047 (member (match-string 2) org-done-keywords))
5048 (insert (car org-todo-keywords-1) " ")
5049 (insert (match-string 2) " "))
5050 (when org-provide-todo-statistics
5051 (org-update-parent-todo-statistics))))
5052
5053 (defun org-insert-subheading (arg)
5054 "Insert a new subheading and demote it.
5055 Works for outline headings and for plain lists alike."
5056 (interactive "P")
5057 (org-insert-heading arg)
5058 (cond
5059 ((org-on-heading-p) (org-do-demote))
5060 ((org-at-item-p) (org-indent-item 1))))
5061
5062 (defun org-insert-todo-subheading (arg)
5063 "Insert a new subheading with TODO keyword or checkbox and demote it.
5064 Works for outline headings and for plain lists alike."
5065 (interactive "P")
5066 (org-insert-todo-heading arg)
5067 (cond
5068 ((org-on-heading-p) (org-do-demote))
5069 ((org-at-item-p) (org-indent-item 1))))
5070
5071 ;;; Promotion and Demotion
5072
5073 (defun org-promote-subtree ()
5074 "Promote the entire subtree.
5075 See also `org-promote'."
5076 (interactive)
5077 (save-excursion
5078 (org-map-tree 'org-promote))
5079 (org-fix-position-after-promote))
5080
5081 (defun org-demote-subtree ()
5082 "Demote the entire subtree. See `org-demote'.
5083 See also `org-promote'."
5084 (interactive)
5085 (save-excursion
5086 (org-map-tree 'org-demote))
5087 (org-fix-position-after-promote))
5088
5089
5090 (defun org-do-promote ()
5091 "Promote the current heading higher up the tree.
5092 If the region is active in `transient-mark-mode', promote all headings
5093 in the region."
5094 (interactive)
5095 (save-excursion
5096 (if (org-region-active-p)
5097 (org-map-region 'org-promote (region-beginning) (region-end))
5098 (org-promote)))
5099 (org-fix-position-after-promote))
5100
5101 (defun org-do-demote ()
5102 "Demote the current heading lower down the tree.
5103 If the region is active in `transient-mark-mode', demote all headings
5104 in the region."
5105 (interactive)
5106 (save-excursion
5107 (if (org-region-active-p)
5108 (org-map-region 'org-demote (region-beginning) (region-end))
5109 (org-demote)))
5110 (org-fix-position-after-promote))
5111
5112 (defun org-fix-position-after-promote ()
5113 "Make sure that after pro/demotion cursor position is right."
5114 (let ((pos (point)))
5115 (when (save-excursion
5116 (beginning-of-line 1)
5117 (looking-at org-todo-line-regexp)
5118 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5119 (cond ((eobp) (insert " "))
5120 ((eolp) (insert " "))
5121 ((equal (char-after) ?\ ) (forward-char 1))))))
5122
5123 (defun org-reduced-level (l)
5124 "Compute the effective level of a heading.
5125 This takes into account the setting of `org-odd-levels-only'."
5126 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5127
5128 (defun org-get-valid-level (level &optional change)
5129 "Rectify a level change under the influence of `org-odd-levels-only'
5130 LEVEL is a current level, CHANGE is by how much the level should be
5131 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5132 even level numbers will become the next higher odd number."
5133 (if org-odd-levels-only
5134 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5135 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5136 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5137 (max 1 (+ level change))))
5138
5139 (if (boundp 'define-obsolete-function-alias)
5140 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5141 (define-obsolete-function-alias 'org-get-legal-level
5142 'org-get-valid-level)
5143 (define-obsolete-function-alias 'org-get-legal-level
5144 'org-get-valid-level "23.1")))
5145
5146 (defun org-promote ()
5147 "Promote the current heading higher up the tree.
5148 If the region is active in `transient-mark-mode', promote all headings
5149 in the region."
5150 (org-back-to-heading t)
5151 (let* ((level (save-match-data (funcall outline-level)))
5152 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5153 (diff (abs (- level (length up-head) -1))))
5154 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5155 (replace-match up-head nil t)
5156 ;; Fixup tag positioning
5157 (and org-auto-align-tags (org-set-tags nil t))
5158 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5159
5160 (defun org-demote ()
5161 "Demote the current heading lower down the tree.
5162 If the region is active in `transient-mark-mode', demote all headings
5163 in the region."
5164 (org-back-to-heading t)
5165 (let* ((level (save-match-data (funcall outline-level)))
5166 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5167 (diff (abs (- level (length down-head) -1))))
5168 (replace-match down-head nil t)
5169 ;; Fixup tag positioning
5170 (and org-auto-align-tags (org-set-tags nil t))
5171 (if org-adapt-indentation (org-fixup-indentation diff))))
5172
5173 (defun org-map-tree (fun)
5174 "Call FUN for every heading underneath the current one."
5175 (org-back-to-heading)
5176 (let ((level (funcall outline-level)))
5177 (save-excursion
5178 (funcall fun)
5179 (while (and (progn
5180 (outline-next-heading)
5181 (> (funcall outline-level) level))
5182 (not (eobp)))
5183 (funcall fun)))))
5184
5185 (defun org-map-region (fun beg end)
5186 "Call FUN for every heading between BEG and END."
5187 (let ((org-ignore-region t))
5188 (save-excursion
5189 (setq end (copy-marker end))
5190 (goto-char beg)
5191 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5192 (< (point) end))
5193 (funcall fun))
5194 (while (and (progn
5195 (outline-next-heading)
5196 (< (point) end))
5197 (not (eobp)))
5198 (funcall fun)))))
5199
5200 (defun org-fixup-indentation (diff)
5201 "Change the indentation in the current entry by DIFF
5202 However, if any line in the current entry has no indentation, or if it
5203 would end up with no indentation after the change, nothing at all is done."
5204 (save-excursion
5205 (let ((end (save-excursion (outline-next-heading)
5206 (point-marker)))
5207 (prohibit (if (> diff 0)
5208 "^\\S-"
5209 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5210 col)
5211 (unless (save-excursion (end-of-line 1)
5212 (re-search-forward prohibit end t))
5213 (while (and (< (point) end)
5214 (re-search-forward "^[ \t]+" end t))
5215 (goto-char (match-end 0))
5216 (setq col (current-column))
5217 (if (< diff 0) (replace-match ""))
5218 (org-indent-to-column (+ diff col))))
5219 (move-marker end nil))))
5220
5221 (defun org-convert-to-odd-levels ()
5222 "Convert an org-mode file with all levels allowed to one with odd levels.
5223 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5224 level 5 etc."
5225 (interactive)
5226 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5227 (let ((org-odd-levels-only nil) n)
5228 (save-excursion
5229 (goto-char (point-min))
5230 (while (re-search-forward "^\\*\\*+ " nil t)
5231 (setq n (- (length (match-string 0)) 2))
5232 (while (>= (setq n (1- n)) 0)
5233 (org-demote))
5234 (end-of-line 1))))))
5235
5236
5237 (defun org-convert-to-oddeven-levels ()
5238 "Convert an org-mode file with only odd levels to one with odd and even levels.
5239 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5240 section with an even level, conversion would destroy the structure of the file. An error
5241 is signaled in this case."
5242 (interactive)
5243 (goto-char (point-min))
5244 ;; First check if there are no even levels
5245 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5246 (org-show-context t)
5247 (error "Not all levels are odd in this file. Conversion not possible."))
5248 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5249 (let ((org-odd-levels-only nil) n)
5250 (save-excursion
5251 (goto-char (point-min))
5252 (while (re-search-forward "^\\*\\*+ " nil t)
5253 (setq n (/ (1- (length (match-string 0))) 2))
5254 (while (>= (setq n (1- n)) 0)
5255 (org-promote))
5256 (end-of-line 1))))))
5257
5258 (defun org-tr-level (n)
5259 "Make N odd if required."
5260 (if org-odd-levels-only (1+ (/ n 2)) n))
5261
5262 ;;; Vertical tree motion, cutting and pasting of subtrees
5263
5264 (defun org-move-subtree-up (&optional arg)
5265 "Move the current subtree up past ARG headlines of the same level."
5266 (interactive "p")
5267 (org-move-subtree-down (- (prefix-numeric-value arg))))
5268
5269 (defun org-move-subtree-down (&optional arg)
5270 "Move the current subtree down past ARG headlines of the same level."
5271 (interactive "p")
5272 (setq arg (prefix-numeric-value arg))
5273 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5274 'outline-get-last-sibling))
5275 (ins-point (make-marker))
5276 (cnt (abs arg))
5277 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5278 ;; Select the tree
5279 (org-back-to-heading)
5280 (setq beg0 (point))
5281 (save-excursion
5282 (setq ne-beg (org-back-over-empty-lines))
5283 (setq beg (point)))
5284 (save-match-data
5285 (save-excursion (outline-end-of-heading)
5286 (setq folded (org-invisible-p)))
5287 (outline-end-of-subtree))
5288 (outline-next-heading)
5289 (setq ne-end (org-back-over-empty-lines))
5290 (setq end (point))
5291 (goto-char beg0)
5292 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5293 ;; include less whitespace
5294 (save-excursion
5295 (goto-char beg)
5296 (forward-line (- ne-beg ne-end))
5297 (setq beg (point))))
5298 ;; Find insertion point, with error handling
5299 (while (> cnt 0)
5300 (or (and (funcall movfunc) (looking-at outline-regexp))
5301 (progn (goto-char beg0)
5302 (error "Cannot move past superior level or buffer limit")))
5303 (setq cnt (1- cnt)))
5304 (if (> arg 0)
5305 ;; Moving forward - still need to move over subtree
5306 (progn (org-end-of-subtree t t)
5307 (save-excursion
5308 (org-back-over-empty-lines)
5309 (or (bolp) (newline)))))
5310 (setq ne-ins (org-back-over-empty-lines))
5311 (move-marker ins-point (point))
5312 (setq txt (buffer-substring beg end))
5313 (org-save-markers-in-region beg end)
5314 (delete-region beg end)
5315 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5316 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5317 (let ((bbb (point)))
5318 (insert-before-markers txt)
5319 (org-reinstall-markers-in-region bbb)
5320 (move-marker ins-point bbb))
5321 (or (bolp) (insert "\n"))
5322 (setq ins-end (point))
5323 (goto-char ins-point)
5324 (org-skip-whitespace)
5325 (when (and (< arg 0)
5326 (org-first-sibling-p)
5327 (> ne-ins ne-beg))
5328 ;; Move whitespace back to beginning
5329 (save-excursion
5330 (goto-char ins-end)
5331 (let ((kill-whole-line t))
5332 (kill-line (- ne-ins ne-beg)) (point)))
5333 (insert (make-string (- ne-ins ne-beg) ?\n)))
5334 (move-marker ins-point nil)
5335 (org-compact-display-after-subtree-move)
5336 (org-show-empty-lines-in-parent)
5337 (unless folded
5338 (org-show-entry)
5339 (show-children)
5340 (org-cycle-hide-drawers 'children))))
5341
5342 (defvar org-subtree-clip ""
5343 "Clipboard for cut and paste of subtrees.
5344 This is actually only a copy of the kill, because we use the normal kill
5345 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5346
5347 (defvar org-subtree-clip-folded nil
5348 "Was the last copied subtree folded?
5349 This is used to fold the tree back after pasting.")
5350
5351 (defun org-cut-subtree (&optional n)
5352 "Cut the current subtree into the clipboard.
5353 With prefix arg N, cut this many sequential subtrees.
5354 This is a short-hand for marking the subtree and then cutting it."
5355 (interactive "p")
5356 (org-copy-subtree n 'cut))
5357
5358 (defun org-copy-subtree (&optional n cut force-store-markers)
5359 "Cut the current subtree into the clipboard.
5360 With prefix arg N, cut this many sequential subtrees.
5361 This is a short-hand for marking the subtree and then copying it.
5362 If CUT is non-nil, actually cut the subtree.
5363 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5364 of some markers in the region, even if CUT is non-nil. This is
5365 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5366 (interactive "p")
5367 (let (beg end folded (beg0 (point)))
5368 (if (interactive-p)
5369 (org-back-to-heading nil) ; take what looks like a subtree
5370 (org-back-to-heading t)) ; take what is really there
5371 (org-back-over-empty-lines)
5372 (setq beg (point))
5373 (skip-chars-forward " \t\r\n")
5374 (save-match-data
5375 (save-excursion (outline-end-of-heading)
5376 (setq folded (org-invisible-p)))
5377 (condition-case nil
5378 (outline-forward-same-level (1- n))
5379 (error nil))
5380 (org-end-of-subtree t t))
5381 (org-back-over-empty-lines)
5382 (setq end (point))
5383 (goto-char beg0)
5384 (when (> end beg)
5385 (setq org-subtree-clip-folded folded)
5386 (when (or cut force-store-markers)
5387 (org-save-markers-in-region beg end))
5388 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5389 (setq org-subtree-clip (current-kill 0))
5390 (message "%s: Subtree(s) with %d characters"
5391 (if cut "Cut" "Copied")
5392 (length org-subtree-clip)))))
5393
5394 (defun org-paste-subtree (&optional level tree for-yank)
5395 "Paste the clipboard as a subtree, with modification of headline level.
5396 The entire subtree is promoted or demoted in order to match a new headline
5397 level.
5398
5399 If the cursor is at the beginning of a headline, the same level as
5400 that headline is used to paste the tree
5401
5402 If not, the new level is derived from the *visible* headings
5403 before and after the insertion point, and taken to be the inferior headline
5404 level of the two. So if the previous visible heading is level 3 and the
5405 next is level 4 (or vice versa), level 4 will be used for insertion.
5406 This makes sure that the subtree remains an independent subtree and does
5407 not swallow low level entries.
5408
5409 You can also force a different level, either by using a numeric prefix
5410 argument, or by inserting the heading marker by hand. For example, if the
5411 cursor is after \"*****\", then the tree will be shifted to level 5.
5412
5413 If optional TREE is given, use this text instead of the kill ring.
5414
5415 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5416 move back over whitespace before inserting, and move point to the end of
5417 the inserted text when done."
5418 (interactive "P")
5419 (unless (org-kill-is-subtree-p tree)
5420 (error "%s"
5421 (substitute-command-keys
5422 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5423 (let* ((visp (not (org-invisible-p)))
5424 (txt (or tree (and kill-ring (current-kill 0))))
5425 (^re (concat "^\\(" outline-regexp "\\)"))
5426 (re (concat "\\(" outline-regexp "\\)"))
5427 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5428
5429 (old-level (if (string-match ^re txt)
5430 (- (match-end 0) (match-beginning 0) 1)
5431 -1))
5432 (force-level (cond (level (prefix-numeric-value level))
5433 ((and (looking-at "[ \t]*$")
5434 (string-match
5435 ^re_ (buffer-substring
5436 (point-at-bol) (point))))
5437 (- (match-end 1) (match-beginning 1)))
5438 ((and (bolp)
5439 (looking-at org-outline-regexp))
5440 (- (match-end 0) (point) 1))
5441 (t nil)))
5442 (previous-level (save-excursion
5443 (condition-case nil
5444 (progn
5445 (outline-previous-visible-heading 1)
5446 (if (looking-at re)
5447 (- (match-end 0) (match-beginning 0) 1)
5448 1))
5449 (error 1))))
5450 (next-level (save-excursion
5451 (condition-case nil
5452 (progn
5453 (or (looking-at outline-regexp)
5454 (outline-next-visible-heading 1))
5455 (if (looking-at re)
5456 (- (match-end 0) (match-beginning 0) 1)
5457 1))
5458 (error 1))))
5459 (new-level (or force-level (max previous-level next-level)))
5460 (shift (if (or (= old-level -1)
5461 (= new-level -1)
5462 (= old-level new-level))
5463 0
5464 (- new-level old-level)))
5465 (delta (if (> shift 0) -1 1))
5466 (func (if (> shift 0) 'org-demote 'org-promote))
5467 (org-odd-levels-only nil)
5468 beg end newend)
5469 ;; Remove the forced level indicator
5470 (if force-level
5471 (delete-region (point-at-bol) (point)))
5472 ;; Paste
5473 (beginning-of-line 1)
5474 (unless for-yank (org-back-over-empty-lines))
5475 (setq beg (point))
5476 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5477 (insert-before-markers txt)
5478 (unless (string-match "\n\\'" txt) (insert "\n"))
5479 (setq newend (point))
5480 (org-reinstall-markers-in-region beg)
5481 (setq end (point))
5482 (goto-char beg)
5483 (skip-chars-forward " \t\n\r")
5484 (setq beg (point))
5485 (if (and (org-invisible-p) visp)
5486 (save-excursion (outline-show-heading)))
5487 ;; Shift if necessary
5488 (unless (= shift 0)
5489 (save-restriction
5490 (narrow-to-region beg end)
5491 (while (not (= shift 0))
5492 (org-map-region func (point-min) (point-max))
5493 (setq shift (+ delta shift)))
5494 (goto-char (point-min))
5495 (setq newend (point-max))))
5496 (when (or (interactive-p) for-yank)
5497 (message "Clipboard pasted as level %d subtree" new-level))
5498 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5499 kill-ring
5500 (eq org-subtree-clip (current-kill 0))
5501 org-subtree-clip-folded)
5502 ;; The tree was folded before it was killed/copied
5503 (hide-subtree))
5504 (and for-yank (goto-char newend))))
5505
5506 (defun org-kill-is-subtree-p (&optional txt)
5507 "Check if the current kill is an outline subtree, or a set of trees.
5508 Returns nil if kill does not start with a headline, or if the first
5509 headline level is not the largest headline level in the tree.
5510 So this will actually accept several entries of equal levels as well,
5511 which is OK for `org-paste-subtree'.
5512 If optional TXT is given, check this string instead of the current kill."
5513 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5514 (start-level (and kill
5515 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5516 org-outline-regexp "\\)")
5517 kill)
5518 (- (match-end 2) (match-beginning 2) 1)))
5519 (re (concat "^" org-outline-regexp))
5520 (start (1+ (or (match-beginning 2) -1))))
5521 (if (not start-level)
5522 (progn
5523 nil) ;; does not even start with a heading
5524 (catch 'exit
5525 (while (setq start (string-match re kill (1+ start)))
5526 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5527 (throw 'exit nil)))
5528 t))))
5529
5530 (defvar org-markers-to-move nil
5531 "Markers that should be moved with a cut-and-paste operation.
5532 Those markers are stored together with their positions relative to
5533 the start of the region.")
5534
5535 (defun org-save-markers-in-region (beg end)
5536 "Check markers in region.
5537 If these markers are between BEG and END, record their position relative
5538 to BEG, so that after moving the block of text, we can put the markers back
5539 into place.
5540 This function gets called just before an entry or tree gets cut from the
5541 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5542 called immediately, to move the markers with the entries."
5543 (setq org-markers-to-move nil)
5544 (when (featurep 'org-clock)
5545 (org-clock-save-markers-for-cut-and-paste beg end))
5546 (when (featurep 'org-agenda)
5547 (org-agenda-save-markers-for-cut-and-paste beg end)))
5548
5549 (defun org-check-and-save-marker (marker beg end)
5550 "Check if MARKER is between BEG and END.
5551 If yes, remember the marker and the distance to BEG."
5552 (when (and (marker-buffer marker)
5553 (equal (marker-buffer marker) (current-buffer)))
5554 (if (and (>= marker beg) (< marker end))
5555 (push (cons marker (- marker beg)) org-markers-to-move))))
5556
5557 (defun org-reinstall-markers-in-region (beg)
5558 "Move all remembered markers to their position relative to BEG."
5559 (mapc (lambda (x)
5560 (move-marker (car x) (+ beg (cdr x))))
5561 org-markers-to-move)
5562 (setq org-markers-to-move nil))
5563
5564 (defun org-narrow-to-subtree ()
5565 "Narrow buffer to the current subtree."
5566 (interactive)
5567 (save-excursion
5568 (save-match-data
5569 (narrow-to-region
5570 (progn (org-back-to-heading) (point))
5571 (progn (org-end-of-subtree t) (point))))))
5572
5573
5574 ;;; Outline Sorting
5575
5576 (defun org-sort (with-case)
5577 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5578 Optional argument WITH-CASE means sort case-sensitively."
5579 (interactive "P")
5580 (if (org-at-table-p)
5581 (org-call-with-arg 'org-table-sort-lines with-case)
5582 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5583
5584 (defun org-sort-remove-invisible (s)
5585 (remove-text-properties 0 (length s) org-rm-props s)
5586 (while (string-match org-bracket-link-regexp s)
5587 (setq s (replace-match (if (match-end 2)
5588 (match-string 3 s)
5589 (match-string 1 s)) t t s)))
5590 s)
5591
5592 (defvar org-priority-regexp) ; defined later in the file
5593
5594 (defun org-sort-entries-or-items
5595 (&optional with-case sorting-type getkey-func compare-func property)
5596 "Sort entries on a certain level of an outline tree.
5597 If there is an active region, the entries in the region are sorted.
5598 Else, if the cursor is before the first entry, sort the top-level items.
5599 Else, the children of the entry at point are sorted.
5600
5601 Sorting can be alphabetically, numerically, and by date/time as given by
5602 the first time stamp in the entry. The command prompts for the sorting
5603 type unless it has been given to the function through the SORTING-TYPE
5604 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5605 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5606 called with point at the beginning of the record. It must return either
5607 a string or a number that should serve as the sorting key for that record.
5608
5609 Comparing entries ignores case by default. However, with an optional argument
5610 WITH-CASE, the sorting considers case as well."
5611 (interactive "P")
5612 (let ((case-func (if with-case 'identity 'downcase))
5613 start beg end stars re re2
5614 txt what tmp plain-list-p)
5615 ;; Find beginning and end of region to sort
5616 (cond
5617 ((org-region-active-p)
5618 ;; we will sort the region
5619 (setq end (region-end)
5620 what "region")
5621 (goto-char (region-beginning))
5622 (if (not (org-on-heading-p)) (outline-next-heading))
5623 (setq start (point)))
5624 ((org-at-item-p)
5625 ;; we will sort this plain list
5626 (org-beginning-of-item-list) (setq start (point))
5627 (org-end-of-item-list) (setq end (point))
5628 (goto-char start)
5629 (setq plain-list-p t
5630 what "plain list"))
5631 ((or (org-on-heading-p)
5632 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5633 ;; we will sort the children of the current headline
5634 (org-back-to-heading)
5635 (setq start (point)
5636 end (progn (org-end-of-subtree t t)
5637 (org-back-over-empty-lines)
5638 (point))
5639 what "children")
5640 (goto-char start)
5641 (show-subtree)
5642 (outline-next-heading))
5643 (t
5644 ;; we will sort the top-level entries in this file
5645 (goto-char (point-min))
5646 (or (org-on-heading-p) (outline-next-heading))
5647 (setq start (point) end (point-max) what "top-level")
5648 (goto-char start)
5649 (show-all)))
5650
5651 (setq beg (point))
5652 (if (>= beg end) (error "Nothing to sort"))
5653
5654 (unless plain-list-p
5655 (looking-at "\\(\\*+\\)")
5656 (setq stars (match-string 1)
5657 re (concat "^" (regexp-quote stars) " +")
5658 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5659 txt (buffer-substring beg end))
5660 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5661 (if (and (not (equal stars "*")) (string-match re2 txt))
5662 (error "Region to sort contains a level above the first entry")))
5663
5664 (unless sorting-type
5665 (message
5666 (if plain-list-p
5667 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5668 "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:")
5669 what)
5670 (setq sorting-type (read-char-exclusive))
5671
5672 (and (= (downcase sorting-type) ?f)
5673 (setq getkey-func
5674 (org-ido-completing-read "Sort using function: "
5675 obarray 'fboundp t nil nil))
5676 (setq getkey-func (intern getkey-func)))
5677
5678 (and (= (downcase sorting-type) ?r)
5679 (setq property
5680 (org-ido-completing-read "Property: "
5681 (mapcar 'list (org-buffer-property-keys t))
5682 nil t))))
5683
5684 (message "Sorting entries...")
5685
5686 (save-restriction
5687 (narrow-to-region start end)
5688
5689 (let ((dcst (downcase sorting-type))
5690 (now (current-time)))
5691 (sort-subr
5692 (/= dcst sorting-type)
5693 ;; This function moves to the beginning character of the "record" to
5694 ;; be sorted.
5695 (if plain-list-p
5696 (lambda nil
5697 (if (org-at-item-p) t (goto-char (point-max))))
5698 (lambda nil
5699 (if (re-search-forward re nil t)
5700 (goto-char (match-beginning 0))
5701 (goto-char (point-max)))))
5702 ;; This function moves to the last character of the "record" being
5703 ;; sorted.
5704 (if plain-list-p
5705 'org-end-of-item
5706 (lambda nil
5707 (save-match-data
5708 (condition-case nil
5709 (outline-forward-same-level 1)
5710 (error
5711 (goto-char (point-max)))))))
5712
5713 ;; This function returns the value that gets sorted against.
5714 (if plain-list-p
5715 (lambda nil
5716 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5717 (cond
5718 ((= dcst ?n)
5719 (string-to-number (buffer-substring (match-end 0)
5720 (point-at-eol))))
5721 ((= dcst ?a)
5722 (buffer-substring (match-end 0) (point-at-eol)))
5723 ((= dcst ?t)
5724 (if (re-search-forward org-ts-regexp
5725 (point-at-eol) t)
5726 (org-time-string-to-time (match-string 0))
5727 now))
5728 ((= dcst ?f)
5729 (if getkey-func
5730 (progn
5731 (setq tmp (funcall getkey-func))
5732 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5733 tmp)
5734 (error "Invalid key function `%s'" getkey-func)))
5735 (t (error "Invalid sorting type `%c'" sorting-type)))))
5736 (lambda nil
5737 (cond
5738 ((= dcst ?n)
5739 (if (looking-at org-complex-heading-regexp)
5740 (string-to-number (match-string 4))
5741 nil))
5742 ((= dcst ?a)
5743 (if (looking-at org-complex-heading-regexp)
5744 (funcall case-func (match-string 4))
5745 nil))
5746 ((= dcst ?t)
5747 (if (re-search-forward org-ts-regexp
5748 (save-excursion
5749 (forward-line 2)
5750 (point)) t)
5751 (org-time-string-to-time (match-string 0))
5752 now))
5753 ((= dcst ?p)
5754 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5755 (string-to-char (match-string 2))
5756 org-default-priority))
5757 ((= dcst ?r)
5758 (or (org-entry-get nil property) ""))
5759 ((= dcst ?o)
5760 (if (looking-at org-complex-heading-regexp)
5761 (- 9999 (length (member (match-string 2)
5762 org-todo-keywords-1)))))
5763 ((= dcst ?f)
5764 (if getkey-func
5765 (progn
5766 (setq tmp (funcall getkey-func))
5767 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5768 tmp)
5769 (error "Invalid key function `%s'" getkey-func)))
5770 (t (error "Invalid sorting type `%c'" sorting-type)))))
5771 nil
5772 (cond
5773 ((= dcst ?a) 'string<)
5774 ((= dcst ?t) 'time-less-p)
5775 ((= dcst ?f) compare-func)
5776 (t nil)))))
5777 (message "Sorting entries...done")))
5778
5779 (defun org-do-sort (table what &optional with-case sorting-type)
5780 "Sort TABLE of WHAT according to SORTING-TYPE.
5781 The user will be prompted for the SORTING-TYPE if the call to this
5782 function does not specify it. WHAT is only for the prompt, to indicate
5783 what is being sorted. The sorting key will be extracted from
5784 the car of the elements of the table.
5785 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5786 (unless sorting-type
5787 (message
5788 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5789 what)
5790 (setq sorting-type (read-char-exclusive)))
5791 (let ((dcst (downcase sorting-type))
5792 extractfun comparefun)
5793 ;; Define the appropriate functions
5794 (cond
5795 ((= dcst ?n)
5796 (setq extractfun 'string-to-number
5797 comparefun (if (= dcst sorting-type) '< '>)))
5798 ((= dcst ?a)
5799 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5800 (lambda(x) (downcase (org-sort-remove-invisible x))))
5801 comparefun (if (= dcst sorting-type)
5802 'string<
5803 (lambda (a b) (and (not (string< a b))
5804 (not (string= a b)))))))
5805 ((= dcst ?t)
5806 (setq extractfun
5807 (lambda (x)
5808 (if (string-match org-ts-regexp x)
5809 (time-to-seconds
5810 (org-time-string-to-time (match-string 0 x)))
5811 0))
5812 comparefun (if (= dcst sorting-type) '< '>)))
5813 (t (error "Invalid sorting type `%c'" sorting-type)))
5814
5815 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5816 table)
5817 (lambda (a b) (funcall comparefun (car a) (car b))))))
5818
5819 ;;; Editing source examples
5820
5821 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5822 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5823 (defvar org-edit-src-force-single-line nil)
5824 (defvar org-edit-src-from-org-mode nil)
5825 (defvar org-edit-src-picture nil)
5826
5827 (define-minor-mode org-exit-edit-mode
5828 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5829
5830 (defun org-edit-src-code ()
5831 "Edit the source code example at point.
5832 An indirect buffer is created, and that buffer is then narrowed to the
5833 example at point and switched to the correct language mode. When done,
5834 exit by killing the buffer with \\[org-edit-src-exit]."
5835 (interactive)
5836 (let ((line (org-current-line))
5837 (case-fold-search t)
5838 (msg (substitute-command-keys
5839 "Edit, then exit with C-c ' (C-c and single quote)"))
5840 (info (org-edit-src-find-region-and-lang))
5841 (org-mode-p (eq major-mode 'org-mode))
5842 beg end lang lang-f single lfmt)
5843 (if (not info)
5844 nil
5845 (setq beg (nth 0 info)
5846 end (nth 1 info)
5847 lang (nth 2 info)
5848 single (nth 3 info)
5849 lfmt (nth 4 info)
5850 lang-f (intern (concat lang "-mode")))
5851 (unless (functionp lang-f)
5852 (error "No such language mode: %s" lang-f))
5853 (goto-line line)
5854 (if (get-buffer "*Org Edit Src Example*")
5855 (kill-buffer "*Org Edit Src Example*"))
5856 (switch-to-buffer (make-indirect-buffer (current-buffer)
5857 "*Org Edit Src Example*"))
5858 (narrow-to-region beg end)
5859 (remove-text-properties beg end '(display nil invisible nil
5860 intangible nil))
5861 (let ((org-inhibit-startup t))
5862 (funcall lang-f))
5863 (set (make-local-variable 'org-edit-src-force-single-line) single)
5864 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5865 (when lfmt
5866 (set (make-local-variable 'org-coderef-label-format) lfmt))
5867 (when org-mode-p
5868 (goto-char (point-min))
5869 (while (re-search-forward "^," nil t)
5870 (replace-match "")))
5871 (goto-line line)
5872 (org-exit-edit-mode)
5873 (org-set-local 'header-line-format msg)
5874 (message "%s" msg)
5875 t)))
5876
5877 (defun org-edit-fixed-width-region ()
5878 "Edit the fixed-width ascii drawing at point.
5879 This must be a region where each line starts with a colon followed by
5880 a space character.
5881 An indirect buffer is created, and that buffer is then narrowed to the
5882 example at point and switched to artist-mode. When done,
5883 exit by killing the buffer with \\[org-edit-src-exit]."
5884 (interactive)
5885 (let ((line (org-current-line))
5886 (case-fold-search t)
5887 (msg (substitute-command-keys
5888 "Edit, then exit with C-c ' (C-c and single quote)"))
5889 (org-mode-p (eq major-mode 'org-mode))
5890 beg end)
5891 (beginning-of-line 1)
5892 (if (looking-at "[ \t]*[^:\n \t]")
5893 nil
5894 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5895 (setq beg (point) end beg)
5896 (save-excursion
5897 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5898 (setq beg (point-at-bol 2))
5899 (setq beg (point))))
5900 (save-excursion
5901 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5902 (setq end (1- (match-beginning 0)))
5903 (setq end (point))))
5904 (goto-line line))
5905 (if (get-buffer "*Org Edit Picture*")
5906 (kill-buffer "*Org Edit Picture*"))
5907 (switch-to-buffer (make-indirect-buffer (current-buffer)
5908 "*Org Edit Picture*"))
5909 (narrow-to-region beg end)
5910 (remove-text-properties beg end '(display nil invisible nil
5911 intangible nil))
5912 (when (fboundp 'font-lock-unfontify-region)
5913 (font-lock-unfontify-region (point-min) (point-max)))
5914 (cond
5915 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5916 (fundamental-mode)
5917 (artist-mode 1))
5918 (t (funcall org-edit-fixed-width-region-mode)))
5919 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5920 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5921 (set (make-local-variable 'org-edit-src-picture) t)
5922 (goto-char (point-min))
5923 (while (re-search-forward "^[ \t]*: ?" nil t)
5924 (replace-match ""))
5925 (goto-line line)
5926 (org-exit-edit-mode)
5927 (org-set-local 'header-line-format msg)
5928 (message "%s" msg)
5929 t)))
5930
5931
5932 (defun org-edit-src-find-region-and-lang ()
5933 "Find the region and language for a local edit.
5934 Return a list with beginning and end of the region, a string representing
5935 the language, a switch telling of the content should be in a single line."
5936 (let ((re-list
5937 (append
5938 org-edit-src-region-extra
5939 '(
5940 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5941 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5942 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5943 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5944 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5945 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5946 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5947 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5948 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5949 ("^#\\+html:" "\n" "html" single-line)
5950 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5951 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5952 ("^#\\+latex:" "\n" "latex" single-line)
5953 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5954 ("^#\\+ascii:" "\n" "ascii" single-line)
5955 )))
5956 (pos (point))
5957 re1 re2 single beg end lang lfmt match-re1)
5958 (catch 'exit
5959 (while (setq entry (pop re-list))
5960 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5961 single (nth 3 entry))
5962 (save-excursion
5963 (if (or (looking-at re1)
5964 (re-search-backward re1 nil t))
5965 (progn
5966 (setq match-re1 (match-string 0))
5967 (setq beg (match-end 0)
5968 lang (org-edit-src-get-lang lang)
5969 lfmt (org-edit-src-get-label-format match-re1))
5970 (if (and (re-search-forward re2 nil t)
5971 (>= (match-end 0) pos))
5972 (throw 'exit (list beg (match-beginning 0)
5973 lang single lfmt))))
5974 (if (or (looking-at re2)
5975 (re-search-forward re2 nil t))
5976 (progn
5977 (setq end (match-beginning 0))
5978 (if (and (re-search-backward re1 nil t)
5979 (<= (match-beginning 0) pos))
5980 (progn
5981 (setq lfmt (org-edit-src-get-label-format
5982 (match-string 0)))
5983 (throw 'exit
5984 (list (match-end 0) end
5985 (org-edit-src-get-lang lang)
5986 single lfmt))))))))))))
5987
5988 (defun org-edit-src-get-lang (lang)
5989 "Extract the src language."
5990 (let ((m (match-string 0)))
5991 (cond
5992 ((stringp lang) lang)
5993 ((integerp lang) (match-string lang))
5994 ((and (eq lang 'lang)
5995 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5996 (match-string 1 m))
5997 ((and (eq lang 'style)
5998 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5999 (match-string 1 m))
6000 (t "fundamental"))))
6001
6002 (defun org-edit-src-get-label-format (s)
6003 "Extract the label format."
6004 (save-match-data
6005 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6006 (match-string 1 s))))
6007
6008 (defun org-edit-src-exit ()
6009 "Exit special edit and protect problematic lines."
6010 (interactive)
6011 (unless (buffer-base-buffer (current-buffer))
6012 (error "This is not an indirect buffer, something is wrong..."))
6013 (unless (> (point-min) 1)
6014 (error "This buffer is not narrowed, something is wrong..."))
6015 (goto-char (point-min))
6016 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6017 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6018 (when (org-bound-and-true-p org-edit-src-force-single-line)
6019 (goto-char (point-min))
6020 (while (re-search-forward "\n" nil t)
6021 (replace-match " "))
6022 (goto-char (point-min))
6023 (if (looking-at "\\s-*") (replace-match " "))
6024 (if (re-search-forward "\\s-+\\'" nil t)
6025 (replace-match "")))
6026 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6027 (goto-char (point-min))
6028 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6029 (replace-match ",\\1"))
6030 (when font-lock-mode
6031 (font-lock-unfontify-region (point-min) (point-max)))
6032 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6033 (when (org-bound-and-true-p org-edit-src-picture)
6034 (untabify (point-min) (point-max))
6035 (goto-char (point-min))
6036 (while (re-search-forward "^" nil t)
6037 (replace-match ": "))
6038 (when font-lock-mode
6039 (font-lock-unfontify-region (point-min) (point-max)))
6040 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6041 (kill-buffer (current-buffer))
6042 (and (org-mode-p) (org-restart-font-lock)))
6043
6044
6045 ;;; The orgstruct minor mode
6046
6047 ;; Define a minor mode which can be used in other modes in order to
6048 ;; integrate the org-mode structure editing commands.
6049
6050 ;; This is really a hack, because the org-mode structure commands use
6051 ;; keys which normally belong to the major mode. Here is how it
6052 ;; works: The minor mode defines all the keys necessary to operate the
6053 ;; structure commands, but wraps the commands into a function which
6054 ;; tests if the cursor is currently at a headline or a plain list
6055 ;; item. If that is the case, the structure command is used,
6056 ;; temporarily setting many Org-mode variables like regular
6057 ;; expressions for filling etc. However, when any of those keys is
6058 ;; used at a different location, function uses `key-binding' to look
6059 ;; up if the key has an associated command in another currently active
6060 ;; keymap (minor modes, major mode, global), and executes that
6061 ;; command. There might be problems if any of the keys is otherwise
6062 ;; used as a prefix key.
6063
6064 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6065 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6066 ;; addresses this by checking explicitly for both bindings.
6067
6068 (defvar orgstruct-mode-map (make-sparse-keymap)
6069 "Keymap for the minor `orgstruct-mode'.")
6070
6071 (defvar org-local-vars nil
6072 "List of local variables, for use by `orgstruct-mode'")
6073
6074 ;;;###autoload
6075 (define-minor-mode orgstruct-mode
6076 "Toggle the minor more `orgstruct-mode'.
6077 This mode is for using Org-mode structure commands in other modes.
6078 The following key behave as if Org-mode was active, if the cursor
6079 is on a headline, or on a plain list item (both in the definition
6080 of Org-mode).
6081
6082 M-up Move entry/item up
6083 M-down Move entry/item down
6084 M-left Promote
6085 M-right Demote
6086 M-S-up Move entry/item up
6087 M-S-down Move entry/item down
6088 M-S-left Promote subtree
6089 M-S-right Demote subtree
6090 M-q Fill paragraph and items like in Org-mode
6091 C-c ^ Sort entries
6092 C-c - Cycle list bullet
6093 TAB Cycle item visibility
6094 M-RET Insert new heading/item
6095 S-M-RET Insert new TODO heading / Checkbox item
6096 C-c C-c Set tags / toggle checkbox"
6097 nil " OrgStruct" nil
6098 (org-load-modules-maybe)
6099 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6100
6101 ;;;###autoload
6102 (defun turn-on-orgstruct ()
6103 "Unconditionally turn on `orgstruct-mode'."
6104 (orgstruct-mode 1))
6105
6106 ;;;###autoload
6107 (defun turn-on-orgstruct++ ()
6108 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6109 In addition to setting orgstruct-mode, this also exports all indentation and
6110 autofilling variables from org-mode into the buffer. Note that turning
6111 off orgstruct-mode will *not* remove these additional settings."
6112 (orgstruct-mode 1)
6113 (let (var val)
6114 (mapc
6115 (lambda (x)
6116 (when (string-match
6117 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6118 (symbol-name (car x)))
6119 (setq var (car x) val (nth 1 x))
6120 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6121 org-local-vars)))
6122
6123 (defun orgstruct-error ()
6124 "Error when there is no default binding for a structure key."
6125 (interactive)
6126 (error "This key has no function outside structure elements"))
6127
6128 (defun orgstruct-setup ()
6129 "Setup orgstruct keymaps."
6130 (let ((nfunc 0)
6131 (bindings
6132 (list
6133 '([(meta up)] org-metaup)
6134 '([(meta down)] org-metadown)
6135 '([(meta left)] org-metaleft)
6136 '([(meta right)] org-metaright)
6137 '([(meta shift up)] org-shiftmetaup)
6138 '([(meta shift down)] org-shiftmetadown)
6139 '([(meta shift left)] org-shiftmetaleft)
6140 '([(meta shift right)] org-shiftmetaright)
6141 '([(shift up)] org-shiftup)
6142 '([(shift down)] org-shiftdown)
6143 '([(shift left)] org-shiftleft)
6144 '([(shift right)] org-shiftright)
6145 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6146 '("\M-q" fill-paragraph)
6147 '("\C-c^" org-sort)
6148 '("\C-c-" org-cycle-list-bullet)))
6149 elt key fun cmd)
6150 (while (setq elt (pop bindings))
6151 (setq nfunc (1+ nfunc))
6152 (setq key (org-key (car elt))
6153 fun (nth 1 elt)
6154 cmd (orgstruct-make-binding fun nfunc key))
6155 (org-defkey orgstruct-mode-map key cmd))
6156
6157 ;; Special treatment needed for TAB and RET
6158 (org-defkey orgstruct-mode-map [(tab)]
6159 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6160 (org-defkey orgstruct-mode-map "\C-i"
6161 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6162
6163 (org-defkey orgstruct-mode-map "\M-\C-m"
6164 (orgstruct-make-binding 'org-insert-heading 105
6165 "\M-\C-m" [(meta return)]))
6166 (org-defkey orgstruct-mode-map [(meta return)]
6167 (orgstruct-make-binding 'org-insert-heading 106
6168 [(meta return)] "\M-\C-m"))
6169
6170 (org-defkey orgstruct-mode-map [(shift meta return)]
6171 (orgstruct-make-binding 'org-insert-todo-heading 107
6172 [(meta return)] "\M-\C-m"))
6173
6174 (unless org-local-vars
6175 (setq org-local-vars (org-get-local-variables)))
6176
6177 t))
6178
6179 (defun orgstruct-make-binding (fun n &rest keys)
6180 "Create a function for binding in the structure minor mode.
6181 FUN is the command to call inside a table. N is used to create a unique
6182 command name. KEYS are keys that should be checked in for a command
6183 to execute outside of tables."
6184 (eval
6185 (list 'defun
6186 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6187 '(arg)
6188 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6189 "Outside of structure, run the binding of `"
6190 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6191 "'.")
6192 '(interactive "p")
6193 (list 'if
6194 '(org-context-p 'headline 'item)
6195 (list 'org-run-like-in-org-mode (list 'quote fun))
6196 (list 'let '(orgstruct-mode)
6197 (list 'call-interactively
6198 (append '(or)
6199 (mapcar (lambda (k)
6200 (list 'key-binding k))
6201 keys)
6202 '('orgstruct-error))))))))
6203
6204 (defun org-context-p (&rest contexts)
6205 "Check if local context is any of CONTEXTS.
6206 Possible values in the list of contexts are `table', `headline', and `item'."
6207 (let ((pos (point)))
6208 (goto-char (point-at-bol))
6209 (prog1 (or (and (memq 'table contexts)
6210 (looking-at "[ \t]*|"))
6211 (and (memq 'headline contexts)
6212 ;;????????? (looking-at "\\*+"))
6213 (looking-at outline-regexp))
6214 (and (memq 'item contexts)
6215 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6216 (goto-char pos))))
6217
6218 (defun org-get-local-variables ()
6219 "Return a list of all local variables in an org-mode buffer."
6220 (let (varlist)
6221 (with-current-buffer (get-buffer-create "*Org tmp*")
6222 (erase-buffer)
6223 (org-mode)
6224 (setq varlist (buffer-local-variables)))
6225 (kill-buffer "*Org tmp*")
6226 (delq nil
6227 (mapcar
6228 (lambda (x)
6229 (setq x
6230 (if (symbolp x)
6231 (list x)
6232 (list (car x) (list 'quote (cdr x)))))
6233 (if (string-match
6234 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6235 (symbol-name (car x)))
6236 x nil))
6237 varlist))))
6238
6239 ;;;###autoload
6240 (defun org-run-like-in-org-mode (cmd)
6241 (org-load-modules-maybe)
6242 (unless org-local-vars
6243 (setq org-local-vars (org-get-local-variables)))
6244 (eval (list 'let org-local-vars
6245 (list 'call-interactively (list 'quote cmd)))))
6246
6247 ;;;; Archiving
6248
6249 (defun org-get-category (&optional pos)
6250 "Get the category applying to position POS."
6251 (get-text-property (or pos (point)) 'org-category))
6252
6253 (defun org-refresh-category-properties ()
6254 "Refresh category text properties in the buffer."
6255 (let ((def-cat (cond
6256 ((null org-category)
6257 (if buffer-file-name
6258 (file-name-sans-extension
6259 (file-name-nondirectory buffer-file-name))
6260 "???"))
6261 ((symbolp org-category) (symbol-name org-category))
6262 (t org-category)))
6263 beg end cat pos optionp)
6264 (org-unmodified
6265 (save-excursion
6266 (save-restriction
6267 (widen)
6268 (goto-char (point-min))
6269 (put-text-property (point) (point-max) 'org-category def-cat)
6270 (while (re-search-forward
6271 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6272 (setq pos (match-end 0)
6273 optionp (equal (char-after (match-beginning 0)) ?#)
6274 cat (org-trim (match-string 2)))
6275 (if optionp
6276 (setq beg (point-at-bol) end (point-max))
6277 (org-back-to-heading t)
6278 (setq beg (point) end (org-end-of-subtree t t)))
6279 (put-text-property beg end 'org-category cat)
6280 (goto-char pos)))))))
6281
6282
6283 ;;;; Link Stuff
6284
6285 ;;; Link abbreviations
6286
6287 (defun org-link-expand-abbrev (link)
6288 "Apply replacements as defined in `org-link-abbrev-alist."
6289 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6290 (let* ((key (match-string 1 link))
6291 (as (or (assoc key org-link-abbrev-alist-local)
6292 (assoc key org-link-abbrev-alist)))
6293 (tag (and (match-end 2) (match-string 3 link)))
6294 rpl)
6295 (if (not as)
6296 link
6297 (setq rpl (cdr as))
6298 (cond
6299 ((symbolp rpl) (funcall rpl tag))
6300 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6301 ((string-match "%h" rpl)
6302 (replace-match (url-hexify-string (or tag "")) t t rpl))
6303 (t (concat rpl tag)))))
6304 link))
6305
6306 ;;; Storing and inserting links
6307
6308 (defvar org-insert-link-history nil
6309 "Minibuffer history for links inserted with `org-insert-link'.")
6310
6311 (defvar org-stored-links nil
6312 "Contains the links stored with `org-store-link'.")
6313
6314 (defvar org-store-link-plist nil
6315 "Plist with info about the most recently link created with `org-store-link'.")
6316
6317 (defvar org-link-protocols nil
6318 "Link protocols added to Org-mode using `org-add-link-type'.")
6319
6320 (defvar org-store-link-functions nil
6321 "List of functions that are called to create and store a link.
6322 Each function will be called in turn until one returns a non-nil
6323 value. Each function should check if it is responsible for creating
6324 this link (for example by looking at the major mode).
6325 If not, it must exit and return nil.
6326 If yes, it should return a non-nil value after a calling
6327 `org-store-link-props' with a list of properties and values.
6328 Special properties are:
6329
6330 :type The link prefix. like \"http\". This must be given.
6331 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6332 This is obligatory as well.
6333 :description Optional default description for the second pair
6334 of brackets in an Org-mode link. The user can still change
6335 this when inserting this link into an Org-mode buffer.
6336
6337 In addition to these, any additional properties can be specified
6338 and then used in remember templates.")
6339
6340 (defun org-add-link-type (type &optional follow export)
6341 "Add TYPE to the list of `org-link-types'.
6342 Re-compute all regular expressions depending on `org-link-types'
6343
6344 FOLLOW and EXPORT are two functions.
6345
6346 FOLLOW should take the link path as the single argument and do whatever
6347 is necessary to follow the link, for example find a file or display
6348 a mail message.
6349
6350 EXPORT should format the link path for export to one of the export formats.
6351 It should be a function accepting three arguments:
6352
6353 path the path of the link, the text after the prefix (like \"http:\")
6354 desc the description of the link, if any, nil if there was no description
6355 format the export format, a symbol like `html' or `latex'.
6356
6357 The function may use the FORMAT information to return different values
6358 depending on the format. The return value will be put literally into
6359 the exported file.
6360 Org-mode has a built-in default for exporting links. If you are happy with
6361 this default, there is no need to define an export function for the link
6362 type. For a simple example of an export function, see `org-bbdb.el'."
6363 (add-to-list 'org-link-types type t)
6364 (org-make-link-regexps)
6365 (if (assoc type org-link-protocols)
6366 (setcdr (assoc type org-link-protocols) (list follow export))
6367 (push (list type follow export) org-link-protocols)))
6368
6369 ;;;###autoload
6370 (defun org-store-link (arg)
6371 "\\<org-mode-map>Store an org-link to the current location.
6372 This link is added to `org-stored-links' and can later be inserted
6373 into an org-buffer with \\[org-insert-link].
6374
6375 For some link types, a prefix arg is interpreted:
6376 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6377 For file links, arg negates `org-context-in-file-links'."
6378 (interactive "P")
6379 (org-load-modules-maybe)
6380 (setq org-store-link-plist nil) ; reset
6381 (let (link cpltxt desc description search txt)
6382 (cond
6383
6384 ((run-hook-with-args-until-success 'org-store-link-functions)
6385 (setq link (plist-get org-store-link-plist :link)
6386 desc (or (plist-get org-store-link-plist :description) link)))
6387
6388 ((equal (buffer-name) "*Org Edit Src Example*")
6389 (let (label gc)
6390 (while (or (not label)
6391 (save-excursion
6392 (save-restriction
6393 (widen)
6394 (goto-char (point-min))
6395 (re-search-forward
6396 (regexp-quote (format org-coderef-label-format label))
6397 nil t))))
6398 (when label (message "Label exists already") (sit-for 2))
6399 (setq label (read-string "Code line label: " label)))
6400 (end-of-line 1)
6401 (setq link (format org-coderef-label-format label))
6402 (setq gc (- 79 (length link)))
6403 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6404 (insert link)
6405 (setq link (concat "(" label ")") desc nil)))
6406
6407 ((eq major-mode 'calendar-mode)
6408 (let ((cd (calendar-cursor-to-date)))
6409 (setq link
6410 (format-time-string
6411 (car org-time-stamp-formats)
6412 (apply 'encode-time
6413 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6414 nil nil nil))))
6415 (org-store-link-props :type "calendar" :date cd)))
6416
6417 ((eq major-mode 'w3-mode)
6418 (setq cpltxt (url-view-url t)
6419 link (org-make-link cpltxt))
6420 (org-store-link-props :type "w3" :url (url-view-url t)))
6421
6422 ((eq major-mode 'w3m-mode)
6423 (setq cpltxt (or w3m-current-title w3m-current-url)
6424 link (org-make-link w3m-current-url))
6425 (org-store-link-props :type "w3m" :url (url-view-url t)))
6426
6427 ((setq search (run-hook-with-args-until-success
6428 'org-create-file-search-functions))
6429 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6430 "::" search))
6431 (setq cpltxt (or description link)))
6432
6433 ((eq major-mode 'image-mode)
6434 (setq cpltxt (concat "file:"
6435 (abbreviate-file-name buffer-file-name))
6436 link (org-make-link cpltxt))
6437 (org-store-link-props :type "image" :file buffer-file-name))
6438
6439 ((eq major-mode 'dired-mode)
6440 ;; link to the file in the current line
6441 (setq cpltxt (concat "file:"
6442 (abbreviate-file-name
6443 (expand-file-name
6444 (dired-get-filename nil t))))
6445 link (org-make-link cpltxt)))
6446
6447 ((and buffer-file-name (org-mode-p))
6448 (cond
6449 ((org-in-regexp "<<\\(.*?\\)>>")
6450 (setq cpltxt
6451 (concat "file:"
6452 (abbreviate-file-name buffer-file-name)
6453 "::" (match-string 1))
6454 link (org-make-link cpltxt)))
6455 ((and (featurep 'org-id)
6456 (or (eq org-link-to-org-use-id t)
6457 (and (eq org-link-to-org-use-id 'create-if-interactive)
6458 (interactive-p))
6459 (and org-link-to-org-use-id
6460 (condition-case nil
6461 (org-entry-get nil "ID")
6462 (error nil)))))
6463 ;; We can make a link using the ID.
6464 (setq link (condition-case nil
6465 (prog1 (org-id-store-link)
6466 (setq desc (plist-get org-store-link-plist
6467 :description)))
6468 (error
6469 ;; probably before first headline, link to file only
6470 (concat "file:"
6471 (abbreviate-file-name buffer-file-name))))))
6472 (t
6473 ;; Just link to current headline
6474 (setq cpltxt (concat "file:"
6475 (abbreviate-file-name buffer-file-name)))
6476 ;; Add a context search string
6477 (when (org-xor org-context-in-file-links arg)
6478 (setq txt (cond
6479 ((org-on-heading-p) nil)
6480 ((org-region-active-p)
6481 (buffer-substring (region-beginning) (region-end)))
6482 (t nil)))
6483 (when (or (null txt) (string-match "\\S-" txt))
6484 (setq cpltxt
6485 (concat cpltxt "::"
6486 (condition-case nil
6487 (org-make-org-heading-search-string txt)
6488 (error "")))
6489 desc "NONE")))
6490 (if (string-match "::\\'" cpltxt)
6491 (setq cpltxt (substring cpltxt 0 -2)))
6492 (setq link (org-make-link cpltxt)))))
6493
6494 ((buffer-file-name (buffer-base-buffer))
6495 ;; Just link to this file here.
6496 (setq cpltxt (concat "file:"
6497 (abbreviate-file-name
6498 (buffer-file-name (buffer-base-buffer)))))
6499 ;; Add a context string
6500 (when (org-xor org-context-in-file-links arg)
6501 (setq txt (if (org-region-active-p)
6502 (buffer-substring (region-beginning) (region-end))
6503 (buffer-substring (point-at-bol) (point-at-eol))))
6504 ;; Only use search option if there is some text.
6505 (when (string-match "\\S-" txt)
6506 (setq cpltxt
6507 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6508 desc "NONE")))
6509 (setq link (org-make-link cpltxt)))
6510
6511 ((interactive-p)
6512 (error "Cannot link to a buffer which is not visiting a file"))
6513
6514 (t (setq link nil)))
6515
6516 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6517 (setq link (or link cpltxt)
6518 desc (or desc cpltxt))
6519 (if (equal desc "NONE") (setq desc nil))
6520
6521 (if (and (interactive-p) link)
6522 (progn
6523 (setq org-stored-links
6524 (cons (list link desc) org-stored-links))
6525 (message "Stored: %s" (or desc link)))
6526 (and link (org-make-link-string link desc)))))
6527
6528 (defun org-store-link-props (&rest plist)
6529 "Store link properties, extract names and addresses."
6530 (let (x adr)
6531 (when (setq x (plist-get plist :from))
6532 (setq adr (mail-extract-address-components x))
6533 (setq plist (plist-put plist :fromname (car adr)))
6534 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6535 (when (setq x (plist-get plist :to))
6536 (setq adr (mail-extract-address-components x))
6537 (setq plist (plist-put plist :toname (car adr)))
6538 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6539 (let ((from (plist-get plist :from))
6540 (to (plist-get plist :to)))
6541 (when (and from to org-from-is-user-regexp)
6542 (setq plist
6543 (plist-put plist :fromto
6544 (if (string-match org-from-is-user-regexp from)
6545 (concat "to %t")
6546 (concat "from %f"))))))
6547 (setq org-store-link-plist plist))
6548
6549 (defun org-add-link-props (&rest plist)
6550 "Add these properties to the link property list."
6551 (let (key value)
6552 (while plist
6553 (setq key (pop plist) value (pop plist))
6554 (setq org-store-link-plist
6555 (plist-put org-store-link-plist key value)))))
6556
6557 (defun org-email-link-description (&optional fmt)
6558 "Return the description part of an email link.
6559 This takes information from `org-store-link-plist' and formats it
6560 according to FMT (default from `org-email-link-description-format')."
6561 (setq fmt (or fmt org-email-link-description-format))
6562 (let* ((p org-store-link-plist)
6563 (to (plist-get p :toaddress))
6564 (from (plist-get p :fromaddress))
6565 (table
6566 (list
6567 (cons "%c" (plist-get p :fromto))
6568 (cons "%F" (plist-get p :from))
6569 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6570 (cons "%T" (plist-get p :to))
6571 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6572 (cons "%s" (plist-get p :subject))
6573 (cons "%m" (plist-get p :message-id)))))
6574 (when (string-match "%c" fmt)
6575 ;; Check if the user wrote this message
6576 (if (and org-from-is-user-regexp from to
6577 (save-match-data (string-match org-from-is-user-regexp from)))
6578 (setq fmt (replace-match "to %t" t t fmt))
6579 (setq fmt (replace-match "from %f" t t fmt))))
6580 (org-replace-escapes fmt table)))
6581
6582 (defun org-make-org-heading-search-string (&optional string heading)
6583 "Make search string for STRING or current headline."
6584 (interactive)
6585 (let ((s (or string (org-get-heading))))
6586 (unless (and string (not heading))
6587 ;; We are using a headline, clean up garbage in there.
6588 (if (string-match org-todo-regexp s)
6589 (setq s (replace-match "" t t s)))
6590 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6591 (setq s (replace-match "" t t s)))
6592 (setq s (org-trim s))
6593 (if (string-match (concat "^\\(" org-quote-string "\\|"
6594 org-comment-string "\\)") s)
6595 (setq s (replace-match "" t t s)))
6596 (while (string-match org-ts-regexp s)
6597 (setq s (replace-match "" t t s))))
6598 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6599 (setq s (replace-match " " t t s)))
6600 (or string (setq s (concat "*" s))) ; Add * for headlines
6601 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6602
6603 (defun org-make-link (&rest strings)
6604 "Concatenate STRINGS."
6605 (apply 'concat strings))
6606
6607 (defun org-make-link-string (link &optional description)
6608 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6609 (unless (string-match "\\S-" link)
6610 (error "Empty link"))
6611 (when (stringp description)
6612 ;; Remove brackets from the description, they are fatal.
6613 (while (string-match "\\[" description)
6614 (setq description (replace-match "{" t t description)))
6615 (while (string-match "\\]" description)
6616 (setq description (replace-match "}" t t description))))
6617 (when (equal (org-link-escape link) description)
6618 ;; No description needed, it is identical
6619 (setq description nil))
6620 (when (and (not description)
6621 (not (equal link (org-link-escape link))))
6622 (setq description (org-extract-attributes link)))
6623 (concat "[[" (org-link-escape link) "]"
6624 (if description (concat "[" description "]") "")
6625 "]"))
6626
6627 (defconst org-link-escape-chars
6628 '((?\ . "%20")
6629 (?\[ . "%5B")
6630 (?\] . "%5D")
6631 (?\340 . "%E0") ; `a
6632 (?\342 . "%E2") ; ^a
6633 (?\347 . "%E7") ; ,c
6634 (?\350 . "%E8") ; `e
6635 (?\351 . "%E9") ; 'e
6636 (?\352 . "%EA") ; ^e
6637 (?\356 . "%EE") ; ^i
6638 (?\364 . "%F4") ; ^o
6639 (?\371 . "%F9") ; `u
6640 (?\373 . "%FB") ; ^u
6641 (?\; . "%3B")
6642 (?? . "%3F")
6643 (?= . "%3D")
6644 (?+ . "%2B")
6645 )
6646 "Association list of escapes for some characters problematic in links.
6647 This is the list that is used for internal purposes.")
6648
6649 (defconst org-link-escape-chars-browser
6650 '((?\ . "%20")) ; 32 for the SPC char
6651 "Association list of escapes for some characters problematic in links.
6652 This is the list that is used before handing over to the browser.")
6653
6654 (defun org-link-escape (text &optional table)
6655 "Escape characters in TEXT that are problematic for links."
6656 (setq table (or table org-link-escape-chars))
6657 (when text
6658 (let ((re (mapconcat (lambda (x) (regexp-quote
6659 (char-to-string (car x))))
6660 table "\\|")))
6661 (while (string-match re text)
6662 (setq text
6663 (replace-match
6664 (cdr (assoc (string-to-char (match-string 0 text))
6665 table))
6666 t t text)))
6667 text)))
6668
6669 (defun org-link-unescape (text &optional table)
6670 "Reverse the action of `org-link-escape'."
6671 (setq table (or table org-link-escape-chars))
6672 (when text
6673 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6674 table "\\|")))
6675 (while (string-match re text)
6676 (setq text
6677 (replace-match
6678 (char-to-string (car (rassoc (match-string 0 text) table)))
6679 t t text)))
6680 text)))
6681
6682 (defun org-xor (a b)
6683 "Exclusive or."
6684 (if a (not b) b))
6685
6686 (defun org-fixup-message-id-for-http (s)
6687 "Replace special characters in a message id, so it can be used in an http query."
6688 (while (string-match "<" s)
6689 (setq s (replace-match "%3C" t t s)))
6690 (while (string-match ">" s)
6691 (setq s (replace-match "%3E" t t s)))
6692 (while (string-match "@" s)
6693 (setq s (replace-match "%40" t t s)))
6694 s)
6695
6696 ;;;###autoload
6697 (defun org-insert-link-global ()
6698 "Insert a link like Org-mode does.
6699 This command can be called in any mode to insert a link in Org-mode syntax."
6700 (interactive)
6701 (org-load-modules-maybe)
6702 (org-run-like-in-org-mode 'org-insert-link))
6703
6704 (defun org-insert-link (&optional complete-file link-location)
6705 "Insert a link. At the prompt, enter the link.
6706
6707 Completion can be used to insert any of the link protocol prefixes like
6708 http or ftp in use.
6709
6710 The history can be used to select a link previously stored with
6711 `org-store-link'. When the empty string is entered (i.e. if you just
6712 press RET at the prompt), the link defaults to the most recently
6713 stored link. As SPC triggers completion in the minibuffer, you need to
6714 use M-SPC or C-q SPC to force the insertion of a space character.
6715
6716 You will also be prompted for a description, and if one is given, it will
6717 be displayed in the buffer instead of the link.
6718
6719 If there is already a link at point, this command will allow you to edit link
6720 and description parts.
6721
6722 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6723 be selected using completion. The path to the file will be relative to the
6724 current directory if the file is in the current directory or a subdirectory.
6725 Otherwise, the link will be the absolute path as completed in the minibuffer
6726 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6727 option `org-link-file-path-type'.
6728
6729 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6730 the current directory or below.
6731
6732 With three \\[universal-argument] prefixes, negate the meaning of
6733 `org-keep-stored-link-after-insertion'.
6734
6735 If `org-make-link-description-function' is non-nil, this function will be
6736 called with the link target, and the result will be the default
6737 link description.
6738
6739 If the LINK-LOCATION parameter is non-nil, this value will be
6740 used as the link location instead of reading one interactively."
6741 (interactive "P")
6742 (let* ((wcf (current-window-configuration))
6743 (region (if (org-region-active-p)
6744 (buffer-substring (region-beginning) (region-end))))
6745 (remove (and region (list (region-beginning) (region-end))))
6746 (desc region)
6747 tmphist ; byte-compile incorrectly complains about this
6748 (link link-location)
6749 entry file)
6750 (cond
6751 (link-location) ; specified by arg, just use it.
6752 ((org-in-regexp org-bracket-link-regexp 1)
6753 ;; We do have a link at point, and we are going to edit it.
6754 (setq remove (list (match-beginning 0) (match-end 0)))
6755 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6756 (setq link (read-string "Link: "
6757 (org-link-unescape
6758 (org-match-string-no-properties 1)))))
6759 ((or (org-in-regexp org-angle-link-re)
6760 (org-in-regexp org-plain-link-re))
6761 ;; Convert to bracket link
6762 (setq remove (list (match-beginning 0) (match-end 0))
6763 link (read-string "Link: "
6764 (org-remove-angle-brackets (match-string 0)))))
6765 ((member complete-file '((4) (16)))
6766 ;; Completing read for file names.
6767 (setq file (read-file-name "File: "))
6768 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6769 (pwd1 (file-name-as-directory (abbreviate-file-name
6770 (expand-file-name ".")))))
6771 (cond
6772 ((equal complete-file '(16))
6773 (setq link (org-make-link
6774 "file:"
6775 (abbreviate-file-name (expand-file-name file)))))
6776 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6777 (setq link (org-make-link "file:" (match-string 1 file))))
6778 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6779 (expand-file-name file))
6780 (setq link (org-make-link
6781 "file:" (match-string 1 (expand-file-name file)))))
6782 (t (setq link (org-make-link "file:" file))))))
6783 (t
6784 ;; Read link, with completion for stored links.
6785 (with-output-to-temp-buffer "*Org Links*"
6786 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6787 (when org-stored-links
6788 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6789 (princ (mapconcat
6790 (lambda (x)
6791 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6792 (reverse org-stored-links) "\n"))))
6793 (let ((cw (selected-window)))
6794 (select-window (get-buffer-window "*Org Links*"))
6795 (setq truncate-lines t)
6796 (org-fit-window-to-buffer)
6797 (select-window cw))
6798 ;; Fake a link history, containing the stored links.
6799 (setq tmphist (append (mapcar 'car org-stored-links)
6800 org-insert-link-history))
6801 (unwind-protect
6802 (setq link
6803 (let ((org-completion-use-ido nil))
6804 (org-completing-read
6805 "Link: "
6806 (append
6807 (mapcar (lambda (x) (list (concat (car x) ":")))
6808 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6809 (mapcar (lambda (x) (list (concat x ":")))
6810 org-link-types))
6811 nil nil nil
6812 'tmphist
6813 (or (car (car org-stored-links))))))
6814 (set-window-configuration wcf)
6815 (kill-buffer "*Org Links*"))
6816 (setq entry (assoc link org-stored-links))
6817 (or entry (push link org-insert-link-history))
6818 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6819 (not org-keep-stored-link-after-insertion))
6820 (setq org-stored-links (delq (assoc link org-stored-links)
6821 org-stored-links)))
6822 (setq desc (or desc (nth 1 entry)))))
6823
6824 (if (string-match org-plain-link-re link)
6825 ;; URL-like link, normalize the use of angular brackets.
6826 (setq link (org-make-link (org-remove-angle-brackets link))))
6827
6828 ;; Check if we are linking to the current file with a search option
6829 ;; If yes, simplify the link by using only the search option.
6830 (when (and buffer-file-name
6831 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6832 (let* ((path (match-string 1 link))
6833 (case-fold-search nil)
6834 (search (match-string 2 link)))
6835 (save-match-data
6836 (if (equal (file-truename buffer-file-name) (file-truename path))
6837 ;; We are linking to this same file, with a search option
6838 (setq link search)))))
6839
6840 ;; Check if we can/should use a relative path. If yes, simplify the link
6841 (when (string-match "^file:\\(.*\\)" link)
6842 (let* ((path (match-string 1 link))
6843 (origpath path)
6844 (case-fold-search nil))
6845 (cond
6846 ((or (eq org-link-file-path-type 'absolute)
6847 (equal complete-file '(16)))
6848 (setq path (abbreviate-file-name (expand-file-name path))))
6849 ((eq org-link-file-path-type 'noabbrev)
6850 (setq path (expand-file-name path)))
6851 ((eq org-link-file-path-type 'relative)
6852 (setq path (file-relative-name path)))
6853 (t
6854 (save-match-data
6855 (if (string-match (concat "^" (regexp-quote
6856 (file-name-as-directory
6857 (expand-file-name "."))))
6858 (expand-file-name path))
6859 ;; We are linking a file with relative path name.
6860 (setq path (substring (expand-file-name path)
6861 (match-end 0)))
6862 (setq path (abbreviate-file-name (expand-file-name path)))))))
6863 (setq link (concat "file:" path))
6864 (if (equal desc origpath)
6865 (setq desc path))))
6866
6867 (if org-make-link-description-function
6868 (setq desc (funcall org-make-link-description-function link desc)))
6869
6870 (setq desc (read-string "Description: " desc))
6871 (unless (string-match "\\S-" desc) (setq desc nil))
6872 (if remove (apply 'delete-region remove))
6873 (insert (org-make-link-string link desc))))
6874
6875 (defun org-completing-read (&rest args)
6876 "Completing-read with SPACE being a normal character."
6877 (let ((minibuffer-local-completion-map
6878 (copy-keymap minibuffer-local-completion-map)))
6879 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6880 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
6881 (apply 'org-ido-completing-read args)))
6882
6883 (defun org-ido-completing-read (&rest args)
6884 "Completing-read using `ido-mode' speedups if available"
6885 (if (and org-completion-use-ido
6886 (fboundp 'ido-completing-read)
6887 (boundp 'ido-mode) ido-mode
6888 (listp (second args)))
6889 (apply 'ido-completing-read (concat (car args)) (cdr args))
6890 (apply 'completing-read args)))
6891
6892 (defun org-extract-attributes (s)
6893 "Extract the attributes cookie from a string and set as text property."
6894 (let (a attr (start 0) key value)
6895 (save-match-data
6896 (when (string-match "{{\\([^}]+\\)}}$" s)
6897 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6898 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6899 (setq key (match-string 1 a) value (match-string 2 a)
6900 start (match-end 0)
6901 attr (plist-put attr (intern key) value))))
6902 (org-add-props s nil 'org-attr attr))
6903 s))
6904
6905 (defun org-attributes-to-string (plist)
6906 "Format a property list into an HTML attribute list."
6907 (let ((s "") key value)
6908 (while plist
6909 (setq key (pop plist) value (pop plist))
6910 (and value
6911 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6912 s))
6913
6914 ;;; Opening/following a link
6915
6916 (defvar org-link-search-failed nil)
6917
6918 (defun org-next-link ()
6919 "Move forward to the next link.
6920 If the link is in hidden text, expose it."
6921 (interactive)
6922 (when (and org-link-search-failed (eq this-command last-command))
6923 (goto-char (point-min))
6924 (message "Link search wrapped back to beginning of buffer"))
6925 (setq org-link-search-failed nil)
6926 (let* ((pos (point))
6927 (ct (org-context))
6928 (a (assoc :link ct)))
6929 (if a (goto-char (nth 2 a)))
6930 (if (re-search-forward org-any-link-re nil t)
6931 (progn
6932 (goto-char (match-beginning 0))
6933 (if (org-invisible-p) (org-show-context)))
6934 (goto-char pos)
6935 (setq org-link-search-failed t)
6936 (error "No further link found"))))
6937
6938 (defun org-previous-link ()
6939 "Move backward to the previous link.
6940 If the link is in hidden text, expose it."
6941 (interactive)
6942 (when (and org-link-search-failed (eq this-command last-command))
6943 (goto-char (point-max))
6944 (message "Link search wrapped back to end of buffer"))
6945 (setq org-link-search-failed nil)
6946 (let* ((pos (point))
6947 (ct (org-context))
6948 (a (assoc :link ct)))
6949 (if a (goto-char (nth 1 a)))
6950 (if (re-search-backward org-any-link-re nil t)
6951 (progn
6952 (goto-char (match-beginning 0))
6953 (if (org-invisible-p) (org-show-context)))
6954 (goto-char pos)
6955 (setq org-link-search-failed t)
6956 (error "No further link found"))))
6957
6958 (defun org-translate-link (s)
6959 "Translate a link string if a translation function has been defined."
6960 (if (and org-link-translation-function
6961 (fboundp org-link-translation-function)
6962 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6963 (progn
6964 (setq s (funcall org-link-translation-function
6965 (match-string 1) (match-string 2)))
6966 (concat (car s) ":" (cdr s)))
6967 s))
6968
6969 (defun org-translate-link-from-planner (type path)
6970 "Translate a link from Emacs Planner syntax so that Org can follow it.
6971 This is still an experimental function, your mileage may vary."
6972 (cond
6973 ((member type '("http" "https" "news" "ftp"))
6974 ;; standard Internet links are the same.
6975 nil)
6976 ((and (equal type "irc") (string-match "^//" path))
6977 ;; Planner has two / at the beginning of an irc link, we have 1.
6978 ;; We should have zero, actually....
6979 (setq path (substring path 1)))
6980 ((and (equal type "lisp") (string-match "^/" path))
6981 ;; Planner has a slash, we do not.
6982 (setq type "elisp" path (substring path 1)))
6983 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6984 ;; A typical message link. Planner has the id after the fina slash,
6985 ;; we separate it with a hash mark
6986 (setq path (concat (match-string 1 path) "#"
6987 (org-remove-angle-brackets (match-string 2 path)))))
6988 )
6989 (cons type path))
6990
6991 (defun org-find-file-at-mouse (ev)
6992 "Open file link or URL at mouse."
6993 (interactive "e")
6994 (mouse-set-point ev)
6995 (org-open-at-point 'in-emacs))
6996
6997 (defun org-open-at-mouse (ev)
6998 "Open file link or URL at mouse."
6999 (interactive "e")
7000 (mouse-set-point ev)
7001 (if (eq major-mode 'org-agenda-mode)
7002 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7003 (org-open-at-point))
7004
7005 (defvar org-window-config-before-follow-link nil
7006 "The window configuration before following a link.
7007 This is saved in case the need arises to restore it.")
7008
7009 (defvar org-open-link-marker (make-marker)
7010 "Marker pointing to the location where `org-open-at-point; was called.")
7011
7012 ;;;###autoload
7013 (defun org-open-at-point-global ()
7014 "Follow a link like Org-mode does.
7015 This command can be called in any mode to follow a link that has
7016 Org-mode syntax."
7017 (interactive)
7018 (org-run-like-in-org-mode 'org-open-at-point))
7019
7020 ;;;###autoload
7021 (defun org-open-link-from-string (s &optional arg)
7022 "Open a link in the string S, as if it was in Org-mode."
7023 (interactive "sLink: \nP")
7024 (with-temp-buffer
7025 (let ((org-inhibit-startup t))
7026 (org-mode)
7027 (insert s)
7028 (goto-char (point-min))
7029 (org-open-at-point arg))))
7030
7031 (defun org-open-at-point (&optional in-emacs)
7032 "Open link at or after point.
7033 If there is no link at point, this function will search forward up to
7034 the end of the current subtree.
7035 Normally, files will be opened by an appropriate application. If the
7036 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7037 With a double prefix argument, try to open outside of Emacs, in the
7038 application the system uses for this file type."
7039 (interactive "P")
7040 (org-load-modules-maybe)
7041 (move-marker org-open-link-marker (point))
7042 (setq org-window-config-before-follow-link (current-window-configuration))
7043 (org-remove-occur-highlights nil nil t)
7044 (cond
7045 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7046 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7047 (org-footnote-action))
7048 (t
7049 (let (type path link line search (pos (point)))
7050 (catch 'match
7051 (save-excursion
7052 (skip-chars-forward "^]\n\r")
7053 (when (org-in-regexp org-bracket-link-regexp)
7054 (setq link (org-extract-attributes
7055 (org-link-unescape (org-match-string-no-properties 1))))
7056 (while (string-match " *\n *" link)
7057 (setq link (replace-match " " t t link)))
7058 (setq link (org-link-expand-abbrev link))
7059 (cond
7060 ((or (file-name-absolute-p link)
7061 (string-match "^\\.\\.?/" link))
7062 (setq type "file" path link))
7063 ((string-match org-link-re-with-space3 link)
7064 (setq type (match-string 1 link) path (match-string 2 link)))
7065 (t (setq type "thisfile" path link)))
7066 (throw 'match t)))
7067
7068 (when (get-text-property (point) 'org-linked-text)
7069 (setq type "thisfile"
7070 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7071 (1+ (point)) (point))
7072 path (buffer-substring
7073 (previous-single-property-change pos 'org-linked-text)
7074 (next-single-property-change pos 'org-linked-text)))
7075 (throw 'match t))
7076
7077 (save-excursion
7078 (when (or (org-in-regexp org-angle-link-re)
7079 (org-in-regexp org-plain-link-re))
7080 (setq type (match-string 1) path (match-string 2))
7081 (throw 'match t)))
7082 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7083 (setq type "tree-match"
7084 path (match-string 1))
7085 (throw 'match t))
7086 (save-excursion
7087 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7088 (setq type "tags"
7089 path (match-string 1))
7090 (while (string-match ":" path)
7091 (setq path (replace-match "+" t t path)))
7092 (throw 'match t))))
7093 (unless path
7094 (error "No link found"))
7095 ;; Remove any trailing spaces in path
7096 (if (string-match " +\\'" path)
7097 (setq path (replace-match "" t t path)))
7098 (if (and org-link-translation-function
7099 (fboundp org-link-translation-function))
7100 ;; Check if we need to translate the link
7101 (let ((tmp (funcall org-link-translation-function type path)))
7102 (setq type (car tmp) path (cdr tmp))))
7103
7104 (cond
7105
7106 ((assoc type org-link-protocols)
7107 (funcall (nth 1 (assoc type org-link-protocols)) path))
7108
7109 ((equal type "mailto")
7110 (let ((cmd (car org-link-mailto-program))
7111 (args (cdr org-link-mailto-program)) args1
7112 (address path) (subject "") a)
7113 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7114 (setq address (match-string 1 path)
7115 subject (org-link-escape (match-string 2 path))))
7116 (while args
7117 (cond
7118 ((not (stringp (car args))) (push (pop args) args1))
7119 (t (setq a (pop args))
7120 (if (string-match "%a" a)
7121 (setq a (replace-match address t t a)))
7122 (if (string-match "%s" a)
7123 (setq a (replace-match subject t t a)))
7124 (push a args1))))
7125 (apply cmd (nreverse args1))))
7126
7127 ((member type '("http" "https" "ftp" "news"))
7128 (browse-url (concat type ":" (org-link-escape
7129 path org-link-escape-chars-browser))))
7130
7131 ((member type '("message"))
7132 (browse-url (concat type ":" path)))
7133
7134 ((string= type "tags")
7135 (org-tags-view in-emacs path))
7136 ((string= type "thisfile")
7137 (if in-emacs
7138 (switch-to-buffer-other-window
7139 (org-get-buffer-for-internal-link (current-buffer)))
7140 (org-mark-ring-push))
7141 (let ((cmd `(org-link-search
7142 ,path
7143 ,(cond ((equal in-emacs '(4)) 'occur)
7144 ((equal in-emacs '(16)) 'org-occur)
7145 (t nil))
7146 ,pos)))
7147 (condition-case nil (eval cmd)
7148 (error (progn (widen) (eval cmd))))))
7149
7150 ((string= type "tree-match")
7151 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7152
7153 ((string= type "file")
7154 (if (string-match "::\\([0-9]+\\)\\'" path)
7155 (setq line (string-to-number (match-string 1 path))
7156 path (substring path 0 (match-beginning 0)))
7157 (if (string-match "::\\(.+\\)\\'" path)
7158 (setq search (match-string 1 path)
7159 path (substring path 0 (match-beginning 0)))))
7160 (if (string-match "[*?{]" (file-name-nondirectory path))
7161 (dired path)
7162 (org-open-file path in-emacs line search)))
7163
7164 ((string= type "news")
7165 (require 'org-gnus)
7166 (org-gnus-follow-link path))
7167
7168 ((string= type "shell")
7169 (let ((cmd path))
7170 (if (or (not org-confirm-shell-link-function)
7171 (funcall org-confirm-shell-link-function
7172 (format "Execute \"%s\" in shell? "
7173 (org-add-props cmd nil
7174 'face 'org-warning))))
7175 (progn
7176 (message "Executing %s" cmd)
7177 (shell-command cmd))
7178 (error "Abort"))))
7179
7180 ((string= type "elisp")
7181 (let ((cmd path))
7182 (if (or (not org-confirm-elisp-link-function)
7183 (funcall org-confirm-elisp-link-function
7184 (format "Execute \"%s\" as elisp? "
7185 (org-add-props cmd nil
7186 'face 'org-warning))))
7187 (message "%s => %s" cmd
7188 (if (equal (string-to-char cmd) ?\()
7189 (eval (read cmd))
7190 (call-interactively (read cmd))))
7191 (error "Abort"))))
7192
7193 (t
7194 (browse-url-at-point))))))
7195 (move-marker org-open-link-marker nil)
7196 (run-hook-with-args 'org-follow-link-hook))
7197
7198 ;;;; Time estimates
7199
7200 (defun org-get-effort (&optional pom)
7201 "Get the effort estimate for the current entry."
7202 (org-entry-get pom org-effort-property))
7203
7204 ;;; File search
7205
7206 (defvar org-create-file-search-functions nil
7207 "List of functions to construct the right search string for a file link.
7208 These functions are called in turn with point at the location to
7209 which the link should point.
7210
7211 A function in the hook should first test if it would like to
7212 handle this file type, for example by checking the major-mode or
7213 the file extension. If it decides not to handle this file, it
7214 should just return nil to give other functions a chance. If it
7215 does handle the file, it must return the search string to be used
7216 when following the link. The search string will be part of the
7217 file link, given after a double colon, and `org-open-at-point'
7218 will automatically search for it. If special measures must be
7219 taken to make the search successful, another function should be
7220 added to the companion hook `org-execute-file-search-functions',
7221 which see.
7222
7223 A function in this hook may also use `setq' to set the variable
7224 `description' to provide a suggestion for the descriptive text to
7225 be used for this link when it gets inserted into an Org-mode
7226 buffer with \\[org-insert-link].")
7227
7228 (defvar org-execute-file-search-functions nil
7229 "List of functions to execute a file search triggered by a link.
7230
7231 Functions added to this hook must accept a single argument, the
7232 search string that was part of the file link, the part after the
7233 double colon. The function must first check if it would like to
7234 handle this search, for example by checking the major-mode or the
7235 file extension. If it decides not to handle this search, it
7236 should just return nil to give other functions a chance. If it
7237 does handle the search, it must return a non-nil value to keep
7238 other functions from trying.
7239
7240 Each function can access the current prefix argument through the
7241 variable `current-prefix-argument'. Note that a single prefix is
7242 used to force opening a link in Emacs, so it may be good to only
7243 use a numeric or double prefix to guide the search function.
7244
7245 In case this is needed, a function in this hook can also restore
7246 the window configuration before `org-open-at-point' was called using:
7247
7248 (set-window-configuration org-window-config-before-follow-link)")
7249
7250 (defun org-link-search (s &optional type avoid-pos)
7251 "Search for a link search option.
7252 If S is surrounded by forward slashes, it is interpreted as a
7253 regular expression. In org-mode files, this will create an `org-occur'
7254 sparse tree. In ordinary files, `occur' will be used to list matches.
7255 If the current buffer is in `dired-mode', grep will be used to search
7256 in all files. If AVOID-POS is given, ignore matches near that position."
7257 (let ((case-fold-search t)
7258 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7259 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7260 (append '(("") (" ") ("\t") ("\n"))
7261 org-emphasis-alist)
7262 "\\|") "\\)"))
7263 (pos (point))
7264 (pre nil) (post nil)
7265 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7266 (cond
7267 ;; First check if there are any special
7268 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7269 ;; Now try the builtin stuff
7270 ((save-excursion
7271 (goto-char (point-min))
7272 (and
7273 (re-search-forward
7274 (concat "<<" (regexp-quote s0) ">>") nil t)
7275 (setq type 'dedicated
7276 pos (match-beginning 0))))
7277 ;; There is an exact target for this
7278 (goto-char pos))
7279 ((and (string-match "^(\\(.*\\))$" s0)
7280 (save-excursion
7281 (goto-char (point-min))
7282 (and
7283 (re-search-forward
7284 (concat "[^[]" (regexp-quote
7285 (format org-coderef-label-format
7286 (match-string 1 s0))))
7287 nil t)
7288 (setq type 'dedicated
7289 pos (1+ (match-beginning 0))))))
7290 ;; There is a coderef target for this
7291 (goto-char pos))
7292 ((string-match "^/\\(.*\\)/$" s)
7293 ;; A regular expression
7294 (cond
7295 ((org-mode-p)
7296 (org-occur (match-string 1 s)))
7297 ;;((eq major-mode 'dired-mode)
7298 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7299 (t (org-do-occur (match-string 1 s)))))
7300 (t
7301 ;; A normal search strings
7302 (when (equal (string-to-char s) ?*)
7303 ;; Anchor on headlines, post may include tags.
7304 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7305 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7306 s (substring s 1)))
7307 (remove-text-properties
7308 0 (length s)
7309 '(face nil mouse-face nil keymap nil fontified nil) s)
7310 ;; Make a series of regular expressions to find a match
7311 (setq words (org-split-string s "[ \n\r\t]+")
7312
7313 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7314 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7315 "\\)" markers)
7316 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7317 re2a (concat "[ \t\r\n]" re2a_)
7318 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7319 re4 (concat "[^a-zA-Z_]" re4_)
7320
7321 re1 (concat pre re2 post)
7322 re3 (concat pre (if pre re4_ re4) post)
7323 re5 (concat pre ".*" re4)
7324 re2 (concat pre re2)
7325 re2a (concat pre (if pre re2a_ re2a))
7326 re4 (concat pre (if pre re4_ re4))
7327 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7328 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7329 re5 "\\)"
7330 ))
7331 (cond
7332 ((eq type 'org-occur) (org-occur reall))
7333 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7334 (t (goto-char (point-min))
7335 (setq type 'fuzzy)
7336 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7337 (org-search-not-self 1 re1 nil t)
7338 (org-search-not-self 1 re2 nil t)
7339 (org-search-not-self 1 re2a nil t)
7340 (org-search-not-self 1 re3 nil t)
7341 (org-search-not-self 1 re4 nil t)
7342 (org-search-not-self 1 re5 nil t)
7343 )
7344 (goto-char (match-beginning 1))
7345 (goto-char pos)
7346 (error "No match")))))
7347 (t
7348 ;; Normal string-search
7349 (goto-char (point-min))
7350 (if (search-forward s nil t)
7351 (goto-char (match-beginning 0))
7352 (error "No match"))))
7353 (and (org-mode-p) (org-show-context 'link-search))
7354 type))
7355
7356 (defun org-search-not-self (group &rest args)
7357 "Execute `re-search-forward', but only accept matches that do not
7358 enclose the position of `org-open-link-marker'."
7359 (let ((m org-open-link-marker))
7360 (catch 'exit
7361 (while (apply 're-search-forward args)
7362 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7363 (goto-char (match-end group))
7364 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7365 (> (match-beginning 0) (marker-position m))
7366 (< (match-end 0) (marker-position m)))
7367 (save-match-data
7368 (or (not (org-in-regexp
7369 org-bracket-link-analytic-regexp 1))
7370 (not (match-end 4)) ; no description
7371 (and (<= (match-beginning 4) (point))
7372 (>= (match-end 4) (point))))))
7373 (throw 'exit (point))))))))
7374
7375 (defun org-get-buffer-for-internal-link (buffer)
7376 "Return a buffer to be used for displaying the link target of internal links."
7377 (cond
7378 ((not org-display-internal-link-with-indirect-buffer)
7379 buffer)
7380 ((string-match "(Clone)$" (buffer-name buffer))
7381 (message "Buffer is already a clone, not making another one")
7382 ;; we also do not modify visibility in this case
7383 buffer)
7384 (t ; make a new indirect buffer for displaying the link
7385 (let* ((bn (buffer-name buffer))
7386 (ibn (concat bn "(Clone)"))
7387 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7388 (with-current-buffer ib (org-overview))
7389 ib))))
7390
7391 (defun org-do-occur (regexp &optional cleanup)
7392 "Call the Emacs command `occur'.
7393 If CLEANUP is non-nil, remove the printout of the regular expression
7394 in the *Occur* buffer. This is useful if the regex is long and not useful
7395 to read."
7396 (occur regexp)
7397 (when cleanup
7398 (let ((cwin (selected-window)) win beg end)
7399 (when (setq win (get-buffer-window "*Occur*"))
7400 (select-window win))
7401 (goto-char (point-min))
7402 (when (re-search-forward "match[a-z]+" nil t)
7403 (setq beg (match-end 0))
7404 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7405 (setq end (1- (match-beginning 0)))))
7406 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7407 (goto-char (point-min))
7408 (select-window cwin))))
7409
7410 ;;; The mark ring for links jumps
7411
7412 (defvar org-mark-ring nil
7413 "Mark ring for positions before jumps in Org-mode.")
7414 (defvar org-mark-ring-last-goto nil
7415 "Last position in the mark ring used to go back.")
7416 ;; Fill and close the ring
7417 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7418 (loop for i from 1 to org-mark-ring-length do
7419 (push (make-marker) org-mark-ring))
7420 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7421 org-mark-ring)
7422
7423 (defun org-mark-ring-push (&optional pos buffer)
7424 "Put the current position or POS into the mark ring and rotate it."
7425 (interactive)
7426 (setq pos (or pos (point)))
7427 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7428 (move-marker (car org-mark-ring)
7429 (or pos (point))
7430 (or buffer (current-buffer)))
7431 (message "%s"
7432 (substitute-command-keys
7433 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7434
7435 (defun org-mark-ring-goto (&optional n)
7436 "Jump to the previous position in the mark ring.
7437 With prefix arg N, jump back that many stored positions. When
7438 called several times in succession, walk through the entire ring.
7439 Org-mode commands jumping to a different position in the current file,
7440 or to another Org-mode file, automatically push the old position
7441 onto the ring."
7442 (interactive "p")
7443 (let (p m)
7444 (if (eq last-command this-command)
7445 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7446 (setq p org-mark-ring))
7447 (setq org-mark-ring-last-goto p)
7448 (setq m (car p))
7449 (switch-to-buffer (marker-buffer m))
7450 (goto-char m)
7451 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7452
7453 (defun org-remove-angle-brackets (s)
7454 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7455 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7456 s)
7457 (defun org-add-angle-brackets (s)
7458 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7459 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7460 s)
7461 (defun org-remove-double-quotes (s)
7462 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7463 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7464 s)
7465
7466 ;;; Following specific links
7467
7468 (defun org-follow-timestamp-link ()
7469 (cond
7470 ((org-at-date-range-p t)
7471 (let ((org-agenda-start-on-weekday)
7472 (t1 (match-string 1))
7473 (t2 (match-string 2)))
7474 (setq t1 (time-to-days (org-time-string-to-time t1))
7475 t2 (time-to-days (org-time-string-to-time t2)))
7476 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7477 ((org-at-timestamp-p t)
7478 (org-agenda-list nil (time-to-days (org-time-string-to-time
7479 (substring (match-string 1) 0 10)))
7480 1))
7481 (t (error "This should not happen"))))
7482
7483
7484 ;;; Following file links
7485 (defvar org-wait nil)
7486 (defun org-open-file (path &optional in-emacs line search)
7487 "Open the file at PATH.
7488 First, this expands any special file name abbreviations. Then the
7489 configuration variable `org-file-apps' is checked if it contains an
7490 entry for this file type, and if yes, the corresponding command is launched.
7491
7492 If no application is found, Emacs simply visits the file.
7493
7494 With optional prefix argument IN-EMACS, Emacs will visit the file.
7495 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7496 and o use an external application to visit the file.
7497
7498 Optional LINE specifies a line to go to, optional SEARCH a string to
7499 search for. If LINE or SEARCH is given, the file will always be
7500 opened in Emacs.
7501 If the file does not exist, an error is thrown."
7502 (setq in-emacs (or in-emacs line search))
7503 (let* ((file (if (equal path "")
7504 buffer-file-name
7505 (substitute-in-file-name (expand-file-name path))))
7506 (apps (append org-file-apps (org-default-apps)))
7507 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7508 (dirp (if remp nil (file-directory-p file)))
7509 (file (if (and dirp org-open-directory-means-index-dot-org)
7510 (concat (file-name-as-directory file) "index.org")
7511 file))
7512 (a-m-a-p (assq 'auto-mode apps))
7513 (dfile (downcase file))
7514 (old-buffer (current-buffer))
7515 (old-pos (point))
7516 (old-mode major-mode)
7517 ext cmd)
7518 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7519 (setq ext (match-string 1 dfile))
7520 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7521 (setq ext (match-string 1 dfile))))
7522 (cond
7523 ((equal in-emacs '(16))
7524 (setq cmd (cdr (assoc 'system apps))))
7525 (in-emacs (setq cmd 'emacs))
7526 (t
7527 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7528 (and dirp (cdr (assoc 'directory apps)))
7529 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7530 'string-match)
7531 (cdr (assoc ext apps))
7532 (cdr (assoc t apps))))))
7533 (when (eq cmd 'system)
7534 (setq cmd (cdr (assoc 'system apps))))
7535 (when (eq cmd 'default)
7536 (setq cmd (cdr (assoc t apps))))
7537 (when (eq cmd 'mailcap)
7538 (require 'mailcap)
7539 (mailcap-parse-mailcaps)
7540 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7541 (command (mailcap-mime-info mime-type)))
7542 (if (stringp command)
7543 (setq cmd command)
7544 (setq cmd 'emacs))))
7545 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7546 (not (file-exists-p file))
7547 (not org-open-non-existing-files))
7548 (error "No such file: %s" file))
7549 (cond
7550 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7551 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7552 (while (string-match "['\"]%s['\"]" cmd)
7553 (setq cmd (replace-match "%s" t t cmd)))
7554 (while (string-match "%s" cmd)
7555 (setq cmd (replace-match
7556 (save-match-data
7557 (shell-quote-argument
7558 (convert-standard-filename file)))
7559 t t cmd)))
7560 (save-window-excursion
7561 (start-process-shell-command cmd nil cmd)
7562 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7563 ))
7564 ((or (stringp cmd)
7565 (eq cmd 'emacs))
7566 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7567 (widen)
7568 (if line (goto-line line)
7569 (if search (org-link-search search))))
7570 ((consp cmd)
7571 (let ((file (convert-standard-filename file)))
7572 (eval cmd)))
7573 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7574 (and (org-mode-p) (eq old-mode 'org-mode)
7575 (or (not (equal old-buffer (current-buffer)))
7576 (not (equal old-pos (point))))
7577 (org-mark-ring-push old-pos old-buffer))))
7578
7579 (defun org-default-apps ()
7580 "Return the default applications for this operating system."
7581 (cond
7582 ((eq system-type 'darwin)
7583 org-file-apps-defaults-macosx)
7584 ((eq system-type 'windows-nt)
7585 org-file-apps-defaults-windowsnt)
7586 (t org-file-apps-defaults-gnu)))
7587
7588 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7589 "Convert extensions to regular expressions in the cars of LIST.
7590 Also, weed out any non-string entries, because the return value is used
7591 only for regexp matching.
7592 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7593 point to the symbol `emacs', indicating that the file should
7594 be opened in Emacs."
7595 (append
7596 (delq nil
7597 (mapcar (lambda (x)
7598 (if (not (stringp (car x)))
7599 nil
7600 (if (string-match "\\W" (car x))
7601 x
7602 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7603 list))
7604 (if add-auto-mode
7605 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7606
7607 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7608 (defun org-file-remote-p (file)
7609 "Test whether FILE specifies a location on a remote system.
7610 Return non-nil if the location is indeed remote.
7611
7612 For example, the filename \"/user@host:/foo\" specifies a location
7613 on the system \"/user@host:\"."
7614 (cond ((fboundp 'file-remote-p)
7615 (file-remote-p file))
7616 ((fboundp 'tramp-handle-file-remote-p)
7617 (tramp-handle-file-remote-p file))
7618 ((and (boundp 'ange-ftp-name-format)
7619 (string-match (car ange-ftp-name-format) file))
7620 t)
7621 (t nil)))
7622
7623
7624 ;;;; Refiling
7625
7626 (defun org-get-org-file ()
7627 "Read a filename, with default directory `org-directory'."
7628 (let ((default (or org-default-notes-file remember-data-file)))
7629 (read-file-name (format "File name [%s]: " default)
7630 (file-name-as-directory org-directory)
7631 default)))
7632
7633 (defun org-notes-order-reversed-p ()
7634 "Check if the current file should receive notes in reversed order."
7635 (cond
7636 ((not org-reverse-note-order) nil)
7637 ((eq t org-reverse-note-order) t)
7638 ((not (listp org-reverse-note-order)) nil)
7639 (t (catch 'exit
7640 (let ((all org-reverse-note-order)
7641 entry)
7642 (while (setq entry (pop all))
7643 (if (string-match (car entry) buffer-file-name)
7644 (throw 'exit (cdr entry))))
7645 nil)))))
7646
7647 (defvar org-refile-target-table nil
7648 "The list of refile targets, created by `org-refile'.")
7649
7650 (defvar org-agenda-new-buffers nil
7651 "Buffers created to visit agenda files.")
7652
7653 (defun org-get-refile-targets (&optional default-buffer)
7654 "Produce a table with refile targets."
7655 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7656 targets txt re files f desc descre fast-path-p level)
7657 (message "Getting targets...")
7658 (with-current-buffer (or default-buffer (current-buffer))
7659 (while (setq entry (pop entries))
7660 (setq files (car entry) desc (cdr entry))
7661 (setq fast-path-p nil)
7662 (cond
7663 ((null files) (setq files (list (current-buffer))))
7664 ((eq files 'org-agenda-files)
7665 (setq files (org-agenda-files 'unrestricted)))
7666 ((and (symbolp files) (fboundp files))
7667 (setq files (funcall files)))
7668 ((and (symbolp files) (boundp files))
7669 (setq files (symbol-value files))))
7670 (if (stringp files) (setq files (list files)))
7671 (cond
7672 ((eq (car desc) :tag)
7673 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7674 ((eq (car desc) :todo)
7675 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7676 ((eq (car desc) :regexp)
7677 (setq descre (cdr desc)))
7678 ((eq (car desc) :level)
7679 (setq descre (concat "^\\*\\{" (number-to-string
7680 (if org-odd-levels-only
7681 (1- (* 2 (cdr desc)))
7682 (cdr desc)))
7683 "\\}[ \t]")))
7684 ((eq (car desc) :maxlevel)
7685 (setq fast-path-p t)
7686 (setq descre (concat "^\\*\\{1," (number-to-string
7687 (if org-odd-levels-only
7688 (1- (* 2 (cdr desc)))
7689 (cdr desc)))
7690 "\\}[ \t]")))
7691 (t (error "Bad refiling target description %s" desc)))
7692 (while (setq f (pop files))
7693 (save-excursion
7694 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7695 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7696 (setq f (expand-file-name f))
7697 (save-excursion
7698 (save-restriction
7699 (widen)
7700 (goto-char (point-min))
7701 (while (re-search-forward descre nil t)
7702 (goto-char (point-at-bol))
7703 (when (looking-at org-complex-heading-regexp)
7704 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7705 txt (org-link-display-format (match-string 4))
7706 re (concat "^" (regexp-quote
7707 (buffer-substring (match-beginning 1)
7708 (match-end 4)))))
7709 (if (match-end 5) (setq re (concat re "[ \t]+"
7710 (regexp-quote
7711 (match-string 5)))))
7712 (setq re (concat re "[ \t]*$"))
7713 (when org-refile-use-outline-path
7714 (setq txt (mapconcat 'org-protect-slash
7715 (append
7716 (if (eq org-refile-use-outline-path 'file)
7717 (list (file-name-nondirectory
7718 (buffer-file-name (buffer-base-buffer))))
7719 (if (eq org-refile-use-outline-path 'full-file-path)
7720 (list (buffer-file-name (buffer-base-buffer)))))
7721 (org-get-outline-path fast-path-p level txt)
7722 (list txt))
7723 "/")))
7724 (push (list txt f re (point)) targets))
7725 (goto-char (point-at-eol))))))))
7726 (message "Getting targets...done")
7727 (nreverse targets))))
7728
7729 (defun org-protect-slash (s)
7730 (while (string-match "/" s)
7731 (setq s (replace-match "\\" t t s)))
7732 s)
7733
7734 (defvar org-olpa (make-vector 20 nil))
7735
7736 (defun org-get-outline-path (&optional fastp level heading)
7737 "Return the outline path to the current entry, as a list."
7738 (if fastp
7739 (progn
7740 (if (> level 19)
7741 (error "Outline path failure, more than 19 levels."))
7742 (loop for i from level upto 19 do
7743 (aset org-olpa i nil))
7744 (prog1
7745 (delq nil (append org-olpa nil))
7746 (aset org-olpa level heading)))
7747 (let (rtn)
7748 (save-excursion
7749 (while (org-up-heading-safe)
7750 (when (looking-at org-complex-heading-regexp)
7751 (push (org-match-string-no-properties 4) rtn)))
7752 rtn))))
7753
7754 (defvar org-refile-history nil
7755 "History for refiling operations.")
7756
7757 (defun org-refile (&optional goto default-buffer)
7758 "Move the entry at point to another heading.
7759 The list of target headings is compiled using the information in
7760 `org-refile-targets', which see. This list is created before each use
7761 and will therefore always be up-to-date.
7762
7763 At the target location, the entry is filed as a subitem of the target heading.
7764 Depending on `org-reverse-note-order', the new subitem will either be the
7765 first or the last subitem.
7766
7767 If there is an active region, all entries in that region will be moved.
7768 However, the region must fulfil the requirement that the first heading
7769 is the first one sets the top-level of the moved text - at most siblings
7770 below it are allowed.
7771
7772 With prefix arg GOTO, the command will only visit the target location,
7773 not actually move anything.
7774 With a double prefix `C-u C-u', go to the location where the last refiling
7775 operation has put the subtree."
7776 (interactive "P")
7777 (let* ((cbuf (current-buffer))
7778 (regionp (org-region-active-p))
7779 (region-start (and regionp (region-beginning)))
7780 (region-end (and regionp (region-end)))
7781 (region-length (and regionp (- region-end region-start)))
7782 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7783 pos it nbuf file re level reversed)
7784 (when regionp (goto-char region-start)
7785 (unless (org-kill-is-subtree-p
7786 (buffer-substring region-start region-end))
7787 (error "The region is not a (sequence of) subtree(s)")))
7788 (if (equal goto '(16))
7789 (org-refile-goto-last-stored)
7790 (when (setq it (org-refile-get-location
7791 (if goto "Goto: " "Refile to: ") default-buffer))
7792 (setq file (nth 1 it)
7793 re (nth 2 it)
7794 pos (nth 3 it))
7795 (if (and (equal (buffer-file-name) file)
7796 (if regionp
7797 (and (>= pos region-start)
7798 (<= pos region-end))
7799 (and (>= pos (point))
7800 (< pos (save-excursion
7801 (org-end-of-subtree t t))))))
7802 (error "Cannot refile to position inside the tree or region"))
7803
7804 (setq nbuf (or (find-buffer-visiting file)
7805 (find-file-noselect file)))
7806 (if goto
7807 (progn
7808 (switch-to-buffer nbuf)
7809 (goto-char pos)
7810 (org-show-context 'org-goto))
7811 (if regionp
7812 (progn
7813 (kill-new (buffer-substring region-start region-end))
7814 (org-save-markers-in-region region-start region-end))
7815 (org-copy-subtree 1 nil t))
7816 (save-excursion
7817 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7818 (find-file-noselect file))))
7819 (setq reversed (org-notes-order-reversed-p))
7820 (save-excursion
7821 (save-restriction
7822 (widen)
7823 (goto-char pos)
7824 (looking-at outline-regexp)
7825 (setq level (org-get-valid-level (funcall outline-level) 1))
7826 (goto-char
7827 (if reversed
7828 (or (outline-next-heading) (point-max))
7829 (or (save-excursion (outline-get-next-sibling))
7830 (org-end-of-subtree t t)
7831 (point-max))))
7832 (if (not (bolp)) (newline))
7833 (bookmark-set "org-refile-last-stored")
7834 (org-paste-subtree level))))
7835 (if regionp
7836 (delete-region (point) (+ (point) region-length))
7837 (org-cut-subtree))
7838 (setq org-markers-to-move nil)
7839 (message "Refiled to \"%s\"" (car it)))))))
7840
7841 (defun org-refile-goto-last-stored ()
7842 "Go to the location where the last refile was stored."
7843 (interactive)
7844 (bookmark-jump "org-refile-last-stored")
7845 (message "This is the location of the last refile"))
7846
7847 (defun org-refile-get-location (&optional prompt default-buffer)
7848 "Prompt the user for a refile location, using PROMPT."
7849 (let ((org-refile-targets org-refile-targets)
7850 (org-refile-use-outline-path org-refile-use-outline-path))
7851 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7852 (unless org-refile-target-table
7853 (error "No refile targets"))
7854 (let* ((cbuf (current-buffer))
7855 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7856 (cfunc (if (and org-refile-use-outline-path
7857 org-outline-path-complete-in-steps)
7858 'org-olpath-completing-read
7859 'org-ido-completing-read))
7860 (extra (if org-refile-use-outline-path "/" ""))
7861 (filename (and cfn (expand-file-name cfn)))
7862 (tbl (mapcar
7863 (lambda (x)
7864 (if (not (equal filename (nth 1 x)))
7865 (cons (concat (car x) extra " ("
7866 (file-name-nondirectory (nth 1 x)) ")")
7867 (cdr x))
7868 (cons (concat (car x) extra) (cdr x))))
7869 org-refile-target-table))
7870 (completion-ignore-case t))
7871 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7872 tbl)))
7873
7874 (defun org-olpath-completing-read (prompt collection &rest args)
7875 "Read an outline path like a file name."
7876 (let ((thetable collection))
7877 (apply
7878 'org-ido-completing-read prompt
7879 (lambda (string predicate &optional flag)
7880 (let (rtn r f (l (length string)))
7881 (cond
7882 ((eq flag nil)
7883 ;; try completion
7884 (try-completion string thetable))
7885 ((eq flag t)
7886 ;; all-completions
7887 (setq rtn (all-completions string thetable predicate))
7888 (mapcar
7889 (lambda (x)
7890 (setq r (substring x l))
7891 (if (string-match " ([^)]*)$" x)
7892 (setq f (match-string 0 x))
7893 (setq f ""))
7894 (if (string-match "/" r)
7895 (concat string (substring r 0 (match-end 0)) f)
7896 x))
7897 rtn))
7898 ((eq flag 'lambda)
7899 ;; exact match?
7900 (assoc string thetable)))
7901 ))
7902 args)))
7903
7904 ;;;; Dynamic blocks
7905
7906 (defun org-find-dblock (name)
7907 "Find the first dynamic block with name NAME in the buffer.
7908 If not found, stay at current position and return nil."
7909 (let (pos)
7910 (save-excursion
7911 (goto-char (point-min))
7912 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7913 nil t)
7914 (match-beginning 0))))
7915 (if pos (goto-char pos))
7916 pos))
7917
7918 (defconst org-dblock-start-re
7919 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7920 "Matches the startline of a dynamic block, with parameters.")
7921
7922 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7923 "Matches the end of a dynamic block.")
7924
7925 (defun org-create-dblock (plist)
7926 "Create a dynamic block section, with parameters taken from PLIST.
7927 PLIST must contain a :name entry which is used as name of the block."
7928 (unless (bolp) (newline))
7929 (let ((name (plist-get plist :name)))
7930 (insert "#+BEGIN: " name)
7931 (while plist
7932 (if (eq (car plist) :name)
7933 (setq plist (cddr plist))
7934 (insert " " (prin1-to-string (pop plist)))))
7935 (insert "\n\n#+END:\n")
7936 (beginning-of-line -2)))
7937
7938 (defun org-prepare-dblock ()
7939 "Prepare dynamic block for refresh.
7940 This empties the block, puts the cursor at the insert position and returns
7941 the property list including an extra property :name with the block name."
7942 (unless (looking-at org-dblock-start-re)
7943 (error "Not at a dynamic block"))
7944 (let* ((begdel (1+ (match-end 0)))
7945 (name (org-no-properties (match-string 1)))
7946 (params (append (list :name name)
7947 (read (concat "(" (match-string 3) ")")))))
7948 (unless (re-search-forward org-dblock-end-re nil t)
7949 (error "Dynamic block not terminated"))
7950 (setq params
7951 (append params
7952 (list :content (buffer-substring
7953 begdel (match-beginning 0)))))
7954 (delete-region begdel (match-beginning 0))
7955 (goto-char begdel)
7956 (open-line 1)
7957 params))
7958
7959 (defun org-map-dblocks (&optional command)
7960 "Apply COMMAND to all dynamic blocks in the current buffer.
7961 If COMMAND is not given, use `org-update-dblock'."
7962 (let ((cmd (or command 'org-update-dblock))
7963 pos)
7964 (save-excursion
7965 (goto-char (point-min))
7966 (while (re-search-forward org-dblock-start-re nil t)
7967 (goto-char (setq pos (match-beginning 0)))
7968 (condition-case nil
7969 (funcall cmd)
7970 (error (message "Error during update of dynamic block")))
7971 (goto-char pos)
7972 (unless (re-search-forward org-dblock-end-re nil t)
7973 (error "Dynamic block not terminated"))))))
7974
7975 (defun org-dblock-update (&optional arg)
7976 "User command for updating dynamic blocks.
7977 Update the dynamic block at point. With prefix ARG, update all dynamic
7978 blocks in the buffer."
7979 (interactive "P")
7980 (if arg
7981 (org-update-all-dblocks)
7982 (or (looking-at org-dblock-start-re)
7983 (org-beginning-of-dblock))
7984 (org-update-dblock)))
7985
7986 (defun org-update-dblock ()
7987 "Update the dynamic block at point
7988 This means to empty the block, parse for parameters and then call
7989 the correct writing function."
7990 (save-window-excursion
7991 (let* ((pos (point))
7992 (line (org-current-line))
7993 (params (org-prepare-dblock))
7994 (name (plist-get params :name))
7995 (cmd (intern (concat "org-dblock-write:" name))))
7996 (message "Updating dynamic block `%s' at line %d..." name line)
7997 (funcall cmd params)
7998 (message "Updating dynamic block `%s' at line %d...done" name line)
7999 (goto-char pos))))
8000
8001 (defun org-beginning-of-dblock ()
8002 "Find the beginning of the dynamic block at point.
8003 Error if there is no such block at point."
8004 (let ((pos (point))
8005 beg)
8006 (end-of-line 1)
8007 (if (and (re-search-backward org-dblock-start-re nil t)
8008 (setq beg (match-beginning 0))
8009 (re-search-forward org-dblock-end-re nil t)
8010 (> (match-end 0) pos))
8011 (goto-char beg)
8012 (goto-char pos)
8013 (error "Not in a dynamic block"))))
8014
8015 (defun org-update-all-dblocks ()
8016 "Update all dynamic blocks in the buffer.
8017 This function can be used in a hook."
8018 (when (org-mode-p)
8019 (org-map-dblocks 'org-update-dblock)))
8020
8021
8022 ;;;; Completion
8023
8024 (defconst org-additional-option-like-keywords
8025 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8026 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8027 "BEGIN_EXAMPLE" "END_EXAMPLE"
8028 "BEGIN_QUOTE" "END_QUOTE"
8029 "BEGIN_VERSE" "END_VERSE"
8030 "BEGIN_SRC" "END_SRC"
8031 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8032
8033 (defcustom org-structure-template-alist
8034 '(
8035 ("s" "#+begin_src ?\n\n#+end_src"
8036 "<src lang=\"?\">\n\n</src>")
8037 ("e" "#+begin_example\n?\n#+end_example"
8038 "<example>\n?\n</example>")
8039 ("q" "#+begin_quote\n?\n#+end_quote"
8040 "<quote>\n?\n</quote>")
8041 ("v" "#+begin_verse\n?\n#+end_verse"
8042 "<verse>\n?\n/verse>")
8043 ("l" "#+begin_latex\n?\n#+end_latex"
8044 "<literal style=\"latex\">\n?\n</literal>")
8045 ("L" "#+latex: "
8046 "<literal style=\"latex\">?</literal>")
8047 ("h" "#+begin_html\n?\n#+end_html"
8048 "<literal style=\"html\">\n?\n</literal>")
8049 ("H" "#+html: "
8050 "<literal style=\"html\">?</literal>")
8051 ("a" "#+begin_ascii\n?\n#+end_ascii")
8052 ("A" "#+ascii: ")
8053 ("i" "#+include %file ?"
8054 "<include file=%file markup=\"?\">")
8055 )
8056 "Structure completion elements.
8057 This is a list of abbreviation keys and values. The value gets inserted
8058 it you type @samp{.} followed by the key and then the completion key,
8059 usually `M-TAB'. %file will be replaced by a file name after prompting
8060 for the file using completion.
8061 There are two templates for each key, the first uses the original Org syntax,
8062 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8063 the default when the /org-mtags.el/ module has been loaded. See also the
8064 variable `org-mtags-prefer-muse-templates'.
8065 This is an experimental feature, it is undecided if it is going to stay in."
8066 :group 'org-completion
8067 :type '(repeat
8068 (string :tag "Key")
8069 (string :tag "Template")
8070 (string :tag "Muse Template")))
8071
8072 (defun org-try-structure-completion ()
8073 "Try to complete a structure template before point.
8074 This looks for strings like \"<e\" on an otherwise empty line and
8075 expands them."
8076 (let ((l (buffer-substring (point-at-bol) (point)))
8077 a)
8078 (when (and (looking-at "[ \t]*$")
8079 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8080 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8081 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8082 (match-beginning 1)) a)
8083 t)))
8084
8085 (defun org-complete-expand-structure-template (start cell)
8086 "Expand a structure template."
8087 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8088 (rpl (nth (if musep 2 1) cell)))
8089 (delete-region start (point))
8090 (when (string-match "\\`#\\+" rpl)
8091 (cond
8092 ((bolp))
8093 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8094 (delete-region (point-at-bol) (point)))
8095 (t (newline))))
8096 (setq start (point))
8097 (if (string-match "%file" rpl)
8098 (setq rpl (replace-match
8099 (concat
8100 "\""
8101 (save-match-data
8102 (abbreviate-file-name (read-file-name "Include file: ")))
8103 "\"")
8104 t t rpl)))
8105 (insert rpl)
8106 (if (re-search-backward "\\?" start t) (delete-char 1))))
8107
8108
8109 (defun org-complete (&optional arg)
8110 "Perform completion on word at point.
8111 At the beginning of a headline, this completes TODO keywords as given in
8112 `org-todo-keywords'.
8113 If the current word is preceded by a backslash, completes the TeX symbols
8114 that are supported for HTML support.
8115 If the current word is preceded by \"#+\", completes special words for
8116 setting file options.
8117 In the line after \"#+STARTUP:, complete valid keywords.\"
8118 At all other locations, this simply calls the value of
8119 `org-completion-fallback-command'."
8120 (interactive "P")
8121 (org-without-partial-completion
8122 (catch 'exit
8123 (let* ((a nil)
8124 (end (point))
8125 (beg1 (save-excursion
8126 (skip-chars-backward (org-re "[:alnum:]_@"))
8127 (point)))
8128 (beg (save-excursion
8129 (skip-chars-backward "a-zA-Z0-9_:$")
8130 (point)))
8131 (confirm (lambda (x) (stringp (car x))))
8132 (searchhead (equal (char-before beg) ?*))
8133 (struct
8134 (when (and (member (char-before beg1) '(?. ?<))
8135 (setq a (assoc (buffer-substring beg1 (point))
8136 org-structure-template-alist)))
8137 (org-complete-expand-structure-template (1- beg1) a)
8138 (throw 'exit t)))
8139 (tag (and (equal (char-before beg1) ?:)
8140 (equal (char-after (point-at-bol)) ?*)))
8141 (prop (and (equal (char-before beg1) ?:)
8142 (not (equal (char-after (point-at-bol)) ?*))))
8143 (texp (equal (char-before beg) ?\\))
8144 (link (equal (char-before beg) ?\[))
8145 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8146 beg)
8147 "#+"))
8148 (startup (string-match "^#\\+STARTUP:.*"
8149 (buffer-substring (point-at-bol) (point))))
8150 (completion-ignore-case opt)
8151 (type nil)
8152 (tbl nil)
8153 (table (cond
8154 (opt
8155 (setq type :opt)
8156 (require 'org-exp)
8157 (append
8158 (mapcar
8159 (lambda (x)
8160 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8161 (cons (match-string 2 x) (match-string 1 x)))
8162 (org-split-string (org-get-current-options) "\n"))
8163 (mapcar 'list org-additional-option-like-keywords)))
8164 (startup
8165 (setq type :startup)
8166 org-startup-options)
8167 (link (append org-link-abbrev-alist-local
8168 org-link-abbrev-alist))
8169 (texp
8170 (setq type :tex)
8171 org-html-entities)
8172 ((string-match "\\`\\*+[ \t]+\\'"
8173 (buffer-substring (point-at-bol) beg))
8174 (setq type :todo)
8175 (mapcar 'list org-todo-keywords-1))
8176 (searchhead
8177 (setq type :searchhead)
8178 (save-excursion
8179 (goto-char (point-min))
8180 (while (re-search-forward org-todo-line-regexp nil t)
8181 (push (list
8182 (org-make-org-heading-search-string
8183 (match-string 3) t))
8184 tbl)))
8185 tbl)
8186 (tag (setq type :tag beg beg1)
8187 (or org-tag-alist (org-get-buffer-tags)))
8188 (prop (setq type :prop beg beg1)
8189 (mapcar 'list (org-buffer-property-keys nil t t)))
8190 (t (progn
8191 (call-interactively org-completion-fallback-command)
8192 (throw 'exit nil)))))
8193 (pattern (buffer-substring-no-properties beg end))
8194 (completion (try-completion pattern table confirm)))
8195 (cond ((eq completion t)
8196 (if (not (assoc (upcase pattern) table))
8197 (message "Already complete")
8198 (if (and (equal type :opt)
8199 (not (member (car (assoc (upcase pattern) table))
8200 org-additional-option-like-keywords)))
8201 (insert (substring (cdr (assoc (upcase pattern) table))
8202 (length pattern)))
8203 (if (memq type '(:tag :prop)) (insert ":")))))
8204 ((null completion)
8205 (message "Can't find completion for \"%s\"" pattern)
8206 (ding))
8207 ((not (string= pattern completion))
8208 (delete-region beg end)
8209 (if (string-match " +$" completion)
8210 (setq completion (replace-match "" t t completion)))
8211 (insert completion)
8212 (if (get-buffer-window "*Completions*")
8213 (delete-window (get-buffer-window "*Completions*")))
8214 (if (assoc completion table)
8215 (if (eq type :todo) (insert " ")
8216 (if (memq type '(:tag :prop)) (insert ":"))))
8217 (if (and (equal type :opt) (assoc completion table))
8218 (message "%s" (substitute-command-keys
8219 "Press \\[org-complete] again to insert example settings"))))
8220 (t
8221 (message "Making completion list...")
8222 (let ((list (sort (all-completions pattern table confirm)
8223 'string<)))
8224 (with-output-to-temp-buffer "*Completions*"
8225 (condition-case nil
8226 ;; Protection needed for XEmacs and emacs 21
8227 (display-completion-list list pattern)
8228 (error (display-completion-list list)))))
8229 (message "Making completion list...%s" "done")))))))
8230
8231 ;;;; TODO, DEADLINE, Comments
8232
8233 (defun org-toggle-comment ()
8234 "Change the COMMENT state of an entry."
8235 (interactive)
8236 (save-excursion
8237 (org-back-to-heading)
8238 (let (case-fold-search)
8239 (if (looking-at (concat outline-regexp
8240 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8241 (replace-match "" t t nil 1)
8242 (if (looking-at outline-regexp)
8243 (progn
8244 (goto-char (match-end 0))
8245 (insert org-comment-string " ")))))))
8246
8247 (defvar org-last-todo-state-is-todo nil
8248 "This is non-nil when the last TODO state change led to a TODO state.
8249 If the last change removed the TODO tag or switched to DONE, then
8250 this is nil.")
8251
8252 (defvar org-setting-tags nil) ; dynamically skipped
8253
8254 (defun org-parse-local-options (string var)
8255 "Parse STRING for startup setting relevant for variable VAR."
8256 (let ((rtn (symbol-value var))
8257 e opts)
8258 (save-match-data
8259 (if (or (not string) (not (string-match "\\S-" string)))
8260 rtn
8261 (setq opts (delq nil (mapcar (lambda (x)
8262 (setq e (assoc x org-startup-options))
8263 (if (eq (nth 1 e) var) e nil))
8264 (org-split-string string "[ \t]+"))))
8265 (if (not opts)
8266 rtn
8267 (setq rtn nil)
8268 (while (setq e (pop opts))
8269 (if (not (nth 3 e))
8270 (setq rtn (nth 2 e))
8271 (if (not (listp rtn)) (setq rtn nil))
8272 (push (nth 2 e) rtn)))
8273 rtn)))))
8274
8275 (defvar org-blocker-hook nil
8276 "Hook for functions that are allowed to block a state change.
8277
8278 Each function gets as its single argument a property list, see
8279 `org-trigger-hook' for more information about this list.
8280
8281 If any of the functions in this hook returns nil, the state change
8282 is blocked.")
8283
8284 (defvar org-trigger-hook nil
8285 "Hook for functions that are triggered by a state change.
8286
8287 Each function gets as its single argument a property list with at least
8288 the following elements:
8289
8290 (:type type-of-change :position pos-at-entry-start
8291 :from old-state :to new-state)
8292
8293 Depending on the type, more properties may be present.
8294
8295 This mechanism is currently implemented for:
8296
8297 TODO state changes
8298 ------------------
8299 :type todo-state-change
8300 :from previous state (keyword as a string), or nil
8301 :to new state (keyword as a string), or nil")
8302
8303 (defvar org-agenda-headline-snapshot-before-repeat)
8304 (defun org-todo (&optional arg)
8305 "Change the TODO state of an item.
8306 The state of an item is given by a keyword at the start of the heading,
8307 like
8308 *** TODO Write paper
8309 *** DONE Call mom
8310
8311 The different keywords are specified in the variable `org-todo-keywords'.
8312 By default the available states are \"TODO\" and \"DONE\".
8313 So for this example: when the item starts with TODO, it is changed to DONE.
8314 When it starts with DONE, the DONE is removed. And when neither TODO nor
8315 DONE are present, add TODO at the beginning of the heading.
8316
8317 With C-u prefix arg, use completion to determine the new state.
8318 With numeric prefix arg, switch to that state.
8319 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8320
8321 For calling through lisp, arg is also interpreted in the following way:
8322 'none -> empty state
8323 \"\"(empty string) -> switch to empty state
8324 'done -> switch to DONE
8325 'nextset -> switch to the next set of keywords
8326 'previousset -> switch to the previous set of keywords
8327 \"WAITING\" -> switch to the specified keyword, but only if it
8328 really is a member of `org-todo-keywords'."
8329 (interactive "P")
8330 (if (equal arg '(16)) (setq arg 'nextset))
8331 (save-excursion
8332 (catch 'exit
8333 (org-back-to-heading)
8334 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8335 (or (looking-at (concat " +" org-todo-regexp " *"))
8336 (looking-at " *"))
8337 (let* ((match-data (match-data))
8338 (startpos (point-at-bol))
8339 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8340 (org-log-done org-log-done)
8341 (org-log-repeat org-log-repeat)
8342 (org-todo-log-states org-todo-log-states)
8343 (this (match-string 1))
8344 (hl-pos (match-beginning 0))
8345 (head (org-get-todo-sequence-head this))
8346 (ass (assoc head org-todo-kwd-alist))
8347 (interpret (nth 1 ass))
8348 (done-word (nth 3 ass))
8349 (final-done-word (nth 4 ass))
8350 (last-state (or this ""))
8351 (completion-ignore-case t)
8352 (member (member this org-todo-keywords-1))
8353 (tail (cdr member))
8354 (state (cond
8355 ((and org-todo-key-trigger
8356 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8357 (and (not arg) org-use-fast-todo-selection
8358 (not (eq org-use-fast-todo-selection 'prefix)))))
8359 ;; Use fast selection
8360 (org-fast-todo-selection))
8361 ((and (equal arg '(4))
8362 (or (not org-use-fast-todo-selection)
8363 (not org-todo-key-trigger)))
8364 ;; Read a state with completion
8365 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8366 org-todo-keywords-1)
8367 nil t))
8368 ((eq arg 'right)
8369 (if this
8370 (if tail (car tail) nil)
8371 (car org-todo-keywords-1)))
8372 ((eq arg 'left)
8373 (if (equal member org-todo-keywords-1)
8374 nil
8375 (if this
8376 (nth (- (length org-todo-keywords-1) (length tail) 2)
8377 org-todo-keywords-1)
8378 (org-last org-todo-keywords-1))))
8379 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8380 (setq arg nil))) ; hack to fall back to cycling
8381 (arg
8382 ;; user or caller requests a specific state
8383 (cond
8384 ((equal arg "") nil)
8385 ((eq arg 'none) nil)
8386 ((eq arg 'done) (or done-word (car org-done-keywords)))
8387 ((eq arg 'nextset)
8388 (or (car (cdr (member head org-todo-heads)))
8389 (car org-todo-heads)))
8390 ((eq arg 'previousset)
8391 (let ((org-todo-heads (reverse org-todo-heads)))
8392 (or (car (cdr (member head org-todo-heads)))
8393 (car org-todo-heads))))
8394 ((car (member arg org-todo-keywords-1)))
8395 ((nth (1- (prefix-numeric-value arg))
8396 org-todo-keywords-1))))
8397 ((null member) (or head (car org-todo-keywords-1)))
8398 ((equal this final-done-word) nil) ;; -> make empty
8399 ((null tail) nil) ;; -> first entry
8400 ((eq interpret 'sequence)
8401 (car tail))
8402 ((memq interpret '(type priority))
8403 (if (eq this-command last-command)
8404 (car tail)
8405 (if (> (length tail) 0)
8406 (or done-word (car org-done-keywords))
8407 nil)))
8408 (t nil)))
8409 (next (if state (concat " " state " ") " "))
8410 (change-plist (list :type 'todo-state-change :from this :to state
8411 :position startpos))
8412 dolog now-done-p)
8413 (when org-blocker-hook
8414 (setq org-last-todo-state-is-todo
8415 (not (member this org-done-keywords)))
8416 (unless (save-excursion
8417 (save-match-data
8418 (run-hook-with-args-until-failure
8419 'org-blocker-hook change-plist)))
8420 (if (interactive-p)
8421 (error "TODO state change from %s to %s blocked" this state)
8422 ;; fail silently
8423 (message "TODO state change from %s to %s blocked" this state)
8424 (throw 'exit nil))))
8425 (store-match-data match-data)
8426 (replace-match next t t)
8427 (unless (pos-visible-in-window-p hl-pos)
8428 (message "TODO state changed to %s" (org-trim next)))
8429 (unless head
8430 (setq head (org-get-todo-sequence-head state)
8431 ass (assoc head org-todo-kwd-alist)
8432 interpret (nth 1 ass)
8433 done-word (nth 3 ass)
8434 final-done-word (nth 4 ass)))
8435 (when (memq arg '(nextset previousset))
8436 (message "Keyword-Set %d/%d: %s"
8437 (- (length org-todo-sets) -1
8438 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8439 (length org-todo-sets)
8440 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8441 (setq org-last-todo-state-is-todo
8442 (not (member state org-done-keywords)))
8443 (setq now-done-p (and (member state org-done-keywords)
8444 (not (member this org-done-keywords))))
8445 (and logging (org-local-logging logging))
8446 (when (and (or org-todo-log-states org-log-done)
8447 (not (memq arg '(nextset previousset))))
8448 ;; we need to look at recording a time and note
8449 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8450 (nth 2 (assoc this org-todo-log-states))))
8451 (when (and state
8452 (member state org-not-done-keywords)
8453 (not (member this org-not-done-keywords)))
8454 ;; This is now a todo state and was not one before
8455 ;; If there was a CLOSED time stamp, get rid of it.
8456 (org-add-planning-info nil nil 'closed))
8457 (when (and now-done-p org-log-done)
8458 ;; It is now done, and it was not done before
8459 (org-add-planning-info 'closed (org-current-time))
8460 (if (and (not dolog) (eq 'note org-log-done))
8461 (org-add-log-setup 'done state 'findpos 'note)))
8462 (when (and state dolog)
8463 ;; This is a non-nil state, and we need to log it
8464 (org-add-log-setup 'state state 'findpos dolog)))
8465 ;; Fixup tag positioning
8466 (org-todo-trigger-tag-changes state)
8467 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8468 (when org-provide-todo-statistics
8469 (org-update-parent-todo-statistics))
8470 (run-hooks 'org-after-todo-state-change-hook)
8471 (if (and arg (not (member state org-done-keywords)))
8472 (setq head (org-get-todo-sequence-head state)))
8473 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8474 ;; Do we need to trigger a repeat?
8475 (when now-done-p
8476 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8477 ;; This is for the agenda, take a snapshot of the headline.
8478 (save-match-data
8479 (setq org-agenda-headline-snapshot-before-repeat
8480 (org-get-heading))))
8481 (org-auto-repeat-maybe state))
8482 ;; Fixup cursor location if close to the keyword
8483 (if (and (outline-on-heading-p)
8484 (not (bolp))
8485 (save-excursion (beginning-of-line 1)
8486 (looking-at org-todo-line-regexp))
8487 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8488 (progn
8489 (goto-char (or (match-end 2) (match-end 1)))
8490 (just-one-space)))
8491 (when org-trigger-hook
8492 (save-excursion
8493 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8494
8495 (defun org-update-parent-todo-statistics ()
8496 "Update any statistics cookie in the parent of the current headline."
8497 (interactive)
8498 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8499 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8500 (catch 'exit
8501 (save-excursion
8502 (setq level (org-up-heading-safe))
8503 (unless (and level
8504 (re-search-forward box-re (point-at-eol) t))
8505 (throw 'exit nil))
8506 (setq is-percent (match-end 2))
8507 (save-match-data
8508 (unless (outline-next-heading) (throw 'exit nil))
8509 (while (looking-at org-todo-line-regexp)
8510 (setq kwd (match-string 2))
8511 (and kwd (setq cnt-all (1+ cnt-all)))
8512 (and (member kwd org-done-keywords)
8513 (setq cnt-done (1+ cnt-done)))
8514 (condition-case nil
8515 (org-forward-same-level 1)
8516 (error (end-of-line 1)))))
8517 (replace-match
8518 (if is-percent
8519 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8520 (format "[%d/%d]" cnt-done cnt-all)))
8521 (run-hook-with-args 'org-after-todo-statistics-hook
8522 cnt-done (- cnt-all cnt-done))))))
8523
8524 (defvar org-after-todo-statistics-hook nil
8525 "Hook that is called after a TODO statistics cookie has been updated.
8526 Each function is called with two arguments: the number of not-done entries
8527 and the number of done entries.
8528
8529 For example, the following function, when added to this hook, will switch
8530 an entry to DONE when all children are done, and back to TODO when new
8531 entries are set to a TODO status. Note that this hook is only called
8532 when there is a statistics cookie in the headline!
8533
8534 (defun org-summary-todo (n-done n-not-done)
8535 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8536 (let (org-log-done org-log-states) ; turn off logging
8537 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8538 ")
8539
8540 (defun org-todo-trigger-tag-changes (state)
8541 "Apply the changes defined in `org-todo-state-tags-triggers'."
8542 (let ((l org-todo-state-tags-triggers)
8543 changes)
8544 (when (or (not state) (equal state ""))
8545 (setq changes (append changes (cdr (assoc "" l)))))
8546 (when (and (stringp state) (> (length state) 0))
8547 (setq changes (append changes (cdr (assoc state l)))))
8548 (when (member state org-not-done-keywords)
8549 (setq changes (append changes (cdr (assoc 'todo l)))))
8550 (when (member state org-done-keywords)
8551 (setq changes (append changes (cdr (assoc 'done l)))))
8552 (dolist (c changes)
8553 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8554
8555 (defun org-local-logging (value)
8556 "Get logging settings from a property VALUE."
8557 (let* (words w a)
8558 ;; directly set the variables, they are already local.
8559 (setq org-log-done nil
8560 org-log-repeat nil
8561 org-todo-log-states nil)
8562 (setq words (org-split-string value))
8563 (while (setq w (pop words))
8564 (cond
8565 ((setq a (assoc w org-startup-options))
8566 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8567 (set (nth 1 a) (nth 2 a))))
8568 ((setq a (org-extract-log-state-settings w))
8569 (and (member (car a) org-todo-keywords-1)
8570 (push a org-todo-log-states)))))))
8571
8572 (defun org-get-todo-sequence-head (kwd)
8573 "Return the head of the TODO sequence to which KWD belongs.
8574 If KWD is not set, check if there is a text property remembering the
8575 right sequence."
8576 (let (p)
8577 (cond
8578 ((not kwd)
8579 (or (get-text-property (point-at-bol) 'org-todo-head)
8580 (progn
8581 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8582 nil (point-at-eol)))
8583 (get-text-property p 'org-todo-head))))
8584 ((not (member kwd org-todo-keywords-1))
8585 (car org-todo-keywords-1))
8586 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8587
8588 (defun org-fast-todo-selection ()
8589 "Fast TODO keyword selection with single keys.
8590 Returns the new TODO keyword, or nil if no state change should occur."
8591 (let* ((fulltable org-todo-key-alist)
8592 (done-keywords org-done-keywords) ;; needed for the faces.
8593 (maxlen (apply 'max (mapcar
8594 (lambda (x)
8595 (if (stringp (car x)) (string-width (car x)) 0))
8596 fulltable)))
8597 (expert nil)
8598 (fwidth (+ maxlen 3 1 3))
8599 (ncol (/ (- (window-width) 4) fwidth))
8600 tg cnt e c tbl
8601 groups ingroup)
8602 (save-window-excursion
8603 (if expert
8604 (set-buffer (get-buffer-create " *Org todo*"))
8605 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8606 (erase-buffer)
8607 (org-set-local 'org-done-keywords done-keywords)
8608 (setq tbl fulltable cnt 0)
8609 (while (setq e (pop tbl))
8610 (cond
8611 ((equal e '(:startgroup))
8612 (push '() groups) (setq ingroup t)
8613 (when (not (= cnt 0))
8614 (setq cnt 0)
8615 (insert "\n"))
8616 (insert "{ "))
8617 ((equal e '(:endgroup))
8618 (setq ingroup nil cnt 0)
8619 (insert "}\n"))
8620 (t
8621 (setq tg (car e) c (cdr e))
8622 (if ingroup (push tg (car groups)))
8623 (setq tg (org-add-props tg nil 'face
8624 (org-get-todo-face tg)))
8625 (if (and (= cnt 0) (not ingroup)) (insert " "))
8626 (insert "[" c "] " tg (make-string
8627 (- fwidth 4 (length tg)) ?\ ))
8628 (when (= (setq cnt (1+ cnt)) ncol)
8629 (insert "\n")
8630 (if ingroup (insert " "))
8631 (setq cnt 0)))))
8632 (insert "\n")
8633 (goto-char (point-min))
8634 (if (not expert) (org-fit-window-to-buffer))
8635 (message "[a-z..]:Set [SPC]:clear")
8636 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8637 (cond
8638 ((or (= c ?\C-g)
8639 (and (= c ?q) (not (rassoc c fulltable))))
8640 (setq quit-flag t))
8641 ((= c ?\ ) nil)
8642 ((setq e (rassoc c fulltable) tg (car e))
8643 tg)
8644 (t (setq quit-flag t))))))
8645
8646 (defun org-entry-is-todo-p ()
8647 (member (org-get-todo-state) org-not-done-keywords))
8648
8649 (defun org-entry-is-done-p ()
8650 (member (org-get-todo-state) org-done-keywords))
8651
8652 (defun org-get-todo-state ()
8653 (save-excursion
8654 (org-back-to-heading t)
8655 (and (looking-at org-todo-line-regexp)
8656 (match-end 2)
8657 (match-string 2))))
8658
8659 (defun org-at-date-range-p (&optional inactive-ok)
8660 "Is the cursor inside a date range?"
8661 (interactive)
8662 (save-excursion
8663 (catch 'exit
8664 (let ((pos (point)))
8665 (skip-chars-backward "^[<\r\n")
8666 (skip-chars-backward "<[")
8667 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8668 (>= (match-end 0) pos)
8669 (throw 'exit t))
8670 (skip-chars-backward "^<[\r\n")
8671 (skip-chars-backward "<[")
8672 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8673 (>= (match-end 0) pos)
8674 (throw 'exit t)))
8675 nil)))
8676
8677 (defun org-get-repeat ()
8678 "Check if there is a deadline/schedule with repeater in this entry."
8679 (save-match-data
8680 (save-excursion
8681 (org-back-to-heading t)
8682 (if (re-search-forward
8683 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8684 (match-string 1)))))
8685
8686 (defvar org-last-changed-timestamp)
8687 (defvar org-last-inserted-timestamp)
8688 (defvar org-log-post-message)
8689 (defvar org-log-note-purpose)
8690 (defvar org-log-note-how)
8691 (defvar org-log-note-extra)
8692 (defun org-auto-repeat-maybe (done-word)
8693 "Check if the current headline contains a repeated deadline/schedule.
8694 If yes, set TODO state back to what it was and change the base date
8695 of repeating deadline/scheduled time stamps to new date.
8696 This function is run automatically after each state change to a DONE state."
8697 ;; last-state is dynamically scoped into this function
8698 (let* ((repeat (org-get-repeat))
8699 (aa (assoc last-state org-todo-kwd-alist))
8700 (interpret (nth 1 aa))
8701 (head (nth 2 aa))
8702 (whata '(("d" . day) ("m" . month) ("y" . year)))
8703 (msg "Entry repeats: ")
8704 (org-log-done nil)
8705 (org-todo-log-states nil)
8706 (nshiftmax 10) (nshift 0)
8707 re type n what ts time)
8708 (when repeat
8709 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8710 (org-todo (if (eq interpret 'type) last-state head))
8711 (when org-log-repeat
8712 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8713 (memq 'org-add-log-note post-command-hook))
8714 ;; OK, we are already setup for some record
8715 (if (eq org-log-repeat 'note)
8716 ;; make sure we take a note, not only a time stamp
8717 (setq org-log-note-how 'note))
8718 ;; Set up for taking a record
8719 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8720 'findpos org-log-repeat)))
8721 (org-back-to-heading t)
8722 (org-add-planning-info nil nil 'closed)
8723 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8724 org-deadline-time-regexp "\\)\\|\\("
8725 org-ts-regexp "\\)"))
8726 (while (re-search-forward
8727 re (save-excursion (outline-next-heading) (point)) t)
8728 (setq type (if (match-end 1) org-scheduled-string
8729 (if (match-end 3) org-deadline-string "Plain:"))
8730 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
8731 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8732 (setq n (string-to-number (match-string 2 ts))
8733 what (match-string 3 ts))
8734 (if (equal what "w") (setq n (* n 7) what "d"))
8735 ;; Preparation, see if we need to modify the start date for the change
8736 (when (match-end 1)
8737 (setq time (save-match-data (org-time-string-to-time ts)))
8738 (cond
8739 ((equal (match-string 1 ts) ".")
8740 ;; Shift starting date to today
8741 (org-timestamp-change
8742 (- (time-to-days (current-time)) (time-to-days time))
8743 'day))
8744 ((equal (match-string 1 ts) "+")
8745 (while (or (= nshift 0)
8746 (<= (time-to-days time) (time-to-days (current-time))))
8747 (when (= (incf nshift) nshiftmax)
8748 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8749 (error "Abort")))
8750 (org-timestamp-change n (cdr (assoc what whata)))
8751 (org-at-timestamp-p t)
8752 (setq ts (match-string 1))
8753 (setq time (save-match-data (org-time-string-to-time ts))))
8754 (org-timestamp-change (- n) (cdr (assoc what whata)))
8755 ;; rematch, so that we have everything in place for the real shift
8756 (org-at-timestamp-p t)
8757 (setq ts (match-string 1))
8758 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8759 (org-timestamp-change n (cdr (assoc what whata)))
8760 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8761 (setq org-log-post-message msg)
8762 (message "%s" msg))))
8763
8764 (defun org-show-todo-tree (arg)
8765 "Make a compact tree which shows all headlines marked with TODO.
8766 The tree will show the lines where the regexp matches, and all higher
8767 headlines above the match.
8768 With a \\[universal-argument] prefix, also show the DONE entries.
8769 With a numeric prefix N, construct a sparse tree for the Nth element
8770 of `org-todo-keywords-1'."
8771 (interactive "P")
8772 (let ((case-fold-search nil)
8773 (kwd-re
8774 (cond ((null arg) org-not-done-regexp)
8775 ((equal arg '(4))
8776 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8777 (mapcar 'list org-todo-keywords-1))))
8778 (concat "\\("
8779 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8780 "\\)\\>")))
8781 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8782 (regexp-quote (nth (1- (prefix-numeric-value arg))
8783 org-todo-keywords-1)))
8784 (t (error "Invalid prefix argument: %s" arg)))))
8785 (message "%d TODO entries found"
8786 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8787
8788 (defun org-deadline (&optional remove time)
8789 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8790 With argument REMOVE, remove any deadline from the item.
8791 When TIME is set, it should be an internal time specification, and the
8792 scheduling will use the corresponding date."
8793 (interactive "P")
8794 (if remove
8795 (progn
8796 (org-remove-timestamp-with-keyword org-deadline-string)
8797 (message "Item no longer has a deadline."))
8798 (if (org-get-repeat)
8799 (error "Cannot change deadline on task with repeater, please do that by hand")
8800 (org-add-planning-info 'deadline time 'closed)
8801 (message "Deadline on %s" org-last-inserted-timestamp))))
8802
8803 (defun org-schedule (&optional remove time)
8804 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8805 With argument REMOVE, remove any scheduling date from the item.
8806 When TIME is set, it should be an internal time specification, and the
8807 scheduling will use the corresponding date."
8808 (interactive "P")
8809 (if remove
8810 (progn
8811 (org-remove-timestamp-with-keyword org-scheduled-string)
8812 (message "Item is no longer scheduled."))
8813 (if (org-get-repeat)
8814 (error "Cannot reschedule task with repeater, please do that by hand")
8815 (org-add-planning-info 'scheduled time 'closed)
8816 (message "Scheduled to %s" org-last-inserted-timestamp))))
8817
8818 (defun org-remove-timestamp-with-keyword (keyword)
8819 "Remove all time stamps with KEYWORD in the current entry."
8820 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8821 beg)
8822 (save-excursion
8823 (org-back-to-heading t)
8824 (setq beg (point))
8825 (org-end-of-subtree t t)
8826 (while (re-search-backward re beg t)
8827 (replace-match "")
8828 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8829 (equal (char-before) ?\ ))
8830 (backward-delete-char 1)
8831 (if (string-match "^[ \t]*$" (buffer-substring
8832 (point-at-bol) (point-at-eol)))
8833 (delete-region (point-at-bol)
8834 (min (point-max) (1+ (point-at-eol))))))))))
8835
8836 (defun org-add-planning-info (what &optional time &rest remove)
8837 "Insert new timestamp with keyword in the line directly after the headline.
8838 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8839 If non is given, the user is prompted for a date.
8840 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8841 be removed."
8842 (interactive)
8843 (let (org-time-was-given org-end-time-was-given ts
8844 end default-time default-input)
8845
8846 (when (and (not time) (memq what '(scheduled deadline)))
8847 ;; Try to get a default date/time from existing timestamp
8848 (save-excursion
8849 (org-back-to-heading t)
8850 (setq end (save-excursion (outline-next-heading) (point)))
8851 (when (re-search-forward (if (eq what 'scheduled)
8852 org-scheduled-time-regexp
8853 org-deadline-time-regexp)
8854 end t)
8855 (setq ts (match-string 1)
8856 default-time
8857 (apply 'encode-time (org-parse-time-string ts))
8858 default-input (and ts (org-get-compact-tod ts))))))
8859 (when what
8860 ;; If necessary, get the time from the user
8861 (setq time (or time (org-read-date nil 'to-time nil nil
8862 default-time default-input))))
8863
8864 (when (and org-insert-labeled-timestamps-at-point
8865 (member what '(scheduled deadline)))
8866 (insert
8867 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8868 (org-insert-time-stamp time org-time-was-given
8869 nil nil nil (list org-end-time-was-given))
8870 (setq what nil))
8871 (save-excursion
8872 (save-restriction
8873 (let (col list elt ts buffer-invisibility-spec)
8874 (org-back-to-heading t)
8875 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8876 (goto-char (match-end 1))
8877 (setq col (current-column))
8878 (goto-char (match-end 0))
8879 (if (eobp) (insert "\n") (forward-char 1))
8880 (if (and (not (looking-at outline-regexp))
8881 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8882 "[^\r\n]*"))
8883 (not (equal (match-string 1) org-clock-string)))
8884 (narrow-to-region (match-beginning 0) (match-end 0))
8885 (insert-before-markers "\n")
8886 (backward-char 1)
8887 (narrow-to-region (point) (point))
8888 (and org-adapt-indentation (org-indent-to-column col)))
8889 ;; Check if we have to remove something.
8890 (setq list (cons what remove))
8891 (while list
8892 (setq elt (pop list))
8893 (goto-char (point-min))
8894 (when (or (and (eq elt 'scheduled)
8895 (re-search-forward org-scheduled-time-regexp nil t))
8896 (and (eq elt 'deadline)
8897 (re-search-forward org-deadline-time-regexp nil t))
8898 (and (eq elt 'closed)
8899 (re-search-forward org-closed-time-regexp nil t)))
8900 (replace-match "")
8901 (if (looking-at "--+<[^>]+>") (replace-match ""))
8902 (if (looking-at " +") (replace-match ""))))
8903 (goto-char (point-max))
8904 (when what
8905 (insert
8906 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8907 (cond ((eq what 'scheduled) org-scheduled-string)
8908 ((eq what 'deadline) org-deadline-string)
8909 ((eq what 'closed) org-closed-string))
8910 " ")
8911 (setq ts (org-insert-time-stamp
8912 time
8913 (or org-time-was-given
8914 (and (eq what 'closed) org-log-done-with-time))
8915 (eq what 'closed)
8916 nil nil (list org-end-time-was-given)))
8917 (end-of-line 1))
8918 (goto-char (point-min))
8919 (widen)
8920 (if (and (looking-at "[ \t]+\n")
8921 (equal (char-before) ?\n))
8922 (delete-region (1- (point)) (point-at-eol)))
8923 ts)))))
8924
8925 (defvar org-log-note-marker (make-marker))
8926 (defvar org-log-note-purpose nil)
8927 (defvar org-log-note-state nil)
8928 (defvar org-log-note-how nil)
8929 (defvar org-log-note-extra nil)
8930 (defvar org-log-note-window-configuration nil)
8931 (defvar org-log-note-return-to (make-marker))
8932 (defvar org-log-post-message nil
8933 "Message to be displayed after a log note has been stored.
8934 The auto-repeater uses this.")
8935
8936 (defun org-add-note ()
8937 "Add a note to the current entry.
8938 This is done in the same way as adding a state change note."
8939 (interactive)
8940 (org-add-log-setup 'note nil 'findpos nil))
8941
8942 (defvar org-property-end-re)
8943 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8944 "Set up the post command hook to take a note.
8945 If this is about to TODO state change, the new state is expected in STATE.
8946 When FINDPOS is non-nil, find the correct position for the note in
8947 the current entry. If not, assume that it can be inserted at point.
8948 HOW is an indicator what kind of note should be created.
8949 EXTRA is additional text that will be inserted into the notes buffer."
8950 (save-restriction
8951 (save-excursion
8952 (when findpos
8953 (org-back-to-heading t)
8954 (narrow-to-region (point) (save-excursion
8955 (outline-next-heading) (point)))
8956 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8957 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8958 "[^\r\n]*\\)?"))
8959 (goto-char (match-end 0))
8960 (when (and org-log-state-notes-insert-after-drawers
8961 (save-excursion
8962 (forward-line) (looking-at org-drawer-regexp)))
8963 (progn (forward-line)
8964 (while (looking-at org-drawer-regexp)
8965 (goto-char (match-end 0))
8966 (re-search-forward org-property-end-re (point-max) t)
8967 (forward-line))
8968 (forward-line -1)))
8969 (unless org-log-states-order-reversed
8970 (and (= (char-after) ?\n) (forward-char 1))
8971 (org-skip-over-state-notes)
8972 (skip-chars-backward " \t\n\r")))
8973 (move-marker org-log-note-marker (point))
8974 (setq org-log-note-purpose purpose
8975 org-log-note-state state
8976 org-log-note-how how
8977 org-log-note-extra extra)
8978 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8979
8980 (defun org-skip-over-state-notes ()
8981 "Skip past the list of State notes in an entry."
8982 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8983 (while (looking-at "[ \t]*- State")
8984 (condition-case nil
8985 (org-next-item)
8986 (error (org-end-of-item)))))
8987
8988 (defun org-add-log-note (&optional purpose)
8989 "Pop up a window for taking a note, and add this note later at point."
8990 (remove-hook 'post-command-hook 'org-add-log-note)
8991 (setq org-log-note-window-configuration (current-window-configuration))
8992 (delete-other-windows)
8993 (move-marker org-log-note-return-to (point))
8994 (switch-to-buffer (marker-buffer org-log-note-marker))
8995 (goto-char org-log-note-marker)
8996 (org-switch-to-buffer-other-window "*Org Note*")
8997 (erase-buffer)
8998 (if (memq org-log-note-how '(time state))
8999 (let (current-prefix-arg) (org-store-log-note))
9000 (let ((org-inhibit-startup t)) (org-mode))
9001 (insert (format "# Insert note for %s.
9002 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9003 (cond
9004 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9005 ((eq org-log-note-purpose 'done) "closed todo item")
9006 ((eq org-log-note-purpose 'state)
9007 (format "state change to \"%s\"" org-log-note-state))
9008 ((eq org-log-note-purpose 'note)
9009 "this entry")
9010 (t (error "This should not happen")))))
9011 (if org-log-note-extra (insert org-log-note-extra))
9012 (org-set-local 'org-finish-function 'org-store-log-note)))
9013
9014 (defvar org-note-abort nil) ; dynamically scoped
9015 (defun org-store-log-note ()
9016 "Finish taking a log note, and insert it to where it belongs."
9017 (let ((txt (buffer-string))
9018 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9019 lines ind)
9020 (kill-buffer (current-buffer))
9021 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9022 (setq txt (replace-match "" t t txt)))
9023 (if (string-match "\\s-+\\'" txt)
9024 (setq txt (replace-match "" t t txt)))
9025 (setq lines (org-split-string txt "\n"))
9026 (when (and note (string-match "\\S-" note))
9027 (setq note
9028 (org-replace-escapes
9029 note
9030 (list (cons "%u" (user-login-name))
9031 (cons "%U" user-full-name)
9032 (cons "%t" (format-time-string
9033 (org-time-stamp-format 'long 'inactive)
9034 (current-time)))
9035 (cons "%s" (if org-log-note-state
9036 (concat "\"" org-log-note-state "\"")
9037 "")))))
9038 (if lines (setq note (concat note " \\\\")))
9039 (push note lines))
9040 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9041 (when lines
9042 (save-excursion
9043 (set-buffer (marker-buffer org-log-note-marker))
9044 (save-excursion
9045 (goto-char org-log-note-marker)
9046 (move-marker org-log-note-marker nil)
9047 (end-of-line 1)
9048 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9049 (indent-relative nil)
9050 (insert "- " (pop lines))
9051 (org-indent-line-function)
9052 (beginning-of-line 1)
9053 (looking-at "[ \t]*")
9054 (setq ind (concat (match-string 0) " "))
9055 (end-of-line 1)
9056 (while lines (insert "\n" ind (pop lines)))))))
9057 (set-window-configuration org-log-note-window-configuration)
9058 (with-current-buffer (marker-buffer org-log-note-return-to)
9059 (goto-char org-log-note-return-to))
9060 (move-marker org-log-note-return-to nil)
9061 (and org-log-post-message (message "%s" org-log-post-message)))
9062
9063 (defun org-sparse-tree (&optional arg)
9064 "Create a sparse tree, prompt for the details.
9065 This command can create sparse trees. You first need to select the type
9066 of match used to create the tree:
9067
9068 t Show entries with a specific TODO keyword.
9069 T Show entries selected by a tags match.
9070 p Enter a property name and its value (both with completion on existing
9071 names/values) and show entries with that property.
9072 r Show entries matching a regular expression
9073 d Show deadlines due within `org-deadline-warning-days'."
9074 (interactive "P")
9075 (let (ans kwd value)
9076 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9077 (setq ans (read-char-exclusive))
9078 (cond
9079 ((equal ans ?d)
9080 (call-interactively 'org-check-deadlines))
9081 ((equal ans ?b)
9082 (call-interactively 'org-check-before-date))
9083 ((equal ans ?t)
9084 (org-show-todo-tree '(4)))
9085 ((equal ans ?T)
9086 (call-interactively 'org-tags-sparse-tree))
9087 ((member ans '(?p ?P))
9088 (setq kwd (org-ido-completing-read "Property: "
9089 (mapcar 'list (org-buffer-property-keys))))
9090 (setq value (org-ido-completing-read "Value: "
9091 (mapcar 'list (org-property-values kwd))))
9092 (unless (string-match "\\`{.*}\\'" value)
9093 (setq value (concat "\"" value "\"")))
9094 (org-tags-sparse-tree arg (concat kwd "=" value)))
9095 ((member ans '(?r ?R ?/))
9096 (call-interactively 'org-occur))
9097 (t (error "No such sparse tree command \"%c\"" ans)))))
9098
9099 (defvar org-occur-highlights nil
9100 "List of overlays used for occur matches.")
9101 (make-variable-buffer-local 'org-occur-highlights)
9102 (defvar org-occur-parameters nil
9103 "Parameters of the active org-occur calls.
9104 This is a list, each call to org-occur pushes as cons cell,
9105 containing the regular expression and the callback, onto the list.
9106 The list can contain several entries if `org-occur' has been called
9107 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9108 will only contain one set of parameters. When the highlights are
9109 removed (for example with `C-c C-c', or with the next edit (depending
9110 on `org-remove-highlights-with-change'), this variable is emptied
9111 as well.")
9112 (make-variable-buffer-local 'org-occur-parameters)
9113
9114 (defun org-occur (regexp &optional keep-previous callback)
9115 "Make a compact tree which shows all matches of REGEXP.
9116 The tree will show the lines where the regexp matches, and all higher
9117 headlines above the match. It will also show the heading after the match,
9118 to make sure editing the matching entry is easy.
9119 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9120 call to `org-occur' will be kept, to allow stacking of calls to this
9121 command.
9122 If CALLBACK is non-nil, it is a function which is called to confirm
9123 that the match should indeed be shown."
9124 (interactive "sRegexp: \nP")
9125 (unless keep-previous
9126 (org-remove-occur-highlights nil nil t))
9127 (push (cons regexp callback) org-occur-parameters)
9128 (let ((cnt 0))
9129 (save-excursion
9130 (goto-char (point-min))
9131 (if (or (not keep-previous) ; do not want to keep
9132 (not org-occur-highlights)) ; no previous matches
9133 ;; hide everything
9134 (org-overview))
9135 (while (re-search-forward regexp nil t)
9136 (when (or (not callback)
9137 (save-match-data (funcall callback)))
9138 (setq cnt (1+ cnt))
9139 (when org-highlight-sparse-tree-matches
9140 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9141 (org-show-context 'occur-tree))))
9142 (when org-remove-highlights-with-change
9143 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9144 nil 'local))
9145 (unless org-sparse-tree-open-archived-trees
9146 (org-hide-archived-subtrees (point-min) (point-max)))
9147 (run-hooks 'org-occur-hook)
9148 (if (interactive-p)
9149 (message "%d match(es) for regexp %s" cnt regexp))
9150 cnt))
9151
9152 (defun org-show-context (&optional key)
9153 "Make sure point and context and visible.
9154 How much context is shown depends upon the variables
9155 `org-show-hierarchy-above', `org-show-following-heading'. and
9156 `org-show-siblings'."
9157 (let ((heading-p (org-on-heading-p t))
9158 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9159 (following-p (org-get-alist-option org-show-following-heading key))
9160 (entry-p (org-get-alist-option org-show-entry-below key))
9161 (siblings-p (org-get-alist-option org-show-siblings key)))
9162 (catch 'exit
9163 ;; Show heading or entry text
9164 (if (and heading-p (not entry-p))
9165 (org-flag-heading nil) ; only show the heading
9166 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9167 (org-show-hidden-entry))) ; show entire entry
9168 (when following-p
9169 ;; Show next sibling, or heading below text
9170 (save-excursion
9171 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9172 (org-flag-heading nil))))
9173 (when siblings-p (org-show-siblings))
9174 (when hierarchy-p
9175 ;; show all higher headings, possibly with siblings
9176 (save-excursion
9177 (while (and (condition-case nil
9178 (progn (org-up-heading-all 1) t)
9179 (error nil))
9180 (not (bobp)))
9181 (org-flag-heading nil)
9182 (when siblings-p (org-show-siblings))))))))
9183
9184 (defun org-reveal (&optional siblings)
9185 "Show current entry, hierarchy above it, and the following headline.
9186 This can be used to show a consistent set of context around locations
9187 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9188 not t for the search context.
9189
9190 With optional argument SIBLINGS, on each level of the hierarchy all
9191 siblings are shown. This repairs the tree structure to what it would
9192 look like when opened with hierarchical calls to `org-cycle'."
9193 (interactive "P")
9194 (let ((org-show-hierarchy-above t)
9195 (org-show-following-heading t)
9196 (org-show-siblings (if siblings t org-show-siblings)))
9197 (org-show-context nil)))
9198
9199 (defun org-highlight-new-match (beg end)
9200 "Highlight from BEG to END and mark the highlight is an occur headline."
9201 (let ((ov (org-make-overlay beg end)))
9202 (org-overlay-put ov 'face 'secondary-selection)
9203 (push ov org-occur-highlights)))
9204
9205 (defun org-remove-occur-highlights (&optional beg end noremove)
9206 "Remove the occur highlights from the buffer.
9207 BEG and END are ignored. If NOREMOVE is nil, remove this function
9208 from the `before-change-functions' in the current buffer."
9209 (interactive)
9210 (unless org-inhibit-highlight-removal
9211 (mapc 'org-delete-overlay org-occur-highlights)
9212 (setq org-occur-highlights nil)
9213 (setq org-occur-parameters nil)
9214 (unless noremove
9215 (remove-hook 'before-change-functions
9216 'org-remove-occur-highlights 'local))))
9217
9218 ;;;; Priorities
9219
9220 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9221 "Regular expression matching the priority indicator.")
9222
9223 (defvar org-remove-priority-next-time nil)
9224
9225 (defun org-priority-up ()
9226 "Increase the priority of the current item."
9227 (interactive)
9228 (org-priority 'up))
9229
9230 (defun org-priority-down ()
9231 "Decrease the priority of the current item."
9232 (interactive)
9233 (org-priority 'down))
9234
9235 (defun org-priority (&optional action)
9236 "Change the priority of an item by ARG.
9237 ACTION can be `set', `up', `down', or a character."
9238 (interactive)
9239 (setq action (or action 'set))
9240 (let (current new news have remove)
9241 (save-excursion
9242 (org-back-to-heading)
9243 (if (looking-at org-priority-regexp)
9244 (setq current (string-to-char (match-string 2))
9245 have t)
9246 (setq current org-default-priority))
9247 (cond
9248 ((or (eq action 'set)
9249 (if (featurep 'xemacs) (characterp action) (integerp action)))
9250 (if (not (eq action 'set))
9251 (setq new action)
9252 (message "Priority %c-%c, SPC to remove: "
9253 org-highest-priority org-lowest-priority)
9254 (setq new (read-char-exclusive)))
9255 (if (and (= (upcase org-highest-priority) org-highest-priority)
9256 (= (upcase org-lowest-priority) org-lowest-priority))
9257 (setq new (upcase new)))
9258 (cond ((equal new ?\ ) (setq remove t))
9259 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9260 (error "Priority must be between `%c' and `%c'"
9261 org-highest-priority org-lowest-priority))))
9262 ((eq action 'up)
9263 (if (and (not have) (eq last-command this-command))
9264 (setq new org-lowest-priority)
9265 (setq new (if (and org-priority-start-cycle-with-default (not have))
9266 org-default-priority (1- current)))))
9267 ((eq action 'down)
9268 (if (and (not have) (eq last-command this-command))
9269 (setq new org-highest-priority)
9270 (setq new (if (and org-priority-start-cycle-with-default (not have))
9271 org-default-priority (1+ current)))))
9272 (t (error "Invalid action")))
9273 (if (or (< (upcase new) org-highest-priority)
9274 (> (upcase new) org-lowest-priority))
9275 (setq remove t))
9276 (setq news (format "%c" new))
9277 (if have
9278 (if remove
9279 (replace-match "" t t nil 1)
9280 (replace-match news t t nil 2))
9281 (if remove
9282 (error "No priority cookie found in line")
9283 (looking-at org-todo-line-regexp)
9284 (if (match-end 2)
9285 (progn
9286 (goto-char (match-end 2))
9287 (insert " [#" news "]"))
9288 (goto-char (match-beginning 3))
9289 (insert "[#" news "] ")))))
9290 (org-preserve-lc (org-set-tags nil 'align))
9291 (if remove
9292 (message "Priority removed")
9293 (message "Priority of current item set to %s" news))))
9294
9295
9296 (defun org-get-priority (s)
9297 "Find priority cookie and return priority."
9298 (save-match-data
9299 (if (not (string-match org-priority-regexp s))
9300 (* 1000 (- org-lowest-priority org-default-priority))
9301 (* 1000 (- org-lowest-priority
9302 (string-to-char (match-string 2 s)))))))
9303
9304 ;;;; Tags
9305
9306 (defvar org-agenda-archives-mode)
9307 (defun org-scan-tags (action matcher &optional todo-only)
9308 "Scan headline tags with inheritance and produce output ACTION.
9309
9310 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9311 or `agenda' to produce an entry list for an agenda view. It can also be
9312 a Lisp form or a function that should be called at each matched headline, in
9313 this case the return value is a list of all return values from these calls.
9314
9315 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9316 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9317 only lines with a TODO keyword are included in the output."
9318 (require 'org-agenda)
9319 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9320 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9321 (org-re
9322 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9323 (props (list 'face 'default
9324 'done-face 'org-done
9325 'undone-face 'default
9326 'mouse-face 'highlight
9327 'org-not-done-regexp org-not-done-regexp
9328 'org-todo-regexp org-todo-regexp
9329 'keymap org-agenda-keymap
9330 'help-echo
9331 (format "mouse-2 or RET jump to org file %s"
9332 (abbreviate-file-name
9333 (or (buffer-file-name (buffer-base-buffer))
9334 (buffer-name (buffer-base-buffer)))))))
9335 (case-fold-search nil)
9336 lspos tags tags-list
9337 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9338 (llast 0) rtn rtn1 level category i txt
9339 todo marker entry priority)
9340 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9341 (setq action (list 'lambda nil action)))
9342 (save-excursion
9343 (goto-char (point-min))
9344 (when (eq action 'sparse-tree)
9345 (org-overview)
9346 (org-remove-occur-highlights))
9347 (while (re-search-forward re nil t)
9348 (catch :skip
9349 (setq todo (if (match-end 1) (match-string 2))
9350 tags (if (match-end 4) (match-string 4)))
9351 (goto-char (setq lspos (1+ (match-beginning 0))))
9352 (setq level (org-reduced-level (funcall outline-level))
9353 category (org-get-category))
9354 (setq i llast llast level)
9355 ;; remove tag lists from same and sublevels
9356 (while (>= i level)
9357 (when (setq entry (assoc i tags-alist))
9358 (setq tags-alist (delete entry tags-alist)))
9359 (setq i (1- i)))
9360 ;; add the next tags
9361 (when tags
9362 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9363 tags-alist
9364 (cons (cons level tags) tags-alist)))
9365 ;; compile tags for current headline
9366 (setq tags-list
9367 (if org-use-tag-inheritance
9368 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9369 tags))
9370 (when org-use-tag-inheritance
9371 (setcdr (car tags-alist)
9372 (mapcar (lambda (x)
9373 (setq x (copy-sequence x))
9374 (org-add-prop-inherited x))
9375 (cdar tags-alist))))
9376 (when (and tags org-use-tag-inheritance
9377 (not (eq t org-use-tag-inheritance)))
9378 ;; selective inheritance, remove uninherited ones
9379 (setcdr (car tags-alist)
9380 (org-remove-uniherited-tags (cdar tags-alist))))
9381 (when (and (or (not todo-only)
9382 (and (member todo org-not-done-keywords)
9383 (or (not org-agenda-tags-todo-honor-ignore-options)
9384 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9385 (let ((case-fold-search t)) (eval matcher))
9386 (or
9387 (not (member org-archive-tag tags-list))
9388 ;; we have an archive tag, should we use this anyway?
9389 (or (not org-agenda-skip-archived-trees)
9390 (and (eq action 'agenda) org-agenda-archives-mode))))
9391 (unless (eq action 'sparse-tree) (org-agenda-skip))
9392
9393 ;; select this headline
9394
9395 (cond
9396 ((eq action 'sparse-tree)
9397 (and org-highlight-sparse-tree-matches
9398 (org-get-heading) (match-end 0)
9399 (org-highlight-new-match
9400 (match-beginning 0) (match-beginning 1)))
9401 (org-show-context 'tags-tree))
9402 ((eq action 'agenda)
9403 (setq txt (org-format-agenda-item
9404 ""
9405 (concat
9406 (if org-tags-match-list-sublevels
9407 (make-string (1- level) ?.) "")
9408 (org-get-heading))
9409 category (org-get-tags-at))
9410 priority (org-get-priority txt))
9411 (goto-char lspos)
9412 (setq marker (org-agenda-new-marker))
9413 (org-add-props txt props
9414 'org-marker marker 'org-hd-marker marker 'org-category category
9415 'priority priority 'type "tagsmatch")
9416 (push txt rtn))
9417 ((functionp action)
9418 (save-excursion
9419 (setq rtn1 (funcall action))
9420 (push rtn1 rtn))
9421 (goto-char (point-at-eol)))
9422 (t (error "Invalid action")))
9423
9424 ;; if we are to skip sublevels, jump to end of subtree
9425 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9426 (when (and (eq action 'sparse-tree)
9427 (not org-sparse-tree-open-archived-trees))
9428 (org-hide-archived-subtrees (point-min) (point-max)))
9429 (nreverse rtn)))
9430
9431 (defun org-remove-uniherited-tags (tags)
9432 "Remove all tags that are not inherited from the list TAGS."
9433 (cond
9434 ((eq org-use-tag-inheritance t)
9435 (if org-tags-exclude-from-inheritance
9436 (org-delete-all org-tags-exclude-from-inheritance tags)
9437 tags))
9438 ((not org-use-tag-inheritance) nil)
9439 ((stringp org-use-tag-inheritance)
9440 (delq nil (mapcar
9441 (lambda (x)
9442 (if (and (string-match org-use-tag-inheritance x)
9443 (not (member x org-tags-exclude-from-inheritance)))
9444 x nil))
9445 tags)))
9446 ((listp org-use-tag-inheritance)
9447 (delq nil (mapcar
9448 (lambda (x)
9449 (if (member x org-use-tag-inheritance) x nil))
9450 tags)))))
9451
9452 (defvar todo-only) ;; dynamically scoped
9453
9454 (defun org-tags-sparse-tree (&optional todo-only match)
9455 "Create a sparse tree according to tags string MATCH.
9456 MATCH can contain positive and negative selection of tags, like
9457 \"+WORK+URGENT-WITHBOSS\".
9458 If optional argument TODO-ONLY is non-nil, only select lines that are
9459 also TODO lines."
9460 (interactive "P")
9461 (org-prepare-agenda-buffers (list (current-buffer)))
9462 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9463
9464 (defvar org-cached-props nil)
9465 (defun org-cached-entry-get (pom property)
9466 (if (or (eq t org-use-property-inheritance)
9467 (and (stringp org-use-property-inheritance)
9468 (string-match org-use-property-inheritance property))
9469 (and (listp org-use-property-inheritance)
9470 (member property org-use-property-inheritance)))
9471 ;; Caching is not possible, check it directly
9472 (org-entry-get pom property 'inherit)
9473 ;; Get all properties, so that we can do complicated checks easily
9474 (cdr (assoc property (or org-cached-props
9475 (setq org-cached-props
9476 (org-entry-properties pom)))))))
9477
9478 (defun org-global-tags-completion-table (&optional files)
9479 "Return the list of all tags in all agenda buffer/files."
9480 (save-excursion
9481 (org-uniquify
9482 (delq nil
9483 (apply 'append
9484 (mapcar
9485 (lambda (file)
9486 (set-buffer (find-file-noselect file))
9487 (append (org-get-buffer-tags)
9488 (mapcar (lambda (x) (if (stringp (car-safe x))
9489 (list (car-safe x)) nil))
9490 org-tag-alist)))
9491 (if (and files (car files))
9492 files
9493 (org-agenda-files))))))))
9494
9495 (defun org-make-tags-matcher (match)
9496 "Create the TAGS//TODO matcher form for the selection string MATCH."
9497 ;; todo-only is scoped dynamically into this function, and the function
9498 ;; may change it if the matcher asks for it.
9499 (unless match
9500 ;; Get a new match request, with completion
9501 (let ((org-last-tags-completion-table
9502 (org-global-tags-completion-table)))
9503 (setq match (org-completing-read
9504 "Match: " 'org-tags-completion-function nil nil nil
9505 'org-tags-history))))
9506
9507 ;; Parse the string and create a lisp form
9508 (let ((match0 match)
9509 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9510 minus tag mm
9511 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9512 orterms term orlist re-p str-p level-p level-op time-p
9513 prop-p pn pv po cat-p gv rest)
9514 (if (string-match "/+" match)
9515 ;; match contains also a todo-matching request
9516 (progn
9517 (setq tagsmatch (substring match 0 (match-beginning 0))
9518 todomatch (substring match (match-end 0)))
9519 (if (string-match "^!" todomatch)
9520 (setq todo-only t todomatch (substring todomatch 1)))
9521 (if (string-match "^\\s-*$" todomatch)
9522 (setq todomatch nil)))
9523 ;; only matching tags
9524 (setq tagsmatch match todomatch nil))
9525
9526 ;; Make the tags matcher
9527 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9528 (setq tagsmatcher t)
9529 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9530 (while (setq term (pop orterms))
9531 (while (and (equal (substring term -1) "\\") orterms)
9532 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9533 (while (string-match re term)
9534 (setq rest (substring term (match-end 0))
9535 minus (and (match-end 1)
9536 (equal (match-string 1 term) "-"))
9537 tag (match-string 2 term)
9538 re-p (equal (string-to-char tag) ?{)
9539 level-p (match-end 4)
9540 prop-p (match-end 5)
9541 mm (cond
9542 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9543 (level-p
9544 (setq level-op (org-op-to-function (match-string 3 term)))
9545 `(,level-op level ,(string-to-number
9546 (match-string 4 term))))
9547 (prop-p
9548 (setq pn (match-string 5 term)
9549 po (match-string 6 term)
9550 pv (match-string 7 term)
9551 cat-p (equal pn "CATEGORY")
9552 re-p (equal (string-to-char pv) ?{)
9553 str-p (equal (string-to-char pv) ?\")
9554 time-p (save-match-data
9555 (string-match "^\"[[<].*[]>]\"$" pv))
9556 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9557 (if time-p (setq pv (org-matcher-time pv)))
9558 (setq po (org-op-to-function po (if time-p 'time str-p)))
9559 (cond
9560 ((equal pn "CATEGORY")
9561 (setq gv '(get-text-property (point) 'org-category)))
9562 ((equal pn "TODO")
9563 (setq gv 'todo))
9564 (t
9565 (setq gv `(org-cached-entry-get nil ,pn))))
9566 (if re-p
9567 (if (eq po 'org<>)
9568 `(not (string-match ,pv (or ,gv "")))
9569 `(string-match ,pv (or ,gv "")))
9570 (if str-p
9571 `(,po (or ,gv "") ,pv)
9572 `(,po (string-to-number (or ,gv ""))
9573 ,(string-to-number pv) ))))
9574 (t `(member ,(downcase tag) tags-list)))
9575 mm (if minus (list 'not mm) mm)
9576 term rest)
9577 (push mm tagsmatcher))
9578 (push (if (> (length tagsmatcher) 1)
9579 (cons 'and tagsmatcher)
9580 (car tagsmatcher))
9581 orlist)
9582 (setq tagsmatcher nil))
9583 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9584 (setq tagsmatcher
9585 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9586 ;; Make the todo matcher
9587 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9588 (setq todomatcher t)
9589 (setq orterms (org-split-string todomatch "|") orlist nil)
9590 (while (setq term (pop orterms))
9591 (while (string-match re term)
9592 (setq minus (and (match-end 1)
9593 (equal (match-string 1 term) "-"))
9594 kwd (match-string 2 term)
9595 re-p (equal (string-to-char kwd) ?{)
9596 term (substring term (match-end 0))
9597 mm (if re-p
9598 `(string-match ,(substring kwd 1 -1) todo)
9599 (list 'equal 'todo kwd))
9600 mm (if minus (list 'not mm) mm))
9601 (push mm todomatcher))
9602 (push (if (> (length todomatcher) 1)
9603 (cons 'and todomatcher)
9604 (car todomatcher))
9605 orlist)
9606 (setq todomatcher nil))
9607 (setq todomatcher (if (> (length orlist) 1)
9608 (cons 'or orlist) (car orlist))))
9609
9610 ;; Return the string and lisp forms of the matcher
9611 (setq matcher (if todomatcher
9612 (list 'and tagsmatcher todomatcher)
9613 tagsmatcher))
9614 (cons match0 matcher)))
9615
9616 (defun org-op-to-function (op &optional stringp)
9617 "Turn an operator into the appropriate function."
9618 (setq op
9619 (cond
9620 ((equal op "<" ) '(< string< org-time<))
9621 ((equal op ">" ) '(> org-string> org-time>))
9622 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9623 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9624 ((member op '("=" "==")) '(= string= org-time=))
9625 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9626 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9627
9628 (defun org<> (a b) (not (= a b)))
9629 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9630 (defun org-string>= (a b) (not (string< a b)))
9631 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9632 (defun org-string<> (a b) (not (string= a b)))
9633 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
9634 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
9635 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
9636 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
9637 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
9638 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
9639 (defun org-2ft (s)
9640 "Convert S to a floating point time.
9641 If S is already a number, just return it. If it is a string, parse
9642 it as a time string and apply `float-time' to it. If S is nil, just return 0."
9643 (cond
9644 ((numberp s) s)
9645 ((stringp s)
9646 (condition-case nil
9647 (float-time (apply 'encode-time (org-parse-time-string s)))
9648 (error 0.)))
9649 (t 0.)))
9650
9651 (defun org-time-today ()
9652 "Time in seconds today at 0:00.
9653 Returns the float number of seconds since the beginning of the
9654 epoch to the beginning of today (00:00)."
9655 (float-time (apply 'encode-time
9656 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9657
9658 (defun org-matcher-time (s)
9659 "Interpret a time comparison value."
9660 (save-match-data
9661 (cond
9662 ((string= s "<now>") (float-time))
9663 ((string= s "<today>") (org-time-today))
9664 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9665 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9666 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9667 (+ (org-time-today)
9668 (* (string-to-number (match-string 1 s))
9669 (cdr (assoc (match-string 2 s)
9670 '(("d" . 86400.0) ("w" . 604800.0)
9671 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9672 (t (org-2ft s)))))
9673
9674 (defun org-match-any-p (re list)
9675 "Does re match any element of list?"
9676 (setq list (mapcar (lambda (x) (string-match re x)) list))
9677 (delq nil list))
9678
9679 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9680 (defvar org-tags-overlay (org-make-overlay 1 1))
9681 (org-detach-overlay org-tags-overlay)
9682
9683 (defun org-get-local-tags-at (&optional pos)
9684 "Get a list of tags defined in the current headline."
9685 (org-get-tags-at pos 'local))
9686
9687 (defun org-get-local-tags ()
9688 "Get a list of tags defined in the current headline."
9689 (org-get-tags-at nil 'local))
9690
9691 (defun org-get-tags-at (&optional pos local)
9692 "Get a list of all headline tags applicable at POS.
9693 POS defaults to point. If tags are inherited, the list contains
9694 the targets in the same sequence as the headlines appear, i.e.
9695 the tags of the current headline come last.
9696 When LOCAL is non-nil, only return tags from the current headline,
9697 ignore inherited ones."
9698 (interactive)
9699 (let (tags ltags lastpos parent)
9700 (save-excursion
9701 (save-restriction
9702 (widen)
9703 (goto-char (or pos (point)))
9704 (save-match-data
9705 (catch 'done
9706 (condition-case nil
9707 (progn
9708 (org-back-to-heading t)
9709 (while (not (equal lastpos (point)))
9710 (setq lastpos (point))
9711 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9712 (setq ltags (org-split-string
9713 (org-match-string-no-properties 1) ":"))
9714 (when parent
9715 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9716 (setq tags (append
9717 (if parent
9718 (org-remove-uniherited-tags ltags)
9719 ltags)
9720 tags)))
9721 (or org-use-tag-inheritance (throw 'done t))
9722 (if local (throw 'done t))
9723 (org-up-heading-all 1)
9724 (setq parent t)))
9725 (error nil)))))
9726 (append (org-remove-uniherited-tags org-file-tags) tags))))
9727
9728 (defun org-add-prop-inherited (s)
9729 (add-text-properties 0 (length s) '(inherited t) s)
9730 s)
9731
9732 (defun org-toggle-tag (tag &optional onoff)
9733 "Toggle the tag TAG for the current line.
9734 If ONOFF is `on' or `off', don't toggle but set to this state."
9735 (let (res current)
9736 (save-excursion
9737 (org-back-to-heading t)
9738 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9739 (point-at-eol) t)
9740 (progn
9741 (setq current (match-string 1))
9742 (replace-match ""))
9743 (setq current ""))
9744 (setq current (nreverse (org-split-string current ":")))
9745 (cond
9746 ((eq onoff 'on)
9747 (setq res t)
9748 (or (member tag current) (push tag current)))
9749 ((eq onoff 'off)
9750 (or (not (member tag current)) (setq current (delete tag current))))
9751 (t (if (member tag current)
9752 (setq current (delete tag current))
9753 (setq res t)
9754 (push tag current))))
9755 (end-of-line 1)
9756 (if current
9757 (progn
9758 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9759 (org-set-tags nil t))
9760 (delete-horizontal-space))
9761 (run-hooks 'org-after-tags-change-hook))
9762 res))
9763
9764 (defun org-align-tags-here (to-col)
9765 ;; Assumes that this is a headline
9766 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9767 (beginning-of-line 1)
9768 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9769 (< pos (match-beginning 2)))
9770 (progn
9771 (setq tags-l (- (match-end 2) (match-beginning 2)))
9772 (goto-char (match-beginning 1))
9773 (insert " ")
9774 (delete-region (point) (1+ (match-beginning 2)))
9775 (setq ncol (max (1+ (current-column))
9776 (1+ col)
9777 (if (> to-col 0)
9778 to-col
9779 (- (abs to-col) tags-l))))
9780 (setq p (point))
9781 (insert (make-string (- ncol (current-column)) ?\ ))
9782 (setq ncol (current-column))
9783 (when indent-tabs-mode (tabify p (point-at-eol)))
9784 (org-move-to-column (min ncol col) t))
9785 (goto-char pos))))
9786
9787 (defun org-set-tags-command (&optional arg just-align)
9788 "Call the set-tags command for the current entry."
9789 (interactive "P")
9790 (if (org-on-heading-p)
9791 (org-set-tags arg just-align)
9792 (save-excursion
9793 (org-back-to-heading t)
9794 (org-set-tags arg just-align))))
9795
9796 (defun org-set-tags (&optional arg just-align)
9797 "Set the tags for the current headline.
9798 With prefix ARG, realign all tags in headings in the current buffer."
9799 (interactive "P")
9800 (let* ((re (concat "^" outline-regexp))
9801 (current (org-get-tags-string))
9802 (col (current-column))
9803 (org-setting-tags t)
9804 table current-tags inherited-tags ; computed below when needed
9805 tags p0 c0 c1 rpl)
9806 (if arg
9807 (save-excursion
9808 (goto-char (point-min))
9809 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9810 (while (re-search-forward re nil t)
9811 (org-set-tags nil t)
9812 (end-of-line 1)))
9813 (message "All tags realigned to column %d" org-tags-column))
9814 (if just-align
9815 (setq tags current)
9816 ;; Get a new set of tags from the user
9817 (save-excursion
9818 (setq table (or org-tag-alist (org-get-buffer-tags))
9819 org-last-tags-completion-table table
9820 current-tags (org-split-string current ":")
9821 inherited-tags (nreverse
9822 (nthcdr (length current-tags)
9823 (nreverse (org-get-tags-at))))
9824 tags
9825 (if (or (eq t org-use-fast-tag-selection)
9826 (and org-use-fast-tag-selection
9827 (delq nil (mapcar 'cdr table))))
9828 (org-fast-tag-selection
9829 current-tags inherited-tags table
9830 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9831 (let ((org-add-colon-after-tag-completion t))
9832 (org-trim
9833 (org-without-partial-completion
9834 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9835 nil nil current 'org-tags-history)))))))
9836 (while (string-match "[-+&]+" tags)
9837 ;; No boolean logic, just a list
9838 (setq tags (replace-match ":" t t tags))))
9839
9840 (if (string-match "\\`[\t ]*\\'" tags)
9841 (setq tags "")
9842 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9843 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9844
9845 ;; Insert new tags at the correct column
9846 (beginning-of-line 1)
9847 (cond
9848 ((and (equal current "") (equal tags "")))
9849 ((re-search-forward
9850 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9851 (point-at-eol) t)
9852 (if (equal tags "")
9853 (setq rpl "")
9854 (goto-char (match-beginning 0))
9855 (setq c0 (current-column) p0 (point)
9856 c1 (max (1+ c0) (if (> org-tags-column 0)
9857 org-tags-column
9858 (- (- org-tags-column) (length tags))))
9859 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9860 (replace-match rpl t t)
9861 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9862 tags)
9863 (t (error "Tags alignment failed")))
9864 (org-move-to-column col)
9865 (unless just-align
9866 (run-hooks 'org-after-tags-change-hook)))))
9867
9868 (defun org-change-tag-in-region (beg end tag off)
9869 "Add or remove TAG for each entry in the region.
9870 This works in the agenda, and also in an org-mode buffer."
9871 (interactive
9872 (list (region-beginning) (region-end)
9873 (let ((org-last-tags-completion-table
9874 (if (org-mode-p)
9875 (org-get-buffer-tags)
9876 (org-global-tags-completion-table))))
9877 (org-ido-completing-read
9878 "Tag: " 'org-tags-completion-function nil nil nil
9879 'org-tags-history))
9880 (progn
9881 (message "[s]et or [r]emove? ")
9882 (equal (read-char-exclusive) ?r))))
9883 (if (fboundp 'deactivate-mark) (deactivate-mark))
9884 (let ((agendap (equal major-mode 'org-agenda-mode))
9885 l1 l2 m buf pos newhead (cnt 0))
9886 (goto-char end)
9887 (setq l2 (1- (org-current-line)))
9888 (goto-char beg)
9889 (setq l1 (org-current-line))
9890 (loop for l from l1 to l2 do
9891 (goto-line l)
9892 (setq m (get-text-property (point) 'org-hd-marker))
9893 (when (or (and (org-mode-p) (org-on-heading-p))
9894 (and agendap m))
9895 (setq buf (if agendap (marker-buffer m) (current-buffer))
9896 pos (if agendap m (point)))
9897 (with-current-buffer buf
9898 (save-excursion
9899 (save-restriction
9900 (goto-char pos)
9901 (setq cnt (1+ cnt))
9902 (org-toggle-tag tag (if off 'off 'on))
9903 (setq newhead (org-get-heading)))))
9904 (and agendap (org-agenda-change-all-lines newhead m))))
9905 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9906
9907 (defun org-tags-completion-function (string predicate &optional flag)
9908 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9909 (confirm (lambda (x) (stringp (car x)))))
9910 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9911 (setq s1 (match-string 1 string)
9912 s2 (match-string 2 string))
9913 (setq s1 "" s2 string))
9914 (cond
9915 ((eq flag nil)
9916 ;; try completion
9917 (setq rtn (try-completion s2 ctable confirm))
9918 (if (stringp rtn)
9919 (setq rtn
9920 (concat s1 s2 (substring rtn (length s2))
9921 (if (and org-add-colon-after-tag-completion
9922 (assoc rtn ctable))
9923 ":" ""))))
9924 rtn)
9925 ((eq flag t)
9926 ;; all-completions
9927 (all-completions s2 ctable confirm)
9928 )
9929 ((eq flag 'lambda)
9930 ;; exact match?
9931 (assoc s2 ctable)))
9932 ))
9933
9934 (defun org-fast-tag-insert (kwd tags face &optional end)
9935 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
9936 (insert (format "%-12s" (concat kwd ":"))
9937 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9938 (or end "")))
9939
9940 (defun org-fast-tag-show-exit (flag)
9941 (save-excursion
9942 (goto-line 3)
9943 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9944 (replace-match ""))
9945 (when flag
9946 (end-of-line 1)
9947 (org-move-to-column (- (window-width) 19) t)
9948 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9949
9950 (defun org-set-current-tags-overlay (current prefix)
9951 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9952 (if (featurep 'xemacs)
9953 (org-overlay-display org-tags-overlay (concat prefix s)
9954 'secondary-selection)
9955 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9956 (org-overlay-display org-tags-overlay (concat prefix s)))))
9957
9958 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9959 "Fast tag selection with single keys.
9960 CURRENT is the current list of tags in the headline, INHERITED is the
9961 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9962 possibly with grouping information. TODO-TABLE is a similar table with
9963 TODO keywords, should these have keys assigned to them.
9964 If the keys are nil, a-z are automatically assigned.
9965 Returns the new tags string, or nil to not change the current settings."
9966 (let* ((fulltable (append table todo-table))
9967 (maxlen (apply 'max (mapcar
9968 (lambda (x)
9969 (if (stringp (car x)) (string-width (car x)) 0))
9970 fulltable)))
9971 (buf (current-buffer))
9972 (expert (eq org-fast-tag-selection-single-key 'expert))
9973 (buffer-tags nil)
9974 (fwidth (+ maxlen 3 1 3))
9975 (ncol (/ (- (window-width) 4) fwidth))
9976 (i-face 'org-done)
9977 (c-face 'org-todo)
9978 tg cnt e c char c1 c2 ntable tbl rtn
9979 ov-start ov-end ov-prefix
9980 (exit-after-next org-fast-tag-selection-single-key)
9981 (done-keywords org-done-keywords)
9982 groups ingroup)
9983 (save-excursion
9984 (beginning-of-line 1)
9985 (if (looking-at
9986 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9987 (setq ov-start (match-beginning 1)
9988 ov-end (match-end 1)
9989 ov-prefix "")
9990 (setq ov-start (1- (point-at-eol))
9991 ov-end (1+ ov-start))
9992 (skip-chars-forward "^\n\r")
9993 (setq ov-prefix
9994 (concat
9995 (buffer-substring (1- (point)) (point))
9996 (if (> (current-column) org-tags-column)
9997 " "
9998 (make-string (- org-tags-column (current-column)) ?\ ))))))
9999 (org-move-overlay org-tags-overlay ov-start ov-end)
10000 (save-window-excursion
10001 (if expert
10002 (set-buffer (get-buffer-create " *Org tags*"))
10003 (delete-other-windows)
10004 (split-window-vertically)
10005 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10006 (erase-buffer)
10007 (org-set-local 'org-done-keywords done-keywords)
10008 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10009 (org-fast-tag-insert "Current" current c-face "\n\n")
10010 (org-fast-tag-show-exit exit-after-next)
10011 (org-set-current-tags-overlay current ov-prefix)
10012 (setq tbl fulltable char ?a cnt 0)
10013 (while (setq e (pop tbl))
10014 (cond
10015 ((equal e '(:startgroup))
10016 (push '() groups) (setq ingroup t)
10017 (when (not (= cnt 0))
10018 (setq cnt 0)
10019 (insert "\n"))
10020 (insert "{ "))
10021 ((equal e '(:endgroup))
10022 (setq ingroup nil cnt 0)
10023 (insert "}\n"))
10024 (t
10025 (setq tg (car e) c2 nil)
10026 (if (cdr e)
10027 (setq c (cdr e))
10028 ;; automatically assign a character.
10029 (setq c1 (string-to-char
10030 (downcase (substring
10031 tg (if (= (string-to-char tg) ?@) 1 0)))))
10032 (if (or (rassoc c1 ntable) (rassoc c1 table))
10033 (while (or (rassoc char ntable) (rassoc char table))
10034 (setq char (1+ char)))
10035 (setq c2 c1))
10036 (setq c (or c2 char)))
10037 (if ingroup (push tg (car groups)))
10038 (setq tg (org-add-props tg nil 'face
10039 (cond
10040 ((not (assoc tg table))
10041 (org-get-todo-face tg))
10042 ((member tg current) c-face)
10043 ((member tg inherited) i-face)
10044 (t nil))))
10045 (if (and (= cnt 0) (not ingroup)) (insert " "))
10046 (insert "[" c "] " tg (make-string
10047 (- fwidth 4 (length tg)) ?\ ))
10048 (push (cons tg c) ntable)
10049 (when (= (setq cnt (1+ cnt)) ncol)
10050 (insert "\n")
10051 (if ingroup (insert " "))
10052 (setq cnt 0)))))
10053 (setq ntable (nreverse ntable))
10054 (insert "\n")
10055 (goto-char (point-min))
10056 (if (not expert) (org-fit-window-to-buffer))
10057 (setq rtn
10058 (catch 'exit
10059 (while t
10060 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10061 (if groups " [!] no groups" " [!]groups")
10062 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10063 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10064 (cond
10065 ((= c ?\r) (throw 'exit t))
10066 ((= c ?!)
10067 (setq groups (not groups))
10068 (goto-char (point-min))
10069 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10070 ((= c ?\C-c)
10071 (if (not expert)
10072 (org-fast-tag-show-exit
10073 (setq exit-after-next (not exit-after-next)))
10074 (setq expert nil)
10075 (delete-other-windows)
10076 (split-window-vertically)
10077 (org-switch-to-buffer-other-window " *Org tags*")
10078 (org-fit-window-to-buffer)))
10079 ((or (= c ?\C-g)
10080 (and (= c ?q) (not (rassoc c ntable))))
10081 (org-detach-overlay org-tags-overlay)
10082 (setq quit-flag t))
10083 ((= c ?\ )
10084 (setq current nil)
10085 (if exit-after-next (setq exit-after-next 'now)))
10086 ((= c ?\t)
10087 (condition-case nil
10088 (setq tg (org-ido-completing-read
10089 "Tag: "
10090 (or buffer-tags
10091 (with-current-buffer buf
10092 (org-get-buffer-tags)))))
10093 (quit (setq tg "")))
10094 (when (string-match "\\S-" tg)
10095 (add-to-list 'buffer-tags (list tg))
10096 (if (member tg current)
10097 (setq current (delete tg current))
10098 (push tg current)))
10099 (if exit-after-next (setq exit-after-next 'now)))
10100 ((setq e (rassoc c todo-table) tg (car e))
10101 (with-current-buffer buf
10102 (save-excursion (org-todo tg)))
10103 (if exit-after-next (setq exit-after-next 'now)))
10104 ((setq e (rassoc c ntable) tg (car e))
10105 (if (member tg current)
10106 (setq current (delete tg current))
10107 (loop for g in groups do
10108 (if (member tg g)
10109 (mapc (lambda (x)
10110 (setq current (delete x current)))
10111 g)))
10112 (push tg current))
10113 (if exit-after-next (setq exit-after-next 'now))))
10114
10115 ;; Create a sorted list
10116 (setq current
10117 (sort current
10118 (lambda (a b)
10119 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10120 (if (eq exit-after-next 'now) (throw 'exit t))
10121 (goto-char (point-min))
10122 (beginning-of-line 2)
10123 (delete-region (point) (point-at-eol))
10124 (org-fast-tag-insert "Current" current c-face)
10125 (org-set-current-tags-overlay current ov-prefix)
10126 (while (re-search-forward
10127 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10128 (setq tg (match-string 1))
10129 (add-text-properties
10130 (match-beginning 1) (match-end 1)
10131 (list 'face
10132 (cond
10133 ((member tg current) c-face)
10134 ((member tg inherited) i-face)
10135 (t (get-text-property (match-beginning 1) 'face))))))
10136 (goto-char (point-min)))))
10137 (org-detach-overlay org-tags-overlay)
10138 (if rtn
10139 (mapconcat 'identity current ":")
10140 nil))))
10141
10142 (defun org-get-tags-string ()
10143 "Get the TAGS string in the current headline."
10144 (unless (org-on-heading-p t)
10145 (error "Not on a heading"))
10146 (save-excursion
10147 (beginning-of-line 1)
10148 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10149 (org-match-string-no-properties 1)
10150 "")))
10151
10152 (defun org-get-tags ()
10153 "Get the list of tags specified in the current headline."
10154 (org-split-string (org-get-tags-string) ":"))
10155
10156 (defun org-get-buffer-tags ()
10157 "Get a table of all tags used in the buffer, for completion."
10158 (let (tags)
10159 (save-excursion
10160 (goto-char (point-min))
10161 (while (re-search-forward
10162 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10163 (when (equal (char-after (point-at-bol 0)) ?*)
10164 (mapc (lambda (x) (add-to-list 'tags x))
10165 (org-split-string (org-match-string-no-properties 1) ":")))))
10166 (mapcar 'list tags)))
10167
10168 ;;;; The mapping API
10169
10170 ;;;###autoload
10171 (defun org-map-entries (func &optional match scope &rest skip)
10172 "Call FUNC at each headline selected by MATCH in SCOPE.
10173
10174 FUNC is a function or a lisp form. The function will be called without
10175 arguments, with the cursor positioned at the beginning of the headline.
10176 The return values of all calls to the function will be collected and
10177 returned as a list.
10178
10179 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10180 Only headlines that are matched by this query will be considered during
10181 the iteration. When MATCH is nil or t, all headlines will be
10182 visited by the iteration.
10183
10184 SCOPE determines the scope of this command. It can be any of:
10185
10186 nil The current buffer, respecting the restriction if any
10187 tree The subtree started with the entry at point
10188 file The current buffer, without restriction
10189 file-with-archives
10190 The current buffer, and any archives associated with it
10191 agenda All agenda files
10192 agenda-with-archives
10193 All agenda files with any archive files associated with them
10194 \(file1 file2 ...)
10195 If this is a list, all files in the list will be scanned
10196
10197 The remaining args are treated as settings for the skipping facilities of
10198 the scanner. The following items can be given here:
10199
10200 archive skip trees with the archive tag.
10201 comment skip trees with the COMMENT keyword
10202 function or Emacs Lisp form:
10203 will be used as value for `org-agenda-skip-function', so whenever
10204 the the function returns t, FUNC will not be called for that
10205 entry and search will continue from the point where the
10206 function leaves it."
10207 (let* ((org-agenda-archives-mode nil) ; just to make sure
10208 (org-agenda-skip-archived-trees (memq 'archive skip))
10209 (org-agenda-skip-comment-trees (memq 'comment skip))
10210 (org-agenda-skip-function
10211 (car (org-delete-all '(comment archive) skip)))
10212 (org-tags-match-list-sublevels t)
10213 matcher file res
10214 org-todo-keywords-for-agenda
10215 org-done-keywords-for-agenda
10216 org-todo-keyword-alist-for-agenda
10217 org-tag-alist-for-agenda)
10218
10219 (cond
10220 ((eq match t) (setq matcher t))
10221 ((eq match nil) (setq matcher t))
10222 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10223
10224 (save-excursion
10225 (save-restriction
10226 (when (eq scope 'tree)
10227 (org-back-to-heading t)
10228 (org-narrow-to-subtree)
10229 (setq scope nil))
10230
10231 (if (not scope)
10232 (progn
10233 (org-prepare-agenda-buffers
10234 (list (buffer-file-name (current-buffer))))
10235 (setq res (org-scan-tags func matcher)))
10236 ;; Get the right scope
10237 (cond
10238 ((and scope (listp scope) (symbolp (car scope)))
10239 (setq scope (eval scope)))
10240 ((eq scope 'agenda)
10241 (setq scope (org-agenda-files t)))
10242 ((eq scope 'agenda-with-archives)
10243 (setq scope (org-agenda-files t))
10244 (setq scope (org-add-archive-files scope)))
10245 ((eq scope 'file)
10246 (setq scope (list (buffer-file-name))))
10247 ((eq scope 'file-with-archives)
10248 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10249 (org-prepare-agenda-buffers scope)
10250 (while (setq file (pop scope))
10251 (with-current-buffer (org-find-base-buffer-visiting file)
10252 (save-excursion
10253 (save-restriction
10254 (widen)
10255 (goto-char (point-min))
10256 (setq res (append res (org-scan-tags func matcher))))))))))
10257 res))
10258
10259 ;;;; Properties
10260
10261 ;;; Setting and retrieving properties
10262
10263 (defconst org-special-properties
10264 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10265 "TIMESTAMP" "TIMESTAMP_IA")
10266 "The special properties valid in Org-mode.
10267
10268 These are properties that are not defined in the property drawer,
10269 but in some other way.")
10270
10271 (defconst org-default-properties
10272 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10273 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10274 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10275 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10276 "Some properties that are used by Org-mode for various purposes.
10277 Being in this list makes sure that they are offered for completion.")
10278
10279 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10280 "Regular expression matching the first line of a property drawer.")
10281
10282 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10283 "Regular expression matching the first line of a property drawer.")
10284
10285 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10286 "Regular expression matching the first line of a property drawer.")
10287
10288 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10289 "Regular expression matching the first line of a property drawer.")
10290
10291 (defconst org-property-drawer-re
10292 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10293 org-property-end-re "\\)\n?")
10294 "Matches an entire property drawer.")
10295
10296 (defconst org-clock-drawer-re
10297 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10298 org-property-end-re "\\)\n?")
10299 "Matches an entire clock drawer.")
10300
10301 (defun org-property-action ()
10302 "Do an action on properties."
10303 (interactive)
10304 (let (c)
10305 (org-at-property-p)
10306 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10307 (setq c (read-char-exclusive))
10308 (cond
10309 ((equal c ?s)
10310 (call-interactively 'org-set-property))
10311 ((equal c ?d)
10312 (call-interactively 'org-delete-property))
10313 ((equal c ?D)
10314 (call-interactively 'org-delete-property-globally))
10315 ((equal c ?c)
10316 (call-interactively 'org-compute-property-at-point))
10317 (t (error "No such property action %c" c)))))
10318
10319 (defun org-at-property-p ()
10320 "Is the cursor in a property line?"
10321 ;; FIXME: Does not check if we are actually in the drawer.
10322 ;; FIXME: also returns true on any drawers.....
10323 ;; This is used by C-c C-c for property action.
10324 (save-excursion
10325 (beginning-of-line 1)
10326 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10327
10328 (defun org-get-property-block (&optional beg end force)
10329 "Return the (beg . end) range of the body of the property drawer.
10330 BEG and END can be beginning and end of subtree, if not given
10331 they will be found.
10332 If the drawer does not exist and FORCE is non-nil, create the drawer."
10333 (catch 'exit
10334 (save-excursion
10335 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10336 (end (or end (progn (outline-next-heading) (point)))))
10337 (goto-char beg)
10338 (if (re-search-forward org-property-start-re end t)
10339 (setq beg (1+ (match-end 0)))
10340 (if force
10341 (save-excursion
10342 (org-insert-property-drawer)
10343 (setq end (progn (outline-next-heading) (point))))
10344 (throw 'exit nil))
10345 (goto-char beg)
10346 (if (re-search-forward org-property-start-re end t)
10347 (setq beg (1+ (match-end 0)))))
10348 (if (re-search-forward org-property-end-re end t)
10349 (setq end (match-beginning 0))
10350 (or force (throw 'exit nil))
10351 (goto-char beg)
10352 (setq end beg)
10353 (org-indent-line-function)
10354 (insert ":END:\n"))
10355 (cons beg end)))))
10356
10357 (defun org-entry-properties (&optional pom which)
10358 "Get all properties of the entry at point-or-marker POM.
10359 This includes the TODO keyword, the tags, time strings for deadline,
10360 scheduled, and clocking, and any additional properties defined in the
10361 entry. The return value is an alist, keys may occur multiple times
10362 if the property key was used several times.
10363 POM may also be nil, in which case the current entry is used.
10364 If WHICH is nil or `all', get all properties. If WHICH is
10365 `special' or `standard', only get that subclass."
10366 (setq which (or which 'all))
10367 (org-with-point-at pom
10368 (let ((clockstr (substring org-clock-string 0 -1))
10369 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10370 beg end range props sum-props key value string clocksum)
10371 (save-excursion
10372 (when (condition-case nil
10373 (and (org-mode-p) (org-back-to-heading t))
10374 (error nil))
10375 (setq beg (point))
10376 (setq sum-props (get-text-property (point) 'org-summaries))
10377 (setq clocksum (get-text-property (point) :org-clock-minutes))
10378 (outline-next-heading)
10379 (setq end (point))
10380 (when (memq which '(all special))
10381 ;; Get the special properties, like TODO and tags
10382 (goto-char beg)
10383 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10384 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10385 (when (looking-at org-priority-regexp)
10386 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10387 (when (and (setq value (org-get-tags-string))
10388 (string-match "\\S-" value))
10389 (push (cons "TAGS" value) props))
10390 (when (setq value (org-get-tags-at))
10391 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10392 props))
10393 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10394 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10395 string (if (equal key clockstr)
10396 (org-no-properties
10397 (org-trim
10398 (buffer-substring
10399 (match-beginning 3) (goto-char (point-at-eol)))))
10400 (substring (org-match-string-no-properties 3) 1 -1)))
10401 (unless key
10402 (if (= (char-after (match-beginning 3)) ?\[)
10403 (setq key "TIMESTAMP_IA")
10404 (setq key "TIMESTAMP")))
10405 (when (or (equal key clockstr) (not (assoc key props)))
10406 (push (cons key string) props)))
10407
10408 )
10409
10410 (when (memq which '(all standard))
10411 ;; Get the standard properties, like :PORP: ...
10412 (setq range (org-get-property-block beg end))
10413 (when range
10414 (goto-char (car range))
10415 (while (re-search-forward
10416 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10417 (cdr range) t)
10418 (setq key (org-match-string-no-properties 1)
10419 value (org-trim (or (org-match-string-no-properties 2) "")))
10420 (unless (member key excluded)
10421 (push (cons key (or value "")) props)))))
10422 (if clocksum
10423 (push (cons "CLOCKSUM"
10424 (org-columns-number-to-string (/ (float clocksum) 60.)
10425 'add_times))
10426 props))
10427 (unless (assoc "CATEGORY" props)
10428 (setq value (or (org-get-category)
10429 (progn (org-refresh-category-properties)
10430 (org-get-category))))
10431 (push (cons "CATEGORY" value) props))
10432 (append sum-props (nreverse props)))))))
10433
10434 (defun org-entry-get (pom property &optional inherit)
10435 "Get value of PROPERTY for entry at point-or-marker POM.
10436 If INHERIT is non-nil and the entry does not have the property,
10437 then also check higher levels of the hierarchy.
10438 If INHERIT is the symbol `selective', use inheritance only if the setting
10439 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10440 If the property is present but empty, the return value is the empty string.
10441 If the property is not present at all, nil is returned."
10442 (org-with-point-at pom
10443 (if (and inherit (if (eq inherit 'selective)
10444 (org-property-inherit-p property)
10445 t))
10446 (org-entry-get-with-inheritance property)
10447 (if (member property org-special-properties)
10448 ;; We need a special property. Use brute force, get all properties.
10449 (cdr (assoc property (org-entry-properties nil 'special)))
10450 (let ((range (org-get-property-block)))
10451 (if (and range
10452 (goto-char (car range))
10453 (re-search-forward
10454 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10455 (cdr range) t))
10456 ;; Found the property, return it.
10457 (if (match-end 1)
10458 (org-match-string-no-properties 1)
10459 "")))))))
10460
10461 (defun org-property-or-variable-value (var &optional inherit)
10462 "Check if there is a property fixing the value of VAR.
10463 If yes, return this value. If not, return the current value of the variable."
10464 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10465 (if (and prop (stringp prop) (string-match "\\S-" prop))
10466 (read prop)
10467 (symbol-value var))))
10468
10469 (defun org-entry-delete (pom property)
10470 "Delete the property PROPERTY from entry at point-or-marker POM."
10471 (org-with-point-at pom
10472 (if (member property org-special-properties)
10473 nil ; cannot delete these properties.
10474 (let ((range (org-get-property-block)))
10475 (if (and range
10476 (goto-char (car range))
10477 (re-search-forward
10478 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10479 (cdr range) t))
10480 (progn
10481 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10482 t)
10483 nil)))))
10484
10485 ;; Multi-values properties are properties that contain multiple values
10486 ;; These values are assumed to be single words, separated by whitespace.
10487 (defun org-entry-add-to-multivalued-property (pom property value)
10488 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10489 (let* ((old (org-entry-get pom property))
10490 (values (and old (org-split-string old "[ \t]"))))
10491 (setq value (org-entry-protect-space value))
10492 (unless (member value values)
10493 (setq values (cons value values))
10494 (org-entry-put pom property
10495 (mapconcat 'identity values " ")))))
10496
10497 (defun org-entry-remove-from-multivalued-property (pom property value)
10498 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10499 (let* ((old (org-entry-get pom property))
10500 (values (and old (org-split-string old "[ \t]"))))
10501 (setq value (org-entry-protect-space value))
10502 (when (member value values)
10503 (setq values (delete value values))
10504 (org-entry-put pom property
10505 (mapconcat 'identity values " ")))))
10506
10507 (defun org-entry-member-in-multivalued-property (pom property value)
10508 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10509 (let* ((old (org-entry-get pom property))
10510 (values (and old (org-split-string old "[ \t]"))))
10511 (setq value (org-entry-protect-space value))
10512 (member value values)))
10513
10514 (defun org-entry-get-multivalued-property (pom property)
10515 "Return a list of values in a multivalued property."
10516 (let* ((value (org-entry-get pom property))
10517 (values (and value (org-split-string value "[ \t]"))))
10518 (mapcar 'org-entry-restore-space values)))
10519
10520 (defun org-entry-put-multivalued-property (pom property &rest values)
10521 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10522 VALUES should be a list of strings. Spaces will be protected."
10523 (org-entry-put pom property
10524 (mapconcat 'org-entry-protect-space values " "))
10525 (let* ((value (org-entry-get pom property))
10526 (values (and value (org-split-string value "[ \t]"))))
10527 (mapcar 'org-entry-restore-space values)))
10528
10529 (defun org-entry-protect-space (s)
10530 "Protect spaces and newline in string S."
10531 (while (string-match " " s)
10532 (setq s (replace-match "%20" t t s)))
10533 (while (string-match "\n" s)
10534 (setq s (replace-match "%0A" t t s)))
10535 s)
10536
10537 (defun org-entry-restore-space (s)
10538 "Restore spaces and newline in string S."
10539 (while (string-match "%20" s)
10540 (setq s (replace-match " " t t s)))
10541 (while (string-match "%0A" s)
10542 (setq s (replace-match "\n" t t s)))
10543 s)
10544
10545 (defvar org-entry-property-inherited-from (make-marker)
10546 "Marker pointing to the entry from where a property was inherited.
10547 Each call to `org-entry-get-with-inheritance' will set this marker to the
10548 location of the entry where the inheritance search matched. If there was
10549 no match, the marker will point nowhere.
10550 Note that also `org-entry-get' calls this function, if the INHERIT flag
10551 is set.")
10552
10553 (defun org-entry-get-with-inheritance (property)
10554 "Get entry property, and search higher levels if not present."
10555 (move-marker org-entry-property-inherited-from nil)
10556 (let (tmp)
10557 (save-excursion
10558 (save-restriction
10559 (widen)
10560 (catch 'ex
10561 (while t
10562 (when (setq tmp (org-entry-get nil property))
10563 (org-back-to-heading t)
10564 (move-marker org-entry-property-inherited-from (point))
10565 (throw 'ex tmp))
10566 (or (org-up-heading-safe) (throw 'ex nil)))))
10567 (or tmp
10568 (cdr (assoc property org-file-properties))
10569 (cdr (assoc property org-global-properties))
10570 (cdr (assoc property org-global-properties-fixed))))))
10571
10572 (defun org-entry-put (pom property value)
10573 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10574 (org-with-point-at pom
10575 (org-back-to-heading t)
10576 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10577 range)
10578 (cond
10579 ((equal property "TODO")
10580 (when (and (stringp value) (string-match "\\S-" value)
10581 (not (member value org-todo-keywords-1)))
10582 (error "\"%s\" is not a valid TODO state" value))
10583 (if (or (not value)
10584 (not (string-match "\\S-" value)))
10585 (setq value 'none))
10586 (org-todo value)
10587 (org-set-tags nil 'align))
10588 ((equal property "PRIORITY")
10589 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10590 (string-to-char value) ?\ ))
10591 (org-set-tags nil 'align))
10592 ((equal property "SCHEDULED")
10593 (if (re-search-forward org-scheduled-time-regexp end t)
10594 (cond
10595 ((eq value 'earlier) (org-timestamp-change -1 'day))
10596 ((eq value 'later) (org-timestamp-change 1 'day))
10597 (t (call-interactively 'org-schedule)))
10598 (call-interactively 'org-schedule)))
10599 ((equal property "DEADLINE")
10600 (if (re-search-forward org-deadline-time-regexp end t)
10601 (cond
10602 ((eq value 'earlier) (org-timestamp-change -1 'day))
10603 ((eq value 'later) (org-timestamp-change 1 'day))
10604 (t (call-interactively 'org-deadline)))
10605 (call-interactively 'org-deadline)))
10606 ((member property org-special-properties)
10607 (error "The %s property can not yet be set with `org-entry-put'"
10608 property))
10609 (t ; a non-special property
10610 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10611 (setq range (org-get-property-block beg end 'force))
10612 (goto-char (car range))
10613 (if (re-search-forward
10614 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10615 (progn
10616 (delete-region (match-beginning 1) (match-end 1))
10617 (goto-char (match-beginning 1)))
10618 (goto-char (cdr range))
10619 (insert "\n")
10620 (backward-char 1)
10621 (org-indent-line-function)
10622 (insert ":" property ":"))
10623 (and value (insert " " value))
10624 (org-indent-line-function)))))))
10625
10626 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10627 "Get all property keys in the current buffer.
10628 With INCLUDE-SPECIALS, also list the special properties that reflect things
10629 like tags and TODO state.
10630 With INCLUDE-DEFAULTS, also include properties that has special meaning
10631 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10632 With INCLUDE-COLUMNS, also include property names given in COLUMN
10633 formats in the current buffer."
10634 (let (rtn range cfmt s p)
10635 (save-excursion
10636 (save-restriction
10637 (widen)
10638 (goto-char (point-min))
10639 (while (re-search-forward org-property-start-re nil t)
10640 (setq range (org-get-property-block))
10641 (goto-char (car range))
10642 (while (re-search-forward
10643 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10644 (cdr range) t)
10645 (add-to-list 'rtn (org-match-string-no-properties 1)))
10646 (outline-next-heading))))
10647
10648 (when include-specials
10649 (setq rtn (append org-special-properties rtn)))
10650
10651 (when include-defaults
10652 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10653
10654 (when include-columns
10655 (save-excursion
10656 (save-restriction
10657 (widen)
10658 (goto-char (point-min))
10659 (while (re-search-forward
10660 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10661 nil t)
10662 (setq cfmt (match-string 2) s 0)
10663 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10664 cfmt s)
10665 (setq s (match-end 0)
10666 p (match-string 1 cfmt))
10667 (unless (or (equal p "ITEM")
10668 (member p org-special-properties))
10669 (add-to-list 'rtn (match-string 1 cfmt))))))))
10670
10671 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10672
10673 (defun org-property-values (key)
10674 "Return a list of all values of property KEY."
10675 (save-excursion
10676 (save-restriction
10677 (widen)
10678 (goto-char (point-min))
10679 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10680 values)
10681 (while (re-search-forward re nil t)
10682 (add-to-list 'values (org-trim (match-string 1))))
10683 (delete "" values)))))
10684
10685 (defun org-insert-property-drawer ()
10686 "Insert a property drawer into the current entry."
10687 (interactive)
10688 (org-back-to-heading t)
10689 (looking-at outline-regexp)
10690 (let ((indent (- (match-end 0)(match-beginning 0)))
10691 (beg (point))
10692 (re (concat "^[ \t]*" org-keyword-time-regexp))
10693 end hiddenp)
10694 (outline-next-heading)
10695 (setq end (point))
10696 (goto-char beg)
10697 (while (re-search-forward re end t))
10698 (setq hiddenp (org-invisible-p))
10699 (end-of-line 1)
10700 (and (equal (char-after) ?\n) (forward-char 1))
10701 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10702 (beginning-of-line 2))
10703 (org-skip-over-state-notes)
10704 (skip-chars-backward " \t\n\r")
10705 (if (eq (char-before) ?*) (forward-char 1))
10706 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10707 (beginning-of-line 0)
10708 (org-indent-to-column indent)
10709 (beginning-of-line 2)
10710 (org-indent-to-column indent)
10711 (beginning-of-line 0)
10712 (if hiddenp
10713 (save-excursion
10714 (org-back-to-heading t)
10715 (hide-entry))
10716 (org-flag-drawer t))))
10717
10718 (defun org-set-property (property value)
10719 "In the current entry, set PROPERTY to VALUE.
10720 When called interactively, this will prompt for a property name, offering
10721 completion on existing and default properties. And then it will prompt
10722 for a value, offering completion either on allowed values (via an inherited
10723 xxx_ALL property) or on existing values in other instances of this property
10724 in the current file."
10725 (interactive
10726 (let* ((completion-ignore-case t)
10727 (keys (org-buffer-property-keys nil t t))
10728 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10729 (prop (if (member prop0 keys)
10730 prop0
10731 (or (cdr (assoc (downcase prop0)
10732 (mapcar (lambda (x) (cons (downcase x) x))
10733 keys)))
10734 prop0)))
10735 (cur (org-entry-get nil prop))
10736 (allowed (org-property-get-allowed-values nil prop 'table))
10737 (existing (mapcar 'list (org-property-values prop)))
10738 (val (if allowed
10739 (org-completing-read "Value: " allowed nil 'req-match)
10740 (org-completing-read
10741 (concat "Value" (if (and cur (string-match "\\S-" cur))
10742 (concat "[" cur "]") "")
10743 ": ")
10744 existing nil nil "" nil cur))))
10745 (list prop (if (equal val "") cur val))))
10746 (unless (equal (org-entry-get nil property) value)
10747 (org-entry-put nil property value)))
10748
10749 (defun org-delete-property (property)
10750 "In the current entry, delete PROPERTY."
10751 (interactive
10752 (let* ((completion-ignore-case t)
10753 (prop (org-ido-completing-read
10754 "Property: " (org-entry-properties nil 'standard))))
10755 (list prop)))
10756 (message "Property %s %s" property
10757 (if (org-entry-delete nil property)
10758 "deleted"
10759 "was not present in the entry")))
10760
10761 (defun org-delete-property-globally (property)
10762 "Remove PROPERTY globally, from all entries."
10763 (interactive
10764 (let* ((completion-ignore-case t)
10765 (prop (org-ido-completing-read
10766 "Globally remove property: "
10767 (mapcar 'list (org-buffer-property-keys)))))
10768 (list prop)))
10769 (save-excursion
10770 (save-restriction
10771 (widen)
10772 (goto-char (point-min))
10773 (let ((cnt 0))
10774 (while (re-search-forward
10775 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10776 nil t)
10777 (setq cnt (1+ cnt))
10778 (replace-match ""))
10779 (message "Property \"%s\" removed from %d entries" property cnt)))))
10780
10781 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10782
10783 (defun org-compute-property-at-point ()
10784 "Compute the property at point.
10785 This looks for an enclosing column format, extracts the operator and
10786 then applies it to the property in the column format's scope."
10787 (interactive)
10788 (unless (org-at-property-p)
10789 (error "Not at a property"))
10790 (let ((prop (org-match-string-no-properties 2)))
10791 (org-columns-get-format-and-top-level)
10792 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10793 (error "No operator defined for property %s" prop))
10794 (org-columns-compute prop)))
10795
10796 (defun org-property-get-allowed-values (pom property &optional table)
10797 "Get allowed values for the property PROPERTY.
10798 When TABLE is non-nil, return an alist that can directly be used for
10799 completion."
10800 (let (vals)
10801 (cond
10802 ((equal property "TODO")
10803 (setq vals (org-with-point-at pom
10804 (append org-todo-keywords-1 '("")))))
10805 ((equal property "PRIORITY")
10806 (let ((n org-lowest-priority))
10807 (while (>= n org-highest-priority)
10808 (push (char-to-string n) vals)
10809 (setq n (1- n)))))
10810 ((member property org-special-properties))
10811 (t
10812 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10813
10814 (when (and vals (string-match "\\S-" vals))
10815 (setq vals (car (read-from-string (concat "(" vals ")"))))
10816 (setq vals (mapcar (lambda (x)
10817 (cond ((stringp x) x)
10818 ((numberp x) (number-to-string x))
10819 ((symbolp x) (symbol-name x))
10820 (t "???")))
10821 vals)))))
10822 (if table (mapcar 'list vals) vals)))
10823
10824 (defun org-property-previous-allowed-value (&optional previous)
10825 "Switch to the next allowed value for this property."
10826 (interactive)
10827 (org-property-next-allowed-value t))
10828
10829 (defun org-property-next-allowed-value (&optional previous)
10830 "Switch to the next allowed value for this property."
10831 (interactive)
10832 (unless (org-at-property-p)
10833 (error "Not at a property"))
10834 (let* ((key (match-string 2))
10835 (value (match-string 3))
10836 (allowed (or (org-property-get-allowed-values (point) key)
10837 (and (member value '("[ ]" "[-]" "[X]"))
10838 '("[ ]" "[X]"))))
10839 nval)
10840 (unless allowed
10841 (error "Allowed values for this property have not been defined"))
10842 (if previous (setq allowed (reverse allowed)))
10843 (if (member value allowed)
10844 (setq nval (car (cdr (member value allowed)))))
10845 (setq nval (or nval (car allowed)))
10846 (if (equal nval value)
10847 (error "Only one allowed value for this property"))
10848 (org-at-property-p)
10849 (replace-match (concat " :" key ": " nval) t t)
10850 (org-indent-line-function)
10851 (beginning-of-line 1)
10852 (skip-chars-forward " \t")))
10853
10854 (defun org-find-entry-with-id (ident)
10855 "Locate the entry that contains the ID property with exact value IDENT.
10856 IDENT can be a string, a symbol or a number, this function will search for
10857 the string representation of it.
10858 Return the position where this entry starts, or nil if there is no such entry."
10859 (interactive "sID: ")
10860 (let ((id (cond
10861 ((stringp ident) ident)
10862 ((symbol-name ident) (symbol-name ident))
10863 ((numberp ident) (number-to-string ident))
10864 (t (error "IDENT %s must be a string, symbol or number" ident))))
10865 (case-fold-search nil))
10866 (save-excursion
10867 (save-restriction
10868 (widen)
10869 (goto-char (point-min))
10870 (when (re-search-forward
10871 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10872 nil t)
10873 (org-back-to-heading)
10874 (point))))))
10875
10876 ;;;; Timestamps
10877
10878 (defvar org-last-changed-timestamp nil)
10879 (defvar org-last-inserted-timestamp nil
10880 "The last time stamp inserted with `org-insert-time-stamp'.")
10881 (defvar org-time-was-given) ; dynamically scoped parameter
10882 (defvar org-end-time-was-given) ; dynamically scoped parameter
10883 (defvar org-ts-what) ; dynamically scoped parameter
10884
10885 (defun org-time-stamp (arg &optional inactive)
10886 "Prompt for a date/time and insert a time stamp.
10887 If the user specifies a time like HH:MM, or if this command is called
10888 with a prefix argument, the time stamp will contain date and time.
10889 Otherwise, only the date will be included. All parts of a date not
10890 specified by the user will be filled in from the current date/time.
10891 So if you press just return without typing anything, the time stamp
10892 will represent the current date/time. If there is already a timestamp
10893 at the cursor, it will be modified."
10894 (interactive "P")
10895 (let* ((ts nil)
10896 (default-time
10897 ;; Default time is either today, or, when entering a range,
10898 ;; the range start.
10899 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10900 (save-excursion
10901 (re-search-backward
10902 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10903 (- (point) 20) t)))
10904 (apply 'encode-time (org-parse-time-string (match-string 1)))
10905 (current-time)))
10906 (default-input (and ts (org-get-compact-tod ts)))
10907 org-time-was-given org-end-time-was-given time)
10908 (cond
10909 ((and (org-at-timestamp-p t)
10910 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10911 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10912 (insert "--")
10913 (setq time (let ((this-command this-command))
10914 (org-read-date arg 'totime nil nil
10915 default-time default-input)))
10916 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10917 ((org-at-timestamp-p t)
10918 (setq time (let ((this-command this-command))
10919 (org-read-date arg 'totime nil nil default-time default-input)))
10920 (when (org-at-timestamp-p t) ; just to get the match data
10921 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10922 (replace-match "")
10923 (setq org-last-changed-timestamp
10924 (org-insert-time-stamp
10925 time (or org-time-was-given arg)
10926 inactive nil nil (list org-end-time-was-given))))
10927 (message "Timestamp updated"))
10928 (t
10929 (setq time (let ((this-command this-command))
10930 (org-read-date arg 'totime nil nil default-time default-input)))
10931 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10932 nil nil (list org-end-time-was-given))))))
10933
10934 ;; FIXME: can we use this for something else, like computing time differences?
10935 (defun org-get-compact-tod (s)
10936 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10937 (let* ((t1 (match-string 1 s))
10938 (h1 (string-to-number (match-string 2 s)))
10939 (m1 (string-to-number (match-string 3 s)))
10940 (t2 (and (match-end 4) (match-string 5 s)))
10941 (h2 (and t2 (string-to-number (match-string 6 s))))
10942 (m2 (and t2 (string-to-number (match-string 7 s))))
10943 dh dm)
10944 (if (not t2)
10945 t1
10946 (setq dh (- h2 h1) dm (- m2 m1))
10947 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10948 (concat t1 "+" (number-to-string dh)
10949 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10950
10951 (defun org-time-stamp-inactive (&optional arg)
10952 "Insert an inactive time stamp.
10953 An inactive time stamp is enclosed in square brackets instead of angle
10954 brackets. It is inactive in the sense that it does not trigger agenda entries,
10955 does not link to the calendar and cannot be changed with the S-cursor keys.
10956 So these are more for recording a certain time/date."
10957 (interactive "P")
10958 (org-time-stamp arg 'inactive))
10959
10960 (defvar org-date-ovl (org-make-overlay 1 1))
10961 (org-overlay-put org-date-ovl 'face 'org-warning)
10962 (org-detach-overlay org-date-ovl)
10963
10964 (defvar org-ans1) ; dynamically scoped parameter
10965 (defvar org-ans2) ; dynamically scoped parameter
10966
10967 (defvar org-plain-time-of-day-regexp) ; defined below
10968
10969 (defvar org-overriding-default-time nil) ; dynamically scoped
10970 (defvar org-read-date-overlay nil)
10971 (defvar org-dcst nil) ; dynamically scoped
10972
10973 (defun org-read-date (&optional with-time to-time from-string prompt
10974 default-time default-input)
10975 "Read a date, possibly a time, and make things smooth for the user.
10976 The prompt will suggest to enter an ISO date, but you can also enter anything
10977 which will at least partially be understood by `parse-time-string'.
10978 Unrecognized parts of the date will default to the current day, month, year,
10979 hour and minute. If this command is called to replace a timestamp at point,
10980 of to enter the second timestamp of a range, the default time is taken from the
10981 existing stamp. For example,
10982 3-2-5 --> 2003-02-05
10983 feb 15 --> currentyear-02-15
10984 sep 12 9 --> 2009-09-12
10985 12:45 --> today 12:45
10986 22 sept 0:34 --> currentyear-09-22 0:34
10987 12 --> currentyear-currentmonth-12
10988 Fri --> nearest Friday (today or later)
10989 etc.
10990
10991 Furthermore you can specify a relative date by giving, as the *first* thing
10992 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10993 change in days weeks, months, years.
10994 With a single plus or minus, the date is relative to today. With a double
10995 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10996 +4d --> four days from today
10997 +4 --> same as above
10998 +2w --> two weeks from today
10999 ++5 --> five days from default date
11000
11001 The function understands only English month and weekday abbreviations,
11002 but this can be configured with the variables `parse-time-months' and
11003 `parse-time-weekdays'.
11004
11005 While prompting, a calendar is popped up - you can also select the
11006 date with the mouse (button 1). The calendar shows a period of three
11007 months. To scroll it to other months, use the keys `>' and `<'.
11008 If you don't like the calendar, turn it off with
11009 \(setq org-read-date-popup-calendar nil)
11010
11011 With optional argument TO-TIME, the date will immediately be converted
11012 to an internal time.
11013 With an optional argument WITH-TIME, the prompt will suggest to also
11014 insert a time. Note that when WITH-TIME is not set, you can still
11015 enter a time, and this function will inform the calling routine about
11016 this change. The calling routine may then choose to change the format
11017 used to insert the time stamp into the buffer to include the time.
11018 With optional argument FROM-STRING, read from this string instead from
11019 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11020 the time/date that is used for everything that is not specified by the
11021 user."
11022 (require 'parse-time)
11023 (let* ((org-time-stamp-rounding-minutes
11024 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11025 (org-dcst org-display-custom-times)
11026 (ct (org-current-time))
11027 (def (or org-overriding-default-time default-time ct))
11028 (defdecode (decode-time def))
11029 (dummy (progn
11030 (when (< (nth 2 defdecode) org-extend-today-until)
11031 (setcar (nthcdr 2 defdecode) -1)
11032 (setcar (nthcdr 1 defdecode) 59)
11033 (setq def (apply 'encode-time defdecode)
11034 defdecode (decode-time def)))))
11035 (calendar-move-hook nil)
11036 (calendar-view-diary-initially-flag nil)
11037 (view-diary-entries-initially nil)
11038 (calendar-view-holidays-initially-flag nil)
11039 (view-calendar-holidays-initially nil)
11040 (timestr (format-time-string
11041 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11042 (prompt (concat (if prompt (concat prompt " ") "")
11043 (format "Date+time [%s]: " timestr)))
11044 ans (org-ans0 "") org-ans1 org-ans2 final)
11045
11046 (cond
11047 (from-string (setq ans from-string))
11048 (org-read-date-popup-calendar
11049 (save-excursion
11050 (save-window-excursion
11051 (calendar)
11052 (calendar-forward-day (- (time-to-days def)
11053 (calendar-absolute-from-gregorian
11054 (calendar-current-date))))
11055 (org-eval-in-calendar nil t)
11056 (let* ((old-map (current-local-map))
11057 (map (copy-keymap calendar-mode-map))
11058 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11059 (org-defkey map (kbd "RET") 'org-calendar-select)
11060 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11061 'org-calendar-select-mouse)
11062 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11063 'org-calendar-select-mouse)
11064 (org-defkey minibuffer-local-map [(meta shift left)]
11065 (lambda () (interactive)
11066 (org-eval-in-calendar '(calendar-backward-month 1))))
11067 (org-defkey minibuffer-local-map [(meta shift right)]
11068 (lambda () (interactive)
11069 (org-eval-in-calendar '(calendar-forward-month 1))))
11070 (org-defkey minibuffer-local-map [(meta shift up)]
11071 (lambda () (interactive)
11072 (org-eval-in-calendar '(calendar-backward-year 1))))
11073 (org-defkey minibuffer-local-map [(meta shift down)]
11074 (lambda () (interactive)
11075 (org-eval-in-calendar '(calendar-forward-year 1))))
11076 (org-defkey minibuffer-local-map [(shift up)]
11077 (lambda () (interactive)
11078 (org-eval-in-calendar '(calendar-backward-week 1))))
11079 (org-defkey minibuffer-local-map [(shift down)]
11080 (lambda () (interactive)
11081 (org-eval-in-calendar '(calendar-forward-week 1))))
11082 (org-defkey minibuffer-local-map [(shift left)]
11083 (lambda () (interactive)
11084 (org-eval-in-calendar '(calendar-backward-day 1))))
11085 (org-defkey minibuffer-local-map [(shift right)]
11086 (lambda () (interactive)
11087 (org-eval-in-calendar '(calendar-forward-day 1))))
11088 (org-defkey minibuffer-local-map ">"
11089 (lambda () (interactive)
11090 (org-eval-in-calendar '(scroll-calendar-left 1))))
11091 (org-defkey minibuffer-local-map "<"
11092 (lambda () (interactive)
11093 (org-eval-in-calendar '(scroll-calendar-right 1))))
11094 (unwind-protect
11095 (progn
11096 (use-local-map map)
11097 (add-hook 'post-command-hook 'org-read-date-display)
11098 (setq org-ans0 (read-string prompt default-input nil nil))
11099 ;; org-ans0: from prompt
11100 ;; org-ans1: from mouse click
11101 ;; org-ans2: from calendar motion
11102 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11103 (remove-hook 'post-command-hook 'org-read-date-display)
11104 (use-local-map old-map)
11105 (when org-read-date-overlay
11106 (org-delete-overlay org-read-date-overlay)
11107 (setq org-read-date-overlay nil)))))))
11108
11109 (t ; Naked prompt only
11110 (unwind-protect
11111 (setq ans (read-string prompt default-input nil timestr))
11112 (when org-read-date-overlay
11113 (org-delete-overlay org-read-date-overlay)
11114 (setq org-read-date-overlay nil)))))
11115
11116 (setq final (org-read-date-analyze ans def defdecode))
11117
11118 (if to-time
11119 (apply 'encode-time final)
11120 (if (and (boundp 'org-time-was-given) org-time-was-given)
11121 (format "%04d-%02d-%02d %02d:%02d"
11122 (nth 5 final) (nth 4 final) (nth 3 final)
11123 (nth 2 final) (nth 1 final))
11124 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11125 (defvar def)
11126 (defvar defdecode)
11127 (defvar with-time)
11128 (defun org-read-date-display ()
11129 "Display the current date prompt interpretation in the minibuffer."
11130 (when org-read-date-display-live
11131 (when org-read-date-overlay
11132 (org-delete-overlay org-read-date-overlay))
11133 (let ((p (point)))
11134 (end-of-line 1)
11135 (while (not (equal (buffer-substring
11136 (max (point-min) (- (point) 4)) (point))
11137 " "))
11138 (insert " "))
11139 (goto-char p))
11140 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11141 " " (or org-ans1 org-ans2)))
11142 (org-end-time-was-given nil)
11143 (f (org-read-date-analyze ans def defdecode))
11144 (fmts (if org-dcst
11145 org-time-stamp-custom-formats
11146 org-time-stamp-formats))
11147 (fmt (if (or with-time
11148 (and (boundp 'org-time-was-given) org-time-was-given))
11149 (cdr fmts)
11150 (car fmts)))
11151 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11152 (when (and org-end-time-was-given
11153 (string-match org-plain-time-of-day-regexp txt))
11154 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11155 org-end-time-was-given
11156 (substring txt (match-end 0)))))
11157 (setq org-read-date-overlay
11158 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11159 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11160
11161 (defun org-read-date-analyze (ans def defdecode)
11162 "Analyse the combined answer of the date prompt."
11163 ;; FIXME: cleanup and comment
11164 (let (delta deltan deltaw deltadef year month day
11165 hour minute second wday pm h2 m2 tl wday1
11166 iso-year iso-weekday iso-week iso-year iso-date)
11167
11168 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11169 (setq ans "+0"))
11170
11171 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11172 (setq ans (replace-match "" t t ans)
11173 deltan (car delta)
11174 deltaw (nth 1 delta)
11175 deltadef (nth 2 delta)))
11176
11177 ;; Check if there is an iso week date in there
11178 ;; If yes, sore the info and postpone interpreting it until the rest
11179 ;; of the parsing is done
11180 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11181 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11182 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11183 iso-week (string-to-number (match-string 2 ans)))
11184 (setq ans (replace-match "" t t ans)))
11185
11186 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11187 (when (string-match
11188 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11189 (setq year (if (match-end 2)
11190 (string-to-number (match-string 2 ans))
11191 (string-to-number (format-time-string "%Y")))
11192 month (string-to-number (match-string 3 ans))
11193 day (string-to-number (match-string 4 ans)))
11194 (if (< year 100) (setq year (+ 2000 year)))
11195 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11196 t nil ans)))
11197 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11198 ;; If there is a time with am/pm, and *no* time without it, we convert
11199 ;; so that matching will be successful.
11200 (loop for i from 1 to 2 do ; twice, for end time as well
11201 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11202 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11203 (setq hour (string-to-number (match-string 1 ans))
11204 minute (if (match-end 3)
11205 (string-to-number (match-string 3 ans))
11206 0)
11207 pm (equal ?p
11208 (string-to-char (downcase (match-string 4 ans)))))
11209 (if (and (= hour 12) (not pm))
11210 (setq hour 0)
11211 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11212 (setq ans (replace-match (format "%02d:%02d" hour minute)
11213 t t ans))))
11214
11215 ;; Check if a time range is given as a duration
11216 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11217 (setq hour (string-to-number (match-string 1 ans))
11218 h2 (+ hour (string-to-number (match-string 3 ans)))
11219 minute (string-to-number (match-string 2 ans))
11220 m2 (+ minute (if (match-end 5) (string-to-number
11221 (match-string 5 ans))0)))
11222 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11223 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11224 t t ans)))
11225
11226 ;; Check if there is a time range
11227 (when (boundp 'org-end-time-was-given)
11228 (setq org-time-was-given nil)
11229 (when (and (string-match org-plain-time-of-day-regexp ans)
11230 (match-end 8))
11231 (setq org-end-time-was-given (match-string 8 ans))
11232 (setq ans (concat (substring ans 0 (match-beginning 7))
11233 (substring ans (match-end 7))))))
11234
11235 (setq tl (parse-time-string ans)
11236 day (or (nth 3 tl) (nth 3 defdecode))
11237 month (or (nth 4 tl)
11238 (if (and org-read-date-prefer-future
11239 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11240 (1+ (nth 4 defdecode))
11241 (nth 4 defdecode)))
11242 year (or (nth 5 tl)
11243 (if (and org-read-date-prefer-future
11244 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11245 (1+ (nth 5 defdecode))
11246 (nth 5 defdecode)))
11247 hour (or (nth 2 tl) (nth 2 defdecode))
11248 minute (or (nth 1 tl) (nth 1 defdecode))
11249 second (or (nth 0 tl) 0)
11250 wday (nth 6 tl))
11251
11252 ;; Special date definitions below
11253 (cond
11254 (iso-week
11255 ;; There was an iso week
11256 (setq year (or iso-year year)
11257 day (or iso-weekday wday 1)
11258 wday nil ; to make sure that the trigger below does not match
11259 iso-date (calendar-gregorian-from-absolute
11260 (calendar-absolute-from-iso
11261 (list iso-week day year))))
11262 ; FIXME: Should we also push ISO weeks into the future?
11263 ; (when (and org-read-date-prefer-future
11264 ; (not iso-year)
11265 ; (< (calendar-absolute-from-gregorian iso-date)
11266 ; (time-to-days (current-time))))
11267 ; (setq year (1+ year)
11268 ; iso-date (calendar-gregorian-from-absolute
11269 ; (calendar-absolute-from-iso
11270 ; (list iso-week day year)))))
11271 (setq month (car iso-date)
11272 year (nth 2 iso-date)
11273 day (nth 1 iso-date)))
11274 (deltan
11275 (unless deltadef
11276 (let ((now (decode-time (current-time))))
11277 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11278 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11279 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11280 ((equal deltaw "m") (setq month (+ month deltan)))
11281 ((equal deltaw "y") (setq year (+ year deltan)))))
11282 ((and wday (not (nth 3 tl)))
11283 ;; Weekday was given, but no day, so pick that day in the week
11284 ;; on or after the derived date.
11285 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11286 (unless (equal wday wday1)
11287 (setq day (+ day (% (- wday wday1 -7) 7))))))
11288 (if (and (boundp 'org-time-was-given)
11289 (nth 2 tl))
11290 (setq org-time-was-given t))
11291 (if (< year 100) (setq year (+ 2000 year)))
11292 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11293 (list second minute hour day month year)))
11294
11295 (defvar parse-time-weekdays)
11296
11297 (defun org-read-date-get-relative (s today default)
11298 "Check string S for special relative date string.
11299 TODAY and DEFAULT are internal times, for today and for a default.
11300 Return shift list (N what def-flag)
11301 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11302 N is the number of WHATs to shift.
11303 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11304 the DEFAULT date rather than TODAY."
11305 (when (and
11306 (string-match
11307 (concat
11308 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11309 "\\([0-9]+\\)?"
11310 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11311 "\\([ \t]\\|$\\)") s)
11312 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11313 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11314 (string-to-char (substring (match-string 1 s) -1))
11315 ?+))
11316 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11317 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11318 (what (if (match-end 3) (match-string 3 s) "d"))
11319 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11320 (date (if rel default today))
11321 (wday (nth 6 (decode-time date)))
11322 delta)
11323 (if wday1
11324 (progn
11325 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11326 (if (= dir ?-) (setq delta (- delta 7)))
11327 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11328 (list delta "d" rel))
11329 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11330
11331 (defun org-eval-in-calendar (form &optional keepdate)
11332 "Eval FORM in the calendar window and return to current window.
11333 Also, store the cursor date in variable org-ans2."
11334 (let ((sw (selected-window)))
11335 (select-window (get-buffer-window "*Calendar*"))
11336 (eval form)
11337 (when (and (not keepdate) (calendar-cursor-to-date))
11338 (let* ((date (calendar-cursor-to-date))
11339 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11340 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11341 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11342 (select-window sw)))
11343
11344 (defun org-calendar-select ()
11345 "Return to `org-read-date' with the date currently selected.
11346 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11347 (interactive)
11348 (when (calendar-cursor-to-date)
11349 (let* ((date (calendar-cursor-to-date))
11350 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11351 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11352 (if (active-minibuffer-window) (exit-minibuffer))))
11353
11354 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11355 "Insert a date stamp for the date given by the internal TIME.
11356 WITH-HM means, use the stamp format that includes the time of the day.
11357 INACTIVE means use square brackets instead of angular ones, so that the
11358 stamp will not contribute to the agenda.
11359 PRE and POST are optional strings to be inserted before and after the
11360 stamp.
11361 The command returns the inserted time stamp."
11362 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11363 stamp)
11364 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11365 (insert-before-markers (or pre ""))
11366 (insert-before-markers (setq stamp (format-time-string fmt time)))
11367 (when (listp extra)
11368 (setq extra (car extra))
11369 (if (and (stringp extra)
11370 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11371 (setq extra (format "-%02d:%02d"
11372 (string-to-number (match-string 1 extra))
11373 (string-to-number (match-string 2 extra))))
11374 (setq extra nil)))
11375 (when extra
11376 (backward-char 1)
11377 (insert-before-markers extra)
11378 (forward-char 1))
11379 (insert-before-markers (or post ""))
11380 (setq org-last-inserted-timestamp stamp)))
11381
11382 (defun org-toggle-time-stamp-overlays ()
11383 "Toggle the use of custom time stamp formats."
11384 (interactive)
11385 (setq org-display-custom-times (not org-display-custom-times))
11386 (unless org-display-custom-times
11387 (let ((p (point-min)) (bmp (buffer-modified-p)))
11388 (while (setq p (next-single-property-change p 'display))
11389 (if (and (get-text-property p 'display)
11390 (eq (get-text-property p 'face) 'org-date))
11391 (remove-text-properties
11392 p (setq p (next-single-property-change p 'display))
11393 '(display t))))
11394 (set-buffer-modified-p bmp)))
11395 (if (featurep 'xemacs)
11396 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11397 (org-restart-font-lock)
11398 (setq org-table-may-need-update t)
11399 (if org-display-custom-times
11400 (message "Time stamps are overlayed with custom format")
11401 (message "Time stamp overlays removed")))
11402
11403 (defun org-display-custom-time (beg end)
11404 "Overlay modified time stamp format over timestamp between BEG and END."
11405 (let* ((ts (buffer-substring beg end))
11406 t1 w1 with-hm tf time str w2 (off 0))
11407 (save-match-data
11408 (setq t1 (org-parse-time-string ts t))
11409 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11410 (setq off (- (match-end 0) (match-beginning 0)))))
11411 (setq end (- end off))
11412 (setq w1 (- end beg)
11413 with-hm (and (nth 1 t1) (nth 2 t1))
11414 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11415 time (org-fix-decoded-time t1)
11416 str (org-add-props
11417 (format-time-string
11418 (substring tf 1 -1) (apply 'encode-time time))
11419 nil 'mouse-face 'highlight)
11420 w2 (length str))
11421 (if (not (= w2 w1))
11422 (add-text-properties (1+ beg) (+ 2 beg)
11423 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11424 (if (featurep 'xemacs)
11425 (progn
11426 (put-text-property beg end 'invisible t)
11427 (put-text-property beg end 'end-glyph (make-glyph str)))
11428 (put-text-property beg end 'display str))))
11429
11430 (defun org-translate-time (string)
11431 "Translate all timestamps in STRING to custom format.
11432 But do this only if the variable `org-display-custom-times' is set."
11433 (when org-display-custom-times
11434 (save-match-data
11435 (let* ((start 0)
11436 (re org-ts-regexp-both)
11437 t1 with-hm inactive tf time str beg end)
11438 (while (setq start (string-match re string start))
11439 (setq beg (match-beginning 0)
11440 end (match-end 0)
11441 t1 (save-match-data
11442 (org-parse-time-string (substring string beg end) t))
11443 with-hm (and (nth 1 t1) (nth 2 t1))
11444 inactive (equal (substring string beg (1+ beg)) "[")
11445 tf (funcall (if with-hm 'cdr 'car)
11446 org-time-stamp-custom-formats)
11447 time (org-fix-decoded-time t1)
11448 str (format-time-string
11449 (concat
11450 (if inactive "[" "<") (substring tf 1 -1)
11451 (if inactive "]" ">"))
11452 (apply 'encode-time time))
11453 string (replace-match str t t string)
11454 start (+ start (length str)))))))
11455 string)
11456
11457 (defun org-fix-decoded-time (time)
11458 "Set 0 instead of nil for the first 6 elements of time.
11459 Don't touch the rest."
11460 (let ((n 0))
11461 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11462
11463 (defun org-days-to-time (timestamp-string)
11464 "Difference between TIMESTAMP-STRING and now in days."
11465 (- (time-to-days (org-time-string-to-time timestamp-string))
11466 (time-to-days (current-time))))
11467
11468 (defun org-deadline-close (timestamp-string &optional ndays)
11469 "Is the time in TIMESTAMP-STRING close to the current date?"
11470 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11471 (and (< (org-days-to-time timestamp-string) ndays)
11472 (not (org-entry-is-done-p))))
11473
11474 (defun org-get-wdays (ts)
11475 "Get the deadline lead time appropriate for timestring TS."
11476 (cond
11477 ((<= org-deadline-warning-days 0)
11478 ;; 0 or negative, enforce this value no matter what
11479 (- org-deadline-warning-days))
11480 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11481 ;; lead time is specified.
11482 (floor (* (string-to-number (match-string 1 ts))
11483 (cdr (assoc (match-string 2 ts)
11484 '(("d" . 1) ("w" . 7)
11485 ("m" . 30.4) ("y" . 365.25)))))))
11486 ;; go for the default.
11487 (t org-deadline-warning-days)))
11488
11489 (defun org-calendar-select-mouse (ev)
11490 "Return to `org-read-date' with the date currently selected.
11491 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11492 (interactive "e")
11493 (mouse-set-point ev)
11494 (when (calendar-cursor-to-date)
11495 (let* ((date (calendar-cursor-to-date))
11496 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11497 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11498 (if (active-minibuffer-window) (exit-minibuffer))))
11499
11500 (defun org-check-deadlines (ndays)
11501 "Check if there are any deadlines due or past due.
11502 A deadline is considered due if it happens within `org-deadline-warning-days'
11503 days from today's date. If the deadline appears in an entry marked DONE,
11504 it is not shown. The prefix arg NDAYS can be used to test that many
11505 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11506 (interactive "P")
11507 (let* ((org-warn-days
11508 (cond
11509 ((equal ndays '(4)) 100000)
11510 (ndays (prefix-numeric-value ndays))
11511 (t (abs org-deadline-warning-days))))
11512 (case-fold-search nil)
11513 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11514 (callback
11515 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11516
11517 (message "%d deadlines past-due or due within %d days"
11518 (org-occur regexp nil callback)
11519 org-warn-days)))
11520
11521 (defun org-check-before-date (date)
11522 "Check if there are deadlines or scheduled entries before DATE."
11523 (interactive (list (org-read-date)))
11524 (let ((case-fold-search nil)
11525 (regexp (concat "\\<\\(" org-deadline-string
11526 "\\|" org-scheduled-string
11527 "\\) *<\\([^>]+\\)>"))
11528 (callback
11529 (lambda () (time-less-p
11530 (org-time-string-to-time (match-string 2))
11531 (org-time-string-to-time date)))))
11532 (message "%d entries before %s"
11533 (org-occur regexp nil callback) date)))
11534
11535 (defun org-evaluate-time-range (&optional to-buffer)
11536 "Evaluate a time range by computing the difference between start and end.
11537 Normally the result is just printed in the echo area, but with prefix arg
11538 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11539 If the time range is actually in a table, the result is inserted into the
11540 next column.
11541 For time difference computation, a year is assumed to be exactly 365
11542 days in order to avoid rounding problems."
11543 (interactive "P")
11544 (or
11545 (org-clock-update-time-maybe)
11546 (save-excursion
11547 (unless (org-at-date-range-p t)
11548 (goto-char (point-at-bol))
11549 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11550 (if (not (org-at-date-range-p t))
11551 (error "Not at a time-stamp range, and none found in current line")))
11552 (let* ((ts1 (match-string 1))
11553 (ts2 (match-string 2))
11554 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11555 (match-end (match-end 0))
11556 (time1 (org-time-string-to-time ts1))
11557 (time2 (org-time-string-to-time ts2))
11558 (t1 (time-to-seconds time1))
11559 (t2 (time-to-seconds time2))
11560 (diff (abs (- t2 t1)))
11561 (negative (< (- t2 t1) 0))
11562 ;; (ys (floor (* 365 24 60 60)))
11563 (ds (* 24 60 60))
11564 (hs (* 60 60))
11565 (fy "%dy %dd %02d:%02d")
11566 (fy1 "%dy %dd")
11567 (fd "%dd %02d:%02d")
11568 (fd1 "%dd")
11569 (fh "%02d:%02d")
11570 y d h m align)
11571 (if havetime
11572 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11573 y 0
11574 d (floor (/ diff ds)) diff (mod diff ds)
11575 h (floor (/ diff hs)) diff (mod diff hs)
11576 m (floor (/ diff 60)))
11577 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11578 y 0
11579 d (floor (+ (/ diff ds) 0.5))
11580 h 0 m 0))
11581 (if (not to-buffer)
11582 (message "%s" (org-make-tdiff-string y d h m))
11583 (if (org-at-table-p)
11584 (progn
11585 (goto-char match-end)
11586 (setq align t)
11587 (and (looking-at " *|") (goto-char (match-end 0))))
11588 (goto-char match-end))
11589 (if (looking-at
11590 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11591 (replace-match ""))
11592 (if negative (insert " -"))
11593 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11594 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11595 (insert " " (format fh h m))))
11596 (if align (org-table-align))
11597 (message "Time difference inserted")))))
11598
11599 (defun org-make-tdiff-string (y d h m)
11600 (let ((fmt "")
11601 (l nil))
11602 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11603 l (push y l)))
11604 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11605 l (push d l)))
11606 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11607 l (push h l)))
11608 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11609 l (push m l)))
11610 (apply 'format fmt (nreverse l))))
11611
11612 (defun org-time-string-to-time (s)
11613 (apply 'encode-time (org-parse-time-string s)))
11614
11615 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11616 "Convert a time stamp to an absolute day number.
11617 If there is a specifyer for a cyclic time stamp, get the closest date to
11618 DAYNR.
11619 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11620 (cond
11621 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11622 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11623 daynr
11624 (+ daynr 1000)))
11625 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11626 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11627 (time-to-days (current-time))) (match-string 0 s)
11628 prefer show-all))
11629 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11630
11631 (defun org-days-to-iso-week (days)
11632 "Return the iso week number."
11633 (require 'cal-iso)
11634 (car (calendar-iso-from-absolute days)))
11635
11636 (defun org-small-year-to-year (year)
11637 "Convert 2-digit years into 4-digit years.
11638 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11639 The year 2000 cannot be abbreviated. Any year larger than 99
11640 is returned unchanged."
11641 (if (< year 38)
11642 (setq year (+ 2000 year))
11643 (if (< year 100)
11644 (setq year (+ 1900 year))))
11645 year)
11646
11647 (defun org-time-from-absolute (d)
11648 "Return the time corresponding to date D.
11649 D may be an absolute day number, or a calendar-type list (month day year)."
11650 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11651 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11652
11653 (defun org-calendar-holiday ()
11654 "List of holidays, for Diary display in Org-mode."
11655 (require 'holidays)
11656 (let ((hl (funcall
11657 (if (fboundp 'calendar-check-holidays)
11658 'calendar-check-holidays 'check-calendar-holidays) date)))
11659 (if hl (mapconcat 'identity hl "; "))))
11660
11661 (defun org-diary-sexp-entry (sexp entry date)
11662 "Process a SEXP diary ENTRY for DATE."
11663 (require 'diary-lib)
11664 (let ((result (if calendar-debug-sexp
11665 (let ((stack-trace-on-error t))
11666 (eval (car (read-from-string sexp))))
11667 (condition-case nil
11668 (eval (car (read-from-string sexp)))
11669 (error
11670 (beep)
11671 (message "Bad sexp at line %d in %s: %s"
11672 (org-current-line)
11673 (buffer-file-name) sexp)
11674 (sleep-for 2))))))
11675 (cond ((stringp result) result)
11676 ((and (consp result)
11677 (stringp (cdr result))) (cdr result))
11678 (result entry)
11679 (t nil))))
11680
11681 (defun org-diary-to-ical-string (frombuf)
11682 "Get iCalendar entries from diary entries in buffer FROMBUF.
11683 This uses the icalendar.el library."
11684 (let* ((tmpdir (if (featurep 'xemacs)
11685 (temp-directory)
11686 temporary-file-directory))
11687 (tmpfile (make-temp-name
11688 (expand-file-name "orgics" tmpdir)))
11689 buf rtn b e)
11690 (save-excursion
11691 (set-buffer frombuf)
11692 (icalendar-export-region (point-min) (point-max) tmpfile)
11693 (setq buf (find-buffer-visiting tmpfile))
11694 (set-buffer buf)
11695 (goto-char (point-min))
11696 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11697 (setq b (match-beginning 0)))
11698 (goto-char (point-max))
11699 (if (re-search-backward "^END:VEVENT" nil t)
11700 (setq e (match-end 0)))
11701 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11702 (kill-buffer buf)
11703 (delete-file tmpfile)
11704 rtn))
11705
11706 (defun org-closest-date (start current change prefer show-all)
11707 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11708 When PREFER is `past' return a date that is either CURRENT or past.
11709 When PREFER is `future', return a date that is either CURRENT or future.
11710 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11711 ;; Make the proper lists from the dates
11712 (catch 'exit
11713 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11714 dn dw sday cday n1 n2 n0
11715 d m y y1 y2 date1 date2 nmonths nm ny m2)
11716
11717 (setq start (org-date-to-gregorian start)
11718 current (org-date-to-gregorian
11719 (if show-all
11720 current
11721 (time-to-days (current-time))))
11722 sday (calendar-absolute-from-gregorian start)
11723 cday (calendar-absolute-from-gregorian current))
11724
11725 (if (<= cday sday) (throw 'exit sday))
11726
11727 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11728 (setq dn (string-to-number (match-string 1 change))
11729 dw (cdr (assoc (match-string 2 change) a1)))
11730 (error "Invalid change specifyer: %s" change))
11731 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11732 (cond
11733 ((eq dw 'day)
11734 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11735 n2 (+ n1 dn)))
11736 ((eq dw 'year)
11737 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11738 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11739 (setq date1 (list m d y1)
11740 n1 (calendar-absolute-from-gregorian date1)
11741 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11742 n2 (calendar-absolute-from-gregorian date2)))
11743 ((eq dw 'month)
11744 ;; approx number of month between the two dates
11745 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11746 ;; How often does dn fit in there?
11747 (setq d (nth 1 start) m (car start) y (nth 2 start)
11748 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11749 m (+ m nm)
11750 ny (floor (/ m 12))
11751 y (+ y ny)
11752 m (- m (* ny 12)))
11753 (while (> m 12) (setq m (- m 12) y (1+ y)))
11754 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11755 (setq m2 (+ m dn) y2 y)
11756 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11757 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11758 (while (<= n2 cday)
11759 (setq n1 n2 m m2 y y2)
11760 (setq m2 (+ m dn) y2 y)
11761 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11762 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11763 ;; Make sure n1 is the earlier date
11764 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
11765 (if show-all
11766 (cond
11767 ((eq prefer 'past) n1)
11768 ((eq prefer 'future) (if (= cday n1) n1 n2))
11769 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11770 (cond
11771 ((eq prefer 'past) n1)
11772 ((eq prefer 'future) (if (= cday n1) n1 n2))
11773 (t (if (= cday n1) n1 n2)))))))
11774
11775 (defun org-date-to-gregorian (date)
11776 "Turn any specification of DATE into a gregorian date for the calendar."
11777 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11778 ((and (listp date) (= (length date) 3)) date)
11779 ((stringp date)
11780 (setq date (org-parse-time-string date))
11781 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11782 ((listp date)
11783 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11784
11785 (defun org-parse-time-string (s &optional nodefault)
11786 "Parse the standard Org-mode time string.
11787 This should be a lot faster than the normal `parse-time-string'.
11788 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11789 hour and minute fields will be nil if not given."
11790 (if (string-match org-ts-regexp0 s)
11791 (list 0
11792 (if (or (match-beginning 8) (not nodefault))
11793 (string-to-number (or (match-string 8 s) "0")))
11794 (if (or (match-beginning 7) (not nodefault))
11795 (string-to-number (or (match-string 7 s) "0")))
11796 (string-to-number (match-string 4 s))
11797 (string-to-number (match-string 3 s))
11798 (string-to-number (match-string 2 s))
11799 nil nil nil)
11800 (make-list 9 0)))
11801
11802 (defun org-timestamp-up (&optional arg)
11803 "Increase the date item at the cursor by one.
11804 If the cursor is on the year, change the year. If it is on the month or
11805 the day, change that.
11806 With prefix ARG, change by that many units."
11807 (interactive "p")
11808 (org-timestamp-change (prefix-numeric-value arg)))
11809
11810 (defun org-timestamp-down (&optional arg)
11811 "Decrease the date item at the cursor by one.
11812 If the cursor is on the year, change the year. If it is on the month or
11813 the day, change that.
11814 With prefix ARG, change by that many units."
11815 (interactive "p")
11816 (org-timestamp-change (- (prefix-numeric-value arg))))
11817
11818 (defun org-timestamp-up-day (&optional arg)
11819 "Increase the date in the time stamp by one day.
11820 With prefix ARG, change that many days."
11821 (interactive "p")
11822 (if (and (not (org-at-timestamp-p t))
11823 (org-on-heading-p))
11824 (org-todo 'up)
11825 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11826
11827 (defun org-timestamp-down-day (&optional arg)
11828 "Decrease the date in the time stamp by one day.
11829 With prefix ARG, change that many days."
11830 (interactive "p")
11831 (if (and (not (org-at-timestamp-p t))
11832 (org-on-heading-p))
11833 (org-todo 'down)
11834 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11835
11836 (defun org-at-timestamp-p (&optional inactive-ok)
11837 "Determine if the cursor is in or at a timestamp."
11838 (interactive)
11839 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11840 (pos (point))
11841 (ans (or (looking-at tsr)
11842 (save-excursion
11843 (skip-chars-backward "^[<\n\r\t")
11844 (if (> (point) (point-min)) (backward-char 1))
11845 (and (looking-at tsr)
11846 (> (- (match-end 0) pos) -1))))))
11847 (and ans
11848 (boundp 'org-ts-what)
11849 (setq org-ts-what
11850 (cond
11851 ((= pos (match-beginning 0)) 'bracket)
11852 ((= pos (1- (match-end 0))) 'bracket)
11853 ((org-pos-in-match-range pos 2) 'year)
11854 ((org-pos-in-match-range pos 3) 'month)
11855 ((org-pos-in-match-range pos 7) 'hour)
11856 ((org-pos-in-match-range pos 8) 'minute)
11857 ((or (org-pos-in-match-range pos 4)
11858 (org-pos-in-match-range pos 5)) 'day)
11859 ((and (> pos (or (match-end 8) (match-end 5)))
11860 (< pos (match-end 0)))
11861 (- pos (or (match-end 8) (match-end 5))))
11862 (t 'day))))
11863 ans))
11864
11865 (defun org-toggle-timestamp-type ()
11866 "Toggle the type (<active> or [inactive]) of a time stamp."
11867 (interactive)
11868 (when (org-at-timestamp-p t)
11869 (let ((beg (match-beginning 0)) (end (match-end 0))
11870 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11871 (save-excursion
11872 (goto-char beg)
11873 (while (re-search-forward "[][<>]" end t)
11874 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11875 t t)))
11876 (message "Timestamp is now %sactive"
11877 (if (equal (char-after beg) ?<) "" "in")))))
11878
11879 (defun org-timestamp-change (n &optional what)
11880 "Change the date in the time stamp at point.
11881 The date will be changed by N times WHAT. WHAT can be `day', `month',
11882 `year', `minute', `second'. If WHAT is not given, the cursor position
11883 in the timestamp determines what will be changed."
11884 (let ((pos (point))
11885 with-hm inactive
11886 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11887 org-ts-what
11888 extra rem
11889 ts time time0)
11890 (if (not (org-at-timestamp-p t))
11891 (error "Not at a timestamp"))
11892 (if (and (not what) (eq org-ts-what 'bracket))
11893 (org-toggle-timestamp-type)
11894 (if (and (not what) (not (eq org-ts-what 'day))
11895 org-display-custom-times
11896 (get-text-property (point) 'display)
11897 (not (get-text-property (1- (point)) 'display)))
11898 (setq org-ts-what 'day))
11899 (setq org-ts-what (or what org-ts-what)
11900 inactive (= (char-after (match-beginning 0)) ?\[)
11901 ts (match-string 0))
11902 (replace-match "")
11903 (if (string-match
11904 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11905 ts)
11906 (setq extra (match-string 1 ts)))
11907 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11908 (setq with-hm t))
11909 (setq time0 (org-parse-time-string ts))
11910 (when (and (eq org-ts-what 'minute)
11911 (eq current-prefix-arg nil))
11912 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11913 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11914 (setcar (cdr time0) (+ (nth 1 time0)
11915 (if (> n 0) (- rem) (- dm rem))))))
11916 (setq time
11917 (encode-time (or (car time0) 0)
11918 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11919 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11920 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11921 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11922 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11923 (nthcdr 6 time0)))
11924 (when (integerp org-ts-what)
11925 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11926 (if (eq what 'calendar)
11927 (let ((cal-date (org-get-date-from-calendar)))
11928 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11929 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11930 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11931 (setcar time0 (or (car time0) 0))
11932 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11933 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11934 (setq time (apply 'encode-time time0))))
11935 (setq org-last-changed-timestamp
11936 (org-insert-time-stamp time with-hm inactive nil nil extra))
11937 (org-clock-update-time-maybe)
11938 (goto-char pos)
11939 ;; Try to recenter the calendar window, if any
11940 (if (and org-calendar-follow-timestamp-change
11941 (get-buffer-window "*Calendar*" t)
11942 (memq org-ts-what '(day month year)))
11943 (org-recenter-calendar (time-to-days time))))))
11944
11945 (defun org-modify-ts-extra (s pos n dm)
11946 "Change the different parts of the lead-time and repeat fields in timestamp."
11947 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11948 ng h m new rem)
11949 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11950 (cond
11951 ((or (org-pos-in-match-range pos 2)
11952 (org-pos-in-match-range pos 3))
11953 (setq m (string-to-number (match-string 3 s))
11954 h (string-to-number (match-string 2 s)))
11955 (if (org-pos-in-match-range pos 2)
11956 (setq h (+ h n))
11957 (setq n (* dm (org-no-warnings (signum n))))
11958 (when (not (= 0 (setq rem (% m dm))))
11959 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11960 (setq m (+ m n)))
11961 (if (< m 0) (setq m (+ m 60) h (1- h)))
11962 (if (> m 59) (setq m (- m 60) h (1+ h)))
11963 (setq h (min 24 (max 0 h)))
11964 (setq ng 1 new (format "-%02d:%02d" h m)))
11965 ((org-pos-in-match-range pos 6)
11966 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11967 ((org-pos-in-match-range pos 5)
11968 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11969
11970 ((org-pos-in-match-range pos 9)
11971 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11972 ((org-pos-in-match-range pos 8)
11973 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11974
11975 (when ng
11976 (setq s (concat
11977 (substring s 0 (match-beginning ng))
11978 new
11979 (substring s (match-end ng))))))
11980 s))
11981
11982 (defun org-recenter-calendar (date)
11983 "If the calendar is visible, recenter it to DATE."
11984 (let* ((win (selected-window))
11985 (cwin (get-buffer-window "*Calendar*" t))
11986 (calendar-move-hook nil))
11987 (when cwin
11988 (select-window cwin)
11989 (calendar-goto-date (if (listp date) date
11990 (calendar-gregorian-from-absolute date)))
11991 (select-window win))))
11992
11993 (defun org-goto-calendar (&optional arg)
11994 "Go to the Emacs calendar at the current date.
11995 If there is a time stamp in the current line, go to that date.
11996 A prefix ARG can be used to force the current date."
11997 (interactive "P")
11998 (let ((tsr org-ts-regexp) diff
11999 (calendar-move-hook nil)
12000 (calendar-view-holidays-initially-flag nil)
12001 (view-calendar-holidays-initially nil)
12002 (calendar-view-diary-initially-flag nil)
12003 (view-diary-entries-initially nil))
12004 (if (or (org-at-timestamp-p)
12005 (save-excursion
12006 (beginning-of-line 1)
12007 (looking-at (concat ".*" tsr))))
12008 (let ((d1 (time-to-days (current-time)))
12009 (d2 (time-to-days
12010 (org-time-string-to-time (match-string 1)))))
12011 (setq diff (- d2 d1))))
12012 (calendar)
12013 (calendar-goto-today)
12014 (if (and diff (not arg)) (calendar-forward-day diff))))
12015
12016 (defun org-get-date-from-calendar ()
12017 "Return a list (month day year) of date at point in calendar."
12018 (with-current-buffer "*Calendar*"
12019 (save-match-data
12020 (calendar-cursor-to-date))))
12021
12022 (defun org-date-from-calendar ()
12023 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12024 If there is already a time stamp at the cursor position, update it."
12025 (interactive)
12026 (if (org-at-timestamp-p t)
12027 (org-timestamp-change 0 'calendar)
12028 (let ((cal-date (org-get-date-from-calendar)))
12029 (org-insert-time-stamp
12030 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12031
12032 (defun org-minutes-to-hh:mm-string (m)
12033 "Compute H:MM from a number of minutes."
12034 (let ((h (/ m 60)))
12035 (setq m (- m (* 60 h)))
12036 (format org-time-clocksum-format h m)))
12037
12038 (defun org-hh:mm-string-to-minutes (s)
12039 "Convert a string H:MM to a number of minutes."
12040 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12041 (+ (* (string-to-number (match-string 1 s)) 60)
12042 (string-to-number (match-string 2 s)))
12043 0))
12044
12045 ;;;; Agenda files
12046
12047 ;;;###autoload
12048 (defun org-iswitchb (&optional arg)
12049 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12050 With a prefix argument, restrict available to files.
12051 With two prefix arguments, restrict available buffers to agenda files.
12052
12053 Due to some yet unresolved reason, the global function
12054 `iswitchb-mode' needs to be active for this function to work."
12055 (interactive "P")
12056 (require 'iswitchb)
12057 (let ((enabled iswitchb-mode) blist)
12058 (or enabled (iswitchb-mode 1))
12059 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12060 ((equal arg '(16)) (org-buffer-list 'agenda))
12061 (t (org-buffer-list))))
12062 (unwind-protect
12063 (let ((iswitchb-make-buflist-hook
12064 (lambda ()
12065 (setq iswitchb-temp-buflist
12066 (mapcar 'buffer-name blist)))))
12067 (switch-to-buffer
12068 (iswitchb-read-buffer
12069 "Switch-to: " nil t))
12070 (or enabled (iswitchb-mode -1))))))
12071
12072 ;;;###autoload
12073 (defun org-ido-switchb (&optional arg)
12074 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12075 With a prefix argument, restrict available to files.
12076 With two prefix arguments, restrict available buffers to agenda files."
12077 (interactive "P")
12078 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12079 ((equal arg '(16)) (org-buffer-list 'agenda))
12080 (t (org-buffer-list)))))
12081 (switch-to-buffer
12082 (org-ido-completing-read "Org buffer: "
12083 (mapcar 'buffer-name blist)
12084 nil t))))
12085
12086 (defun org-buffer-list (&optional predicate exclude-tmp)
12087 "Return a list of Org buffers.
12088 PREDICATE can be `export', `files' or `agenda'.
12089
12090 export restrict the list to Export buffers.
12091 files restrict the list to buffers visiting Org files.
12092 agenda restrict the list to buffers visiting agenda files.
12093
12094 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12095 (let* ((bfn nil)
12096 (agenda-files (and (eq predicate 'agenda)
12097 (mapcar 'file-truename (org-agenda-files t))))
12098 (filter
12099 (cond
12100 ((eq predicate 'files)
12101 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12102 ((eq predicate 'export)
12103 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12104 ((eq predicate 'agenda)
12105 (lambda (b)
12106 (with-current-buffer b
12107 (and (eq major-mode 'org-mode)
12108 (setq bfn (buffer-file-name b))
12109 (member (file-truename bfn) agenda-files)))))
12110 (t (lambda (b) (with-current-buffer b
12111 (or (eq major-mode 'org-mode)
12112 (string-match "\*Org .*Export"
12113 (buffer-name b)))))))))
12114 (delq nil
12115 (mapcar
12116 (lambda(b)
12117 (if (and (funcall filter b)
12118 (or (not exclude-tmp)
12119 (not (string-match "tmp" (buffer-name b)))))
12120 b
12121 nil))
12122 (buffer-list)))))
12123
12124 (defun org-agenda-files (&optional unrestricted archives)
12125 "Get the list of agenda files.
12126 Optional UNRESTRICTED means return the full list even if a restriction
12127 is currently in place.
12128 When ARCHIVES is t, include all archive files hat are really being
12129 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12130 `org-agenda-archives-mode' is t."
12131 (let ((files
12132 (cond
12133 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12134 ((stringp org-agenda-files) (org-read-agenda-file-list))
12135 ((listp org-agenda-files) org-agenda-files)
12136 (t (error "Invalid value of `org-agenda-files'")))))
12137 (setq files (apply 'append
12138 (mapcar (lambda (f)
12139 (if (file-directory-p f)
12140 (directory-files
12141 f t org-agenda-file-regexp)
12142 (list f)))
12143 files)))
12144 (when org-agenda-skip-unavailable-files
12145 (setq files (delq nil
12146 (mapcar (function
12147 (lambda (file)
12148 (and (file-readable-p file) file)))
12149 files))))
12150 (when (or (eq archives t)
12151 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12152 (setq files (org-add-archive-files files)))
12153 files))
12154
12155 (defun org-edit-agenda-file-list ()
12156 "Edit the list of agenda files.
12157 Depending on setup, this either uses customize to edit the variable
12158 `org-agenda-files', or it visits the file that is holding the list. In the
12159 latter case, the buffer is set up in a way that saving it automatically kills
12160 the buffer and restores the previous window configuration."
12161 (interactive)
12162 (if (stringp org-agenda-files)
12163 (let ((cw (current-window-configuration)))
12164 (find-file org-agenda-files)
12165 (org-set-local 'org-window-configuration cw)
12166 (org-add-hook 'after-save-hook
12167 (lambda ()
12168 (set-window-configuration
12169 (prog1 org-window-configuration
12170 (kill-buffer (current-buffer))))
12171 (org-install-agenda-files-menu)
12172 (message "New agenda file list installed"))
12173 nil 'local)
12174 (message "%s" (substitute-command-keys
12175 "Edit list and finish with \\[save-buffer]")))
12176 (customize-variable 'org-agenda-files)))
12177
12178 (defun org-store-new-agenda-file-list (list)
12179 "Set new value for the agenda file list and save it correctly."
12180 (if (stringp org-agenda-files)
12181 (let ((f org-agenda-files) b)
12182 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12183 (with-temp-file f
12184 (insert (mapconcat 'identity list "\n") "\n")))
12185 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12186 (setq org-agenda-files list)
12187 (customize-save-variable 'org-agenda-files org-agenda-files))))
12188
12189 (defun org-read-agenda-file-list ()
12190 "Read the list of agenda files from a file."
12191 (when (file-directory-p org-agenda-files)
12192 (error "`org-agenda-files' cannot be a single directory"))
12193 (when (stringp org-agenda-files)
12194 (with-temp-buffer
12195 (insert-file-contents org-agenda-files)
12196 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12197
12198
12199 ;;;###autoload
12200 (defun org-cycle-agenda-files ()
12201 "Cycle through the files in `org-agenda-files'.
12202 If the current buffer visits an agenda file, find the next one in the list.
12203 If the current buffer does not, find the first agenda file."
12204 (interactive)
12205 (let* ((fs (org-agenda-files t))
12206 (files (append fs (list (car fs))))
12207 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12208 file)
12209 (unless files (error "No agenda files"))
12210 (catch 'exit
12211 (while (setq file (pop files))
12212 (if (equal (file-truename file) tcf)
12213 (when (car files)
12214 (find-file (car files))
12215 (throw 'exit t))))
12216 (find-file (car fs)))
12217 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12218
12219 (defun org-agenda-file-to-front (&optional to-end)
12220 "Move/add the current file to the top of the agenda file list.
12221 If the file is not present in the list, it is added to the front. If it is
12222 present, it is moved there. With optional argument TO-END, add/move to the
12223 end of the list."
12224 (interactive "P")
12225 (let ((org-agenda-skip-unavailable-files nil)
12226 (file-alist (mapcar (lambda (x)
12227 (cons (file-truename x) x))
12228 (org-agenda-files t)))
12229 (ctf (file-truename buffer-file-name))
12230 x had)
12231 (setq x (assoc ctf file-alist) had x)
12232
12233 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12234 (if to-end
12235 (setq file-alist (append (delq x file-alist) (list x)))
12236 (setq file-alist (cons x (delq x file-alist))))
12237 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12238 (org-install-agenda-files-menu)
12239 (message "File %s to %s of agenda file list"
12240 (if had "moved" "added") (if to-end "end" "front"))))
12241
12242 (defun org-remove-file (&optional file)
12243 "Remove current file from the list of files in variable `org-agenda-files'.
12244 These are the files which are being checked for agenda entries.
12245 Optional argument FILE means, use this file instead of the current."
12246 (interactive)
12247 (let* ((org-agenda-skip-unavailable-files nil)
12248 (file (or file buffer-file-name))
12249 (true-file (file-truename file))
12250 (afile (abbreviate-file-name file))
12251 (files (delq nil (mapcar
12252 (lambda (x)
12253 (if (equal true-file
12254 (file-truename x))
12255 nil x))
12256 (org-agenda-files t)))))
12257 (if (not (= (length files) (length (org-agenda-files t))))
12258 (progn
12259 (org-store-new-agenda-file-list files)
12260 (org-install-agenda-files-menu)
12261 (message "Removed file: %s" afile))
12262 (message "File was not in list: %s (not removed)" afile))))
12263
12264 (defun org-file-menu-entry (file)
12265 (vector file (list 'find-file file) t))
12266
12267 (defun org-check-agenda-file (file)
12268 "Make sure FILE exists. If not, ask user what to do."
12269 (when (not (file-exists-p file))
12270 (message "non-existent file %s. [R]emove from list or [A]bort?"
12271 (abbreviate-file-name file))
12272 (let ((r (downcase (read-char-exclusive))))
12273 (cond
12274 ((equal r ?r)
12275 (org-remove-file file)
12276 (throw 'nextfile t))
12277 (t (error "Abort"))))))
12278
12279 (defun org-get-agenda-file-buffer (file)
12280 "Get a buffer visiting FILE. If the buffer needs to be created, add
12281 it to the list of buffers which might be released later."
12282 (let ((buf (org-find-base-buffer-visiting file)))
12283 (if buf
12284 buf ; just return it
12285 ;; Make a new buffer and remember it
12286 (setq buf (find-file-noselect file))
12287 (if buf (push buf org-agenda-new-buffers))
12288 buf)))
12289
12290 (defun org-release-buffers (blist)
12291 "Release all buffers in list, asking the user for confirmation when needed.
12292 When a buffer is unmodified, it is just killed. When modified, it is saved
12293 \(if the user agrees) and then killed."
12294 (let (buf file)
12295 (while (setq buf (pop blist))
12296 (setq file (buffer-file-name buf))
12297 (when (and (buffer-modified-p buf)
12298 file
12299 (y-or-n-p (format "Save file %s? " file)))
12300 (with-current-buffer buf (save-buffer)))
12301 (kill-buffer buf))))
12302
12303 (defun org-prepare-agenda-buffers (files)
12304 "Create buffers for all agenda files, protect archived trees and comments."
12305 (interactive)
12306 (let ((pa '(:org-archived t))
12307 (pc '(:org-comment t))
12308 (pall '(:org-archived t :org-comment t))
12309 (inhibit-read-only t)
12310 (rea (concat ":" org-archive-tag ":"))
12311 bmp file re)
12312 (save-excursion
12313 (save-restriction
12314 (while (setq file (pop files))
12315 (if (bufferp file)
12316 (set-buffer file)
12317 (org-check-agenda-file file)
12318 (set-buffer (org-get-agenda-file-buffer file)))
12319 (widen)
12320 (setq bmp (buffer-modified-p))
12321 (org-refresh-category-properties)
12322 (setq org-todo-keywords-for-agenda
12323 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12324 (setq org-done-keywords-for-agenda
12325 (append org-done-keywords-for-agenda org-done-keywords))
12326 (setq org-todo-keyword-alist-for-agenda
12327 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12328 (setq org-tag-alist-for-agenda
12329 (append org-tag-alist-for-agenda org-tag-alist))
12330
12331 (save-excursion
12332 (remove-text-properties (point-min) (point-max) pall)
12333 (when org-agenda-skip-archived-trees
12334 (goto-char (point-min))
12335 (while (re-search-forward rea nil t)
12336 (if (org-on-heading-p t)
12337 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12338 (goto-char (point-min))
12339 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12340 (while (re-search-forward re nil t)
12341 (add-text-properties
12342 (match-beginning 0) (org-end-of-subtree t) pc)))
12343 (set-buffer-modified-p bmp))))
12344 (setq org-todo-keyword-alist-for-agenda
12345 (org-uniquify org-todo-keyword-alist-for-agenda)
12346 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12347
12348 ;;;; Embedded LaTeX
12349
12350 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12351 "Keymap for the minor `org-cdlatex-mode'.")
12352
12353 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12354 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12355 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12356 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12357 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12358
12359 (defvar org-cdlatex-texmathp-advice-is-done nil
12360 "Flag remembering if we have applied the advice to texmathp already.")
12361
12362 (define-minor-mode org-cdlatex-mode
12363 "Toggle the minor `org-cdlatex-mode'.
12364 This mode supports entering LaTeX environment and math in LaTeX fragments
12365 in Org-mode.
12366 \\{org-cdlatex-mode-map}"
12367 nil " OCDL" nil
12368 (when org-cdlatex-mode (require 'cdlatex))
12369 (unless org-cdlatex-texmathp-advice-is-done
12370 (setq org-cdlatex-texmathp-advice-is-done t)
12371 (defadvice texmathp (around org-math-always-on activate)
12372 "Always return t in org-mode buffers.
12373 This is because we want to insert math symbols without dollars even outside
12374 the LaTeX math segments. If Orgmode thinks that point is actually inside
12375 an embedded LaTeX fragment, let texmathp do its job.
12376 \\[org-cdlatex-mode-map]"
12377 (interactive)
12378 (let (p)
12379 (cond
12380 ((not (org-mode-p)) ad-do-it)
12381 ((eq this-command 'cdlatex-math-symbol)
12382 (setq ad-return-value t
12383 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12384 (t
12385 (let ((p (org-inside-LaTeX-fragment-p)))
12386 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12387 (setq ad-return-value t
12388 texmathp-why '("Org-mode embedded math" . 0))
12389 (if p ad-do-it)))))))))
12390
12391 (defun turn-on-org-cdlatex ()
12392 "Unconditionally turn on `org-cdlatex-mode'."
12393 (org-cdlatex-mode 1))
12394
12395 (defun org-inside-LaTeX-fragment-p ()
12396 "Test if point is inside a LaTeX fragment.
12397 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12398 sequence appearing also before point.
12399 Even though the matchers for math are configurable, this function assumes
12400 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12401 delimiters are skipped when they have been removed by customization.
12402 The return value is nil, or a cons cell with the delimiter and
12403 and the position of this delimiter.
12404
12405 This function does a reasonably good job, but can locally be fooled by
12406 for example currency specifications. For example it will assume being in
12407 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12408 fragments that are properly closed, but during editing, we have to live
12409 with the uncertainty caused by missing closing delimiters. This function
12410 looks only before point, not after."
12411 (catch 'exit
12412 (let ((pos (point))
12413 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12414 (lim (progn
12415 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12416 (point)))
12417 dd-on str (start 0) m re)
12418 (goto-char pos)
12419 (when dodollar
12420 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12421 re (nth 1 (assoc "$" org-latex-regexps)))
12422 (while (string-match re str start)
12423 (cond
12424 ((= (match-end 0) (length str))
12425 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12426 ((= (match-end 0) (- (length str) 5))
12427 (throw 'exit nil))
12428 (t (setq start (match-end 0))))))
12429 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12430 (goto-char pos)
12431 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12432 (and (match-beginning 2) (throw 'exit nil))
12433 ;; count $$
12434 (while (re-search-backward "\\$\\$" lim t)
12435 (setq dd-on (not dd-on)))
12436 (goto-char pos)
12437 (if dd-on (cons "$$" m))))))
12438
12439
12440 (defun org-try-cdlatex-tab ()
12441 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12442 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12443 - inside a LaTeX fragment, or
12444 - after the first word in a line, where an abbreviation expansion could
12445 insert a LaTeX environment."
12446 (when org-cdlatex-mode
12447 (cond
12448 ((save-excursion
12449 (skip-chars-backward "a-zA-Z0-9*")
12450 (skip-chars-backward " \t")
12451 (bolp))
12452 (cdlatex-tab) t)
12453 ((org-inside-LaTeX-fragment-p)
12454 (cdlatex-tab) t)
12455 (t nil))))
12456
12457 (defun org-cdlatex-underscore-caret (&optional arg)
12458 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12459 Revert to the normal definition outside of these fragments."
12460 (interactive "P")
12461 (if (org-inside-LaTeX-fragment-p)
12462 (call-interactively 'cdlatex-sub-superscript)
12463 (let (org-cdlatex-mode)
12464 (call-interactively (key-binding (vector last-input-event))))))
12465
12466 (defun org-cdlatex-math-modify (&optional arg)
12467 "Execute `cdlatex-math-modify' in LaTeX fragments.
12468 Revert to the normal definition outside of these fragments."
12469 (interactive "P")
12470 (if (org-inside-LaTeX-fragment-p)
12471 (call-interactively 'cdlatex-math-modify)
12472 (let (org-cdlatex-mode)
12473 (call-interactively (key-binding (vector last-input-event))))))
12474
12475 (defvar org-latex-fragment-image-overlays nil
12476 "List of overlays carrying the images of latex fragments.")
12477 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12478
12479 (defun org-remove-latex-fragment-image-overlays ()
12480 "Remove all overlays with LaTeX fragment images in current buffer."
12481 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12482 (setq org-latex-fragment-image-overlays nil))
12483
12484 (defun org-preview-latex-fragment (&optional subtree)
12485 "Preview the LaTeX fragment at point, or all locally or globally.
12486 If the cursor is in a LaTeX fragment, create the image and overlay
12487 it over the source code. If there is no fragment at point, display
12488 all fragments in the current text, from one headline to the next. With
12489 prefix SUBTREE, display all fragments in the current subtree. With a
12490 double prefix `C-u C-u', or when the cursor is before the first headline,
12491 display all fragments in the buffer.
12492 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12493 (interactive "P")
12494 (org-remove-latex-fragment-image-overlays)
12495 (save-excursion
12496 (save-restriction
12497 (let (beg end at msg)
12498 (cond
12499 ((or (equal subtree '(16))
12500 (not (save-excursion
12501 (re-search-backward (concat "^" outline-regexp) nil t))))
12502 (setq beg (point-min) end (point-max)
12503 msg "Creating images for buffer...%s"))
12504 ((equal subtree '(4))
12505 (org-back-to-heading)
12506 (setq beg (point) end (org-end-of-subtree t)
12507 msg "Creating images for subtree...%s"))
12508 (t
12509 (if (setq at (org-inside-LaTeX-fragment-p))
12510 (goto-char (max (point-min) (- (cdr at) 2)))
12511 (org-back-to-heading))
12512 (setq beg (point) end (progn (outline-next-heading) (point))
12513 msg (if at "Creating image...%s"
12514 "Creating images for entry...%s"))))
12515 (message msg "")
12516 (narrow-to-region beg end)
12517 (goto-char beg)
12518 (org-format-latex
12519 (concat "ltxpng/" (file-name-sans-extension
12520 (file-name-nondirectory
12521 buffer-file-name)))
12522 default-directory 'overlays msg at 'forbuffer)
12523 (message msg "done. Use `C-c C-c' to remove images.")))))
12524
12525 (defvar org-latex-regexps
12526 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12527 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12528 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12529 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12530 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12531 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12532 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12533 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12534 "Regular expressions for matching embedded LaTeX.")
12535
12536 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12537 "Replace LaTeX fragments with links to an image, and produce images."
12538 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12539 (let* ((prefixnodir (file-name-nondirectory prefix))
12540 (absprefix (expand-file-name prefix dir))
12541 (todir (file-name-directory absprefix))
12542 (opt org-format-latex-options)
12543 (matchers (plist-get opt :matchers))
12544 (re-list org-latex-regexps)
12545 (cnt 0) txt link beg end re e checkdir
12546 m n block linkfile movefile ov)
12547 ;; Check if there are old images files with this prefix, and remove them
12548 (when (file-directory-p todir)
12549 (mapc 'delete-file
12550 (directory-files
12551 todir 'full
12552 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12553 ;; Check the different regular expressions
12554 (while (setq e (pop re-list))
12555 (setq m (car e) re (nth 1 e) n (nth 2 e)
12556 block (if (nth 3 e) "\n\n" ""))
12557 (when (member m matchers)
12558 (goto-char (point-min))
12559 (while (re-search-forward re nil t)
12560 (when (or (not at) (equal (cdr at) (match-beginning n)))
12561 (setq txt (match-string n)
12562 beg (match-beginning n) end (match-end n)
12563 cnt (1+ cnt)
12564 linkfile (format "%s_%04d.png" prefix cnt)
12565 movefile (format "%s_%04d.png" absprefix cnt)
12566 link (concat block "[[file:" linkfile "]]" block))
12567 (if msg (message msg cnt))
12568 (goto-char beg)
12569 (unless checkdir ; make sure the directory exists
12570 (setq checkdir t)
12571 (or (file-directory-p todir) (make-directory todir)))
12572 (org-create-formula-image
12573 txt movefile opt forbuffer)
12574 (if overlays
12575 (progn
12576 (setq ov (org-make-overlay beg end))
12577 (if (featurep 'xemacs)
12578 (progn
12579 (org-overlay-put ov 'invisible t)
12580 (org-overlay-put
12581 ov 'end-glyph
12582 (make-glyph (vector 'png :file movefile))))
12583 (org-overlay-put
12584 ov 'display
12585 (list 'image :type 'png :file movefile :ascent 'center)))
12586 (push ov org-latex-fragment-image-overlays)
12587 (goto-char end))
12588 (delete-region beg end)
12589 (insert link))))))))
12590
12591 ;; This function borrows from Ganesh Swami's latex2png.el
12592 (defun org-create-formula-image (string tofile options buffer)
12593 (let* ((tmpdir (if (featurep 'xemacs)
12594 (temp-directory)
12595 temporary-file-directory))
12596 (texfilebase (make-temp-name
12597 (expand-file-name "orgtex" tmpdir)))
12598 (texfile (concat texfilebase ".tex"))
12599 (dvifile (concat texfilebase ".dvi"))
12600 (pngfile (concat texfilebase ".png"))
12601 (fnh (if (featurep 'xemacs)
12602 (font-height (get-face-font 'default))
12603 (face-attribute 'default :height nil)))
12604 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12605 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12606 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12607 "Black"))
12608 (bg (or (plist-get options (if buffer :background :html-background))
12609 "Transparent")))
12610 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12611 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12612 (with-temp-file texfile
12613 (insert org-format-latex-header
12614 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12615 (let ((dir default-directory))
12616 (condition-case nil
12617 (progn
12618 (cd tmpdir)
12619 (call-process "latex" nil nil nil texfile))
12620 (error nil))
12621 (cd dir))
12622 (if (not (file-exists-p dvifile))
12623 (progn (message "Failed to create dvi file from %s" texfile) nil)
12624 (condition-case nil
12625 (call-process "dvipng" nil nil nil
12626 "-E" "-fg" fg "-bg" bg
12627 "-D" dpi
12628 ;;"-x" scale "-y" scale
12629 "-T" "tight"
12630 "-o" pngfile
12631 dvifile)
12632 (error nil))
12633 (if (not (file-exists-p pngfile))
12634 (progn (message "Failed to create png file from %s" texfile) nil)
12635 ;; Use the requested file name and clean up
12636 (copy-file pngfile tofile 'replace)
12637 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12638 (delete-file (concat texfilebase e)))
12639 pngfile))))
12640
12641 (defun org-dvipng-color (attr)
12642 "Return an rgb color specification for dvipng."
12643 (apply 'format "rgb %s %s %s"
12644 (mapcar 'org-normalize-color
12645 (color-values (face-attribute 'default attr nil)))))
12646
12647 (defun org-normalize-color (value)
12648 "Return string to be used as color value for an RGB component."
12649 (format "%g" (/ value 65535.0)))
12650
12651 ;;;; Key bindings
12652
12653 ;; Make `C-c C-x' a prefix key
12654 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12655
12656 ;; TAB key with modifiers
12657 (org-defkey org-mode-map "\C-i" 'org-cycle)
12658 (org-defkey org-mode-map [(tab)] 'org-cycle)
12659 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12660 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12661 (org-defkey org-mode-map "\M-\t" 'org-complete)
12662 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12663 ;; The following line is necessary under Suse GNU/Linux
12664 (unless (featurep 'xemacs)
12665 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12666 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12667 (define-key org-mode-map [backtab] 'org-shifttab)
12668
12669 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12670 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12671 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12672
12673 ;; Cursor keys with modifiers
12674 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12675 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12676 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12677 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12678
12679 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12680 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12681 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12682 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12683
12684 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12685 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12686 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12687 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12688
12689 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12690 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12691
12692 ;;; Extra keys for tty access.
12693 ;; We only set them when really needed because otherwise the
12694 ;; menus don't show the simple keys
12695
12696 (when (or org-use-extra-keys
12697 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12698 (not window-system))
12699 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12700 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12701 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12702 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12703 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12704 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12705 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12706 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12707 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12708 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12709 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12710 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12711 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12712 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12713 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12714 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12715 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12716 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12717 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12718 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12719 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12720 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12721
12722 ;; All the other keys
12723
12724 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12725 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12726 (if (boundp 'narrow-map)
12727 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12728 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12729 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12730 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12731 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12732 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12733 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12734 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12735 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12736 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12737 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12738 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12739 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12740 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12741 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12742 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12743 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12744 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12745 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12746 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12747 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12748 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12749 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12750 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12751 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12752 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12753 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12754 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12755 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12756 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12757 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12758 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12759 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12760 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12761 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12762 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12763 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12764 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12765 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12766 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12767 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12768 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12769 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12770 (org-defkey org-mode-map "\C-c^" 'org-sort)
12771 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12772 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12773 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12774 (org-defkey org-mode-map "\C-m" 'org-return)
12775 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12776 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12777 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12778 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12779 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12780 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12781 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12782 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12783 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12784 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12785 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12786 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12787 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12788 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12789 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12790 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12791 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
12792
12793 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12794 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12795 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12796 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12797
12798 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12799 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12800 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12801 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12802 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12803 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12804 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12805 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12806 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12807 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12808 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12809 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12810
12811 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12812 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12813 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12814 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
12815
12816 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12817
12818 (when (featurep 'xemacs)
12819 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12820
12821 (defvar org-table-auto-blank-field) ; defined in org-table.el
12822 (defun org-self-insert-command (N)
12823 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12824 If the cursor is in a table looking at whitespace, the whitespace is
12825 overwritten, and the table is not marked as requiring realignment."
12826 (interactive "p")
12827 (if (and (org-table-p)
12828 (progn
12829 ;; check if we blank the field, and if that triggers align
12830 (and (featurep 'org-table) org-table-auto-blank-field
12831 (member last-command
12832 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12833 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12834 ;; got extra space, this field does not determine column width
12835 (let (org-table-may-need-update) (org-table-blank-field))
12836 ;; no extra space, this field may determine column width
12837 (org-table-blank-field)))
12838 t)
12839 (eq N 1)
12840 (looking-at "[^|\n]* |"))
12841 (let (org-table-may-need-update)
12842 (goto-char (1- (match-end 0)))
12843 (delete-backward-char 1)
12844 (goto-char (match-beginning 0))
12845 (self-insert-command N))
12846 (setq org-table-may-need-update t)
12847 (self-insert-command N)
12848 (org-fix-tags-on-the-fly)))
12849
12850 (defun org-fix-tags-on-the-fly ()
12851 (when (and (equal (char-after (point-at-bol)) ?*)
12852 (org-on-heading-p))
12853 (org-align-tags-here org-tags-column)))
12854
12855 (defun org-delete-backward-char (N)
12856 "Like `delete-backward-char', insert whitespace at field end in tables.
12857 When deleting backwards, in tables this function will insert whitespace in
12858 front of the next \"|\" separator, to keep the table aligned. The table will
12859 still be marked for re-alignment if the field did fill the entire column,
12860 because, in this case the deletion might narrow the column."
12861 (interactive "p")
12862 (if (and (org-table-p)
12863 (eq N 1)
12864 (string-match "|" (buffer-substring (point-at-bol) (point)))
12865 (looking-at ".*?|"))
12866 (let ((pos (point))
12867 (noalign (looking-at "[^|\n\r]* |"))
12868 (c org-table-may-need-update))
12869 (backward-delete-char N)
12870 (skip-chars-forward "^|")
12871 (insert " ")
12872 (goto-char (1- pos))
12873 ;; noalign: if there were two spaces at the end, this field
12874 ;; does not determine the width of the column.
12875 (if noalign (setq org-table-may-need-update c)))
12876 (backward-delete-char N)
12877 (org-fix-tags-on-the-fly)))
12878
12879 (defun org-delete-char (N)
12880 "Like `delete-char', but insert whitespace at field end in tables.
12881 When deleting characters, in tables this function will insert whitespace in
12882 front of the next \"|\" separator, to keep the table aligned. The table will
12883 still be marked for re-alignment if the field did fill the entire column,
12884 because, in this case the deletion might narrow the column."
12885 (interactive "p")
12886 (if (and (org-table-p)
12887 (not (bolp))
12888 (not (= (char-after) ?|))
12889 (eq N 1))
12890 (if (looking-at ".*?|")
12891 (let ((pos (point))
12892 (noalign (looking-at "[^|\n\r]* |"))
12893 (c org-table-may-need-update))
12894 (replace-match (concat
12895 (substring (match-string 0) 1 -1)
12896 " |"))
12897 (goto-char pos)
12898 ;; noalign: if there were two spaces at the end, this field
12899 ;; does not determine the width of the column.
12900 (if noalign (setq org-table-may-need-update c)))
12901 (delete-char N))
12902 (delete-char N)
12903 (org-fix-tags-on-the-fly)))
12904
12905 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12906 (put 'org-self-insert-command 'delete-selection t)
12907 (put 'orgtbl-self-insert-command 'delete-selection t)
12908 (put 'org-delete-char 'delete-selection 'supersede)
12909 (put 'org-delete-backward-char 'delete-selection 'supersede)
12910 (put 'org-yank 'delete-selection 'yank)
12911
12912 ;; Make `flyspell-mode' delay after some commands
12913 (put 'org-self-insert-command 'flyspell-delayed t)
12914 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12915 (put 'org-delete-char 'flyspell-delayed t)
12916 (put 'org-delete-backward-char 'flyspell-delayed t)
12917
12918 ;; Make pabbrev-mode expand after org-mode commands
12919 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12920 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
12921
12922 ;; How to do this: Measure non-white length of current string
12923 ;; If equal to column width, we should realign.
12924
12925 (defun org-remap (map &rest commands)
12926 "In MAP, remap the functions given in COMMANDS.
12927 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12928 (let (new old)
12929 (while commands
12930 (setq old (pop commands) new (pop commands))
12931 (if (fboundp 'command-remapping)
12932 (org-defkey map (vector 'remap old) new)
12933 (substitute-key-definition old new map global-map)))))
12934
12935 (when (eq org-enable-table-editor 'optimized)
12936 ;; If the user wants maximum table support, we need to hijack
12937 ;; some standard editing functions
12938 (org-remap org-mode-map
12939 'self-insert-command 'org-self-insert-command
12940 'delete-char 'org-delete-char
12941 'delete-backward-char 'org-delete-backward-char)
12942 (org-defkey org-mode-map "|" 'org-force-self-insert))
12943
12944 (defun org-modifier-cursor-error ()
12945 "Throw an error, a modified cursor command was applied in wrong context."
12946 (error "This command is active in special context like tables, headlines or items"))
12947
12948 (defun org-shiftselect-error ()
12949 "Throw an error because Shift-Cursor command was applied in wrong context."
12950 (if (and (boundp 'shift-select-mode) shift-select-mode)
12951 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
12952 (error "This command works only in special context like headlines or timestamps.")))
12953
12954 (defun org-call-for-shift-select (cmd)
12955 (let ((this-command-keys-shift-translated t))
12956 (call-interactively cmd)))
12957
12958 (defun org-shifttab (&optional arg)
12959 "Global visibility cycling or move to previous table field.
12960 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12961 on context.
12962 See the individual commands for more information."
12963 (interactive "P")
12964 (cond
12965 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12966 ((integerp arg)
12967 (message "Content view to level: %d" arg)
12968 (org-content (prefix-numeric-value arg))
12969 (setq org-cycle-global-status 'overview))
12970 (t (call-interactively 'org-global-cycle))))
12971
12972 (defun org-shiftmetaleft ()
12973 "Promote subtree or delete table column.
12974 Calls `org-promote-subtree', `org-outdent-item',
12975 or `org-table-delete-column', depending on context.
12976 See the individual commands for more information."
12977 (interactive)
12978 (cond
12979 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12980 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12981 ((org-at-item-p) (call-interactively 'org-outdent-item))
12982 (t (org-modifier-cursor-error))))
12983
12984 (defun org-shiftmetaright ()
12985 "Demote subtree or insert table column.
12986 Calls `org-demote-subtree', `org-indent-item',
12987 or `org-table-insert-column', depending on context.
12988 See the individual commands for more information."
12989 (interactive)
12990 (cond
12991 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12992 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12993 ((org-at-item-p) (call-interactively 'org-indent-item))
12994 (t (org-modifier-cursor-error))))
12995
12996 (defun org-shiftmetaup (&optional arg)
12997 "Move subtree up or kill table row.
12998 Calls `org-move-subtree-up' or `org-table-kill-row' or
12999 `org-move-item-up' depending on context. See the individual commands
13000 for more information."
13001 (interactive "P")
13002 (cond
13003 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13004 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13005 ((org-at-item-p) (call-interactively 'org-move-item-up))
13006 (t (org-modifier-cursor-error))))
13007 (defun org-shiftmetadown (&optional arg)
13008 "Move subtree down or insert table row.
13009 Calls `org-move-subtree-down' or `org-table-insert-row' or
13010 `org-move-item-down', depending on context. See the individual
13011 commands for more information."
13012 (interactive "P")
13013 (cond
13014 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13015 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13016 ((org-at-item-p) (call-interactively 'org-move-item-down))
13017 (t (org-modifier-cursor-error))))
13018
13019 (defun org-metaleft (&optional arg)
13020 "Promote heading or move table column to left.
13021 Calls `org-do-promote' or `org-table-move-column', depending on context.
13022 With no specific context, calls the Emacs default `backward-word'.
13023 See the individual commands for more information."
13024 (interactive "P")
13025 (cond
13026 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13027 ((or (org-on-heading-p) (org-region-active-p))
13028 (call-interactively 'org-do-promote))
13029 ((org-at-item-p) (call-interactively 'org-outdent-item))
13030 (t (call-interactively 'backward-word))))
13031
13032 (defun org-metaright (&optional arg)
13033 "Demote subtree or move table column to right.
13034 Calls `org-do-demote' or `org-table-move-column', depending on context.
13035 With no specific context, calls the Emacs default `forward-word'.
13036 See the individual commands for more information."
13037 (interactive "P")
13038 (cond
13039 ((org-at-table-p) (call-interactively 'org-table-move-column))
13040 ((or (org-on-heading-p) (org-region-active-p))
13041 (call-interactively 'org-do-demote))
13042 ((org-at-item-p) (call-interactively 'org-indent-item))
13043 (t (call-interactively 'forward-word))))
13044
13045 (defun org-metaup (&optional arg)
13046 "Move subtree up or move table row up.
13047 Calls `org-move-subtree-up' or `org-table-move-row' or
13048 `org-move-item-up', depending on context. See the individual commands
13049 for more information."
13050 (interactive "P")
13051 (cond
13052 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13053 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13054 ((org-at-item-p) (call-interactively 'org-move-item-up))
13055 (t (transpose-lines 1) (beginning-of-line -1))))
13056
13057 (defun org-metadown (&optional arg)
13058 "Move subtree down or move table row down.
13059 Calls `org-move-subtree-down' or `org-table-move-row' or
13060 `org-move-item-down', depending on context. See the individual
13061 commands for more information."
13062 (interactive "P")
13063 (cond
13064 ((org-at-table-p) (call-interactively 'org-table-move-row))
13065 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13066 ((org-at-item-p) (call-interactively 'org-move-item-down))
13067 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13068
13069 (defun org-shiftup (&optional arg)
13070 "Increase item in timestamp or increase priority of current headline.
13071 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13072 depending on context. See the individual commands for more information."
13073 (interactive "P")
13074 (cond
13075 ((and org-support-shift-select (org-region-active-p))
13076 (org-call-for-shift-select 'previous-line))
13077 ((org-at-timestamp-p t)
13078 (call-interactively (if org-edit-timestamp-down-means-later
13079 'org-timestamp-down 'org-timestamp-up)))
13080 ((and (not (eq org-support-shift-select 'always))
13081 (org-on-heading-p))
13082 (call-interactively 'org-priority-up))
13083 ((and (not org-support-shift-select) (org-at-item-p))
13084 (call-interactively 'org-previous-item))
13085 ((org-clocktable-try-shift 'up arg))
13086 (org-support-shift-select
13087 (org-call-for-shift-select 'previous-line))
13088 (t (org-shiftselect-error))))
13089
13090 (defun org-shiftdown (&optional arg)
13091 "Decrease item in timestamp or decrease priority of current headline.
13092 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13093 depending on context. See the individual commands for more information."
13094 (interactive "P")
13095 (cond
13096 ((and org-support-shift-select (org-region-active-p))
13097 (org-call-for-shift-select 'next-line))
13098 ((org-at-timestamp-p t)
13099 (call-interactively (if org-edit-timestamp-down-means-later
13100 'org-timestamp-up 'org-timestamp-down)))
13101 ((and (not (eq org-support-shift-select 'always))
13102 (org-on-heading-p))
13103 (call-interactively 'org-priority-down))
13104 ((and (not org-support-shift-select) (org-at-item-p))
13105 (call-interactively 'org-next-item))
13106 ((org-clocktable-try-shift 'down arg))
13107 (org-support-shift-select
13108 (org-call-for-shift-select 'next-line))
13109 (t (org-shiftselect-error))))
13110
13111 (defun org-shiftright (&optional arg)
13112 "Cycle the thing at point or in the current line, depending on context.
13113 Depending on context, this does one of the following:
13114
13115 - switch a timestamp at point one day into the future
13116 - on a headline, switch to the next TODO keyword.
13117 - on an item, switch entire list to the next bullet type
13118 - on a property line, switch to the next allowed value
13119 - on a clocktable definition line, move time block into the future"
13120 (interactive "P")
13121 (cond
13122 ((and org-support-shift-select (org-region-active-p))
13123 (org-call-for-shift-select 'forward-char))
13124 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13125 ((and (not (eq org-support-shift-select 'always))
13126 (org-on-heading-p))
13127 (org-call-with-arg 'org-todo 'right))
13128 ((or (and org-support-shift-select
13129 (not (eq org-support-shift-select 'always))
13130 (org-at-item-bullet-p))
13131 (and (not org-support-shift-select) (org-at-item-p)))
13132 (org-call-with-arg 'org-cycle-list-bullet nil))
13133 ((and (not (eq org-support-shift-select 'always))
13134 (org-at-property-p))
13135 (call-interactively 'org-property-next-allowed-value))
13136 ((org-clocktable-try-shift 'right arg))
13137 (org-support-shift-select
13138 (org-call-for-shift-select 'forward-char))
13139 (t (org-shiftselect-error))))
13140
13141 (defun org-shiftleft (&optional arg)
13142 "Cycle the thing at point or in the current line, depending on context.
13143 Depending on context, this does one of the following:
13144
13145 - switch a timestamp at point one day into the past
13146 - on a headline, switch to the previous TODO keyword.
13147 - on an item, switch entire list to the previous bullet type
13148 - on a property line, switch to the previous allowed value
13149 - on a clocktable definition line, move time block into the past"
13150 (interactive "P")
13151 (cond
13152 ((and org-support-shift-select (org-region-active-p))
13153 (org-call-for-shift-select 'backward-char))
13154 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13155 ((and (not (eq org-support-shift-select 'always))
13156 (org-on-heading-p))
13157 (org-call-with-arg 'org-todo 'left))
13158 ((or (and org-support-shift-select
13159 (not (eq org-support-shift-select 'always))
13160 (org-at-item-bullet-p))
13161 (and (not org-support-shift-select) (org-at-item-p)))
13162 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13163 ((and (not (eq org-support-shift-select 'always))
13164 (org-at-property-p))
13165 (call-interactively 'org-property-previous-allowed-value))
13166 ((org-clocktable-try-shift 'left arg))
13167 (org-support-shift-select
13168 (org-call-for-shift-select 'backward-char))
13169 (t (org-shiftselect-error))))
13170
13171 (defun org-shiftcontrolright ()
13172 "Switch to next TODO set."
13173 (interactive)
13174 (cond
13175 ((and org-support-shift-select (org-region-active-p))
13176 (org-call-for-shift-select 'forward-word))
13177 ((and (not (eq org-support-shift-select 'always))
13178 (org-on-heading-p))
13179 (org-call-with-arg 'org-todo 'nextset))
13180 (org-support-shift-select
13181 (org-call-for-shift-select 'forward-word))
13182 (t (org-shiftselect-error))))
13183
13184 (defun org-shiftcontrolleft ()
13185 "Switch to previous TODO set."
13186 (interactive)
13187 (cond
13188 ((and org-support-shift-select (org-region-active-p))
13189 (org-call-for-shift-select 'backward-word))
13190 ((and (not (eq org-support-shift-select 'always))
13191 (org-on-heading-p))
13192 (org-call-with-arg 'org-todo 'previousset))
13193 (org-support-shift-select
13194 (org-call-for-shift-select 'backward-word))
13195 (t (org-shiftselect-error))))
13196
13197 (defun org-ctrl-c-ret ()
13198 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13199 (interactive)
13200 (cond
13201 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13202 (t (call-interactively 'org-insert-heading))))
13203
13204 (defun org-copy-special ()
13205 "Copy region in table or copy current subtree.
13206 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13207 See the individual commands for more information."
13208 (interactive)
13209 (call-interactively
13210 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13211
13212 (defun org-cut-special ()
13213 "Cut region in table or cut current subtree.
13214 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13215 See the individual commands for more information."
13216 (interactive)
13217 (call-interactively
13218 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13219
13220 (defun org-paste-special (arg)
13221 "Paste rectangular region into table, or past subtree relative to level.
13222 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13223 See the individual commands for more information."
13224 (interactive "P")
13225 (if (org-at-table-p)
13226 (org-table-paste-rectangle)
13227 (org-paste-subtree arg)))
13228
13229 (defun org-edit-special ()
13230 "Call a special editor for the stuff at point.
13231 When at a table, call the formula editor with `org-table-edit-formulas'.
13232 When at the first line of an src example, call `org-edit-src-code'.
13233 When in an #+include line, visit the include file. Otherwise call
13234 `ffap' to visit the file at point."
13235 (interactive)
13236 (cond
13237 ((org-at-table-p)
13238 (call-interactively 'org-table-edit-formulas))
13239 ((save-excursion
13240 (beginning-of-line 1)
13241 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13242 (find-file (org-trim (match-string 1))))
13243 ((org-edit-src-code))
13244 ((org-edit-fixed-width-region))
13245 (t (call-interactively 'ffap))))
13246
13247 (defun org-ctrl-c-ctrl-c (&optional arg)
13248 "Set tags in headline, or update according to changed information at point.
13249
13250 This command does many different things, depending on context:
13251
13252 - If the cursor is in a headline, prompt for tags and insert them
13253 into the current line, aligned to `org-tags-column'. When called
13254 with prefix arg, realign all tags in the current buffer.
13255
13256 - If the cursor is in one of the special #+KEYWORD lines, this
13257 triggers scanning the buffer for these lines and updating the
13258 information.
13259
13260 - If the cursor is inside a table, realign the table. This command
13261 works even if the automatic table editor has been turned off.
13262
13263 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13264 the entire table.
13265
13266 - If the cursor is at a footnote reference or definition, jump to
13267 the corresponding definition or references, respectively.
13268
13269 - If the cursor is a the beginning of a dynamic block, update it.
13270
13271 - If the cursor is inside a table created by the table.el package,
13272 activate that table.
13273
13274 - If the current buffer is a remember buffer, close note and file
13275 it. A prefix argument of 1 files to the default location
13276 without further interaction. A prefix argument of 2 files to
13277 the currently clocking task.
13278
13279 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13280 links in this buffer.
13281
13282 - If the cursor is on a numbered item in a plain list, renumber the
13283 ordered list.
13284
13285 - If the cursor is on a checkbox, toggle it."
13286 (interactive "P")
13287 (let ((org-enable-table-editor t))
13288 (cond
13289 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13290 org-occur-highlights
13291 org-latex-fragment-image-overlays)
13292 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13293 (org-remove-occur-highlights)
13294 (org-remove-latex-fragment-image-overlays)
13295 (message "Temporary highlights/overlays removed from current buffer"))
13296 ((and (local-variable-p 'org-finish-function (current-buffer))
13297 (fboundp org-finish-function))
13298 (funcall org-finish-function))
13299 ((org-at-property-p)
13300 (call-interactively 'org-property-action))
13301 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13302 ((org-on-heading-p) (call-interactively 'org-set-tags))
13303 ((org-at-table.el-p)
13304 (require 'table)
13305 (beginning-of-line 1)
13306 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13307 (call-interactively 'table-recognize-table))
13308 ((org-at-table-p)
13309 (org-table-maybe-eval-formula)
13310 (if arg
13311 (call-interactively 'org-table-recalculate)
13312 (org-table-maybe-recalculate-line))
13313 (call-interactively 'org-table-align))
13314 ((or (org-footnote-at-reference-p)
13315 (org-footnote-at-definition-p))
13316 (call-interactively 'org-footnote-action))
13317 ((org-at-item-checkbox-p)
13318 (call-interactively 'org-toggle-checkbox))
13319 ((org-at-item-p)
13320 (call-interactively 'org-maybe-renumber-ordered-list))
13321 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13322 ;; Dynamic block
13323 (beginning-of-line 1)
13324 (save-excursion (org-update-dblock)))
13325 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13326 (cond
13327 ((equal (match-string 1) "TBLFM")
13328 ;; Recalculate the table before this line
13329 (save-excursion
13330 (beginning-of-line 1)
13331 (skip-chars-backward " \r\n\t")
13332 (if (org-at-table-p)
13333 (org-call-with-arg 'org-table-recalculate t))))
13334 (t
13335 ; (org-set-regexps-and-options)
13336 ; (org-restart-font-lock)
13337 (let ((org-inhibit-startup t)) (org-mode-restart))
13338 (message "Local setup has been refreshed"))))
13339 (t (error "C-c C-c can do nothing useful at this location.")))))
13340
13341 (defun org-mode-restart ()
13342 "Restart Org-mode, to scan again for special lines.
13343 Also updates the keyword regular expressions."
13344 (interactive)
13345 (org-mode)
13346 (message "Org-mode restarted"))
13347
13348 (defun org-kill-note-or-show-branches ()
13349 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13350 (interactive)
13351 (if (not org-finish-function)
13352 (call-interactively 'show-branches)
13353 (let ((org-note-abort t))
13354 (funcall org-finish-function))))
13355
13356 (defun org-return (&optional indent)
13357 "Goto next table row or insert a newline.
13358 Calls `org-table-next-row' or `newline', depending on context.
13359 See the individual commands for more information."
13360 (interactive)
13361 (cond
13362 ((bobp) (if indent (newline-and-indent) (newline)))
13363 ((and (org-at-heading-p)
13364 (looking-at
13365 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13366 (org-show-entry)
13367 (end-of-line 1)
13368 (newline))
13369 ((org-at-table-p)
13370 (org-table-justify-field-maybe)
13371 (call-interactively 'org-table-next-row))
13372 (t (if indent (newline-and-indent) (newline)))))
13373
13374 (defun org-return-indent ()
13375 "Goto next table row or insert a newline and indent.
13376 Calls `org-table-next-row' or `newline-and-indent', depending on
13377 context. See the individual commands for more information."
13378 (interactive)
13379 (org-return t))
13380
13381 (defun org-ctrl-c-star ()
13382 "Compute table, or change heading status of lines.
13383 Calls `org-table-recalculate' or `org-toggle-heading',
13384 depending on context."
13385 (interactive)
13386 (cond
13387 ((org-at-table-p)
13388 (call-interactively 'org-table-recalculate))
13389 (t
13390 ;; Convert all lines in region to list items
13391 (call-interactively 'org-toggle-heading))))
13392
13393 (defun org-ctrl-c-minus ()
13394 "Insert separator line in table or modify bullet status of line.
13395 Also turns a plain line or a region of lines into list items.
13396 Calls `org-table-insert-hline', `org-toggle-item', or
13397 `org-cycle-list-bullet', depending on context."
13398 (interactive)
13399 (cond
13400 ((org-at-table-p)
13401 (call-interactively 'org-table-insert-hline))
13402 ((org-region-active-p)
13403 (call-interactively 'org-toggle-item))
13404 ((org-in-item-p)
13405 (call-interactively 'org-cycle-list-bullet))
13406 (t
13407 (call-interactively 'org-toggle-item))))
13408
13409 (defun org-toggle-item ()
13410 "Convert headings or normal lines to items, items to normal lines.
13411 If there is no active region, only the current line is considered.
13412
13413 If the first line in the region is a headline, convert all headlines to items.
13414
13415 If the first line in the region is an item, convert all items to normal lines.
13416
13417 If the first line is normal text, add an item bullet to each line."
13418 (interactive)
13419 (let (l2 l beg end)
13420 (if (org-region-active-p)
13421 (setq beg (region-beginning) end (region-end))
13422 (setq beg (point-at-bol)
13423 end (min (1+ (point-at-eol)) (point-max))))
13424 (save-excursion
13425 (goto-char end)
13426 (setq l2 (org-current-line))
13427 (goto-char beg)
13428 (beginning-of-line 1)
13429 (setq l (1- (org-current-line)))
13430 (if (org-at-item-p)
13431 ;; We already have items, de-itemize
13432 (while (< (setq l (1+ l)) l2)
13433 (when (org-at-item-p)
13434 (goto-char (match-beginning 2))
13435 (delete-region (match-beginning 2) (match-end 2))
13436 (and (looking-at "[ \t]+") (replace-match "")))
13437 (beginning-of-line 2))
13438 (if (org-on-heading-p)
13439 ;; Headings, convert to items
13440 (while (< (setq l (1+ l)) l2)
13441 (if (looking-at org-outline-regexp)
13442 (replace-match "- " t t))
13443 (beginning-of-line 2))
13444 ;; normal lines, turn them into items
13445 (while (< (setq l (1+ l)) l2)
13446 (unless (org-at-item-p)
13447 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13448 (replace-match "\\1- \\2")))
13449 (beginning-of-line 2)))))))
13450
13451 (defun org-toggle-heading (&optional nstars)
13452 "Convert headings to normal text, or items or text to headings.
13453 If there is no active region, only the current line is considered.
13454
13455 If the first line is a heading, remove the stars from all headlines
13456 in the region.
13457
13458 If the first line is a plain list item, turn all plain list items into
13459 headings.
13460
13461 If the first line is a normal line, turn each and every line in the region
13462 into a heading.
13463
13464 When converting a line into a heading, the number of stars is chosen
13465 such that the lines become children of the current entry. However, when
13466 a prefix argument is given, its value determines the number of stars to add."
13467 (interactive "P")
13468 (let (l2 l itemp beg end)
13469 (if (org-region-active-p)
13470 (setq beg (region-beginning) end (region-end))
13471 (setq beg (point-at-bol)
13472 end (min (1+ (point-at-eol)) (point-max))))
13473 (save-excursion
13474 (goto-char end)
13475 (setq l2 (org-current-line))
13476 (goto-char beg)
13477 (beginning-of-line 1)
13478 (setq l (1- (org-current-line)))
13479 (if (org-on-heading-p)
13480 ;; We already have headlines, de-star them
13481 (while (< (setq l (1+ l)) l2)
13482 (when (org-on-heading-p t)
13483 (and (looking-at outline-regexp) (replace-match "")))
13484 (beginning-of-line 2))
13485 (setq itemp (org-at-item-p))
13486 (let* ((stars
13487 (if nstars
13488 (make-string (prefix-numeric-value current-prefix-arg)
13489 ?*)
13490 (save-excursion
13491 (re-search-backward org-complex-heading-regexp nil t)
13492 (or (match-string 1) "*"))))
13493 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
13494 (rpl (concat stars add-stars " ")))
13495 (while (< (setq l (1+ l)) l2)
13496 (if itemp
13497 (and (org-at-item-p) (replace-match rpl t t))
13498 (unless (org-on-heading-p)
13499 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13500 (replace-match (concat rpl (match-string 2))))))
13501 (beginning-of-line 2)))))))
13502
13503 (defun org-meta-return (&optional arg)
13504 "Insert a new heading or wrap a region in a table.
13505 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13506 See the individual commands for more information."
13507 (interactive "P")
13508 (cond
13509 ((org-at-table-p)
13510 (call-interactively 'org-table-wrap-region))
13511 (t (call-interactively 'org-insert-heading))))
13512
13513 ;;; Menu entries
13514
13515 ;; Define the Org-mode menus
13516 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13517 '("Tbl"
13518 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13519 ["Next Field" org-cycle (org-at-table-p)]
13520 ["Previous Field" org-shifttab (org-at-table-p)]
13521 ["Next Row" org-return (org-at-table-p)]
13522 "--"
13523 ["Blank Field" org-table-blank-field (org-at-table-p)]
13524 ["Edit Field" org-table-edit-field (org-at-table-p)]
13525 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13526 "--"
13527 ("Column"
13528 ["Move Column Left" org-metaleft (org-at-table-p)]
13529 ["Move Column Right" org-metaright (org-at-table-p)]
13530 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13531 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13532 ("Row"
13533 ["Move Row Up" org-metaup (org-at-table-p)]
13534 ["Move Row Down" org-metadown (org-at-table-p)]
13535 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13536 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13537 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13538 "--"
13539 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13540 ("Rectangle"
13541 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13542 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13543 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13544 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13545 "--"
13546 ("Calculate"
13547 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13548 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13549 ["Edit Formulas" org-edit-special (org-at-table-p)]
13550 "--"
13551 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13552 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13553 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13554 "--"
13555 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13556 "--"
13557 ["Sum Column/Rectangle" org-table-sum
13558 (or (org-at-table-p) (org-region-active-p))]
13559 ["Which Column?" org-table-current-column (org-at-table-p)])
13560 ["Debug Formulas"
13561 org-table-toggle-formula-debugger
13562 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13563 ["Show Col/Row Numbers"
13564 org-table-toggle-coordinate-overlays
13565 :style toggle
13566 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13567 "--"
13568 ["Create" org-table-create (and (not (org-at-table-p))
13569 org-enable-table-editor)]
13570 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13571 ["Import from File" org-table-import (not (org-at-table-p))]
13572 ["Export to File" org-table-export (org-at-table-p)]
13573 "--"
13574 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13575
13576 (easy-menu-define org-org-menu org-mode-map "Org menu"
13577 '("Org"
13578 ("Show/Hide"
13579 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13580 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13581 ["Sparse Tree..." org-sparse-tree t]
13582 ["Reveal Context" org-reveal t]
13583 ["Show All" show-all t]
13584 "--"
13585 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13586 "--"
13587 ["New Heading" org-insert-heading t]
13588 ("Navigate Headings"
13589 ["Up" outline-up-heading t]
13590 ["Next" outline-next-visible-heading t]
13591 ["Previous" outline-previous-visible-heading t]
13592 ["Next Same Level" outline-forward-same-level t]
13593 ["Previous Same Level" outline-backward-same-level t]
13594 "--"
13595 ["Jump" org-goto t])
13596 ("Edit Structure"
13597 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13598 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13599 "--"
13600 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13601 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13602 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13603 "--"
13604 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13605 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13606 ["Demote Heading" org-metaright (not (org-at-table-p))]
13607 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13608 "--"
13609 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13610 "--"
13611 ["Convert to odd levels" org-convert-to-odd-levels t]
13612 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13613 ("Editing"
13614 ["Emphasis..." org-emphasize t]
13615 ["Edit Source Example" org-edit-special t]
13616 "--"
13617 ["Footnote new/jump" org-footnote-action t]
13618 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13619 ("Archive"
13620 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13621 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13622 ; :active t :keys "C-u C-c C-x C-a"]
13623 ["Sparse trees open ARCHIVE trees"
13624 (setq org-sparse-tree-open-archived-trees
13625 (not org-sparse-tree-open-archived-trees))
13626 :style toggle :selected org-sparse-tree-open-archived-trees]
13627 ["Cycling opens ARCHIVE trees"
13628 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13629 :style toggle :selected org-cycle-open-archived-trees]
13630 "--"
13631 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13632 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13633 ; ["Check and Move Children" (org-archive-subtree '(4))
13634 ; :active t :keys "C-u C-c C-x C-s"]
13635 )
13636 "--"
13637 ("TODO Lists"
13638 ["TODO/DONE/-" org-todo t]
13639 ("Select keyword"
13640 ["Next keyword" org-shiftright (org-on-heading-p)]
13641 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13642 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13643 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13644 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13645 ["Show TODO Tree" org-show-todo-tree t]
13646 ["Global TODO list" org-todo-list t]
13647 "--"
13648 ["Set Priority" org-priority t]
13649 ["Priority Up" org-shiftup t]
13650 ["Priority Down" org-shiftdown t])
13651 ("TAGS and Properties"
13652 ["Set Tags" org-set-tags-command t]
13653 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13654 "--"
13655 ["Set property" org-set-property t]
13656 ["Column view of properties" org-columns t]
13657 ["Insert Column View DBlock" org-insert-columns-dblock t])
13658 ("Dates and Scheduling"
13659 ["Timestamp" org-time-stamp t]
13660 ["Timestamp (inactive)" org-time-stamp-inactive t]
13661 ("Change Date"
13662 ["1 Day Later" org-shiftright t]
13663 ["1 Day Earlier" org-shiftleft t]
13664 ["1 ... Later" org-shiftup t]
13665 ["1 ... Earlier" org-shiftdown t])
13666 ["Compute Time Range" org-evaluate-time-range t]
13667 ["Schedule Item" org-schedule t]
13668 ["Deadline" org-deadline t]
13669 "--"
13670 ["Custom time format" org-toggle-time-stamp-overlays
13671 :style radio :selected org-display-custom-times]
13672 "--"
13673 ["Goto Calendar" org-goto-calendar t]
13674 ["Date from Calendar" org-date-from-calendar t]
13675 "--"
13676 ["Start/Restart Timer" org-timer-start t]
13677 ["Pause/Continue Timer" org-timer-pause-or-continue t]
13678 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
13679 ["Insert Timer String" org-timer t]
13680 ["Insert Timer Item" org-timer-item t])
13681 ("Logging work"
13682 ["Clock in" org-clock-in t]
13683 ["Clock out" org-clock-out t]
13684 ["Clock cancel" org-clock-cancel t]
13685 ["Goto running clock" org-clock-goto t]
13686 ["Display times" org-clock-display t]
13687 ["Create clock table" org-clock-report t]
13688 "--"
13689 ["Record DONE time"
13690 (progn (setq org-log-done (not org-log-done))
13691 (message "Switching to %s will %s record a timestamp"
13692 (car org-done-keywords)
13693 (if org-log-done "automatically" "not")))
13694 :style toggle :selected org-log-done])
13695 "--"
13696 ["Agenda Command..." org-agenda t]
13697 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13698 ("File List for Agenda")
13699 ("Special views current file"
13700 ["TODO Tree" org-show-todo-tree t]
13701 ["Check Deadlines" org-check-deadlines t]
13702 ["Timeline" org-timeline t]
13703 ["Tags Tree" org-tags-sparse-tree t])
13704 "--"
13705 ("Hyperlinks"
13706 ["Store Link (Global)" org-store-link t]
13707 ["Insert Link" org-insert-link t]
13708 ["Follow Link" org-open-at-point t]
13709 "--"
13710 ["Next link" org-next-link t]
13711 ["Previous link" org-previous-link t]
13712 "--"
13713 ["Descriptive Links"
13714 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13715 :style radio
13716 :selected (member '(org-link) buffer-invisibility-spec)]
13717 ["Literal Links"
13718 (progn
13719 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13720 :style radio
13721 :selected (not (member '(org-link) buffer-invisibility-spec))])
13722 "--"
13723 ["Export/Publish..." org-export t]
13724 ("LaTeX"
13725 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13726 :selected org-cdlatex-mode]
13727 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13728 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13729 ["Modify math symbol" org-cdlatex-math-modify
13730 (org-inside-LaTeX-fragment-p)]
13731 ["Export LaTeX fragments as images"
13732 (if (featurep 'org-exp)
13733 (setq org-export-with-LaTeX-fragments
13734 (not org-export-with-LaTeX-fragments))
13735 (require 'org-exp))
13736 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13737 org-export-with-LaTeX-fragments)])
13738 "--"
13739 ("Documentation"
13740 ["Show Version" org-version t]
13741 ["Info Documentation" org-info t])
13742 ("Customize"
13743 ["Browse Org Group" org-customize t]
13744 "--"
13745 ["Expand This Menu" org-create-customize-menu
13746 (fboundp 'customize-menu-create)])
13747 "--"
13748 ["Refresh setup" org-mode-restart t]
13749 ))
13750
13751 (defun org-info (&optional node)
13752 "Read documentation for Org-mode in the info system.
13753 With optional NODE, go directly to that node."
13754 (interactive)
13755 (info (format "(org)%s" (or node ""))))
13756
13757 (defun org-install-agenda-files-menu ()
13758 (let ((bl (buffer-list)))
13759 (save-excursion
13760 (while bl
13761 (set-buffer (pop bl))
13762 (if (org-mode-p) (setq bl nil)))
13763 (when (org-mode-p)
13764 (easy-menu-change
13765 '("Org") "File List for Agenda"
13766 (append
13767 (list
13768 ["Edit File List" (org-edit-agenda-file-list) t]
13769 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13770 ["Remove Current File from List" org-remove-file t]
13771 ["Cycle through agenda files" org-cycle-agenda-files t]
13772 ["Occur in all agenda files" org-occur-in-agenda-files t]
13773 "--")
13774 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13775
13776 ;;;; Documentation
13777
13778 ;;;###autoload
13779 (defun org-require-autoloaded-modules ()
13780 (interactive)
13781 (mapc 'require
13782 '(org-agenda org-archive org-clock org-colview
13783 org-exp org-id org-export-latex org-publish
13784 org-remember org-table)))
13785
13786 ;;;###autoload
13787 (defun org-customize ()
13788 "Call the customize function with org as argument."
13789 (interactive)
13790 (org-load-modules-maybe)
13791 (org-require-autoloaded-modules)
13792 (customize-browse 'org))
13793
13794 (defun org-create-customize-menu ()
13795 "Create a full customization menu for Org-mode, insert it into the menu."
13796 (interactive)
13797 (org-load-modules-maybe)
13798 (org-require-autoloaded-modules)
13799 (if (fboundp 'customize-menu-create)
13800 (progn
13801 (easy-menu-change
13802 '("Org") "Customize"
13803 `(["Browse Org group" org-customize t]
13804 "--"
13805 ,(customize-menu-create 'org)
13806 ["Set" Custom-set t]
13807 ["Save" Custom-save t]
13808 ["Reset to Current" Custom-reset-current t]
13809 ["Reset to Saved" Custom-reset-saved t]
13810 ["Reset to Standard Settings" Custom-reset-standard t]))
13811 (message "\"Org\"-menu now contains full customization menu"))
13812 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13813
13814 ;;;; Miscellaneous stuff
13815
13816 ;;; Generally useful functions
13817
13818 (defun org-find-text-property-in-string (prop s)
13819 "Return the first non-nil value of property PROP in string S."
13820 (or (get-text-property 0 prop s)
13821 (get-text-property (or (next-single-property-change 0 prop s) 0)
13822 prop s)))
13823
13824 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13825 "Display the given MESSAGE as a warning."
13826 (if (fboundp 'display-warning)
13827 (display-warning 'org message
13828 (if (featurep 'xemacs)
13829 'warning
13830 :warning))
13831 (let ((buf (get-buffer-create "*Org warnings*")))
13832 (with-current-buffer buf
13833 (goto-char (point-max))
13834 (insert "Warning (Org): " message)
13835 (unless (bolp)
13836 (newline)))
13837 (display-buffer buf)
13838 (sit-for 0))))
13839
13840 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13841 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13842 (if (and marker (marker-buffer marker)
13843 (buffer-live-p (marker-buffer marker)))
13844 (progn
13845 (switch-to-buffer (marker-buffer marker))
13846 (if (or (> marker (point-max)) (< marker (point-min)))
13847 (widen))
13848 (goto-char marker)
13849 (org-show-context 'org-goto))
13850 (if bookmark
13851 (bookmark-jump bookmark)
13852 (error "Cannot find location"))))
13853
13854 (defun org-quote-csv-field (s)
13855 "Quote field for inclusion in CSV material."
13856 (if (string-match "[\",]" s)
13857 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13858 s))
13859
13860 (defun org-plist-delete (plist property)
13861 "Delete PROPERTY from PLIST.
13862 This is in contrast to merely setting it to 0."
13863 (let (p)
13864 (while plist
13865 (if (not (eq property (car plist)))
13866 (setq p (plist-put p (car plist) (nth 1 plist))))
13867 (setq plist (cddr plist)))
13868 p))
13869
13870 (defun org-force-self-insert (N)
13871 "Needed to enforce self-insert under remapping."
13872 (interactive "p")
13873 (self-insert-command N))
13874
13875 (defun org-string-width (s)
13876 "Compute width of string, ignoring invisible characters.
13877 This ignores character with invisibility property `org-link', and also
13878 characters with property `org-cwidth', because these will become invisible
13879 upon the next fontification round."
13880 (let (b l)
13881 (when (or (eq t buffer-invisibility-spec)
13882 (assq 'org-link buffer-invisibility-spec))
13883 (while (setq b (text-property-any 0 (length s)
13884 'invisible 'org-link s))
13885 (setq s (concat (substring s 0 b)
13886 (substring s (or (next-single-property-change
13887 b 'invisible s) (length s)))))))
13888 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13889 (setq s (concat (substring s 0 b)
13890 (substring s (or (next-single-property-change
13891 b 'org-cwidth s) (length s))))))
13892 (setq l (string-width s) b -1)
13893 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13894 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13895 l))
13896
13897 (defun org-get-indentation (&optional line)
13898 "Get the indentation of the current line, interpreting tabs.
13899 When LINE is given, assume it represents a line and compute its indentation."
13900 (if line
13901 (if (string-match "^ *" (org-remove-tabs line))
13902 (match-end 0))
13903 (save-excursion
13904 (beginning-of-line 1)
13905 (skip-chars-forward " \t")
13906 (current-column))))
13907
13908 (defun org-remove-tabs (s &optional width)
13909 "Replace tabulators in S with spaces.
13910 Assumes that s is a single line, starting in column 0."
13911 (setq width (or width tab-width))
13912 (while (string-match "\t" s)
13913 (setq s (replace-match
13914 (make-string
13915 (- (* width (/ (+ (match-beginning 0) width) width))
13916 (match-beginning 0)) ?\ )
13917 t t s)))
13918 s)
13919
13920 (defun org-fix-indentation (line ind)
13921 "Fix indentation in LINE.
13922 IND is a cons cell with target and minimum indentation.
13923 If the current indentation in LINE is smaller than the minimum,
13924 leave it alone. If it is larger than ind, set it to the target."
13925 (let* ((l (org-remove-tabs line))
13926 (i (org-get-indentation l))
13927 (i1 (car ind)) (i2 (cdr ind)))
13928 (if (>= i i2) (setq l (substring line i2)))
13929 (if (> i1 0)
13930 (concat (make-string i1 ?\ ) l)
13931 l)))
13932
13933 (defun org-base-buffer (buffer)
13934 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13935 (if (not buffer)
13936 buffer
13937 (or (buffer-base-buffer buffer)
13938 buffer)))
13939
13940 (defun org-trim (s)
13941 "Remove whitespace at beginning and end of string."
13942 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13943 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13944 s)
13945
13946 (defun org-wrap (string &optional width lines)
13947 "Wrap string to either a number of lines, or a width in characters.
13948 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13949 that costs. If there is a word longer than WIDTH, the text is actually
13950 wrapped to the length of that word.
13951 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13952 many lines, whatever width that takes.
13953 The return value is a list of lines, without newlines at the end."
13954 (let* ((words (org-split-string string "[ \t\n]+"))
13955 (maxword (apply 'max (mapcar 'org-string-width words)))
13956 w ll)
13957 (cond (width
13958 (org-do-wrap words (max maxword width)))
13959 (lines
13960 (setq w maxword)
13961 (setq ll (org-do-wrap words maxword))
13962 (if (<= (length ll) lines)
13963 ll
13964 (setq ll words)
13965 (while (> (length ll) lines)
13966 (setq w (1+ w))
13967 (setq ll (org-do-wrap words w)))
13968 ll))
13969 (t (error "Cannot wrap this")))))
13970
13971 (defun org-do-wrap (words width)
13972 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13973 (let (lines line)
13974 (while words
13975 (setq line (pop words))
13976 (while (and words (< (+ (length line) (length (car words))) width))
13977 (setq line (concat line " " (pop words))))
13978 (setq lines (push line lines)))
13979 (nreverse lines)))
13980
13981 (defun org-split-string (string &optional separators)
13982 "Splits STRING into substrings at SEPARATORS.
13983 No empty strings are returned if there are matches at the beginning
13984 and end of string."
13985 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13986 (start 0)
13987 notfirst
13988 (list nil))
13989 (while (and (string-match rexp string
13990 (if (and notfirst
13991 (= start (match-beginning 0))
13992 (< start (length string)))
13993 (1+ start) start))
13994 (< (match-beginning 0) (length string)))
13995 (setq notfirst t)
13996 (or (eq (match-beginning 0) 0)
13997 (and (eq (match-beginning 0) (match-end 0))
13998 (eq (match-beginning 0) start))
13999 (setq list
14000 (cons (substring string start (match-beginning 0))
14001 list)))
14002 (setq start (match-end 0)))
14003 (or (eq start (length string))
14004 (setq list
14005 (cons (substring string start)
14006 list)))
14007 (nreverse list)))
14008
14009 (defun org-context ()
14010 "Return a list of contexts of the current cursor position.
14011 If several contexts apply, all are returned.
14012 Each context entry is a list with a symbol naming the context, and
14013 two positions indicating start and end of the context. Possible
14014 contexts are:
14015
14016 :headline anywhere in a headline
14017 :headline-stars on the leading stars in a headline
14018 :todo-keyword on a TODO keyword (including DONE) in a headline
14019 :tags on the TAGS in a headline
14020 :priority on the priority cookie in a headline
14021 :item on the first line of a plain list item
14022 :item-bullet on the bullet/number of a plain list item
14023 :checkbox on the checkbox in a plain list item
14024 :table in an org-mode table
14025 :table-special on a special filed in a table
14026 :table-table in a table.el table
14027 :link on a hyperlink
14028 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14029 :target on a <<target>>
14030 :radio-target on a <<<radio-target>>>
14031 :latex-fragment on a LaTeX fragment
14032 :latex-preview on a LaTeX fragment with overlayed preview image
14033
14034 This function expects the position to be visible because it uses font-lock
14035 faces as a help to recognize the following contexts: :table-special, :link,
14036 and :keyword."
14037 (let* ((f (get-text-property (point) 'face))
14038 (faces (if (listp f) f (list f)))
14039 (p (point)) clist o)
14040 ;; First the large context
14041 (cond
14042 ((org-on-heading-p t)
14043 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14044 (when (progn
14045 (beginning-of-line 1)
14046 (looking-at org-todo-line-tags-regexp))
14047 (push (org-point-in-group p 1 :headline-stars) clist)
14048 (push (org-point-in-group p 2 :todo-keyword) clist)
14049 (push (org-point-in-group p 4 :tags) clist))
14050 (goto-char p)
14051 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14052 (if (looking-at "\\[#[A-Z0-9]\\]")
14053 (push (org-point-in-group p 0 :priority) clist)))
14054
14055 ((org-at-item-p)
14056 (push (org-point-in-group p 2 :item-bullet) clist)
14057 (push (list :item (point-at-bol)
14058 (save-excursion (org-end-of-item) (point)))
14059 clist)
14060 (and (org-at-item-checkbox-p)
14061 (push (org-point-in-group p 0 :checkbox) clist)))
14062
14063 ((org-at-table-p)
14064 (push (list :table (org-table-begin) (org-table-end)) clist)
14065 (if (memq 'org-formula faces)
14066 (push (list :table-special
14067 (previous-single-property-change p 'face)
14068 (next-single-property-change p 'face)) clist)))
14069 ((org-at-table-p 'any)
14070 (push (list :table-table) clist)))
14071 (goto-char p)
14072
14073 ;; Now the small context
14074 (cond
14075 ((org-at-timestamp-p)
14076 (push (org-point-in-group p 0 :timestamp) clist))
14077 ((memq 'org-link faces)
14078 (push (list :link
14079 (previous-single-property-change p 'face)
14080 (next-single-property-change p 'face)) clist))
14081 ((memq 'org-special-keyword faces)
14082 (push (list :keyword
14083 (previous-single-property-change p 'face)
14084 (next-single-property-change p 'face)) clist))
14085 ((org-on-target-p)
14086 (push (org-point-in-group p 0 :target) clist)
14087 (goto-char (1- (match-beginning 0)))
14088 (if (looking-at org-radio-target-regexp)
14089 (push (org-point-in-group p 0 :radio-target) clist))
14090 (goto-char p))
14091 ((setq o (car (delq nil
14092 (mapcar
14093 (lambda (x)
14094 (if (memq x org-latex-fragment-image-overlays) x))
14095 (org-overlays-at (point))))))
14096 (push (list :latex-fragment
14097 (org-overlay-start o) (org-overlay-end o)) clist)
14098 (push (list :latex-preview
14099 (org-overlay-start o) (org-overlay-end o)) clist))
14100 ((org-inside-LaTeX-fragment-p)
14101 ;; FIXME: positions wrong.
14102 (push (list :latex-fragment (point) (point)) clist)))
14103
14104 (setq clist (nreverse (delq nil clist)))
14105 clist))
14106
14107 ;; FIXME: Compare with at-regexp-p Do we need both?
14108 (defun org-in-regexp (re &optional nlines visually)
14109 "Check if point is inside a match of regexp.
14110 Normally only the current line is checked, but you can include NLINES extra
14111 lines both before and after point into the search.
14112 If VISUALLY is set, require that the cursor is not after the match but
14113 really on, so that the block visually is on the match."
14114 (catch 'exit
14115 (let ((pos (point))
14116 (eol (point-at-eol (+ 1 (or nlines 0))))
14117 (inc (if visually 1 0)))
14118 (save-excursion
14119 (beginning-of-line (- 1 (or nlines 0)))
14120 (while (re-search-forward re eol t)
14121 (if (and (<= (match-beginning 0) pos)
14122 (>= (+ inc (match-end 0)) pos))
14123 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14124
14125 (defun org-at-regexp-p (regexp)
14126 "Is point inside a match of REGEXP in the current line?"
14127 (catch 'exit
14128 (save-excursion
14129 (let ((pos (point)) (end (point-at-eol)))
14130 (beginning-of-line 1)
14131 (while (re-search-forward regexp end t)
14132 (if (and (<= (match-beginning 0) pos)
14133 (>= (match-end 0) pos))
14134 (throw 'exit t)))
14135 nil))))
14136
14137 (defun org-occur-in-agenda-files (regexp &optional nlines)
14138 "Call `multi-occur' with buffers for all agenda files."
14139 (interactive "sOrg-files matching: \np")
14140 (let* ((files (org-agenda-files))
14141 (tnames (mapcar 'file-truename files))
14142 (extra org-agenda-text-search-extra-files)
14143 f)
14144 (when (eq (car extra) 'agenda-archives)
14145 (setq extra (cdr extra))
14146 (setq files (org-add-archive-files files)))
14147 (while (setq f (pop extra))
14148 (unless (member (file-truename f) tnames)
14149 (add-to-list 'files f 'append)
14150 (add-to-list 'tnames (file-truename f) 'append)))
14151 (multi-occur
14152 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14153 regexp)))
14154
14155 (if (boundp 'occur-mode-find-occurrence-hook)
14156 ;; Emacs 23
14157 (add-hook 'occur-mode-find-occurrence-hook
14158 (lambda ()
14159 (when (org-mode-p)
14160 (org-reveal))))
14161 ;; Emacs 22
14162 (defadvice occur-mode-goto-occurrence
14163 (after org-occur-reveal activate)
14164 (and (org-mode-p) (org-reveal)))
14165 (defadvice occur-mode-goto-occurrence-other-window
14166 (after org-occur-reveal activate)
14167 (and (org-mode-p) (org-reveal)))
14168 (defadvice occur-mode-display-occurrence
14169 (after org-occur-reveal activate)
14170 (when (org-mode-p)
14171 (let ((pos (occur-mode-find-occurrence)))
14172 (with-current-buffer (marker-buffer pos)
14173 (save-excursion
14174 (goto-char pos)
14175 (org-reveal)))))))
14176
14177 (defun org-uniquify (list)
14178 "Remove duplicate elements from LIST."
14179 (let (res)
14180 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14181 res))
14182
14183 (defun org-delete-all (elts list)
14184 "Remove all elements in ELTS from LIST."
14185 (while elts
14186 (setq list (delete (pop elts) list)))
14187 list)
14188
14189 (defun org-back-over-empty-lines ()
14190 "Move backwards over whitespace, to the beginning of the first empty line.
14191 Returns the number of empty lines passed."
14192 (let ((pos (point)))
14193 (skip-chars-backward " \t\n\r")
14194 (beginning-of-line 2)
14195 (goto-char (min (point) pos))
14196 (count-lines (point) pos)))
14197
14198 (defun org-skip-whitespace ()
14199 (skip-chars-forward " \t\n\r"))
14200
14201 (defun org-point-in-group (point group &optional context)
14202 "Check if POINT is in match-group GROUP.
14203 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14204 match. If the match group does ot exist or point is not inside it,
14205 return nil."
14206 (and (match-beginning group)
14207 (>= point (match-beginning group))
14208 (<= point (match-end group))
14209 (if context
14210 (list context (match-beginning group) (match-end group))
14211 t)))
14212
14213 (defun org-switch-to-buffer-other-window (&rest args)
14214 "Switch to buffer in a second window on the current frame.
14215 In particular, do not allow pop-up frames."
14216 (let (pop-up-frames special-display-buffer-names special-display-regexps
14217 special-display-function)
14218 (apply 'switch-to-buffer-other-window args)))
14219
14220 (defun org-combine-plists (&rest plists)
14221 "Create a single property list from all plists in PLISTS.
14222 The process starts by copying the first list, and then setting properties
14223 from the other lists. Settings in the last list are the most significant
14224 ones and overrule settings in the other lists."
14225 (let ((rtn (copy-sequence (pop plists)))
14226 p v ls)
14227 (while plists
14228 (setq ls (pop plists))
14229 (while ls
14230 (setq p (pop ls) v (pop ls))
14231 (setq rtn (plist-put rtn p v))))
14232 rtn))
14233
14234 (defun org-move-line-down (arg)
14235 "Move the current line down. With prefix argument, move it past ARG lines."
14236 (interactive "p")
14237 (let ((col (current-column))
14238 beg end pos)
14239 (beginning-of-line 1) (setq beg (point))
14240 (beginning-of-line 2) (setq end (point))
14241 (beginning-of-line (+ 1 arg))
14242 (setq pos (move-marker (make-marker) (point)))
14243 (insert (delete-and-extract-region beg end))
14244 (goto-char pos)
14245 (org-move-to-column col)))
14246
14247 (defun org-move-line-up (arg)
14248 "Move the current line up. With prefix argument, move it past ARG lines."
14249 (interactive "p")
14250 (let ((col (current-column))
14251 beg end pos)
14252 (beginning-of-line 1) (setq beg (point))
14253 (beginning-of-line 2) (setq end (point))
14254 (beginning-of-line (- arg))
14255 (setq pos (move-marker (make-marker) (point)))
14256 (insert (delete-and-extract-region beg end))
14257 (goto-char pos)
14258 (org-move-to-column col)))
14259
14260 (defun org-replace-escapes (string table)
14261 "Replace %-escapes in STRING with values in TABLE.
14262 TABLE is an association list with keys like \"%a\" and string values.
14263 The sequences in STRING may contain normal field width and padding information,
14264 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14265 so values can contain further %-escapes if they are define later in TABLE."
14266 (let ((case-fold-search nil)
14267 e re rpl)
14268 (while (setq e (pop table))
14269 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14270 (while (string-match re string)
14271 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14272 (cdr e)))
14273 (setq string (replace-match rpl t t string))))
14274 string))
14275
14276
14277 (defun org-sublist (list start end)
14278 "Return a section of LIST, from START to END.
14279 Counting starts at 1."
14280 (let (rtn (c start))
14281 (setq list (nthcdr (1- start) list))
14282 (while (and list (<= c end))
14283 (push (pop list) rtn)
14284 (setq c (1+ c)))
14285 (nreverse rtn)))
14286
14287 (defun org-find-base-buffer-visiting (file)
14288 "Like `find-buffer-visiting' but alway return the base buffer and
14289 not an indirect buffer."
14290 (let ((buf (find-buffer-visiting file)))
14291 (if buf
14292 (or (buffer-base-buffer buf) buf)
14293 nil)))
14294
14295 (defun org-image-file-name-regexp (&optional extensions)
14296 "Return regexp matching the file names of images.
14297 If EXTENSIONS is given, only match these."
14298 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14299 (image-file-name-regexp)
14300 (let ((image-file-name-extensions
14301 (or extensions
14302 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14303 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14304 (concat "\\."
14305 (regexp-opt (nconc (mapcar 'upcase
14306 image-file-name-extensions)
14307 image-file-name-extensions)
14308 t)
14309 "\\'"))))
14310
14311 (defun org-file-image-p (file &optional extensions)
14312 "Return non-nil if FILE is an image."
14313 (save-match-data
14314 (string-match (org-image-file-name-regexp extensions) file)))
14315
14316 (defun org-get-cursor-date ()
14317 "Return the date at cursor in as a time.
14318 This works in the calendar and in the agenda, anywhere else it just
14319 returns the current time."
14320 (let (date day defd)
14321 (cond
14322 ((eq major-mode 'calendar-mode)
14323 (setq date (calendar-cursor-to-date)
14324 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14325 ((eq major-mode 'org-agenda-mode)
14326 (setq day (get-text-property (point) 'day))
14327 (if day
14328 (setq date (calendar-gregorian-from-absolute day)
14329 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14330 (nth 2 date))))))
14331 (or defd (current-time))))
14332
14333 (defvar org-agenda-action-marker (make-marker)
14334 "Marker pointing to the entry for the next agenda action.")
14335
14336 (defun org-mark-entry-for-agenda-action ()
14337 "Mark the current entry as target of an agenda action.
14338 Agenda actions are actions executed from the agenda with the key `k',
14339 which make use of the date at the cursor."
14340 (interactive)
14341 (move-marker org-agenda-action-marker
14342 (save-excursion (org-back-to-heading t) (point))
14343 (current-buffer))
14344 (message
14345 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14346
14347 ;;; Paragraph filling stuff.
14348 ;; We want this to be just right, so use the full arsenal.
14349
14350 (defun org-indent-line-function ()
14351 "Indent line like previous, but further if previous was headline or item."
14352 (interactive)
14353 (let* ((pos (point))
14354 (itemp (org-at-item-p))
14355 column bpos bcol tpos tcol bullet btype bullet-type)
14356 ;; Find the previous relevant line
14357 (beginning-of-line 1)
14358 (cond
14359 ((looking-at "#") (setq column 0))
14360 ((looking-at "\\*+ ") (setq column 0))
14361 (t
14362 (beginning-of-line 0)
14363 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14364 (beginning-of-line 0))
14365 (cond
14366 ((looking-at "\\*+[ \t]+")
14367 (if (not org-adapt-indentation)
14368 (setq column 0)
14369 (goto-char (match-end 0))
14370 (setq column (current-column))))
14371 ((org-in-item-p)
14372 (org-beginning-of-item)
14373 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14374 (setq bpos (match-beginning 1) tpos (match-end 0)
14375 bcol (progn (goto-char bpos) (current-column))
14376 tcol (progn (goto-char tpos) (current-column))
14377 bullet (match-string 1)
14378 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14379 (if (> tcol (+ bcol org-description-max-indent))
14380 (setq tcol (+ bcol 5)))
14381 (if (not itemp)
14382 (setq column tcol)
14383 (goto-char pos)
14384 (beginning-of-line 1)
14385 (if (looking-at "\\S-")
14386 (progn
14387 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14388 (setq bullet (match-string 1)
14389 btype (if (string-match "[0-9]" bullet) "n" bullet))
14390 (setq column (if (equal btype bullet-type) bcol tcol)))
14391 (setq column (org-get-indentation)))))
14392 (t (setq column (org-get-indentation))))))
14393 (goto-char pos)
14394 (if (<= (current-column) (current-indentation))
14395 (org-indent-line-to column)
14396 (save-excursion (org-indent-line-to column)))
14397 (setq column (current-column))
14398 (beginning-of-line 1)
14399 (if (looking-at
14400 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14401 (replace-match (concat "\\1" (format org-property-format
14402 (match-string 2) (match-string 3)))
14403 t nil))
14404 (org-move-to-column column)))
14405
14406 (defun org-set-autofill-regexps ()
14407 (interactive)
14408 ;; In the paragraph separator we include headlines, because filling
14409 ;; text in a line directly attached to a headline would otherwise
14410 ;; fill the headline as well.
14411 (org-set-local 'comment-start-skip "^#+[ \t]*")
14412 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14413 ;; The paragraph starter includes hand-formatted lists.
14414 (org-set-local 'paragraph-start
14415 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14416 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14417 ;; But only if the user has not turned off tables or fixed-width regions
14418 (org-set-local
14419 'auto-fill-inhibit-regexp
14420 (concat "\\*+ \\|#\\+"
14421 "\\|[ \t]*" org-keyword-time-regexp
14422 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14423 (concat
14424 "\\|[ \t]*["
14425 (if org-enable-table-editor "|" "")
14426 (if org-enable-fixed-width-editor ":" "")
14427 "]"))))
14428 ;; We use our own fill-paragraph function, to make sure that tables
14429 ;; and fixed-width regions are not wrapped. That function will pass
14430 ;; through to `fill-paragraph' when appropriate.
14431 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14432 ; Adaptive filling: To get full control, first make sure that
14433 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14434 (org-set-local 'adaptive-fill-regexp "\000")
14435 (org-set-local 'adaptive-fill-function
14436 'org-adaptive-fill-function)
14437 (org-set-local
14438 'align-mode-rules-list
14439 '((org-in-buffer-settings
14440 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14441 (modes . '(org-mode))))))
14442
14443 (defun org-fill-paragraph (&optional justify)
14444 "Re-align a table, pass through to fill-paragraph if no table."
14445 (let ((table-p (org-at-table-p))
14446 (table.el-p (org-at-table.el-p)))
14447 (cond ((and (equal (char-after (point-at-bol)) ?*)
14448 (save-excursion (goto-char (point-at-bol))
14449 (looking-at outline-regexp)))
14450 t) ; skip headlines
14451 (table.el-p t) ; skip table.el tables
14452 (table-p (org-table-align) t) ; align org-mode tables
14453 (t nil)))) ; call paragraph-fill
14454
14455 ;; For reference, this is the default value of adaptive-fill-regexp
14456 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14457
14458 (defun org-adaptive-fill-function ()
14459 "Return a fill prefix for org-mode files.
14460 In particular, this makes sure hanging paragraphs for hand-formatted lists
14461 work correctly."
14462 (cond ((looking-at "#[ \t]+")
14463 (match-string 0))
14464 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14465 (save-excursion
14466 (if (> (match-end 1) (+ (match-beginning 1)
14467 org-description-max-indent))
14468 (goto-char (+ (match-beginning 1) 5))
14469 (goto-char (match-end 0)))
14470 (make-string (current-column) ?\ )))
14471 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14472 (save-excursion
14473 (goto-char (match-end 0))
14474 (make-string (current-column) ?\ )))
14475 (t nil)))
14476
14477 ;;; Other stuff.
14478
14479 (defun org-toggle-fixed-width-section (arg)
14480 "Toggle the fixed-width export.
14481 If there is no active region, the QUOTE keyword at the current headline is
14482 inserted or removed. When present, it causes the text between this headline
14483 and the next to be exported as fixed-width text, and unmodified.
14484 If there is an active region, this command adds or removes a colon as the
14485 first character of this line. If the first character of a line is a colon,
14486 this line is also exported in fixed-width font."
14487 (interactive "P")
14488 (let* ((cc 0)
14489 (regionp (org-region-active-p))
14490 (beg (if regionp (region-beginning) (point)))
14491 (end (if regionp (region-end)))
14492 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14493 (case-fold-search nil)
14494 (re "[ \t]*\\(:\\)")
14495 off)
14496 (if regionp
14497 (save-excursion
14498 (goto-char beg)
14499 (setq cc (current-column))
14500 (beginning-of-line 1)
14501 (setq off (looking-at re))
14502 (while (> nlines 0)
14503 (setq nlines (1- nlines))
14504 (beginning-of-line 1)
14505 (cond
14506 (arg
14507 (org-move-to-column cc t)
14508 (insert ":\n")
14509 (forward-line -1))
14510 ((and off (looking-at re))
14511 (replace-match "" t t nil 1))
14512 ((not off) (org-move-to-column cc t) (insert ":")))
14513 (forward-line 1)))
14514 (save-excursion
14515 (org-back-to-heading)
14516 (if (looking-at (concat outline-regexp
14517 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14518 (replace-match "" t t nil 1)
14519 (if (looking-at outline-regexp)
14520 (progn
14521 (goto-char (match-end 0))
14522 (insert org-quote-string " "))))))))
14523
14524 ;;;; Functions extending outline functionality
14525
14526 (defun org-beginning-of-line (&optional arg)
14527 "Go to the beginning of the current line. If that is invisible, continue
14528 to a visible line beginning. This makes the function of C-a more intuitive.
14529 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14530 first attempt, and only move to after the tags when the cursor is already
14531 beyond the end of the headline."
14532 (interactive "P")
14533 (let ((pos (point)) refpos)
14534 (beginning-of-line 1)
14535 (if (bobp)
14536 nil
14537 (backward-char 1)
14538 (if (org-invisible-p)
14539 (while (and (not (bobp)) (org-invisible-p))
14540 (backward-char 1)
14541 (beginning-of-line 1))
14542 (forward-char 1)))
14543 (when org-special-ctrl-a/e
14544 (cond
14545 ((and (looking-at org-complex-heading-regexp)
14546 (= (char-after (match-end 1)) ?\ ))
14547 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14548 (point-at-eol)))
14549 (goto-char
14550 (if (eq org-special-ctrl-a/e t)
14551 (cond ((> pos refpos) refpos)
14552 ((= pos (point)) refpos)
14553 (t (point)))
14554 (cond ((> pos (point)) (point))
14555 ((not (eq last-command this-command)) (point))
14556 (t refpos)))))
14557 ((org-at-item-p)
14558 (goto-char
14559 (if (eq org-special-ctrl-a/e t)
14560 (cond ((> pos (match-end 4)) (match-end 4))
14561 ((= pos (point)) (match-end 4))
14562 (t (point)))
14563 (cond ((> pos (point)) (point))
14564 ((not (eq last-command this-command)) (point))
14565 (t (match-end 4))))))))
14566 (org-no-warnings
14567 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14568
14569 (defun org-end-of-line (&optional arg)
14570 "Go to the end of the line.
14571 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14572 first attempt, and only move to after the tags when the cursor is already
14573 beyond the end of the headline."
14574 (interactive "P")
14575 (if (or (not org-special-ctrl-a/e)
14576 (not (org-on-heading-p)))
14577 (end-of-line arg)
14578 (let ((pos (point)))
14579 (beginning-of-line 1)
14580 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14581 (if (eq org-special-ctrl-a/e t)
14582 (if (or (< pos (match-beginning 1))
14583 (= pos (match-end 0)))
14584 (goto-char (match-beginning 1))
14585 (goto-char (match-end 0)))
14586 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14587 (goto-char (match-end 0))
14588 (goto-char (match-beginning 1))))
14589 (end-of-line arg))))
14590 (org-no-warnings
14591 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14592
14593
14594 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14595 (define-key org-mode-map "\C-e" 'org-end-of-line)
14596
14597 (defun org-kill-line (&optional arg)
14598 "Kill line, to tags or end of line."
14599 (interactive "P")
14600 (cond
14601 ((or (not org-special-ctrl-k)
14602 (bolp)
14603 (not (org-on-heading-p)))
14604 (call-interactively 'kill-line))
14605 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14606 (kill-region (point) (match-beginning 1))
14607 (org-set-tags nil t))
14608 (t (kill-region (point) (point-at-eol)))))
14609
14610 (define-key org-mode-map "\C-k" 'org-kill-line)
14611
14612 (defun org-yank (&optional arg)
14613 "Yank. If the kill is a subtree, treat it specially.
14614 This command will look at the current kill and check if is a single
14615 subtree, or a series of subtrees[1]. If it passes the test, and if the
14616 cursor is at the beginning of a line or after the stars of a currently
14617 empty headline, then the yank is handled specially. How exactly depends
14618 on the value of the following variables, both set by default.
14619
14620 org-yank-folded-subtrees
14621 When set, the subtree(s) will be folded after insertion, but only
14622 if doing so would now swallow text after the yanked text.
14623
14624 org-yank-adjusted-subtrees
14625 When set, the subtree will be promoted or demoted in order to
14626 fit into the local outline tree structure, which means that the level
14627 will be adjusted so that it becomes the smaller one of the two
14628 *visible* surrounding headings.
14629
14630 Any prefix to this command will cause `yank' to be called directly with
14631 no special treatment. In particular, a simple `C-u' prefix will just
14632 plainly yank the text as it is.
14633
14634 \[1] Basically, the test checks if the first non-white line is a heading
14635 and if there are no other headings with fewer stars."
14636 (interactive "P")
14637 (setq this-command 'yank)
14638 (if arg
14639 (call-interactively 'yank)
14640 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14641 (and (org-kill-is-subtree-p)
14642 (or (bolp)
14643 (and (looking-at "[ \t]*$")
14644 (string-match
14645 "\\`\\*+\\'"
14646 (buffer-substring (point-at-bol) (point)))))))
14647 swallowp)
14648 (cond
14649 ((and subtreep org-yank-folded-subtrees)
14650 (let ((beg (point))
14651 end)
14652 (if (and subtreep org-yank-adjusted-subtrees)
14653 (org-paste-subtree nil nil 'for-yank)
14654 (call-interactively 'yank))
14655 (setq end (point))
14656 (goto-char beg)
14657 (when (and (bolp) subtreep
14658 (not (setq swallowp
14659 (org-yank-folding-would-swallow-text beg end))))
14660 (or (looking-at outline-regexp)
14661 (re-search-forward (concat "^" outline-regexp) end t))
14662 (while (and (< (point) end) (looking-at outline-regexp))
14663 (hide-subtree)
14664 (org-cycle-show-empty-lines 'folded)
14665 (condition-case nil
14666 (outline-forward-same-level 1)
14667 (error (goto-char end)))))
14668 (when swallowp
14669 (message
14670 "Yanked text not folded because that would swallow text"))
14671 (goto-char end)
14672 (skip-chars-forward " \t\n\r")
14673 (beginning-of-line 1)
14674 (push-mark beg 'nomsg)))
14675 ((and subtreep org-yank-adjusted-subtrees)
14676 (let ((beg (point-at-bol)))
14677 (org-paste-subtree nil nil 'for-yank)
14678 (push-mark beg 'nomsg)))
14679 (t
14680 (call-interactively 'yank))))))
14681
14682 (defun org-yank-folding-would-swallow-text (beg end)
14683 "Would hide-subtree at BEG swallow any text after END?"
14684 (let (level)
14685 (save-excursion
14686 (goto-char beg)
14687 (when (or (looking-at outline-regexp)
14688 (re-search-forward (concat "^" outline-regexp) end t))
14689 (setq level (org-outline-level)))
14690 (goto-char end)
14691 (skip-chars-forward " \t\r\n\v\f")
14692 (if (or (eobp)
14693 (and (bolp) (looking-at org-outline-regexp)
14694 (<= (org-outline-level) level)))
14695 nil ; Nothing would be swallowed
14696 t)))) ; something would swallow
14697
14698 (define-key org-mode-map "\C-y" 'org-yank)
14699
14700 (defun org-invisible-p ()
14701 "Check if point is at a character currently not visible."
14702 ;; Early versions of noutline don't have `outline-invisible-p'.
14703 (if (fboundp 'outline-invisible-p)
14704 (outline-invisible-p)
14705 (get-char-property (point) 'invisible)))
14706
14707 (defun org-invisible-p2 ()
14708 "Check if point is at a character currently not visible."
14709 (save-excursion
14710 (if (and (eolp) (not (bobp))) (backward-char 1))
14711 ;; Early versions of noutline don't have `outline-invisible-p'.
14712 (if (fboundp 'outline-invisible-p)
14713 (outline-invisible-p)
14714 (get-char-property (point) 'invisible))))
14715
14716 (defun org-back-to-heading (&optional invisible-ok)
14717 "Call `outline-back-to-heading', but provide a better error message."
14718 (condition-case nil
14719 (outline-back-to-heading invisible-ok)
14720 (error (error "Before first headline at position %d in buffer %s"
14721 (point) (current-buffer)))))
14722
14723 (defun org-before-first-heading-p ()
14724 "Before first heading?"
14725 (save-excursion
14726 (null (re-search-backward "^\\*+ " nil t))))
14727
14728 (defalias 'org-on-heading-p 'outline-on-heading-p)
14729 (defalias 'org-at-heading-p 'outline-on-heading-p)
14730 (defun org-at-heading-or-item-p ()
14731 (or (org-on-heading-p) (org-at-item-p)))
14732
14733 (defun org-on-target-p ()
14734 (or (org-in-regexp org-radio-target-regexp)
14735 (org-in-regexp org-target-regexp)))
14736
14737 (defun org-up-heading-all (arg)
14738 "Move to the heading line of which the present line is a subheading.
14739 This function considers both visible and invisible heading lines.
14740 With argument, move up ARG levels."
14741 (if (fboundp 'outline-up-heading-all)
14742 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14743 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14744
14745 (defun org-up-heading-safe ()
14746 "Move to the heading line of which the present line is a subheading.
14747 This version will not throw an error. It will return the level of the
14748 headline found, or nil if no higher level is found."
14749 (let (start-level re)
14750 (org-back-to-heading t)
14751 (setq start-level (funcall outline-level))
14752 (if (equal start-level 1)
14753 nil
14754 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14755 (if (re-search-backward re nil t)
14756 (funcall outline-level)))))
14757
14758 (defun org-first-sibling-p ()
14759 "Is this heading the first child of its parents?"
14760 (interactive)
14761 (let ((re (concat "^" outline-regexp))
14762 level l)
14763 (unless (org-at-heading-p t)
14764 (error "Not at a heading"))
14765 (setq level (funcall outline-level))
14766 (save-excursion
14767 (if (not (re-search-backward re nil t))
14768 t
14769 (setq l (funcall outline-level))
14770 (< l level)))))
14771
14772 (defun org-goto-sibling (&optional previous)
14773 "Goto the next sibling, even if it is invisible.
14774 When PREVIOUS is set, go to the previous sibling instead. Returns t
14775 when a sibling was found. When none is found, return nil and don't
14776 move point."
14777 (let ((fun (if previous 're-search-backward 're-search-forward))
14778 (pos (point))
14779 (re (concat "^" outline-regexp))
14780 level l)
14781 (when (condition-case nil (org-back-to-heading t) (error nil))
14782 (setq level (funcall outline-level))
14783 (catch 'exit
14784 (or previous (forward-char 1))
14785 (while (funcall fun re nil t)
14786 (setq l (funcall outline-level))
14787 (when (< l level) (goto-char pos) (throw 'exit nil))
14788 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14789 (goto-char pos)
14790 nil))))
14791
14792 (defun org-show-siblings ()
14793 "Show all siblings of the current headline."
14794 (save-excursion
14795 (while (org-goto-sibling) (org-flag-heading nil)))
14796 (save-excursion
14797 (while (org-goto-sibling 'previous)
14798 (org-flag-heading nil))))
14799
14800 (defun org-show-hidden-entry ()
14801 "Show an entry where even the heading is hidden."
14802 (save-excursion
14803 (org-show-entry)))
14804
14805 (defun org-flag-heading (flag &optional entry)
14806 "Flag the current heading. FLAG non-nil means make invisible.
14807 When ENTRY is non-nil, show the entire entry."
14808 (save-excursion
14809 (org-back-to-heading t)
14810 ;; Check if we should show the entire entry
14811 (if entry
14812 (progn
14813 (org-show-entry)
14814 (save-excursion
14815 (and (outline-next-heading)
14816 (org-flag-heading nil))))
14817 (outline-flag-region (max (point-min) (1- (point)))
14818 (save-excursion (outline-end-of-heading) (point))
14819 flag))))
14820
14821 (defun org-forward-same-level (arg)
14822 "Move forward to the ARG'th subheading at same level as this one.
14823 Stop at the first and last subheadings of a superior heading.
14824 This is like outline-forward-same-level, but invisible headings are ok."
14825 (interactive "p")
14826 (org-back-to-heading t)
14827 (while (> arg 0)
14828 (let ((point-to-move-to (save-excursion
14829 (org-get-next-sibling))))
14830 (if point-to-move-to
14831 (progn
14832 (goto-char point-to-move-to)
14833 (setq arg (1- arg)))
14834 (progn
14835 (setq arg 0)
14836 (error "No following same-level heading"))))))
14837
14838 (defun org-get-next-sibling ()
14839 "Move to next heading of the same level, and return point.
14840 If there is no such heading, return nil.
14841 This is like outline-next-sibling, but invisible headings are ok."
14842 (let ((level (funcall outline-level)))
14843 (outline-next-heading)
14844 (while (and (not (eobp)) (> (funcall outline-level) level))
14845 (outline-next-heading))
14846 (if (or (eobp) (< (funcall outline-level) level))
14847 nil
14848 (point))))
14849
14850 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14851 ;; This is an exact copy of the original function, but it uses
14852 ;; `org-back-to-heading', to make it work also in invisible
14853 ;; trees. And is uses an invisible-OK argument.
14854 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14855 (org-back-to-heading invisible-OK)
14856 (let ((first t)
14857 (level (funcall outline-level)))
14858 (while (and (not (eobp))
14859 (or first (> (funcall outline-level) level)))
14860 (setq first nil)
14861 (outline-next-heading))
14862 (unless to-heading
14863 (if (memq (preceding-char) '(?\n ?\^M))
14864 (progn
14865 ;; Go to end of line before heading
14866 (forward-char -1)
14867 (if (memq (preceding-char) '(?\n ?\^M))
14868 ;; leave blank line before heading
14869 (forward-char -1))))))
14870 (point))
14871
14872 (defun org-show-subtree ()
14873 "Show everything after this heading at deeper levels."
14874 (outline-flag-region
14875 (point)
14876 (save-excursion
14877 (outline-end-of-subtree) (outline-next-heading) (point))
14878 nil))
14879
14880 (defun org-show-entry ()
14881 "Show the body directly following this heading.
14882 Show the heading too, if it is currently invisible."
14883 (interactive)
14884 (save-excursion
14885 (condition-case nil
14886 (progn
14887 (org-back-to-heading t)
14888 (outline-flag-region
14889 (max (point-min) (1- (point)))
14890 (save-excursion
14891 (re-search-forward
14892 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14893 (or (match-beginning 1) (point-max)))
14894 nil))
14895 (error nil))))
14896
14897 (defun org-make-options-regexp (kwds)
14898 "Make a regular expression for keyword lines."
14899 (concat
14900 "^"
14901 "#?[ \t]*\\+\\("
14902 (mapconcat 'regexp-quote kwds "\\|")
14903 "\\):[ \t]*"
14904 "\\(.+\\)"))
14905
14906 ;; Make isearch reveal the necessary context
14907 (defun org-isearch-end ()
14908 "Reveal context after isearch exits."
14909 (when isearch-success ; only if search was successful
14910 (if (featurep 'xemacs)
14911 ;; Under XEmacs, the hook is run in the correct place,
14912 ;; we directly show the context.
14913 (org-show-context 'isearch)
14914 ;; In Emacs the hook runs *before* restoring the overlays.
14915 ;; So we have to use a one-time post-command-hook to do this.
14916 ;; (Emacs 22 has a special variable, see function `org-mode')
14917 (unless (and (boundp 'isearch-mode-end-hook-quit)
14918 isearch-mode-end-hook-quit)
14919 ;; Only when the isearch was not quitted.
14920 (org-add-hook 'post-command-hook 'org-isearch-post-command
14921 'append 'local)))))
14922
14923 (defun org-isearch-post-command ()
14924 "Remove self from hook, and show context."
14925 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14926 (org-show-context 'isearch))
14927
14928
14929 ;;;; Integration with and fixes for other packages
14930
14931 ;;; Imenu support
14932
14933 (defvar org-imenu-markers nil
14934 "All markers currently used by Imenu.")
14935 (make-variable-buffer-local 'org-imenu-markers)
14936
14937 (defun org-imenu-new-marker (&optional pos)
14938 "Return a new marker for use by Imenu, and remember the marker."
14939 (let ((m (make-marker)))
14940 (move-marker m (or pos (point)))
14941 (push m org-imenu-markers)
14942 m))
14943
14944 (defun org-imenu-get-tree ()
14945 "Produce the index for Imenu."
14946 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14947 (setq org-imenu-markers nil)
14948 (let* ((n org-imenu-depth)
14949 (re (concat "^" outline-regexp))
14950 (subs (make-vector (1+ n) nil))
14951 (last-level 0)
14952 m level head)
14953 (save-excursion
14954 (save-restriction
14955 (widen)
14956 (goto-char (point-max))
14957 (while (re-search-backward re nil t)
14958 (setq level (org-reduced-level (funcall outline-level)))
14959 (when (<= level n)
14960 (looking-at org-complex-heading-regexp)
14961 (setq head (org-link-display-format
14962 (org-match-string-no-properties 4))
14963 m (org-imenu-new-marker))
14964 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14965 (if (>= level last-level)
14966 (push (cons head m) (aref subs level))
14967 (push (cons head (aref subs (1+ level))) (aref subs level))
14968 (loop for i from (1+ level) to n do (aset subs i nil)))
14969 (setq last-level level)))))
14970 (aref subs 1)))
14971
14972 (eval-after-load "imenu"
14973 '(progn
14974 (add-hook 'imenu-after-jump-hook
14975 (lambda ()
14976 (if (eq major-mode 'org-mode)
14977 (org-show-context 'org-goto))))))
14978
14979 (defun org-link-display-format (link)
14980 "Replace a link with either the description, or the link target
14981 if no description is present"
14982 (save-match-data
14983 (if (string-match org-bracket-link-analytic-regexp link)
14984 (replace-match (or (match-string 5 link)
14985 (concat (match-string 1 link)
14986 (match-string 3 link)))
14987 nil nil link)
14988 link)))
14989
14990 ;; Speedbar support
14991
14992 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14993 "Overlay marking the agenda restriction line in speedbar.")
14994 (org-overlay-put org-speedbar-restriction-lock-overlay
14995 'face 'org-agenda-restriction-lock)
14996 (org-overlay-put org-speedbar-restriction-lock-overlay
14997 'help-echo "Agendas are currently limited to this item.")
14998 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14999
15000 (defun org-speedbar-set-agenda-restriction ()
15001 "Restrict future agenda commands to the location at point in speedbar.
15002 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15003 (interactive)
15004 (require 'org-agenda)
15005 (let (p m tp np dir txt)
15006 (cond
15007 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15008 'org-imenu t))
15009 (setq m (get-text-property p 'org-imenu-marker))
15010 (save-excursion
15011 (save-restriction
15012 (set-buffer (marker-buffer m))
15013 (goto-char m)
15014 (org-agenda-set-restriction-lock 'subtree))))
15015 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15016 'speedbar-function 'speedbar-find-file))
15017 (setq tp (previous-single-property-change
15018 (1+ p) 'speedbar-function)
15019 np (next-single-property-change
15020 tp 'speedbar-function)
15021 dir (speedbar-line-directory)
15022 txt (buffer-substring-no-properties (or tp (point-min))
15023 (or np (point-max))))
15024 (save-excursion
15025 (save-restriction
15026 (set-buffer (find-file-noselect
15027 (let ((default-directory dir))
15028 (expand-file-name txt))))
15029 (unless (org-mode-p)
15030 (error "Cannot restrict to non-Org-mode file"))
15031 (org-agenda-set-restriction-lock 'file))))
15032 (t (error "Don't know how to restrict Org-mode's agenda")))
15033 (org-move-overlay org-speedbar-restriction-lock-overlay
15034 (point-at-bol) (point-at-eol))
15035 (setq current-prefix-arg nil)
15036 (org-agenda-maybe-redo)))
15037
15038 (eval-after-load "speedbar"
15039 '(progn
15040 (speedbar-add-supported-extension ".org")
15041 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15042 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15043 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15044 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15045 (add-hook 'speedbar-visiting-tag-hook
15046 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15047
15048
15049 ;;; Fixes and Hacks for problems with other packages
15050
15051 ;; Make flyspell not check words in links, to not mess up our keymap
15052 (defun org-mode-flyspell-verify ()
15053 "Don't let flyspell put overlays at active buttons."
15054 (not (get-text-property (point) 'keymap)))
15055
15056 ;; Make `bookmark-jump' show the jump location if it was hidden.
15057 (eval-after-load "bookmark"
15058 '(if (boundp 'bookmark-after-jump-hook)
15059 ;; We can use the hook
15060 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15061 ;; Hook not available, use advice
15062 (defadvice bookmark-jump (after org-make-visible activate)
15063 "Make the position visible."
15064 (org-bookmark-jump-unhide))))
15065
15066 ;; Make sure saveplace show the location if it was hidden
15067 (eval-after-load "saveplace"
15068 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15069 "Make the position visible."
15070 (org-bookmark-jump-unhide)))
15071
15072 (defun org-bookmark-jump-unhide ()
15073 "Unhide the current position, to show the bookmark location."
15074 (and (org-mode-p)
15075 (or (org-invisible-p)
15076 (save-excursion (goto-char (max (point-min) (1- (point))))
15077 (org-invisible-p)))
15078 (org-show-context 'bookmark-jump)))
15079
15080 ;; Make session.el ignore our circular variable
15081 (eval-after-load "session"
15082 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15083
15084 ;;;; Experimental code
15085
15086 (defun org-closed-in-range ()
15087 "Sparse tree of items closed in a certain time range.
15088 Still experimental, may disappear in the future."
15089 (interactive)
15090 ;; Get the time interval from the user.
15091 (let* ((time1 (time-to-seconds
15092 (org-read-date nil 'to-time nil "Starting date: ")))
15093 (time2 (time-to-seconds
15094 (org-read-date nil 'to-time nil "End date:")))
15095 ;; callback function
15096 (callback (lambda ()
15097 (let ((time
15098 (time-to-seconds
15099 (apply 'encode-time
15100 (org-parse-time-string
15101 (match-string 1))))))
15102 ;; check if time in interval
15103 (and (>= time time1) (<= time time2))))))
15104 ;; make tree, check each match with the callback
15105 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15106
15107
15108 ;;;; Finish up
15109
15110 (provide 'org)
15111
15112 (run-hooks 'org-load-hook)
15113
15114 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15115
15116 ;;; org.el ends here