]> code.delx.au - gnu-emacs/blob - lisp/org/org.el
(tex-uptodate-p): Accept [1{/var/foo}] as a page number.
[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.21b
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.21b"
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 or 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 nil
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 t
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 (defvar org-blocker-hook nil
1607 "Hook for functions that are allowed to block a state change.
1608
1609 Each function gets as its single argument a property list, see
1610 `org-trigger-hook' for more information about this list.
1611
1612 If any of the functions in this hook returns nil, the state change
1613 is blocked.")
1614
1615 (defvar org-trigger-hook nil
1616 "Hook for functions that are triggered by a state change.
1617
1618 Each function gets as its single argument a property list with at least
1619 the following elements:
1620
1621 (:type type-of-change :position pos-at-entry-start
1622 :from old-state :to new-state)
1623
1624 Depending on the type, more properties may be present.
1625
1626 This mechanism is currently implemented for:
1627
1628 TODO state changes
1629 ------------------
1630 :type todo-state-change
1631 :from previous state (keyword as a string), or nil, or a symbol
1632 'todo' or 'done', to indicate the general type of state.
1633 :to new state, like in :from")
1634
1635 (defcustom org-enforce-todo-dependencies nil
1636 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1637 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1638 be blocked if any prior sibling is not yet done.
1639 This variable needs to be set before org.el is loaded, and you need to
1640 restart Emacs after a change to make the change effective. The only way
1641 to change is while Emacs is running is through the customize interface."
1642 :set (lambda (var val)
1643 (set var val)
1644 (if val
1645 (add-hook 'org-blocker-hook
1646 'org-block-todo-from-children-or-siblings)
1647 (remove-hook 'org-blocker-hook
1648 'org-block-todo-from-children-or-siblings)))
1649 :group 'org-todo
1650 :type 'boolean)
1651
1652 (defcustom org-enforce-todo-checkbox-dependencies nil
1653 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1654 When this is nil, checkboxes have no influence on switching TODO states.
1655 When non-nil, you first need to check off all check boxes before the TODO
1656 entry can be switched to DONE.
1657 This variable needs to be set before org.el is loaded, and you need to
1658 restart Emacs after a change to make the change effective. The only way
1659 to change is while Emacs is running is through the customize interface."
1660 :set (lambda (var val)
1661 (set var val)
1662 (if val
1663 (add-hook 'org-blocker-hook
1664 'org-block-todo-from-checkboxes)
1665 (remove-hook 'org-blocker-hook
1666 'org-block-todo-from-checkboxes)))
1667 :group 'org-todo
1668 :type 'boolean)
1669
1670 (defcustom org-todo-state-tags-triggers nil
1671 "Tag changes that should be triggered by TODO state changes.
1672 This is a list. Each entry is
1673
1674 (state-change (tag . flag) .......)
1675
1676 State-change can be a string with a state, and empty string to indicate the
1677 state that has no TODO keyword, or it can be one of the symbols `todo'
1678 or `done', meaning any not-done or done state, respectively."
1679 :group 'org-todo
1680 :group 'org-tags
1681 :type '(repeat
1682 (cons (choice :tag "When changing to"
1683 (const :tag "Not-done state" todo)
1684 (const :tag "Done state" done)
1685 (string :tag "State"))
1686 (repeat
1687 (cons :tag "Tag action"
1688 (string :tag "Tag")
1689 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1690
1691 (defcustom org-log-done nil
1692 "Information to record when a task moves to the DONE state.
1693
1694 Possible values are:
1695
1696 nil Don't add anything, just change the keyword
1697 time Add a time stamp to the task
1698 note Prompt a closing note and add it with template `org-log-note-headings'
1699
1700 This option can also be set with on a per-file-basis with
1701
1702 #+STARTUP: nologdone
1703 #+STARTUP: logdone
1704 #+STARTUP: lognotedone
1705
1706 You can have local logging settings for a subtree by setting the LOGGING
1707 property to one or more of these keywords."
1708 :group 'org-todo
1709 :group 'org-progress
1710 :type '(choice
1711 (const :tag "No logging" nil)
1712 (const :tag "Record CLOSED timestamp" time)
1713 (const :tag "Record CLOSED timestamp with closing note." note)))
1714
1715 ;; Normalize old uses of org-log-done.
1716 (cond
1717 ((eq org-log-done t) (setq org-log-done 'time))
1718 ((and (listp org-log-done) (memq 'done org-log-done))
1719 (setq org-log-done 'note)))
1720
1721 (defcustom org-log-note-clock-out nil
1722 "Non-nil means, record a note when clocking out of an item.
1723 This can also be configured on a per-file basis by adding one of
1724 the following lines anywhere in the buffer:
1725
1726 #+STARTUP: lognoteclock-out
1727 #+STARTUP: nolognoteclock-out"
1728 :group 'org-todo
1729 :group 'org-progress
1730 :type 'boolean)
1731
1732 (defcustom org-log-done-with-time t
1733 "Non-nil means, the CLOSED time stamp will contain date and time.
1734 When nil, only the date will be recorded."
1735 :group 'org-progress
1736 :type 'boolean)
1737
1738 (defcustom org-log-note-headings
1739 '((done . "CLOSING NOTE %t")
1740 (state . "State %-12s %t")
1741 (note . "Note taken on %t")
1742 (clock-out . ""))
1743 "Headings for notes added to entries.
1744 The value is an alist, with the car being a symbol indicating the note
1745 context, and the cdr is the heading to be used. The heading may also be the
1746 empty string.
1747 %t in the heading will be replaced by a time stamp.
1748 %s will be replaced by the new TODO state, in double quotes.
1749 %u will be replaced by the user name.
1750 %U will be replaced by the full user name."
1751 :group 'org-todo
1752 :group 'org-progress
1753 :type '(list :greedy t
1754 (cons (const :tag "Heading when closing an item" done) string)
1755 (cons (const :tag
1756 "Heading when changing todo state (todo sequence only)"
1757 state) string)
1758 (cons (const :tag "Heading when just taking a note" note) string)
1759 (cons (const :tag "Heading when clocking out" clock-out) string)))
1760
1761 (unless (assq 'note org-log-note-headings)
1762 (push '(note . "%t") org-log-note-headings))
1763
1764 (defcustom org-log-state-notes-insert-after-drawers nil
1765 "Non-nil means, insert state change notes after any drawers in entry.
1766 Only the drawers that *immediately* follow the headline and the
1767 deadline/scheduled line are skipped.
1768 When nil, insert notes right after the heading and perhaps the line
1769 with deadline/scheduling if present."
1770 :group 'org-todo
1771 :group 'org-progress
1772 :type 'boolean)
1773
1774 (defcustom org-log-states-order-reversed t
1775 "Non-nil means, the latest state change note will be directly after heading.
1776 When nil, the notes will be orderer according to time."
1777 :group 'org-todo
1778 :group 'org-progress
1779 :type 'boolean)
1780
1781 (defcustom org-log-repeat 'time
1782 "Non-nil means, record moving through the DONE state when triggering repeat.
1783 An auto-repeating tasks is immediately switched back to TODO when marked
1784 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1785 the TODO keyword definition, or recording a closing note by setting
1786 `org-log-done', there will be no record of the task moving through DONE.
1787 This variable forces taking a note anyway. Possible values are:
1788
1789 nil Don't force a record
1790 time Record a time stamp
1791 note Record a note
1792
1793 This option can also be set with on a per-file-basis with
1794
1795 #+STARTUP: logrepeat
1796 #+STARTUP: lognoterepeat
1797 #+STARTUP: nologrepeat
1798
1799 You can have local logging settings for a subtree by setting the LOGGING
1800 property to one or more of these keywords."
1801 :group 'org-todo
1802 :group 'org-progress
1803 :type '(choice
1804 (const :tag "Don't force a record" nil)
1805 (const :tag "Force recording the DONE state" time)
1806 (const :tag "Force recording a note with the DONE state" note)))
1807
1808
1809 (defgroup org-priorities nil
1810 "Priorities in Org-mode."
1811 :tag "Org Priorities"
1812 :group 'org-todo)
1813
1814 (defcustom org-highest-priority ?A
1815 "The highest priority of TODO items. A character like ?A, ?B etc.
1816 Must have a smaller ASCII number than `org-lowest-priority'."
1817 :group 'org-priorities
1818 :type 'character)
1819
1820 (defcustom org-lowest-priority ?C
1821 "The lowest priority of TODO items. A character like ?A, ?B etc.
1822 Must have a larger ASCII number than `org-highest-priority'."
1823 :group 'org-priorities
1824 :type 'character)
1825
1826 (defcustom org-default-priority ?B
1827 "The default priority of TODO items.
1828 This is the priority an item get if no explicit priority is given."
1829 :group 'org-priorities
1830 :type 'character)
1831
1832 (defcustom org-priority-start-cycle-with-default t
1833 "Non-nil means, start with default priority when starting to cycle.
1834 When this is nil, the first step in the cycle will be (depending on the
1835 command used) one higher or lower that the default priority."
1836 :group 'org-priorities
1837 :type 'boolean)
1838
1839 (defgroup org-time nil
1840 "Options concerning time stamps and deadlines in Org-mode."
1841 :tag "Org Time"
1842 :group 'org)
1843
1844 (defcustom org-insert-labeled-timestamps-at-point nil
1845 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1846 When nil, these labeled time stamps are forces into the second line of an
1847 entry, just after the headline. When scheduling from the global TODO list,
1848 the time stamp will always be forced into the second line."
1849 :group 'org-time
1850 :type 'boolean)
1851
1852 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1853 "Formats for `format-time-string' which are used for time stamps.
1854 It is not recommended to change this constant.")
1855
1856 (defcustom org-time-stamp-rounding-minutes '(0 5)
1857 "Number of minutes to round time stamps to.
1858 These are two values, the first applies when first creating a time stamp.
1859 The second applies when changing it with the commands `S-up' and `S-down'.
1860 When changing the time stamp, this means that it will change in steps
1861 of N minutes, as given by the second value.
1862
1863 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1864 numbers should be factors of 60, so for example 5, 10, 15.
1865
1866 When this is larger than 1, you can still force an exact time-stamp by using
1867 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1868 and by using a prefix arg to `S-up/down' to specify the exact number
1869 of minutes to shift."
1870 :group 'org-time
1871 :get '(lambda (var) ; Make sure all entries have 5 elements
1872 (if (integerp (default-value var))
1873 (list (default-value var) 5)
1874 (default-value var)))
1875 :type '(list
1876 (integer :tag "when inserting times")
1877 (integer :tag "when modifying times")))
1878
1879 ;; Normalize old customizations of this variable.
1880 (when (integerp org-time-stamp-rounding-minutes)
1881 (setq org-time-stamp-rounding-minutes
1882 (list org-time-stamp-rounding-minutes
1883 org-time-stamp-rounding-minutes)))
1884
1885 (defcustom org-display-custom-times nil
1886 "Non-nil means, overlay custom formats over all time stamps.
1887 The formats are defined through the variable `org-time-stamp-custom-formats'.
1888 To turn this on on a per-file basis, insert anywhere in the file:
1889 #+STARTUP: customtime"
1890 :group 'org-time
1891 :set 'set-default
1892 :type 'sexp)
1893 (make-variable-buffer-local 'org-display-custom-times)
1894
1895 (defcustom org-time-stamp-custom-formats
1896 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1897 "Custom formats for time stamps. See `format-time-string' for the syntax.
1898 These are overlayed over the default ISO format if the variable
1899 `org-display-custom-times' is set. Time like %H:%M should be at the
1900 end of the second format."
1901 :group 'org-time
1902 :type 'sexp)
1903
1904 (defun org-time-stamp-format (&optional long inactive)
1905 "Get the right format for a time string."
1906 (let ((f (if long (cdr org-time-stamp-formats)
1907 (car org-time-stamp-formats))))
1908 (if inactive
1909 (concat "[" (substring f 1 -1) "]")
1910 f)))
1911
1912 (defcustom org-time-clocksum-format "%d:%02d"
1913 "The format string used when creating CLOCKSUM lines, or when
1914 org-mode generates a time duration."
1915 :group 'org-time
1916 :type 'string)
1917
1918 (defcustom org-deadline-warning-days 14
1919 "No. of days before expiration during which a deadline becomes active.
1920 This variable governs the display in sparse trees and in the agenda.
1921 When 0 or negative, it means use this number (the absolute value of it)
1922 even if a deadline has a different individual lead time specified."
1923 :group 'org-time
1924 :group 'org-agenda-daily/weekly
1925 :type 'number)
1926
1927 (defcustom org-read-date-prefer-future t
1928 "Non-nil means, assume future for incomplete date input from user.
1929 This affects the following situations:
1930 1. The user gives a day, but no month.
1931 For example, if today is the 15th, and you enter \"3\", Org-mode will
1932 read this as the third of *next* month. However, if you enter \"17\",
1933 it will be considered as *this* month.
1934 2. The user gives a month but not a year.
1935 For example, if it is april and you enter \"feb 2\", this will be read
1936 as feb 2, *next* year. \"May 5\", however, will be this year.
1937
1938 Currently this does not work for ISO week specifications.
1939
1940 When this option is nil, the current month and year will always be used
1941 as defaults."
1942 :group 'org-time
1943 :type 'boolean)
1944
1945 (defcustom org-read-date-display-live t
1946 "Non-nil means, display current interpretation of date prompt live.
1947 This display will be in an overlay, in the minibuffer."
1948 :group 'org-time
1949 :type 'boolean)
1950
1951 (defcustom org-read-date-popup-calendar t
1952 "Non-nil means, pop up a calendar when prompting for a date.
1953 In the calendar, the date can be selected with mouse-1. However, the
1954 minibuffer will also be active, and you can simply enter the date as well.
1955 When nil, only the minibuffer will be available."
1956 :group 'org-time
1957 :type 'boolean)
1958 (if (fboundp 'defvaralias)
1959 (defvaralias 'org-popup-calendar-for-date-prompt
1960 'org-read-date-popup-calendar))
1961
1962 (defcustom org-extend-today-until 0
1963 "The hour when your day really ends. Must be an integer.
1964 This has influence for the following applications:
1965 - When switching the agenda to \"today\". It it is still earlier than
1966 the time given here, the day recognized as TODAY is actually yesterday.
1967 - When a date is read from the user and it is still before the time given
1968 here, the current date and time will be assumed to be yesterday, 23:59.
1969 Also, timestamps inserted in remember templates follow this rule.
1970
1971 IMPORTANT: This is a feature whose implementation is and likely will
1972 remain incomplete. Really, it is only here because past midnight seems to
1973 be the favorite working time of John Wiegley :-)"
1974 :group 'org-time
1975 :type 'number)
1976
1977 (defcustom org-edit-timestamp-down-means-later nil
1978 "Non-nil means, S-down will increase the time in a time stamp.
1979 When nil, S-up will increase."
1980 :group 'org-time
1981 :type 'boolean)
1982
1983 (defcustom org-calendar-follow-timestamp-change t
1984 "Non-nil means, make the calendar window follow timestamp changes.
1985 When a timestamp is modified and the calendar window is visible, it will be
1986 moved to the new date."
1987 :group 'org-time
1988 :type 'boolean)
1989
1990 (defgroup org-tags nil
1991 "Options concerning tags in Org-mode."
1992 :tag "Org Tags"
1993 :group 'org)
1994
1995 (defcustom org-tag-alist nil
1996 "List of tags allowed in Org-mode files.
1997 When this list is nil, Org-mode will base TAG input on what is already in the
1998 buffer.
1999 The value of this variable is an alist, the car of each entry must be a
2000 keyword as a string, the cdr may be a character that is used to select
2001 that tag through the fast-tag-selection interface.
2002 See the manual for details."
2003 :group 'org-tags
2004 :type '(repeat
2005 (choice
2006 (cons (string :tag "Tag name")
2007 (character :tag "Access char"))
2008 (const :tag "Start radio group" (:startgroup))
2009 (const :tag "End radio group" (:endgroup)))))
2010
2011 (defvar org-file-tags nil
2012 "List of tags that can be inherited by all entries in the file.
2013 The tags will be inherited if the variable `org-use-tag-inheritance'
2014 says they should be.
2015 This variable is populated from #+TAG lines.")
2016
2017 (defcustom org-use-fast-tag-selection 'auto
2018 "Non-nil means, use fast tag selection scheme.
2019 This is a special interface to select and deselect tags with single keys.
2020 When nil, fast selection is never used.
2021 When the symbol `auto', fast selection is used if and only if selection
2022 characters for tags have been configured, either through the variable
2023 `org-tag-alist' or through a #+TAGS line in the buffer.
2024 When t, fast selection is always used and selection keys are assigned
2025 automatically if necessary."
2026 :group 'org-tags
2027 :type '(choice
2028 (const :tag "Always" t)
2029 (const :tag "Never" nil)
2030 (const :tag "When selection characters are configured" 'auto)))
2031
2032 (defcustom org-fast-tag-selection-single-key nil
2033 "Non-nil means, fast tag selection exits after first change.
2034 When nil, you have to press RET to exit it.
2035 During fast tag selection, you can toggle this flag with `C-c'.
2036 This variable can also have the value `expert'. In this case, the window
2037 displaying the tags menu is not even shown, until you press C-c again."
2038 :group 'org-tags
2039 :type '(choice
2040 (const :tag "No" nil)
2041 (const :tag "Yes" t)
2042 (const :tag "Expert" expert)))
2043
2044 (defvar org-fast-tag-selection-include-todo nil
2045 "Non-nil means, fast tags selection interface will also offer TODO states.
2046 This is an undocumented feature, you should not rely on it.")
2047
2048 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2049 "The column to which tags should be indented in a headline.
2050 If this number is positive, it specifies the column. If it is negative,
2051 it means that the tags should be flushright to that column. For example,
2052 -80 works well for a normal 80 character screen."
2053 :group 'org-tags
2054 :type 'integer)
2055
2056 (defcustom org-auto-align-tags t
2057 "Non-nil means, realign tags after pro/demotion of TODO state change.
2058 These operations change the length of a headline and therefore shift
2059 the tags around. With this options turned on, after each such operation
2060 the tags are again aligned to `org-tags-column'."
2061 :group 'org-tags
2062 :type 'boolean)
2063
2064 (defcustom org-use-tag-inheritance t
2065 "Non-nil means, tags in levels apply also for sublevels.
2066 When nil, only the tags directly given in a specific line apply there.
2067 This may also be a list of tags that should be inherited, or a regexp that
2068 matches tags that should be inherited. Additional control is possible
2069 with the variable `org-tags-exclude-from-inheritance' which gives an
2070 explicit list of tags to be excluded from inheritance., even if the value of
2071 `org-use-tag-inheritance' would select it for inheritance.
2072
2073 If this option is t, a match early-on in a tree can lead to a large
2074 number of matches in the subtree when constructing the agenda or creating
2075 a sparse tree. If you only want to see the first match in a tree during
2076 a search, check out the variable `org-tags-match-list-sublevels'."
2077 :group 'org-tags
2078 :type '(choice
2079 (const :tag "Not" nil)
2080 (const :tag "Always" t)
2081 (repeat :tag "Specific tags" (string :tag "Tag"))
2082 (regexp :tag "Tags matched by regexp")))
2083
2084 (defcustom org-tags-exclude-from-inheritance nil
2085 "List of tags that should never be inherited.
2086 This is a way to exclude a few tags from inheritance. For way to do
2087 the opposite, to actively allow inheritance for selected tags,
2088 see the variable `org-use-tag-inheritance'."
2089 :group 'org-tags
2090 :type '(repeat (string :tag "Tag")))
2091
2092 (defun org-tag-inherit-p (tag)
2093 "Check if TAG is one that should be inherited."
2094 (cond
2095 ((member tag org-tags-exclude-from-inheritance) nil)
2096 ((eq org-use-tag-inheritance t) t)
2097 ((not org-use-tag-inheritance) nil)
2098 ((stringp org-use-tag-inheritance)
2099 (string-match org-use-tag-inheritance tag))
2100 ((listp org-use-tag-inheritance)
2101 (member tag org-use-tag-inheritance))
2102 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2103
2104 (defcustom org-tags-match-list-sublevels t
2105 "Non-nil means list also sublevels of headlines matching tag search.
2106 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2107 the sublevels of a headline matching a tag search often also match
2108 the same search. Listing all of them can create very long lists.
2109 Setting this variable to nil causes subtrees of a match to be skipped.
2110 This option is off by default, because inheritance in on. If you turn
2111 inheritance off, you very likely want to turn this option on.
2112
2113 As a special case, if the tag search is restricted to TODO items, the
2114 value of this variable is ignored and sublevels are always checked, to
2115 make sure all corresponding TODO items find their way into the list.
2116
2117 This variable is semi-obsolete and probably should always be true. It
2118 is better to limit inheritance to certain tags using the variables
2119 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2120 :group 'org-tags
2121 :type 'boolean)
2122
2123 (defvar org-tags-history nil
2124 "History of minibuffer reads for tags.")
2125 (defvar org-last-tags-completion-table nil
2126 "The last used completion table for tags.")
2127 (defvar org-after-tags-change-hook nil
2128 "Hook that is run after the tags in a line have changed.")
2129
2130 (defgroup org-properties nil
2131 "Options concerning properties in Org-mode."
2132 :tag "Org Properties"
2133 :group 'org)
2134
2135 (defcustom org-property-format "%-10s %s"
2136 "How property key/value pairs should be formatted by `indent-line'.
2137 When `indent-line' hits a property definition, it will format the line
2138 according to this format, mainly to make sure that the values are
2139 lined-up with respect to each other."
2140 :group 'org-properties
2141 :type 'string)
2142
2143 (defcustom org-use-property-inheritance nil
2144 "Non-nil means, properties apply also for sublevels.
2145
2146 This setting is chiefly used during property searches. Turning it on can
2147 cause significant overhead when doing a search, which is why it is not
2148 on by default.
2149
2150 When nil, only the properties directly given in the current entry count.
2151 When t, every property is inherited. The value may also be a list of
2152 properties that should have inheritance, or a regular expression matching
2153 properties that should be inherited.
2154
2155 However, note that some special properties use inheritance under special
2156 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2157 and the properties ending in \"_ALL\" when they are used as descriptor
2158 for valid values of a property.
2159
2160 Note for programmers:
2161 When querying an entry with `org-entry-get', you can control if inheritance
2162 should be used. By default, `org-entry-get' looks only at the local
2163 properties. You can request inheritance by setting the inherit argument
2164 to t (to force inheritance) or to `selective' (to respect the setting
2165 in this variable)."
2166 :group 'org-properties
2167 :type '(choice
2168 (const :tag "Not" nil)
2169 (const :tag "Always" t)
2170 (repeat :tag "Specific properties" (string :tag "Property"))
2171 (regexp :tag "Properties matched by regexp")))
2172
2173 (defun org-property-inherit-p (property)
2174 "Check if PROPERTY is one that should be inherited."
2175 (cond
2176 ((eq org-use-property-inheritance t) t)
2177 ((not org-use-property-inheritance) nil)
2178 ((stringp org-use-property-inheritance)
2179 (string-match org-use-property-inheritance property))
2180 ((listp org-use-property-inheritance)
2181 (member property org-use-property-inheritance))
2182 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2183
2184 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2185 "The default column format, if no other format has been defined.
2186 This variable can be set on the per-file basis by inserting a line
2187
2188 #+COLUMNS: %25ITEM ....."
2189 :group 'org-properties
2190 :type 'string)
2191
2192 (defcustom org-columns-ellipses ".."
2193 "The ellipses to be used when a field in column view is truncated.
2194 When this is the empty string, as many characters as possible are shown,
2195 but then there will be no visual indication that the field has been truncated.
2196 When this is a string of length N, the last N characters of a truncated
2197 field are replaced by this string. If the column is narrower than the
2198 ellipses string, only part of the ellipses string will be shown."
2199 :group 'org-properties
2200 :type 'string)
2201
2202 (defcustom org-columns-modify-value-for-display-function nil
2203 "Function that modifies values for display in column view.
2204 For example, it can be used to cut out a certain part from a time stamp.
2205 The function must take 2 arguments:
2206
2207 column-title The title of the column (*not* the property name)
2208 value The value that should be modified.
2209
2210 The function should return the value that should be displayed,
2211 or nil if the normal value should be used."
2212 :group 'org-properties
2213 :type 'function)
2214
2215 (defcustom org-effort-property "Effort"
2216 "The property that is being used to keep track of effort estimates.
2217 Effort estimates given in this property need to have the format H:MM."
2218 :group 'org-properties
2219 :group 'org-progress
2220 :type '(string :tag "Property"))
2221
2222 (defconst org-global-properties-fixed
2223 '(("VISIBILITY_ALL" . "folded children content all"))
2224 "List of property/value pairs that can be inherited by any entry.
2225 These are fixed values, for the preset properties.")
2226
2227
2228 (defcustom org-global-properties nil
2229 "List of property/value pairs that can be inherited by any entry.
2230 You can set buffer-local values for the same purpose in the variable
2231 `org-file-properties' this by adding lines like
2232
2233 #+PROPERTY: NAME VALUE"
2234 :group 'org-properties
2235 :type '(repeat
2236 (cons (string :tag "Property")
2237 (string :tag "Value"))))
2238
2239 (defvar org-file-properties nil
2240 "List of property/value pairs that can be inherited by any entry.
2241 Valid for the current buffer.
2242 This variable is populated from #+PROPERTY lines.")
2243 (make-variable-buffer-local 'org-file-properties)
2244
2245 (defgroup org-agenda nil
2246 "Options concerning agenda views in Org-mode."
2247 :tag "Org Agenda"
2248 :group 'org)
2249
2250 (defvar org-category nil
2251 "Variable used by org files to set a category for agenda display.
2252 Such files should use a file variable to set it, for example
2253
2254 # -*- mode: org; org-category: \"ELisp\"
2255
2256 or contain a special line
2257
2258 #+CATEGORY: ELisp
2259
2260 If the file does not specify a category, then file's base name
2261 is used instead.")
2262 (make-variable-buffer-local 'org-category)
2263 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2264
2265 (defcustom org-agenda-files nil
2266 "The files to be used for agenda display.
2267 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2268 \\[org-remove-file]. You can also use customize to edit the list.
2269
2270 If an entry is a directory, all files in that directory that are matched by
2271 `org-agenda-file-regexp' will be part of the file list.
2272
2273 If the value of the variable is not a list but a single file name, then
2274 the list of agenda files is actually stored and maintained in that file, one
2275 agenda file per line."
2276 :group 'org-agenda
2277 :type '(choice
2278 (repeat :tag "List of files and directories" file)
2279 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2280
2281 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2282 "Regular expression to match files for `org-agenda-files'.
2283 If any element in the list in that variable contains a directory instead
2284 of a normal file, all files in that directory that are matched by this
2285 regular expression will be included."
2286 :group 'org-agenda
2287 :type 'regexp)
2288
2289 (defcustom org-agenda-text-search-extra-files nil
2290 "List of extra files to be searched by text search commands.
2291 These files will be search in addition to the agenda files by the
2292 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2293 Note that these files will only be searched for text search commands,
2294 not for the other agenda views like todo lists, tag searches or the weekly
2295 agenda. This variable is intended to list notes and possibly archive files
2296 that should also be searched by these two commands.
2297 In fact, if the first element in the list is the symbol `agenda-archives',
2298 than all archive files of all agenda files will be added to the search
2299 scope."
2300 :group 'org-agenda
2301 :type '(set :greedy t
2302 (const :tag "Agenda Archives" agenda-archives)
2303 (repeat :inline t (file))))
2304
2305 (if (fboundp 'defvaralias)
2306 (defvaralias 'org-agenda-multi-occur-extra-files
2307 'org-agenda-text-search-extra-files))
2308
2309 (defcustom org-agenda-skip-unavailable-files nil
2310 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2311 A nil value means to remove them, after a query, from the list."
2312 :group 'org-agenda
2313 :type 'boolean)
2314
2315 (defcustom org-calendar-to-agenda-key [?c]
2316 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2317 The command `org-calendar-goto-agenda' will be bound to this key. The
2318 default is the character `c' because then `c' can be used to switch back and
2319 forth between agenda and calendar."
2320 :group 'org-agenda
2321 :type 'sexp)
2322
2323 (defcustom org-calendar-agenda-action-key [?k]
2324 "The key to be installed in `calendar-mode-map' for agenda-action.
2325 The command `org-agenda-action' will be bound to this key. The
2326 default is the character `k' because we use the same key in the agenda."
2327 :group 'org-agenda
2328 :type 'sexp)
2329
2330 (eval-after-load "calendar"
2331 '(progn
2332 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2333 'org-calendar-goto-agenda)
2334 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2335 'org-agenda-action)))
2336
2337 (defgroup org-latex nil
2338 "Options for embedding LaTeX code into Org-mode."
2339 :tag "Org LaTeX"
2340 :group 'org)
2341
2342 (defcustom org-format-latex-options
2343 '(:foreground default :background default :scale 1.0
2344 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2345 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2346 "Options for creating images from LaTeX fragments.
2347 This is a property list with the following properties:
2348 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2349 `default' means use the foreground of the default face.
2350 :background the background color, or \"Transparent\".
2351 `default' means use the background of the default face.
2352 :scale a scaling factor for the size of the images.
2353 :html-foreground, :html-background, :html-scale
2354 the same numbers for HTML export.
2355 :matchers a list indicating which matchers should be used to
2356 find LaTeX fragments. Valid members of this list are:
2357 \"begin\" find environments
2358 \"$1\" find single characters surrounded by $.$
2359 \"$\" find math expressions surrounded by $...$
2360 \"$$\" find math expressions surrounded by $$....$$
2361 \"\\(\" find math expressions surrounded by \\(...\\)
2362 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2363 :group 'org-latex
2364 :type 'plist)
2365
2366 (defcustom org-format-latex-header "\\documentclass{article}
2367 \\usepackage{fullpage} % do not remove
2368 \\usepackage{amssymb}
2369 \\usepackage[usenames]{color}
2370 \\usepackage{amsmath}
2371 \\usepackage{latexsym}
2372 \\usepackage[mathscr]{eucal}
2373 \\pagestyle{empty} % do not remove"
2374 "The document header used for processing LaTeX fragments."
2375 :group 'org-latex
2376 :type 'string)
2377
2378
2379 (defgroup org-font-lock nil
2380 "Font-lock settings for highlighting in Org-mode."
2381 :tag "Org Font Lock"
2382 :group 'org)
2383
2384 (defcustom org-level-color-stars-only nil
2385 "Non-nil means fontify only the stars in each headline.
2386 When nil, the entire headline is fontified.
2387 Changing it requires restart of `font-lock-mode' to become effective
2388 also in regions already fontified."
2389 :group 'org-font-lock
2390 :type 'boolean)
2391
2392 (defcustom org-hide-leading-stars nil
2393 "Non-nil means, hide the first N-1 stars in a headline.
2394 This works by using the face `org-hide' for these stars. This
2395 face is white for a light background, and black for a dark
2396 background. You may have to customize the face `org-hide' to
2397 make this work.
2398 Changing it requires restart of `font-lock-mode' to become effective
2399 also in regions already fontified.
2400 You may also set this on a per-file basis by adding one of the following
2401 lines to the buffer:
2402
2403 #+STARTUP: hidestars
2404 #+STARTUP: showstars"
2405 :group 'org-font-lock
2406 :type 'boolean)
2407
2408 (defcustom org-fontify-done-headline nil
2409 "Non-nil means, change the face of a headline if it is marked DONE.
2410 Normally, only the TODO/DONE keyword indicates the state of a headline.
2411 When this is non-nil, the headline after the keyword is set to the
2412 `org-headline-done' as an additional indication."
2413 :group 'org-font-lock
2414 :type 'boolean)
2415
2416 (defcustom org-fontify-emphasized-text t
2417 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2418 Changing this variable requires a restart of Emacs to take effect."
2419 :group 'org-font-lock
2420 :type 'boolean)
2421
2422 (defcustom org-highlight-latex-fragments-and-specials nil
2423 "Non-nil means, fontify what is treated specially by the exporters."
2424 :group 'org-font-lock
2425 :type 'boolean)
2426
2427 (defcustom org-hide-emphasis-markers nil
2428 "Non-nil mean font-lock should hide the emphasis marker characters."
2429 :group 'org-font-lock
2430 :type 'boolean)
2431
2432 (defvar org-emph-re nil
2433 "Regular expression for matching emphasis.")
2434 (defvar org-verbatim-re nil
2435 "Regular expression for matching verbatim text.")
2436 (defvar org-emphasis-regexp-components) ; defined just below
2437 (defvar org-emphasis-alist) ; defined just below
2438 (defun org-set-emph-re (var val)
2439 "Set variable and compute the emphasis regular expression."
2440 (set var val)
2441 (when (and (boundp 'org-emphasis-alist)
2442 (boundp 'org-emphasis-regexp-components)
2443 org-emphasis-alist org-emphasis-regexp-components)
2444 (let* ((e org-emphasis-regexp-components)
2445 (pre (car e))
2446 (post (nth 1 e))
2447 (border (nth 2 e))
2448 (body (nth 3 e))
2449 (nl (nth 4 e))
2450 (body1 (concat body "*?"))
2451 (markers (mapconcat 'car org-emphasis-alist ""))
2452 (vmarkers (mapconcat
2453 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2454 org-emphasis-alist "")))
2455 ;; make sure special characters appear at the right position in the class
2456 (if (string-match "\\^" markers)
2457 (setq markers (concat (replace-match "" t t markers) "^")))
2458 (if (string-match "-" markers)
2459 (setq markers (concat (replace-match "" t t markers) "-")))
2460 (if (string-match "\\^" vmarkers)
2461 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2462 (if (string-match "-" vmarkers)
2463 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2464 (if (> nl 0)
2465 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2466 (int-to-string nl) "\\}")))
2467 ;; Make the regexp
2468 (setq org-emph-re
2469 (concat "\\([" pre "]\\|^\\)"
2470 "\\("
2471 "\\([" markers "]\\)"
2472 "\\("
2473 "[^" border "]\\|"
2474 "[^" border "]"
2475 body1
2476 "[^" border "]"
2477 "\\)"
2478 "\\3\\)"
2479 "\\([" post "]\\|$\\)"))
2480 (setq org-verbatim-re
2481 (concat "\\([" pre "]\\|^\\)"
2482 "\\("
2483 "\\([" vmarkers "]\\)"
2484 "\\("
2485 "[^" border "]\\|"
2486 "[^" border "]"
2487 body1
2488 "[^" border "]"
2489 "\\)"
2490 "\\3\\)"
2491 "\\([" post "]\\|$\\)")))))
2492
2493 (defcustom org-emphasis-regexp-components
2494 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2495 "Components used to build the regular expression for emphasis.
2496 This is a list with 6 entries. Terminology: In an emphasis string
2497 like \" *strong word* \", we call the initial space PREMATCH, the final
2498 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2499 and \"trong wor\" is the body. The different components in this variable
2500 specify what is allowed/forbidden in each part:
2501
2502 pre Chars allowed as prematch. Beginning of line will be allowed too.
2503 post Chars allowed as postmatch. End of line will be allowed too.
2504 border The chars *forbidden* as border characters.
2505 body-regexp A regexp like \".\" to match a body character. Don't use
2506 non-shy groups here, and don't allow newline here.
2507 newline The maximum number of newlines allowed in an emphasis exp.
2508
2509 Use customize to modify this, or restart Emacs after changing it."
2510 :group 'org-font-lock
2511 :set 'org-set-emph-re
2512 :type '(list
2513 (sexp :tag "Allowed chars in pre ")
2514 (sexp :tag "Allowed chars in post ")
2515 (sexp :tag "Forbidden chars in border ")
2516 (sexp :tag "Regexp for body ")
2517 (integer :tag "number of newlines allowed")
2518 (option (boolean :tag "Please ignore this button"))))
2519
2520 (defcustom org-emphasis-alist
2521 `(("*" bold "<b>" "</b>")
2522 ("/" italic "<i>" "</i>")
2523 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2524 ("=" org-code "<code>" "</code>" verbatim)
2525 ("~" org-verbatim "<code>" "</code>" verbatim)
2526 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2527 "<del>" "</del>")
2528 )
2529 "Special syntax for emphasized text.
2530 Text starting and ending with a special character will be emphasized, for
2531 example *bold*, _underlined_ and /italic/. This variable sets the marker
2532 characters, the face to be used by font-lock for highlighting in Org-mode
2533 Emacs buffers, and the HTML tags to be used for this.
2534 Use customize to modify this, or restart Emacs after changing it."
2535 :group 'org-font-lock
2536 :set 'org-set-emph-re
2537 :type '(repeat
2538 (list
2539 (string :tag "Marker character")
2540 (choice
2541 (face :tag "Font-lock-face")
2542 (plist :tag "Face property list"))
2543 (string :tag "HTML start tag")
2544 (string :tag "HTML end tag")
2545 (option (const verbatim)))))
2546
2547 ;;; Miscellaneous options
2548
2549 (defgroup org-completion nil
2550 "Completion in Org-mode."
2551 :tag "Org Completion"
2552 :group 'org)
2553
2554 (defcustom org-completion-use-ido nil
2555 "Non-nil means, use ido completion wherever possible.
2556 Note that `ido-mode' must be active for this variable to be relevant.
2557 If you decide to turn this variable on, you might well want to turn off
2558 `org-outline-path-complete-in-steps'."
2559 :group 'org-completion
2560 :type 'boolean)
2561
2562 (defcustom org-completion-fallback-command 'hippie-expand
2563 "The expansion command called by \\[org-complete] in normal context.
2564 Normal means, no org-mode-specific context."
2565 :group 'org-completion
2566 :type 'function)
2567
2568 ;;; Functions and variables from ther packages
2569 ;; Declared here to avoid compiler warnings
2570
2571 ;; XEmacs only
2572 (defvar outline-mode-menu-heading)
2573 (defvar outline-mode-menu-show)
2574 (defvar outline-mode-menu-hide)
2575 (defvar zmacs-regions) ; XEmacs regions
2576
2577 ;; Emacs only
2578 (defvar mark-active)
2579
2580 ;; Various packages
2581 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2582 (declare-function calendar-forward-day "cal-move" (arg))
2583 (declare-function calendar-goto-date "cal-move" (date))
2584 (declare-function calendar-goto-today "cal-move" ())
2585 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2586 (defvar calc-embedded-close-formula)
2587 (defvar calc-embedded-open-formula)
2588 (declare-function cdlatex-tab "ext:cdlatex" ())
2589 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2590 (defvar font-lock-unfontify-region-function)
2591 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2592 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2593 (defvar iswitchb-temp-buflist)
2594 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2595 (defvar org-agenda-tags-todo-honor-ignore-options)
2596 (declare-function org-agenda-skip "org-agenda" ())
2597 (declare-function org-format-agenda-item "org-agenda"
2598 (extra txt &optional category tags dotime noprefix remove-re))
2599 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2600 (declare-function org-agenda-change-all-lines "org-agenda"
2601 (newhead hdmarker &optional fixface just-this))
2602 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2603 (declare-function org-agenda-maybe-redo "org-agenda" ())
2604 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2605 (beg end))
2606 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2607 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2608 "org-agenda" (&optional end))
2609
2610 (declare-function parse-time-string "parse-time" (string))
2611 (declare-function remember "remember" (&optional initial))
2612 (declare-function remember-buffer-desc "remember" ())
2613 (declare-function remember-finalize "remember" ())
2614 (defvar remember-save-after-remembering)
2615 (defvar remember-data-file)
2616 (defvar remember-register)
2617 (defvar remember-buffer)
2618 (defvar remember-handler-functions)
2619 (defvar remember-annotation-functions)
2620 (defvar texmathp-why)
2621 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2622 (declare-function table--at-cell-p "table" (position &optional object at-column))
2623
2624 (defvar w3m-current-url)
2625 (defvar w3m-current-title)
2626
2627 (defvar org-latex-regexps)
2628
2629 ;;; Autoload and prepare some org modules
2630
2631 ;; Some table stuff that needs to be defined here, because it is used
2632 ;; by the functions setting up org-mode or checking for table context.
2633
2634 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2635 "Detects an org-type or table-type table.")
2636 (defconst org-table-line-regexp "^[ \t]*|"
2637 "Detects an org-type table line.")
2638 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2639 "Detects an org-type table line.")
2640 (defconst org-table-hline-regexp "^[ \t]*|-"
2641 "Detects an org-type table hline.")
2642 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2643 "Detects a table-type table hline.")
2644 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2645 "Searching from within a table (any type) this finds the first line
2646 outside the table.")
2647
2648 ;; Autoload the functions in org-table.el that are needed by functions here.
2649
2650 (eval-and-compile
2651 (org-autoload "org-table"
2652 '(org-table-align org-table-begin org-table-blank-field
2653 org-table-convert org-table-convert-region org-table-copy-down
2654 org-table-copy-region org-table-create
2655 org-table-create-or-convert-from-region
2656 org-table-create-with-table.el org-table-current-dline
2657 org-table-cut-region org-table-delete-column org-table-edit-field
2658 org-table-edit-formulas org-table-end org-table-eval-formula
2659 org-table-export org-table-field-info
2660 org-table-get-stored-formulas org-table-goto-column
2661 org-table-hline-and-move org-table-import org-table-insert-column
2662 org-table-insert-hline org-table-insert-row org-table-iterate
2663 org-table-justify-field-maybe org-table-kill-row
2664 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2665 org-table-move-column org-table-move-column-left
2666 org-table-move-column-right org-table-move-row
2667 org-table-move-row-down org-table-move-row-up
2668 org-table-next-field org-table-next-row org-table-paste-rectangle
2669 org-table-previous-field org-table-recalculate
2670 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2671 org-table-toggle-coordinate-overlays
2672 org-table-toggle-formula-debugger org-table-wrap-region
2673 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2674
2675 (defun org-at-table-p (&optional table-type)
2676 "Return t if the cursor is inside an org-type table.
2677 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2678 (if org-enable-table-editor
2679 (save-excursion
2680 (beginning-of-line 1)
2681 (looking-at (if table-type org-table-any-line-regexp
2682 org-table-line-regexp)))
2683 nil))
2684 (defsubst org-table-p () (org-at-table-p))
2685
2686 (defun org-at-table.el-p ()
2687 "Return t if and only if we are at a table.el table."
2688 (and (org-at-table-p 'any)
2689 (save-excursion
2690 (goto-char (org-table-begin 'any))
2691 (looking-at org-table1-hline-regexp))))
2692 (defun org-table-recognize-table.el ()
2693 "If there is a table.el table nearby, recognize it and move into it."
2694 (if org-table-tab-recognizes-table.el
2695 (if (org-at-table.el-p)
2696 (progn
2697 (beginning-of-line 1)
2698 (if (looking-at org-table-dataline-regexp)
2699 nil
2700 (if (looking-at org-table1-hline-regexp)
2701 (progn
2702 (beginning-of-line 2)
2703 (if (looking-at org-table-any-border-regexp)
2704 (beginning-of-line -1)))))
2705 (if (re-search-forward "|" (org-table-end t) t)
2706 (progn
2707 (require 'table)
2708 (if (table--at-cell-p (point))
2709 t
2710 (message "recognizing table.el table...")
2711 (table-recognize-table)
2712 (message "recognizing table.el table...done")))
2713 (error "This should not happen..."))
2714 t)
2715 nil)
2716 nil))
2717
2718 (defun org-at-table-hline-p ()
2719 "Return t if the cursor is inside a hline in a table."
2720 (if org-enable-table-editor
2721 (save-excursion
2722 (beginning-of-line 1)
2723 (looking-at org-table-hline-regexp))
2724 nil))
2725
2726 (defvar org-table-clean-did-remove-column nil)
2727
2728 (defun org-table-map-tables (function)
2729 "Apply FUNCTION to the start of all tables in the buffer."
2730 (save-excursion
2731 (save-restriction
2732 (widen)
2733 (goto-char (point-min))
2734 (while (re-search-forward org-table-any-line-regexp nil t)
2735 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2736 (beginning-of-line 1)
2737 (if (looking-at org-table-line-regexp)
2738 (save-excursion (funcall function)))
2739 (re-search-forward org-table-any-border-regexp nil 1))))
2740 (message "Mapping tables: done"))
2741
2742 ;; Declare and autoload functions from org-exp.el
2743
2744 (declare-function org-default-export-plist "org-exp")
2745 (declare-function org-infile-export-plist "org-exp")
2746 (declare-function org-get-current-options "org-exp")
2747 (eval-and-compile
2748 (org-autoload "org-exp"
2749 '(org-export org-export-as-ascii org-export-visible
2750 org-insert-export-options-template org-export-as-html-and-open
2751 org-export-as-html-batch org-export-as-html-to-buffer
2752 org-replace-region-by-html org-export-region-as-html
2753 org-export-as-html org-export-icalendar-this-file
2754 org-export-icalendar-all-agenda-files
2755 org-table-clean-before-export
2756 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2757
2758 ;; Declare and autoload functions from org-agenda.el
2759
2760 (eval-and-compile
2761 (org-autoload "org-agenda"
2762 '(org-agenda org-agenda-list org-search-view
2763 org-todo-list org-tags-view org-agenda-list-stuck-projects
2764 org-diary org-agenda-to-appt
2765 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2766
2767 ;; Autoload org-remember
2768
2769 (eval-and-compile
2770 (org-autoload "org-remember"
2771 '(org-remember-insinuate org-remember-annotation
2772 org-remember-apply-template org-remember org-remember-handler)))
2773
2774 ;; Autoload org-clock.el
2775
2776
2777 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2778 (beg end))
2779 (declare-function org-clock-update-mode-line "org-clock" ())
2780 (defvar org-clock-start-time)
2781 (defvar org-clock-marker (make-marker)
2782 "Marker recording the last clock-in.")
2783
2784 (eval-and-compile
2785 (org-autoload
2786 "org-clock"
2787 '(org-clock-in org-clock-out org-clock-cancel
2788 org-clock-goto org-clock-sum org-clock-display
2789 org-clock-remove-overlays org-clock-report
2790 org-clocktable-shift org-dblock-write:clocktable
2791 org-get-clocktable)))
2792
2793 (defun org-clock-update-time-maybe ()
2794 "If this is a CLOCK line, update it and return t.
2795 Otherwise, return nil."
2796 (interactive)
2797 (save-excursion
2798 (beginning-of-line 1)
2799 (skip-chars-forward " \t")
2800 (when (looking-at org-clock-string)
2801 (let ((re (concat "[ \t]*" org-clock-string
2802 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2803 "\\([ \t]*=>.*\\)?\\)?"))
2804 ts te h m s neg)
2805 (cond
2806 ((not (looking-at re))
2807 nil)
2808 ((not (match-end 2))
2809 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2810 (> org-clock-marker (point))
2811 (<= org-clock-marker (point-at-eol)))
2812 ;; The clock is running here
2813 (setq org-clock-start-time
2814 (apply 'encode-time
2815 (org-parse-time-string (match-string 1))))
2816 (org-clock-update-mode-line)))
2817 (t
2818 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2819 (end-of-line 1)
2820 (setq ts (match-string 1)
2821 te (match-string 3))
2822 (setq s (- (time-to-seconds
2823 (apply 'encode-time (org-parse-time-string te)))
2824 (time-to-seconds
2825 (apply 'encode-time (org-parse-time-string ts))))
2826 neg (< s 0)
2827 s (abs s)
2828 h (floor (/ s 3600))
2829 s (- s (* 3600 h))
2830 m (floor (/ s 60))
2831 s (- s (* 60 s)))
2832 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2833 t))))))
2834
2835 (defun org-check-running-clock ()
2836 "Check if the current buffer contains the running clock.
2837 If yes, offer to stop it and to save the buffer with the changes."
2838 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2839 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2840 (buffer-name))))
2841 (org-clock-out)
2842 (when (y-or-n-p "Save changed buffer?")
2843 (save-buffer))))
2844
2845 (defun org-clocktable-try-shift (dir n)
2846 "Check if this line starts a clock table, if yes, shift the time block."
2847 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2848 (org-clocktable-shift dir n)))
2849
2850 ;; Autoload org-timer.el
2851
2852 ;(declare-function org-timer "org-timer")
2853
2854 (eval-and-compile
2855 (org-autoload
2856 "org-timer"
2857 '(org-timer-start org-timer org-timer-item
2858 org-timer-change-times-in-region)))
2859
2860
2861 ;; Autoload archiving code
2862 ;; The stuff that is needed for cycling and tags has to be defined here.
2863
2864 (defgroup org-archive nil
2865 "Options concerning archiving in Org-mode."
2866 :tag "Org Archive"
2867 :group 'org-structure)
2868
2869 (defcustom org-archive-location "%s_archive::"
2870 "The location where subtrees should be archived.
2871
2872 The value of this variable is a string, consisting of two parts,
2873 separated by a double-colon. The first part is a filename and
2874 the second part is a headline.
2875
2876 When the filename is omitted, archiving happens in the same file.
2877 %s in the filename will be replaced by the current file
2878 name (without the directory part). Archiving to a different file
2879 is useful to keep archived entries from contributing to the
2880 Org-mode Agenda.
2881
2882 The archived entries will be filed as subtrees of the specified
2883 headline. When the headline is omitted, the subtrees are simply
2884 filed away at the end of the file, as top-level entries. Also in
2885 the heading you can use %s to represent the file name, this can be
2886 useful when using the same archive for a number of different files.
2887
2888 Here are a few examples:
2889 \"%s_archive::\"
2890 If the current file is Projects.org, archive in file
2891 Projects.org_archive, as top-level trees. This is the default.
2892
2893 \"::* Archived Tasks\"
2894 Archive in the current file, under the top-level headline
2895 \"* Archived Tasks\".
2896
2897 \"~/org/archive.org::\"
2898 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2899
2900 \"~/org/archive.org::From %s\"
2901 Archive in file ~/org/archive.org (absolute path), und headlines
2902 \"From FILENAME\" where file name is the current file name.
2903
2904 \"basement::** Finished Tasks\"
2905 Archive in file ./basement (relative path), as level 3 trees
2906 below the level 2 heading \"** Finished Tasks\".
2907
2908 You may set this option on a per-file basis by adding to the buffer a
2909 line like
2910
2911 #+ARCHIVE: basement::** Finished Tasks
2912
2913 You may also define it locally for a subtree by setting an ARCHIVE property
2914 in the entry. If such a property is found in an entry, or anywhere up
2915 the hierarchy, it will be used."
2916 :group 'org-archive
2917 :type 'string)
2918
2919 (defcustom org-archive-tag "ARCHIVE"
2920 "The tag that marks a subtree as archived.
2921 An archived subtree does not open during visibility cycling, and does
2922 not contribute to the agenda listings.
2923 After changing this, font-lock must be restarted in the relevant buffers to
2924 get the proper fontification."
2925 :group 'org-archive
2926 :group 'org-keywords
2927 :type 'string)
2928
2929 (defcustom org-agenda-skip-archived-trees t
2930 "Non-nil means, the agenda will skip any items located in archived trees.
2931 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2932 variable is no longer recommended, you should leave it at the value t.
2933 Instead, use the key `v' to cycle the archives-mode in the agenda."
2934 :group 'org-archive
2935 :group 'org-agenda-skip
2936 :type 'boolean)
2937
2938 (defcustom org-cycle-open-archived-trees nil
2939 "Non-nil means, `org-cycle' will open archived trees.
2940 An archived tree is a tree marked with the tag ARCHIVE.
2941 When nil, archived trees will stay folded. You can still open them with
2942 normal outline commands like `show-all', but not with the cycling commands."
2943 :group 'org-archive
2944 :group 'org-cycle
2945 :type 'boolean)
2946
2947 (defcustom org-sparse-tree-open-archived-trees nil
2948 "Non-nil means sparse tree construction shows matches in archived trees.
2949 When nil, matches in these trees are highlighted, but the trees are kept in
2950 collapsed state."
2951 :group 'org-archive
2952 :group 'org-sparse-trees
2953 :type 'boolean)
2954
2955 (defun org-cycle-hide-archived-subtrees (state)
2956 "Re-hide all archived subtrees after a visibility state change."
2957 (when (and (not org-cycle-open-archived-trees)
2958 (not (memq state '(overview folded))))
2959 (save-excursion
2960 (let* ((globalp (memq state '(contents all)))
2961 (beg (if globalp (point-min) (point)))
2962 (end (if globalp (point-max) (org-end-of-subtree t))))
2963 (org-hide-archived-subtrees beg end)
2964 (goto-char beg)
2965 (if (looking-at (concat ".*:" org-archive-tag ":"))
2966 (message "%s" (substitute-command-keys
2967 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2968
2969 (defun org-force-cycle-archived ()
2970 "Cycle subtree even if it is archived."
2971 (interactive)
2972 (setq this-command 'org-cycle)
2973 (let ((org-cycle-open-archived-trees t))
2974 (call-interactively 'org-cycle)))
2975
2976 (defun org-hide-archived-subtrees (beg end)
2977 "Re-hide all archived subtrees after a visibility state change."
2978 (save-excursion
2979 (let* ((re (concat ":" org-archive-tag ":")))
2980 (goto-char beg)
2981 (while (re-search-forward re end t)
2982 (and (org-on-heading-p) (hide-subtree))
2983 (org-end-of-subtree t)))))
2984
2985 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2986
2987 (eval-and-compile
2988 (org-autoload "org-archive"
2989 '(org-add-archive-files org-archive-subtree
2990 org-archive-to-archive-sibling org-toggle-archive-tag)))
2991
2992 ;; Autoload Column View Code
2993
2994 (declare-function org-columns-number-to-string "org-colview")
2995 (declare-function org-columns-get-format-and-top-level "org-colview")
2996 (declare-function org-columns-compute "org-colview")
2997
2998 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2999 '(org-columns-number-to-string org-columns-get-format-and-top-level
3000 org-columns-compute org-agenda-columns org-columns-remove-overlays
3001 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3002
3003 ;; Autoload ID code
3004
3005 (declare-function org-id-store-link "org-id")
3006 (org-autoload "org-id"
3007 '(org-id-get-create org-id-new org-id-copy org-id-get
3008 org-id-get-with-outline-path-completion
3009 org-id-get-with-outline-drilling
3010 org-id-goto org-id-find org-id-store-link))
3011
3012 ;;; Variables for pre-computed regular expressions, all buffer local
3013
3014 (defvar org-drawer-regexp nil
3015 "Matches first line of a hidden block.")
3016 (make-variable-buffer-local 'org-drawer-regexp)
3017 (defvar org-todo-regexp nil
3018 "Matches any of the TODO state keywords.")
3019 (make-variable-buffer-local 'org-todo-regexp)
3020 (defvar org-not-done-regexp nil
3021 "Matches any of the TODO state keywords except the last one.")
3022 (make-variable-buffer-local 'org-not-done-regexp)
3023 (defvar org-todo-line-regexp nil
3024 "Matches a headline and puts TODO state into group 2 if present.")
3025 (make-variable-buffer-local 'org-todo-line-regexp)
3026 (defvar org-complex-heading-regexp nil
3027 "Matches a headline and puts everything into groups:
3028 group 1: the stars
3029 group 2: The todo keyword, maybe
3030 group 3: Priority cookie
3031 group 4: True headline
3032 group 5: Tags")
3033 (make-variable-buffer-local 'org-complex-heading-regexp)
3034 (defvar org-todo-line-tags-regexp nil
3035 "Matches a headline and puts TODO state into group 2 if present.
3036 Also put tags into group 4 if tags are present.")
3037 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3038 (defvar org-nl-done-regexp nil
3039 "Matches newline followed by a headline with the DONE keyword.")
3040 (make-variable-buffer-local 'org-nl-done-regexp)
3041 (defvar org-looking-at-done-regexp nil
3042 "Matches the DONE keyword a point.")
3043 (make-variable-buffer-local 'org-looking-at-done-regexp)
3044 (defvar org-ds-keyword-length 12
3045 "Maximum length of the Deadline and SCHEDULED keywords.")
3046 (make-variable-buffer-local 'org-ds-keyword-length)
3047 (defvar org-deadline-regexp nil
3048 "Matches the DEADLINE keyword.")
3049 (make-variable-buffer-local 'org-deadline-regexp)
3050 (defvar org-deadline-time-regexp nil
3051 "Matches the DEADLINE keyword together with a time stamp.")
3052 (make-variable-buffer-local 'org-deadline-time-regexp)
3053 (defvar org-deadline-line-regexp nil
3054 "Matches the DEADLINE keyword and the rest of the line.")
3055 (make-variable-buffer-local 'org-deadline-line-regexp)
3056 (defvar org-scheduled-regexp nil
3057 "Matches the SCHEDULED keyword.")
3058 (make-variable-buffer-local 'org-scheduled-regexp)
3059 (defvar org-scheduled-time-regexp nil
3060 "Matches the SCHEDULED keyword together with a time stamp.")
3061 (make-variable-buffer-local 'org-scheduled-time-regexp)
3062 (defvar org-closed-time-regexp nil
3063 "Matches the CLOSED keyword together with a time stamp.")
3064 (make-variable-buffer-local 'org-closed-time-regexp)
3065
3066 (defvar org-keyword-time-regexp nil
3067 "Matches any of the 4 keywords, together with the time stamp.")
3068 (make-variable-buffer-local 'org-keyword-time-regexp)
3069 (defvar org-keyword-time-not-clock-regexp nil
3070 "Matches any of the 3 keywords, together with the time stamp.")
3071 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3072 (defvar org-maybe-keyword-time-regexp nil
3073 "Matches a timestamp, possibly preceeded by a keyword.")
3074 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3075 (defvar org-planning-or-clock-line-re nil
3076 "Matches a line with planning or clock info.")
3077 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3078
3079 (defconst org-plain-time-of-day-regexp
3080 (concat
3081 "\\(\\<[012]?[0-9]"
3082 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3083 "\\(--?"
3084 "\\(\\<[012]?[0-9]"
3085 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3086 "\\)?")
3087 "Regular expression to match a plain time or time range.
3088 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3089 groups carry important information:
3090 0 the full match
3091 1 the first time, range or not
3092 8 the second time, if it is a range.")
3093
3094 (defconst org-plain-time-extension-regexp
3095 (concat
3096 "\\(\\<[012]?[0-9]"
3097 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3098 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3099 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3100 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3101 groups carry important information:
3102 0 the full match
3103 7 hours of duration
3104 9 minutes of duration")
3105
3106 (defconst org-stamp-time-of-day-regexp
3107 (concat
3108 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3109 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3110 "\\(--?"
3111 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3112 "Regular expression to match a timestamp time or time range.
3113 After a match, the following groups carry important information:
3114 0 the full match
3115 1 date plus weekday, for backreferencing to make sure both times on same day
3116 2 the first time, range or not
3117 4 the second time, if it is a range.")
3118
3119 (defconst org-startup-options
3120 '(("fold" org-startup-folded t)
3121 ("overview" org-startup-folded t)
3122 ("nofold" org-startup-folded nil)
3123 ("showall" org-startup-folded nil)
3124 ("content" org-startup-folded content)
3125 ("hidestars" org-hide-leading-stars t)
3126 ("showstars" org-hide-leading-stars nil)
3127 ("odd" org-odd-levels-only t)
3128 ("oddeven" org-odd-levels-only nil)
3129 ("align" org-startup-align-all-tables t)
3130 ("noalign" org-startup-align-all-tables nil)
3131 ("customtime" org-display-custom-times t)
3132 ("logdone" org-log-done time)
3133 ("lognotedone" org-log-done note)
3134 ("nologdone" org-log-done nil)
3135 ("lognoteclock-out" org-log-note-clock-out t)
3136 ("nolognoteclock-out" org-log-note-clock-out nil)
3137 ("logrepeat" org-log-repeat state)
3138 ("lognoterepeat" org-log-repeat note)
3139 ("nologrepeat" org-log-repeat nil)
3140 ("fninline" org-footnote-define-inline t)
3141 ("nofninline" org-footnote-define-inline nil)
3142 ("fnlocal" org-footnote-section nil)
3143 ("fnauto" org-footnote-auto-label t)
3144 ("fnprompt" org-footnote-auto-label nil)
3145 ("fnconfirm" org-footnote-auto-label confirm)
3146 ("fnplain" org-footnote-auto-label plain)
3147 ("constcgs" constants-unit-system cgs)
3148 ("constSI" constants-unit-system SI))
3149 "Variable associated with STARTUP options for org-mode.
3150 Each element is a list of three items: The startup options as written
3151 in the #+STARTUP line, the corresponding variable, and the value to
3152 set this variable to if the option is found. An optional forth element PUSH
3153 means to push this value onto the list in the variable.")
3154
3155 (defun org-set-regexps-and-options ()
3156 "Precompute regular expressions for current buffer."
3157 (when (org-mode-p)
3158 (org-set-local 'org-todo-kwd-alist nil)
3159 (org-set-local 'org-todo-key-alist nil)
3160 (org-set-local 'org-todo-key-trigger nil)
3161 (org-set-local 'org-todo-keywords-1 nil)
3162 (org-set-local 'org-done-keywords nil)
3163 (org-set-local 'org-todo-heads nil)
3164 (org-set-local 'org-todo-sets nil)
3165 (org-set-local 'org-todo-log-states nil)
3166 (org-set-local 'org-file-properties nil)
3167 (org-set-local 'org-file-tags nil)
3168 (let ((re (org-make-options-regexp
3169 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3170 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3171 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3172 (splitre "[ \t]+")
3173 kwds kws0 kwsa key log value cat arch tags const links hw dws
3174 tail sep kws1 prio props ftags drawers
3175 ext-setup-or-nil setup-contents (start 0))
3176 (save-excursion
3177 (save-restriction
3178 (widen)
3179 (goto-char (point-min))
3180 (while (or (and ext-setup-or-nil
3181 (string-match re ext-setup-or-nil start)
3182 (setq start (match-end 0)))
3183 (and (setq ext-setup-or-nil nil start 0)
3184 (re-search-forward re nil t)))
3185 (setq key (upcase (match-string 1 ext-setup-or-nil))
3186 value (org-match-string-no-properties 2 ext-setup-or-nil))
3187 (cond
3188 ((equal key "CATEGORY")
3189 (if (string-match "[ \t]+$" value)
3190 (setq value (replace-match "" t t value)))
3191 (setq cat value))
3192 ((member key '("SEQ_TODO" "TODO"))
3193 (push (cons 'sequence (org-split-string value splitre)) kwds))
3194 ((equal key "TYP_TODO")
3195 (push (cons 'type (org-split-string value splitre)) kwds))
3196 ((equal key "TAGS")
3197 (setq tags (append tags (org-split-string value splitre))))
3198 ((equal key "COLUMNS")
3199 (org-set-local 'org-columns-default-format value))
3200 ((equal key "LINK")
3201 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3202 (push (cons (match-string 1 value)
3203 (org-trim (match-string 2 value)))
3204 links)))
3205 ((equal key "PRIORITIES")
3206 (setq prio (org-split-string value " +")))
3207 ((equal key "PROPERTY")
3208 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3209 (push (cons (match-string 1 value) (match-string 2 value))
3210 props)))
3211 ((equal key "FILETAGS")
3212 (when (string-match "\\S-" value)
3213 (setq ftags
3214 (append
3215 ftags
3216 (apply 'append
3217 (mapcar (lambda (x) (org-split-string x ":"))
3218 (org-split-string value)))))))
3219 ((equal key "DRAWERS")
3220 (setq drawers (org-split-string value splitre)))
3221 ((equal key "CONSTANTS")
3222 (setq const (append const (org-split-string value splitre))))
3223 ((equal key "STARTUP")
3224 (let ((opts (org-split-string value splitre))
3225 l var val)
3226 (while (setq l (pop opts))
3227 (when (setq l (assoc l org-startup-options))
3228 (setq var (nth 1 l) val (nth 2 l))
3229 (if (not (nth 3 l))
3230 (set (make-local-variable var) val)
3231 (if (not (listp (symbol-value var)))
3232 (set (make-local-variable var) nil))
3233 (set (make-local-variable var) (symbol-value var))
3234 (add-to-list var val))))))
3235 ((equal key "ARCHIVE")
3236 (string-match " *$" value)
3237 (setq arch (replace-match "" t t value))
3238 (remove-text-properties 0 (length arch)
3239 '(face t fontified t) arch))
3240 ((equal key "SETUPFILE")
3241 (setq setup-contents (org-file-contents
3242 (expand-file-name
3243 (org-remove-double-quotes value))
3244 'noerror))
3245 (if (not ext-setup-or-nil)
3246 (setq ext-setup-or-nil setup-contents start 0)
3247 (setq ext-setup-or-nil
3248 (concat (substring ext-setup-or-nil 0 start)
3249 "\n" setup-contents "\n"
3250 (substring ext-setup-or-nil start)))))
3251 ))))
3252 (when cat
3253 (org-set-local 'org-category (intern cat))
3254 (push (cons "CATEGORY" cat) props))
3255 (when prio
3256 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3257 (setq prio (mapcar 'string-to-char prio))
3258 (org-set-local 'org-highest-priority (nth 0 prio))
3259 (org-set-local 'org-lowest-priority (nth 1 prio))
3260 (org-set-local 'org-default-priority (nth 2 prio)))
3261 (and props (org-set-local 'org-file-properties (nreverse props)))
3262 (and ftags (org-set-local 'org-file-tags ftags))
3263 (and drawers (org-set-local 'org-drawers drawers))
3264 (and arch (org-set-local 'org-archive-location arch))
3265 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3266 ;; Process the TODO keywords
3267 (unless kwds
3268 ;; Use the global values as if they had been given locally.
3269 (setq kwds (default-value 'org-todo-keywords))
3270 (if (stringp (car kwds))
3271 (setq kwds (list (cons org-todo-interpretation
3272 (default-value 'org-todo-keywords)))))
3273 (setq kwds (reverse kwds)))
3274 (setq kwds (nreverse kwds))
3275 (let (inter kws kw)
3276 (while (setq kws (pop kwds))
3277 (setq inter (pop kws) sep (member "|" kws)
3278 kws0 (delete "|" (copy-sequence kws))
3279 kwsa nil
3280 kws1 (mapcar
3281 (lambda (x)
3282 ;; 1 2
3283 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3284 (progn
3285 (setq kw (match-string 1 x)
3286 key (and (match-end 2) (match-string 2 x))
3287 log (org-extract-log-state-settings x))
3288 (push (cons kw (and key (string-to-char key))) kwsa)
3289 (and log (push log org-todo-log-states))
3290 kw)
3291 (error "Invalid TODO keyword %s" x)))
3292 kws0)
3293 kwsa (if kwsa (append '((:startgroup))
3294 (nreverse kwsa)
3295 '((:endgroup))))
3296 hw (car kws1)
3297 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3298 tail (list inter hw (car dws) (org-last dws)))
3299 (add-to-list 'org-todo-heads hw 'append)
3300 (push kws1 org-todo-sets)
3301 (setq org-done-keywords (append org-done-keywords dws nil))
3302 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3303 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3304 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3305 (setq org-todo-sets (nreverse org-todo-sets)
3306 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3307 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3308 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3309 ;; Process the constants
3310 (when const
3311 (let (e cst)
3312 (while (setq e (pop const))
3313 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3314 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3315 (setq org-table-formula-constants-local cst)))
3316
3317 ;; Process the tags.
3318 (when tags
3319 (let (e tgs)
3320 (while (setq e (pop tags))
3321 (cond
3322 ((equal e "{") (push '(:startgroup) tgs))
3323 ((equal e "}") (push '(:endgroup) tgs))
3324 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3325 (push (cons (match-string 1 e)
3326 (string-to-char (match-string 2 e)))
3327 tgs))
3328 (t (push (list e) tgs))))
3329 (org-set-local 'org-tag-alist nil)
3330 (while (setq e (pop tgs))
3331 (or (and (stringp (car e))
3332 (assoc (car e) org-tag-alist))
3333 (push e org-tag-alist)))))
3334
3335 ;; Compute the regular expressions and other local variables
3336 (if (not org-done-keywords)
3337 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3338 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3339 (length org-scheduled-string)
3340 (length org-clock-string)
3341 (length org-closed-string)))
3342 org-drawer-regexp
3343 (concat "^[ \t]*:\\("
3344 (mapconcat 'regexp-quote org-drawers "\\|")
3345 "\\):[ \t]*$")
3346 org-not-done-keywords
3347 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3348 org-todo-regexp
3349 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3350 "\\|") "\\)\\>")
3351 org-not-done-regexp
3352 (concat "\\<\\("
3353 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3354 "\\)\\>")
3355 org-todo-line-regexp
3356 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3357 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3358 "\\)\\>\\)?[ \t]*\\(.*\\)")
3359 org-complex-heading-regexp
3360 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3361 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3362 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3363 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3364 org-nl-done-regexp
3365 (concat "\n\\*+[ \t]+"
3366 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3367 "\\)" "\\>")
3368 org-todo-line-tags-regexp
3369 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3370 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3371 (org-re
3372 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3373 org-looking-at-done-regexp
3374 (concat "^" "\\(?:"
3375 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3376 "\\>")
3377 org-deadline-regexp (concat "\\<" org-deadline-string)
3378 org-deadline-time-regexp
3379 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3380 org-deadline-line-regexp
3381 (concat "\\<\\(" org-deadline-string "\\).*")
3382 org-scheduled-regexp
3383 (concat "\\<" org-scheduled-string)
3384 org-scheduled-time-regexp
3385 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3386 org-closed-time-regexp
3387 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3388 org-keyword-time-regexp
3389 (concat "\\<\\(" org-scheduled-string
3390 "\\|" org-deadline-string
3391 "\\|" org-closed-string
3392 "\\|" org-clock-string "\\)"
3393 " *[[<]\\([^]>]+\\)[]>]")
3394 org-keyword-time-not-clock-regexp
3395 (concat "\\<\\(" org-scheduled-string
3396 "\\|" org-deadline-string
3397 "\\|" org-closed-string
3398 "\\)"
3399 " *[[<]\\([^]>]+\\)[]>]")
3400 org-maybe-keyword-time-regexp
3401 (concat "\\(\\<\\(" org-scheduled-string
3402 "\\|" org-deadline-string
3403 "\\|" org-closed-string
3404 "\\|" org-clock-string "\\)\\)?"
3405 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3406 org-planning-or-clock-line-re
3407 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3408 "\\|" org-deadline-string
3409 "\\|" org-closed-string "\\|" org-clock-string
3410 "\\)\\>\\)")
3411 )
3412 (org-compute-latex-and-specials-regexp)
3413 (org-set-font-lock-defaults))))
3414
3415 (defun org-file-contents (file &optional noerror)
3416 "Return the contents of FILE, as a string."
3417 (if (or (not file)
3418 (not (file-readable-p file)))
3419 (if noerror
3420 (progn
3421 (message "Cannot read file %s" file)
3422 (ding) (sit-for 2)
3423 "")
3424 (error "Cannot read file %s" file))
3425 (with-temp-buffer
3426 (insert-file-contents file)
3427 (buffer-string))))
3428
3429 (defun org-extract-log-state-settings (x)
3430 "Extract the log state setting from a TODO keyword string.
3431 This will extract info from a string like \"WAIT(w@/!)\"."
3432 (let (kw key log1 log2)
3433 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3434 (setq kw (match-string 1 x)
3435 key (and (match-end 2) (match-string 2 x))
3436 log1 (and (match-end 3) (match-string 3 x))
3437 log2 (and (match-end 4) (match-string 4 x)))
3438 (and (or log1 log2)
3439 (list kw
3440 (and log1 (if (equal log1 "!") 'time 'note))
3441 (and log2 (if (equal log2 "!") 'time 'note)))))))
3442
3443 (defun org-remove-keyword-keys (list)
3444 "Remove a pair of parenthesis at the end of each string in LIST."
3445 (mapcar (lambda (x)
3446 (if (string-match "(.*)$" x)
3447 (substring x 0 (match-beginning 0))
3448 x))
3449 list))
3450
3451 ;; FIXME: this could be done much better, using second characters etc.
3452 (defun org-assign-fast-keys (alist)
3453 "Assign fast keys to a keyword-key alist.
3454 Respect keys that are already there."
3455 (let (new e k c c1 c2 (char ?a))
3456 (while (setq e (pop alist))
3457 (cond
3458 ((equal e '(:startgroup)) (push e new))
3459 ((equal e '(:endgroup)) (push e new))
3460 (t
3461 (setq k (car e) c2 nil)
3462 (if (cdr e)
3463 (setq c (cdr e))
3464 ;; automatically assign a character.
3465 (setq c1 (string-to-char
3466 (downcase (substring
3467 k (if (= (string-to-char k) ?@) 1 0)))))
3468 (if (or (rassoc c1 new) (rassoc c1 alist))
3469 (while (or (rassoc char new) (rassoc char alist))
3470 (setq char (1+ char)))
3471 (setq c2 c1))
3472 (setq c (or c2 char)))
3473 (push (cons k c) new))))
3474 (nreverse new)))
3475
3476 ;;; Some variables used in various places
3477
3478 (defvar org-window-configuration nil
3479 "Used in various places to store a window configuration.")
3480 (defvar org-finish-function nil
3481 "Function to be called when `C-c C-c' is used.
3482 This is for getting out of special buffers like remember.")
3483
3484
3485 ;; FIXME: Occasionally check by commenting these, to make sure
3486 ;; no other functions uses these, forgetting to let-bind them.
3487 (defvar entry)
3488 (defvar state)
3489 (defvar last-state)
3490 (defvar date)
3491 (defvar description)
3492
3493 ;; Defined somewhere in this file, but used before definition.
3494 (defvar org-html-entities)
3495 (defvar org-struct-menu)
3496 (defvar org-org-menu)
3497 (defvar org-tbl-menu)
3498 (defvar org-agenda-keymap)
3499
3500 ;;;; Define the Org-mode
3501
3502 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3503 (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."))
3504
3505
3506 ;; We use a before-change function to check if a table might need
3507 ;; an update.
3508 (defvar org-table-may-need-update t
3509 "Indicates that a table might need an update.
3510 This variable is set by `org-before-change-function'.
3511 `org-table-align' sets it back to nil.")
3512 (defun org-before-change-function (beg end)
3513 "Every change indicates that a table might need an update."
3514 (setq org-table-may-need-update t))
3515 (defvar org-mode-map)
3516 (defvar org-mode-hook nil
3517 "Mode hook for Org-mode, run after the mode was turned on.")
3518 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3519 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3520 (defvar org-table-buffer-is-an nil)
3521 (defconst org-outline-regexp "\\*+ ")
3522
3523 ;;;###autoload
3524 (define-derived-mode org-mode outline-mode "Org"
3525 "Outline-based notes management and organizer, alias
3526 \"Carsten's outline-mode for keeping track of everything.\"
3527
3528 Org-mode develops organizational tasks around a NOTES file which
3529 contains information about projects as plain text. Org-mode is
3530 implemented on top of outline-mode, which is ideal to keep the content
3531 of large files well structured. It supports ToDo items, deadlines and
3532 time stamps, which magically appear in the diary listing of the Emacs
3533 calendar. Tables are easily created with a built-in table editor.
3534 Plain text URL-like links connect to websites, emails (VM), Usenet
3535 messages (Gnus), BBDB entries, and any files related to the project.
3536 For printing and sharing of notes, an Org-mode file (or a part of it)
3537 can be exported as a structured ASCII or HTML file.
3538
3539 The following commands are available:
3540
3541 \\{org-mode-map}"
3542
3543 ;; Get rid of Outline menus, they are not needed
3544 ;; Need to do this here because define-derived-mode sets up
3545 ;; the keymap so late. Still, it is a waste to call this each time
3546 ;; we switch another buffer into org-mode.
3547 (if (featurep 'xemacs)
3548 (when (boundp 'outline-mode-menu-heading)
3549 ;; Assume this is Greg's port, it used easymenu
3550 (easy-menu-remove outline-mode-menu-heading)
3551 (easy-menu-remove outline-mode-menu-show)
3552 (easy-menu-remove outline-mode-menu-hide))
3553 (define-key org-mode-map [menu-bar headings] 'undefined)
3554 (define-key org-mode-map [menu-bar hide] 'undefined)
3555 (define-key org-mode-map [menu-bar show] 'undefined))
3556
3557 (org-load-modules-maybe)
3558 (easy-menu-add org-org-menu)
3559 (easy-menu-add org-tbl-menu)
3560 (org-install-agenda-files-menu)
3561 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3562 (org-add-to-invisibility-spec '(org-cwidth))
3563 (when (featurep 'xemacs)
3564 (org-set-local 'line-move-ignore-invisible t))
3565 (org-set-local 'outline-regexp org-outline-regexp)
3566 (org-set-local 'outline-level 'org-outline-level)
3567 (when (and org-ellipsis
3568 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3569 (fboundp 'make-glyph-code))
3570 (unless org-display-table
3571 (setq org-display-table (make-display-table)))
3572 (set-display-table-slot
3573 org-display-table 4
3574 (vconcat (mapcar
3575 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3576 org-ellipsis)))
3577 (if (stringp org-ellipsis) org-ellipsis "..."))))
3578 (setq buffer-display-table org-display-table))
3579 (org-set-regexps-and-options)
3580 (when (and org-tag-faces (not org-tags-special-faces-re))
3581 ;; tag faces set outside customize.... force initialization.
3582 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3583 ;; Calc embedded
3584 (org-set-local 'calc-embedded-open-mode "# ")
3585 (modify-syntax-entry ?# "<")
3586 (modify-syntax-entry ?@ "w")
3587 (if org-startup-truncated (setq truncate-lines t))
3588 (org-set-local 'font-lock-unfontify-region-function
3589 'org-unfontify-region)
3590 ;; Activate before-change-function
3591 (org-set-local 'org-table-may-need-update t)
3592 (org-add-hook 'before-change-functions 'org-before-change-function nil
3593 'local)
3594 ;; Check for running clock before killing a buffer
3595 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3596 ;; Paragraphs and auto-filling
3597 (org-set-autofill-regexps)
3598 (setq indent-line-function 'org-indent-line-function)
3599 (org-update-radio-target-regexp)
3600 ;; Make sure dependence stuff works reliably, even for users who set it
3601 ;; too late :-(
3602 (if org-enforce-todo-dependencies
3603 (add-hook 'org-blocker-hook
3604 'org-block-todo-from-children-or-siblings)
3605 (remove-hook 'org-blocker-hook
3606 'org-block-todo-from-children-or-siblings))
3607 (if org-enforce-todo-checkbox-dependencies
3608 (add-hook 'org-blocker-hook
3609 'org-block-todo-from-checkboxes)
3610 (remove-hook 'org-blocker-hook
3611 'org-block-todo-from-checkboxes))
3612
3613 ;; Comment characters
3614 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3615 (org-set-local 'comment-padding " ")
3616
3617 ;; Align options lines
3618 (org-set-local
3619 'align-mode-rules-list
3620 '((org-in-buffer-settings
3621 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3622 (modes . '(org-mode)))))
3623
3624 ;; Imenu
3625 (org-set-local 'imenu-create-index-function
3626 'org-imenu-get-tree)
3627
3628 ;; Make isearch reveal context
3629 (if (or (featurep 'xemacs)
3630 (not (boundp 'outline-isearch-open-invisible-function)))
3631 ;; Emacs 21 and XEmacs make use of the hook
3632 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3633 ;; Emacs 22 deals with this through a special variable
3634 (org-set-local 'outline-isearch-open-invisible-function
3635 (lambda (&rest ignore) (org-show-context 'isearch))))
3636
3637 ;; If empty file that did not turn on org-mode automatically, make it to.
3638 (if (and org-insert-mode-line-in-empty-file
3639 (interactive-p)
3640 (= (point-min) (point-max)))
3641 (insert "# -*- mode: org -*-\n\n"))
3642
3643 (unless org-inhibit-startup
3644 (when org-startup-align-all-tables
3645 (let ((bmp (buffer-modified-p)))
3646 (org-table-map-tables 'org-table-align)
3647 (set-buffer-modified-p bmp)))
3648 (org-set-startup-visibility)))
3649
3650 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3651
3652 (defun org-current-time ()
3653 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3654 (if (> (car org-time-stamp-rounding-minutes) 1)
3655 (let ((r (car org-time-stamp-rounding-minutes))
3656 (time (decode-time)))
3657 (apply 'encode-time
3658 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3659 (nthcdr 2 time))))
3660 (current-time)))
3661
3662 ;;;; Font-Lock stuff, including the activators
3663
3664 (defvar org-mouse-map (make-sparse-keymap))
3665 (org-defkey org-mouse-map
3666 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3667 (org-defkey org-mouse-map
3668 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3669 (when org-mouse-1-follows-link
3670 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3671 (when org-tab-follows-link
3672 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3673 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3674 (when org-return-follows-link
3675 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3676 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3677
3678 (require 'font-lock)
3679
3680 (defconst org-non-link-chars "]\t\n\r<>")
3681 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3682 "shell" "elisp"))
3683 (defvar org-link-types-re nil
3684 "Matches a link that has a url-like prefix like \"http:\"")
3685 (defvar org-link-re-with-space nil
3686 "Matches a link with spaces, optional angular brackets around it.")
3687 (defvar org-link-re-with-space2 nil
3688 "Matches a link with spaces, optional angular brackets around it.")
3689 (defvar org-link-re-with-space3 nil
3690 "Matches a link with spaces, only for internal part in bracket links.")
3691 (defvar org-angle-link-re nil
3692 "Matches link with angular brackets, spaces are allowed.")
3693 (defvar org-plain-link-re nil
3694 "Matches plain link, without spaces.")
3695 (defvar org-bracket-link-regexp nil
3696 "Matches a link in double brackets.")
3697 (defvar org-bracket-link-analytic-regexp nil
3698 "Regular expression used to analyze links.
3699 Here is what the match groups contain after a match:
3700 1: http:
3701 2: http
3702 3: path
3703 4: [desc]
3704 5: desc")
3705 (defvar org-bracket-link-analytic-regexp++ nil
3706 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3707 (defvar org-any-link-re nil
3708 "Regular expression matching any link.")
3709
3710 (defun org-make-link-regexps ()
3711 "Update the link regular expressions.
3712 This should be called after the variable `org-link-types' has changed."
3713 (setq org-link-types-re
3714 (concat
3715 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3716 org-link-re-with-space
3717 (concat
3718 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3719 "\\([^" org-non-link-chars " ]"
3720 "[^" org-non-link-chars "]*"
3721 "[^" org-non-link-chars " ]\\)>?")
3722 org-link-re-with-space2
3723 (concat
3724 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3725 "\\([^" org-non-link-chars " ]"
3726 "[^\t\n\r]*"
3727 "[^" org-non-link-chars " ]\\)>?")
3728 org-link-re-with-space3
3729 (concat
3730 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3731 "\\([^" org-non-link-chars " ]"
3732 "[^\t\n\r]*\\)")
3733 org-angle-link-re
3734 (concat
3735 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3736 "\\([^" org-non-link-chars " ]"
3737 "[^" org-non-link-chars "]*"
3738 "\\)>")
3739 org-plain-link-re
3740 (concat
3741 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3742 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3743 org-bracket-link-regexp
3744 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3745 org-bracket-link-analytic-regexp
3746 (concat
3747 "\\[\\["
3748 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3749 "\\([^]]+\\)"
3750 "\\]"
3751 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3752 "\\]")
3753 org-bracket-link-analytic-regexp++
3754 (concat
3755 "\\[\\["
3756 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3757 "\\([^]]+\\)"
3758 "\\]"
3759 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3760 "\\]")
3761 org-any-link-re
3762 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3763 org-angle-link-re "\\)\\|\\("
3764 org-plain-link-re "\\)")))
3765
3766 (org-make-link-regexps)
3767
3768 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3769 "Regular expression for fast time stamp matching.")
3770 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3771 "Regular expression for fast time stamp matching.")
3772 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3773 "Regular expression matching time strings for analysis.
3774 This one does not require the space after the date, so it can be used
3775 on a string that terminates immediately after the date.")
3776 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3777 "Regular expression matching time strings for analysis.")
3778 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3779 "Regular expression matching time stamps, with groups.")
3780 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3781 "Regular expression matching time stamps (also [..]), with groups.")
3782 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3783 "Regular expression matching a time stamp range.")
3784 (defconst org-tr-regexp-both
3785 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3786 "Regular expression matching a time stamp range.")
3787 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3788 org-ts-regexp "\\)?")
3789 "Regular expression matching a time stamp or time stamp range.")
3790 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3791 org-ts-regexp-both "\\)?")
3792 "Regular expression matching a time stamp or time stamp range.
3793 The time stamps may be either active or inactive.")
3794
3795 (defvar org-emph-face nil)
3796
3797 (defun org-do-emphasis-faces (limit)
3798 "Run through the buffer and add overlays to links."
3799 (let (rtn)
3800 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3801 (if (not (= (char-after (match-beginning 3))
3802 (char-after (match-beginning 4))))
3803 (progn
3804 (setq rtn t)
3805 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3806 'face
3807 (nth 1 (assoc (match-string 3)
3808 org-emphasis-alist)))
3809 (add-text-properties (match-beginning 2) (match-end 2)
3810 '(font-lock-multiline t))
3811 (when org-hide-emphasis-markers
3812 (add-text-properties (match-end 4) (match-beginning 5)
3813 '(invisible org-link))
3814 (add-text-properties (match-beginning 3) (match-end 3)
3815 '(invisible org-link)))))
3816 (backward-char 1))
3817 rtn))
3818
3819 (defun org-emphasize (&optional char)
3820 "Insert or change an emphasis, i.e. a font like bold or italic.
3821 If there is an active region, change that region to a new emphasis.
3822 If there is no region, just insert the marker characters and position
3823 the cursor between them.
3824 CHAR should be either the marker character, or the first character of the
3825 HTML tag associated with that emphasis. If CHAR is a space, the means
3826 to remove the emphasis of the selected region.
3827 If char is not given (for example in an interactive call) it
3828 will be prompted for."
3829 (interactive)
3830 (let ((eal org-emphasis-alist) e det
3831 (erc org-emphasis-regexp-components)
3832 (prompt "")
3833 (string "") beg end move tag c s)
3834 (if (org-region-active-p)
3835 (setq beg (region-beginning) end (region-end)
3836 string (buffer-substring beg end))
3837 (setq move t))
3838
3839 (while (setq e (pop eal))
3840 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3841 c (aref tag 0))
3842 (push (cons c (string-to-char (car e))) det)
3843 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3844 (substring tag 1)))))
3845 (setq det (nreverse det))
3846 (unless char
3847 (message "%s" (concat "Emphasis marker or tag:" prompt))
3848 (setq char (read-char-exclusive)))
3849 (setq char (or (cdr (assoc char det)) char))
3850 (if (equal char ?\ )
3851 (setq s "" move nil)
3852 (unless (assoc (char-to-string char) org-emphasis-alist)
3853 (error "No such emphasis marker: \"%c\"" char))
3854 (setq s (char-to-string char)))
3855 (while (and (> (length string) 1)
3856 (equal (substring string 0 1) (substring string -1))
3857 (assoc (substring string 0 1) org-emphasis-alist))
3858 (setq string (substring string 1 -1)))
3859 (setq string (concat s string s))
3860 (if beg (delete-region beg end))
3861 (unless (or (bolp)
3862 (string-match (concat "[" (nth 0 erc) "\n]")
3863 (char-to-string (char-before (point)))))
3864 (insert " "))
3865 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3866 (char-to-string (char-after (point))))
3867 (insert " ") (backward-char 1))
3868 (insert string)
3869 (and move (backward-char 1))))
3870
3871 (defconst org-nonsticky-props
3872 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3873
3874
3875 (defun org-activate-plain-links (limit)
3876 "Run through the buffer and add overlays to links."
3877 (catch 'exit
3878 (let (f)
3879 (while (re-search-forward org-plain-link-re limit t)
3880 (setq f (get-text-property (match-beginning 0) 'face))
3881 (if (or (eq f 'org-tag)
3882 (and (listp f) (memq 'org-tag f)))
3883 nil
3884 (add-text-properties (match-beginning 0) (match-end 0)
3885 (list 'mouse-face 'highlight
3886 'rear-nonsticky org-nonsticky-props
3887 'keymap org-mouse-map
3888 ))
3889 (throw 'exit t))))))
3890
3891 (defun org-activate-code (limit)
3892 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3893 (progn
3894 (remove-text-properties (match-beginning 0) (match-end 0)
3895 '(display t invisible t intangible t))
3896 t)))
3897
3898 (defun org-activate-angle-links (limit)
3899 "Run through the buffer and add overlays to links."
3900 (if (re-search-forward org-angle-link-re limit t)
3901 (progn
3902 (add-text-properties (match-beginning 0) (match-end 0)
3903 (list 'mouse-face 'highlight
3904 'rear-nonsticky org-nonsticky-props
3905 'keymap org-mouse-map
3906 ))
3907 t)))
3908
3909 (defun org-activate-footnote-links (limit)
3910 "Run through the buffer and add overlays to links."
3911 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
3912 limit t)
3913 (progn
3914 (add-text-properties (match-beginning 2) (match-end 2)
3915 (list 'mouse-face 'highlight
3916 'rear-nonsticky org-nonsticky-props
3917 'keymap org-mouse-map
3918 'help-echo
3919 (if (= (point-at-bol) (match-beginning 2))
3920 "Footnote definition"
3921 "Footnote reference")
3922 ))
3923 t)))
3924
3925 (defun org-activate-bracket-links (limit)
3926 "Run through the buffer and add overlays to bracketed links."
3927 (if (re-search-forward org-bracket-link-regexp limit t)
3928 (let* ((help (concat "LINK: "
3929 (org-match-string-no-properties 1)))
3930 ;; FIXME: above we should remove the escapes.
3931 ;; but that requires another match, protecting match data,
3932 ;; a lot of overhead for font-lock.
3933 (ip (org-maybe-intangible
3934 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3935 'keymap org-mouse-map 'mouse-face 'highlight
3936 'font-lock-multiline t 'help-echo help)))
3937 (vp (list 'rear-nonsticky org-nonsticky-props
3938 'keymap org-mouse-map 'mouse-face 'highlight
3939 ' font-lock-multiline t 'help-echo help)))
3940 ;; We need to remove the invisible property here. Table narrowing
3941 ;; may have made some of this invisible.
3942 (remove-text-properties (match-beginning 0) (match-end 0)
3943 '(invisible nil))
3944 (if (match-end 3)
3945 (progn
3946 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3947 (add-text-properties (match-beginning 3) (match-end 3) vp)
3948 (add-text-properties (match-end 3) (match-end 0) ip))
3949 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3950 (add-text-properties (match-beginning 1) (match-end 1) vp)
3951 (add-text-properties (match-end 1) (match-end 0) ip))
3952 t)))
3953
3954 (defun org-activate-dates (limit)
3955 "Run through the buffer and add overlays to dates."
3956 (if (re-search-forward org-tsr-regexp-both limit t)
3957 (progn
3958 (add-text-properties (match-beginning 0) (match-end 0)
3959 (list 'mouse-face 'highlight
3960 'rear-nonsticky org-nonsticky-props
3961 'keymap org-mouse-map))
3962 (when org-display-custom-times
3963 (if (match-end 3)
3964 (org-display-custom-time (match-beginning 3) (match-end 3)))
3965 (org-display-custom-time (match-beginning 1) (match-end 1)))
3966 t)))
3967
3968 (defvar org-target-link-regexp nil
3969 "Regular expression matching radio targets in plain text.")
3970 (make-variable-buffer-local 'org-target-link-regexp)
3971 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3972 "Regular expression matching a link target.")
3973 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3974 "Regular expression matching a radio target.")
3975 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3976 "Regular expression matching any target.")
3977
3978 (defun org-activate-target-links (limit)
3979 "Run through the buffer and add overlays to target matches."
3980 (when org-target-link-regexp
3981 (let ((case-fold-search t))
3982 (if (re-search-forward org-target-link-regexp limit t)
3983 (progn
3984 (add-text-properties (match-beginning 0) (match-end 0)
3985 (list 'mouse-face 'highlight
3986 'rear-nonsticky org-nonsticky-props
3987 'keymap org-mouse-map
3988 'help-echo "Radio target link"
3989 'org-linked-text t))
3990 t)))))
3991
3992 (defun org-update-radio-target-regexp ()
3993 "Find all radio targets in this file and update the regular expression."
3994 (interactive)
3995 (when (memq 'radio org-activate-links)
3996 (setq org-target-link-regexp
3997 (org-make-target-link-regexp (org-all-targets 'radio)))
3998 (org-restart-font-lock)))
3999
4000 (defun org-hide-wide-columns (limit)
4001 (let (s e)
4002 (setq s (text-property-any (point) (or limit (point-max))
4003 'org-cwidth t))
4004 (when s
4005 (setq e (next-single-property-change s 'org-cwidth))
4006 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4007 (goto-char e)
4008 t)))
4009
4010 (defvar org-latex-and-specials-regexp nil
4011 "Regular expression for highlighting export special stuff.")
4012 (defvar org-match-substring-regexp)
4013 (defvar org-match-substring-with-braces-regexp)
4014 (defvar org-export-html-special-string-regexps)
4015
4016 (defun org-compute-latex-and-specials-regexp ()
4017 "Compute regular expression for stuff treated specially by exporters."
4018 (if (not org-highlight-latex-fragments-and-specials)
4019 (org-set-local 'org-latex-and-specials-regexp nil)
4020 (require 'org-exp)
4021 (let*
4022 ((matchers (plist-get org-format-latex-options :matchers))
4023 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4024 org-latex-regexps)))
4025 (options (org-combine-plists (org-default-export-plist)
4026 (org-infile-export-plist)))
4027 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4028 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4029 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4030 (org-export-html-expand (plist-get options :expand-quoted-html))
4031 (org-export-with-special-strings (plist-get options :special-strings))
4032 (re-sub
4033 (cond
4034 ((equal org-export-with-sub-superscripts '{})
4035 (list org-match-substring-with-braces-regexp))
4036 (org-export-with-sub-superscripts
4037 (list org-match-substring-regexp))
4038 (t nil)))
4039 (re-latex
4040 (if org-export-with-LaTeX-fragments
4041 (mapcar (lambda (x) (nth 1 x)) latexs)))
4042 (re-macros
4043 (if org-export-with-TeX-macros
4044 (list (concat "\\\\"
4045 (regexp-opt
4046 (append (mapcar 'car org-html-entities)
4047 (if (boundp 'org-latex-entities)
4048 org-latex-entities nil))
4049 'words))) ; FIXME
4050 ))
4051 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4052 (re-special (if org-export-with-special-strings
4053 (mapcar (lambda (x) (car x))
4054 org-export-html-special-string-regexps)))
4055 (re-rest
4056 (delq nil
4057 (list
4058 (if org-export-html-expand "@<[^>\n]+>")
4059 ))))
4060 (org-set-local
4061 'org-latex-and-specials-regexp
4062 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4063 re-rest) "\\|")))))
4064
4065 (defun org-do-latex-and-special-faces (limit)
4066 "Run through the buffer and add overlays to links."
4067 (when org-latex-and-specials-regexp
4068 (let (rtn d)
4069 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4070 limit t))
4071 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4072 'face))
4073 '(org-code org-verbatim underline)))
4074 (progn
4075 (setq rtn t
4076 d (cond ((member (char-after (1+ (match-beginning 0)))
4077 '(?_ ?^)) 1)
4078 (t 0)))
4079 (font-lock-prepend-text-property
4080 (+ d (match-beginning 0)) (match-end 0)
4081 'face 'org-latex-and-export-specials)
4082 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4083 '(font-lock-multiline t)))))
4084 rtn)))
4085
4086 (defun org-restart-font-lock ()
4087 "Restart font-lock-mode, to force refontification."
4088 (when (and (boundp 'font-lock-mode) font-lock-mode)
4089 (font-lock-mode -1)
4090 (font-lock-mode 1)))
4091
4092 (defun org-all-targets (&optional radio)
4093 "Return a list of all targets in this file.
4094 With optional argument RADIO, only find radio targets."
4095 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4096 rtn)
4097 (save-excursion
4098 (goto-char (point-min))
4099 (while (re-search-forward re nil t)
4100 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4101 rtn)))
4102
4103 (defun org-make-target-link-regexp (targets)
4104 "Make regular expression matching all strings in TARGETS.
4105 The regular expression finds the targets also if there is a line break
4106 between words."
4107 (and targets
4108 (concat
4109 "\\<\\("
4110 (mapconcat
4111 (lambda (x)
4112 (while (string-match " +" x)
4113 (setq x (replace-match "\\s-+" t t x)))
4114 x)
4115 targets
4116 "\\|")
4117 "\\)\\>")))
4118
4119 (defun org-activate-tags (limit)
4120 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4121 (progn
4122 (add-text-properties (match-beginning 1) (match-end 1)
4123 (list 'mouse-face 'highlight
4124 'rear-nonsticky org-nonsticky-props
4125 'keymap org-mouse-map))
4126 t)))
4127
4128 (defun org-outline-level ()
4129 (save-excursion
4130 (looking-at outline-regexp)
4131 (if (match-beginning 1)
4132 (+ (org-get-string-indentation (match-string 1)) 1000)
4133 (1- (- (match-end 0) (match-beginning 0))))))
4134
4135 (defvar org-font-lock-keywords nil)
4136
4137 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4138 "Regular expression matching a property line.")
4139
4140 (defvar org-font-lock-hook nil
4141 "Functions to be called for special font lock stuff.")
4142
4143 (defun org-font-lock-hook (limit)
4144 (run-hook-with-args 'org-font-lock-hook limit))
4145
4146 (defun org-set-font-lock-defaults ()
4147 (let* ((em org-fontify-emphasized-text)
4148 (lk org-activate-links)
4149 (org-font-lock-extra-keywords
4150 (list
4151 ;; Call the hook
4152 '(org-font-lock-hook)
4153 ;; Headlines
4154 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4155 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4156 ;; Table lines
4157 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4158 (1 'org-table t))
4159 ;; Table internals
4160 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4161 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4162 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4163 ;; Drawers
4164 (list org-drawer-regexp '(0 'org-special-keyword t))
4165 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4166 ;; Properties
4167 (list org-property-re
4168 '(1 'org-special-keyword t)
4169 '(3 'org-property-value t))
4170 (if org-format-transports-properties-p
4171 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4172 ;; Links
4173 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4174 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4175 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4176 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4177 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4178 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4179 (if (memq 'footnote lk) '(org-activate-footnote-links
4180 (2 'org-footnote t)))
4181 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4182 '(org-hide-wide-columns (0 nil append))
4183 ;; TODO lines
4184 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4185 '(1 (org-get-todo-face 1) t))
4186 ;; DONE
4187 (if org-fontify-done-headline
4188 (list (concat "^[*]+ +\\<\\("
4189 (mapconcat 'regexp-quote org-done-keywords "\\|")
4190 "\\)\\(.*\\)")
4191 '(2 'org-headline-done t))
4192 nil)
4193 ;; Priorities
4194 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4195 ;; Tags
4196 '(org-font-lock-add-tag-faces)
4197 ;; Special keywords
4198 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4199 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4200 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4201 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4202 ;; Emphasis
4203 (if em
4204 (if (featurep 'xemacs)
4205 '(org-do-emphasis-faces (0 nil append))
4206 '(org-do-emphasis-faces)))
4207 ;; Checkboxes
4208 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4209 2 'bold prepend)
4210 (if org-provide-checkbox-statistics
4211 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4212 (0 (org-get-checkbox-statistics-face) t)))
4213 ;; Description list items
4214 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4215 2 'bold prepend)
4216 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4217 '(1 'org-archived prepend))
4218 ;; Specials
4219 '(org-do-latex-and-special-faces)
4220 ;; Code
4221 '(org-activate-code (1 'org-code t))
4222 ;; COMMENT
4223 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4224 "\\|" org-quote-string "\\)\\>")
4225 '(1 'org-special-keyword t))
4226 '("^#.*" (0 'font-lock-comment-face t))
4227 )))
4228 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4229 ;; Now set the full font-lock-keywords
4230 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4231 (org-set-local 'font-lock-defaults
4232 '(org-font-lock-keywords t nil nil backward-paragraph))
4233 (kill-local-variable 'font-lock-keywords) nil))
4234
4235 (defvar org-m nil)
4236 (defvar org-l nil)
4237 (defvar org-f nil)
4238 (defun org-get-level-face (n)
4239 "Get the right face for match N in font-lock matching of headlines."
4240 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4241 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4242 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4243 (cond
4244 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4245 ((eq n 2) org-f)
4246 (t (if org-level-color-stars-only nil org-f))))
4247
4248 (defun org-get-todo-face (kwd)
4249 "Get the right face for a TODO keyword KWD.
4250 If KWD is a number, get the corresponding match group."
4251 (if (numberp kwd) (setq kwd (match-string kwd)))
4252 (or (cdr (assoc kwd org-todo-keyword-faces))
4253 (and (member kwd org-done-keywords) 'org-done)
4254 'org-todo))
4255
4256 (defun org-font-lock-add-tag-faces (limit)
4257 "Add the special tag faces."
4258 (when (and org-tag-faces org-tags-special-faces-re)
4259 (while (re-search-forward org-tags-special-faces-re limit t)
4260 (add-text-properties (match-beginning 1) (match-end 1)
4261 (list 'face (org-get-tag-face 1)
4262 'font-lock-fontified t))
4263 (backward-char 1))))
4264
4265 (defun org-get-tag-face (kwd)
4266 "Get the right face for a TODO keyword KWD.
4267 If KWD is a number, get the corresponding match group."
4268 (if (numberp kwd) (setq kwd (match-string kwd)))
4269 (or (cdr (assoc kwd org-tag-faces))
4270 'org-tag))
4271
4272 (defun org-unfontify-region (beg end &optional maybe_loudly)
4273 "Remove fontification and activation overlays from links."
4274 (font-lock-default-unfontify-region beg end)
4275 (let* ((buffer-undo-list t)
4276 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4277 (inhibit-modification-hooks t)
4278 deactivate-mark buffer-file-name buffer-file-truename)
4279 (remove-text-properties beg end
4280 '(mouse-face t keymap t org-linked-text t
4281 invisible t intangible t))))
4282
4283 ;;;; Visibility cycling, including org-goto and indirect buffer
4284
4285 ;;; Cycling
4286
4287 (defvar org-cycle-global-status nil)
4288 (make-variable-buffer-local 'org-cycle-global-status)
4289 (defvar org-cycle-subtree-status nil)
4290 (make-variable-buffer-local 'org-cycle-subtree-status)
4291
4292 ;;;###autoload
4293 (defun org-cycle (&optional arg)
4294 "Visibility cycling for Org-mode.
4295
4296 - When this function is called with a prefix argument, rotate the entire
4297 buffer through 3 states (global cycling)
4298 1. OVERVIEW: Show only top-level headlines.
4299 2. CONTENTS: Show all headlines of all levels, but no body text.
4300 3. SHOW ALL: Show everything.
4301 When called with two C-u C-u prefixes, switch to the startup visibility,
4302 determined by the variable `org-startup-folded', and by any VISIBILITY
4303 properties in the buffer.
4304 When called with three C-u C-u C-u prefixed, show the entire buffer,
4305 including drawers.
4306
4307 - When point is at the beginning of a headline, rotate the subtree started
4308 by this line through 3 different states (local cycling)
4309 1. FOLDED: Only the main headline is shown.
4310 2. CHILDREN: The main headline and the direct children are shown.
4311 From this state, you can move to one of the children
4312 and zoom in further.
4313 3. SUBTREE: Show the entire subtree, including body text.
4314
4315 - When there is a numeric prefix, go up to a heading with level ARG, do
4316 a `show-subtree' and return to the previous cursor position. If ARG
4317 is negative, go up that many levels.
4318
4319 - When point is not at the beginning of a headline, execute the global
4320 binding for TAB, which is re-indenting the line. See the option
4321 `org-cycle-emulate-tab' for details.
4322
4323 - Special case: if point is at the beginning of the buffer and there is
4324 no headline in line 1, this function will act as if called with prefix arg.
4325 But only if also the variable `org-cycle-global-at-bob' is t."
4326 (interactive "P")
4327 (org-load-modules-maybe)
4328 (let* ((outline-regexp
4329 (if (and (org-mode-p) org-cycle-include-plain-lists)
4330 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4331 outline-regexp))
4332 (bob-special (and org-cycle-global-at-bob (bobp)
4333 (not (looking-at outline-regexp))))
4334 (org-cycle-hook
4335 (if bob-special
4336 (delq 'org-optimize-window-after-visibility-change
4337 (copy-sequence org-cycle-hook))
4338 org-cycle-hook))
4339 (pos (point)))
4340
4341 (if (or bob-special (equal arg '(4)))
4342 ;; special case: use global cycling
4343 (setq arg t))
4344
4345 (cond
4346
4347 ((equal arg '(16))
4348 (org-set-startup-visibility)
4349 (message "Startup visibility, plus VISIBILITY properties"))
4350
4351 ((equal arg '(64))
4352 (show-all)
4353 (message "Entire buffer visible, including drawers"))
4354
4355 ((org-at-table-p 'any)
4356 ;; Enter the table or move to the next field in the table
4357 (or (org-table-recognize-table.el)
4358 (progn
4359 (if arg (org-table-edit-field t)
4360 (org-table-justify-field-maybe)
4361 (call-interactively 'org-table-next-field)))))
4362
4363 ((eq arg t) ;; Global cycling
4364
4365 (cond
4366 ((and (eq last-command this-command)
4367 (eq org-cycle-global-status 'overview))
4368 ;; We just created the overview - now do table of contents
4369 ;; This can be slow in very large buffers, so indicate action
4370 (message "CONTENTS...")
4371 (org-content)
4372 (message "CONTENTS...done")
4373 (setq org-cycle-global-status 'contents)
4374 (run-hook-with-args 'org-cycle-hook 'contents))
4375
4376 ((and (eq last-command this-command)
4377 (eq org-cycle-global-status 'contents))
4378 ;; We just showed the table of contents - now show everything
4379 (show-all)
4380 (message "SHOW ALL")
4381 (setq org-cycle-global-status 'all)
4382 (run-hook-with-args 'org-cycle-hook 'all))
4383
4384 (t
4385 ;; Default action: go to overview
4386 (org-overview)
4387 (message "OVERVIEW")
4388 (setq org-cycle-global-status 'overview)
4389 (run-hook-with-args 'org-cycle-hook 'overview))))
4390
4391 ((and org-drawers org-drawer-regexp
4392 (save-excursion
4393 (beginning-of-line 1)
4394 (looking-at org-drawer-regexp)))
4395 ;; Toggle block visibility
4396 (org-flag-drawer
4397 (not (get-char-property (match-end 0) 'invisible))))
4398
4399 ((integerp arg)
4400 ;; Show-subtree, ARG levels up from here.
4401 (save-excursion
4402 (org-back-to-heading)
4403 (outline-up-heading (if (< arg 0) (- arg)
4404 (- (funcall outline-level) arg)))
4405 (org-show-subtree)))
4406
4407 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4408 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4409 ;; At a heading: rotate between three different views
4410 (org-back-to-heading)
4411 (let ((goal-column 0) eoh eol eos)
4412 ;; First, some boundaries
4413 (save-excursion
4414 (org-back-to-heading)
4415 (save-excursion
4416 (beginning-of-line 2)
4417 (while (and (not (eobp)) ;; this is like `next-line'
4418 (get-char-property (1- (point)) 'invisible))
4419 (beginning-of-line 2)) (setq eol (point)))
4420 (outline-end-of-heading) (setq eoh (point))
4421 (org-end-of-subtree t)
4422 (unless (eobp)
4423 (skip-chars-forward " \t\n")
4424 (beginning-of-line 1) ; in case this is an item
4425 )
4426 (setq eos (1- (point))))
4427 ;; Find out what to do next and set `this-command'
4428 (cond
4429 ((= eos eoh)
4430 ;; Nothing is hidden behind this heading
4431 (message "EMPTY ENTRY")
4432 (setq org-cycle-subtree-status nil)
4433 (save-excursion
4434 (goto-char eos)
4435 (outline-next-heading)
4436 (if (org-invisible-p) (org-flag-heading nil))))
4437 ((or (>= eol eos)
4438 (not (string-match "\\S-" (buffer-substring eol eos))))
4439 ;; Entire subtree is hidden in one line: open it
4440 (org-show-entry)
4441 (show-children)
4442 (message "CHILDREN")
4443 (save-excursion
4444 (goto-char eos)
4445 (outline-next-heading)
4446 (if (org-invisible-p) (org-flag-heading nil)))
4447 (setq org-cycle-subtree-status 'children)
4448 (run-hook-with-args 'org-cycle-hook 'children))
4449 ((and (eq last-command this-command)
4450 (eq org-cycle-subtree-status 'children))
4451 ;; We just showed the children, now show everything.
4452 (org-show-subtree)
4453 (message "SUBTREE")
4454 (setq org-cycle-subtree-status 'subtree)
4455 (run-hook-with-args 'org-cycle-hook 'subtree))
4456 (t
4457 ;; Default action: hide the subtree.
4458 (hide-subtree)
4459 (message "FOLDED")
4460 (setq org-cycle-subtree-status 'folded)
4461 (run-hook-with-args 'org-cycle-hook 'folded)))))
4462
4463 ;; TAB emulation and template completion
4464 (buffer-read-only (org-back-to-heading))
4465
4466 ((org-try-structure-completion))
4467
4468 ((org-try-cdlatex-tab))
4469
4470 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4471 (or (not (bolp))
4472 (not (looking-at outline-regexp))))
4473 (call-interactively (global-key-binding "\t")))
4474
4475 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4476 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4477 (or (and (eq org-cycle-emulate-tab 'white)
4478 (= (match-end 0) (point-at-eol)))
4479 (and (eq org-cycle-emulate-tab 'whitestart)
4480 (>= (match-end 0) pos))))
4481 t
4482 (eq org-cycle-emulate-tab t))
4483 (call-interactively (global-key-binding "\t")))
4484
4485 (t (save-excursion
4486 (org-back-to-heading)
4487 (org-cycle))))))
4488
4489 ;;;###autoload
4490 (defun org-global-cycle (&optional arg)
4491 "Cycle the global visibility. For details see `org-cycle'.
4492 With C-u prefix arg, switch to startup visibility.
4493 With a numeric prefix, show all headlines up to that level."
4494 (interactive "P")
4495 (let ((org-cycle-include-plain-lists
4496 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4497 (cond
4498 ((integerp arg)
4499 (show-all)
4500 (hide-sublevels arg)
4501 (setq org-cycle-global-status 'contents))
4502 ((equal arg '(4))
4503 (org-set-startup-visibility)
4504 (message "Startup visibility, plus VISIBILITY properties."))
4505 (t
4506 (org-cycle '(4))))))
4507
4508 (defun org-set-startup-visibility ()
4509 "Set the visibility required by startup options and properties."
4510 (cond
4511 ((eq org-startup-folded t)
4512 (org-cycle '(4)))
4513 ((eq org-startup-folded 'content)
4514 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4515 (org-cycle '(4)) (org-cycle '(4)))))
4516 (org-set-visibility-according-to-property 'no-cleanup)
4517 (org-cycle-hide-archived-subtrees 'all)
4518 (org-cycle-hide-drawers 'all)
4519 (org-cycle-show-empty-lines 'all))
4520
4521 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4522 "Switch subtree visibilities according to :VISIBILITY: property."
4523 (interactive)
4524 (let (org-show-entry-below state)
4525 (save-excursion
4526 (goto-char (point-min))
4527 (while (re-search-forward
4528 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4529 nil t)
4530 (setq state (match-string 1))
4531 (save-excursion
4532 (org-back-to-heading t)
4533 (hide-subtree)
4534 (org-reveal)
4535 (cond
4536 ((equal state '("fold" "folded"))
4537 (hide-subtree))
4538 ((equal state "children")
4539 (org-show-hidden-entry)
4540 (show-children))
4541 ((equal state "content")
4542 (save-excursion
4543 (save-restriction
4544 (org-narrow-to-subtree)
4545 (org-content))))
4546 ((member state '("all" "showall"))
4547 (show-subtree)))))
4548 (unless no-cleanup
4549 (org-cycle-hide-archived-subtrees 'all)
4550 (org-cycle-hide-drawers 'all)
4551 (org-cycle-show-empty-lines 'all)))))
4552
4553 (defun org-overview ()
4554 "Switch to overview mode, showing only top-level headlines.
4555 Really, this shows all headlines with level equal or greater than the level
4556 of the first headline in the buffer. This is important, because if the
4557 first headline is not level one, then (hide-sublevels 1) gives confusing
4558 results."
4559 (interactive)
4560 (let ((level (save-excursion
4561 (goto-char (point-min))
4562 (if (re-search-forward (concat "^" outline-regexp) nil t)
4563 (progn
4564 (goto-char (match-beginning 0))
4565 (funcall outline-level))))))
4566 (and level (hide-sublevels level))))
4567
4568 (defun org-content (&optional arg)
4569 "Show all headlines in the buffer, like a table of contents.
4570 With numerical argument N, show content up to level N."
4571 (interactive "P")
4572 (save-excursion
4573 ;; Visit all headings and show their offspring
4574 (and (integerp arg) (org-overview))
4575 (goto-char (point-max))
4576 (catch 'exit
4577 (while (and (progn (condition-case nil
4578 (outline-previous-visible-heading 1)
4579 (error (goto-char (point-min))))
4580 t)
4581 (looking-at outline-regexp))
4582 (if (integerp arg)
4583 (show-children (1- arg))
4584 (show-branches))
4585 (if (bobp) (throw 'exit nil))))))
4586
4587
4588 (defun org-optimize-window-after-visibility-change (state)
4589 "Adjust the window after a change in outline visibility.
4590 This function is the default value of the hook `org-cycle-hook'."
4591 (when (get-buffer-window (current-buffer))
4592 (cond
4593 ; ((eq state 'overview) (org-first-headline-recenter 1))
4594 ; ((eq state 'overview) (org-beginning-of-line))
4595 ((eq state 'content) nil)
4596 ((eq state 'all) nil)
4597 ((eq state 'folded) nil)
4598 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4599 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4600
4601 (defun org-compact-display-after-subtree-move ()
4602 "Show a compacter version of the tree of the entry's parent."
4603 (save-excursion
4604 (if (org-up-heading-safe)
4605 (progn
4606 (hide-subtree)
4607 (show-entry)
4608 (show-children)
4609 (org-cycle-show-empty-lines 'children)
4610 (org-cycle-hide-drawers 'children))
4611 (org-overview))))
4612
4613 (defun org-cycle-show-empty-lines (state)
4614 "Show empty lines above all visible headlines.
4615 The region to be covered depends on STATE when called through
4616 `org-cycle-hook'. Lisp program can use t for STATE to get the
4617 entire buffer covered. Note that an empty line is only shown if there
4618 are at least `org-cycle-separator-lines' empty lines before the headline."
4619 (when (> org-cycle-separator-lines 0)
4620 (save-excursion
4621 (let* ((n org-cycle-separator-lines)
4622 (re (cond
4623 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4624 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4625 (t (let ((ns (number-to-string (- n 2))))
4626 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4627 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4628 beg end)
4629 (cond
4630 ((memq state '(overview contents t))
4631 (setq beg (point-min) end (point-max)))
4632 ((memq state '(children folded))
4633 (setq beg (point) end (progn (org-end-of-subtree t t)
4634 (beginning-of-line 2)
4635 (point)))))
4636 (when beg
4637 (goto-char beg)
4638 (while (re-search-forward re end t)
4639 (if (not (get-char-property (match-end 1) 'invisible))
4640 (outline-flag-region
4641 (match-beginning 1) (match-end 1) nil)))))))
4642 ;; Never hide empty lines at the end of the file.
4643 (save-excursion
4644 (goto-char (point-max))
4645 (outline-previous-heading)
4646 (outline-end-of-heading)
4647 (if (and (looking-at "[ \t\n]+")
4648 (= (match-end 0) (point-max)))
4649 (outline-flag-region (point) (match-end 0) nil))))
4650
4651 (defun org-show-empty-lines-in-parent ()
4652 "Move to the parent and re-show empty lines before visible headlines."
4653 (save-excursion
4654 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4655 (org-cycle-show-empty-lines context))))
4656
4657 (defun org-cycle-hide-drawers (state)
4658 "Re-hide all drawers after a visibility state change."
4659 (when (and (org-mode-p)
4660 (not (memq state '(overview folded))))
4661 (save-excursion
4662 (let* ((globalp (memq state '(contents all)))
4663 (beg (if globalp (point-min) (point)))
4664 (end (if globalp (point-max) (org-end-of-subtree t))))
4665 (goto-char beg)
4666 (while (re-search-forward org-drawer-regexp end t)
4667 (org-flag-drawer t))))))
4668
4669 (defun org-flag-drawer (flag)
4670 (save-excursion
4671 (beginning-of-line 1)
4672 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4673 (let ((b (match-end 0))
4674 (outline-regexp org-outline-regexp))
4675 (if (re-search-forward
4676 "^[ \t]*:END:"
4677 (save-excursion (outline-next-heading) (point)) t)
4678 (outline-flag-region b (point-at-eol) flag)
4679 (error ":END: line missing"))))))
4680
4681 (defun org-subtree-end-visible-p ()
4682 "Is the end of the current subtree visible?"
4683 (pos-visible-in-window-p
4684 (save-excursion (org-end-of-subtree t) (point))))
4685
4686 (defun org-first-headline-recenter (&optional N)
4687 "Move cursor to the first headline and recenter the headline.
4688 Optional argument N means, put the headline into the Nth line of the window."
4689 (goto-char (point-min))
4690 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4691 (beginning-of-line)
4692 (recenter (prefix-numeric-value N))))
4693
4694 ;;; Org-goto
4695
4696 (defvar org-goto-window-configuration nil)
4697 (defvar org-goto-marker nil)
4698 (defvar org-goto-map
4699 (let ((map (make-sparse-keymap)))
4700 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4701 (while (setq cmd (pop cmds))
4702 (substitute-key-definition cmd cmd map global-map)))
4703 (suppress-keymap map)
4704 (org-defkey map "\C-m" 'org-goto-ret)
4705 (org-defkey map [(return)] 'org-goto-ret)
4706 (org-defkey map [(left)] 'org-goto-left)
4707 (org-defkey map [(right)] 'org-goto-right)
4708 (org-defkey map [(control ?g)] 'org-goto-quit)
4709 (org-defkey map "\C-i" 'org-cycle)
4710 (org-defkey map [(tab)] 'org-cycle)
4711 (org-defkey map [(down)] 'outline-next-visible-heading)
4712 (org-defkey map [(up)] 'outline-previous-visible-heading)
4713 (if org-goto-auto-isearch
4714 (if (fboundp 'define-key-after)
4715 (define-key-after map [t] 'org-goto-local-auto-isearch)
4716 nil)
4717 (org-defkey map "q" 'org-goto-quit)
4718 (org-defkey map "n" 'outline-next-visible-heading)
4719 (org-defkey map "p" 'outline-previous-visible-heading)
4720 (org-defkey map "f" 'outline-forward-same-level)
4721 (org-defkey map "b" 'outline-backward-same-level)
4722 (org-defkey map "u" 'outline-up-heading))
4723 (org-defkey map "/" 'org-occur)
4724 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4725 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4726 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4727 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4728 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4729 map))
4730
4731 (defconst org-goto-help
4732 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4733 RET=jump to location [Q]uit and return to previous location
4734 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4735
4736 (defvar org-goto-start-pos) ; dynamically scoped parameter
4737
4738 ;; FIXME: Docstring doe not mention both interfaces
4739 (defun org-goto (&optional alternative-interface)
4740 "Look up a different location in the current file, keeping current visibility.
4741
4742 When you want look-up or go to a different location in a document, the
4743 fastest way is often to fold the entire buffer and then dive into the tree.
4744 This method has the disadvantage, that the previous location will be folded,
4745 which may not be what you want.
4746
4747 This command works around this by showing a copy of the current buffer
4748 in an indirect buffer, in overview mode. You can dive into the tree in
4749 that copy, use org-occur and incremental search to find a location.
4750 When pressing RET or `Q', the command returns to the original buffer in
4751 which the visibility is still unchanged. After RET is will also jump to
4752 the location selected in the indirect buffer and expose the
4753 the headline hierarchy above."
4754 (interactive "P")
4755 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4756 (org-refile-use-outline-path t)
4757 (interface
4758 (if (not alternative-interface)
4759 org-goto-interface
4760 (if (eq org-goto-interface 'outline)
4761 'outline-path-completion
4762 'outline)))
4763 (org-goto-start-pos (point))
4764 (selected-point
4765 (if (eq interface 'outline)
4766 (car (org-get-location (current-buffer) org-goto-help))
4767 (nth 3 (org-refile-get-location "Goto: ")))))
4768 (if selected-point
4769 (progn
4770 (org-mark-ring-push org-goto-start-pos)
4771 (goto-char selected-point)
4772 (if (or (org-invisible-p) (org-invisible-p2))
4773 (org-show-context 'org-goto)))
4774 (message "Quit"))))
4775
4776 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4777 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4778 (defvar org-goto-local-auto-isearch-map) ; defined below
4779
4780 (defun org-get-location (buf help)
4781 "Let the user select a location in the Org-mode buffer BUF.
4782 This function uses a recursive edit. It returns the selected position
4783 or nil."
4784 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4785 (isearch-hide-immediately nil)
4786 (isearch-search-fun-function
4787 (lambda () 'org-goto-local-search-headings))
4788 (org-goto-selected-point org-goto-exit-command))
4789 (save-excursion
4790 (save-window-excursion
4791 (delete-other-windows)
4792 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4793 (switch-to-buffer
4794 (condition-case nil
4795 (make-indirect-buffer (current-buffer) "*org-goto*")
4796 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4797 (with-output-to-temp-buffer "*Help*"
4798 (princ help))
4799 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4800 (setq buffer-read-only nil)
4801 (let ((org-startup-truncated t)
4802 (org-startup-folded nil)
4803 (org-startup-align-all-tables nil))
4804 (org-mode)
4805 (org-overview))
4806 (setq buffer-read-only t)
4807 (if (and (boundp 'org-goto-start-pos)
4808 (integer-or-marker-p org-goto-start-pos))
4809 (let ((org-show-hierarchy-above t)
4810 (org-show-siblings t)
4811 (org-show-following-heading t))
4812 (goto-char org-goto-start-pos)
4813 (and (org-invisible-p) (org-show-context)))
4814 (goto-char (point-min)))
4815 (let (org-special-ctrl-a/e) (org-beginning-of-line))
4816 (message "Select location and press RET")
4817 (use-local-map org-goto-map)
4818 (recursive-edit)
4819 ))
4820 (kill-buffer "*org-goto*")
4821 (cons org-goto-selected-point org-goto-exit-command)))
4822
4823 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4824 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4825 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4826 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4827
4828 (defun org-goto-local-search-headings (string bound noerror)
4829 "Search and make sure that any matches are in headlines."
4830 (catch 'return
4831 (while (if isearch-forward
4832 (search-forward string bound noerror)
4833 (search-backward string bound noerror))
4834 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4835 (and (member :headline context)
4836 (not (member :tags context))))
4837 (throw 'return (point))))))
4838
4839 (defun org-goto-local-auto-isearch ()
4840 "Start isearch."
4841 (interactive)
4842 (goto-char (point-min))
4843 (let ((keys (this-command-keys)))
4844 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4845 (isearch-mode t)
4846 (isearch-process-search-char (string-to-char keys)))))
4847
4848 (defun org-goto-ret (&optional arg)
4849 "Finish `org-goto' by going to the new location."
4850 (interactive "P")
4851 (setq org-goto-selected-point (point)
4852 org-goto-exit-command 'return)
4853 (throw 'exit nil))
4854
4855 (defun org-goto-left ()
4856 "Finish `org-goto' by going to the new location."
4857 (interactive)
4858 (if (org-on-heading-p)
4859 (progn
4860 (beginning-of-line 1)
4861 (setq org-goto-selected-point (point)
4862 org-goto-exit-command 'left)
4863 (throw 'exit nil))
4864 (error "Not on a heading")))
4865
4866 (defun org-goto-right ()
4867 "Finish `org-goto' by going to the new location."
4868 (interactive)
4869 (if (org-on-heading-p)
4870 (progn
4871 (setq org-goto-selected-point (point)
4872 org-goto-exit-command 'right)
4873 (throw 'exit nil))
4874 (error "Not on a heading")))
4875
4876 (defun org-goto-quit ()
4877 "Finish `org-goto' without cursor motion."
4878 (interactive)
4879 (setq org-goto-selected-point nil)
4880 (setq org-goto-exit-command 'quit)
4881 (throw 'exit nil))
4882
4883 ;;; Indirect buffer display of subtrees
4884
4885 (defvar org-indirect-dedicated-frame nil
4886 "This is the frame being used for indirect tree display.")
4887 (defvar org-last-indirect-buffer nil)
4888
4889 (defun org-tree-to-indirect-buffer (&optional arg)
4890 "Create indirect buffer and narrow it to current subtree.
4891 With numerical prefix ARG, go up to this level and then take that tree.
4892 If ARG is negative, go up that many levels.
4893 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4894 indirect buffer previously made with this command, to avoid proliferation of
4895 indirect buffers. However, when you call the command with a `C-u' prefix, or
4896 when `org-indirect-buffer-display' is `new-frame', the last buffer
4897 is kept so that you can work with several indirect buffers at the same time.
4898 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4899 requests that a new frame be made for the new buffer, so that the dedicated
4900 frame is not changed."
4901 (interactive "P")
4902 (let ((cbuf (current-buffer))
4903 (cwin (selected-window))
4904 (pos (point))
4905 beg end level heading ibuf)
4906 (save-excursion
4907 (org-back-to-heading t)
4908 (when (numberp arg)
4909 (setq level (org-outline-level))
4910 (if (< arg 0) (setq arg (+ level arg)))
4911 (while (> (setq level (org-outline-level)) arg)
4912 (outline-up-heading 1 t)))
4913 (setq beg (point)
4914 heading (org-get-heading))
4915 (org-end-of-subtree t) (setq end (point)))
4916 (if (and (buffer-live-p org-last-indirect-buffer)
4917 (not (eq org-indirect-buffer-display 'new-frame))
4918 (not arg))
4919 (kill-buffer org-last-indirect-buffer))
4920 (setq ibuf (org-get-indirect-buffer cbuf)
4921 org-last-indirect-buffer ibuf)
4922 (cond
4923 ((or (eq org-indirect-buffer-display 'new-frame)
4924 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4925 (select-frame (make-frame))
4926 (delete-other-windows)
4927 (switch-to-buffer ibuf)
4928 (org-set-frame-title heading))
4929 ((eq org-indirect-buffer-display 'dedicated-frame)
4930 (raise-frame
4931 (select-frame (or (and org-indirect-dedicated-frame
4932 (frame-live-p org-indirect-dedicated-frame)
4933 org-indirect-dedicated-frame)
4934 (setq org-indirect-dedicated-frame (make-frame)))))
4935 (delete-other-windows)
4936 (switch-to-buffer ibuf)
4937 (org-set-frame-title (concat "Indirect: " heading)))
4938 ((eq org-indirect-buffer-display 'current-window)
4939 (switch-to-buffer ibuf))
4940 ((eq org-indirect-buffer-display 'other-window)
4941 (pop-to-buffer ibuf))
4942 (t (error "Invalid value.")))
4943 (if (featurep 'xemacs)
4944 (save-excursion (org-mode) (turn-on-font-lock)))
4945 (narrow-to-region beg end)
4946 (show-all)
4947 (goto-char pos)
4948 (and (window-live-p cwin) (select-window cwin))))
4949
4950 (defun org-get-indirect-buffer (&optional buffer)
4951 (setq buffer (or buffer (current-buffer)))
4952 (let ((n 1) (base (buffer-name buffer)) bname)
4953 (while (buffer-live-p
4954 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4955 (setq n (1+ n)))
4956 (condition-case nil
4957 (make-indirect-buffer buffer bname 'clone)
4958 (error (make-indirect-buffer buffer bname)))))
4959
4960 (defun org-set-frame-title (title)
4961 "Set the title of the current frame to the string TITLE."
4962 ;; FIXME: how to name a single frame in XEmacs???
4963 (unless (featurep 'xemacs)
4964 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4965
4966 ;;;; Structure editing
4967
4968 ;;; Inserting headlines
4969
4970 (defun org-previous-line-empty-p ()
4971 (save-excursion
4972 (and (not (bobp))
4973 (or (beginning-of-line 0) t)
4974 (save-match-data
4975 (looking-at "[ \t]*$")))))
4976
4977 (defun org-insert-heading (&optional force-heading)
4978 "Insert a new heading or item with same depth at point.
4979 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4980 If point is at the beginning of a headline, insert a sibling before the
4981 current headline. If point is not at the beginning, do not split the line,
4982 but create the new headline after the current line."
4983 (interactive "P")
4984 (if (= (buffer-size) 0)
4985 (insert "\n* ")
4986 (when (or force-heading (not (org-insert-item)))
4987 (let* ((empty-line-p nil)
4988 (head (save-excursion
4989 (condition-case nil
4990 (progn
4991 (org-back-to-heading)
4992 (setq empty-line-p (org-previous-line-empty-p))
4993 (match-string 0))
4994 (error "*"))))
4995 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
4996 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
4997 pos hide-previous previous-pos)
4998 (cond
4999 ((and (org-on-heading-p) (bolp)
5000 (or (bobp)
5001 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5002 ;; insert before the current line
5003 (open-line (if blank 2 1)))
5004 ((and (bolp)
5005 (or (bobp)
5006 (save-excursion
5007 (backward-char 1) (not (org-invisible-p)))))
5008 ;; insert right here
5009 nil)
5010 (t
5011 ;; somewhere in the line
5012 (save-excursion
5013 (setq previous-pos (point-at-bol))
5014 (end-of-line)
5015 (setq hide-previous (org-invisible-p)))
5016 (and org-insert-heading-respect-content (org-show-subtree))
5017 (let ((split
5018 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5019 (save-excursion
5020 (let ((p (point)))
5021 (goto-char (point-at-bol))
5022 (and (looking-at org-complex-heading-regexp)
5023 (> p (match-beginning 4)))))))
5024 tags pos)
5025 (cond
5026 (org-insert-heading-respect-content
5027 (org-end-of-subtree nil t)
5028 (or (bolp) (newline))
5029 (or (org-previous-line-empty-p)
5030 (and blank (newline)))
5031 (open-line 1))
5032 ((org-on-heading-p)
5033 (when hide-previous
5034 (show-children)
5035 (org-show-entry))
5036 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5037 (setq tags (and (match-end 2) (match-string 2)))
5038 (and (match-end 1)
5039 (delete-region (match-beginning 1) (match-end 1)))
5040 (setq pos (point-at-bol))
5041 (or split (end-of-line 1))
5042 (delete-horizontal-space)
5043 (newline (if blank 2 1))
5044 (when tags
5045 (save-excursion
5046 (goto-char pos)
5047 (end-of-line 1)
5048 (insert " " tags)
5049 (org-set-tags nil 'align))))
5050 (t
5051 (or split (end-of-line 1))
5052 (newline (if blank 2 1)))))))
5053 (insert head) (just-one-space)
5054 (setq pos (point))
5055 (end-of-line 1)
5056 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5057 (when (and org-insert-heading-respect-content hide-previous)
5058 (save-excursion
5059 (goto-char previous-pos)
5060 (hide-subtree)))
5061 (run-hooks 'org-insert-heading-hook)))))
5062
5063 (defun org-get-heading (&optional no-tags)
5064 "Return the heading of the current entry, without the stars."
5065 (save-excursion
5066 (org-back-to-heading t)
5067 (if (looking-at
5068 (if no-tags
5069 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5070 "\\*+[ \t]+\\([^\r\n]*\\)"))
5071 (match-string 1) "")))
5072
5073 (defun org-heading-components ()
5074 "Return the components of the current heading.
5075 This is a list with the following elements:
5076 - the level as an integer
5077 - the reduced level, different if `org-odd-levels-only' is set.
5078 - the TODO keyword, or nil
5079 - the priority character, like ?A, or nil if no priority is given
5080 - the headline text itself, or the tags string if no headline text
5081 - the tags string, or nil."
5082 (save-excursion
5083 (org-back-to-heading t)
5084 (if (looking-at org-complex-heading-regexp)
5085 (list (length (match-string 1))
5086 (org-reduced-level (length (match-string 1)))
5087 (org-match-string-no-properties 2)
5088 (and (match-end 3) (aref (match-string 3) 2))
5089 (org-match-string-no-properties 4)
5090 (org-match-string-no-properties 5)))))
5091
5092 (defun org-insert-heading-after-current ()
5093 "Insert a new heading with same level as current, after current subtree."
5094 (interactive)
5095 (org-back-to-heading)
5096 (org-insert-heading)
5097 (org-move-subtree-down)
5098 (end-of-line 1))
5099
5100 (defun org-insert-heading-respect-content ()
5101 (interactive)
5102 (let ((org-insert-heading-respect-content t))
5103 (org-insert-heading t)))
5104
5105 (defun org-insert-todo-heading-respect-content (&optional force-state)
5106 (interactive "P")
5107 (let ((org-insert-heading-respect-content t))
5108 (org-insert-todo-heading force-state t)))
5109
5110 (defun org-insert-todo-heading (arg &optional force-heading)
5111 "Insert a new heading with the same level and TODO state as current heading.
5112 If the heading has no TODO state, or if the state is DONE, use the first
5113 state (TODO by default). Also with prefix arg, force first state."
5114 (interactive "P")
5115 (when (or force-heading (not (org-insert-item 'checkbox)))
5116 (org-insert-heading force-heading)
5117 (save-excursion
5118 (org-back-to-heading)
5119 (outline-previous-heading)
5120 (looking-at org-todo-line-regexp))
5121 (if (or arg
5122 (not (match-beginning 2))
5123 (member (match-string 2) org-done-keywords))
5124 (insert (car org-todo-keywords-1) " ")
5125 (insert (match-string 2) " "))
5126 (when org-provide-todo-statistics
5127 (org-update-parent-todo-statistics))))
5128
5129 (defun org-insert-subheading (arg)
5130 "Insert a new subheading and demote it.
5131 Works for outline headings and for plain lists alike."
5132 (interactive "P")
5133 (org-insert-heading arg)
5134 (cond
5135 ((org-on-heading-p) (org-do-demote))
5136 ((org-at-item-p) (org-indent-item 1))))
5137
5138 (defun org-insert-todo-subheading (arg)
5139 "Insert a new subheading with TODO keyword or checkbox and demote it.
5140 Works for outline headings and for plain lists alike."
5141 (interactive "P")
5142 (org-insert-todo-heading arg)
5143 (cond
5144 ((org-on-heading-p) (org-do-demote))
5145 ((org-at-item-p) (org-indent-item 1))))
5146
5147 ;;; Promotion and Demotion
5148
5149 (defun org-promote-subtree ()
5150 "Promote the entire subtree.
5151 See also `org-promote'."
5152 (interactive)
5153 (save-excursion
5154 (org-map-tree 'org-promote))
5155 (org-fix-position-after-promote))
5156
5157 (defun org-demote-subtree ()
5158 "Demote the entire subtree. See `org-demote'.
5159 See also `org-promote'."
5160 (interactive)
5161 (save-excursion
5162 (org-map-tree 'org-demote))
5163 (org-fix-position-after-promote))
5164
5165
5166 (defun org-do-promote ()
5167 "Promote the current heading higher up the tree.
5168 If the region is active in `transient-mark-mode', promote all headings
5169 in the region."
5170 (interactive)
5171 (save-excursion
5172 (if (org-region-active-p)
5173 (org-map-region 'org-promote (region-beginning) (region-end))
5174 (org-promote)))
5175 (org-fix-position-after-promote))
5176
5177 (defun org-do-demote ()
5178 "Demote the current heading lower down the tree.
5179 If the region is active in `transient-mark-mode', demote all headings
5180 in the region."
5181 (interactive)
5182 (save-excursion
5183 (if (org-region-active-p)
5184 (org-map-region 'org-demote (region-beginning) (region-end))
5185 (org-demote)))
5186 (org-fix-position-after-promote))
5187
5188 (defun org-fix-position-after-promote ()
5189 "Make sure that after pro/demotion cursor position is right."
5190 (let ((pos (point)))
5191 (when (save-excursion
5192 (beginning-of-line 1)
5193 (looking-at org-todo-line-regexp)
5194 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5195 (cond ((eobp) (insert " "))
5196 ((eolp) (insert " "))
5197 ((equal (char-after) ?\ ) (forward-char 1))))))
5198
5199 (defun org-reduced-level (l)
5200 "Compute the effective level of a heading.
5201 This takes into account the setting of `org-odd-levels-only'."
5202 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5203
5204 (defun org-get-valid-level (level &optional change)
5205 "Rectify a level change under the influence of `org-odd-levels-only'
5206 LEVEL is a current level, CHANGE is by how much the level should be
5207 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5208 even level numbers will become the next higher odd number."
5209 (if org-odd-levels-only
5210 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5211 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5212 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5213 (max 1 (+ level change))))
5214
5215 (if (boundp 'define-obsolete-function-alias)
5216 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5217 (define-obsolete-function-alias 'org-get-legal-level
5218 'org-get-valid-level)
5219 (define-obsolete-function-alias 'org-get-legal-level
5220 'org-get-valid-level "23.1")))
5221
5222 (defun org-promote ()
5223 "Promote the current heading higher up the tree.
5224 If the region is active in `transient-mark-mode', promote all headings
5225 in the region."
5226 (org-back-to-heading t)
5227 (let* ((level (save-match-data (funcall outline-level)))
5228 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5229 (diff (abs (- level (length up-head) -1))))
5230 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5231 (replace-match up-head nil t)
5232 ;; Fixup tag positioning
5233 (and org-auto-align-tags (org-set-tags nil t))
5234 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5235
5236 (defun org-demote ()
5237 "Demote the current heading lower down the tree.
5238 If the region is active in `transient-mark-mode', demote all headings
5239 in the region."
5240 (org-back-to-heading t)
5241 (let* ((level (save-match-data (funcall outline-level)))
5242 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5243 (diff (abs (- level (length down-head) -1))))
5244 (replace-match down-head nil t)
5245 ;; Fixup tag positioning
5246 (and org-auto-align-tags (org-set-tags nil t))
5247 (if org-adapt-indentation (org-fixup-indentation diff))))
5248
5249 (defun org-map-tree (fun)
5250 "Call FUN for every heading underneath the current one."
5251 (org-back-to-heading)
5252 (let ((level (funcall outline-level)))
5253 (save-excursion
5254 (funcall fun)
5255 (while (and (progn
5256 (outline-next-heading)
5257 (> (funcall outline-level) level))
5258 (not (eobp)))
5259 (funcall fun)))))
5260
5261 (defun org-map-region (fun beg end)
5262 "Call FUN for every heading between BEG and END."
5263 (let ((org-ignore-region t))
5264 (save-excursion
5265 (setq end (copy-marker end))
5266 (goto-char beg)
5267 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5268 (< (point) end))
5269 (funcall fun))
5270 (while (and (progn
5271 (outline-next-heading)
5272 (< (point) end))
5273 (not (eobp)))
5274 (funcall fun)))))
5275
5276 (defun org-fixup-indentation (diff)
5277 "Change the indentation in the current entry by DIFF
5278 However, if any line in the current entry has no indentation, or if it
5279 would end up with no indentation after the change, nothing at all is done."
5280 (save-excursion
5281 (let ((end (save-excursion (outline-next-heading)
5282 (point-marker)))
5283 (prohibit (if (> diff 0)
5284 "^\\S-"
5285 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5286 col)
5287 (unless (save-excursion (end-of-line 1)
5288 (re-search-forward prohibit end t))
5289 (while (and (< (point) end)
5290 (re-search-forward "^[ \t]+" end t))
5291 (goto-char (match-end 0))
5292 (setq col (current-column))
5293 (if (< diff 0) (replace-match ""))
5294 (org-indent-to-column (+ diff col))))
5295 (move-marker end nil))))
5296
5297 (defun org-convert-to-odd-levels ()
5298 "Convert an org-mode file with all levels allowed to one with odd levels.
5299 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5300 level 5 etc."
5301 (interactive)
5302 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5303 (let ((org-odd-levels-only nil) n)
5304 (save-excursion
5305 (goto-char (point-min))
5306 (while (re-search-forward "^\\*\\*+ " nil t)
5307 (setq n (- (length (match-string 0)) 2))
5308 (while (>= (setq n (1- n)) 0)
5309 (org-demote))
5310 (end-of-line 1))))))
5311
5312
5313 (defun org-convert-to-oddeven-levels ()
5314 "Convert an org-mode file with only odd levels to one with odd and even levels.
5315 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5316 section with an even level, conversion would destroy the structure of the file. An error
5317 is signaled in this case."
5318 (interactive)
5319 (goto-char (point-min))
5320 ;; First check if there are no even levels
5321 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5322 (org-show-context t)
5323 (error "Not all levels are odd in this file. Conversion not possible."))
5324 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5325 (let ((org-odd-levels-only nil) n)
5326 (save-excursion
5327 (goto-char (point-min))
5328 (while (re-search-forward "^\\*\\*+ " nil t)
5329 (setq n (/ (1- (length (match-string 0))) 2))
5330 (while (>= (setq n (1- n)) 0)
5331 (org-promote))
5332 (end-of-line 1))))))
5333
5334 (defun org-tr-level (n)
5335 "Make N odd if required."
5336 (if org-odd-levels-only (1+ (/ n 2)) n))
5337
5338 ;;; Vertical tree motion, cutting and pasting of subtrees
5339
5340 (defun org-move-subtree-up (&optional arg)
5341 "Move the current subtree up past ARG headlines of the same level."
5342 (interactive "p")
5343 (org-move-subtree-down (- (prefix-numeric-value arg))))
5344
5345 (defun org-move-subtree-down (&optional arg)
5346 "Move the current subtree down past ARG headlines of the same level."
5347 (interactive "p")
5348 (setq arg (prefix-numeric-value arg))
5349 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5350 'outline-get-last-sibling))
5351 (ins-point (make-marker))
5352 (cnt (abs arg))
5353 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5354 ;; Select the tree
5355 (org-back-to-heading)
5356 (setq beg0 (point))
5357 (save-excursion
5358 (setq ne-beg (org-back-over-empty-lines))
5359 (setq beg (point)))
5360 (save-match-data
5361 (save-excursion (outline-end-of-heading)
5362 (setq folded (org-invisible-p)))
5363 (outline-end-of-subtree))
5364 (outline-next-heading)
5365 (setq ne-end (org-back-over-empty-lines))
5366 (setq end (point))
5367 (goto-char beg0)
5368 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5369 ;; include less whitespace
5370 (save-excursion
5371 (goto-char beg)
5372 (forward-line (- ne-beg ne-end))
5373 (setq beg (point))))
5374 ;; Find insertion point, with error handling
5375 (while (> cnt 0)
5376 (or (and (funcall movfunc) (looking-at outline-regexp))
5377 (progn (goto-char beg0)
5378 (error "Cannot move past superior level or buffer limit")))
5379 (setq cnt (1- cnt)))
5380 (if (> arg 0)
5381 ;; Moving forward - still need to move over subtree
5382 (progn (org-end-of-subtree t t)
5383 (save-excursion
5384 (org-back-over-empty-lines)
5385 (or (bolp) (newline)))))
5386 (setq ne-ins (org-back-over-empty-lines))
5387 (move-marker ins-point (point))
5388 (setq txt (buffer-substring beg end))
5389 (org-save-markers-in-region beg end)
5390 (delete-region beg end)
5391 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5392 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5393 (let ((bbb (point)))
5394 (insert-before-markers txt)
5395 (org-reinstall-markers-in-region bbb)
5396 (move-marker ins-point bbb))
5397 (or (bolp) (insert "\n"))
5398 (setq ins-end (point))
5399 (goto-char ins-point)
5400 (org-skip-whitespace)
5401 (when (and (< arg 0)
5402 (org-first-sibling-p)
5403 (> ne-ins ne-beg))
5404 ;; Move whitespace back to beginning
5405 (save-excursion
5406 (goto-char ins-end)
5407 (let ((kill-whole-line t))
5408 (kill-line (- ne-ins ne-beg)) (point)))
5409 (insert (make-string (- ne-ins ne-beg) ?\n)))
5410 (move-marker ins-point nil)
5411 (org-compact-display-after-subtree-move)
5412 (org-show-empty-lines-in-parent)
5413 (unless folded
5414 (org-show-entry)
5415 (show-children)
5416 (org-cycle-hide-drawers 'children))))
5417
5418 (defvar org-subtree-clip ""
5419 "Clipboard for cut and paste of subtrees.
5420 This is actually only a copy of the kill, because we use the normal kill
5421 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5422
5423 (defvar org-subtree-clip-folded nil
5424 "Was the last copied subtree folded?
5425 This is used to fold the tree back after pasting.")
5426
5427 (defun org-cut-subtree (&optional n)
5428 "Cut the current subtree into the clipboard.
5429 With prefix arg N, cut this many sequential subtrees.
5430 This is a short-hand for marking the subtree and then cutting it."
5431 (interactive "p")
5432 (org-copy-subtree n 'cut))
5433
5434 (defun org-copy-subtree (&optional n cut force-store-markers)
5435 "Cut the current subtree into the clipboard.
5436 With prefix arg N, cut this many sequential subtrees.
5437 This is a short-hand for marking the subtree and then copying it.
5438 If CUT is non-nil, actually cut the subtree.
5439 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5440 of some markers in the region, even if CUT is non-nil. This is
5441 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5442 (interactive "p")
5443 (let (beg end folded (beg0 (point)))
5444 (if (interactive-p)
5445 (org-back-to-heading nil) ; take what looks like a subtree
5446 (org-back-to-heading t)) ; take what is really there
5447 (org-back-over-empty-lines)
5448 (setq beg (point))
5449 (skip-chars-forward " \t\r\n")
5450 (save-match-data
5451 (save-excursion (outline-end-of-heading)
5452 (setq folded (org-invisible-p)))
5453 (condition-case nil
5454 (outline-forward-same-level (1- n))
5455 (error nil))
5456 (org-end-of-subtree t t))
5457 (org-back-over-empty-lines)
5458 (setq end (point))
5459 (goto-char beg0)
5460 (when (> end beg)
5461 (setq org-subtree-clip-folded folded)
5462 (when (or cut force-store-markers)
5463 (org-save-markers-in-region beg end))
5464 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5465 (setq org-subtree-clip (current-kill 0))
5466 (message "%s: Subtree(s) with %d characters"
5467 (if cut "Cut" "Copied")
5468 (length org-subtree-clip)))))
5469
5470 (defun org-paste-subtree (&optional level tree for-yank)
5471 "Paste the clipboard as a subtree, with modification of headline level.
5472 The entire subtree is promoted or demoted in order to match a new headline
5473 level.
5474
5475 If the cursor is at the beginning of a headline, the same level as
5476 that headline is used to paste the tree
5477
5478 If not, the new level is derived from the *visible* headings
5479 before and after the insertion point, and taken to be the inferior headline
5480 level of the two. So if the previous visible heading is level 3 and the
5481 next is level 4 (or vice versa), level 4 will be used for insertion.
5482 This makes sure that the subtree remains an independent subtree and does
5483 not swallow low level entries.
5484
5485 You can also force a different level, either by using a numeric prefix
5486 argument, or by inserting the heading marker by hand. For example, if the
5487 cursor is after \"*****\", then the tree will be shifted to level 5.
5488
5489 If optional TREE is given, use this text instead of the kill ring.
5490
5491 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5492 move back over whitespace before inserting, and move point to the end of
5493 the inserted text when done."
5494 (interactive "P")
5495 (unless (org-kill-is-subtree-p tree)
5496 (error "%s"
5497 (substitute-command-keys
5498 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5499 (let* ((visp (not (org-invisible-p)))
5500 (txt (or tree (and kill-ring (current-kill 0))))
5501 (^re (concat "^\\(" outline-regexp "\\)"))
5502 (re (concat "\\(" outline-regexp "\\)"))
5503 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5504
5505 (old-level (if (string-match ^re txt)
5506 (- (match-end 0) (match-beginning 0) 1)
5507 -1))
5508 (force-level (cond (level (prefix-numeric-value level))
5509 ((and (looking-at "[ \t]*$")
5510 (string-match
5511 ^re_ (buffer-substring
5512 (point-at-bol) (point))))
5513 (- (match-end 1) (match-beginning 1)))
5514 ((and (bolp)
5515 (looking-at org-outline-regexp))
5516 (- (match-end 0) (point) 1))
5517 (t nil)))
5518 (previous-level (save-excursion
5519 (condition-case nil
5520 (progn
5521 (outline-previous-visible-heading 1)
5522 (if (looking-at re)
5523 (- (match-end 0) (match-beginning 0) 1)
5524 1))
5525 (error 1))))
5526 (next-level (save-excursion
5527 (condition-case nil
5528 (progn
5529 (or (looking-at outline-regexp)
5530 (outline-next-visible-heading 1))
5531 (if (looking-at re)
5532 (- (match-end 0) (match-beginning 0) 1)
5533 1))
5534 (error 1))))
5535 (new-level (or force-level (max previous-level next-level)))
5536 (shift (if (or (= old-level -1)
5537 (= new-level -1)
5538 (= old-level new-level))
5539 0
5540 (- new-level old-level)))
5541 (delta (if (> shift 0) -1 1))
5542 (func (if (> shift 0) 'org-demote 'org-promote))
5543 (org-odd-levels-only nil)
5544 beg end newend)
5545 ;; Remove the forced level indicator
5546 (if force-level
5547 (delete-region (point-at-bol) (point)))
5548 ;; Paste
5549 (beginning-of-line 1)
5550 (unless for-yank (org-back-over-empty-lines))
5551 (setq beg (point))
5552 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5553 (insert-before-markers txt)
5554 (unless (string-match "\n\\'" txt) (insert "\n"))
5555 (setq newend (point))
5556 (org-reinstall-markers-in-region beg)
5557 (setq end (point))
5558 (goto-char beg)
5559 (skip-chars-forward " \t\n\r")
5560 (setq beg (point))
5561 (if (and (org-invisible-p) visp)
5562 (save-excursion (outline-show-heading)))
5563 ;; Shift if necessary
5564 (unless (= shift 0)
5565 (save-restriction
5566 (narrow-to-region beg end)
5567 (while (not (= shift 0))
5568 (org-map-region func (point-min) (point-max))
5569 (setq shift (+ delta shift)))
5570 (goto-char (point-min))
5571 (setq newend (point-max))))
5572 (when (or (interactive-p) for-yank)
5573 (message "Clipboard pasted as level %d subtree" new-level))
5574 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5575 kill-ring
5576 (eq org-subtree-clip (current-kill 0))
5577 org-subtree-clip-folded)
5578 ;; The tree was folded before it was killed/copied
5579 (hide-subtree))
5580 (and for-yank (goto-char newend))))
5581
5582 (defun org-kill-is-subtree-p (&optional txt)
5583 "Check if the current kill is an outline subtree, or a set of trees.
5584 Returns nil if kill does not start with a headline, or if the first
5585 headline level is not the largest headline level in the tree.
5586 So this will actually accept several entries of equal levels as well,
5587 which is OK for `org-paste-subtree'.
5588 If optional TXT is given, check this string instead of the current kill."
5589 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5590 (start-level (and kill
5591 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5592 org-outline-regexp "\\)")
5593 kill)
5594 (- (match-end 2) (match-beginning 2) 1)))
5595 (re (concat "^" org-outline-regexp))
5596 (start (1+ (or (match-beginning 2) -1))))
5597 (if (not start-level)
5598 (progn
5599 nil) ;; does not even start with a heading
5600 (catch 'exit
5601 (while (setq start (string-match re kill (1+ start)))
5602 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5603 (throw 'exit nil)))
5604 t))))
5605
5606 (defvar org-markers-to-move nil
5607 "Markers that should be moved with a cut-and-paste operation.
5608 Those markers are stored together with their positions relative to
5609 the start of the region.")
5610
5611 (defun org-save-markers-in-region (beg end)
5612 "Check markers in region.
5613 If these markers are between BEG and END, record their position relative
5614 to BEG, so that after moving the block of text, we can put the markers back
5615 into place.
5616 This function gets called just before an entry or tree gets cut from the
5617 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5618 called immediately, to move the markers with the entries."
5619 (setq org-markers-to-move nil)
5620 (when (featurep 'org-clock)
5621 (org-clock-save-markers-for-cut-and-paste beg end))
5622 (when (featurep 'org-agenda)
5623 (org-agenda-save-markers-for-cut-and-paste beg end)))
5624
5625 (defun org-check-and-save-marker (marker beg end)
5626 "Check if MARKER is between BEG and END.
5627 If yes, remember the marker and the distance to BEG."
5628 (when (and (marker-buffer marker)
5629 (equal (marker-buffer marker) (current-buffer)))
5630 (if (and (>= marker beg) (< marker end))
5631 (push (cons marker (- marker beg)) org-markers-to-move))))
5632
5633 (defun org-reinstall-markers-in-region (beg)
5634 "Move all remembered markers to their position relative to BEG."
5635 (mapc (lambda (x)
5636 (move-marker (car x) (+ beg (cdr x))))
5637 org-markers-to-move)
5638 (setq org-markers-to-move nil))
5639
5640 (defun org-narrow-to-subtree ()
5641 "Narrow buffer to the current subtree."
5642 (interactive)
5643 (save-excursion
5644 (save-match-data
5645 (narrow-to-region
5646 (progn (org-back-to-heading) (point))
5647 (progn (org-end-of-subtree t) (point))))))
5648
5649
5650 ;;; Outline Sorting
5651
5652 (defun org-sort (with-case)
5653 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5654 Optional argument WITH-CASE means sort case-sensitively."
5655 (interactive "P")
5656 (if (org-at-table-p)
5657 (org-call-with-arg 'org-table-sort-lines with-case)
5658 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5659
5660 (defun org-sort-remove-invisible (s)
5661 (remove-text-properties 0 (length s) org-rm-props s)
5662 (while (string-match org-bracket-link-regexp s)
5663 (setq s (replace-match (if (match-end 2)
5664 (match-string 3 s)
5665 (match-string 1 s)) t t s)))
5666 s)
5667
5668 (defvar org-priority-regexp) ; defined later in the file
5669
5670 (defun org-sort-entries-or-items
5671 (&optional with-case sorting-type getkey-func compare-func property)
5672 "Sort entries on a certain level of an outline tree.
5673 If there is an active region, the entries in the region are sorted.
5674 Else, if the cursor is before the first entry, sort the top-level items.
5675 Else, the children of the entry at point are sorted.
5676
5677 Sorting can be alphabetically, numerically, and by date/time as given by
5678 the first time stamp in the entry. The command prompts for the sorting
5679 type unless it has been given to the function through the SORTING-TYPE
5680 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5681 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5682 called with point at the beginning of the record. It must return either
5683 a string or a number that should serve as the sorting key for that record.
5684
5685 Comparing entries ignores case by default. However, with an optional argument
5686 WITH-CASE, the sorting considers case as well."
5687 (interactive "P")
5688 (let ((case-func (if with-case 'identity 'downcase))
5689 start beg end stars re re2
5690 txt what tmp plain-list-p)
5691 ;; Find beginning and end of region to sort
5692 (cond
5693 ((org-region-active-p)
5694 ;; we will sort the region
5695 (setq end (region-end)
5696 what "region")
5697 (goto-char (region-beginning))
5698 (if (not (org-on-heading-p)) (outline-next-heading))
5699 (setq start (point)))
5700 ((org-at-item-p)
5701 ;; we will sort this plain list
5702 (org-beginning-of-item-list) (setq start (point))
5703 (org-end-of-item-list) (setq end (point))
5704 (goto-char start)
5705 (setq plain-list-p t
5706 what "plain list"))
5707 ((or (org-on-heading-p)
5708 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5709 ;; we will sort the children of the current headline
5710 (org-back-to-heading)
5711 (setq start (point)
5712 end (progn (org-end-of-subtree t t)
5713 (org-back-over-empty-lines)
5714 (point))
5715 what "children")
5716 (goto-char start)
5717 (show-subtree)
5718 (outline-next-heading))
5719 (t
5720 ;; we will sort the top-level entries in this file
5721 (goto-char (point-min))
5722 (or (org-on-heading-p) (outline-next-heading))
5723 (setq start (point) end (point-max) what "top-level")
5724 (goto-char start)
5725 (show-all)))
5726
5727 (setq beg (point))
5728 (if (>= beg end) (error "Nothing to sort"))
5729
5730 (unless plain-list-p
5731 (looking-at "\\(\\*+\\)")
5732 (setq stars (match-string 1)
5733 re (concat "^" (regexp-quote stars) " +")
5734 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5735 txt (buffer-substring beg end))
5736 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5737 (if (and (not (equal stars "*")) (string-match re2 txt))
5738 (error "Region to sort contains a level above the first entry")))
5739
5740 (unless sorting-type
5741 (message
5742 (if plain-list-p
5743 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5744 "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:")
5745 what)
5746 (setq sorting-type (read-char-exclusive))
5747
5748 (and (= (downcase sorting-type) ?f)
5749 (setq getkey-func
5750 (org-ido-completing-read "Sort using function: "
5751 obarray 'fboundp t nil nil))
5752 (setq getkey-func (intern getkey-func)))
5753
5754 (and (= (downcase sorting-type) ?r)
5755 (setq property
5756 (org-ido-completing-read "Property: "
5757 (mapcar 'list (org-buffer-property-keys t))
5758 nil t))))
5759
5760 (message "Sorting entries...")
5761
5762 (save-restriction
5763 (narrow-to-region start end)
5764
5765 (let ((dcst (downcase sorting-type))
5766 (now (current-time)))
5767 (sort-subr
5768 (/= dcst sorting-type)
5769 ;; This function moves to the beginning character of the "record" to
5770 ;; be sorted.
5771 (if plain-list-p
5772 (lambda nil
5773 (if (org-at-item-p) t (goto-char (point-max))))
5774 (lambda nil
5775 (if (re-search-forward re nil t)
5776 (goto-char (match-beginning 0))
5777 (goto-char (point-max)))))
5778 ;; This function moves to the last character of the "record" being
5779 ;; sorted.
5780 (if plain-list-p
5781 'org-end-of-item
5782 (lambda nil
5783 (save-match-data
5784 (condition-case nil
5785 (outline-forward-same-level 1)
5786 (error
5787 (goto-char (point-max)))))))
5788
5789 ;; This function returns the value that gets sorted against.
5790 (if plain-list-p
5791 (lambda nil
5792 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5793 (cond
5794 ((= dcst ?n)
5795 (string-to-number (buffer-substring (match-end 0)
5796 (point-at-eol))))
5797 ((= dcst ?a)
5798 (buffer-substring (match-end 0) (point-at-eol)))
5799 ((= dcst ?t)
5800 (if (re-search-forward org-ts-regexp
5801 (point-at-eol) t)
5802 (org-time-string-to-time (match-string 0))
5803 now))
5804 ((= dcst ?f)
5805 (if getkey-func
5806 (progn
5807 (setq tmp (funcall getkey-func))
5808 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5809 tmp)
5810 (error "Invalid key function `%s'" getkey-func)))
5811 (t (error "Invalid sorting type `%c'" sorting-type)))))
5812 (lambda nil
5813 (cond
5814 ((= dcst ?n)
5815 (if (looking-at org-complex-heading-regexp)
5816 (string-to-number (match-string 4))
5817 nil))
5818 ((= dcst ?a)
5819 (if (looking-at org-complex-heading-regexp)
5820 (funcall case-func (match-string 4))
5821 nil))
5822 ((= dcst ?t)
5823 (if (re-search-forward org-ts-regexp
5824 (save-excursion
5825 (forward-line 2)
5826 (point)) t)
5827 (org-time-string-to-time (match-string 0))
5828 now))
5829 ((= dcst ?p)
5830 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5831 (string-to-char (match-string 2))
5832 org-default-priority))
5833 ((= dcst ?r)
5834 (or (org-entry-get nil property) ""))
5835 ((= dcst ?o)
5836 (if (looking-at org-complex-heading-regexp)
5837 (- 9999 (length (member (match-string 2)
5838 org-todo-keywords-1)))))
5839 ((= dcst ?f)
5840 (if getkey-func
5841 (progn
5842 (setq tmp (funcall getkey-func))
5843 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5844 tmp)
5845 (error "Invalid key function `%s'" getkey-func)))
5846 (t (error "Invalid sorting type `%c'" sorting-type)))))
5847 nil
5848 (cond
5849 ((= dcst ?a) 'string<)
5850 ((= dcst ?t) 'time-less-p)
5851 ((= dcst ?f) compare-func)
5852 (t nil)))))
5853 (message "Sorting entries...done")))
5854
5855 (defun org-do-sort (table what &optional with-case sorting-type)
5856 "Sort TABLE of WHAT according to SORTING-TYPE.
5857 The user will be prompted for the SORTING-TYPE if the call to this
5858 function does not specify it. WHAT is only for the prompt, to indicate
5859 what is being sorted. The sorting key will be extracted from
5860 the car of the elements of the table.
5861 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5862 (unless sorting-type
5863 (message
5864 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5865 what)
5866 (setq sorting-type (read-char-exclusive)))
5867 (let ((dcst (downcase sorting-type))
5868 extractfun comparefun)
5869 ;; Define the appropriate functions
5870 (cond
5871 ((= dcst ?n)
5872 (setq extractfun 'string-to-number
5873 comparefun (if (= dcst sorting-type) '< '>)))
5874 ((= dcst ?a)
5875 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5876 (lambda(x) (downcase (org-sort-remove-invisible x))))
5877 comparefun (if (= dcst sorting-type)
5878 'string<
5879 (lambda (a b) (and (not (string< a b))
5880 (not (string= a b)))))))
5881 ((= dcst ?t)
5882 (setq extractfun
5883 (lambda (x)
5884 (if (string-match org-ts-regexp x)
5885 (time-to-seconds
5886 (org-time-string-to-time (match-string 0 x)))
5887 0))
5888 comparefun (if (= dcst sorting-type) '< '>)))
5889 (t (error "Invalid sorting type `%c'" sorting-type)))
5890
5891 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5892 table)
5893 (lambda (a b) (funcall comparefun (car a) (car b))))))
5894
5895 ;;; Editing source examples
5896
5897 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5898 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5899 (defvar org-edit-src-force-single-line nil)
5900 (defvar org-edit-src-from-org-mode nil)
5901 (defvar org-edit-src-picture nil)
5902
5903 (define-minor-mode org-exit-edit-mode
5904 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5905
5906 (defun org-edit-src-code ()
5907 "Edit the source code example at point.
5908 An indirect buffer is created, and that buffer is then narrowed to the
5909 example at point and switched to the correct language mode. When done,
5910 exit by killing the buffer with \\[org-edit-src-exit]."
5911 (interactive)
5912 (let ((line (org-current-line))
5913 (case-fold-search t)
5914 (msg (substitute-command-keys
5915 "Edit, then exit with C-c ' (C-c and single quote)"))
5916 (info (org-edit-src-find-region-and-lang))
5917 (org-mode-p (eq major-mode 'org-mode))
5918 beg end lang lang-f single lfmt)
5919 (if (not info)
5920 nil
5921 (setq beg (nth 0 info)
5922 end (nth 1 info)
5923 lang (nth 2 info)
5924 single (nth 3 info)
5925 lfmt (nth 4 info)
5926 lang-f (intern (concat lang "-mode")))
5927 (unless (functionp lang-f)
5928 (error "No such language mode: %s" lang-f))
5929 (goto-line line)
5930 (if (get-buffer "*Org Edit Src Example*")
5931 (kill-buffer "*Org Edit Src Example*"))
5932 (switch-to-buffer (make-indirect-buffer (current-buffer)
5933 "*Org Edit Src Example*"))
5934 (narrow-to-region beg end)
5935 (remove-text-properties beg end '(display nil invisible nil
5936 intangible nil))
5937 (let ((org-inhibit-startup t))
5938 (funcall lang-f))
5939 (set (make-local-variable 'org-edit-src-force-single-line) single)
5940 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5941 (when lfmt
5942 (set (make-local-variable 'org-coderef-label-format) lfmt))
5943 (when org-mode-p
5944 (goto-char (point-min))
5945 (while (re-search-forward "^," nil t)
5946 (replace-match "")))
5947 (goto-line line)
5948 (org-exit-edit-mode)
5949 (org-set-local 'header-line-format msg)
5950 (message "%s" msg)
5951 t)))
5952
5953 (defun org-edit-fixed-width-region ()
5954 "Edit the fixed-width ascii drawing at point.
5955 This must be a region where each line starts with a colon followed by
5956 a space character.
5957 An indirect buffer is created, and that buffer is then narrowed to the
5958 example at point and switched to artist-mode. When done,
5959 exit by killing the buffer with \\[org-edit-src-exit]."
5960 (interactive)
5961 (let ((line (org-current-line))
5962 (case-fold-search t)
5963 (msg (substitute-command-keys
5964 "Edit, then exit with C-c ' (C-c and single quote)"))
5965 (org-mode-p (eq major-mode 'org-mode))
5966 beg end)
5967 (beginning-of-line 1)
5968 (if (looking-at "[ \t]*[^:\n \t]")
5969 nil
5970 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5971 (setq beg (point) end beg)
5972 (save-excursion
5973 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5974 (setq beg (point-at-bol 2))
5975 (setq beg (point))))
5976 (save-excursion
5977 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5978 (setq end (1- (match-beginning 0)))
5979 (setq end (point))))
5980 (goto-line line))
5981 (if (get-buffer "*Org Edit Picture*")
5982 (kill-buffer "*Org Edit Picture*"))
5983 (switch-to-buffer (make-indirect-buffer (current-buffer)
5984 "*Org Edit Picture*"))
5985 (narrow-to-region beg end)
5986 (remove-text-properties beg end '(display nil invisible nil
5987 intangible nil))
5988 (when (fboundp 'font-lock-unfontify-region)
5989 (font-lock-unfontify-region (point-min) (point-max)))
5990 (cond
5991 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5992 (fundamental-mode)
5993 (artist-mode 1))
5994 (t (funcall org-edit-fixed-width-region-mode)))
5995 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5996 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5997 (set (make-local-variable 'org-edit-src-picture) t)
5998 (goto-char (point-min))
5999 (while (re-search-forward "^[ \t]*: ?" nil t)
6000 (replace-match ""))
6001 (goto-line line)
6002 (org-exit-edit-mode)
6003 (org-set-local 'header-line-format msg)
6004 (message "%s" msg)
6005 t)))
6006
6007
6008 (defun org-edit-src-find-region-and-lang ()
6009 "Find the region and language for a local edit.
6010 Return a list with beginning and end of the region, a string representing
6011 the language, a switch telling of the content should be in a single line."
6012 (let ((re-list
6013 (append
6014 org-edit-src-region-extra
6015 '(
6016 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6017 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6018 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6019 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6020 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6021 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6022 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6023 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6024 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6025 ("^#\\+html:" "\n" "html" single-line)
6026 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6027 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6028 ("^#\\+latex:" "\n" "latex" single-line)
6029 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6030 ("^#\\+ascii:" "\n" "ascii" single-line)
6031 )))
6032 (pos (point))
6033 re1 re2 single beg end lang lfmt match-re1)
6034 (catch 'exit
6035 (while (setq entry (pop re-list))
6036 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6037 single (nth 3 entry))
6038 (save-excursion
6039 (if (or (looking-at re1)
6040 (re-search-backward re1 nil t))
6041 (progn
6042 (setq match-re1 (match-string 0))
6043 (setq beg (match-end 0)
6044 lang (org-edit-src-get-lang lang)
6045 lfmt (org-edit-src-get-label-format match-re1))
6046 (if (and (re-search-forward re2 nil t)
6047 (>= (match-end 0) pos))
6048 (throw 'exit (list beg (match-beginning 0)
6049 lang single lfmt))))
6050 (if (or (looking-at re2)
6051 (re-search-forward re2 nil t))
6052 (progn
6053 (setq end (match-beginning 0))
6054 (if (and (re-search-backward re1 nil t)
6055 (<= (match-beginning 0) pos))
6056 (progn
6057 (setq lfmt (org-edit-src-get-label-format
6058 (match-string 0)))
6059 (throw 'exit
6060 (list (match-end 0) end
6061 (org-edit-src-get-lang lang)
6062 single lfmt))))))))))))
6063
6064 (defun org-edit-src-get-lang (lang)
6065 "Extract the src language."
6066 (let ((m (match-string 0)))
6067 (cond
6068 ((stringp lang) lang)
6069 ((integerp lang) (match-string lang))
6070 ((and (eq lang 'lang)
6071 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6072 (match-string 1 m))
6073 ((and (eq lang 'style)
6074 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6075 (match-string 1 m))
6076 (t "fundamental"))))
6077
6078 (defun org-edit-src-get-label-format (s)
6079 "Extract the label format."
6080 (save-match-data
6081 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6082 (match-string 1 s))))
6083
6084 (defun org-edit-src-exit ()
6085 "Exit special edit and protect problematic lines."
6086 (interactive)
6087 (unless (buffer-base-buffer (current-buffer))
6088 (error "This is not an indirect buffer, something is wrong..."))
6089 (unless (> (point-min) 1)
6090 (error "This buffer is not narrowed, something is wrong..."))
6091 (goto-char (point-min))
6092 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6093 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6094 (when (org-bound-and-true-p org-edit-src-force-single-line)
6095 (goto-char (point-min))
6096 (while (re-search-forward "\n" nil t)
6097 (replace-match " "))
6098 (goto-char (point-min))
6099 (if (looking-at "\\s-*") (replace-match " "))
6100 (if (re-search-forward "\\s-+\\'" nil t)
6101 (replace-match "")))
6102 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6103 (goto-char (point-min))
6104 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6105 (replace-match ",\\1"))
6106 (when font-lock-mode
6107 (font-lock-unfontify-region (point-min) (point-max)))
6108 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6109 (when (org-bound-and-true-p org-edit-src-picture)
6110 (untabify (point-min) (point-max))
6111 (goto-char (point-min))
6112 (while (re-search-forward "^" nil t)
6113 (replace-match ": "))
6114 (when font-lock-mode
6115 (font-lock-unfontify-region (point-min) (point-max)))
6116 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6117 (kill-buffer (current-buffer))
6118 (and (org-mode-p) (org-restart-font-lock)))
6119
6120
6121 ;;; The orgstruct minor mode
6122
6123 ;; Define a minor mode which can be used in other modes in order to
6124 ;; integrate the org-mode structure editing commands.
6125
6126 ;; This is really a hack, because the org-mode structure commands use
6127 ;; keys which normally belong to the major mode. Here is how it
6128 ;; works: The minor mode defines all the keys necessary to operate the
6129 ;; structure commands, but wraps the commands into a function which
6130 ;; tests if the cursor is currently at a headline or a plain list
6131 ;; item. If that is the case, the structure command is used,
6132 ;; temporarily setting many Org-mode variables like regular
6133 ;; expressions for filling etc. However, when any of those keys is
6134 ;; used at a different location, function uses `key-binding' to look
6135 ;; up if the key has an associated command in another currently active
6136 ;; keymap (minor modes, major mode, global), and executes that
6137 ;; command. There might be problems if any of the keys is otherwise
6138 ;; used as a prefix key.
6139
6140 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6141 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6142 ;; addresses this by checking explicitly for both bindings.
6143
6144 (defvar orgstruct-mode-map (make-sparse-keymap)
6145 "Keymap for the minor `orgstruct-mode'.")
6146
6147 (defvar org-local-vars nil
6148 "List of local variables, for use by `orgstruct-mode'")
6149
6150 ;;;###autoload
6151 (define-minor-mode orgstruct-mode
6152 "Toggle the minor more `orgstruct-mode'.
6153 This mode is for using Org-mode structure commands in other modes.
6154 The following key behave as if Org-mode was active, if the cursor
6155 is on a headline, or on a plain list item (both in the definition
6156 of Org-mode).
6157
6158 M-up Move entry/item up
6159 M-down Move entry/item down
6160 M-left Promote
6161 M-right Demote
6162 M-S-up Move entry/item up
6163 M-S-down Move entry/item down
6164 M-S-left Promote subtree
6165 M-S-right Demote subtree
6166 M-q Fill paragraph and items like in Org-mode
6167 C-c ^ Sort entries
6168 C-c - Cycle list bullet
6169 TAB Cycle item visibility
6170 M-RET Insert new heading/item
6171 S-M-RET Insert new TODO heading / Checkbox item
6172 C-c C-c Set tags / toggle checkbox"
6173 nil " OrgStruct" nil
6174 (org-load-modules-maybe)
6175 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6176
6177 ;;;###autoload
6178 (defun turn-on-orgstruct ()
6179 "Unconditionally turn on `orgstruct-mode'."
6180 (orgstruct-mode 1))
6181
6182 ;;;###autoload
6183 (defun turn-on-orgstruct++ ()
6184 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6185 In addition to setting orgstruct-mode, this also exports all indentation and
6186 autofilling variables from org-mode into the buffer. Note that turning
6187 off orgstruct-mode will *not* remove these additional settings."
6188 (orgstruct-mode 1)
6189 (let (var val)
6190 (mapc
6191 (lambda (x)
6192 (when (string-match
6193 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6194 (symbol-name (car x)))
6195 (setq var (car x) val (nth 1 x))
6196 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6197 org-local-vars)))
6198
6199 (defun orgstruct-error ()
6200 "Error when there is no default binding for a structure key."
6201 (interactive)
6202 (error "This key has no function outside structure elements"))
6203
6204 (defun orgstruct-setup ()
6205 "Setup orgstruct keymaps."
6206 (let ((nfunc 0)
6207 (bindings
6208 (list
6209 '([(meta up)] org-metaup)
6210 '([(meta down)] org-metadown)
6211 '([(meta left)] org-metaleft)
6212 '([(meta right)] org-metaright)
6213 '([(meta shift up)] org-shiftmetaup)
6214 '([(meta shift down)] org-shiftmetadown)
6215 '([(meta shift left)] org-shiftmetaleft)
6216 '([(meta shift right)] org-shiftmetaright)
6217 '([(shift up)] org-shiftup)
6218 '([(shift down)] org-shiftdown)
6219 '([(shift left)] org-shiftleft)
6220 '([(shift right)] org-shiftright)
6221 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6222 '("\M-q" fill-paragraph)
6223 '("\C-c^" org-sort)
6224 '("\C-c-" org-cycle-list-bullet)))
6225 elt key fun cmd)
6226 (while (setq elt (pop bindings))
6227 (setq nfunc (1+ nfunc))
6228 (setq key (org-key (car elt))
6229 fun (nth 1 elt)
6230 cmd (orgstruct-make-binding fun nfunc key))
6231 (org-defkey orgstruct-mode-map key cmd))
6232
6233 ;; Special treatment needed for TAB and RET
6234 (org-defkey orgstruct-mode-map [(tab)]
6235 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6236 (org-defkey orgstruct-mode-map "\C-i"
6237 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6238
6239 (org-defkey orgstruct-mode-map "\M-\C-m"
6240 (orgstruct-make-binding 'org-insert-heading 105
6241 "\M-\C-m" [(meta return)]))
6242 (org-defkey orgstruct-mode-map [(meta return)]
6243 (orgstruct-make-binding 'org-insert-heading 106
6244 [(meta return)] "\M-\C-m"))
6245
6246 (org-defkey orgstruct-mode-map [(shift meta return)]
6247 (orgstruct-make-binding 'org-insert-todo-heading 107
6248 [(meta return)] "\M-\C-m"))
6249
6250 (unless org-local-vars
6251 (setq org-local-vars (org-get-local-variables)))
6252
6253 t))
6254
6255 (defun orgstruct-make-binding (fun n &rest keys)
6256 "Create a function for binding in the structure minor mode.
6257 FUN is the command to call inside a table. N is used to create a unique
6258 command name. KEYS are keys that should be checked in for a command
6259 to execute outside of tables."
6260 (eval
6261 (list 'defun
6262 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6263 '(arg)
6264 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6265 "Outside of structure, run the binding of `"
6266 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6267 "'.")
6268 '(interactive "p")
6269 (list 'if
6270 '(org-context-p 'headline 'item)
6271 (list 'org-run-like-in-org-mode (list 'quote fun))
6272 (list 'let '(orgstruct-mode)
6273 (list 'call-interactively
6274 (append '(or)
6275 (mapcar (lambda (k)
6276 (list 'key-binding k))
6277 keys)
6278 '('orgstruct-error))))))))
6279
6280 (defun org-context-p (&rest contexts)
6281 "Check if local context is any of CONTEXTS.
6282 Possible values in the list of contexts are `table', `headline', and `item'."
6283 (let ((pos (point)))
6284 (goto-char (point-at-bol))
6285 (prog1 (or (and (memq 'table contexts)
6286 (looking-at "[ \t]*|"))
6287 (and (memq 'headline contexts)
6288 ;;????????? (looking-at "\\*+"))
6289 (looking-at outline-regexp))
6290 (and (memq 'item contexts)
6291 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6292 (goto-char pos))))
6293
6294 (defun org-get-local-variables ()
6295 "Return a list of all local variables in an org-mode buffer."
6296 (let (varlist)
6297 (with-current-buffer (get-buffer-create "*Org tmp*")
6298 (erase-buffer)
6299 (org-mode)
6300 (setq varlist (buffer-local-variables)))
6301 (kill-buffer "*Org tmp*")
6302 (delq nil
6303 (mapcar
6304 (lambda (x)
6305 (setq x
6306 (if (symbolp x)
6307 (list x)
6308 (list (car x) (list 'quote (cdr x)))))
6309 (if (string-match
6310 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6311 (symbol-name (car x)))
6312 x nil))
6313 varlist))))
6314
6315 ;;;###autoload
6316 (defun org-run-like-in-org-mode (cmd)
6317 (org-load-modules-maybe)
6318 (unless org-local-vars
6319 (setq org-local-vars (org-get-local-variables)))
6320 (eval (list 'let org-local-vars
6321 (list 'call-interactively (list 'quote cmd)))))
6322
6323 ;;;; Archiving
6324
6325 (defun org-get-category (&optional pos)
6326 "Get the category applying to position POS."
6327 (get-text-property (or pos (point)) 'org-category))
6328
6329 (defun org-refresh-category-properties ()
6330 "Refresh category text properties in the buffer."
6331 (let ((def-cat (cond
6332 ((null org-category)
6333 (if buffer-file-name
6334 (file-name-sans-extension
6335 (file-name-nondirectory buffer-file-name))
6336 "???"))
6337 ((symbolp org-category) (symbol-name org-category))
6338 (t org-category)))
6339 beg end cat pos optionp)
6340 (org-unmodified
6341 (save-excursion
6342 (save-restriction
6343 (widen)
6344 (goto-char (point-min))
6345 (put-text-property (point) (point-max) 'org-category def-cat)
6346 (while (re-search-forward
6347 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6348 (setq pos (match-end 0)
6349 optionp (equal (char-after (match-beginning 0)) ?#)
6350 cat (org-trim (match-string 2)))
6351 (if optionp
6352 (setq beg (point-at-bol) end (point-max))
6353 (org-back-to-heading t)
6354 (setq beg (point) end (org-end-of-subtree t t)))
6355 (put-text-property beg end 'org-category cat)
6356 (goto-char pos)))))))
6357
6358
6359 ;;;; Link Stuff
6360
6361 ;;; Link abbreviations
6362
6363 (defun org-link-expand-abbrev (link)
6364 "Apply replacements as defined in `org-link-abbrev-alist."
6365 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6366 (let* ((key (match-string 1 link))
6367 (as (or (assoc key org-link-abbrev-alist-local)
6368 (assoc key org-link-abbrev-alist)))
6369 (tag (and (match-end 2) (match-string 3 link)))
6370 rpl)
6371 (if (not as)
6372 link
6373 (setq rpl (cdr as))
6374 (cond
6375 ((symbolp rpl) (funcall rpl tag))
6376 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6377 ((string-match "%h" rpl)
6378 (replace-match (url-hexify-string (or tag "")) t t rpl))
6379 (t (concat rpl tag)))))
6380 link))
6381
6382 ;;; Storing and inserting links
6383
6384 (defvar org-insert-link-history nil
6385 "Minibuffer history for links inserted with `org-insert-link'.")
6386
6387 (defvar org-stored-links nil
6388 "Contains the links stored with `org-store-link'.")
6389
6390 (defvar org-store-link-plist nil
6391 "Plist with info about the most recently link created with `org-store-link'.")
6392
6393 (defvar org-link-protocols nil
6394 "Link protocols added to Org-mode using `org-add-link-type'.")
6395
6396 (defvar org-store-link-functions nil
6397 "List of functions that are called to create and store a link.
6398 Each function will be called in turn until one returns a non-nil
6399 value. Each function should check if it is responsible for creating
6400 this link (for example by looking at the major mode).
6401 If not, it must exit and return nil.
6402 If yes, it should return a non-nil value after a calling
6403 `org-store-link-props' with a list of properties and values.
6404 Special properties are:
6405
6406 :type The link prefix. like \"http\". This must be given.
6407 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6408 This is obligatory as well.
6409 :description Optional default description for the second pair
6410 of brackets in an Org-mode link. The user can still change
6411 this when inserting this link into an Org-mode buffer.
6412
6413 In addition to these, any additional properties can be specified
6414 and then used in remember templates.")
6415
6416 (defun org-add-link-type (type &optional follow export)
6417 "Add TYPE to the list of `org-link-types'.
6418 Re-compute all regular expressions depending on `org-link-types'
6419
6420 FOLLOW and EXPORT are two functions.
6421
6422 FOLLOW should take the link path as the single argument and do whatever
6423 is necessary to follow the link, for example find a file or display
6424 a mail message.
6425
6426 EXPORT should format the link path for export to one of the export formats.
6427 It should be a function accepting three arguments:
6428
6429 path the path of the link, the text after the prefix (like \"http:\")
6430 desc the description of the link, if any, nil if there was no description
6431 format the export format, a symbol like `html' or `latex'.
6432
6433 The function may use the FORMAT information to return different values
6434 depending on the format. The return value will be put literally into
6435 the exported file.
6436 Org-mode has a built-in default for exporting links. If you are happy with
6437 this default, there is no need to define an export function for the link
6438 type. For a simple example of an export function, see `org-bbdb.el'."
6439 (add-to-list 'org-link-types type t)
6440 (org-make-link-regexps)
6441 (if (assoc type org-link-protocols)
6442 (setcdr (assoc type org-link-protocols) (list follow export))
6443 (push (list type follow export) org-link-protocols)))
6444
6445 ;;;###autoload
6446 (defun org-store-link (arg)
6447 "\\<org-mode-map>Store an org-link to the current location.
6448 This link is added to `org-stored-links' and can later be inserted
6449 into an org-buffer with \\[org-insert-link].
6450
6451 For some link types, a prefix arg is interpreted:
6452 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6453 For file links, arg negates `org-context-in-file-links'."
6454 (interactive "P")
6455 (org-load-modules-maybe)
6456 (setq org-store-link-plist nil) ; reset
6457 (let (link cpltxt desc description search txt)
6458 (cond
6459
6460 ((run-hook-with-args-until-success 'org-store-link-functions)
6461 (setq link (plist-get org-store-link-plist :link)
6462 desc (or (plist-get org-store-link-plist :description) link)))
6463
6464 ((equal (buffer-name) "*Org Edit Src Example*")
6465 (let (label gc)
6466 (while (or (not label)
6467 (save-excursion
6468 (save-restriction
6469 (widen)
6470 (goto-char (point-min))
6471 (re-search-forward
6472 (regexp-quote (format org-coderef-label-format label))
6473 nil t))))
6474 (when label (message "Label exists already") (sit-for 2))
6475 (setq label (read-string "Code line label: " label)))
6476 (end-of-line 1)
6477 (setq link (format org-coderef-label-format label))
6478 (setq gc (- 79 (length link)))
6479 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6480 (insert link)
6481 (setq link (concat "(" label ")") desc nil)))
6482
6483 ((eq major-mode 'calendar-mode)
6484 (let ((cd (calendar-cursor-to-date)))
6485 (setq link
6486 (format-time-string
6487 (car org-time-stamp-formats)
6488 (apply 'encode-time
6489 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6490 nil nil nil))))
6491 (org-store-link-props :type "calendar" :date cd)))
6492
6493 ((eq major-mode 'w3-mode)
6494 (setq cpltxt (url-view-url t)
6495 link (org-make-link cpltxt))
6496 (org-store-link-props :type "w3" :url (url-view-url t)))
6497
6498 ((eq major-mode 'w3m-mode)
6499 (setq cpltxt (or w3m-current-title w3m-current-url)
6500 link (org-make-link w3m-current-url))
6501 (org-store-link-props :type "w3m" :url (url-view-url t)))
6502
6503 ((setq search (run-hook-with-args-until-success
6504 'org-create-file-search-functions))
6505 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6506 "::" search))
6507 (setq cpltxt (or description link)))
6508
6509 ((eq major-mode 'image-mode)
6510 (setq cpltxt (concat "file:"
6511 (abbreviate-file-name buffer-file-name))
6512 link (org-make-link cpltxt))
6513 (org-store-link-props :type "image" :file buffer-file-name))
6514
6515 ((eq major-mode 'dired-mode)
6516 ;; link to the file in the current line
6517 (setq cpltxt (concat "file:"
6518 (abbreviate-file-name
6519 (expand-file-name
6520 (dired-get-filename nil t))))
6521 link (org-make-link cpltxt)))
6522
6523 ((and buffer-file-name (org-mode-p))
6524 (cond
6525 ((org-in-regexp "<<\\(.*?\\)>>")
6526 (setq cpltxt
6527 (concat "file:"
6528 (abbreviate-file-name buffer-file-name)
6529 "::" (match-string 1))
6530 link (org-make-link cpltxt)))
6531 ((and (featurep 'org-id)
6532 (or (eq org-link-to-org-use-id t)
6533 (and (eq org-link-to-org-use-id 'create-if-interactive)
6534 (interactive-p))
6535 (and org-link-to-org-use-id
6536 (condition-case nil
6537 (org-entry-get nil "ID")
6538 (error nil)))))
6539 ;; We can make a link using the ID.
6540 (setq link (condition-case nil
6541 (prog1 (org-id-store-link)
6542 (setq desc (plist-get org-store-link-plist
6543 :description)))
6544 (error
6545 ;; probably before first headline, link to file only
6546 (concat "file:"
6547 (abbreviate-file-name buffer-file-name))))))
6548 (t
6549 ;; Just link to current headline
6550 (setq cpltxt (concat "file:"
6551 (abbreviate-file-name buffer-file-name)))
6552 ;; Add a context search string
6553 (when (org-xor org-context-in-file-links arg)
6554 (setq txt (cond
6555 ((org-on-heading-p) nil)
6556 ((org-region-active-p)
6557 (buffer-substring (region-beginning) (region-end)))
6558 (t nil)))
6559 (when (or (null txt) (string-match "\\S-" txt))
6560 (setq cpltxt
6561 (concat cpltxt "::"
6562 (condition-case nil
6563 (org-make-org-heading-search-string txt)
6564 (error "")))
6565 desc "NONE")))
6566 (if (string-match "::\\'" cpltxt)
6567 (setq cpltxt (substring cpltxt 0 -2)))
6568 (setq link (org-make-link cpltxt)))))
6569
6570 ((buffer-file-name (buffer-base-buffer))
6571 ;; Just link to this file here.
6572 (setq cpltxt (concat "file:"
6573 (abbreviate-file-name
6574 (buffer-file-name (buffer-base-buffer)))))
6575 ;; Add a context string
6576 (when (org-xor org-context-in-file-links arg)
6577 (setq txt (if (org-region-active-p)
6578 (buffer-substring (region-beginning) (region-end))
6579 (buffer-substring (point-at-bol) (point-at-eol))))
6580 ;; Only use search option if there is some text.
6581 (when (string-match "\\S-" txt)
6582 (setq cpltxt
6583 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6584 desc "NONE")))
6585 (setq link (org-make-link cpltxt)))
6586
6587 ((interactive-p)
6588 (error "Cannot link to a buffer which is not visiting a file"))
6589
6590 (t (setq link nil)))
6591
6592 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6593 (setq link (or link cpltxt)
6594 desc (or desc cpltxt))
6595 (if (equal desc "NONE") (setq desc nil))
6596
6597 (if (and (interactive-p) link)
6598 (progn
6599 (setq org-stored-links
6600 (cons (list link desc) org-stored-links))
6601 (message "Stored: %s" (or desc link)))
6602 (and link (org-make-link-string link desc)))))
6603
6604 (defun org-store-link-props (&rest plist)
6605 "Store link properties, extract names and addresses."
6606 (let (x adr)
6607 (when (setq x (plist-get plist :from))
6608 (setq adr (mail-extract-address-components x))
6609 (setq plist (plist-put plist :fromname (car adr)))
6610 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6611 (when (setq x (plist-get plist :to))
6612 (setq adr (mail-extract-address-components x))
6613 (setq plist (plist-put plist :toname (car adr)))
6614 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6615 (let ((from (plist-get plist :from))
6616 (to (plist-get plist :to)))
6617 (when (and from to org-from-is-user-regexp)
6618 (setq plist
6619 (plist-put plist :fromto
6620 (if (string-match org-from-is-user-regexp from)
6621 (concat "to %t")
6622 (concat "from %f"))))))
6623 (setq org-store-link-plist plist))
6624
6625 (defun org-add-link-props (&rest plist)
6626 "Add these properties to the link property list."
6627 (let (key value)
6628 (while plist
6629 (setq key (pop plist) value (pop plist))
6630 (setq org-store-link-plist
6631 (plist-put org-store-link-plist key value)))))
6632
6633 (defun org-email-link-description (&optional fmt)
6634 "Return the description part of an email link.
6635 This takes information from `org-store-link-plist' and formats it
6636 according to FMT (default from `org-email-link-description-format')."
6637 (setq fmt (or fmt org-email-link-description-format))
6638 (let* ((p org-store-link-plist)
6639 (to (plist-get p :toaddress))
6640 (from (plist-get p :fromaddress))
6641 (table
6642 (list
6643 (cons "%c" (plist-get p :fromto))
6644 (cons "%F" (plist-get p :from))
6645 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6646 (cons "%T" (plist-get p :to))
6647 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6648 (cons "%s" (plist-get p :subject))
6649 (cons "%m" (plist-get p :message-id)))))
6650 (when (string-match "%c" fmt)
6651 ;; Check if the user wrote this message
6652 (if (and org-from-is-user-regexp from to
6653 (save-match-data (string-match org-from-is-user-regexp from)))
6654 (setq fmt (replace-match "to %t" t t fmt))
6655 (setq fmt (replace-match "from %f" t t fmt))))
6656 (org-replace-escapes fmt table)))
6657
6658 (defun org-make-org-heading-search-string (&optional string heading)
6659 "Make search string for STRING or current headline."
6660 (interactive)
6661 (let ((s (or string (org-get-heading))))
6662 (unless (and string (not heading))
6663 ;; We are using a headline, clean up garbage in there.
6664 (if (string-match org-todo-regexp s)
6665 (setq s (replace-match "" t t s)))
6666 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6667 (setq s (replace-match "" t t s)))
6668 (setq s (org-trim s))
6669 (if (string-match (concat "^\\(" org-quote-string "\\|"
6670 org-comment-string "\\)") s)
6671 (setq s (replace-match "" t t s)))
6672 (while (string-match org-ts-regexp s)
6673 (setq s (replace-match "" t t s))))
6674 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6675 (setq s (replace-match " " t t s)))
6676 (or string (setq s (concat "*" s))) ; Add * for headlines
6677 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6678
6679 (defun org-make-link (&rest strings)
6680 "Concatenate STRINGS."
6681 (apply 'concat strings))
6682
6683 (defun org-make-link-string (link &optional description)
6684 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6685 (unless (string-match "\\S-" link)
6686 (error "Empty link"))
6687 (when (stringp description)
6688 ;; Remove brackets from the description, they are fatal.
6689 (while (string-match "\\[" description)
6690 (setq description (replace-match "{" t t description)))
6691 (while (string-match "\\]" description)
6692 (setq description (replace-match "}" t t description))))
6693 (when (equal (org-link-escape link) description)
6694 ;; No description needed, it is identical
6695 (setq description nil))
6696 (when (and (not description)
6697 (not (equal link (org-link-escape link))))
6698 (setq description (org-extract-attributes link)))
6699 (concat "[[" (org-link-escape link) "]"
6700 (if description (concat "[" description "]") "")
6701 "]"))
6702
6703 (defconst org-link-escape-chars
6704 '((?\ . "%20")
6705 (?\[ . "%5B")
6706 (?\] . "%5D")
6707 (?\340 . "%E0") ; `a
6708 (?\342 . "%E2") ; ^a
6709 (?\347 . "%E7") ; ,c
6710 (?\350 . "%E8") ; `e
6711 (?\351 . "%E9") ; 'e
6712 (?\352 . "%EA") ; ^e
6713 (?\356 . "%EE") ; ^i
6714 (?\364 . "%F4") ; ^o
6715 (?\371 . "%F9") ; `u
6716 (?\373 . "%FB") ; ^u
6717 (?\; . "%3B")
6718 (?? . "%3F")
6719 (?= . "%3D")
6720 (?+ . "%2B")
6721 )
6722 "Association list of escapes for some characters problematic in links.
6723 This is the list that is used for internal purposes.")
6724
6725 (defconst org-link-escape-chars-browser
6726 '((?\ . "%20")) ; 32 for the SPC char
6727 "Association list of escapes for some characters problematic in links.
6728 This is the list that is used before handing over to the browser.")
6729
6730 (defun org-link-escape (text &optional table)
6731 "Escape characters in TEXT that are problematic for links."
6732 (setq table (or table org-link-escape-chars))
6733 (when text
6734 (let ((re (mapconcat (lambda (x) (regexp-quote
6735 (char-to-string (car x))))
6736 table "\\|")))
6737 (while (string-match re text)
6738 (setq text
6739 (replace-match
6740 (cdr (assoc (string-to-char (match-string 0 text))
6741 table))
6742 t t text)))
6743 text)))
6744
6745 (defun org-link-unescape (text &optional table)
6746 "Reverse the action of `org-link-escape'."
6747 (setq table (or table org-link-escape-chars))
6748 (when text
6749 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6750 table "\\|")))
6751 (while (string-match re text)
6752 (setq text
6753 (replace-match
6754 (char-to-string (car (rassoc (match-string 0 text) table)))
6755 t t text)))
6756 text)))
6757
6758 (defun org-xor (a b)
6759 "Exclusive or."
6760 (if a (not b) b))
6761
6762 (defun org-fixup-message-id-for-http (s)
6763 "Replace special characters in a message id, so it can be used in an http query."
6764 (while (string-match "<" s)
6765 (setq s (replace-match "%3C" t t s)))
6766 (while (string-match ">" s)
6767 (setq s (replace-match "%3E" t t s)))
6768 (while (string-match "@" s)
6769 (setq s (replace-match "%40" t t s)))
6770 s)
6771
6772 ;;;###autoload
6773 (defun org-insert-link-global ()
6774 "Insert a link like Org-mode does.
6775 This command can be called in any mode to insert a link in Org-mode syntax."
6776 (interactive)
6777 (org-load-modules-maybe)
6778 (org-run-like-in-org-mode 'org-insert-link))
6779
6780 (defun org-insert-link (&optional complete-file link-location)
6781 "Insert a link. At the prompt, enter the link.
6782
6783 Completion can be used to insert any of the link protocol prefixes like
6784 http or ftp in use.
6785
6786 The history can be used to select a link previously stored with
6787 `org-store-link'. When the empty string is entered (i.e. if you just
6788 press RET at the prompt), the link defaults to the most recently
6789 stored link. As SPC triggers completion in the minibuffer, you need to
6790 use M-SPC or C-q SPC to force the insertion of a space character.
6791
6792 You will also be prompted for a description, and if one is given, it will
6793 be displayed in the buffer instead of the link.
6794
6795 If there is already a link at point, this command will allow you to edit link
6796 and description parts.
6797
6798 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6799 be selected using completion. The path to the file will be relative to the
6800 current directory if the file is in the current directory or a subdirectory.
6801 Otherwise, the link will be the absolute path as completed in the minibuffer
6802 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6803 option `org-link-file-path-type'.
6804
6805 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6806 the current directory or below.
6807
6808 With three \\[universal-argument] prefixes, negate the meaning of
6809 `org-keep-stored-link-after-insertion'.
6810
6811 If `org-make-link-description-function' is non-nil, this function will be
6812 called with the link target, and the result will be the default
6813 link description.
6814
6815 If the LINK-LOCATION parameter is non-nil, this value will be
6816 used as the link location instead of reading one interactively."
6817 (interactive "P")
6818 (let* ((wcf (current-window-configuration))
6819 (region (if (org-region-active-p)
6820 (buffer-substring (region-beginning) (region-end))))
6821 (remove (and region (list (region-beginning) (region-end))))
6822 (desc region)
6823 tmphist ; byte-compile incorrectly complains about this
6824 (link link-location)
6825 entry file)
6826 (cond
6827 (link-location) ; specified by arg, just use it.
6828 ((org-in-regexp org-bracket-link-regexp 1)
6829 ;; We do have a link at point, and we are going to edit it.
6830 (setq remove (list (match-beginning 0) (match-end 0)))
6831 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6832 (setq link (read-string "Link: "
6833 (org-link-unescape
6834 (org-match-string-no-properties 1)))))
6835 ((or (org-in-regexp org-angle-link-re)
6836 (org-in-regexp org-plain-link-re))
6837 ;; Convert to bracket link
6838 (setq remove (list (match-beginning 0) (match-end 0))
6839 link (read-string "Link: "
6840 (org-remove-angle-brackets (match-string 0)))))
6841 ((member complete-file '((4) (16)))
6842 ;; Completing read for file names.
6843 (setq file (read-file-name "File: "))
6844 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6845 (pwd1 (file-name-as-directory (abbreviate-file-name
6846 (expand-file-name ".")))))
6847 (cond
6848 ((equal complete-file '(16))
6849 (setq link (org-make-link
6850 "file:"
6851 (abbreviate-file-name (expand-file-name file)))))
6852 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6853 (setq link (org-make-link "file:" (match-string 1 file))))
6854 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6855 (expand-file-name file))
6856 (setq link (org-make-link
6857 "file:" (match-string 1 (expand-file-name file)))))
6858 (t (setq link (org-make-link "file:" file))))))
6859 (t
6860 ;; Read link, with completion for stored links.
6861 (with-output-to-temp-buffer "*Org Links*"
6862 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6863 (when org-stored-links
6864 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6865 (princ (mapconcat
6866 (lambda (x)
6867 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6868 (reverse org-stored-links) "\n"))))
6869 (let ((cw (selected-window)))
6870 (select-window (get-buffer-window "*Org Links*"))
6871 (setq truncate-lines t)
6872 (org-fit-window-to-buffer)
6873 (select-window cw))
6874 ;; Fake a link history, containing the stored links.
6875 (setq tmphist (append (mapcar 'car org-stored-links)
6876 org-insert-link-history))
6877 (unwind-protect
6878 (setq link
6879 (let ((org-completion-use-ido nil))
6880 (org-completing-read
6881 "Link: "
6882 (append
6883 (mapcar (lambda (x) (list (concat (car x) ":")))
6884 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6885 (mapcar (lambda (x) (list (concat x ":")))
6886 org-link-types))
6887 nil nil nil
6888 'tmphist
6889 (or (car (car org-stored-links))))))
6890 (set-window-configuration wcf)
6891 (kill-buffer "*Org Links*"))
6892 (setq entry (assoc link org-stored-links))
6893 (or entry (push link org-insert-link-history))
6894 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6895 (not org-keep-stored-link-after-insertion))
6896 (setq org-stored-links (delq (assoc link org-stored-links)
6897 org-stored-links)))
6898 (setq desc (or desc (nth 1 entry)))))
6899
6900 (if (string-match org-plain-link-re link)
6901 ;; URL-like link, normalize the use of angular brackets.
6902 (setq link (org-make-link (org-remove-angle-brackets link))))
6903
6904 ;; Check if we are linking to the current file with a search option
6905 ;; If yes, simplify the link by using only the search option.
6906 (when (and buffer-file-name
6907 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6908 (let* ((path (match-string 1 link))
6909 (case-fold-search nil)
6910 (search (match-string 2 link)))
6911 (save-match-data
6912 (if (equal (file-truename buffer-file-name) (file-truename path))
6913 ;; We are linking to this same file, with a search option
6914 (setq link search)))))
6915
6916 ;; Check if we can/should use a relative path. If yes, simplify the link
6917 (when (string-match "^file:\\(.*\\)" link)
6918 (let* ((path (match-string 1 link))
6919 (origpath path)
6920 (case-fold-search nil))
6921 (cond
6922 ((or (eq org-link-file-path-type 'absolute)
6923 (equal complete-file '(16)))
6924 (setq path (abbreviate-file-name (expand-file-name path))))
6925 ((eq org-link-file-path-type 'noabbrev)
6926 (setq path (expand-file-name path)))
6927 ((eq org-link-file-path-type 'relative)
6928 (setq path (file-relative-name path)))
6929 (t
6930 (save-match-data
6931 (if (string-match (concat "^" (regexp-quote
6932 (file-name-as-directory
6933 (expand-file-name "."))))
6934 (expand-file-name path))
6935 ;; We are linking a file with relative path name.
6936 (setq path (substring (expand-file-name path)
6937 (match-end 0)))
6938 (setq path (abbreviate-file-name (expand-file-name path)))))))
6939 (setq link (concat "file:" path))
6940 (if (equal desc origpath)
6941 (setq desc path))))
6942
6943 (if org-make-link-description-function
6944 (setq desc (funcall org-make-link-description-function link desc)))
6945
6946 (setq desc (read-string "Description: " desc))
6947 (unless (string-match "\\S-" desc) (setq desc nil))
6948 (if remove (apply 'delete-region remove))
6949 (insert (org-make-link-string link desc))))
6950
6951 (defun org-completing-read (&rest args)
6952 "Completing-read with SPACE being a normal character."
6953 (let ((minibuffer-local-completion-map
6954 (copy-keymap minibuffer-local-completion-map)))
6955 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6956 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
6957 (apply 'org-ido-completing-read args)))
6958
6959 (defun org-completing-read-no-ido (&rest args)
6960 (let (org-completion-use-ido)
6961 (apply 'org-completing-read args)))
6962
6963 (defun org-ido-completing-read (&rest args)
6964 "Completing-read using `ido-mode' speedups if available"
6965 (if (and org-completion-use-ido
6966 (fboundp 'ido-completing-read)
6967 (boundp 'ido-mode) ido-mode
6968 (listp (second args)))
6969 (apply 'ido-completing-read (concat (car args)) (cdr args))
6970 (apply 'completing-read args)))
6971
6972 (defun org-extract-attributes (s)
6973 "Extract the attributes cookie from a string and set as text property."
6974 (let (a attr (start 0) key value)
6975 (save-match-data
6976 (when (string-match "{{\\([^}]+\\)}}$" s)
6977 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6978 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6979 (setq key (match-string 1 a) value (match-string 2 a)
6980 start (match-end 0)
6981 attr (plist-put attr (intern key) value))))
6982 (org-add-props s nil 'org-attr attr))
6983 s))
6984
6985 (defun org-attributes-to-string (plist)
6986 "Format a property list into an HTML attribute list."
6987 (let ((s "") key value)
6988 (while plist
6989 (setq key (pop plist) value (pop plist))
6990 (and value
6991 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6992 s))
6993
6994 ;;; Opening/following a link
6995
6996 (defvar org-link-search-failed nil)
6997
6998 (defun org-next-link ()
6999 "Move forward to the next link.
7000 If the link is in hidden text, expose it."
7001 (interactive)
7002 (when (and org-link-search-failed (eq this-command last-command))
7003 (goto-char (point-min))
7004 (message "Link search wrapped back to beginning of buffer"))
7005 (setq org-link-search-failed nil)
7006 (let* ((pos (point))
7007 (ct (org-context))
7008 (a (assoc :link ct)))
7009 (if a (goto-char (nth 2 a)))
7010 (if (re-search-forward org-any-link-re nil t)
7011 (progn
7012 (goto-char (match-beginning 0))
7013 (if (org-invisible-p) (org-show-context)))
7014 (goto-char pos)
7015 (setq org-link-search-failed t)
7016 (error "No further link found"))))
7017
7018 (defun org-previous-link ()
7019 "Move backward to the previous link.
7020 If the link is in hidden text, expose it."
7021 (interactive)
7022 (when (and org-link-search-failed (eq this-command last-command))
7023 (goto-char (point-max))
7024 (message "Link search wrapped back to end of buffer"))
7025 (setq org-link-search-failed nil)
7026 (let* ((pos (point))
7027 (ct (org-context))
7028 (a (assoc :link ct)))
7029 (if a (goto-char (nth 1 a)))
7030 (if (re-search-backward org-any-link-re nil t)
7031 (progn
7032 (goto-char (match-beginning 0))
7033 (if (org-invisible-p) (org-show-context)))
7034 (goto-char pos)
7035 (setq org-link-search-failed t)
7036 (error "No further link found"))))
7037
7038 (defun org-translate-link (s)
7039 "Translate a link string if a translation function has been defined."
7040 (if (and org-link-translation-function
7041 (fboundp org-link-translation-function)
7042 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7043 (progn
7044 (setq s (funcall org-link-translation-function
7045 (match-string 1) (match-string 2)))
7046 (concat (car s) ":" (cdr s)))
7047 s))
7048
7049 (defun org-translate-link-from-planner (type path)
7050 "Translate a link from Emacs Planner syntax so that Org can follow it.
7051 This is still an experimental function, your mileage may vary."
7052 (cond
7053 ((member type '("http" "https" "news" "ftp"))
7054 ;; standard Internet links are the same.
7055 nil)
7056 ((and (equal type "irc") (string-match "^//" path))
7057 ;; Planner has two / at the beginning of an irc link, we have 1.
7058 ;; We should have zero, actually....
7059 (setq path (substring path 1)))
7060 ((and (equal type "lisp") (string-match "^/" path))
7061 ;; Planner has a slash, we do not.
7062 (setq type "elisp" path (substring path 1)))
7063 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7064 ;; A typical message link. Planner has the id after the fina slash,
7065 ;; we separate it with a hash mark
7066 (setq path (concat (match-string 1 path) "#"
7067 (org-remove-angle-brackets (match-string 2 path)))))
7068 )
7069 (cons type path))
7070
7071 (defun org-find-file-at-mouse (ev)
7072 "Open file link or URL at mouse."
7073 (interactive "e")
7074 (mouse-set-point ev)
7075 (org-open-at-point 'in-emacs))
7076
7077 (defun org-open-at-mouse (ev)
7078 "Open file link or URL at mouse."
7079 (interactive "e")
7080 (mouse-set-point ev)
7081 (if (eq major-mode 'org-agenda-mode)
7082 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7083 (org-open-at-point))
7084
7085 (defvar org-window-config-before-follow-link nil
7086 "The window configuration before following a link.
7087 This is saved in case the need arises to restore it.")
7088
7089 (defvar org-open-link-marker (make-marker)
7090 "Marker pointing to the location where `org-open-at-point; was called.")
7091
7092 ;;;###autoload
7093 (defun org-open-at-point-global ()
7094 "Follow a link like Org-mode does.
7095 This command can be called in any mode to follow a link that has
7096 Org-mode syntax."
7097 (interactive)
7098 (org-run-like-in-org-mode 'org-open-at-point))
7099
7100 ;;;###autoload
7101 (defun org-open-link-from-string (s &optional arg)
7102 "Open a link in the string S, as if it was in Org-mode."
7103 (interactive "sLink: \nP")
7104 (with-temp-buffer
7105 (let ((org-inhibit-startup t))
7106 (org-mode)
7107 (insert s)
7108 (goto-char (point-min))
7109 (org-open-at-point arg))))
7110
7111 (defun org-open-at-point (&optional in-emacs)
7112 "Open link at or after point.
7113 If there is no link at point, this function will search forward up to
7114 the end of the current subtree.
7115 Normally, files will be opened by an appropriate application. If the
7116 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7117 With a double prefix argument, try to open outside of Emacs, in the
7118 application the system uses for this file type."
7119 (interactive "P")
7120 (org-load-modules-maybe)
7121 (move-marker org-open-link-marker (point))
7122 (setq org-window-config-before-follow-link (current-window-configuration))
7123 (org-remove-occur-highlights nil nil t)
7124 (cond
7125 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7126 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7127 (org-footnote-action))
7128 (t
7129 (let (type path link line search (pos (point)))
7130 (catch 'match
7131 (save-excursion
7132 (skip-chars-forward "^]\n\r")
7133 (when (org-in-regexp org-bracket-link-regexp)
7134 (setq link (org-extract-attributes
7135 (org-link-unescape (org-match-string-no-properties 1))))
7136 (while (string-match " *\n *" link)
7137 (setq link (replace-match " " t t link)))
7138 (setq link (org-link-expand-abbrev link))
7139 (cond
7140 ((or (file-name-absolute-p link)
7141 (string-match "^\\.\\.?/" link))
7142 (setq type "file" path link))
7143 ((string-match org-link-re-with-space3 link)
7144 (setq type (match-string 1 link) path (match-string 2 link)))
7145 (t (setq type "thisfile" path link)))
7146 (throw 'match t)))
7147
7148 (when (get-text-property (point) 'org-linked-text)
7149 (setq type "thisfile"
7150 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7151 (1+ (point)) (point))
7152 path (buffer-substring
7153 (previous-single-property-change pos 'org-linked-text)
7154 (next-single-property-change pos 'org-linked-text)))
7155 (throw 'match t))
7156
7157 (save-excursion
7158 (when (or (org-in-regexp org-angle-link-re)
7159 (org-in-regexp org-plain-link-re))
7160 (setq type (match-string 1) path (match-string 2))
7161 (throw 'match t)))
7162 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7163 (setq type "tree-match"
7164 path (match-string 1))
7165 (throw 'match t))
7166 (save-excursion
7167 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7168 (setq type "tags"
7169 path (match-string 1))
7170 (while (string-match ":" path)
7171 (setq path (replace-match "+" t t path)))
7172 (throw 'match t))))
7173 (unless path
7174 (error "No link found"))
7175 ;; Remove any trailing spaces in path
7176 (if (string-match " +\\'" path)
7177 (setq path (replace-match "" t t path)))
7178 (if (and org-link-translation-function
7179 (fboundp org-link-translation-function))
7180 ;; Check if we need to translate the link
7181 (let ((tmp (funcall org-link-translation-function type path)))
7182 (setq type (car tmp) path (cdr tmp))))
7183
7184 (cond
7185
7186 ((assoc type org-link-protocols)
7187 (funcall (nth 1 (assoc type org-link-protocols)) path))
7188
7189 ((equal type "mailto")
7190 (let ((cmd (car org-link-mailto-program))
7191 (args (cdr org-link-mailto-program)) args1
7192 (address path) (subject "") a)
7193 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7194 (setq address (match-string 1 path)
7195 subject (org-link-escape (match-string 2 path))))
7196 (while args
7197 (cond
7198 ((not (stringp (car args))) (push (pop args) args1))
7199 (t (setq a (pop args))
7200 (if (string-match "%a" a)
7201 (setq a (replace-match address t t a)))
7202 (if (string-match "%s" a)
7203 (setq a (replace-match subject t t a)))
7204 (push a args1))))
7205 (apply cmd (nreverse args1))))
7206
7207 ((member type '("http" "https" "ftp" "news"))
7208 (browse-url (concat type ":" (org-link-escape
7209 path org-link-escape-chars-browser))))
7210
7211 ((member type '("message"))
7212 (browse-url (concat type ":" path)))
7213
7214 ((string= type "tags")
7215 (org-tags-view in-emacs path))
7216 ((string= type "thisfile")
7217 (if in-emacs
7218 (switch-to-buffer-other-window
7219 (org-get-buffer-for-internal-link (current-buffer)))
7220 (org-mark-ring-push))
7221 (let ((cmd `(org-link-search
7222 ,path
7223 ,(cond ((equal in-emacs '(4)) 'occur)
7224 ((equal in-emacs '(16)) 'org-occur)
7225 (t nil))
7226 ,pos)))
7227 (condition-case nil (eval cmd)
7228 (error (progn (widen) (eval cmd))))))
7229
7230 ((string= type "tree-match")
7231 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7232
7233 ((string= type "file")
7234 (if (string-match "::\\([0-9]+\\)\\'" path)
7235 (setq line (string-to-number (match-string 1 path))
7236 path (substring path 0 (match-beginning 0)))
7237 (if (string-match "::\\(.+\\)\\'" path)
7238 (setq search (match-string 1 path)
7239 path (substring path 0 (match-beginning 0)))))
7240 (if (string-match "[*?{]" (file-name-nondirectory path))
7241 (dired path)
7242 (org-open-file path in-emacs line search)))
7243
7244 ((string= type "news")
7245 (require 'org-gnus)
7246 (org-gnus-follow-link path))
7247
7248 ((string= type "shell")
7249 (let ((cmd path))
7250 (if (or (not org-confirm-shell-link-function)
7251 (funcall org-confirm-shell-link-function
7252 (format "Execute \"%s\" in shell? "
7253 (org-add-props cmd nil
7254 'face 'org-warning))))
7255 (progn
7256 (message "Executing %s" cmd)
7257 (shell-command cmd))
7258 (error "Abort"))))
7259
7260 ((string= type "elisp")
7261 (let ((cmd path))
7262 (if (or (not org-confirm-elisp-link-function)
7263 (funcall org-confirm-elisp-link-function
7264 (format "Execute \"%s\" as elisp? "
7265 (org-add-props cmd nil
7266 'face 'org-warning))))
7267 (message "%s => %s" cmd
7268 (if (equal (string-to-char cmd) ?\()
7269 (eval (read cmd))
7270 (call-interactively (read cmd))))
7271 (error "Abort"))))
7272
7273 (t
7274 (browse-url-at-point))))))
7275 (move-marker org-open-link-marker nil)
7276 (run-hook-with-args 'org-follow-link-hook))
7277
7278 ;;;; Time estimates
7279
7280 (defun org-get-effort (&optional pom)
7281 "Get the effort estimate for the current entry."
7282 (org-entry-get pom org-effort-property))
7283
7284 ;;; File search
7285
7286 (defvar org-create-file-search-functions nil
7287 "List of functions to construct the right search string for a file link.
7288 These functions are called in turn with point at the location to
7289 which the link should point.
7290
7291 A function in the hook should first test if it would like to
7292 handle this file type, for example by checking the major-mode or
7293 the file extension. If it decides not to handle this file, it
7294 should just return nil to give other functions a chance. If it
7295 does handle the file, it must return the search string to be used
7296 when following the link. The search string will be part of the
7297 file link, given after a double colon, and `org-open-at-point'
7298 will automatically search for it. If special measures must be
7299 taken to make the search successful, another function should be
7300 added to the companion hook `org-execute-file-search-functions',
7301 which see.
7302
7303 A function in this hook may also use `setq' to set the variable
7304 `description' to provide a suggestion for the descriptive text to
7305 be used for this link when it gets inserted into an Org-mode
7306 buffer with \\[org-insert-link].")
7307
7308 (defvar org-execute-file-search-functions nil
7309 "List of functions to execute a file search triggered by a link.
7310
7311 Functions added to this hook must accept a single argument, the
7312 search string that was part of the file link, the part after the
7313 double colon. The function must first check if it would like to
7314 handle this search, for example by checking the major-mode or the
7315 file extension. If it decides not to handle this search, it
7316 should just return nil to give other functions a chance. If it
7317 does handle the search, it must return a non-nil value to keep
7318 other functions from trying.
7319
7320 Each function can access the current prefix argument through the
7321 variable `current-prefix-argument'. Note that a single prefix is
7322 used to force opening a link in Emacs, so it may be good to only
7323 use a numeric or double prefix to guide the search function.
7324
7325 In case this is needed, a function in this hook can also restore
7326 the window configuration before `org-open-at-point' was called using:
7327
7328 (set-window-configuration org-window-config-before-follow-link)")
7329
7330 (defun org-link-search (s &optional type avoid-pos)
7331 "Search for a link search option.
7332 If S is surrounded by forward slashes, it is interpreted as a
7333 regular expression. In org-mode files, this will create an `org-occur'
7334 sparse tree. In ordinary files, `occur' will be used to list matches.
7335 If the current buffer is in `dired-mode', grep will be used to search
7336 in all files. If AVOID-POS is given, ignore matches near that position."
7337 (let ((case-fold-search t)
7338 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7339 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7340 (append '(("") (" ") ("\t") ("\n"))
7341 org-emphasis-alist)
7342 "\\|") "\\)"))
7343 (pos (point))
7344 (pre nil) (post nil)
7345 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7346 (cond
7347 ;; First check if there are any special
7348 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7349 ;; Now try the builtin stuff
7350 ((save-excursion
7351 (goto-char (point-min))
7352 (and
7353 (re-search-forward
7354 (concat "<<" (regexp-quote s0) ">>") nil t)
7355 (setq type 'dedicated
7356 pos (match-beginning 0))))
7357 ;; There is an exact target for this
7358 (goto-char pos))
7359 ((and (string-match "^(\\(.*\\))$" s0)
7360 (save-excursion
7361 (goto-char (point-min))
7362 (and
7363 (re-search-forward
7364 (concat "[^[]" (regexp-quote
7365 (format org-coderef-label-format
7366 (match-string 1 s0))))
7367 nil t)
7368 (setq type 'dedicated
7369 pos (1+ (match-beginning 0))))))
7370 ;; There is a coderef target for this
7371 (goto-char pos))
7372 ((string-match "^/\\(.*\\)/$" s)
7373 ;; A regular expression
7374 (cond
7375 ((org-mode-p)
7376 (org-occur (match-string 1 s)))
7377 ;;((eq major-mode 'dired-mode)
7378 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7379 (t (org-do-occur (match-string 1 s)))))
7380 (t
7381 ;; A normal search strings
7382 (when (equal (string-to-char s) ?*)
7383 ;; Anchor on headlines, post may include tags.
7384 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7385 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7386 s (substring s 1)))
7387 (remove-text-properties
7388 0 (length s)
7389 '(face nil mouse-face nil keymap nil fontified nil) s)
7390 ;; Make a series of regular expressions to find a match
7391 (setq words (org-split-string s "[ \n\r\t]+")
7392
7393 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7394 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7395 "\\)" markers)
7396 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7397 re2a (concat "[ \t\r\n]" re2a_)
7398 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7399 re4 (concat "[^a-zA-Z_]" re4_)
7400
7401 re1 (concat pre re2 post)
7402 re3 (concat pre (if pre re4_ re4) post)
7403 re5 (concat pre ".*" re4)
7404 re2 (concat pre re2)
7405 re2a (concat pre (if pre re2a_ re2a))
7406 re4 (concat pre (if pre re4_ re4))
7407 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7408 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7409 re5 "\\)"
7410 ))
7411 (cond
7412 ((eq type 'org-occur) (org-occur reall))
7413 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7414 (t (goto-char (point-min))
7415 (setq type 'fuzzy)
7416 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7417 (org-search-not-self 1 re1 nil t)
7418 (org-search-not-self 1 re2 nil t)
7419 (org-search-not-self 1 re2a nil t)
7420 (org-search-not-self 1 re3 nil t)
7421 (org-search-not-self 1 re4 nil t)
7422 (org-search-not-self 1 re5 nil t)
7423 )
7424 (goto-char (match-beginning 1))
7425 (goto-char pos)
7426 (error "No match")))))
7427 (t
7428 ;; Normal string-search
7429 (goto-char (point-min))
7430 (if (search-forward s nil t)
7431 (goto-char (match-beginning 0))
7432 (error "No match"))))
7433 (and (org-mode-p) (org-show-context 'link-search))
7434 type))
7435
7436 (defun org-search-not-self (group &rest args)
7437 "Execute `re-search-forward', but only accept matches that do not
7438 enclose the position of `org-open-link-marker'."
7439 (let ((m org-open-link-marker))
7440 (catch 'exit
7441 (while (apply 're-search-forward args)
7442 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7443 (goto-char (match-end group))
7444 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7445 (> (match-beginning 0) (marker-position m))
7446 (< (match-end 0) (marker-position m)))
7447 (save-match-data
7448 (or (not (org-in-regexp
7449 org-bracket-link-analytic-regexp 1))
7450 (not (match-end 4)) ; no description
7451 (and (<= (match-beginning 4) (point))
7452 (>= (match-end 4) (point))))))
7453 (throw 'exit (point))))))))
7454
7455 (defun org-get-buffer-for-internal-link (buffer)
7456 "Return a buffer to be used for displaying the link target of internal links."
7457 (cond
7458 ((not org-display-internal-link-with-indirect-buffer)
7459 buffer)
7460 ((string-match "(Clone)$" (buffer-name buffer))
7461 (message "Buffer is already a clone, not making another one")
7462 ;; we also do not modify visibility in this case
7463 buffer)
7464 (t ; make a new indirect buffer for displaying the link
7465 (let* ((bn (buffer-name buffer))
7466 (ibn (concat bn "(Clone)"))
7467 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7468 (with-current-buffer ib (org-overview))
7469 ib))))
7470
7471 (defun org-do-occur (regexp &optional cleanup)
7472 "Call the Emacs command `occur'.
7473 If CLEANUP is non-nil, remove the printout of the regular expression
7474 in the *Occur* buffer. This is useful if the regex is long and not useful
7475 to read."
7476 (occur regexp)
7477 (when cleanup
7478 (let ((cwin (selected-window)) win beg end)
7479 (when (setq win (get-buffer-window "*Occur*"))
7480 (select-window win))
7481 (goto-char (point-min))
7482 (when (re-search-forward "match[a-z]+" nil t)
7483 (setq beg (match-end 0))
7484 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7485 (setq end (1- (match-beginning 0)))))
7486 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7487 (goto-char (point-min))
7488 (select-window cwin))))
7489
7490 ;;; The mark ring for links jumps
7491
7492 (defvar org-mark-ring nil
7493 "Mark ring for positions before jumps in Org-mode.")
7494 (defvar org-mark-ring-last-goto nil
7495 "Last position in the mark ring used to go back.")
7496 ;; Fill and close the ring
7497 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7498 (loop for i from 1 to org-mark-ring-length do
7499 (push (make-marker) org-mark-ring))
7500 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7501 org-mark-ring)
7502
7503 (defun org-mark-ring-push (&optional pos buffer)
7504 "Put the current position or POS into the mark ring and rotate it."
7505 (interactive)
7506 (setq pos (or pos (point)))
7507 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7508 (move-marker (car org-mark-ring)
7509 (or pos (point))
7510 (or buffer (current-buffer)))
7511 (message "%s"
7512 (substitute-command-keys
7513 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7514
7515 (defun org-mark-ring-goto (&optional n)
7516 "Jump to the previous position in the mark ring.
7517 With prefix arg N, jump back that many stored positions. When
7518 called several times in succession, walk through the entire ring.
7519 Org-mode commands jumping to a different position in the current file,
7520 or to another Org-mode file, automatically push the old position
7521 onto the ring."
7522 (interactive "p")
7523 (let (p m)
7524 (if (eq last-command this-command)
7525 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7526 (setq p org-mark-ring))
7527 (setq org-mark-ring-last-goto p)
7528 (setq m (car p))
7529 (switch-to-buffer (marker-buffer m))
7530 (goto-char m)
7531 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7532
7533 (defun org-remove-angle-brackets (s)
7534 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7535 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7536 s)
7537 (defun org-add-angle-brackets (s)
7538 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7539 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7540 s)
7541 (defun org-remove-double-quotes (s)
7542 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7543 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7544 s)
7545
7546 ;;; Following specific links
7547
7548 (defun org-follow-timestamp-link ()
7549 (cond
7550 ((org-at-date-range-p t)
7551 (let ((org-agenda-start-on-weekday)
7552 (t1 (match-string 1))
7553 (t2 (match-string 2)))
7554 (setq t1 (time-to-days (org-time-string-to-time t1))
7555 t2 (time-to-days (org-time-string-to-time t2)))
7556 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7557 ((org-at-timestamp-p t)
7558 (org-agenda-list nil (time-to-days (org-time-string-to-time
7559 (substring (match-string 1) 0 10)))
7560 1))
7561 (t (error "This should not happen"))))
7562
7563
7564 ;;; Following file links
7565 (defvar org-wait nil)
7566 (defun org-open-file (path &optional in-emacs line search)
7567 "Open the file at PATH.
7568 First, this expands any special file name abbreviations. Then the
7569 configuration variable `org-file-apps' is checked if it contains an
7570 entry for this file type, and if yes, the corresponding command is launched.
7571
7572 If no application is found, Emacs simply visits the file.
7573
7574 With optional prefix argument IN-EMACS, Emacs will visit the file.
7575 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7576 and o use an external application to visit the file.
7577
7578 Optional LINE specifies a line to go to, optional SEARCH a string to
7579 search for. If LINE or SEARCH is given, the file will always be
7580 opened in Emacs.
7581 If the file does not exist, an error is thrown."
7582 (setq in-emacs (or in-emacs line search))
7583 (let* ((file (if (equal path "")
7584 buffer-file-name
7585 (substitute-in-file-name (expand-file-name path))))
7586 (apps (append org-file-apps (org-default-apps)))
7587 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7588 (dirp (if remp nil (file-directory-p file)))
7589 (file (if (and dirp org-open-directory-means-index-dot-org)
7590 (concat (file-name-as-directory file) "index.org")
7591 file))
7592 (a-m-a-p (assq 'auto-mode apps))
7593 (dfile (downcase file))
7594 (old-buffer (current-buffer))
7595 (old-pos (point))
7596 (old-mode major-mode)
7597 ext cmd)
7598 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7599 (setq ext (match-string 1 dfile))
7600 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7601 (setq ext (match-string 1 dfile))))
7602 (cond
7603 ((equal in-emacs '(16))
7604 (setq cmd (cdr (assoc 'system apps))))
7605 (in-emacs (setq cmd 'emacs))
7606 (t
7607 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7608 (and dirp (cdr (assoc 'directory apps)))
7609 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7610 'string-match)
7611 (cdr (assoc ext apps))
7612 (cdr (assoc t apps))))))
7613 (when (eq cmd 'system)
7614 (setq cmd (cdr (assoc 'system apps))))
7615 (when (eq cmd 'default)
7616 (setq cmd (cdr (assoc t apps))))
7617 (when (eq cmd 'mailcap)
7618 (require 'mailcap)
7619 (mailcap-parse-mailcaps)
7620 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7621 (command (mailcap-mime-info mime-type)))
7622 (if (stringp command)
7623 (setq cmd command)
7624 (setq cmd 'emacs))))
7625 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7626 (not (file-exists-p file))
7627 (not org-open-non-existing-files))
7628 (error "No such file: %s" file))
7629 (cond
7630 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7631 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7632 (while (string-match "['\"]%s['\"]" cmd)
7633 (setq cmd (replace-match "%s" t t cmd)))
7634 (while (string-match "%s" cmd)
7635 (setq cmd (replace-match
7636 (save-match-data
7637 (shell-quote-argument
7638 (convert-standard-filename file)))
7639 t t cmd)))
7640 (save-window-excursion
7641 (start-process-shell-command cmd nil cmd)
7642 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7643 ))
7644 ((or (stringp cmd)
7645 (eq cmd 'emacs))
7646 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7647 (widen)
7648 (if line (goto-line line)
7649 (if search (org-link-search search))))
7650 ((consp cmd)
7651 (let ((file (convert-standard-filename file)))
7652 (eval cmd)))
7653 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7654 (and (org-mode-p) (eq old-mode 'org-mode)
7655 (or (not (equal old-buffer (current-buffer)))
7656 (not (equal old-pos (point))))
7657 (org-mark-ring-push old-pos old-buffer))))
7658
7659 (defun org-default-apps ()
7660 "Return the default applications for this operating system."
7661 (cond
7662 ((eq system-type 'darwin)
7663 org-file-apps-defaults-macosx)
7664 ((eq system-type 'windows-nt)
7665 org-file-apps-defaults-windowsnt)
7666 (t org-file-apps-defaults-gnu)))
7667
7668 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7669 "Convert extensions to regular expressions in the cars of LIST.
7670 Also, weed out any non-string entries, because the return value is used
7671 only for regexp matching.
7672 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7673 point to the symbol `emacs', indicating that the file should
7674 be opened in Emacs."
7675 (append
7676 (delq nil
7677 (mapcar (lambda (x)
7678 (if (not (stringp (car x)))
7679 nil
7680 (if (string-match "\\W" (car x))
7681 x
7682 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7683 list))
7684 (if add-auto-mode
7685 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7686
7687 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7688 (defun org-file-remote-p (file)
7689 "Test whether FILE specifies a location on a remote system.
7690 Return non-nil if the location is indeed remote.
7691
7692 For example, the filename \"/user@host:/foo\" specifies a location
7693 on the system \"/user@host:\"."
7694 (cond ((fboundp 'file-remote-p)
7695 (file-remote-p file))
7696 ((fboundp 'tramp-handle-file-remote-p)
7697 (tramp-handle-file-remote-p file))
7698 ((and (boundp 'ange-ftp-name-format)
7699 (string-match (car ange-ftp-name-format) file))
7700 t)
7701 (t nil)))
7702
7703
7704 ;;;; Refiling
7705
7706 (defun org-get-org-file ()
7707 "Read a filename, with default directory `org-directory'."
7708 (let ((default (or org-default-notes-file remember-data-file)))
7709 (read-file-name (format "File name [%s]: " default)
7710 (file-name-as-directory org-directory)
7711 default)))
7712
7713 (defun org-notes-order-reversed-p ()
7714 "Check if the current file should receive notes in reversed order."
7715 (cond
7716 ((not org-reverse-note-order) nil)
7717 ((eq t org-reverse-note-order) t)
7718 ((not (listp org-reverse-note-order)) nil)
7719 (t (catch 'exit
7720 (let ((all org-reverse-note-order)
7721 entry)
7722 (while (setq entry (pop all))
7723 (if (string-match (car entry) buffer-file-name)
7724 (throw 'exit (cdr entry))))
7725 nil)))))
7726
7727 (defvar org-refile-target-table nil
7728 "The list of refile targets, created by `org-refile'.")
7729
7730 (defvar org-agenda-new-buffers nil
7731 "Buffers created to visit agenda files.")
7732
7733 (defun org-get-refile-targets (&optional default-buffer)
7734 "Produce a table with refile targets."
7735 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7736 targets txt re files f desc descre fast-path-p level)
7737 (message "Getting targets...")
7738 (with-current-buffer (or default-buffer (current-buffer))
7739 (while (setq entry (pop entries))
7740 (setq files (car entry) desc (cdr entry))
7741 (setq fast-path-p nil)
7742 (cond
7743 ((null files) (setq files (list (current-buffer))))
7744 ((eq files 'org-agenda-files)
7745 (setq files (org-agenda-files 'unrestricted)))
7746 ((and (symbolp files) (fboundp files))
7747 (setq files (funcall files)))
7748 ((and (symbolp files) (boundp files))
7749 (setq files (symbol-value files))))
7750 (if (stringp files) (setq files (list files)))
7751 (cond
7752 ((eq (car desc) :tag)
7753 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7754 ((eq (car desc) :todo)
7755 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7756 ((eq (car desc) :regexp)
7757 (setq descre (cdr desc)))
7758 ((eq (car desc) :level)
7759 (setq descre (concat "^\\*\\{" (number-to-string
7760 (if org-odd-levels-only
7761 (1- (* 2 (cdr desc)))
7762 (cdr desc)))
7763 "\\}[ \t]")))
7764 ((eq (car desc) :maxlevel)
7765 (setq fast-path-p t)
7766 (setq descre (concat "^\\*\\{1," (number-to-string
7767 (if org-odd-levels-only
7768 (1- (* 2 (cdr desc)))
7769 (cdr desc)))
7770 "\\}[ \t]")))
7771 (t (error "Bad refiling target description %s" desc)))
7772 (while (setq f (pop files))
7773 (save-excursion
7774 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7775 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7776 (setq f (expand-file-name f))
7777 (save-excursion
7778 (save-restriction
7779 (widen)
7780 (goto-char (point-min))
7781 (while (re-search-forward descre nil t)
7782 (goto-char (point-at-bol))
7783 (when (looking-at org-complex-heading-regexp)
7784 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7785 txt (org-link-display-format (match-string 4))
7786 re (concat "^" (regexp-quote
7787 (buffer-substring (match-beginning 1)
7788 (match-end 4)))))
7789 (if (match-end 5) (setq re (concat re "[ \t]+"
7790 (regexp-quote
7791 (match-string 5)))))
7792 (setq re (concat re "[ \t]*$"))
7793 (when org-refile-use-outline-path
7794 (setq txt (mapconcat 'org-protect-slash
7795 (append
7796 (if (eq org-refile-use-outline-path 'file)
7797 (list (file-name-nondirectory
7798 (buffer-file-name (buffer-base-buffer))))
7799 (if (eq org-refile-use-outline-path 'full-file-path)
7800 (list (buffer-file-name (buffer-base-buffer)))))
7801 (org-get-outline-path fast-path-p level txt)
7802 (list txt))
7803 "/")))
7804 (push (list txt f re (point)) targets))
7805 (goto-char (point-at-eol))))))))
7806 (message "Getting targets...done")
7807 (nreverse targets))))
7808
7809 (defun org-protect-slash (s)
7810 (while (string-match "/" s)
7811 (setq s (replace-match "\\" t t s)))
7812 s)
7813
7814 (defvar org-olpa (make-vector 20 nil))
7815
7816 (defun org-get-outline-path (&optional fastp level heading)
7817 "Return the outline path to the current entry, as a list."
7818 (if fastp
7819 (progn
7820 (if (> level 19)
7821 (error "Outline path failure, more than 19 levels."))
7822 (loop for i from level upto 19 do
7823 (aset org-olpa i nil))
7824 (prog1
7825 (delq nil (append org-olpa nil))
7826 (aset org-olpa level heading)))
7827 (let (rtn)
7828 (save-excursion
7829 (while (org-up-heading-safe)
7830 (when (looking-at org-complex-heading-regexp)
7831 (push (org-match-string-no-properties 4) rtn)))
7832 rtn))))
7833
7834 (defvar org-refile-history nil
7835 "History for refiling operations.")
7836
7837 (defun org-refile (&optional goto default-buffer)
7838 "Move the entry at point to another heading.
7839 The list of target headings is compiled using the information in
7840 `org-refile-targets', which see. This list is created before each use
7841 and will therefore always be up-to-date.
7842
7843 At the target location, the entry is filed as a subitem of the target heading.
7844 Depending on `org-reverse-note-order', the new subitem will either be the
7845 first or the last subitem.
7846
7847 If there is an active region, all entries in that region will be moved.
7848 However, the region must fulfil the requirement that the first heading
7849 is the first one sets the top-level of the moved text - at most siblings
7850 below it are allowed.
7851
7852 With prefix arg GOTO, the command will only visit the target location,
7853 not actually move anything.
7854 With a double prefix `C-u C-u', go to the location where the last refiling
7855 operation has put the subtree."
7856 (interactive "P")
7857 (let* ((cbuf (current-buffer))
7858 (regionp (org-region-active-p))
7859 (region-start (and regionp (region-beginning)))
7860 (region-end (and regionp (region-end)))
7861 (region-length (and regionp (- region-end region-start)))
7862 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7863 pos it nbuf file re level reversed)
7864 (when regionp (goto-char region-start)
7865 (unless (org-kill-is-subtree-p
7866 (buffer-substring region-start region-end))
7867 (error "The region is not a (sequence of) subtree(s)")))
7868 (if (equal goto '(16))
7869 (org-refile-goto-last-stored)
7870 (when (setq it (org-refile-get-location
7871 (if goto "Goto: " "Refile to: ") default-buffer))
7872 (setq file (nth 1 it)
7873 re (nth 2 it)
7874 pos (nth 3 it))
7875 (if (and (equal (buffer-file-name) file)
7876 (if regionp
7877 (and (>= pos region-start)
7878 (<= pos region-end))
7879 (and (>= pos (point))
7880 (< pos (save-excursion
7881 (org-end-of-subtree t t))))))
7882 (error "Cannot refile to position inside the tree or region"))
7883
7884 (setq nbuf (or (find-buffer-visiting file)
7885 (find-file-noselect file)))
7886 (if goto
7887 (progn
7888 (switch-to-buffer nbuf)
7889 (goto-char pos)
7890 (org-show-context 'org-goto))
7891 (if regionp
7892 (progn
7893 (kill-new (buffer-substring region-start region-end))
7894 (org-save-markers-in-region region-start region-end))
7895 (org-copy-subtree 1 nil t))
7896 (save-excursion
7897 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7898 (find-file-noselect file))))
7899 (setq reversed (org-notes-order-reversed-p))
7900 (save-excursion
7901 (save-restriction
7902 (widen)
7903 (goto-char pos)
7904 (looking-at outline-regexp)
7905 (setq level (org-get-valid-level (funcall outline-level) 1))
7906 (goto-char
7907 (if reversed
7908 (or (outline-next-heading) (point-max))
7909 (or (save-excursion (outline-get-next-sibling))
7910 (org-end-of-subtree t t)
7911 (point-max))))
7912 (if (not (bolp)) (newline))
7913 (bookmark-set "org-refile-last-stored")
7914 (org-paste-subtree level))))
7915 (if regionp
7916 (delete-region (point) (+ (point) region-length))
7917 (org-cut-subtree))
7918 (setq org-markers-to-move nil)
7919 (message "Refiled to \"%s\"" (car it)))))))
7920
7921 (defun org-refile-goto-last-stored ()
7922 "Go to the location where the last refile was stored."
7923 (interactive)
7924 (bookmark-jump "org-refile-last-stored")
7925 (message "This is the location of the last refile"))
7926
7927 (defun org-refile-get-location (&optional prompt default-buffer)
7928 "Prompt the user for a refile location, using PROMPT."
7929 (let ((org-refile-targets org-refile-targets)
7930 (org-refile-use-outline-path org-refile-use-outline-path))
7931 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7932 (unless org-refile-target-table
7933 (error "No refile targets"))
7934 (let* ((cbuf (current-buffer))
7935 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7936 (cfunc (if (and org-refile-use-outline-path
7937 org-outline-path-complete-in-steps)
7938 'org-olpath-completing-read
7939 'org-ido-completing-read))
7940 (extra (if org-refile-use-outline-path "/" ""))
7941 (filename (and cfn (expand-file-name cfn)))
7942 (tbl (mapcar
7943 (lambda (x)
7944 (if (not (equal filename (nth 1 x)))
7945 (cons (concat (car x) extra " ("
7946 (file-name-nondirectory (nth 1 x)) ")")
7947 (cdr x))
7948 (cons (concat (car x) extra) (cdr x))))
7949 org-refile-target-table))
7950 (completion-ignore-case t))
7951 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7952 tbl)))
7953
7954 (defun org-olpath-completing-read (prompt collection &rest args)
7955 "Read an outline path like a file name."
7956 (let ((thetable collection))
7957 (apply
7958 'org-ido-completing-read prompt
7959 (lambda (string predicate &optional flag)
7960 (let (rtn r f (l (length string)))
7961 (cond
7962 ((eq flag nil)
7963 ;; try completion
7964 (try-completion string thetable))
7965 ((eq flag t)
7966 ;; all-completions
7967 (setq rtn (all-completions string thetable predicate))
7968 (mapcar
7969 (lambda (x)
7970 (setq r (substring x l))
7971 (if (string-match " ([^)]*)$" x)
7972 (setq f (match-string 0 x))
7973 (setq f ""))
7974 (if (string-match "/" r)
7975 (concat string (substring r 0 (match-end 0)) f)
7976 x))
7977 rtn))
7978 ((eq flag 'lambda)
7979 ;; exact match?
7980 (assoc string thetable)))
7981 ))
7982 args)))
7983
7984 ;;;; Dynamic blocks
7985
7986 (defun org-find-dblock (name)
7987 "Find the first dynamic block with name NAME in the buffer.
7988 If not found, stay at current position and return nil."
7989 (let (pos)
7990 (save-excursion
7991 (goto-char (point-min))
7992 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7993 nil t)
7994 (match-beginning 0))))
7995 (if pos (goto-char pos))
7996 pos))
7997
7998 (defconst org-dblock-start-re
7999 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8000 "Matches the startline of a dynamic block, with parameters.")
8001
8002 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8003 "Matches the end of a dynamic block.")
8004
8005 (defun org-create-dblock (plist)
8006 "Create a dynamic block section, with parameters taken from PLIST.
8007 PLIST must contain a :name entry which is used as name of the block."
8008 (unless (bolp) (newline))
8009 (let ((name (plist-get plist :name)))
8010 (insert "#+BEGIN: " name)
8011 (while plist
8012 (if (eq (car plist) :name)
8013 (setq plist (cddr plist))
8014 (insert " " (prin1-to-string (pop plist)))))
8015 (insert "\n\n#+END:\n")
8016 (beginning-of-line -2)))
8017
8018 (defun org-prepare-dblock ()
8019 "Prepare dynamic block for refresh.
8020 This empties the block, puts the cursor at the insert position and returns
8021 the property list including an extra property :name with the block name."
8022 (unless (looking-at org-dblock-start-re)
8023 (error "Not at a dynamic block"))
8024 (let* ((begdel (1+ (match-end 0)))
8025 (name (org-no-properties (match-string 1)))
8026 (params (append (list :name name)
8027 (read (concat "(" (match-string 3) ")")))))
8028 (unless (re-search-forward org-dblock-end-re nil t)
8029 (error "Dynamic block not terminated"))
8030 (setq params
8031 (append params
8032 (list :content (buffer-substring
8033 begdel (match-beginning 0)))))
8034 (delete-region begdel (match-beginning 0))
8035 (goto-char begdel)
8036 (open-line 1)
8037 params))
8038
8039 (defun org-map-dblocks (&optional command)
8040 "Apply COMMAND to all dynamic blocks in the current buffer.
8041 If COMMAND is not given, use `org-update-dblock'."
8042 (let ((cmd (or command 'org-update-dblock))
8043 pos)
8044 (save-excursion
8045 (goto-char (point-min))
8046 (while (re-search-forward org-dblock-start-re nil t)
8047 (goto-char (setq pos (match-beginning 0)))
8048 (condition-case nil
8049 (funcall cmd)
8050 (error (message "Error during update of dynamic block")))
8051 (goto-char pos)
8052 (unless (re-search-forward org-dblock-end-re nil t)
8053 (error "Dynamic block not terminated"))))))
8054
8055 (defun org-dblock-update (&optional arg)
8056 "User command for updating dynamic blocks.
8057 Update the dynamic block at point. With prefix ARG, update all dynamic
8058 blocks in the buffer."
8059 (interactive "P")
8060 (if arg
8061 (org-update-all-dblocks)
8062 (or (looking-at org-dblock-start-re)
8063 (org-beginning-of-dblock))
8064 (org-update-dblock)))
8065
8066 (defun org-update-dblock ()
8067 "Update the dynamic block at point
8068 This means to empty the block, parse for parameters and then call
8069 the correct writing function."
8070 (save-window-excursion
8071 (let* ((pos (point))
8072 (line (org-current-line))
8073 (params (org-prepare-dblock))
8074 (name (plist-get params :name))
8075 (cmd (intern (concat "org-dblock-write:" name))))
8076 (message "Updating dynamic block `%s' at line %d..." name line)
8077 (funcall cmd params)
8078 (message "Updating dynamic block `%s' at line %d...done" name line)
8079 (goto-char pos))))
8080
8081 (defun org-beginning-of-dblock ()
8082 "Find the beginning of the dynamic block at point.
8083 Error if there is no such block at point."
8084 (let ((pos (point))
8085 beg)
8086 (end-of-line 1)
8087 (if (and (re-search-backward org-dblock-start-re nil t)
8088 (setq beg (match-beginning 0))
8089 (re-search-forward org-dblock-end-re nil t)
8090 (> (match-end 0) pos))
8091 (goto-char beg)
8092 (goto-char pos)
8093 (error "Not in a dynamic block"))))
8094
8095 (defun org-update-all-dblocks ()
8096 "Update all dynamic blocks in the buffer.
8097 This function can be used in a hook."
8098 (when (org-mode-p)
8099 (org-map-dblocks 'org-update-dblock)))
8100
8101
8102 ;;;; Completion
8103
8104 (defconst org-additional-option-like-keywords
8105 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8106 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8107 "BEGIN_EXAMPLE" "END_EXAMPLE"
8108 "BEGIN_QUOTE" "END_QUOTE"
8109 "BEGIN_VERSE" "END_VERSE"
8110 "BEGIN_SRC" "END_SRC"
8111 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8112
8113 (defcustom org-structure-template-alist
8114 '(
8115 ("s" "#+begin_src ?\n\n#+end_src"
8116 "<src lang=\"?\">\n\n</src>")
8117 ("e" "#+begin_example\n?\n#+end_example"
8118 "<example>\n?\n</example>")
8119 ("q" "#+begin_quote\n?\n#+end_quote"
8120 "<quote>\n?\n</quote>")
8121 ("v" "#+begin_verse\n?\n#+end_verse"
8122 "<verse>\n?\n/verse>")
8123 ("l" "#+begin_latex\n?\n#+end_latex"
8124 "<literal style=\"latex\">\n?\n</literal>")
8125 ("L" "#+latex: "
8126 "<literal style=\"latex\">?</literal>")
8127 ("h" "#+begin_html\n?\n#+end_html"
8128 "<literal style=\"html\">\n?\n</literal>")
8129 ("H" "#+html: "
8130 "<literal style=\"html\">?</literal>")
8131 ("a" "#+begin_ascii\n?\n#+end_ascii")
8132 ("A" "#+ascii: ")
8133 ("i" "#+include %file ?"
8134 "<include file=%file markup=\"?\">")
8135 )
8136 "Structure completion elements.
8137 This is a list of abbreviation keys and values. The value gets inserted
8138 it you type @samp{.} followed by the key and then the completion key,
8139 usually `M-TAB'. %file will be replaced by a file name after prompting
8140 for the file using completion.
8141 There are two templates for each key, the first uses the original Org syntax,
8142 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8143 the default when the /org-mtags.el/ module has been loaded. See also the
8144 variable `org-mtags-prefer-muse-templates'.
8145 This is an experimental feature, it is undecided if it is going to stay in."
8146 :group 'org-completion
8147 :type '(repeat
8148 (string :tag "Key")
8149 (string :tag "Template")
8150 (string :tag "Muse Template")))
8151
8152 (defun org-try-structure-completion ()
8153 "Try to complete a structure template before point.
8154 This looks for strings like \"<e\" on an otherwise empty line and
8155 expands them."
8156 (let ((l (buffer-substring (point-at-bol) (point)))
8157 a)
8158 (when (and (looking-at "[ \t]*$")
8159 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8160 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8161 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8162 (match-beginning 1)) a)
8163 t)))
8164
8165 (defun org-complete-expand-structure-template (start cell)
8166 "Expand a structure template."
8167 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8168 (rpl (nth (if musep 2 1) cell)))
8169 (delete-region start (point))
8170 (when (string-match "\\`#\\+" rpl)
8171 (cond
8172 ((bolp))
8173 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8174 (delete-region (point-at-bol) (point)))
8175 (t (newline))))
8176 (setq start (point))
8177 (if (string-match "%file" rpl)
8178 (setq rpl (replace-match
8179 (concat
8180 "\""
8181 (save-match-data
8182 (abbreviate-file-name (read-file-name "Include file: ")))
8183 "\"")
8184 t t rpl)))
8185 (insert rpl)
8186 (if (re-search-backward "\\?" start t) (delete-char 1))))
8187
8188
8189 (defun org-complete (&optional arg)
8190 "Perform completion on word at point.
8191 At the beginning of a headline, this completes TODO keywords as given in
8192 `org-todo-keywords'.
8193 If the current word is preceded by a backslash, completes the TeX symbols
8194 that are supported for HTML support.
8195 If the current word is preceded by \"#+\", completes special words for
8196 setting file options.
8197 In the line after \"#+STARTUP:, complete valid keywords.\"
8198 At all other locations, this simply calls the value of
8199 `org-completion-fallback-command'."
8200 (interactive "P")
8201 (org-without-partial-completion
8202 (catch 'exit
8203 (let* ((a nil)
8204 (end (point))
8205 (beg1 (save-excursion
8206 (skip-chars-backward (org-re "[:alnum:]_@"))
8207 (point)))
8208 (beg (save-excursion
8209 (skip-chars-backward "a-zA-Z0-9_:$")
8210 (point)))
8211 (confirm (lambda (x) (stringp (car x))))
8212 (searchhead (equal (char-before beg) ?*))
8213 (struct
8214 (when (and (member (char-before beg1) '(?. ?<))
8215 (setq a (assoc (buffer-substring beg1 (point))
8216 org-structure-template-alist)))
8217 (org-complete-expand-structure-template (1- beg1) a)
8218 (throw 'exit t)))
8219 (tag (and (equal (char-before beg1) ?:)
8220 (equal (char-after (point-at-bol)) ?*)))
8221 (prop (and (equal (char-before beg1) ?:)
8222 (not (equal (char-after (point-at-bol)) ?*))))
8223 (texp (equal (char-before beg) ?\\))
8224 (link (equal (char-before beg) ?\[))
8225 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8226 beg)
8227 "#+"))
8228 (startup (string-match "^#\\+STARTUP:.*"
8229 (buffer-substring (point-at-bol) (point))))
8230 (completion-ignore-case opt)
8231 (type nil)
8232 (tbl nil)
8233 (table (cond
8234 (opt
8235 (setq type :opt)
8236 (require 'org-exp)
8237 (append
8238 (mapcar
8239 (lambda (x)
8240 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8241 (cons (match-string 2 x) (match-string 1 x)))
8242 (org-split-string (org-get-current-options) "\n"))
8243 (mapcar 'list org-additional-option-like-keywords)))
8244 (startup
8245 (setq type :startup)
8246 org-startup-options)
8247 (link (append org-link-abbrev-alist-local
8248 org-link-abbrev-alist))
8249 (texp
8250 (setq type :tex)
8251 org-html-entities)
8252 ((string-match "\\`\\*+[ \t]+\\'"
8253 (buffer-substring (point-at-bol) beg))
8254 (setq type :todo)
8255 (mapcar 'list org-todo-keywords-1))
8256 (searchhead
8257 (setq type :searchhead)
8258 (save-excursion
8259 (goto-char (point-min))
8260 (while (re-search-forward org-todo-line-regexp nil t)
8261 (push (list
8262 (org-make-org-heading-search-string
8263 (match-string 3) t))
8264 tbl)))
8265 tbl)
8266 (tag (setq type :tag beg beg1)
8267 (or org-tag-alist (org-get-buffer-tags)))
8268 (prop (setq type :prop beg beg1)
8269 (mapcar 'list (org-buffer-property-keys nil t t)))
8270 (t (progn
8271 (call-interactively org-completion-fallback-command)
8272 (throw 'exit nil)))))
8273 (pattern (buffer-substring-no-properties beg end))
8274 (completion (try-completion pattern table confirm)))
8275 (cond ((eq completion t)
8276 (if (not (assoc (upcase pattern) table))
8277 (message "Already complete")
8278 (if (and (equal type :opt)
8279 (not (member (car (assoc (upcase pattern) table))
8280 org-additional-option-like-keywords)))
8281 (insert (substring (cdr (assoc (upcase pattern) table))
8282 (length pattern)))
8283 (if (memq type '(:tag :prop)) (insert ":")))))
8284 ((null completion)
8285 (message "Can't find completion for \"%s\"" pattern)
8286 (ding))
8287 ((not (string= pattern completion))
8288 (delete-region beg end)
8289 (if (string-match " +$" completion)
8290 (setq completion (replace-match "" t t completion)))
8291 (insert completion)
8292 (if (get-buffer-window "*Completions*")
8293 (delete-window (get-buffer-window "*Completions*")))
8294 (if (assoc completion table)
8295 (if (eq type :todo) (insert " ")
8296 (if (memq type '(:tag :prop)) (insert ":"))))
8297 (if (and (equal type :opt) (assoc completion table))
8298 (message "%s" (substitute-command-keys
8299 "Press \\[org-complete] again to insert example settings"))))
8300 (t
8301 (message "Making completion list...")
8302 (let ((list (sort (all-completions pattern table confirm)
8303 'string<)))
8304 (with-output-to-temp-buffer "*Completions*"
8305 (condition-case nil
8306 ;; Protection needed for XEmacs and emacs 21
8307 (display-completion-list list pattern)
8308 (error (display-completion-list list)))))
8309 (message "Making completion list...%s" "done")))))))
8310
8311 ;;;; TODO, DEADLINE, Comments
8312
8313 (defun org-toggle-comment ()
8314 "Change the COMMENT state of an entry."
8315 (interactive)
8316 (save-excursion
8317 (org-back-to-heading)
8318 (let (case-fold-search)
8319 (if (looking-at (concat outline-regexp
8320 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8321 (replace-match "" t t nil 1)
8322 (if (looking-at outline-regexp)
8323 (progn
8324 (goto-char (match-end 0))
8325 (insert org-comment-string " ")))))))
8326
8327 (defvar org-last-todo-state-is-todo nil
8328 "This is non-nil when the last TODO state change led to a TODO state.
8329 If the last change removed the TODO tag or switched to DONE, then
8330 this is nil.")
8331
8332 (defvar org-setting-tags nil) ; dynamically skipped
8333
8334 (defun org-parse-local-options (string var)
8335 "Parse STRING for startup setting relevant for variable VAR."
8336 (let ((rtn (symbol-value var))
8337 e opts)
8338 (save-match-data
8339 (if (or (not string) (not (string-match "\\S-" string)))
8340 rtn
8341 (setq opts (delq nil (mapcar (lambda (x)
8342 (setq e (assoc x org-startup-options))
8343 (if (eq (nth 1 e) var) e nil))
8344 (org-split-string string "[ \t]+"))))
8345 (if (not opts)
8346 rtn
8347 (setq rtn nil)
8348 (while (setq e (pop opts))
8349 (if (not (nth 3 e))
8350 (setq rtn (nth 2 e))
8351 (if (not (listp rtn)) (setq rtn nil))
8352 (push (nth 2 e) rtn)))
8353 rtn)))))
8354
8355 (defvar org-agenda-headline-snapshot-before-repeat)
8356 (defun org-todo (&optional arg)
8357 "Change the TODO state of an item.
8358 The state of an item is given by a keyword at the start of the heading,
8359 like
8360 *** TODO Write paper
8361 *** DONE Call mom
8362
8363 The different keywords are specified in the variable `org-todo-keywords'.
8364 By default the available states are \"TODO\" and \"DONE\".
8365 So for this example: when the item starts with TODO, it is changed to DONE.
8366 When it starts with DONE, the DONE is removed. And when neither TODO nor
8367 DONE are present, add TODO at the beginning of the heading.
8368
8369 With C-u prefix arg, use completion to determine the new state.
8370 With numeric prefix arg, switch to that state.
8371 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8372 With a tripple C-u prefix, circumvent any state blocking.
8373
8374 For calling through lisp, arg is also interpreted in the following way:
8375 'none -> empty state
8376 \"\"(empty string) -> switch to empty state
8377 'done -> switch to DONE
8378 'nextset -> switch to the next set of keywords
8379 'previousset -> switch to the previous set of keywords
8380 \"WAITING\" -> switch to the specified keyword, but only if it
8381 really is a member of `org-todo-keywords'."
8382 (interactive "P")
8383 (if (equal arg '(16)) (setq arg 'nextset))
8384 (let ((org-blocker-hook org-blocker-hook))
8385 (when (equal arg '(64))
8386 (setq arg nil org-blocker-hook nil))
8387 (save-excursion
8388 (catch 'exit
8389 (org-back-to-heading)
8390 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8391 (or (looking-at (concat " +" org-todo-regexp " *"))
8392 (looking-at " *"))
8393 (let* ((match-data (match-data))
8394 (startpos (point-at-bol))
8395 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8396 (org-log-done org-log-done)
8397 (org-log-repeat org-log-repeat)
8398 (org-todo-log-states org-todo-log-states)
8399 (this (match-string 1))
8400 (hl-pos (match-beginning 0))
8401 (head (org-get-todo-sequence-head this))
8402 (ass (assoc head org-todo-kwd-alist))
8403 (interpret (nth 1 ass))
8404 (done-word (nth 3 ass))
8405 (final-done-word (nth 4 ass))
8406 (last-state (or this ""))
8407 (completion-ignore-case t)
8408 (member (member this org-todo-keywords-1))
8409 (tail (cdr member))
8410 (state (cond
8411 ((and org-todo-key-trigger
8412 (or (and (equal arg '(4))
8413 (eq org-use-fast-todo-selection 'prefix))
8414 (and (not arg) org-use-fast-todo-selection
8415 (not (eq org-use-fast-todo-selection
8416 'prefix)))))
8417 ;; Use fast selection
8418 (org-fast-todo-selection))
8419 ((and (equal arg '(4))
8420 (or (not org-use-fast-todo-selection)
8421 (not org-todo-key-trigger)))
8422 ;; Read a state with completion
8423 (org-ido-completing-read
8424 "State: " (mapcar (lambda(x) (list x))
8425 org-todo-keywords-1)
8426 nil t))
8427 ((eq arg 'right)
8428 (if this
8429 (if tail (car tail) nil)
8430 (car org-todo-keywords-1)))
8431 ((eq arg 'left)
8432 (if (equal member org-todo-keywords-1)
8433 nil
8434 (if this
8435 (nth (- (length org-todo-keywords-1)
8436 (length tail) 2)
8437 org-todo-keywords-1)
8438 (org-last org-todo-keywords-1))))
8439 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8440 (setq arg nil))) ; hack to fall back to cycling
8441 (arg
8442 ;; user or caller requests a specific state
8443 (cond
8444 ((equal arg "") nil)
8445 ((eq arg 'none) nil)
8446 ((eq arg 'done) (or done-word (car org-done-keywords)))
8447 ((eq arg 'nextset)
8448 (or (car (cdr (member head org-todo-heads)))
8449 (car org-todo-heads)))
8450 ((eq arg 'previousset)
8451 (let ((org-todo-heads (reverse org-todo-heads)))
8452 (or (car (cdr (member head org-todo-heads)))
8453 (car org-todo-heads))))
8454 ((car (member arg org-todo-keywords-1)))
8455 ((nth (1- (prefix-numeric-value arg))
8456 org-todo-keywords-1))))
8457 ((null member) (or head (car org-todo-keywords-1)))
8458 ((equal this final-done-word) nil) ;; -> make empty
8459 ((null tail) nil) ;; -> first entry
8460 ((eq interpret 'sequence)
8461 (car tail))
8462 ((memq interpret '(type priority))
8463 (if (eq this-command last-command)
8464 (car tail)
8465 (if (> (length tail) 0)
8466 (or done-word (car org-done-keywords))
8467 nil)))
8468 (t nil)))
8469 (next (if state (concat " " state " ") " "))
8470 (change-plist (list :type 'todo-state-change :from this :to state
8471 :position startpos))
8472 dolog now-done-p)
8473 (when org-blocker-hook
8474 (setq org-last-todo-state-is-todo
8475 (not (member this org-done-keywords)))
8476 (unless (save-excursion
8477 (save-match-data
8478 (run-hook-with-args-until-failure
8479 'org-blocker-hook change-plist)))
8480 (if (interactive-p)
8481 (error "TODO state change from %s to %s blocked" this state)
8482 ;; fail silently
8483 (message "TODO state change from %s to %s blocked" this state)
8484 (throw 'exit nil))))
8485 (store-match-data match-data)
8486 (replace-match next t t)
8487 (unless (pos-visible-in-window-p hl-pos)
8488 (message "TODO state changed to %s" (org-trim next)))
8489 (unless head
8490 (setq head (org-get-todo-sequence-head state)
8491 ass (assoc head org-todo-kwd-alist)
8492 interpret (nth 1 ass)
8493 done-word (nth 3 ass)
8494 final-done-word (nth 4 ass)))
8495 (when (memq arg '(nextset previousset))
8496 (message "Keyword-Set %d/%d: %s"
8497 (- (length org-todo-sets) -1
8498 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8499 (length org-todo-sets)
8500 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8501 (setq org-last-todo-state-is-todo
8502 (not (member state org-done-keywords)))
8503 (setq now-done-p (and (member state org-done-keywords)
8504 (not (member this org-done-keywords))))
8505 (and logging (org-local-logging logging))
8506 (when (and (or org-todo-log-states org-log-done)
8507 (not (memq arg '(nextset previousset))))
8508 ;; we need to look at recording a time and note
8509 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8510 (nth 2 (assoc this org-todo-log-states))))
8511 (when (and state
8512 (member state org-not-done-keywords)
8513 (not (member this org-not-done-keywords)))
8514 ;; This is now a todo state and was not one before
8515 ;; If there was a CLOSED time stamp, get rid of it.
8516 (org-add-planning-info nil nil 'closed))
8517 (when (and now-done-p org-log-done)
8518 ;; It is now done, and it was not done before
8519 (org-add-planning-info 'closed (org-current-time))
8520 (if (and (not dolog) (eq 'note org-log-done))
8521 (org-add-log-setup 'done state 'findpos 'note)))
8522 (when (and state dolog)
8523 ;; This is a non-nil state, and we need to log it
8524 (org-add-log-setup 'state state 'findpos dolog)))
8525 ;; Fixup tag positioning
8526 (org-todo-trigger-tag-changes state)
8527 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8528 (when org-provide-todo-statistics
8529 (org-update-parent-todo-statistics))
8530 (run-hooks 'org-after-todo-state-change-hook)
8531 (if (and arg (not (member state org-done-keywords)))
8532 (setq head (org-get-todo-sequence-head state)))
8533 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8534 ;; Do we need to trigger a repeat?
8535 (when now-done-p
8536 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8537 ;; This is for the agenda, take a snapshot of the headline.
8538 (save-match-data
8539 (setq org-agenda-headline-snapshot-before-repeat
8540 (org-get-heading))))
8541 (org-auto-repeat-maybe state))
8542 ;; Fixup cursor location if close to the keyword
8543 (if (and (outline-on-heading-p)
8544 (not (bolp))
8545 (save-excursion (beginning-of-line 1)
8546 (looking-at org-todo-line-regexp))
8547 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8548 (progn
8549 (goto-char (or (match-end 2) (match-end 1)))
8550 (just-one-space)))
8551 (when org-trigger-hook
8552 (save-excursion
8553 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8554
8555 (defun org-block-todo-from-children-or-siblings (change-plist)
8556 "Block turning an entry into a TODO, using the hierarchy.
8557 This checks whether the current task should be blocked from state
8558 changes. Such blocking occurs when:
8559
8560 1. The task has children which are not all in a completed state.
8561
8562 2. A task has a parent with the property :ORDERED:, and there
8563 are siblings prior to the current task with incomplete
8564 status."
8565 (catch 'dont-block
8566 ;; If this is not a todo state change, or if this entry is already DONE,
8567 ;; do not block
8568 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8569 (member (plist-get change-plist :from)
8570 (cons 'done org-done-keywords))
8571 (member (plist-get change-plist :to)
8572 (cons 'todo org-not-done-keywords)))
8573 (throw 'dont-block t))
8574 ;; If this task has children, and any are undone, it's blocked
8575 (save-excursion
8576 (org-back-to-heading t)
8577 (let ((this-level (funcall outline-level)))
8578 (outline-next-heading)
8579 (let ((child-level (funcall outline-level)))
8580 (while (and (not (eobp))
8581 (> child-level this-level))
8582 ;; this todo has children, check whether they are all
8583 ;; completed
8584 (if (and (not (org-entry-is-done-p))
8585 (org-entry-is-todo-p))
8586 (throw 'dont-block nil))
8587 (outline-next-heading)
8588 (setq child-level (funcall outline-level))))))
8589 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8590 ;; any previous siblings are undone, it's blocked
8591 (save-excursion
8592 (org-back-to-heading t)
8593 (when (save-excursion
8594 (ignore-errors
8595 (org-up-heading-all 1)
8596 (org-entry-get (point) "ORDERED")))
8597 (let* ((this-level (funcall outline-level))
8598 (current-level this-level))
8599 (while (and (not (bobp))
8600 (= current-level this-level))
8601 (outline-previous-heading)
8602 (setq current-level (funcall outline-level))
8603 (if (= current-level this-level)
8604 ;; this todo has children, check whether they are all
8605 ;; completed
8606 (if (and (not (org-entry-is-done-p))
8607 (org-entry-is-todo-p))
8608 (throw 'dont-block nil)))))))
8609 t)) ; don't block
8610
8611 (defun org-toggle-ordered-property ()
8612 "Toggle the ORDERED property of the current entry."
8613 (interactive)
8614 (save-excursion
8615 (org-back-to-heading)
8616 (if (org-entry-get nil "ORDERED")
8617 (progn
8618 (org-delete-property "ORDERED")
8619 (message "Subtasks can be completed in arbitrary order or parallel"))
8620 (org-entry-put nil "ORDERED" "t")
8621 (message "Subtasks must be completed in sequence"))))
8622
8623 (defun org-block-todo-from-checkboxes (change-plist)
8624 "Block turning an entry into a TODO, using checkboxes.
8625 This checks whether the current task should be blocked from state
8626 changes because there are uncheckd boxes in this entry."
8627 (catch 'dont-block
8628 ;; If this is not a todo state change, or if this entry is already DONE,
8629 ;; do not block
8630 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8631 (member (plist-get change-plist :from)
8632 (cons 'done org-done-keywords))
8633 (member (plist-get change-plist :to)
8634 (cons 'todo org-not-done-keywords)))
8635 (throw 'dont-block t))
8636 ;; If this task has checkboxes that are not checked, it's blocked
8637 (save-excursion
8638 (org-back-to-heading t)
8639 (let ((beg (point)) end)
8640 (outline-next-heading)
8641 (setq end (point))
8642 (goto-char beg)
8643 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
8644 end t)
8645 (throw 'dont-block nil))))
8646 t)) ; do not block
8647
8648 (defun org-update-parent-todo-statistics ()
8649 "Update any statistics cookie in the parent of the current headline."
8650 (interactive)
8651 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8652 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
8653 (catch 'exit
8654 (save-excursion
8655 (setq level (org-up-heading-safe))
8656 (unless level
8657 (throw 'exit nil))
8658 (while (re-search-forward box-re (point-at-eol) t)
8659 (setq cnt-all 0 cnt-done 0 cookie-present t)
8660 (setq is-percent (match-end 2))
8661 (save-match-data
8662 (unless (outline-next-heading) (throw 'exit nil))
8663 (while (looking-at org-todo-line-regexp)
8664 (setq kwd (match-string 2))
8665 (and kwd (setq cnt-all (1+ cnt-all)))
8666 (and (member kwd org-done-keywords)
8667 (setq cnt-done (1+ cnt-done)))
8668 (condition-case nil
8669 (org-forward-same-level 1)
8670 (error (end-of-line 1)))))
8671 (replace-match
8672 (if is-percent
8673 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8674 (format "[%d/%d]" cnt-done cnt-all))))
8675 (when cookie-present
8676 (run-hook-with-args 'org-after-todo-statistics-hook
8677 cnt-done (- cnt-all cnt-done)))))))
8678
8679 (defvar org-after-todo-statistics-hook nil
8680 "Hook that is called after a TODO statistics cookie has been updated.
8681 Each function is called with two arguments: the number of not-done entries
8682 and the number of done entries.
8683
8684 For example, the following function, when added to this hook, will switch
8685 an entry to DONE when all children are done, and back to TODO when new
8686 entries are set to a TODO status. Note that this hook is only called
8687 when there is a statistics cookie in the headline!
8688
8689 (defun org-summary-todo (n-done n-not-done)
8690 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8691 (let (org-log-done org-log-states) ; turn off logging
8692 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8693 ")
8694
8695 (defun org-todo-trigger-tag-changes (state)
8696 "Apply the changes defined in `org-todo-state-tags-triggers'."
8697 (let ((l org-todo-state-tags-triggers)
8698 changes)
8699 (when (or (not state) (equal state ""))
8700 (setq changes (append changes (cdr (assoc "" l)))))
8701 (when (and (stringp state) (> (length state) 0))
8702 (setq changes (append changes (cdr (assoc state l)))))
8703 (when (member state org-not-done-keywords)
8704 (setq changes (append changes (cdr (assoc 'todo l)))))
8705 (when (member state org-done-keywords)
8706 (setq changes (append changes (cdr (assoc 'done l)))))
8707 (dolist (c changes)
8708 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8709
8710 (defun org-local-logging (value)
8711 "Get logging settings from a property VALUE."
8712 (let* (words w a)
8713 ;; directly set the variables, they are already local.
8714 (setq org-log-done nil
8715 org-log-repeat nil
8716 org-todo-log-states nil)
8717 (setq words (org-split-string value))
8718 (while (setq w (pop words))
8719 (cond
8720 ((setq a (assoc w org-startup-options))
8721 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8722 (set (nth 1 a) (nth 2 a))))
8723 ((setq a (org-extract-log-state-settings w))
8724 (and (member (car a) org-todo-keywords-1)
8725 (push a org-todo-log-states)))))))
8726
8727 (defun org-get-todo-sequence-head (kwd)
8728 "Return the head of the TODO sequence to which KWD belongs.
8729 If KWD is not set, check if there is a text property remembering the
8730 right sequence."
8731 (let (p)
8732 (cond
8733 ((not kwd)
8734 (or (get-text-property (point-at-bol) 'org-todo-head)
8735 (progn
8736 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8737 nil (point-at-eol)))
8738 (get-text-property p 'org-todo-head))))
8739 ((not (member kwd org-todo-keywords-1))
8740 (car org-todo-keywords-1))
8741 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8742
8743 (defun org-fast-todo-selection ()
8744 "Fast TODO keyword selection with single keys.
8745 Returns the new TODO keyword, or nil if no state change should occur."
8746 (let* ((fulltable org-todo-key-alist)
8747 (done-keywords org-done-keywords) ;; needed for the faces.
8748 (maxlen (apply 'max (mapcar
8749 (lambda (x)
8750 (if (stringp (car x)) (string-width (car x)) 0))
8751 fulltable)))
8752 (expert nil)
8753 (fwidth (+ maxlen 3 1 3))
8754 (ncol (/ (- (window-width) 4) fwidth))
8755 tg cnt e c tbl
8756 groups ingroup)
8757 (save-excursion
8758 (save-window-excursion
8759 (if expert
8760 (set-buffer (get-buffer-create " *Org todo*"))
8761 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8762 (erase-buffer)
8763 (org-set-local 'org-done-keywords done-keywords)
8764 (setq tbl fulltable cnt 0)
8765 (while (setq e (pop tbl))
8766 (cond
8767 ((equal e '(:startgroup))
8768 (push '() groups) (setq ingroup t)
8769 (when (not (= cnt 0))
8770 (setq cnt 0)
8771 (insert "\n"))
8772 (insert "{ "))
8773 ((equal e '(:endgroup))
8774 (setq ingroup nil cnt 0)
8775 (insert "}\n"))
8776 (t
8777 (setq tg (car e) c (cdr e))
8778 (if ingroup (push tg (car groups)))
8779 (setq tg (org-add-props tg nil 'face
8780 (org-get-todo-face tg)))
8781 (if (and (= cnt 0) (not ingroup)) (insert " "))
8782 (insert "[" c "] " tg (make-string
8783 (- fwidth 4 (length tg)) ?\ ))
8784 (when (= (setq cnt (1+ cnt)) ncol)
8785 (insert "\n")
8786 (if ingroup (insert " "))
8787 (setq cnt 0)))))
8788 (insert "\n")
8789 (goto-char (point-min))
8790 (if (not expert) (org-fit-window-to-buffer))
8791 (message "[a-z..]:Set [SPC]:clear")
8792 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8793 (cond
8794 ((or (= c ?\C-g)
8795 (and (= c ?q) (not (rassoc c fulltable))))
8796 (setq quit-flag t))
8797 ((= c ?\ ) nil)
8798 ((setq e (rassoc c fulltable) tg (car e))
8799 tg)
8800 (t (setq quit-flag t)))))))
8801
8802 (defun org-entry-is-todo-p ()
8803 (member (org-get-todo-state) org-not-done-keywords))
8804
8805 (defun org-entry-is-done-p ()
8806 (member (org-get-todo-state) org-done-keywords))
8807
8808 (defun org-get-todo-state ()
8809 (save-excursion
8810 (org-back-to-heading t)
8811 (and (looking-at org-todo-line-regexp)
8812 (match-end 2)
8813 (match-string 2))))
8814
8815 (defun org-at-date-range-p (&optional inactive-ok)
8816 "Is the cursor inside a date range?"
8817 (interactive)
8818 (save-excursion
8819 (catch 'exit
8820 (let ((pos (point)))
8821 (skip-chars-backward "^[<\r\n")
8822 (skip-chars-backward "<[")
8823 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8824 (>= (match-end 0) pos)
8825 (throw 'exit t))
8826 (skip-chars-backward "^<[\r\n")
8827 (skip-chars-backward "<[")
8828 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8829 (>= (match-end 0) pos)
8830 (throw 'exit t)))
8831 nil)))
8832
8833 (defun org-get-repeat ()
8834 "Check if there is a deadline/schedule with repeater in this entry."
8835 (save-match-data
8836 (save-excursion
8837 (org-back-to-heading t)
8838 (if (re-search-forward
8839 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8840 (match-string 1)))))
8841
8842 (defvar org-last-changed-timestamp)
8843 (defvar org-last-inserted-timestamp)
8844 (defvar org-log-post-message)
8845 (defvar org-log-note-purpose)
8846 (defvar org-log-note-how)
8847 (defvar org-log-note-extra)
8848 (defun org-auto-repeat-maybe (done-word)
8849 "Check if the current headline contains a repeated deadline/schedule.
8850 If yes, set TODO state back to what it was and change the base date
8851 of repeating deadline/scheduled time stamps to new date.
8852 This function is run automatically after each state change to a DONE state."
8853 ;; last-state is dynamically scoped into this function
8854 (let* ((repeat (org-get-repeat))
8855 (aa (assoc last-state org-todo-kwd-alist))
8856 (interpret (nth 1 aa))
8857 (head (nth 2 aa))
8858 (whata '(("d" . day) ("m" . month) ("y" . year)))
8859 (msg "Entry repeats: ")
8860 (org-log-done nil)
8861 (org-todo-log-states nil)
8862 (nshiftmax 10) (nshift 0)
8863 re type n what ts time)
8864 (when repeat
8865 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8866 (org-todo (if (eq interpret 'type) last-state head))
8867 (when org-log-repeat
8868 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8869 (memq 'org-add-log-note post-command-hook))
8870 ;; OK, we are already setup for some record
8871 (if (eq org-log-repeat 'note)
8872 ;; make sure we take a note, not only a time stamp
8873 (setq org-log-note-how 'note))
8874 ;; Set up for taking a record
8875 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8876 'findpos org-log-repeat)))
8877 (org-back-to-heading t)
8878 (org-add-planning-info nil nil 'closed)
8879 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8880 org-deadline-time-regexp "\\)\\|\\("
8881 org-ts-regexp "\\)"))
8882 (while (re-search-forward
8883 re (save-excursion (outline-next-heading) (point)) t)
8884 (setq type (if (match-end 1) org-scheduled-string
8885 (if (match-end 3) org-deadline-string "Plain:"))
8886 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
8887 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8888 (setq n (string-to-number (match-string 2 ts))
8889 what (match-string 3 ts))
8890 (if (equal what "w") (setq n (* n 7) what "d"))
8891 ;; Preparation, see if we need to modify the start date for the change
8892 (when (match-end 1)
8893 (setq time (save-match-data (org-time-string-to-time ts)))
8894 (cond
8895 ((equal (match-string 1 ts) ".")
8896 ;; Shift starting date to today
8897 (org-timestamp-change
8898 (- (time-to-days (current-time)) (time-to-days time))
8899 'day))
8900 ((equal (match-string 1 ts) "+")
8901 (while (or (= nshift 0)
8902 (<= (time-to-days time) (time-to-days (current-time))))
8903 (when (= (incf nshift) nshiftmax)
8904 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8905 (error "Abort")))
8906 (org-timestamp-change n (cdr (assoc what whata)))
8907 (org-at-timestamp-p t)
8908 (setq ts (match-string 1))
8909 (setq time (save-match-data (org-time-string-to-time ts))))
8910 (org-timestamp-change (- n) (cdr (assoc what whata)))
8911 ;; rematch, so that we have everything in place for the real shift
8912 (org-at-timestamp-p t)
8913 (setq ts (match-string 1))
8914 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8915 (org-timestamp-change n (cdr (assoc what whata)))
8916 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8917 (setq org-log-post-message msg)
8918 (message "%s" msg))))
8919
8920 (defun org-show-todo-tree (arg)
8921 "Make a compact tree which shows all headlines marked with TODO.
8922 The tree will show the lines where the regexp matches, and all higher
8923 headlines above the match.
8924 With a \\[universal-argument] prefix, also show the DONE entries.
8925 With a numeric prefix N, construct a sparse tree for the Nth element
8926 of `org-todo-keywords-1'."
8927 (interactive "P")
8928 (let ((case-fold-search nil)
8929 (kwd-re
8930 (cond ((null arg) org-not-done-regexp)
8931 ((equal arg '(4))
8932 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8933 (mapcar 'list org-todo-keywords-1))))
8934 (concat "\\("
8935 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8936 "\\)\\>")))
8937 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8938 (regexp-quote (nth (1- (prefix-numeric-value arg))
8939 org-todo-keywords-1)))
8940 (t (error "Invalid prefix argument: %s" arg)))))
8941 (message "%d TODO entries found"
8942 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8943
8944 (defun org-deadline (&optional remove time)
8945 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8946 With argument REMOVE, remove any deadline from the item.
8947 When TIME is set, it should be an internal time specification, and the
8948 scheduling will use the corresponding date."
8949 (interactive "P")
8950 (if remove
8951 (progn
8952 (org-remove-timestamp-with-keyword org-deadline-string)
8953 (message "Item no longer has a deadline."))
8954 (if (org-get-repeat)
8955 (error "Cannot change deadline on task with repeater, please do that by hand")
8956 (org-add-planning-info 'deadline time 'closed)
8957 (message "Deadline on %s" org-last-inserted-timestamp))))
8958
8959 (defun org-schedule (&optional remove time)
8960 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8961 With argument REMOVE, remove any scheduling date from the item.
8962 When TIME is set, it should be an internal time specification, and the
8963 scheduling will use the corresponding date."
8964 (interactive "P")
8965 (if remove
8966 (progn
8967 (org-remove-timestamp-with-keyword org-scheduled-string)
8968 (message "Item is no longer scheduled."))
8969 (if (org-get-repeat)
8970 (error "Cannot reschedule task with repeater, please do that by hand")
8971 (org-add-planning-info 'scheduled time 'closed)
8972 (message "Scheduled to %s" org-last-inserted-timestamp))))
8973
8974 (defun org-remove-timestamp-with-keyword (keyword)
8975 "Remove all time stamps with KEYWORD in the current entry."
8976 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8977 beg)
8978 (save-excursion
8979 (org-back-to-heading t)
8980 (setq beg (point))
8981 (org-end-of-subtree t t)
8982 (while (re-search-backward re beg t)
8983 (replace-match "")
8984 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8985 (equal (char-before) ?\ ))
8986 (backward-delete-char 1)
8987 (if (string-match "^[ \t]*$" (buffer-substring
8988 (point-at-bol) (point-at-eol)))
8989 (delete-region (point-at-bol)
8990 (min (point-max) (1+ (point-at-eol))))))))))
8991
8992 (defun org-add-planning-info (what &optional time &rest remove)
8993 "Insert new timestamp with keyword in the line directly after the headline.
8994 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8995 If non is given, the user is prompted for a date.
8996 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8997 be removed."
8998 (interactive)
8999 (let (org-time-was-given org-end-time-was-given ts
9000 end default-time default-input)
9001
9002 (when (and (not time) (memq what '(scheduled deadline)))
9003 ;; Try to get a default date/time from existing timestamp
9004 (save-excursion
9005 (org-back-to-heading t)
9006 (setq end (save-excursion (outline-next-heading) (point)))
9007 (when (re-search-forward (if (eq what 'scheduled)
9008 org-scheduled-time-regexp
9009 org-deadline-time-regexp)
9010 end t)
9011 (setq ts (match-string 1)
9012 default-time
9013 (apply 'encode-time (org-parse-time-string ts))
9014 default-input (and ts (org-get-compact-tod ts))))))
9015 (when what
9016 ;; If necessary, get the time from the user
9017 (setq time (or time (org-read-date nil 'to-time nil nil
9018 default-time default-input))))
9019
9020 (when (and org-insert-labeled-timestamps-at-point
9021 (member what '(scheduled deadline)))
9022 (insert
9023 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9024 (org-insert-time-stamp time org-time-was-given
9025 nil nil nil (list org-end-time-was-given))
9026 (setq what nil))
9027 (save-excursion
9028 (save-restriction
9029 (let (col list elt ts buffer-invisibility-spec)
9030 (org-back-to-heading t)
9031 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9032 (goto-char (match-end 1))
9033 (setq col (current-column))
9034 (goto-char (match-end 0))
9035 (if (eobp) (insert "\n") (forward-char 1))
9036 (if (and (not (looking-at outline-regexp))
9037 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9038 "[^\r\n]*"))
9039 (not (equal (match-string 1) org-clock-string)))
9040 (narrow-to-region (match-beginning 0) (match-end 0))
9041 (insert-before-markers "\n")
9042 (backward-char 1)
9043 (narrow-to-region (point) (point))
9044 (and org-adapt-indentation (org-indent-to-column col)))
9045 ;; Check if we have to remove something.
9046 (setq list (cons what remove))
9047 (while list
9048 (setq elt (pop list))
9049 (goto-char (point-min))
9050 (when (or (and (eq elt 'scheduled)
9051 (re-search-forward org-scheduled-time-regexp nil t))
9052 (and (eq elt 'deadline)
9053 (re-search-forward org-deadline-time-regexp nil t))
9054 (and (eq elt 'closed)
9055 (re-search-forward org-closed-time-regexp nil t)))
9056 (replace-match "")
9057 (if (looking-at "--+<[^>]+>") (replace-match ""))
9058 (if (looking-at " +") (replace-match ""))))
9059 (goto-char (point-max))
9060 (when what
9061 (insert
9062 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9063 (cond ((eq what 'scheduled) org-scheduled-string)
9064 ((eq what 'deadline) org-deadline-string)
9065 ((eq what 'closed) org-closed-string))
9066 " ")
9067 (setq ts (org-insert-time-stamp
9068 time
9069 (or org-time-was-given
9070 (and (eq what 'closed) org-log-done-with-time))
9071 (eq what 'closed)
9072 nil nil (list org-end-time-was-given)))
9073 (end-of-line 1))
9074 (goto-char (point-min))
9075 (widen)
9076 (if (and (looking-at "[ \t]+\n")
9077 (equal (char-before) ?\n))
9078 (delete-region (1- (point)) (point-at-eol)))
9079 ts)))))
9080
9081 (defvar org-log-note-marker (make-marker))
9082 (defvar org-log-note-purpose nil)
9083 (defvar org-log-note-state nil)
9084 (defvar org-log-note-how nil)
9085 (defvar org-log-note-extra nil)
9086 (defvar org-log-note-window-configuration nil)
9087 (defvar org-log-note-return-to (make-marker))
9088 (defvar org-log-post-message nil
9089 "Message to be displayed after a log note has been stored.
9090 The auto-repeater uses this.")
9091
9092 (defun org-add-note ()
9093 "Add a note to the current entry.
9094 This is done in the same way as adding a state change note."
9095 (interactive)
9096 (org-add-log-setup 'note nil 'findpos nil))
9097
9098 (defvar org-property-end-re)
9099 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
9100 "Set up the post command hook to take a note.
9101 If this is about to TODO state change, the new state is expected in STATE.
9102 When FINDPOS is non-nil, find the correct position for the note in
9103 the current entry. If not, assume that it can be inserted at point.
9104 HOW is an indicator what kind of note should be created.
9105 EXTRA is additional text that will be inserted into the notes buffer."
9106 (save-restriction
9107 (save-excursion
9108 (when findpos
9109 (org-back-to-heading t)
9110 (narrow-to-region (point) (save-excursion
9111 (outline-next-heading) (point)))
9112 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9113 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9114 "[^\r\n]*\\)?"))
9115 (goto-char (match-end 0))
9116 (when (and org-log-state-notes-insert-after-drawers
9117 (save-excursion
9118 (forward-line) (looking-at org-drawer-regexp)))
9119 (progn (forward-line)
9120 (while (looking-at org-drawer-regexp)
9121 (goto-char (match-end 0))
9122 (re-search-forward org-property-end-re (point-max) t)
9123 (forward-line))
9124 (forward-line -1)))
9125 (unless org-log-states-order-reversed
9126 (and (= (char-after) ?\n) (forward-char 1))
9127 (org-skip-over-state-notes)
9128 (skip-chars-backward " \t\n\r")))
9129 (move-marker org-log-note-marker (point))
9130 (setq org-log-note-purpose purpose
9131 org-log-note-state state
9132 org-log-note-how how
9133 org-log-note-extra extra)
9134 (add-hook 'post-command-hook 'org-add-log-note 'append))))
9135
9136 (defun org-skip-over-state-notes ()
9137 "Skip past the list of State notes in an entry."
9138 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9139 (while (looking-at "[ \t]*- State")
9140 (condition-case nil
9141 (org-next-item)
9142 (error (org-end-of-item)))))
9143
9144 (defun org-add-log-note (&optional purpose)
9145 "Pop up a window for taking a note, and add this note later at point."
9146 (remove-hook 'post-command-hook 'org-add-log-note)
9147 (setq org-log-note-window-configuration (current-window-configuration))
9148 (delete-other-windows)
9149 (move-marker org-log-note-return-to (point))
9150 (switch-to-buffer (marker-buffer org-log-note-marker))
9151 (goto-char org-log-note-marker)
9152 (org-switch-to-buffer-other-window "*Org Note*")
9153 (erase-buffer)
9154 (if (memq org-log-note-how '(time state))
9155 (let (current-prefix-arg) (org-store-log-note))
9156 (let ((org-inhibit-startup t)) (org-mode))
9157 (insert (format "# Insert note for %s.
9158 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9159 (cond
9160 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9161 ((eq org-log-note-purpose 'done) "closed todo item")
9162 ((eq org-log-note-purpose 'state)
9163 (format "state change to \"%s\"" org-log-note-state))
9164 ((eq org-log-note-purpose 'note)
9165 "this entry")
9166 (t (error "This should not happen")))))
9167 (if org-log-note-extra (insert org-log-note-extra))
9168 (org-set-local 'org-finish-function 'org-store-log-note)))
9169
9170 (defvar org-note-abort nil) ; dynamically scoped
9171 (defun org-store-log-note ()
9172 "Finish taking a log note, and insert it to where it belongs."
9173 (let ((txt (buffer-string))
9174 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9175 lines ind)
9176 (kill-buffer (current-buffer))
9177 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9178 (setq txt (replace-match "" t t txt)))
9179 (if (string-match "\\s-+\\'" txt)
9180 (setq txt (replace-match "" t t txt)))
9181 (setq lines (org-split-string txt "\n"))
9182 (when (and note (string-match "\\S-" note))
9183 (setq note
9184 (org-replace-escapes
9185 note
9186 (list (cons "%u" (user-login-name))
9187 (cons "%U" user-full-name)
9188 (cons "%t" (format-time-string
9189 (org-time-stamp-format 'long 'inactive)
9190 (current-time)))
9191 (cons "%s" (if org-log-note-state
9192 (concat "\"" org-log-note-state "\"")
9193 "")))))
9194 (if lines (setq note (concat note " \\\\")))
9195 (push note lines))
9196 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9197 (when lines
9198 (save-excursion
9199 (set-buffer (marker-buffer org-log-note-marker))
9200 (save-excursion
9201 (goto-char org-log-note-marker)
9202 (move-marker org-log-note-marker nil)
9203 (end-of-line 1)
9204 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9205 (indent-relative nil)
9206 (insert "- " (pop lines))
9207 (org-indent-line-function)
9208 (beginning-of-line 1)
9209 (looking-at "[ \t]*")
9210 (setq ind (concat (match-string 0) " "))
9211 (end-of-line 1)
9212 (while lines (insert "\n" ind (pop lines)))))))
9213 (set-window-configuration org-log-note-window-configuration)
9214 (with-current-buffer (marker-buffer org-log-note-return-to)
9215 (goto-char org-log-note-return-to))
9216 (move-marker org-log-note-return-to nil)
9217 (and org-log-post-message (message "%s" org-log-post-message)))
9218
9219 (defun org-sparse-tree (&optional arg)
9220 "Create a sparse tree, prompt for the details.
9221 This command can create sparse trees. You first need to select the type
9222 of match used to create the tree:
9223
9224 t Show entries with a specific TODO keyword.
9225 T Show entries selected by a tags match.
9226 p Enter a property name and its value (both with completion on existing
9227 names/values) and show entries with that property.
9228 r Show entries matching a regular expression
9229 d Show deadlines due within `org-deadline-warning-days'."
9230 (interactive "P")
9231 (let (ans kwd value)
9232 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9233 (setq ans (read-char-exclusive))
9234 (cond
9235 ((equal ans ?d)
9236 (call-interactively 'org-check-deadlines))
9237 ((equal ans ?b)
9238 (call-interactively 'org-check-before-date))
9239 ((equal ans ?t)
9240 (org-show-todo-tree '(4)))
9241 ((equal ans ?T)
9242 (call-interactively 'org-tags-sparse-tree))
9243 ((member ans '(?p ?P))
9244 (setq kwd (org-ido-completing-read "Property: "
9245 (mapcar 'list (org-buffer-property-keys))))
9246 (setq value (org-ido-completing-read "Value: "
9247 (mapcar 'list (org-property-values kwd))))
9248 (unless (string-match "\\`{.*}\\'" value)
9249 (setq value (concat "\"" value "\"")))
9250 (org-tags-sparse-tree arg (concat kwd "=" value)))
9251 ((member ans '(?r ?R ?/))
9252 (call-interactively 'org-occur))
9253 (t (error "No such sparse tree command \"%c\"" ans)))))
9254
9255 (defvar org-occur-highlights nil
9256 "List of overlays used for occur matches.")
9257 (make-variable-buffer-local 'org-occur-highlights)
9258 (defvar org-occur-parameters nil
9259 "Parameters of the active org-occur calls.
9260 This is a list, each call to org-occur pushes as cons cell,
9261 containing the regular expression and the callback, onto the list.
9262 The list can contain several entries if `org-occur' has been called
9263 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9264 will only contain one set of parameters. When the highlights are
9265 removed (for example with `C-c C-c', or with the next edit (depending
9266 on `org-remove-highlights-with-change'), this variable is emptied
9267 as well.")
9268 (make-variable-buffer-local 'org-occur-parameters)
9269
9270 (defun org-occur (regexp &optional keep-previous callback)
9271 "Make a compact tree which shows all matches of REGEXP.
9272 The tree will show the lines where the regexp matches, and all higher
9273 headlines above the match. It will also show the heading after the match,
9274 to make sure editing the matching entry is easy.
9275 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9276 call to `org-occur' will be kept, to allow stacking of calls to this
9277 command.
9278 If CALLBACK is non-nil, it is a function which is called to confirm
9279 that the match should indeed be shown."
9280 (interactive "sRegexp: \nP")
9281 (unless keep-previous
9282 (org-remove-occur-highlights nil nil t))
9283 (push (cons regexp callback) org-occur-parameters)
9284 (let ((cnt 0))
9285 (save-excursion
9286 (goto-char (point-min))
9287 (if (or (not keep-previous) ; do not want to keep
9288 (not org-occur-highlights)) ; no previous matches
9289 ;; hide everything
9290 (org-overview))
9291 (while (re-search-forward regexp nil t)
9292 (when (or (not callback)
9293 (save-match-data (funcall callback)))
9294 (setq cnt (1+ cnt))
9295 (when org-highlight-sparse-tree-matches
9296 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9297 (org-show-context 'occur-tree))))
9298 (when org-remove-highlights-with-change
9299 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9300 nil 'local))
9301 (unless org-sparse-tree-open-archived-trees
9302 (org-hide-archived-subtrees (point-min) (point-max)))
9303 (run-hooks 'org-occur-hook)
9304 (if (interactive-p)
9305 (message "%d match(es) for regexp %s" cnt regexp))
9306 cnt))
9307
9308 (defun org-show-context (&optional key)
9309 "Make sure point and context and visible.
9310 How much context is shown depends upon the variables
9311 `org-show-hierarchy-above', `org-show-following-heading'. and
9312 `org-show-siblings'."
9313 (let ((heading-p (org-on-heading-p t))
9314 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9315 (following-p (org-get-alist-option org-show-following-heading key))
9316 (entry-p (org-get-alist-option org-show-entry-below key))
9317 (siblings-p (org-get-alist-option org-show-siblings key)))
9318 (catch 'exit
9319 ;; Show heading or entry text
9320 (if (and heading-p (not entry-p))
9321 (org-flag-heading nil) ; only show the heading
9322 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9323 (org-show-hidden-entry))) ; show entire entry
9324 (when following-p
9325 ;; Show next sibling, or heading below text
9326 (save-excursion
9327 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9328 (org-flag-heading nil))))
9329 (when siblings-p (org-show-siblings))
9330 (when hierarchy-p
9331 ;; show all higher headings, possibly with siblings
9332 (save-excursion
9333 (while (and (condition-case nil
9334 (progn (org-up-heading-all 1) t)
9335 (error nil))
9336 (not (bobp)))
9337 (org-flag-heading nil)
9338 (when siblings-p (org-show-siblings))))))))
9339
9340 (defun org-reveal (&optional siblings)
9341 "Show current entry, hierarchy above it, and the following headline.
9342 This can be used to show a consistent set of context around locations
9343 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9344 not t for the search context.
9345
9346 With optional argument SIBLINGS, on each level of the hierarchy all
9347 siblings are shown. This repairs the tree structure to what it would
9348 look like when opened with hierarchical calls to `org-cycle'."
9349 (interactive "P")
9350 (let ((org-show-hierarchy-above t)
9351 (org-show-following-heading t)
9352 (org-show-siblings (if siblings t org-show-siblings)))
9353 (org-show-context nil)))
9354
9355 (defun org-highlight-new-match (beg end)
9356 "Highlight from BEG to END and mark the highlight is an occur headline."
9357 (let ((ov (org-make-overlay beg end)))
9358 (org-overlay-put ov 'face 'secondary-selection)
9359 (push ov org-occur-highlights)))
9360
9361 (defun org-remove-occur-highlights (&optional beg end noremove)
9362 "Remove the occur highlights from the buffer.
9363 BEG and END are ignored. If NOREMOVE is nil, remove this function
9364 from the `before-change-functions' in the current buffer."
9365 (interactive)
9366 (unless org-inhibit-highlight-removal
9367 (mapc 'org-delete-overlay org-occur-highlights)
9368 (setq org-occur-highlights nil)
9369 (setq org-occur-parameters nil)
9370 (unless noremove
9371 (remove-hook 'before-change-functions
9372 'org-remove-occur-highlights 'local))))
9373
9374 ;;;; Priorities
9375
9376 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9377 "Regular expression matching the priority indicator.")
9378
9379 (defvar org-remove-priority-next-time nil)
9380
9381 (defun org-priority-up ()
9382 "Increase the priority of the current item."
9383 (interactive)
9384 (org-priority 'up))
9385
9386 (defun org-priority-down ()
9387 "Decrease the priority of the current item."
9388 (interactive)
9389 (org-priority 'down))
9390
9391 (defun org-priority (&optional action)
9392 "Change the priority of an item by ARG.
9393 ACTION can be `set', `up', `down', or a character."
9394 (interactive)
9395 (setq action (or action 'set))
9396 (let (current new news have remove)
9397 (save-excursion
9398 (org-back-to-heading t)
9399 (if (looking-at org-priority-regexp)
9400 (setq current (string-to-char (match-string 2))
9401 have t)
9402 (setq current org-default-priority))
9403 (cond
9404 ((or (eq action 'set)
9405 (if (featurep 'xemacs) (characterp action) (integerp action)))
9406 (if (not (eq action 'set))
9407 (setq new action)
9408 (message "Priority %c-%c, SPC to remove: "
9409 org-highest-priority org-lowest-priority)
9410 (setq new (read-char-exclusive)))
9411 (if (and (= (upcase org-highest-priority) org-highest-priority)
9412 (= (upcase org-lowest-priority) org-lowest-priority))
9413 (setq new (upcase new)))
9414 (cond ((equal new ?\ ) (setq remove t))
9415 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9416 (error "Priority must be between `%c' and `%c'"
9417 org-highest-priority org-lowest-priority))))
9418 ((eq action 'up)
9419 (if (and (not have) (eq last-command this-command))
9420 (setq new org-lowest-priority)
9421 (setq new (if (and org-priority-start-cycle-with-default (not have))
9422 org-default-priority (1- current)))))
9423 ((eq action 'down)
9424 (if (and (not have) (eq last-command this-command))
9425 (setq new org-highest-priority)
9426 (setq new (if (and org-priority-start-cycle-with-default (not have))
9427 org-default-priority (1+ current)))))
9428 (t (error "Invalid action")))
9429 (if (or (< (upcase new) org-highest-priority)
9430 (> (upcase new) org-lowest-priority))
9431 (setq remove t))
9432 (setq news (format "%c" new))
9433 (if have
9434 (if remove
9435 (replace-match "" t t nil 1)
9436 (replace-match news t t nil 2))
9437 (if remove
9438 (error "No priority cookie found in line")
9439 (looking-at org-todo-line-regexp)
9440 (if (match-end 2)
9441 (progn
9442 (goto-char (match-end 2))
9443 (insert " [#" news "]"))
9444 (goto-char (match-beginning 3))
9445 (insert "[#" news "] ")))))
9446 (org-preserve-lc (org-set-tags nil 'align))
9447 (if remove
9448 (message "Priority removed")
9449 (message "Priority of current item set to %s" news))))
9450
9451
9452 (defun org-get-priority (s)
9453 "Find priority cookie and return priority."
9454 (save-match-data
9455 (if (not (string-match org-priority-regexp s))
9456 (* 1000 (- org-lowest-priority org-default-priority))
9457 (* 1000 (- org-lowest-priority
9458 (string-to-char (match-string 2 s)))))))
9459
9460 ;;;; Tags
9461
9462 (defvar org-agenda-archives-mode)
9463 (defun org-scan-tags (action matcher &optional todo-only)
9464 "Scan headline tags with inheritance and produce output ACTION.
9465
9466 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9467 or `agenda' to produce an entry list for an agenda view. It can also be
9468 a Lisp form or a function that should be called at each matched headline, in
9469 this case the return value is a list of all return values from these calls.
9470
9471 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9472 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9473 only lines with a TODO keyword are included in the output."
9474 (require 'org-agenda)
9475 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9476 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9477 (org-re
9478 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9479 (props (list 'face 'default
9480 'done-face 'org-done
9481 'undone-face 'default
9482 'mouse-face 'highlight
9483 'org-not-done-regexp org-not-done-regexp
9484 'org-todo-regexp org-todo-regexp
9485 'keymap org-agenda-keymap
9486 'help-echo
9487 (format "mouse-2 or RET jump to org file %s"
9488 (abbreviate-file-name
9489 (or (buffer-file-name (buffer-base-buffer))
9490 (buffer-name (buffer-base-buffer)))))))
9491 (case-fold-search nil)
9492 lspos tags tags-list
9493 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9494 (llast 0) rtn rtn1 level category i txt
9495 todo marker entry priority)
9496 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9497 (setq action (list 'lambda nil action)))
9498 (save-excursion
9499 (goto-char (point-min))
9500 (when (eq action 'sparse-tree)
9501 (org-overview)
9502 (org-remove-occur-highlights))
9503 (while (re-search-forward re nil t)
9504 (catch :skip
9505 (setq todo (if (match-end 1) (match-string 2))
9506 tags (if (match-end 4) (match-string 4)))
9507 (goto-char (setq lspos (1+ (match-beginning 0))))
9508 (setq level (org-reduced-level (funcall outline-level))
9509 category (org-get-category))
9510 (setq i llast llast level)
9511 ;; remove tag lists from same and sublevels
9512 (while (>= i level)
9513 (when (setq entry (assoc i tags-alist))
9514 (setq tags-alist (delete entry tags-alist)))
9515 (setq i (1- i)))
9516 ;; add the next tags
9517 (when tags
9518 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9519 tags-alist
9520 (cons (cons level tags) tags-alist)))
9521 ;; compile tags for current headline
9522 (setq tags-list
9523 (if org-use-tag-inheritance
9524 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9525 tags))
9526 (when org-use-tag-inheritance
9527 (setcdr (car tags-alist)
9528 (mapcar (lambda (x)
9529 (setq x (copy-sequence x))
9530 (org-add-prop-inherited x))
9531 (cdar tags-alist))))
9532 (when (and tags org-use-tag-inheritance
9533 (not (eq t org-use-tag-inheritance)))
9534 ;; selective inheritance, remove uninherited ones
9535 (setcdr (car tags-alist)
9536 (org-remove-uniherited-tags (cdar tags-alist))))
9537 (when (and (or (not todo-only)
9538 (and (member todo org-not-done-keywords)
9539 (or (not org-agenda-tags-todo-honor-ignore-options)
9540 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9541 (let ((case-fold-search t)) (eval matcher))
9542 (or
9543 (not (member org-archive-tag tags-list))
9544 ;; we have an archive tag, should we use this anyway?
9545 (or (not org-agenda-skip-archived-trees)
9546 (and (eq action 'agenda) org-agenda-archives-mode))))
9547 (unless (eq action 'sparse-tree) (org-agenda-skip))
9548
9549 ;; select this headline
9550
9551 (cond
9552 ((eq action 'sparse-tree)
9553 (and org-highlight-sparse-tree-matches
9554 (org-get-heading) (match-end 0)
9555 (org-highlight-new-match
9556 (match-beginning 0) (match-beginning 1)))
9557 (org-show-context 'tags-tree))
9558 ((eq action 'agenda)
9559 (setq txt (org-format-agenda-item
9560 ""
9561 (concat
9562 (if org-tags-match-list-sublevels
9563 (make-string (1- level) ?.) "")
9564 (org-get-heading))
9565 category (org-get-tags-at))
9566 priority (org-get-priority txt))
9567 (goto-char lspos)
9568 (setq marker (org-agenda-new-marker))
9569 (org-add-props txt props
9570 'org-marker marker 'org-hd-marker marker 'org-category category
9571 'priority priority 'type "tagsmatch")
9572 (push txt rtn))
9573 ((functionp action)
9574 (save-excursion
9575 (setq rtn1 (funcall action))
9576 (push rtn1 rtn))
9577 (goto-char (point-at-eol)))
9578 (t (error "Invalid action")))
9579
9580 ;; if we are to skip sublevels, jump to end of subtree
9581 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9582 (when (and (eq action 'sparse-tree)
9583 (not org-sparse-tree-open-archived-trees))
9584 (org-hide-archived-subtrees (point-min) (point-max)))
9585 (nreverse rtn)))
9586
9587 (defun org-remove-uniherited-tags (tags)
9588 "Remove all tags that are not inherited from the list TAGS."
9589 (cond
9590 ((eq org-use-tag-inheritance t)
9591 (if org-tags-exclude-from-inheritance
9592 (org-delete-all org-tags-exclude-from-inheritance tags)
9593 tags))
9594 ((not org-use-tag-inheritance) nil)
9595 ((stringp org-use-tag-inheritance)
9596 (delq nil (mapcar
9597 (lambda (x)
9598 (if (and (string-match org-use-tag-inheritance x)
9599 (not (member x org-tags-exclude-from-inheritance)))
9600 x nil))
9601 tags)))
9602 ((listp org-use-tag-inheritance)
9603 (delq nil (mapcar
9604 (lambda (x)
9605 (if (member x org-use-tag-inheritance) x nil))
9606 tags)))))
9607
9608 (defvar todo-only) ;; dynamically scoped
9609
9610 (defun org-tags-sparse-tree (&optional todo-only match)
9611 "Create a sparse tree according to tags string MATCH.
9612 MATCH can contain positive and negative selection of tags, like
9613 \"+WORK+URGENT-WITHBOSS\".
9614 If optional argument TODO-ONLY is non-nil, only select lines that are
9615 also TODO lines."
9616 (interactive "P")
9617 (org-prepare-agenda-buffers (list (current-buffer)))
9618 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9619
9620 (defvar org-cached-props nil)
9621 (defun org-cached-entry-get (pom property)
9622 (if (or (eq t org-use-property-inheritance)
9623 (and (stringp org-use-property-inheritance)
9624 (string-match org-use-property-inheritance property))
9625 (and (listp org-use-property-inheritance)
9626 (member property org-use-property-inheritance)))
9627 ;; Caching is not possible, check it directly
9628 (org-entry-get pom property 'inherit)
9629 ;; Get all properties, so that we can do complicated checks easily
9630 (cdr (assoc property (or org-cached-props
9631 (setq org-cached-props
9632 (org-entry-properties pom)))))))
9633
9634 (defun org-global-tags-completion-table (&optional files)
9635 "Return the list of all tags in all agenda buffer/files."
9636 (save-excursion
9637 (org-uniquify
9638 (delq nil
9639 (apply 'append
9640 (mapcar
9641 (lambda (file)
9642 (set-buffer (find-file-noselect file))
9643 (append (org-get-buffer-tags)
9644 (mapcar (lambda (x) (if (stringp (car-safe x))
9645 (list (car-safe x)) nil))
9646 org-tag-alist)))
9647 (if (and files (car files))
9648 files
9649 (org-agenda-files))))))))
9650
9651 (defun org-make-tags-matcher (match)
9652 "Create the TAGS//TODO matcher form for the selection string MATCH."
9653 ;; todo-only is scoped dynamically into this function, and the function
9654 ;; may change it if the matcher asks for it.
9655 (unless match
9656 ;; Get a new match request, with completion
9657 (let ((org-last-tags-completion-table
9658 (org-global-tags-completion-table)))
9659 (setq match (org-completing-read-no-ido
9660 "Match: " 'org-tags-completion-function nil nil nil
9661 'org-tags-history))))
9662
9663 ;; Parse the string and create a lisp form
9664 (let ((match0 match)
9665 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9666 minus tag mm
9667 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9668 orterms term orlist re-p str-p level-p level-op time-p
9669 prop-p pn pv po cat-p gv rest)
9670 (if (string-match "/+" match)
9671 ;; match contains also a todo-matching request
9672 (progn
9673 (setq tagsmatch (substring match 0 (match-beginning 0))
9674 todomatch (substring match (match-end 0)))
9675 (if (string-match "^!" todomatch)
9676 (setq todo-only t todomatch (substring todomatch 1)))
9677 (if (string-match "^\\s-*$" todomatch)
9678 (setq todomatch nil)))
9679 ;; only matching tags
9680 (setq tagsmatch match todomatch nil))
9681
9682 ;; Make the tags matcher
9683 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9684 (setq tagsmatcher t)
9685 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9686 (while (setq term (pop orterms))
9687 (while (and (equal (substring term -1) "\\") orterms)
9688 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9689 (while (string-match re term)
9690 (setq rest (substring term (match-end 0))
9691 minus (and (match-end 1)
9692 (equal (match-string 1 term) "-"))
9693 tag (match-string 2 term)
9694 re-p (equal (string-to-char tag) ?{)
9695 level-p (match-end 4)
9696 prop-p (match-end 5)
9697 mm (cond
9698 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9699 (level-p
9700 (setq level-op (org-op-to-function (match-string 3 term)))
9701 `(,level-op level ,(string-to-number
9702 (match-string 4 term))))
9703 (prop-p
9704 (setq pn (match-string 5 term)
9705 po (match-string 6 term)
9706 pv (match-string 7 term)
9707 cat-p (equal pn "CATEGORY")
9708 re-p (equal (string-to-char pv) ?{)
9709 str-p (equal (string-to-char pv) ?\")
9710 time-p (save-match-data
9711 (string-match "^\"[[<].*[]>]\"$" pv))
9712 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9713 (if time-p (setq pv (org-matcher-time pv)))
9714 (setq po (org-op-to-function po (if time-p 'time str-p)))
9715 (cond
9716 ((equal pn "CATEGORY")
9717 (setq gv '(get-text-property (point) 'org-category)))
9718 ((equal pn "TODO")
9719 (setq gv 'todo))
9720 (t
9721 (setq gv `(org-cached-entry-get nil ,pn))))
9722 (if re-p
9723 (if (eq po 'org<>)
9724 `(not (string-match ,pv (or ,gv "")))
9725 `(string-match ,pv (or ,gv "")))
9726 (if str-p
9727 `(,po (or ,gv "") ,pv)
9728 `(,po (string-to-number (or ,gv ""))
9729 ,(string-to-number pv) ))))
9730 (t `(member ,(downcase tag) tags-list)))
9731 mm (if minus (list 'not mm) mm)
9732 term rest)
9733 (push mm tagsmatcher))
9734 (push (if (> (length tagsmatcher) 1)
9735 (cons 'and tagsmatcher)
9736 (car tagsmatcher))
9737 orlist)
9738 (setq tagsmatcher nil))
9739 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9740 (setq tagsmatcher
9741 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9742 ;; Make the todo matcher
9743 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9744 (setq todomatcher t)
9745 (setq orterms (org-split-string todomatch "|") orlist nil)
9746 (while (setq term (pop orterms))
9747 (while (string-match re term)
9748 (setq minus (and (match-end 1)
9749 (equal (match-string 1 term) "-"))
9750 kwd (match-string 2 term)
9751 re-p (equal (string-to-char kwd) ?{)
9752 term (substring term (match-end 0))
9753 mm (if re-p
9754 `(string-match ,(substring kwd 1 -1) todo)
9755 (list 'equal 'todo kwd))
9756 mm (if minus (list 'not mm) mm))
9757 (push mm todomatcher))
9758 (push (if (> (length todomatcher) 1)
9759 (cons 'and todomatcher)
9760 (car todomatcher))
9761 orlist)
9762 (setq todomatcher nil))
9763 (setq todomatcher (if (> (length orlist) 1)
9764 (cons 'or orlist) (car orlist))))
9765
9766 ;; Return the string and lisp forms of the matcher
9767 (setq matcher (if todomatcher
9768 (list 'and tagsmatcher todomatcher)
9769 tagsmatcher))
9770 (cons match0 matcher)))
9771
9772 (defun org-op-to-function (op &optional stringp)
9773 "Turn an operator into the appropriate function."
9774 (setq op
9775 (cond
9776 ((equal op "<" ) '(< string< org-time<))
9777 ((equal op ">" ) '(> org-string> org-time>))
9778 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9779 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9780 ((member op '("=" "==")) '(= string= org-time=))
9781 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9782 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9783
9784 (defun org<> (a b) (not (= a b)))
9785 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9786 (defun org-string>= (a b) (not (string< a b)))
9787 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9788 (defun org-string<> (a b) (not (string= a b)))
9789 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
9790 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
9791 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
9792 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
9793 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
9794 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
9795 (defun org-2ft (s)
9796 "Convert S to a floating point time.
9797 If S is already a number, just return it. If it is a string, parse
9798 it as a time string and apply `float-time' to it. If S is nil, just return 0."
9799 (cond
9800 ((numberp s) s)
9801 ((stringp s)
9802 (condition-case nil
9803 (float-time (apply 'encode-time (org-parse-time-string s)))
9804 (error 0.)))
9805 (t 0.)))
9806
9807 (defun org-time-today ()
9808 "Time in seconds today at 0:00.
9809 Returns the float number of seconds since the beginning of the
9810 epoch to the beginning of today (00:00)."
9811 (float-time (apply 'encode-time
9812 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9813
9814 (defun org-matcher-time (s)
9815 "Interpret a time comparison value."
9816 (save-match-data
9817 (cond
9818 ((string= s "<now>") (float-time))
9819 ((string= s "<today>") (org-time-today))
9820 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9821 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9822 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9823 (+ (org-time-today)
9824 (* (string-to-number (match-string 1 s))
9825 (cdr (assoc (match-string 2 s)
9826 '(("d" . 86400.0) ("w" . 604800.0)
9827 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9828 (t (org-2ft s)))))
9829
9830 (defun org-match-any-p (re list)
9831 "Does re match any element of list?"
9832 (setq list (mapcar (lambda (x) (string-match re x)) list))
9833 (delq nil list))
9834
9835 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9836 (defvar org-tags-overlay (org-make-overlay 1 1))
9837 (org-detach-overlay org-tags-overlay)
9838
9839 (defun org-get-local-tags-at (&optional pos)
9840 "Get a list of tags defined in the current headline."
9841 (org-get-tags-at pos 'local))
9842
9843 (defun org-get-local-tags ()
9844 "Get a list of tags defined in the current headline."
9845 (org-get-tags-at nil 'local))
9846
9847 (defun org-get-tags-at (&optional pos local)
9848 "Get a list of all headline tags applicable at POS.
9849 POS defaults to point. If tags are inherited, the list contains
9850 the targets in the same sequence as the headlines appear, i.e.
9851 the tags of the current headline come last.
9852 When LOCAL is non-nil, only return tags from the current headline,
9853 ignore inherited ones."
9854 (interactive)
9855 (let (tags ltags lastpos parent)
9856 (save-excursion
9857 (save-restriction
9858 (widen)
9859 (goto-char (or pos (point)))
9860 (save-match-data
9861 (catch 'done
9862 (condition-case nil
9863 (progn
9864 (org-back-to-heading t)
9865 (while (not (equal lastpos (point)))
9866 (setq lastpos (point))
9867 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9868 (setq ltags (org-split-string
9869 (org-match-string-no-properties 1) ":"))
9870 (when parent
9871 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9872 (setq tags (append
9873 (if parent
9874 (org-remove-uniherited-tags ltags)
9875 ltags)
9876 tags)))
9877 (or org-use-tag-inheritance (throw 'done t))
9878 (if local (throw 'done t))
9879 (org-up-heading-all 1)
9880 (setq parent t)))
9881 (error nil)))))
9882 (append (org-remove-uniherited-tags org-file-tags) tags))))
9883
9884 (defun org-add-prop-inherited (s)
9885 (add-text-properties 0 (length s) '(inherited t) s)
9886 s)
9887
9888 (defun org-toggle-tag (tag &optional onoff)
9889 "Toggle the tag TAG for the current line.
9890 If ONOFF is `on' or `off', don't toggle but set to this state."
9891 (let (res current)
9892 (save-excursion
9893 (org-back-to-heading t)
9894 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9895 (point-at-eol) t)
9896 (progn
9897 (setq current (match-string 1))
9898 (replace-match ""))
9899 (setq current ""))
9900 (setq current (nreverse (org-split-string current ":")))
9901 (cond
9902 ((eq onoff 'on)
9903 (setq res t)
9904 (or (member tag current) (push tag current)))
9905 ((eq onoff 'off)
9906 (or (not (member tag current)) (setq current (delete tag current))))
9907 (t (if (member tag current)
9908 (setq current (delete tag current))
9909 (setq res t)
9910 (push tag current))))
9911 (end-of-line 1)
9912 (if current
9913 (progn
9914 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9915 (org-set-tags nil t))
9916 (delete-horizontal-space))
9917 (run-hooks 'org-after-tags-change-hook))
9918 res))
9919
9920 (defun org-align-tags-here (to-col)
9921 ;; Assumes that this is a headline
9922 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9923 (beginning-of-line 1)
9924 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9925 (< pos (match-beginning 2)))
9926 (progn
9927 (setq tags-l (- (match-end 2) (match-beginning 2)))
9928 (goto-char (match-beginning 1))
9929 (insert " ")
9930 (delete-region (point) (1+ (match-beginning 2)))
9931 (setq ncol (max (1+ (current-column))
9932 (1+ col)
9933 (if (> to-col 0)
9934 to-col
9935 (- (abs to-col) tags-l))))
9936 (setq p (point))
9937 (insert (make-string (- ncol (current-column)) ?\ ))
9938 (setq ncol (current-column))
9939 (when indent-tabs-mode (tabify p (point-at-eol)))
9940 (org-move-to-column (min ncol col) t))
9941 (goto-char pos))))
9942
9943 (defun org-set-tags-command (&optional arg just-align)
9944 "Call the set-tags command for the current entry."
9945 (interactive "P")
9946 (if (org-on-heading-p)
9947 (org-set-tags arg just-align)
9948 (save-excursion
9949 (org-back-to-heading t)
9950 (org-set-tags arg just-align))))
9951
9952 (defun org-set-tags (&optional arg just-align)
9953 "Set the tags for the current headline.
9954 With prefix ARG, realign all tags in headings in the current buffer."
9955 (interactive "P")
9956 (let* ((re (concat "^" outline-regexp))
9957 (current (org-get-tags-string))
9958 (col (current-column))
9959 (org-setting-tags t)
9960 table current-tags inherited-tags ; computed below when needed
9961 tags p0 c0 c1 rpl)
9962 (if arg
9963 (save-excursion
9964 (goto-char (point-min))
9965 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9966 (while (re-search-forward re nil t)
9967 (org-set-tags nil t)
9968 (end-of-line 1)))
9969 (message "All tags realigned to column %d" org-tags-column))
9970 (if just-align
9971 (setq tags current)
9972 ;; Get a new set of tags from the user
9973 (save-excursion
9974 (setq table (or org-tag-alist (org-get-buffer-tags))
9975 org-last-tags-completion-table table
9976 current-tags (org-split-string current ":")
9977 inherited-tags (nreverse
9978 (nthcdr (length current-tags)
9979 (nreverse (org-get-tags-at))))
9980 tags
9981 (if (or (eq t org-use-fast-tag-selection)
9982 (and org-use-fast-tag-selection
9983 (delq nil (mapcar 'cdr table))))
9984 (org-fast-tag-selection
9985 current-tags inherited-tags table
9986 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9987 (let ((org-add-colon-after-tag-completion t))
9988 (org-trim
9989 (org-without-partial-completion
9990 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9991 nil nil current 'org-tags-history)))))))
9992 (while (string-match "[-+&]+" tags)
9993 ;; No boolean logic, just a list
9994 (setq tags (replace-match ":" t t tags))))
9995
9996 (if (string-match "\\`[\t ]*\\'" tags)
9997 (setq tags "")
9998 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9999 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10000
10001 ;; Insert new tags at the correct column
10002 (beginning-of-line 1)
10003 (cond
10004 ((and (equal current "") (equal tags "")))
10005 ((re-search-forward
10006 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10007 (point-at-eol) t)
10008 (if (equal tags "")
10009 (setq rpl "")
10010 (goto-char (match-beginning 0))
10011 (setq c0 (current-column) p0 (point)
10012 c1 (max (1+ c0) (if (> org-tags-column 0)
10013 org-tags-column
10014 (- (- org-tags-column) (length tags))))
10015 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10016 (replace-match rpl t t)
10017 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10018 tags)
10019 (t (error "Tags alignment failed")))
10020 (org-move-to-column col)
10021 (unless just-align
10022 (run-hooks 'org-after-tags-change-hook)))))
10023
10024 (defun org-change-tag-in-region (beg end tag off)
10025 "Add or remove TAG for each entry in the region.
10026 This works in the agenda, and also in an org-mode buffer."
10027 (interactive
10028 (list (region-beginning) (region-end)
10029 (let ((org-last-tags-completion-table
10030 (if (org-mode-p)
10031 (org-get-buffer-tags)
10032 (org-global-tags-completion-table))))
10033 (org-ido-completing-read
10034 "Tag: " 'org-tags-completion-function nil nil nil
10035 'org-tags-history))
10036 (progn
10037 (message "[s]et or [r]emove? ")
10038 (equal (read-char-exclusive) ?r))))
10039 (if (fboundp 'deactivate-mark) (deactivate-mark))
10040 (let ((agendap (equal major-mode 'org-agenda-mode))
10041 l1 l2 m buf pos newhead (cnt 0))
10042 (goto-char end)
10043 (setq l2 (1- (org-current-line)))
10044 (goto-char beg)
10045 (setq l1 (org-current-line))
10046 (loop for l from l1 to l2 do
10047 (goto-line l)
10048 (setq m (get-text-property (point) 'org-hd-marker))
10049 (when (or (and (org-mode-p) (org-on-heading-p))
10050 (and agendap m))
10051 (setq buf (if agendap (marker-buffer m) (current-buffer))
10052 pos (if agendap m (point)))
10053 (with-current-buffer buf
10054 (save-excursion
10055 (save-restriction
10056 (goto-char pos)
10057 (setq cnt (1+ cnt))
10058 (org-toggle-tag tag (if off 'off 'on))
10059 (setq newhead (org-get-heading)))))
10060 (and agendap (org-agenda-change-all-lines newhead m))))
10061 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10062
10063 (defun org-tags-completion-function (string predicate &optional flag)
10064 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10065 (confirm (lambda (x) (stringp (car x)))))
10066 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10067 (setq s1 (match-string 1 string)
10068 s2 (match-string 2 string))
10069 (setq s1 "" s2 string))
10070 (cond
10071 ((eq flag nil)
10072 ;; try completion
10073 (setq rtn (try-completion s2 ctable confirm))
10074 (if (stringp rtn)
10075 (setq rtn
10076 (concat s1 s2 (substring rtn (length s2))
10077 (if (and org-add-colon-after-tag-completion
10078 (assoc rtn ctable))
10079 ":" ""))))
10080 rtn)
10081 ((eq flag t)
10082 ;; all-completions
10083 (all-completions s2 ctable confirm)
10084 )
10085 ((eq flag 'lambda)
10086 ;; exact match?
10087 (assoc s2 ctable)))
10088 ))
10089
10090 (defun org-fast-tag-insert (kwd tags face &optional end)
10091 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10092 (insert (format "%-12s" (concat kwd ":"))
10093 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10094 (or end "")))
10095
10096 (defun org-fast-tag-show-exit (flag)
10097 (save-excursion
10098 (goto-line 3)
10099 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10100 (replace-match ""))
10101 (when flag
10102 (end-of-line 1)
10103 (org-move-to-column (- (window-width) 19) t)
10104 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10105
10106 (defun org-set-current-tags-overlay (current prefix)
10107 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10108 (if (featurep 'xemacs)
10109 (org-overlay-display org-tags-overlay (concat prefix s)
10110 'secondary-selection)
10111 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10112 (org-overlay-display org-tags-overlay (concat prefix s)))))
10113
10114 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10115 "Fast tag selection with single keys.
10116 CURRENT is the current list of tags in the headline, INHERITED is the
10117 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10118 possibly with grouping information. TODO-TABLE is a similar table with
10119 TODO keywords, should these have keys assigned to them.
10120 If the keys are nil, a-z are automatically assigned.
10121 Returns the new tags string, or nil to not change the current settings."
10122 (let* ((fulltable (append table todo-table))
10123 (maxlen (apply 'max (mapcar
10124 (lambda (x)
10125 (if (stringp (car x)) (string-width (car x)) 0))
10126 fulltable)))
10127 (buf (current-buffer))
10128 (expert (eq org-fast-tag-selection-single-key 'expert))
10129 (buffer-tags nil)
10130 (fwidth (+ maxlen 3 1 3))
10131 (ncol (/ (- (window-width) 4) fwidth))
10132 (i-face 'org-done)
10133 (c-face 'org-todo)
10134 tg cnt e c char c1 c2 ntable tbl rtn
10135 ov-start ov-end ov-prefix
10136 (exit-after-next org-fast-tag-selection-single-key)
10137 (done-keywords org-done-keywords)
10138 groups ingroup)
10139 (save-excursion
10140 (beginning-of-line 1)
10141 (if (looking-at
10142 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10143 (setq ov-start (match-beginning 1)
10144 ov-end (match-end 1)
10145 ov-prefix "")
10146 (setq ov-start (1- (point-at-eol))
10147 ov-end (1+ ov-start))
10148 (skip-chars-forward "^\n\r")
10149 (setq ov-prefix
10150 (concat
10151 (buffer-substring (1- (point)) (point))
10152 (if (> (current-column) org-tags-column)
10153 " "
10154 (make-string (- org-tags-column (current-column)) ?\ ))))))
10155 (org-move-overlay org-tags-overlay ov-start ov-end)
10156 (save-window-excursion
10157 (if expert
10158 (set-buffer (get-buffer-create " *Org tags*"))
10159 (delete-other-windows)
10160 (split-window-vertically)
10161 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10162 (erase-buffer)
10163 (org-set-local 'org-done-keywords done-keywords)
10164 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10165 (org-fast-tag-insert "Current" current c-face "\n\n")
10166 (org-fast-tag-show-exit exit-after-next)
10167 (org-set-current-tags-overlay current ov-prefix)
10168 (setq tbl fulltable char ?a cnt 0)
10169 (while (setq e (pop tbl))
10170 (cond
10171 ((equal e '(:startgroup))
10172 (push '() groups) (setq ingroup t)
10173 (when (not (= cnt 0))
10174 (setq cnt 0)
10175 (insert "\n"))
10176 (insert "{ "))
10177 ((equal e '(:endgroup))
10178 (setq ingroup nil cnt 0)
10179 (insert "}\n"))
10180 (t
10181 (setq tg (car e) c2 nil)
10182 (if (cdr e)
10183 (setq c (cdr e))
10184 ;; automatically assign a character.
10185 (setq c1 (string-to-char
10186 (downcase (substring
10187 tg (if (= (string-to-char tg) ?@) 1 0)))))
10188 (if (or (rassoc c1 ntable) (rassoc c1 table))
10189 (while (or (rassoc char ntable) (rassoc char table))
10190 (setq char (1+ char)))
10191 (setq c2 c1))
10192 (setq c (or c2 char)))
10193 (if ingroup (push tg (car groups)))
10194 (setq tg (org-add-props tg nil 'face
10195 (cond
10196 ((not (assoc tg table))
10197 (org-get-todo-face tg))
10198 ((member tg current) c-face)
10199 ((member tg inherited) i-face)
10200 (t nil))))
10201 (if (and (= cnt 0) (not ingroup)) (insert " "))
10202 (insert "[" c "] " tg (make-string
10203 (- fwidth 4 (length tg)) ?\ ))
10204 (push (cons tg c) ntable)
10205 (when (= (setq cnt (1+ cnt)) ncol)
10206 (insert "\n")
10207 (if ingroup (insert " "))
10208 (setq cnt 0)))))
10209 (setq ntable (nreverse ntable))
10210 (insert "\n")
10211 (goto-char (point-min))
10212 (if (not expert) (org-fit-window-to-buffer))
10213 (setq rtn
10214 (catch 'exit
10215 (while t
10216 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10217 (if groups " [!] no groups" " [!]groups")
10218 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10219 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10220 (cond
10221 ((= c ?\r) (throw 'exit t))
10222 ((= c ?!)
10223 (setq groups (not groups))
10224 (goto-char (point-min))
10225 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10226 ((= c ?\C-c)
10227 (if (not expert)
10228 (org-fast-tag-show-exit
10229 (setq exit-after-next (not exit-after-next)))
10230 (setq expert nil)
10231 (delete-other-windows)
10232 (split-window-vertically)
10233 (org-switch-to-buffer-other-window " *Org tags*")
10234 (org-fit-window-to-buffer)))
10235 ((or (= c ?\C-g)
10236 (and (= c ?q) (not (rassoc c ntable))))
10237 (org-detach-overlay org-tags-overlay)
10238 (setq quit-flag t))
10239 ((= c ?\ )
10240 (setq current nil)
10241 (if exit-after-next (setq exit-after-next 'now)))
10242 ((= c ?\t)
10243 (condition-case nil
10244 (setq tg (org-ido-completing-read
10245 "Tag: "
10246 (or buffer-tags
10247 (with-current-buffer buf
10248 (org-get-buffer-tags)))))
10249 (quit (setq tg "")))
10250 (when (string-match "\\S-" tg)
10251 (add-to-list 'buffer-tags (list tg))
10252 (if (member tg current)
10253 (setq current (delete tg current))
10254 (push tg current)))
10255 (if exit-after-next (setq exit-after-next 'now)))
10256 ((setq e (rassoc c todo-table) tg (car e))
10257 (with-current-buffer buf
10258 (save-excursion (org-todo tg)))
10259 (if exit-after-next (setq exit-after-next 'now)))
10260 ((setq e (rassoc c ntable) tg (car e))
10261 (if (member tg current)
10262 (setq current (delete tg current))
10263 (loop for g in groups do
10264 (if (member tg g)
10265 (mapc (lambda (x)
10266 (setq current (delete x current)))
10267 g)))
10268 (push tg current))
10269 (if exit-after-next (setq exit-after-next 'now))))
10270
10271 ;; Create a sorted list
10272 (setq current
10273 (sort current
10274 (lambda (a b)
10275 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10276 (if (eq exit-after-next 'now) (throw 'exit t))
10277 (goto-char (point-min))
10278 (beginning-of-line 2)
10279 (delete-region (point) (point-at-eol))
10280 (org-fast-tag-insert "Current" current c-face)
10281 (org-set-current-tags-overlay current ov-prefix)
10282 (while (re-search-forward
10283 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10284 (setq tg (match-string 1))
10285 (add-text-properties
10286 (match-beginning 1) (match-end 1)
10287 (list 'face
10288 (cond
10289 ((member tg current) c-face)
10290 ((member tg inherited) i-face)
10291 (t (get-text-property (match-beginning 1) 'face))))))
10292 (goto-char (point-min)))))
10293 (org-detach-overlay org-tags-overlay)
10294 (if rtn
10295 (mapconcat 'identity current ":")
10296 nil))))
10297
10298 (defun org-get-tags-string ()
10299 "Get the TAGS string in the current headline."
10300 (unless (org-on-heading-p t)
10301 (error "Not on a heading"))
10302 (save-excursion
10303 (beginning-of-line 1)
10304 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10305 (org-match-string-no-properties 1)
10306 "")))
10307
10308 (defun org-get-tags ()
10309 "Get the list of tags specified in the current headline."
10310 (org-split-string (org-get-tags-string) ":"))
10311
10312 (defun org-get-buffer-tags ()
10313 "Get a table of all tags used in the buffer, for completion."
10314 (let (tags)
10315 (save-excursion
10316 (goto-char (point-min))
10317 (while (re-search-forward
10318 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10319 (when (equal (char-after (point-at-bol 0)) ?*)
10320 (mapc (lambda (x) (add-to-list 'tags x))
10321 (org-split-string (org-match-string-no-properties 1) ":")))))
10322 (mapcar 'list tags)))
10323
10324 ;;;; The mapping API
10325
10326 ;;;###autoload
10327 (defun org-map-entries (func &optional match scope &rest skip)
10328 "Call FUNC at each headline selected by MATCH in SCOPE.
10329
10330 FUNC is a function or a lisp form. The function will be called without
10331 arguments, with the cursor positioned at the beginning of the headline.
10332 The return values of all calls to the function will be collected and
10333 returned as a list.
10334
10335 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10336 Only headlines that are matched by this query will be considered during
10337 the iteration. When MATCH is nil or t, all headlines will be
10338 visited by the iteration.
10339
10340 SCOPE determines the scope of this command. It can be any of:
10341
10342 nil The current buffer, respecting the restriction if any
10343 tree The subtree started with the entry at point
10344 file The current buffer, without restriction
10345 file-with-archives
10346 The current buffer, and any archives associated with it
10347 agenda All agenda files
10348 agenda-with-archives
10349 All agenda files with any archive files associated with them
10350 \(file1 file2 ...)
10351 If this is a list, all files in the list will be scanned
10352
10353 The remaining args are treated as settings for the skipping facilities of
10354 the scanner. The following items can be given here:
10355
10356 archive skip trees with the archive tag.
10357 comment skip trees with the COMMENT keyword
10358 function or Emacs Lisp form:
10359 will be used as value for `org-agenda-skip-function', so whenever
10360 the the function returns t, FUNC will not be called for that
10361 entry and search will continue from the point where the
10362 function leaves it."
10363 (let* ((org-agenda-archives-mode nil) ; just to make sure
10364 (org-agenda-skip-archived-trees (memq 'archive skip))
10365 (org-agenda-skip-comment-trees (memq 'comment skip))
10366 (org-agenda-skip-function
10367 (car (org-delete-all '(comment archive) skip)))
10368 (org-tags-match-list-sublevels t)
10369 matcher file res
10370 org-todo-keywords-for-agenda
10371 org-done-keywords-for-agenda
10372 org-todo-keyword-alist-for-agenda
10373 org-tag-alist-for-agenda)
10374
10375 (cond
10376 ((eq match t) (setq matcher t))
10377 ((eq match nil) (setq matcher t))
10378 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10379
10380 (save-excursion
10381 (save-restriction
10382 (when (eq scope 'tree)
10383 (org-back-to-heading t)
10384 (org-narrow-to-subtree)
10385 (setq scope nil))
10386
10387 (if (not scope)
10388 (progn
10389 (org-prepare-agenda-buffers
10390 (list (buffer-file-name (current-buffer))))
10391 (setq res (org-scan-tags func matcher)))
10392 ;; Get the right scope
10393 (cond
10394 ((and scope (listp scope) (symbolp (car scope)))
10395 (setq scope (eval scope)))
10396 ((eq scope 'agenda)
10397 (setq scope (org-agenda-files t)))
10398 ((eq scope 'agenda-with-archives)
10399 (setq scope (org-agenda-files t))
10400 (setq scope (org-add-archive-files scope)))
10401 ((eq scope 'file)
10402 (setq scope (list (buffer-file-name))))
10403 ((eq scope 'file-with-archives)
10404 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10405 (org-prepare-agenda-buffers scope)
10406 (while (setq file (pop scope))
10407 (with-current-buffer (org-find-base-buffer-visiting file)
10408 (save-excursion
10409 (save-restriction
10410 (widen)
10411 (goto-char (point-min))
10412 (setq res (append res (org-scan-tags func matcher))))))))))
10413 res))
10414
10415 ;;;; Properties
10416
10417 ;;; Setting and retrieving properties
10418
10419 (defconst org-special-properties
10420 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10421 "TIMESTAMP" "TIMESTAMP_IA")
10422 "The special properties valid in Org-mode.
10423
10424 These are properties that are not defined in the property drawer,
10425 but in some other way.")
10426
10427 (defconst org-default-properties
10428 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10429 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10430 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10431 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10432 "Some properties that are used by Org-mode for various purposes.
10433 Being in this list makes sure that they are offered for completion.")
10434
10435 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10436 "Regular expression matching the first line of a property drawer.")
10437
10438 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10439 "Regular expression matching the first line of a property drawer.")
10440
10441 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10442 "Regular expression matching the first line of a property drawer.")
10443
10444 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10445 "Regular expression matching the first line of a property drawer.")
10446
10447 (defconst org-property-drawer-re
10448 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10449 org-property-end-re "\\)\n?")
10450 "Matches an entire property drawer.")
10451
10452 (defconst org-clock-drawer-re
10453 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10454 org-property-end-re "\\)\n?")
10455 "Matches an entire clock drawer.")
10456
10457 (defun org-property-action ()
10458 "Do an action on properties."
10459 (interactive)
10460 (let (c)
10461 (org-at-property-p)
10462 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10463 (setq c (read-char-exclusive))
10464 (cond
10465 ((equal c ?s)
10466 (call-interactively 'org-set-property))
10467 ((equal c ?d)
10468 (call-interactively 'org-delete-property))
10469 ((equal c ?D)
10470 (call-interactively 'org-delete-property-globally))
10471 ((equal c ?c)
10472 (call-interactively 'org-compute-property-at-point))
10473 (t (error "No such property action %c" c)))))
10474
10475 (defun org-at-property-p ()
10476 "Is the cursor in a property line?"
10477 ;; FIXME: Does not check if we are actually in the drawer.
10478 ;; FIXME: also returns true on any drawers.....
10479 ;; This is used by C-c C-c for property action.
10480 (save-excursion
10481 (beginning-of-line 1)
10482 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10483
10484 (defun org-get-property-block (&optional beg end force)
10485 "Return the (beg . end) range of the body of the property drawer.
10486 BEG and END can be beginning and end of subtree, if not given
10487 they will be found.
10488 If the drawer does not exist and FORCE is non-nil, create the drawer."
10489 (catch 'exit
10490 (save-excursion
10491 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10492 (end (or end (progn (outline-next-heading) (point)))))
10493 (goto-char beg)
10494 (if (re-search-forward org-property-start-re end t)
10495 (setq beg (1+ (match-end 0)))
10496 (if force
10497 (save-excursion
10498 (org-insert-property-drawer)
10499 (setq end (progn (outline-next-heading) (point))))
10500 (throw 'exit nil))
10501 (goto-char beg)
10502 (if (re-search-forward org-property-start-re end t)
10503 (setq beg (1+ (match-end 0)))))
10504 (if (re-search-forward org-property-end-re end t)
10505 (setq end (match-beginning 0))
10506 (or force (throw 'exit nil))
10507 (goto-char beg)
10508 (setq end beg)
10509 (org-indent-line-function)
10510 (insert ":END:\n"))
10511 (cons beg end)))))
10512
10513 (defun org-entry-properties (&optional pom which)
10514 "Get all properties of the entry at point-or-marker POM.
10515 This includes the TODO keyword, the tags, time strings for deadline,
10516 scheduled, and clocking, and any additional properties defined in the
10517 entry. The return value is an alist, keys may occur multiple times
10518 if the property key was used several times.
10519 POM may also be nil, in which case the current entry is used.
10520 If WHICH is nil or `all', get all properties. If WHICH is
10521 `special' or `standard', only get that subclass."
10522 (setq which (or which 'all))
10523 (org-with-point-at pom
10524 (let ((clockstr (substring org-clock-string 0 -1))
10525 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10526 beg end range props sum-props key value string clocksum)
10527 (save-excursion
10528 (when (condition-case nil
10529 (and (org-mode-p) (org-back-to-heading t))
10530 (error nil))
10531 (setq beg (point))
10532 (setq sum-props (get-text-property (point) 'org-summaries))
10533 (setq clocksum (get-text-property (point) :org-clock-minutes))
10534 (outline-next-heading)
10535 (setq end (point))
10536 (when (memq which '(all special))
10537 ;; Get the special properties, like TODO and tags
10538 (goto-char beg)
10539 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10540 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10541 (when (looking-at org-priority-regexp)
10542 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10543 (when (and (setq value (org-get-tags-string))
10544 (string-match "\\S-" value))
10545 (push (cons "TAGS" value) props))
10546 (when (setq value (org-get-tags-at))
10547 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10548 props))
10549 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10550 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10551 string (if (equal key clockstr)
10552 (org-no-properties
10553 (org-trim
10554 (buffer-substring
10555 (match-beginning 3) (goto-char (point-at-eol)))))
10556 (substring (org-match-string-no-properties 3) 1 -1)))
10557 (unless key
10558 (if (= (char-after (match-beginning 3)) ?\[)
10559 (setq key "TIMESTAMP_IA")
10560 (setq key "TIMESTAMP")))
10561 (when (or (equal key clockstr) (not (assoc key props)))
10562 (push (cons key string) props)))
10563
10564 )
10565
10566 (when (memq which '(all standard))
10567 ;; Get the standard properties, like :PORP: ...
10568 (setq range (org-get-property-block beg end))
10569 (when range
10570 (goto-char (car range))
10571 (while (re-search-forward
10572 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10573 (cdr range) t)
10574 (setq key (org-match-string-no-properties 1)
10575 value (org-trim (or (org-match-string-no-properties 2) "")))
10576 (unless (member key excluded)
10577 (push (cons key (or value "")) props)))))
10578 (if clocksum
10579 (push (cons "CLOCKSUM"
10580 (org-columns-number-to-string (/ (float clocksum) 60.)
10581 'add_times))
10582 props))
10583 (unless (assoc "CATEGORY" props)
10584 (setq value (or (org-get-category)
10585 (progn (org-refresh-category-properties)
10586 (org-get-category))))
10587 (push (cons "CATEGORY" value) props))
10588 (append sum-props (nreverse props)))))))
10589
10590 (defun org-entry-get (pom property &optional inherit)
10591 "Get value of PROPERTY for entry at point-or-marker POM.
10592 If INHERIT is non-nil and the entry does not have the property,
10593 then also check higher levels of the hierarchy.
10594 If INHERIT is the symbol `selective', use inheritance only if the setting
10595 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10596 If the property is present but empty, the return value is the empty string.
10597 If the property is not present at all, nil is returned."
10598 (org-with-point-at pom
10599 (if (and inherit (if (eq inherit 'selective)
10600 (org-property-inherit-p property)
10601 t))
10602 (org-entry-get-with-inheritance property)
10603 (if (member property org-special-properties)
10604 ;; We need a special property. Use brute force, get all properties.
10605 (cdr (assoc property (org-entry-properties nil 'special)))
10606 (let ((range (org-get-property-block)))
10607 (if (and range
10608 (goto-char (car range))
10609 (re-search-forward
10610 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10611 (cdr range) t))
10612 ;; Found the property, return it.
10613 (if (match-end 1)
10614 (org-match-string-no-properties 1)
10615 "")))))))
10616
10617 (defun org-property-or-variable-value (var &optional inherit)
10618 "Check if there is a property fixing the value of VAR.
10619 If yes, return this value. If not, return the current value of the variable."
10620 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10621 (if (and prop (stringp prop) (string-match "\\S-" prop))
10622 (read prop)
10623 (symbol-value var))))
10624
10625 (defun org-entry-delete (pom property)
10626 "Delete the property PROPERTY from entry at point-or-marker POM."
10627 (org-with-point-at pom
10628 (if (member property org-special-properties)
10629 nil ; cannot delete these properties.
10630 (let ((range (org-get-property-block)))
10631 (if (and range
10632 (goto-char (car range))
10633 (re-search-forward
10634 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10635 (cdr range) t))
10636 (progn
10637 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10638 t)
10639 nil)))))
10640
10641 ;; Multi-values properties are properties that contain multiple values
10642 ;; These values are assumed to be single words, separated by whitespace.
10643 (defun org-entry-add-to-multivalued-property (pom property value)
10644 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10645 (let* ((old (org-entry-get pom property))
10646 (values (and old (org-split-string old "[ \t]"))))
10647 (setq value (org-entry-protect-space value))
10648 (unless (member value values)
10649 (setq values (cons value values))
10650 (org-entry-put pom property
10651 (mapconcat 'identity values " ")))))
10652
10653 (defun org-entry-remove-from-multivalued-property (pom property value)
10654 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10655 (let* ((old (org-entry-get pom property))
10656 (values (and old (org-split-string old "[ \t]"))))
10657 (setq value (org-entry-protect-space value))
10658 (when (member value values)
10659 (setq values (delete value values))
10660 (org-entry-put pom property
10661 (mapconcat 'identity values " ")))))
10662
10663 (defun org-entry-member-in-multivalued-property (pom property value)
10664 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10665 (let* ((old (org-entry-get pom property))
10666 (values (and old (org-split-string old "[ \t]"))))
10667 (setq value (org-entry-protect-space value))
10668 (member value values)))
10669
10670 (defun org-entry-get-multivalued-property (pom property)
10671 "Return a list of values in a multivalued property."
10672 (let* ((value (org-entry-get pom property))
10673 (values (and value (org-split-string value "[ \t]"))))
10674 (mapcar 'org-entry-restore-space values)))
10675
10676 (defun org-entry-put-multivalued-property (pom property &rest values)
10677 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10678 VALUES should be a list of strings. Spaces will be protected."
10679 (org-entry-put pom property
10680 (mapconcat 'org-entry-protect-space values " "))
10681 (let* ((value (org-entry-get pom property))
10682 (values (and value (org-split-string value "[ \t]"))))
10683 (mapcar 'org-entry-restore-space values)))
10684
10685 (defun org-entry-protect-space (s)
10686 "Protect spaces and newline in string S."
10687 (while (string-match " " s)
10688 (setq s (replace-match "%20" t t s)))
10689 (while (string-match "\n" s)
10690 (setq s (replace-match "%0A" t t s)))
10691 s)
10692
10693 (defun org-entry-restore-space (s)
10694 "Restore spaces and newline in string S."
10695 (while (string-match "%20" s)
10696 (setq s (replace-match " " t t s)))
10697 (while (string-match "%0A" s)
10698 (setq s (replace-match "\n" t t s)))
10699 s)
10700
10701 (defvar org-entry-property-inherited-from (make-marker)
10702 "Marker pointing to the entry from where a property was inherited.
10703 Each call to `org-entry-get-with-inheritance' will set this marker to the
10704 location of the entry where the inheritance search matched. If there was
10705 no match, the marker will point nowhere.
10706 Note that also `org-entry-get' calls this function, if the INHERIT flag
10707 is set.")
10708
10709 (defun org-entry-get-with-inheritance (property)
10710 "Get entry property, and search higher levels if not present."
10711 (move-marker org-entry-property-inherited-from nil)
10712 (let (tmp)
10713 (save-excursion
10714 (save-restriction
10715 (widen)
10716 (catch 'ex
10717 (while t
10718 (when (setq tmp (org-entry-get nil property))
10719 (org-back-to-heading t)
10720 (move-marker org-entry-property-inherited-from (point))
10721 (throw 'ex tmp))
10722 (or (org-up-heading-safe) (throw 'ex nil)))))
10723 (or tmp
10724 (cdr (assoc property org-file-properties))
10725 (cdr (assoc property org-global-properties))
10726 (cdr (assoc property org-global-properties-fixed))))))
10727
10728 (defun org-entry-put (pom property value)
10729 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10730 (org-with-point-at pom
10731 (org-back-to-heading t)
10732 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10733 range)
10734 (cond
10735 ((equal property "TODO")
10736 (when (and (stringp value) (string-match "\\S-" value)
10737 (not (member value org-todo-keywords-1)))
10738 (error "\"%s\" is not a valid TODO state" value))
10739 (if (or (not value)
10740 (not (string-match "\\S-" value)))
10741 (setq value 'none))
10742 (org-todo value)
10743 (org-set-tags nil 'align))
10744 ((equal property "PRIORITY")
10745 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10746 (string-to-char value) ?\ ))
10747 (org-set-tags nil 'align))
10748 ((equal property "SCHEDULED")
10749 (if (re-search-forward org-scheduled-time-regexp end t)
10750 (cond
10751 ((eq value 'earlier) (org-timestamp-change -1 'day))
10752 ((eq value 'later) (org-timestamp-change 1 'day))
10753 (t (call-interactively 'org-schedule)))
10754 (call-interactively 'org-schedule)))
10755 ((equal property "DEADLINE")
10756 (if (re-search-forward org-deadline-time-regexp end t)
10757 (cond
10758 ((eq value 'earlier) (org-timestamp-change -1 'day))
10759 ((eq value 'later) (org-timestamp-change 1 'day))
10760 (t (call-interactively 'org-deadline)))
10761 (call-interactively 'org-deadline)))
10762 ((member property org-special-properties)
10763 (error "The %s property can not yet be set with `org-entry-put'"
10764 property))
10765 (t ; a non-special property
10766 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10767 (setq range (org-get-property-block beg end 'force))
10768 (goto-char (car range))
10769 (if (re-search-forward
10770 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10771 (progn
10772 (delete-region (match-beginning 1) (match-end 1))
10773 (goto-char (match-beginning 1)))
10774 (goto-char (cdr range))
10775 (insert "\n")
10776 (backward-char 1)
10777 (org-indent-line-function)
10778 (insert ":" property ":"))
10779 (and value (insert " " value))
10780 (org-indent-line-function)))))))
10781
10782 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10783 "Get all property keys in the current buffer.
10784 With INCLUDE-SPECIALS, also list the special properties that reflect things
10785 like tags and TODO state.
10786 With INCLUDE-DEFAULTS, also include properties that has special meaning
10787 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10788 With INCLUDE-COLUMNS, also include property names given in COLUMN
10789 formats in the current buffer."
10790 (let (rtn range cfmt s p)
10791 (save-excursion
10792 (save-restriction
10793 (widen)
10794 (goto-char (point-min))
10795 (while (re-search-forward org-property-start-re nil t)
10796 (setq range (org-get-property-block))
10797 (goto-char (car range))
10798 (while (re-search-forward
10799 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10800 (cdr range) t)
10801 (add-to-list 'rtn (org-match-string-no-properties 1)))
10802 (outline-next-heading))))
10803
10804 (when include-specials
10805 (setq rtn (append org-special-properties rtn)))
10806
10807 (when include-defaults
10808 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10809
10810 (when include-columns
10811 (save-excursion
10812 (save-restriction
10813 (widen)
10814 (goto-char (point-min))
10815 (while (re-search-forward
10816 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10817 nil t)
10818 (setq cfmt (match-string 2) s 0)
10819 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10820 cfmt s)
10821 (setq s (match-end 0)
10822 p (match-string 1 cfmt))
10823 (unless (or (equal p "ITEM")
10824 (member p org-special-properties))
10825 (add-to-list 'rtn (match-string 1 cfmt))))))))
10826
10827 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10828
10829 (defun org-property-values (key)
10830 "Return a list of all values of property KEY."
10831 (save-excursion
10832 (save-restriction
10833 (widen)
10834 (goto-char (point-min))
10835 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10836 values)
10837 (while (re-search-forward re nil t)
10838 (add-to-list 'values (org-trim (match-string 1))))
10839 (delete "" values)))))
10840
10841 (defun org-insert-property-drawer ()
10842 "Insert a property drawer into the current entry."
10843 (interactive)
10844 (org-back-to-heading t)
10845 (looking-at outline-regexp)
10846 (let ((indent (- (match-end 0)(match-beginning 0)))
10847 (beg (point))
10848 (re (concat "^[ \t]*" org-keyword-time-regexp))
10849 end hiddenp)
10850 (outline-next-heading)
10851 (setq end (point))
10852 (goto-char beg)
10853 (while (re-search-forward re end t))
10854 (setq hiddenp (org-invisible-p))
10855 (end-of-line 1)
10856 (and (equal (char-after) ?\n) (forward-char 1))
10857 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10858 (beginning-of-line 2))
10859 (org-skip-over-state-notes)
10860 (skip-chars-backward " \t\n\r")
10861 (if (eq (char-before) ?*) (forward-char 1))
10862 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10863 (beginning-of-line 0)
10864 (org-indent-to-column indent)
10865 (beginning-of-line 2)
10866 (org-indent-to-column indent)
10867 (beginning-of-line 0)
10868 (if hiddenp
10869 (save-excursion
10870 (org-back-to-heading t)
10871 (hide-entry))
10872 (org-flag-drawer t))))
10873
10874 (defun org-set-property (property value)
10875 "In the current entry, set PROPERTY to VALUE.
10876 When called interactively, this will prompt for a property name, offering
10877 completion on existing and default properties. And then it will prompt
10878 for a value, offering completion either on allowed values (via an inherited
10879 xxx_ALL property) or on existing values in other instances of this property
10880 in the current file."
10881 (interactive
10882 (let* ((completion-ignore-case t)
10883 (keys (org-buffer-property-keys nil t t))
10884 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10885 (prop (if (member prop0 keys)
10886 prop0
10887 (or (cdr (assoc (downcase prop0)
10888 (mapcar (lambda (x) (cons (downcase x) x))
10889 keys)))
10890 prop0)))
10891 (cur (org-entry-get nil prop))
10892 (allowed (org-property-get-allowed-values nil prop 'table))
10893 (existing (mapcar 'list (org-property-values prop)))
10894 (val (if allowed
10895 (org-completing-read "Value: " allowed nil 'req-match)
10896 (org-completing-read-no-ido
10897 (concat "Value" (if (and cur (string-match "\\S-" cur))
10898 (concat "[" cur "]") "")
10899 ": ")
10900 existing nil nil "" nil cur))))
10901 (list prop (if (equal val "") cur val))))
10902 (unless (equal (org-entry-get nil property) value)
10903 (org-entry-put nil property value)))
10904
10905 (defun org-delete-property (property)
10906 "In the current entry, delete PROPERTY."
10907 (interactive
10908 (let* ((completion-ignore-case t)
10909 (prop (org-ido-completing-read
10910 "Property: " (org-entry-properties nil 'standard))))
10911 (list prop)))
10912 (message "Property %s %s" property
10913 (if (org-entry-delete nil property)
10914 "deleted"
10915 "was not present in the entry")))
10916
10917 (defun org-delete-property-globally (property)
10918 "Remove PROPERTY globally, from all entries."
10919 (interactive
10920 (let* ((completion-ignore-case t)
10921 (prop (org-ido-completing-read
10922 "Globally remove property: "
10923 (mapcar 'list (org-buffer-property-keys)))))
10924 (list prop)))
10925 (save-excursion
10926 (save-restriction
10927 (widen)
10928 (goto-char (point-min))
10929 (let ((cnt 0))
10930 (while (re-search-forward
10931 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10932 nil t)
10933 (setq cnt (1+ cnt))
10934 (replace-match ""))
10935 (message "Property \"%s\" removed from %d entries" property cnt)))))
10936
10937 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10938
10939 (defun org-compute-property-at-point ()
10940 "Compute the property at point.
10941 This looks for an enclosing column format, extracts the operator and
10942 then applies it to the property in the column format's scope."
10943 (interactive)
10944 (unless (org-at-property-p)
10945 (error "Not at a property"))
10946 (let ((prop (org-match-string-no-properties 2)))
10947 (org-columns-get-format-and-top-level)
10948 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10949 (error "No operator defined for property %s" prop))
10950 (org-columns-compute prop)))
10951
10952 (defun org-property-get-allowed-values (pom property &optional table)
10953 "Get allowed values for the property PROPERTY.
10954 When TABLE is non-nil, return an alist that can directly be used for
10955 completion."
10956 (let (vals)
10957 (cond
10958 ((equal property "TODO")
10959 (setq vals (org-with-point-at pom
10960 (append org-todo-keywords-1 '("")))))
10961 ((equal property "PRIORITY")
10962 (let ((n org-lowest-priority))
10963 (while (>= n org-highest-priority)
10964 (push (char-to-string n) vals)
10965 (setq n (1- n)))))
10966 ((member property org-special-properties))
10967 (t
10968 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10969
10970 (when (and vals (string-match "\\S-" vals))
10971 (setq vals (car (read-from-string (concat "(" vals ")"))))
10972 (setq vals (mapcar (lambda (x)
10973 (cond ((stringp x) x)
10974 ((numberp x) (number-to-string x))
10975 ((symbolp x) (symbol-name x))
10976 (t "???")))
10977 vals)))))
10978 (if table (mapcar 'list vals) vals)))
10979
10980 (defun org-property-previous-allowed-value (&optional previous)
10981 "Switch to the next allowed value for this property."
10982 (interactive)
10983 (org-property-next-allowed-value t))
10984
10985 (defun org-property-next-allowed-value (&optional previous)
10986 "Switch to the next allowed value for this property."
10987 (interactive)
10988 (unless (org-at-property-p)
10989 (error "Not at a property"))
10990 (let* ((key (match-string 2))
10991 (value (match-string 3))
10992 (allowed (or (org-property-get-allowed-values (point) key)
10993 (and (member value '("[ ]" "[-]" "[X]"))
10994 '("[ ]" "[X]"))))
10995 nval)
10996 (unless allowed
10997 (error "Allowed values for this property have not been defined"))
10998 (if previous (setq allowed (reverse allowed)))
10999 (if (member value allowed)
11000 (setq nval (car (cdr (member value allowed)))))
11001 (setq nval (or nval (car allowed)))
11002 (if (equal nval value)
11003 (error "Only one allowed value for this property"))
11004 (org-at-property-p)
11005 (replace-match (concat " :" key ": " nval) t t)
11006 (org-indent-line-function)
11007 (beginning-of-line 1)
11008 (skip-chars-forward " \t")))
11009
11010 (defun org-find-entry-with-id (ident)
11011 "Locate the entry that contains the ID property with exact value IDENT.
11012 IDENT can be a string, a symbol or a number, this function will search for
11013 the string representation of it.
11014 Return the position where this entry starts, or nil if there is no such entry."
11015 (interactive "sID: ")
11016 (let ((id (cond
11017 ((stringp ident) ident)
11018 ((symbol-name ident) (symbol-name ident))
11019 ((numberp ident) (number-to-string ident))
11020 (t (error "IDENT %s must be a string, symbol or number" ident))))
11021 (case-fold-search nil))
11022 (save-excursion
11023 (save-restriction
11024 (widen)
11025 (goto-char (point-min))
11026 (when (re-search-forward
11027 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11028 nil t)
11029 (org-back-to-heading)
11030 (point))))))
11031
11032 ;;;; Timestamps
11033
11034 (defvar org-last-changed-timestamp nil)
11035 (defvar org-last-inserted-timestamp nil
11036 "The last time stamp inserted with `org-insert-time-stamp'.")
11037 (defvar org-time-was-given) ; dynamically scoped parameter
11038 (defvar org-end-time-was-given) ; dynamically scoped parameter
11039 (defvar org-ts-what) ; dynamically scoped parameter
11040
11041 (defun org-time-stamp (arg &optional inactive)
11042 "Prompt for a date/time and insert a time stamp.
11043 If the user specifies a time like HH:MM, or if this command is called
11044 with a prefix argument, the time stamp will contain date and time.
11045 Otherwise, only the date will be included. All parts of a date not
11046 specified by the user will be filled in from the current date/time.
11047 So if you press just return without typing anything, the time stamp
11048 will represent the current date/time. If there is already a timestamp
11049 at the cursor, it will be modified."
11050 (interactive "P")
11051 (let* ((ts nil)
11052 (default-time
11053 ;; Default time is either today, or, when entering a range,
11054 ;; the range start.
11055 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11056 (save-excursion
11057 (re-search-backward
11058 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11059 (- (point) 20) t)))
11060 (apply 'encode-time (org-parse-time-string (match-string 1)))
11061 (current-time)))
11062 (default-input (and ts (org-get-compact-tod ts)))
11063 org-time-was-given org-end-time-was-given time)
11064 (cond
11065 ((and (org-at-timestamp-p t)
11066 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11067 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11068 (insert "--")
11069 (setq time (let ((this-command this-command))
11070 (org-read-date arg 'totime nil nil
11071 default-time default-input)))
11072 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11073 ((org-at-timestamp-p t)
11074 (setq time (let ((this-command this-command))
11075 (org-read-date arg 'totime nil nil default-time default-input)))
11076 (when (org-at-timestamp-p t) ; just to get the match data
11077 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11078 (replace-match "")
11079 (setq org-last-changed-timestamp
11080 (org-insert-time-stamp
11081 time (or org-time-was-given arg)
11082 inactive nil nil (list org-end-time-was-given))))
11083 (message "Timestamp updated"))
11084 (t
11085 (setq time (let ((this-command this-command))
11086 (org-read-date arg 'totime nil nil default-time default-input)))
11087 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11088 nil nil (list org-end-time-was-given))))))
11089
11090 ;; FIXME: can we use this for something else, like computing time differences?
11091 (defun org-get-compact-tod (s)
11092 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11093 (let* ((t1 (match-string 1 s))
11094 (h1 (string-to-number (match-string 2 s)))
11095 (m1 (string-to-number (match-string 3 s)))
11096 (t2 (and (match-end 4) (match-string 5 s)))
11097 (h2 (and t2 (string-to-number (match-string 6 s))))
11098 (m2 (and t2 (string-to-number (match-string 7 s))))
11099 dh dm)
11100 (if (not t2)
11101 t1
11102 (setq dh (- h2 h1) dm (- m2 m1))
11103 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11104 (concat t1 "+" (number-to-string dh)
11105 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11106
11107 (defun org-time-stamp-inactive (&optional arg)
11108 "Insert an inactive time stamp.
11109 An inactive time stamp is enclosed in square brackets instead of angle
11110 brackets. It is inactive in the sense that it does not trigger agenda entries,
11111 does not link to the calendar and cannot be changed with the S-cursor keys.
11112 So these are more for recording a certain time/date."
11113 (interactive "P")
11114 (org-time-stamp arg 'inactive))
11115
11116 (defvar org-date-ovl (org-make-overlay 1 1))
11117 (org-overlay-put org-date-ovl 'face 'org-warning)
11118 (org-detach-overlay org-date-ovl)
11119
11120 (defvar org-ans1) ; dynamically scoped parameter
11121 (defvar org-ans2) ; dynamically scoped parameter
11122
11123 (defvar org-plain-time-of-day-regexp) ; defined below
11124
11125 (defvar org-overriding-default-time nil) ; dynamically scoped
11126 (defvar org-read-date-overlay nil)
11127 (defvar org-dcst nil) ; dynamically scoped
11128
11129 (defun org-read-date (&optional with-time to-time from-string prompt
11130 default-time default-input)
11131 "Read a date, possibly a time, and make things smooth for the user.
11132 The prompt will suggest to enter an ISO date, but you can also enter anything
11133 which will at least partially be understood by `parse-time-string'.
11134 Unrecognized parts of the date will default to the current day, month, year,
11135 hour and minute. If this command is called to replace a timestamp at point,
11136 of to enter the second timestamp of a range, the default time is taken from the
11137 existing stamp. For example,
11138 3-2-5 --> 2003-02-05
11139 feb 15 --> currentyear-02-15
11140 sep 12 9 --> 2009-09-12
11141 12:45 --> today 12:45
11142 22 sept 0:34 --> currentyear-09-22 0:34
11143 12 --> currentyear-currentmonth-12
11144 Fri --> nearest Friday (today or later)
11145 etc.
11146
11147 Furthermore you can specify a relative date by giving, as the *first* thing
11148 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11149 change in days weeks, months, years.
11150 With a single plus or minus, the date is relative to today. With a double
11151 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11152 +4d --> four days from today
11153 +4 --> same as above
11154 +2w --> two weeks from today
11155 ++5 --> five days from default date
11156
11157 The function understands only English month and weekday abbreviations,
11158 but this can be configured with the variables `parse-time-months' and
11159 `parse-time-weekdays'.
11160
11161 While prompting, a calendar is popped up - you can also select the
11162 date with the mouse (button 1). The calendar shows a period of three
11163 months. To scroll it to other months, use the keys `>' and `<'.
11164 If you don't like the calendar, turn it off with
11165 \(setq org-read-date-popup-calendar nil)
11166
11167 With optional argument TO-TIME, the date will immediately be converted
11168 to an internal time.
11169 With an optional argument WITH-TIME, the prompt will suggest to also
11170 insert a time. Note that when WITH-TIME is not set, you can still
11171 enter a time, and this function will inform the calling routine about
11172 this change. The calling routine may then choose to change the format
11173 used to insert the time stamp into the buffer to include the time.
11174 With optional argument FROM-STRING, read from this string instead from
11175 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11176 the time/date that is used for everything that is not specified by the
11177 user."
11178 (require 'parse-time)
11179 (let* ((org-time-stamp-rounding-minutes
11180 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11181 (org-dcst org-display-custom-times)
11182 (ct (org-current-time))
11183 (def (or org-overriding-default-time default-time ct))
11184 (defdecode (decode-time def))
11185 (dummy (progn
11186 (when (< (nth 2 defdecode) org-extend-today-until)
11187 (setcar (nthcdr 2 defdecode) -1)
11188 (setcar (nthcdr 1 defdecode) 59)
11189 (setq def (apply 'encode-time defdecode)
11190 defdecode (decode-time def)))))
11191 (calendar-move-hook nil)
11192 (calendar-view-diary-initially-flag nil)
11193 (view-diary-entries-initially nil)
11194 (calendar-view-holidays-initially-flag nil)
11195 (view-calendar-holidays-initially nil)
11196 (timestr (format-time-string
11197 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11198 (prompt (concat (if prompt (concat prompt " ") "")
11199 (format "Date+time [%s]: " timestr)))
11200 ans (org-ans0 "") org-ans1 org-ans2 final)
11201
11202 (cond
11203 (from-string (setq ans from-string))
11204 (org-read-date-popup-calendar
11205 (save-excursion
11206 (save-window-excursion
11207 (calendar)
11208 (calendar-forward-day (- (time-to-days def)
11209 (calendar-absolute-from-gregorian
11210 (calendar-current-date))))
11211 (org-eval-in-calendar nil t)
11212 (let* ((old-map (current-local-map))
11213 (map (copy-keymap calendar-mode-map))
11214 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11215 (org-defkey map (kbd "RET") 'org-calendar-select)
11216 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11217 'org-calendar-select-mouse)
11218 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11219 'org-calendar-select-mouse)
11220 (org-defkey minibuffer-local-map [(meta shift left)]
11221 (lambda () (interactive)
11222 (org-eval-in-calendar '(calendar-backward-month 1))))
11223 (org-defkey minibuffer-local-map [(meta shift right)]
11224 (lambda () (interactive)
11225 (org-eval-in-calendar '(calendar-forward-month 1))))
11226 (org-defkey minibuffer-local-map [(meta shift up)]
11227 (lambda () (interactive)
11228 (org-eval-in-calendar '(calendar-backward-year 1))))
11229 (org-defkey minibuffer-local-map [(meta shift down)]
11230 (lambda () (interactive)
11231 (org-eval-in-calendar '(calendar-forward-year 1))))
11232 (org-defkey minibuffer-local-map [(shift up)]
11233 (lambda () (interactive)
11234 (org-eval-in-calendar '(calendar-backward-week 1))))
11235 (org-defkey minibuffer-local-map [(shift down)]
11236 (lambda () (interactive)
11237 (org-eval-in-calendar '(calendar-forward-week 1))))
11238 (org-defkey minibuffer-local-map [(shift left)]
11239 (lambda () (interactive)
11240 (org-eval-in-calendar '(calendar-backward-day 1))))
11241 (org-defkey minibuffer-local-map [(shift right)]
11242 (lambda () (interactive)
11243 (org-eval-in-calendar '(calendar-forward-day 1))))
11244 (org-defkey minibuffer-local-map ">"
11245 (lambda () (interactive)
11246 (org-eval-in-calendar '(scroll-calendar-left 1))))
11247 (org-defkey minibuffer-local-map "<"
11248 (lambda () (interactive)
11249 (org-eval-in-calendar '(scroll-calendar-right 1))))
11250 (unwind-protect
11251 (progn
11252 (use-local-map map)
11253 (add-hook 'post-command-hook 'org-read-date-display)
11254 (setq org-ans0 (read-string prompt default-input nil nil))
11255 ;; org-ans0: from prompt
11256 ;; org-ans1: from mouse click
11257 ;; org-ans2: from calendar motion
11258 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11259 (remove-hook 'post-command-hook 'org-read-date-display)
11260 (use-local-map old-map)
11261 (when org-read-date-overlay
11262 (org-delete-overlay org-read-date-overlay)
11263 (setq org-read-date-overlay nil)))))))
11264
11265 (t ; Naked prompt only
11266 (unwind-protect
11267 (setq ans (read-string prompt default-input nil timestr))
11268 (when org-read-date-overlay
11269 (org-delete-overlay org-read-date-overlay)
11270 (setq org-read-date-overlay nil)))))
11271
11272 (setq final (org-read-date-analyze ans def defdecode))
11273
11274 (if to-time
11275 (apply 'encode-time final)
11276 (if (and (boundp 'org-time-was-given) org-time-was-given)
11277 (format "%04d-%02d-%02d %02d:%02d"
11278 (nth 5 final) (nth 4 final) (nth 3 final)
11279 (nth 2 final) (nth 1 final))
11280 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11281 (defvar def)
11282 (defvar defdecode)
11283 (defvar with-time)
11284 (defun org-read-date-display ()
11285 "Display the current date prompt interpretation in the minibuffer."
11286 (when org-read-date-display-live
11287 (when org-read-date-overlay
11288 (org-delete-overlay org-read-date-overlay))
11289 (let ((p (point)))
11290 (end-of-line 1)
11291 (while (not (equal (buffer-substring
11292 (max (point-min) (- (point) 4)) (point))
11293 " "))
11294 (insert " "))
11295 (goto-char p))
11296 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11297 " " (or org-ans1 org-ans2)))
11298 (org-end-time-was-given nil)
11299 (f (org-read-date-analyze ans def defdecode))
11300 (fmts (if org-dcst
11301 org-time-stamp-custom-formats
11302 org-time-stamp-formats))
11303 (fmt (if (or with-time
11304 (and (boundp 'org-time-was-given) org-time-was-given))
11305 (cdr fmts)
11306 (car fmts)))
11307 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11308 (when (and org-end-time-was-given
11309 (string-match org-plain-time-of-day-regexp txt))
11310 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11311 org-end-time-was-given
11312 (substring txt (match-end 0)))))
11313 (setq org-read-date-overlay
11314 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11315 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11316
11317 (defun org-read-date-analyze (ans def defdecode)
11318 "Analyse the combined answer of the date prompt."
11319 ;; FIXME: cleanup and comment
11320 (let (delta deltan deltaw deltadef year month day
11321 hour minute second wday pm h2 m2 tl wday1
11322 iso-year iso-weekday iso-week iso-year iso-date)
11323
11324 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11325 (setq ans "+0"))
11326
11327 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11328 (setq ans (replace-match "" t t ans)
11329 deltan (car delta)
11330 deltaw (nth 1 delta)
11331 deltadef (nth 2 delta)))
11332
11333 ;; Check if there is an iso week date in there
11334 ;; If yes, sore the info and postpone interpreting it until the rest
11335 ;; of the parsing is done
11336 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11337 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11338 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11339 iso-week (string-to-number (match-string 2 ans)))
11340 (setq ans (replace-match "" t t ans)))
11341
11342 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11343 (when (string-match
11344 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11345 (setq year (if (match-end 2)
11346 (string-to-number (match-string 2 ans))
11347 (string-to-number (format-time-string "%Y")))
11348 month (string-to-number (match-string 3 ans))
11349 day (string-to-number (match-string 4 ans)))
11350 (if (< year 100) (setq year (+ 2000 year)))
11351 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11352 t nil ans)))
11353 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11354 ;; If there is a time with am/pm, and *no* time without it, we convert
11355 ;; so that matching will be successful.
11356 (loop for i from 1 to 2 do ; twice, for end time as well
11357 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11358 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11359 (setq hour (string-to-number (match-string 1 ans))
11360 minute (if (match-end 3)
11361 (string-to-number (match-string 3 ans))
11362 0)
11363 pm (equal ?p
11364 (string-to-char (downcase (match-string 4 ans)))))
11365 (if (and (= hour 12) (not pm))
11366 (setq hour 0)
11367 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11368 (setq ans (replace-match (format "%02d:%02d" hour minute)
11369 t t ans))))
11370
11371 ;; Check if a time range is given as a duration
11372 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11373 (setq hour (string-to-number (match-string 1 ans))
11374 h2 (+ hour (string-to-number (match-string 3 ans)))
11375 minute (string-to-number (match-string 2 ans))
11376 m2 (+ minute (if (match-end 5) (string-to-number
11377 (match-string 5 ans))0)))
11378 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11379 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11380 t t ans)))
11381
11382 ;; Check if there is a time range
11383 (when (boundp 'org-end-time-was-given)
11384 (setq org-time-was-given nil)
11385 (when (and (string-match org-plain-time-of-day-regexp ans)
11386 (match-end 8))
11387 (setq org-end-time-was-given (match-string 8 ans))
11388 (setq ans (concat (substring ans 0 (match-beginning 7))
11389 (substring ans (match-end 7))))))
11390
11391 (setq tl (parse-time-string ans)
11392 day (or (nth 3 tl) (nth 3 defdecode))
11393 month (or (nth 4 tl)
11394 (if (and org-read-date-prefer-future
11395 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11396 (1+ (nth 4 defdecode))
11397 (nth 4 defdecode)))
11398 year (or (nth 5 tl)
11399 (if (and org-read-date-prefer-future
11400 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11401 (1+ (nth 5 defdecode))
11402 (nth 5 defdecode)))
11403 hour (or (nth 2 tl) (nth 2 defdecode))
11404 minute (or (nth 1 tl) (nth 1 defdecode))
11405 second (or (nth 0 tl) 0)
11406 wday (nth 6 tl))
11407
11408 ;; Special date definitions below
11409 (cond
11410 (iso-week
11411 ;; There was an iso week
11412 (setq year (or iso-year year)
11413 day (or iso-weekday wday 1)
11414 wday nil ; to make sure that the trigger below does not match
11415 iso-date (calendar-gregorian-from-absolute
11416 (calendar-absolute-from-iso
11417 (list iso-week day year))))
11418 ; FIXME: Should we also push ISO weeks into the future?
11419 ; (when (and org-read-date-prefer-future
11420 ; (not iso-year)
11421 ; (< (calendar-absolute-from-gregorian iso-date)
11422 ; (time-to-days (current-time))))
11423 ; (setq year (1+ year)
11424 ; iso-date (calendar-gregorian-from-absolute
11425 ; (calendar-absolute-from-iso
11426 ; (list iso-week day year)))))
11427 (setq month (car iso-date)
11428 year (nth 2 iso-date)
11429 day (nth 1 iso-date)))
11430 (deltan
11431 (unless deltadef
11432 (let ((now (decode-time (current-time))))
11433 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11434 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11435 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11436 ((equal deltaw "m") (setq month (+ month deltan)))
11437 ((equal deltaw "y") (setq year (+ year deltan)))))
11438 ((and wday (not (nth 3 tl)))
11439 ;; Weekday was given, but no day, so pick that day in the week
11440 ;; on or after the derived date.
11441 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11442 (unless (equal wday wday1)
11443 (setq day (+ day (% (- wday wday1 -7) 7))))))
11444 (if (and (boundp 'org-time-was-given)
11445 (nth 2 tl))
11446 (setq org-time-was-given t))
11447 (if (< year 100) (setq year (+ 2000 year)))
11448 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11449 (list second minute hour day month year)))
11450
11451 (defvar parse-time-weekdays)
11452
11453 (defun org-read-date-get-relative (s today default)
11454 "Check string S for special relative date string.
11455 TODAY and DEFAULT are internal times, for today and for a default.
11456 Return shift list (N what def-flag)
11457 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11458 N is the number of WHATs to shift.
11459 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11460 the DEFAULT date rather than TODAY."
11461 (when (and
11462 (string-match
11463 (concat
11464 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11465 "\\([0-9]+\\)?"
11466 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11467 "\\([ \t]\\|$\\)") s)
11468 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11469 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11470 (string-to-char (substring (match-string 1 s) -1))
11471 ?+))
11472 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11473 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11474 (what (if (match-end 3) (match-string 3 s) "d"))
11475 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11476 (date (if rel default today))
11477 (wday (nth 6 (decode-time date)))
11478 delta)
11479 (if wday1
11480 (progn
11481 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11482 (if (= dir ?-) (setq delta (- delta 7)))
11483 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11484 (list delta "d" rel))
11485 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11486
11487 (defun org-eval-in-calendar (form &optional keepdate)
11488 "Eval FORM in the calendar window and return to current window.
11489 Also, store the cursor date in variable org-ans2."
11490 (let ((sw (selected-window)))
11491 (select-window (get-buffer-window "*Calendar*"))
11492 (eval form)
11493 (when (and (not keepdate) (calendar-cursor-to-date))
11494 (let* ((date (calendar-cursor-to-date))
11495 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11496 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11497 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11498 (select-window sw)))
11499
11500 (defun org-calendar-select ()
11501 "Return to `org-read-date' with the date currently selected.
11502 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11503 (interactive)
11504 (when (calendar-cursor-to-date)
11505 (let* ((date (calendar-cursor-to-date))
11506 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11507 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11508 (if (active-minibuffer-window) (exit-minibuffer))))
11509
11510 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11511 "Insert a date stamp for the date given by the internal TIME.
11512 WITH-HM means, use the stamp format that includes the time of the day.
11513 INACTIVE means use square brackets instead of angular ones, so that the
11514 stamp will not contribute to the agenda.
11515 PRE and POST are optional strings to be inserted before and after the
11516 stamp.
11517 The command returns the inserted time stamp."
11518 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11519 stamp)
11520 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11521 (insert-before-markers (or pre ""))
11522 (insert-before-markers (setq stamp (format-time-string fmt time)))
11523 (when (listp extra)
11524 (setq extra (car extra))
11525 (if (and (stringp extra)
11526 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11527 (setq extra (format "-%02d:%02d"
11528 (string-to-number (match-string 1 extra))
11529 (string-to-number (match-string 2 extra))))
11530 (setq extra nil)))
11531 (when extra
11532 (backward-char 1)
11533 (insert-before-markers extra)
11534 (forward-char 1))
11535 (insert-before-markers (or post ""))
11536 (setq org-last-inserted-timestamp stamp)))
11537
11538 (defun org-toggle-time-stamp-overlays ()
11539 "Toggle the use of custom time stamp formats."
11540 (interactive)
11541 (setq org-display-custom-times (not org-display-custom-times))
11542 (unless org-display-custom-times
11543 (let ((p (point-min)) (bmp (buffer-modified-p)))
11544 (while (setq p (next-single-property-change p 'display))
11545 (if (and (get-text-property p 'display)
11546 (eq (get-text-property p 'face) 'org-date))
11547 (remove-text-properties
11548 p (setq p (next-single-property-change p 'display))
11549 '(display t))))
11550 (set-buffer-modified-p bmp)))
11551 (if (featurep 'xemacs)
11552 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11553 (org-restart-font-lock)
11554 (setq org-table-may-need-update t)
11555 (if org-display-custom-times
11556 (message "Time stamps are overlayed with custom format")
11557 (message "Time stamp overlays removed")))
11558
11559 (defun org-display-custom-time (beg end)
11560 "Overlay modified time stamp format over timestamp between BEG and END."
11561 (let* ((ts (buffer-substring beg end))
11562 t1 w1 with-hm tf time str w2 (off 0))
11563 (save-match-data
11564 (setq t1 (org-parse-time-string ts t))
11565 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11566 (setq off (- (match-end 0) (match-beginning 0)))))
11567 (setq end (- end off))
11568 (setq w1 (- end beg)
11569 with-hm (and (nth 1 t1) (nth 2 t1))
11570 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11571 time (org-fix-decoded-time t1)
11572 str (org-add-props
11573 (format-time-string
11574 (substring tf 1 -1) (apply 'encode-time time))
11575 nil 'mouse-face 'highlight)
11576 w2 (length str))
11577 (if (not (= w2 w1))
11578 (add-text-properties (1+ beg) (+ 2 beg)
11579 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11580 (if (featurep 'xemacs)
11581 (progn
11582 (put-text-property beg end 'invisible t)
11583 (put-text-property beg end 'end-glyph (make-glyph str)))
11584 (put-text-property beg end 'display str))))
11585
11586 (defun org-translate-time (string)
11587 "Translate all timestamps in STRING to custom format.
11588 But do this only if the variable `org-display-custom-times' is set."
11589 (when org-display-custom-times
11590 (save-match-data
11591 (let* ((start 0)
11592 (re org-ts-regexp-both)
11593 t1 with-hm inactive tf time str beg end)
11594 (while (setq start (string-match re string start))
11595 (setq beg (match-beginning 0)
11596 end (match-end 0)
11597 t1 (save-match-data
11598 (org-parse-time-string (substring string beg end) t))
11599 with-hm (and (nth 1 t1) (nth 2 t1))
11600 inactive (equal (substring string beg (1+ beg)) "[")
11601 tf (funcall (if with-hm 'cdr 'car)
11602 org-time-stamp-custom-formats)
11603 time (org-fix-decoded-time t1)
11604 str (format-time-string
11605 (concat
11606 (if inactive "[" "<") (substring tf 1 -1)
11607 (if inactive "]" ">"))
11608 (apply 'encode-time time))
11609 string (replace-match str t t string)
11610 start (+ start (length str)))))))
11611 string)
11612
11613 (defun org-fix-decoded-time (time)
11614 "Set 0 instead of nil for the first 6 elements of time.
11615 Don't touch the rest."
11616 (let ((n 0))
11617 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11618
11619 (defun org-days-to-time (timestamp-string)
11620 "Difference between TIMESTAMP-STRING and now in days."
11621 (- (time-to-days (org-time-string-to-time timestamp-string))
11622 (time-to-days (current-time))))
11623
11624 (defun org-deadline-close (timestamp-string &optional ndays)
11625 "Is the time in TIMESTAMP-STRING close to the current date?"
11626 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11627 (and (< (org-days-to-time timestamp-string) ndays)
11628 (not (org-entry-is-done-p))))
11629
11630 (defun org-get-wdays (ts)
11631 "Get the deadline lead time appropriate for timestring TS."
11632 (cond
11633 ((<= org-deadline-warning-days 0)
11634 ;; 0 or negative, enforce this value no matter what
11635 (- org-deadline-warning-days))
11636 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11637 ;; lead time is specified.
11638 (floor (* (string-to-number (match-string 1 ts))
11639 (cdr (assoc (match-string 2 ts)
11640 '(("d" . 1) ("w" . 7)
11641 ("m" . 30.4) ("y" . 365.25)))))))
11642 ;; go for the default.
11643 (t org-deadline-warning-days)))
11644
11645 (defun org-calendar-select-mouse (ev)
11646 "Return to `org-read-date' with the date currently selected.
11647 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11648 (interactive "e")
11649 (mouse-set-point ev)
11650 (when (calendar-cursor-to-date)
11651 (let* ((date (calendar-cursor-to-date))
11652 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11653 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11654 (if (active-minibuffer-window) (exit-minibuffer))))
11655
11656 (defun org-check-deadlines (ndays)
11657 "Check if there are any deadlines due or past due.
11658 A deadline is considered due if it happens within `org-deadline-warning-days'
11659 days from today's date. If the deadline appears in an entry marked DONE,
11660 it is not shown. The prefix arg NDAYS can be used to test that many
11661 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11662 (interactive "P")
11663 (let* ((org-warn-days
11664 (cond
11665 ((equal ndays '(4)) 100000)
11666 (ndays (prefix-numeric-value ndays))
11667 (t (abs org-deadline-warning-days))))
11668 (case-fold-search nil)
11669 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11670 (callback
11671 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11672
11673 (message "%d deadlines past-due or due within %d days"
11674 (org-occur regexp nil callback)
11675 org-warn-days)))
11676
11677 (defun org-check-before-date (date)
11678 "Check if there are deadlines or scheduled entries before DATE."
11679 (interactive (list (org-read-date)))
11680 (let ((case-fold-search nil)
11681 (regexp (concat "\\<\\(" org-deadline-string
11682 "\\|" org-scheduled-string
11683 "\\) *<\\([^>]+\\)>"))
11684 (callback
11685 (lambda () (time-less-p
11686 (org-time-string-to-time (match-string 2))
11687 (org-time-string-to-time date)))))
11688 (message "%d entries before %s"
11689 (org-occur regexp nil callback) date)))
11690
11691 (defun org-evaluate-time-range (&optional to-buffer)
11692 "Evaluate a time range by computing the difference between start and end.
11693 Normally the result is just printed in the echo area, but with prefix arg
11694 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11695 If the time range is actually in a table, the result is inserted into the
11696 next column.
11697 For time difference computation, a year is assumed to be exactly 365
11698 days in order to avoid rounding problems."
11699 (interactive "P")
11700 (or
11701 (org-clock-update-time-maybe)
11702 (save-excursion
11703 (unless (org-at-date-range-p t)
11704 (goto-char (point-at-bol))
11705 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11706 (if (not (org-at-date-range-p t))
11707 (error "Not at a time-stamp range, and none found in current line")))
11708 (let* ((ts1 (match-string 1))
11709 (ts2 (match-string 2))
11710 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11711 (match-end (match-end 0))
11712 (time1 (org-time-string-to-time ts1))
11713 (time2 (org-time-string-to-time ts2))
11714 (t1 (time-to-seconds time1))
11715 (t2 (time-to-seconds time2))
11716 (diff (abs (- t2 t1)))
11717 (negative (< (- t2 t1) 0))
11718 ;; (ys (floor (* 365 24 60 60)))
11719 (ds (* 24 60 60))
11720 (hs (* 60 60))
11721 (fy "%dy %dd %02d:%02d")
11722 (fy1 "%dy %dd")
11723 (fd "%dd %02d:%02d")
11724 (fd1 "%dd")
11725 (fh "%02d:%02d")
11726 y d h m align)
11727 (if havetime
11728 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11729 y 0
11730 d (floor (/ diff ds)) diff (mod diff ds)
11731 h (floor (/ diff hs)) diff (mod diff hs)
11732 m (floor (/ diff 60)))
11733 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11734 y 0
11735 d (floor (+ (/ diff ds) 0.5))
11736 h 0 m 0))
11737 (if (not to-buffer)
11738 (message "%s" (org-make-tdiff-string y d h m))
11739 (if (org-at-table-p)
11740 (progn
11741 (goto-char match-end)
11742 (setq align t)
11743 (and (looking-at " *|") (goto-char (match-end 0))))
11744 (goto-char match-end))
11745 (if (looking-at
11746 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11747 (replace-match ""))
11748 (if negative (insert " -"))
11749 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11750 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11751 (insert " " (format fh h m))))
11752 (if align (org-table-align))
11753 (message "Time difference inserted")))))
11754
11755 (defun org-make-tdiff-string (y d h m)
11756 (let ((fmt "")
11757 (l nil))
11758 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11759 l (push y l)))
11760 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11761 l (push d l)))
11762 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11763 l (push h l)))
11764 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11765 l (push m l)))
11766 (apply 'format fmt (nreverse l))))
11767
11768 (defun org-time-string-to-time (s)
11769 (apply 'encode-time (org-parse-time-string s)))
11770
11771 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11772 "Convert a time stamp to an absolute day number.
11773 If there is a specifyer for a cyclic time stamp, get the closest date to
11774 DAYNR.
11775 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11776 (cond
11777 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11778 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11779 daynr
11780 (+ daynr 1000)))
11781 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11782 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11783 (time-to-days (current-time))) (match-string 0 s)
11784 prefer show-all))
11785 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11786
11787 (defun org-days-to-iso-week (days)
11788 "Return the iso week number."
11789 (require 'cal-iso)
11790 (car (calendar-iso-from-absolute days)))
11791
11792 (defun org-small-year-to-year (year)
11793 "Convert 2-digit years into 4-digit years.
11794 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11795 The year 2000 cannot be abbreviated. Any year larger than 99
11796 is returned unchanged."
11797 (if (< year 38)
11798 (setq year (+ 2000 year))
11799 (if (< year 100)
11800 (setq year (+ 1900 year))))
11801 year)
11802
11803 (defun org-time-from-absolute (d)
11804 "Return the time corresponding to date D.
11805 D may be an absolute day number, or a calendar-type list (month day year)."
11806 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11807 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11808
11809 (defun org-calendar-holiday ()
11810 "List of holidays, for Diary display in Org-mode."
11811 (require 'holidays)
11812 (let ((hl (funcall
11813 (if (fboundp 'calendar-check-holidays)
11814 'calendar-check-holidays 'check-calendar-holidays) date)))
11815 (if hl (mapconcat 'identity hl "; "))))
11816
11817 (defun org-diary-sexp-entry (sexp entry date)
11818 "Process a SEXP diary ENTRY for DATE."
11819 (require 'diary-lib)
11820 (let ((result (if calendar-debug-sexp
11821 (let ((stack-trace-on-error t))
11822 (eval (car (read-from-string sexp))))
11823 (condition-case nil
11824 (eval (car (read-from-string sexp)))
11825 (error
11826 (beep)
11827 (message "Bad sexp at line %d in %s: %s"
11828 (org-current-line)
11829 (buffer-file-name) sexp)
11830 (sleep-for 2))))))
11831 (cond ((stringp result) result)
11832 ((and (consp result)
11833 (stringp (cdr result))) (cdr result))
11834 (result entry)
11835 (t nil))))
11836
11837 (defun org-diary-to-ical-string (frombuf)
11838 "Get iCalendar entries from diary entries in buffer FROMBUF.
11839 This uses the icalendar.el library."
11840 (let* ((tmpdir (if (featurep 'xemacs)
11841 (temp-directory)
11842 temporary-file-directory))
11843 (tmpfile (make-temp-name
11844 (expand-file-name "orgics" tmpdir)))
11845 buf rtn b e)
11846 (save-excursion
11847 (set-buffer frombuf)
11848 (icalendar-export-region (point-min) (point-max) tmpfile)
11849 (setq buf (find-buffer-visiting tmpfile))
11850 (set-buffer buf)
11851 (goto-char (point-min))
11852 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11853 (setq b (match-beginning 0)))
11854 (goto-char (point-max))
11855 (if (re-search-backward "^END:VEVENT" nil t)
11856 (setq e (match-end 0)))
11857 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11858 (kill-buffer buf)
11859 (delete-file tmpfile)
11860 rtn))
11861
11862 (defun org-closest-date (start current change prefer show-all)
11863 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11864 When PREFER is `past' return a date that is either CURRENT or past.
11865 When PREFER is `future', return a date that is either CURRENT or future.
11866 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11867 ;; Make the proper lists from the dates
11868 (catch 'exit
11869 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11870 dn dw sday cday n1 n2 n0
11871 d m y y1 y2 date1 date2 nmonths nm ny m2)
11872
11873 (setq start (org-date-to-gregorian start)
11874 current (org-date-to-gregorian
11875 (if show-all
11876 current
11877 (time-to-days (current-time))))
11878 sday (calendar-absolute-from-gregorian start)
11879 cday (calendar-absolute-from-gregorian current))
11880
11881 (if (<= cday sday) (throw 'exit sday))
11882
11883 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11884 (setq dn (string-to-number (match-string 1 change))
11885 dw (cdr (assoc (match-string 2 change) a1)))
11886 (error "Invalid change specifyer: %s" change))
11887 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11888 (cond
11889 ((eq dw 'day)
11890 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11891 n2 (+ n1 dn)))
11892 ((eq dw 'year)
11893 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11894 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11895 (setq date1 (list m d y1)
11896 n1 (calendar-absolute-from-gregorian date1)
11897 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11898 n2 (calendar-absolute-from-gregorian date2)))
11899 ((eq dw 'month)
11900 ;; approx number of month between the two dates
11901 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11902 ;; How often does dn fit in there?
11903 (setq d (nth 1 start) m (car start) y (nth 2 start)
11904 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11905 m (+ m nm)
11906 ny (floor (/ m 12))
11907 y (+ y ny)
11908 m (- m (* ny 12)))
11909 (while (> m 12) (setq m (- m 12) y (1+ y)))
11910 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11911 (setq m2 (+ m dn) y2 y)
11912 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11913 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11914 (while (<= n2 cday)
11915 (setq n1 n2 m m2 y y2)
11916 (setq m2 (+ m dn) y2 y)
11917 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11918 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11919 ;; Make sure n1 is the earlier date
11920 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
11921 (if show-all
11922 (cond
11923 ((eq prefer 'past) n1)
11924 ((eq prefer 'future) (if (= cday n1) n1 n2))
11925 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11926 (cond
11927 ((eq prefer 'past) n1)
11928 ((eq prefer 'future) (if (= cday n1) n1 n2))
11929 (t (if (= cday n1) n1 n2)))))))
11930
11931 (defun org-date-to-gregorian (date)
11932 "Turn any specification of DATE into a gregorian date for the calendar."
11933 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11934 ((and (listp date) (= (length date) 3)) date)
11935 ((stringp date)
11936 (setq date (org-parse-time-string date))
11937 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11938 ((listp date)
11939 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11940
11941 (defun org-parse-time-string (s &optional nodefault)
11942 "Parse the standard Org-mode time string.
11943 This should be a lot faster than the normal `parse-time-string'.
11944 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11945 hour and minute fields will be nil if not given."
11946 (if (string-match org-ts-regexp0 s)
11947 (list 0
11948 (if (or (match-beginning 8) (not nodefault))
11949 (string-to-number (or (match-string 8 s) "0")))
11950 (if (or (match-beginning 7) (not nodefault))
11951 (string-to-number (or (match-string 7 s) "0")))
11952 (string-to-number (match-string 4 s))
11953 (string-to-number (match-string 3 s))
11954 (string-to-number (match-string 2 s))
11955 nil nil nil)
11956 (make-list 9 0)))
11957
11958 (defun org-timestamp-up (&optional arg)
11959 "Increase the date item at the cursor by one.
11960 If the cursor is on the year, change the year. If it is on the month or
11961 the day, change that.
11962 With prefix ARG, change by that many units."
11963 (interactive "p")
11964 (org-timestamp-change (prefix-numeric-value arg)))
11965
11966 (defun org-timestamp-down (&optional arg)
11967 "Decrease the date item at the cursor by one.
11968 If the cursor is on the year, change the year. If it is on the month or
11969 the day, change that.
11970 With prefix ARG, change by that many units."
11971 (interactive "p")
11972 (org-timestamp-change (- (prefix-numeric-value arg))))
11973
11974 (defun org-timestamp-up-day (&optional arg)
11975 "Increase the date in the time stamp by one day.
11976 With prefix ARG, change that many days."
11977 (interactive "p")
11978 (if (and (not (org-at-timestamp-p t))
11979 (org-on-heading-p))
11980 (org-todo 'up)
11981 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11982
11983 (defun org-timestamp-down-day (&optional arg)
11984 "Decrease the date in the time stamp by one day.
11985 With prefix ARG, change that many days."
11986 (interactive "p")
11987 (if (and (not (org-at-timestamp-p t))
11988 (org-on-heading-p))
11989 (org-todo 'down)
11990 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11991
11992 (defun org-at-timestamp-p (&optional inactive-ok)
11993 "Determine if the cursor is in or at a timestamp."
11994 (interactive)
11995 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11996 (pos (point))
11997 (ans (or (looking-at tsr)
11998 (save-excursion
11999 (skip-chars-backward "^[<\n\r\t")
12000 (if (> (point) (point-min)) (backward-char 1))
12001 (and (looking-at tsr)
12002 (> (- (match-end 0) pos) -1))))))
12003 (and ans
12004 (boundp 'org-ts-what)
12005 (setq org-ts-what
12006 (cond
12007 ((= pos (match-beginning 0)) 'bracket)
12008 ((= pos (1- (match-end 0))) 'bracket)
12009 ((org-pos-in-match-range pos 2) 'year)
12010 ((org-pos-in-match-range pos 3) 'month)
12011 ((org-pos-in-match-range pos 7) 'hour)
12012 ((org-pos-in-match-range pos 8) 'minute)
12013 ((or (org-pos-in-match-range pos 4)
12014 (org-pos-in-match-range pos 5)) 'day)
12015 ((and (> pos (or (match-end 8) (match-end 5)))
12016 (< pos (match-end 0)))
12017 (- pos (or (match-end 8) (match-end 5))))
12018 (t 'day))))
12019 ans))
12020
12021 (defun org-toggle-timestamp-type ()
12022 "Toggle the type (<active> or [inactive]) of a time stamp."
12023 (interactive)
12024 (when (org-at-timestamp-p t)
12025 (let ((beg (match-beginning 0)) (end (match-end 0))
12026 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12027 (save-excursion
12028 (goto-char beg)
12029 (while (re-search-forward "[][<>]" end t)
12030 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12031 t t)))
12032 (message "Timestamp is now %sactive"
12033 (if (equal (char-after beg) ?<) "" "in")))))
12034
12035 (defun org-timestamp-change (n &optional what)
12036 "Change the date in the time stamp at point.
12037 The date will be changed by N times WHAT. WHAT can be `day', `month',
12038 `year', `minute', `second'. If WHAT is not given, the cursor position
12039 in the timestamp determines what will be changed."
12040 (let ((pos (point))
12041 with-hm inactive
12042 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12043 org-ts-what
12044 extra rem
12045 ts time time0)
12046 (if (not (org-at-timestamp-p t))
12047 (error "Not at a timestamp"))
12048 (if (and (not what) (eq org-ts-what 'bracket))
12049 (org-toggle-timestamp-type)
12050 (if (and (not what) (not (eq org-ts-what 'day))
12051 org-display-custom-times
12052 (get-text-property (point) 'display)
12053 (not (get-text-property (1- (point)) 'display)))
12054 (setq org-ts-what 'day))
12055 (setq org-ts-what (or what org-ts-what)
12056 inactive (= (char-after (match-beginning 0)) ?\[)
12057 ts (match-string 0))
12058 (replace-match "")
12059 (if (string-match
12060 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12061 ts)
12062 (setq extra (match-string 1 ts)))
12063 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12064 (setq with-hm t))
12065 (setq time0 (org-parse-time-string ts))
12066 (when (and (eq org-ts-what 'minute)
12067 (eq current-prefix-arg nil))
12068 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12069 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12070 (setcar (cdr time0) (+ (nth 1 time0)
12071 (if (> n 0) (- rem) (- dm rem))))))
12072 (setq time
12073 (encode-time (or (car time0) 0)
12074 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12075 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12076 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12077 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12078 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12079 (nthcdr 6 time0)))
12080 (when (integerp org-ts-what)
12081 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12082 (if (eq what 'calendar)
12083 (let ((cal-date (org-get-date-from-calendar)))
12084 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12085 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12086 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12087 (setcar time0 (or (car time0) 0))
12088 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12089 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12090 (setq time (apply 'encode-time time0))))
12091 (setq org-last-changed-timestamp
12092 (org-insert-time-stamp time with-hm inactive nil nil extra))
12093 (org-clock-update-time-maybe)
12094 (goto-char pos)
12095 ;; Try to recenter the calendar window, if any
12096 (if (and org-calendar-follow-timestamp-change
12097 (get-buffer-window "*Calendar*" t)
12098 (memq org-ts-what '(day month year)))
12099 (org-recenter-calendar (time-to-days time))))))
12100
12101 (defun org-modify-ts-extra (s pos n dm)
12102 "Change the different parts of the lead-time and repeat fields in timestamp."
12103 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12104 ng h m new rem)
12105 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12106 (cond
12107 ((or (org-pos-in-match-range pos 2)
12108 (org-pos-in-match-range pos 3))
12109 (setq m (string-to-number (match-string 3 s))
12110 h (string-to-number (match-string 2 s)))
12111 (if (org-pos-in-match-range pos 2)
12112 (setq h (+ h n))
12113 (setq n (* dm (org-no-warnings (signum n))))
12114 (when (not (= 0 (setq rem (% m dm))))
12115 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12116 (setq m (+ m n)))
12117 (if (< m 0) (setq m (+ m 60) h (1- h)))
12118 (if (> m 59) (setq m (- m 60) h (1+ h)))
12119 (setq h (min 24 (max 0 h)))
12120 (setq ng 1 new (format "-%02d:%02d" h m)))
12121 ((org-pos-in-match-range pos 6)
12122 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12123 ((org-pos-in-match-range pos 5)
12124 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12125
12126 ((org-pos-in-match-range pos 9)
12127 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12128 ((org-pos-in-match-range pos 8)
12129 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12130
12131 (when ng
12132 (setq s (concat
12133 (substring s 0 (match-beginning ng))
12134 new
12135 (substring s (match-end ng))))))
12136 s))
12137
12138 (defun org-recenter-calendar (date)
12139 "If the calendar is visible, recenter it to DATE."
12140 (let* ((win (selected-window))
12141 (cwin (get-buffer-window "*Calendar*" t))
12142 (calendar-move-hook nil))
12143 (when cwin
12144 (select-window cwin)
12145 (calendar-goto-date (if (listp date) date
12146 (calendar-gregorian-from-absolute date)))
12147 (select-window win))))
12148
12149 (defun org-goto-calendar (&optional arg)
12150 "Go to the Emacs calendar at the current date.
12151 If there is a time stamp in the current line, go to that date.
12152 A prefix ARG can be used to force the current date."
12153 (interactive "P")
12154 (let ((tsr org-ts-regexp) diff
12155 (calendar-move-hook nil)
12156 (calendar-view-holidays-initially-flag nil)
12157 (view-calendar-holidays-initially nil)
12158 (calendar-view-diary-initially-flag nil)
12159 (view-diary-entries-initially nil))
12160 (if (or (org-at-timestamp-p)
12161 (save-excursion
12162 (beginning-of-line 1)
12163 (looking-at (concat ".*" tsr))))
12164 (let ((d1 (time-to-days (current-time)))
12165 (d2 (time-to-days
12166 (org-time-string-to-time (match-string 1)))))
12167 (setq diff (- d2 d1))))
12168 (calendar)
12169 (calendar-goto-today)
12170 (if (and diff (not arg)) (calendar-forward-day diff))))
12171
12172 (defun org-get-date-from-calendar ()
12173 "Return a list (month day year) of date at point in calendar."
12174 (with-current-buffer "*Calendar*"
12175 (save-match-data
12176 (calendar-cursor-to-date))))
12177
12178 (defun org-date-from-calendar ()
12179 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12180 If there is already a time stamp at the cursor position, update it."
12181 (interactive)
12182 (if (org-at-timestamp-p t)
12183 (org-timestamp-change 0 'calendar)
12184 (let ((cal-date (org-get-date-from-calendar)))
12185 (org-insert-time-stamp
12186 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12187
12188 (defun org-minutes-to-hh:mm-string (m)
12189 "Compute H:MM from a number of minutes."
12190 (let ((h (/ m 60)))
12191 (setq m (- m (* 60 h)))
12192 (format org-time-clocksum-format h m)))
12193
12194 (defun org-hh:mm-string-to-minutes (s)
12195 "Convert a string H:MM to a number of minutes."
12196 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12197 (+ (* (string-to-number (match-string 1 s)) 60)
12198 (string-to-number (match-string 2 s)))
12199 0))
12200
12201 ;;;; Agenda files
12202
12203 ;;;###autoload
12204 (defun org-iswitchb (&optional arg)
12205 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12206 With a prefix argument, restrict available to files.
12207 With two prefix arguments, restrict available buffers to agenda files.
12208
12209 Due to some yet unresolved reason, the global function
12210 `iswitchb-mode' needs to be active for this function to work."
12211 (interactive "P")
12212 (require 'iswitchb)
12213 (let ((enabled iswitchb-mode) blist)
12214 (or enabled (iswitchb-mode 1))
12215 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12216 ((equal arg '(16)) (org-buffer-list 'agenda))
12217 (t (org-buffer-list))))
12218 (unwind-protect
12219 (let ((iswitchb-make-buflist-hook
12220 (lambda ()
12221 (setq iswitchb-temp-buflist
12222 (mapcar 'buffer-name blist)))))
12223 (switch-to-buffer
12224 (iswitchb-read-buffer
12225 "Switch-to: " nil t))
12226 (or enabled (iswitchb-mode -1))))))
12227
12228 ;;;###autoload
12229 (defun org-ido-switchb (&optional arg)
12230 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12231 With a prefix argument, restrict available to files.
12232 With two prefix arguments, restrict available buffers to agenda files."
12233 (interactive "P")
12234 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12235 ((equal arg '(16)) (org-buffer-list 'agenda))
12236 (t (org-buffer-list)))))
12237 (switch-to-buffer
12238 (org-ido-completing-read "Org buffer: "
12239 (mapcar 'buffer-name blist)
12240 nil t))))
12241
12242 (defun org-buffer-list (&optional predicate exclude-tmp)
12243 "Return a list of Org buffers.
12244 PREDICATE can be `export', `files' or `agenda'.
12245
12246 export restrict the list to Export buffers.
12247 files restrict the list to buffers visiting Org files.
12248 agenda restrict the list to buffers visiting agenda files.
12249
12250 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12251 (let* ((bfn nil)
12252 (agenda-files (and (eq predicate 'agenda)
12253 (mapcar 'file-truename (org-agenda-files t))))
12254 (filter
12255 (cond
12256 ((eq predicate 'files)
12257 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12258 ((eq predicate 'export)
12259 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12260 ((eq predicate 'agenda)
12261 (lambda (b)
12262 (with-current-buffer b
12263 (and (eq major-mode 'org-mode)
12264 (setq bfn (buffer-file-name b))
12265 (member (file-truename bfn) agenda-files)))))
12266 (t (lambda (b) (with-current-buffer b
12267 (or (eq major-mode 'org-mode)
12268 (string-match "\*Org .*Export"
12269 (buffer-name b)))))))))
12270 (delq nil
12271 (mapcar
12272 (lambda(b)
12273 (if (and (funcall filter b)
12274 (or (not exclude-tmp)
12275 (not (string-match "tmp" (buffer-name b)))))
12276 b
12277 nil))
12278 (buffer-list)))))
12279
12280 (defun org-agenda-files (&optional unrestricted archives)
12281 "Get the list of agenda files.
12282 Optional UNRESTRICTED means return the full list even if a restriction
12283 is currently in place.
12284 When ARCHIVES is t, include all archive files hat are really being
12285 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12286 `org-agenda-archives-mode' is t."
12287 (let ((files
12288 (cond
12289 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12290 ((stringp org-agenda-files) (org-read-agenda-file-list))
12291 ((listp org-agenda-files) org-agenda-files)
12292 (t (error "Invalid value of `org-agenda-files'")))))
12293 (setq files (apply 'append
12294 (mapcar (lambda (f)
12295 (if (file-directory-p f)
12296 (directory-files
12297 f t org-agenda-file-regexp)
12298 (list f)))
12299 files)))
12300 (when org-agenda-skip-unavailable-files
12301 (setq files (delq nil
12302 (mapcar (function
12303 (lambda (file)
12304 (and (file-readable-p file) file)))
12305 files))))
12306 (when (or (eq archives t)
12307 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12308 (setq files (org-add-archive-files files)))
12309 files))
12310
12311 (defun org-edit-agenda-file-list ()
12312 "Edit the list of agenda files.
12313 Depending on setup, this either uses customize to edit the variable
12314 `org-agenda-files', or it visits the file that is holding the list. In the
12315 latter case, the buffer is set up in a way that saving it automatically kills
12316 the buffer and restores the previous window configuration."
12317 (interactive)
12318 (if (stringp org-agenda-files)
12319 (let ((cw (current-window-configuration)))
12320 (find-file org-agenda-files)
12321 (org-set-local 'org-window-configuration cw)
12322 (org-add-hook 'after-save-hook
12323 (lambda ()
12324 (set-window-configuration
12325 (prog1 org-window-configuration
12326 (kill-buffer (current-buffer))))
12327 (org-install-agenda-files-menu)
12328 (message "New agenda file list installed"))
12329 nil 'local)
12330 (message "%s" (substitute-command-keys
12331 "Edit list and finish with \\[save-buffer]")))
12332 (customize-variable 'org-agenda-files)))
12333
12334 (defun org-store-new-agenda-file-list (list)
12335 "Set new value for the agenda file list and save it correctly."
12336 (if (stringp org-agenda-files)
12337 (let ((f org-agenda-files) b)
12338 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12339 (with-temp-file f
12340 (insert (mapconcat 'identity list "\n") "\n")))
12341 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12342 (setq org-agenda-files list)
12343 (customize-save-variable 'org-agenda-files org-agenda-files))))
12344
12345 (defun org-read-agenda-file-list ()
12346 "Read the list of agenda files from a file."
12347 (when (file-directory-p org-agenda-files)
12348 (error "`org-agenda-files' cannot be a single directory"))
12349 (when (stringp org-agenda-files)
12350 (with-temp-buffer
12351 (insert-file-contents org-agenda-files)
12352 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12353
12354
12355 ;;;###autoload
12356 (defun org-cycle-agenda-files ()
12357 "Cycle through the files in `org-agenda-files'.
12358 If the current buffer visits an agenda file, find the next one in the list.
12359 If the current buffer does not, find the first agenda file."
12360 (interactive)
12361 (let* ((fs (org-agenda-files t))
12362 (files (append fs (list (car fs))))
12363 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12364 file)
12365 (unless files (error "No agenda files"))
12366 (catch 'exit
12367 (while (setq file (pop files))
12368 (if (equal (file-truename file) tcf)
12369 (when (car files)
12370 (find-file (car files))
12371 (throw 'exit t))))
12372 (find-file (car fs)))
12373 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12374
12375 (defun org-agenda-file-to-front (&optional to-end)
12376 "Move/add the current file to the top of the agenda file list.
12377 If the file is not present in the list, it is added to the front. If it is
12378 present, it is moved there. With optional argument TO-END, add/move to the
12379 end of the list."
12380 (interactive "P")
12381 (let ((org-agenda-skip-unavailable-files nil)
12382 (file-alist (mapcar (lambda (x)
12383 (cons (file-truename x) x))
12384 (org-agenda-files t)))
12385 (ctf (file-truename buffer-file-name))
12386 x had)
12387 (setq x (assoc ctf file-alist) had x)
12388
12389 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12390 (if to-end
12391 (setq file-alist (append (delq x file-alist) (list x)))
12392 (setq file-alist (cons x (delq x file-alist))))
12393 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12394 (org-install-agenda-files-menu)
12395 (message "File %s to %s of agenda file list"
12396 (if had "moved" "added") (if to-end "end" "front"))))
12397
12398 (defun org-remove-file (&optional file)
12399 "Remove current file from the list of files in variable `org-agenda-files'.
12400 These are the files which are being checked for agenda entries.
12401 Optional argument FILE means, use this file instead of the current."
12402 (interactive)
12403 (let* ((org-agenda-skip-unavailable-files nil)
12404 (file (or file buffer-file-name))
12405 (true-file (file-truename file))
12406 (afile (abbreviate-file-name file))
12407 (files (delq nil (mapcar
12408 (lambda (x)
12409 (if (equal true-file
12410 (file-truename x))
12411 nil x))
12412 (org-agenda-files t)))))
12413 (if (not (= (length files) (length (org-agenda-files t))))
12414 (progn
12415 (org-store-new-agenda-file-list files)
12416 (org-install-agenda-files-menu)
12417 (message "Removed file: %s" afile))
12418 (message "File was not in list: %s (not removed)" afile))))
12419
12420 (defun org-file-menu-entry (file)
12421 (vector file (list 'find-file file) t))
12422
12423 (defun org-check-agenda-file (file)
12424 "Make sure FILE exists. If not, ask user what to do."
12425 (when (not (file-exists-p file))
12426 (message "non-existent file %s. [R]emove from list or [A]bort?"
12427 (abbreviate-file-name file))
12428 (let ((r (downcase (read-char-exclusive))))
12429 (cond
12430 ((equal r ?r)
12431 (org-remove-file file)
12432 (throw 'nextfile t))
12433 (t (error "Abort"))))))
12434
12435 (defun org-get-agenda-file-buffer (file)
12436 "Get a buffer visiting FILE. If the buffer needs to be created, add
12437 it to the list of buffers which might be released later."
12438 (let ((buf (org-find-base-buffer-visiting file)))
12439 (if buf
12440 buf ; just return it
12441 ;; Make a new buffer and remember it
12442 (setq buf (find-file-noselect file))
12443 (if buf (push buf org-agenda-new-buffers))
12444 buf)))
12445
12446 (defun org-release-buffers (blist)
12447 "Release all buffers in list, asking the user for confirmation when needed.
12448 When a buffer is unmodified, it is just killed. When modified, it is saved
12449 \(if the user agrees) and then killed."
12450 (let (buf file)
12451 (while (setq buf (pop blist))
12452 (setq file (buffer-file-name buf))
12453 (when (and (buffer-modified-p buf)
12454 file
12455 (y-or-n-p (format "Save file %s? " file)))
12456 (with-current-buffer buf (save-buffer)))
12457 (kill-buffer buf))))
12458
12459 (defun org-prepare-agenda-buffers (files)
12460 "Create buffers for all agenda files, protect archived trees and comments."
12461 (interactive)
12462 (let ((pa '(:org-archived t))
12463 (pc '(:org-comment t))
12464 (pall '(:org-archived t :org-comment t))
12465 (inhibit-read-only t)
12466 (rea (concat ":" org-archive-tag ":"))
12467 bmp file re)
12468 (save-excursion
12469 (save-restriction
12470 (while (setq file (pop files))
12471 (if (bufferp file)
12472 (set-buffer file)
12473 (org-check-agenda-file file)
12474 (set-buffer (org-get-agenda-file-buffer file)))
12475 (widen)
12476 (setq bmp (buffer-modified-p))
12477 (org-refresh-category-properties)
12478 (setq org-todo-keywords-for-agenda
12479 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12480 (setq org-done-keywords-for-agenda
12481 (append org-done-keywords-for-agenda org-done-keywords))
12482 (setq org-todo-keyword-alist-for-agenda
12483 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12484 (setq org-tag-alist-for-agenda
12485 (append org-tag-alist-for-agenda org-tag-alist))
12486
12487 (save-excursion
12488 (remove-text-properties (point-min) (point-max) pall)
12489 (when org-agenda-skip-archived-trees
12490 (goto-char (point-min))
12491 (while (re-search-forward rea nil t)
12492 (if (org-on-heading-p t)
12493 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12494 (goto-char (point-min))
12495 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12496 (while (re-search-forward re nil t)
12497 (add-text-properties
12498 (match-beginning 0) (org-end-of-subtree t) pc)))
12499 (set-buffer-modified-p bmp))))
12500 (setq org-todo-keyword-alist-for-agenda
12501 (org-uniquify org-todo-keyword-alist-for-agenda)
12502 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12503
12504 ;;;; Embedded LaTeX
12505
12506 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12507 "Keymap for the minor `org-cdlatex-mode'.")
12508
12509 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12510 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12511 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12512 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12513 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12514
12515 (defvar org-cdlatex-texmathp-advice-is-done nil
12516 "Flag remembering if we have applied the advice to texmathp already.")
12517
12518 (define-minor-mode org-cdlatex-mode
12519 "Toggle the minor `org-cdlatex-mode'.
12520 This mode supports entering LaTeX environment and math in LaTeX fragments
12521 in Org-mode.
12522 \\{org-cdlatex-mode-map}"
12523 nil " OCDL" nil
12524 (when org-cdlatex-mode (require 'cdlatex))
12525 (unless org-cdlatex-texmathp-advice-is-done
12526 (setq org-cdlatex-texmathp-advice-is-done t)
12527 (defadvice texmathp (around org-math-always-on activate)
12528 "Always return t in org-mode buffers.
12529 This is because we want to insert math symbols without dollars even outside
12530 the LaTeX math segments. If Orgmode thinks that point is actually inside
12531 an embedded LaTeX fragment, let texmathp do its job.
12532 \\[org-cdlatex-mode-map]"
12533 (interactive)
12534 (let (p)
12535 (cond
12536 ((not (org-mode-p)) ad-do-it)
12537 ((eq this-command 'cdlatex-math-symbol)
12538 (setq ad-return-value t
12539 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12540 (t
12541 (let ((p (org-inside-LaTeX-fragment-p)))
12542 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12543 (setq ad-return-value t
12544 texmathp-why '("Org-mode embedded math" . 0))
12545 (if p ad-do-it)))))))))
12546
12547 (defun turn-on-org-cdlatex ()
12548 "Unconditionally turn on `org-cdlatex-mode'."
12549 (org-cdlatex-mode 1))
12550
12551 (defun org-inside-LaTeX-fragment-p ()
12552 "Test if point is inside a LaTeX fragment.
12553 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12554 sequence appearing also before point.
12555 Even though the matchers for math are configurable, this function assumes
12556 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12557 delimiters are skipped when they have been removed by customization.
12558 The return value is nil, or a cons cell with the delimiter and
12559 and the position of this delimiter.
12560
12561 This function does a reasonably good job, but can locally be fooled by
12562 for example currency specifications. For example it will assume being in
12563 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12564 fragments that are properly closed, but during editing, we have to live
12565 with the uncertainty caused by missing closing delimiters. This function
12566 looks only before point, not after."
12567 (catch 'exit
12568 (let ((pos (point))
12569 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12570 (lim (progn
12571 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12572 (point)))
12573 dd-on str (start 0) m re)
12574 (goto-char pos)
12575 (when dodollar
12576 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12577 re (nth 1 (assoc "$" org-latex-regexps)))
12578 (while (string-match re str start)
12579 (cond
12580 ((= (match-end 0) (length str))
12581 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12582 ((= (match-end 0) (- (length str) 5))
12583 (throw 'exit nil))
12584 (t (setq start (match-end 0))))))
12585 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12586 (goto-char pos)
12587 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12588 (and (match-beginning 2) (throw 'exit nil))
12589 ;; count $$
12590 (while (re-search-backward "\\$\\$" lim t)
12591 (setq dd-on (not dd-on)))
12592 (goto-char pos)
12593 (if dd-on (cons "$$" m))))))
12594
12595
12596 (defun org-try-cdlatex-tab ()
12597 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12598 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12599 - inside a LaTeX fragment, or
12600 - after the first word in a line, where an abbreviation expansion could
12601 insert a LaTeX environment."
12602 (when org-cdlatex-mode
12603 (cond
12604 ((save-excursion
12605 (skip-chars-backward "a-zA-Z0-9*")
12606 (skip-chars-backward " \t")
12607 (bolp))
12608 (cdlatex-tab) t)
12609 ((org-inside-LaTeX-fragment-p)
12610 (cdlatex-tab) t)
12611 (t nil))))
12612
12613 (defun org-cdlatex-underscore-caret (&optional arg)
12614 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12615 Revert to the normal definition outside of these fragments."
12616 (interactive "P")
12617 (if (org-inside-LaTeX-fragment-p)
12618 (call-interactively 'cdlatex-sub-superscript)
12619 (let (org-cdlatex-mode)
12620 (call-interactively (key-binding (vector last-input-event))))))
12621
12622 (defun org-cdlatex-math-modify (&optional arg)
12623 "Execute `cdlatex-math-modify' in LaTeX fragments.
12624 Revert to the normal definition outside of these fragments."
12625 (interactive "P")
12626 (if (org-inside-LaTeX-fragment-p)
12627 (call-interactively 'cdlatex-math-modify)
12628 (let (org-cdlatex-mode)
12629 (call-interactively (key-binding (vector last-input-event))))))
12630
12631 (defvar org-latex-fragment-image-overlays nil
12632 "List of overlays carrying the images of latex fragments.")
12633 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12634
12635 (defun org-remove-latex-fragment-image-overlays ()
12636 "Remove all overlays with LaTeX fragment images in current buffer."
12637 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12638 (setq org-latex-fragment-image-overlays nil))
12639
12640 (defun org-preview-latex-fragment (&optional subtree)
12641 "Preview the LaTeX fragment at point, or all locally or globally.
12642 If the cursor is in a LaTeX fragment, create the image and overlay
12643 it over the source code. If there is no fragment at point, display
12644 all fragments in the current text, from one headline to the next. With
12645 prefix SUBTREE, display all fragments in the current subtree. With a
12646 double prefix `C-u C-u', or when the cursor is before the first headline,
12647 display all fragments in the buffer.
12648 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12649 (interactive "P")
12650 (org-remove-latex-fragment-image-overlays)
12651 (save-excursion
12652 (save-restriction
12653 (let (beg end at msg)
12654 (cond
12655 ((or (equal subtree '(16))
12656 (not (save-excursion
12657 (re-search-backward (concat "^" outline-regexp) nil t))))
12658 (setq beg (point-min) end (point-max)
12659 msg "Creating images for buffer...%s"))
12660 ((equal subtree '(4))
12661 (org-back-to-heading)
12662 (setq beg (point) end (org-end-of-subtree t)
12663 msg "Creating images for subtree...%s"))
12664 (t
12665 (if (setq at (org-inside-LaTeX-fragment-p))
12666 (goto-char (max (point-min) (- (cdr at) 2)))
12667 (org-back-to-heading))
12668 (setq beg (point) end (progn (outline-next-heading) (point))
12669 msg (if at "Creating image...%s"
12670 "Creating images for entry...%s"))))
12671 (message msg "")
12672 (narrow-to-region beg end)
12673 (goto-char beg)
12674 (org-format-latex
12675 (concat "ltxpng/" (file-name-sans-extension
12676 (file-name-nondirectory
12677 buffer-file-name)))
12678 default-directory 'overlays msg at 'forbuffer)
12679 (message msg "done. Use `C-c C-c' to remove images.")))))
12680
12681 (defvar org-latex-regexps
12682 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12683 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12684 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12685 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12686 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12687 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12688 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12689 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12690 "Regular expressions for matching embedded LaTeX.")
12691
12692 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12693 "Replace LaTeX fragments with links to an image, and produce images."
12694 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12695 (let* ((prefixnodir (file-name-nondirectory prefix))
12696 (absprefix (expand-file-name prefix dir))
12697 (todir (file-name-directory absprefix))
12698 (opt org-format-latex-options)
12699 (matchers (plist-get opt :matchers))
12700 (re-list org-latex-regexps)
12701 (cnt 0) txt link beg end re e checkdir
12702 m n block linkfile movefile ov)
12703 ;; Check if there are old images files with this prefix, and remove them
12704 (when (file-directory-p todir)
12705 (mapc 'delete-file
12706 (directory-files
12707 todir 'full
12708 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12709 ;; Check the different regular expressions
12710 (while (setq e (pop re-list))
12711 (setq m (car e) re (nth 1 e) n (nth 2 e)
12712 block (if (nth 3 e) "\n\n" ""))
12713 (when (member m matchers)
12714 (goto-char (point-min))
12715 (while (re-search-forward re nil t)
12716 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
12717 (not (get-text-property (match-beginning n)
12718 'org-protected)))
12719 (setq txt (match-string n)
12720 beg (match-beginning n) end (match-end n)
12721 cnt (1+ cnt)
12722 linkfile (format "%s_%04d.png" prefix cnt)
12723 movefile (format "%s_%04d.png" absprefix cnt)
12724 link (concat block "[[file:" linkfile "]]" block))
12725 (if msg (message msg cnt))
12726 (goto-char beg)
12727 (unless checkdir ; make sure the directory exists
12728 (setq checkdir t)
12729 (or (file-directory-p todir) (make-directory todir)))
12730 (org-create-formula-image
12731 txt movefile opt forbuffer)
12732 (if overlays
12733 (progn
12734 (setq ov (org-make-overlay beg end))
12735 (if (featurep 'xemacs)
12736 (progn
12737 (org-overlay-put ov 'invisible t)
12738 (org-overlay-put
12739 ov 'end-glyph
12740 (make-glyph (vector 'png :file movefile))))
12741 (org-overlay-put
12742 ov 'display
12743 (list 'image :type 'png :file movefile :ascent 'center)))
12744 (push ov org-latex-fragment-image-overlays)
12745 (goto-char end))
12746 (delete-region beg end)
12747 (insert link))))))))
12748
12749 ;; This function borrows from Ganesh Swami's latex2png.el
12750 (defun org-create-formula-image (string tofile options buffer)
12751 (let* ((tmpdir (if (featurep 'xemacs)
12752 (temp-directory)
12753 temporary-file-directory))
12754 (texfilebase (make-temp-name
12755 (expand-file-name "orgtex" tmpdir)))
12756 (texfile (concat texfilebase ".tex"))
12757 (dvifile (concat texfilebase ".dvi"))
12758 (pngfile (concat texfilebase ".png"))
12759 (fnh (if (featurep 'xemacs)
12760 (font-height (get-face-font 'default))
12761 (face-attribute 'default :height nil)))
12762 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12763 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12764 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12765 "Black"))
12766 (bg (or (plist-get options (if buffer :background :html-background))
12767 "Transparent")))
12768 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12769 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12770 (with-temp-file texfile
12771 (insert org-format-latex-header
12772 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12773 (let ((dir default-directory))
12774 (condition-case nil
12775 (progn
12776 (cd tmpdir)
12777 (call-process "latex" nil nil nil texfile))
12778 (error nil))
12779 (cd dir))
12780 (if (not (file-exists-p dvifile))
12781 (progn (message "Failed to create dvi file from %s" texfile) nil)
12782 (condition-case nil
12783 (call-process "dvipng" nil nil nil
12784 "-E" "-fg" fg "-bg" bg
12785 "-D" dpi
12786 ;;"-x" scale "-y" scale
12787 "-T" "tight"
12788 "-o" pngfile
12789 dvifile)
12790 (error nil))
12791 (if (not (file-exists-p pngfile))
12792 (progn (message "Failed to create png file from %s" texfile) nil)
12793 ;; Use the requested file name and clean up
12794 (copy-file pngfile tofile 'replace)
12795 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12796 (delete-file (concat texfilebase e)))
12797 pngfile))))
12798
12799 (defun org-dvipng-color (attr)
12800 "Return an rgb color specification for dvipng."
12801 (apply 'format "rgb %s %s %s"
12802 (mapcar 'org-normalize-color
12803 (color-values (face-attribute 'default attr nil)))))
12804
12805 (defun org-normalize-color (value)
12806 "Return string to be used as color value for an RGB component."
12807 (format "%g" (/ value 65535.0)))
12808
12809 ;;;; Key bindings
12810
12811 ;; Make `C-c C-x' a prefix key
12812 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12813
12814 ;; TAB key with modifiers
12815 (org-defkey org-mode-map "\C-i" 'org-cycle)
12816 (org-defkey org-mode-map [(tab)] 'org-cycle)
12817 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12818 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12819 (org-defkey org-mode-map "\M-\t" 'org-complete)
12820 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12821 ;; The following line is necessary under Suse GNU/Linux
12822 (unless (featurep 'xemacs)
12823 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12824 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12825 (define-key org-mode-map [backtab] 'org-shifttab)
12826
12827 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12828 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12829 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12830
12831 ;; Cursor keys with modifiers
12832 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12833 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12834 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12835 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12836
12837 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12838 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12839 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12840 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12841
12842 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12843 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12844 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12845 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12846
12847 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12848 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12849
12850 ;;; Extra keys for tty access.
12851 ;; We only set them when really needed because otherwise the
12852 ;; menus don't show the simple keys
12853
12854 (when (or org-use-extra-keys
12855 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12856 (not window-system))
12857 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12858 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12859 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12860 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12861 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12862 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12863 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12864 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12865 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12866 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12867 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12868 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12869 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12870 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12871 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12872 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12873 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12874 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12875 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12876 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12877 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12878 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12879
12880 ;; All the other keys
12881
12882 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12883 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12884 (if (boundp 'narrow-map)
12885 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12886 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12887 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12888 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12889 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12890 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12891 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12892 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12893 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12894 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12895 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12896 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12897 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12898 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12899 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12900 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12901 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12902 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12903 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12904 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12905 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12906 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12907 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12908 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12909 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12910 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12911 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12912 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12913 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12914 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12915 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12916 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12917 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12918 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12919 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12920 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12921 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12922 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12923 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12924 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12925 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12926 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12927 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12928 (org-defkey org-mode-map "\C-c^" 'org-sort)
12929 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12930 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12931 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12932 (org-defkey org-mode-map "\C-m" 'org-return)
12933 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12934 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12935 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12936 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12937 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12938 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12939 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12940 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12941 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12942 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12943 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12944 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12945 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12946 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12947 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12948 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12949 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
12950
12951 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12952 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12953 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12954 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12955
12956 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12957 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12958 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12959 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12960 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12961 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12962 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12963 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12964 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12965 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12966 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12967 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
12968 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12969
12970 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12971 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12972 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12973 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
12974
12975 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12976
12977 (when (featurep 'xemacs)
12978 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12979
12980 (defvar org-table-auto-blank-field) ; defined in org-table.el
12981 (defun org-self-insert-command (N)
12982 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12983 If the cursor is in a table looking at whitespace, the whitespace is
12984 overwritten, and the table is not marked as requiring realignment."
12985 (interactive "p")
12986 (if (and (org-table-p)
12987 (progn
12988 ;; check if we blank the field, and if that triggers align
12989 (and (featurep 'org-table) org-table-auto-blank-field
12990 (member last-command
12991 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12992 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12993 ;; got extra space, this field does not determine column width
12994 (let (org-table-may-need-update) (org-table-blank-field))
12995 ;; no extra space, this field may determine column width
12996 (org-table-blank-field)))
12997 t)
12998 (eq N 1)
12999 (looking-at "[^|\n]* |"))
13000 (let (org-table-may-need-update)
13001 (goto-char (1- (match-end 0)))
13002 (delete-backward-char 1)
13003 (goto-char (match-beginning 0))
13004 (self-insert-command N))
13005 (setq org-table-may-need-update t)
13006 (self-insert-command N)
13007 (org-fix-tags-on-the-fly)))
13008
13009 (defun org-fix-tags-on-the-fly ()
13010 (when (and (equal (char-after (point-at-bol)) ?*)
13011 (org-on-heading-p))
13012 (org-align-tags-here org-tags-column)))
13013
13014 (defun org-delete-backward-char (N)
13015 "Like `delete-backward-char', insert whitespace at field end in tables.
13016 When deleting backwards, in tables this function will insert whitespace in
13017 front of the next \"|\" separator, to keep the table aligned. The table will
13018 still be marked for re-alignment if the field did fill the entire column,
13019 because, in this case the deletion might narrow the column."
13020 (interactive "p")
13021 (if (and (org-table-p)
13022 (eq N 1)
13023 (string-match "|" (buffer-substring (point-at-bol) (point)))
13024 (looking-at ".*?|"))
13025 (let ((pos (point))
13026 (noalign (looking-at "[^|\n\r]* |"))
13027 (c org-table-may-need-update))
13028 (backward-delete-char N)
13029 (skip-chars-forward "^|")
13030 (insert " ")
13031 (goto-char (1- pos))
13032 ;; noalign: if there were two spaces at the end, this field
13033 ;; does not determine the width of the column.
13034 (if noalign (setq org-table-may-need-update c)))
13035 (backward-delete-char N)
13036 (org-fix-tags-on-the-fly)))
13037
13038 (defun org-delete-char (N)
13039 "Like `delete-char', but insert whitespace at field end in tables.
13040 When deleting characters, in tables this function will insert whitespace in
13041 front of the next \"|\" separator, to keep the table aligned. The table will
13042 still be marked for re-alignment if the field did fill the entire column,
13043 because, in this case the deletion might narrow the column."
13044 (interactive "p")
13045 (if (and (org-table-p)
13046 (not (bolp))
13047 (not (= (char-after) ?|))
13048 (eq N 1))
13049 (if (looking-at ".*?|")
13050 (let ((pos (point))
13051 (noalign (looking-at "[^|\n\r]* |"))
13052 (c org-table-may-need-update))
13053 (replace-match (concat
13054 (substring (match-string 0) 1 -1)
13055 " |"))
13056 (goto-char pos)
13057 ;; noalign: if there were two spaces at the end, this field
13058 ;; does not determine the width of the column.
13059 (if noalign (setq org-table-may-need-update c)))
13060 (delete-char N))
13061 (delete-char N)
13062 (org-fix-tags-on-the-fly)))
13063
13064 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13065 (put 'org-self-insert-command 'delete-selection t)
13066 (put 'orgtbl-self-insert-command 'delete-selection t)
13067 (put 'org-delete-char 'delete-selection 'supersede)
13068 (put 'org-delete-backward-char 'delete-selection 'supersede)
13069 (put 'org-yank 'delete-selection 'yank)
13070
13071 ;; Make `flyspell-mode' delay after some commands
13072 (put 'org-self-insert-command 'flyspell-delayed t)
13073 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13074 (put 'org-delete-char 'flyspell-delayed t)
13075 (put 'org-delete-backward-char 'flyspell-delayed t)
13076
13077 ;; Make pabbrev-mode expand after org-mode commands
13078 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13079 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13080
13081 ;; How to do this: Measure non-white length of current string
13082 ;; If equal to column width, we should realign.
13083
13084 (defun org-remap (map &rest commands)
13085 "In MAP, remap the functions given in COMMANDS.
13086 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13087 (let (new old)
13088 (while commands
13089 (setq old (pop commands) new (pop commands))
13090 (if (fboundp 'command-remapping)
13091 (org-defkey map (vector 'remap old) new)
13092 (substitute-key-definition old new map global-map)))))
13093
13094 (when (eq org-enable-table-editor 'optimized)
13095 ;; If the user wants maximum table support, we need to hijack
13096 ;; some standard editing functions
13097 (org-remap org-mode-map
13098 'self-insert-command 'org-self-insert-command
13099 'delete-char 'org-delete-char
13100 'delete-backward-char 'org-delete-backward-char)
13101 (org-defkey org-mode-map "|" 'org-force-self-insert))
13102
13103 (defun org-modifier-cursor-error ()
13104 "Throw an error, a modified cursor command was applied in wrong context."
13105 (error "This command is active in special context like tables, headlines or items"))
13106
13107 (defun org-shiftselect-error ()
13108 "Throw an error because Shift-Cursor command was applied in wrong context."
13109 (if (and (boundp 'shift-select-mode) shift-select-mode)
13110 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13111 (error "This command works only in special context like headlines or timestamps.")))
13112
13113 (defun org-call-for-shift-select (cmd)
13114 (let ((this-command-keys-shift-translated t))
13115 (call-interactively cmd)))
13116
13117 (defun org-shifttab (&optional arg)
13118 "Global visibility cycling or move to previous table field.
13119 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13120 on context.
13121 See the individual commands for more information."
13122 (interactive "P")
13123 (cond
13124 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13125 ((integerp arg)
13126 (message "Content view to level: %d" arg)
13127 (org-content (prefix-numeric-value arg))
13128 (setq org-cycle-global-status 'overview))
13129 (t (call-interactively 'org-global-cycle))))
13130
13131 (defun org-shiftmetaleft ()
13132 "Promote subtree or delete table column.
13133 Calls `org-promote-subtree', `org-outdent-item',
13134 or `org-table-delete-column', depending on context.
13135 See the individual commands for more information."
13136 (interactive)
13137 (cond
13138 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13139 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13140 ((org-at-item-p) (call-interactively 'org-outdent-item))
13141 (t (org-modifier-cursor-error))))
13142
13143 (defun org-shiftmetaright ()
13144 "Demote subtree or insert table column.
13145 Calls `org-demote-subtree', `org-indent-item',
13146 or `org-table-insert-column', depending on context.
13147 See the individual commands for more information."
13148 (interactive)
13149 (cond
13150 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13151 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13152 ((org-at-item-p) (call-interactively 'org-indent-item))
13153 (t (org-modifier-cursor-error))))
13154
13155 (defun org-shiftmetaup (&optional arg)
13156 "Move subtree up or kill table row.
13157 Calls `org-move-subtree-up' or `org-table-kill-row' or
13158 `org-move-item-up' depending on context. See the individual commands
13159 for more information."
13160 (interactive "P")
13161 (cond
13162 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13163 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13164 ((org-at-item-p) (call-interactively 'org-move-item-up))
13165 (t (org-modifier-cursor-error))))
13166 (defun org-shiftmetadown (&optional arg)
13167 "Move subtree down or insert table row.
13168 Calls `org-move-subtree-down' or `org-table-insert-row' or
13169 `org-move-item-down', depending on context. See the individual
13170 commands for more information."
13171 (interactive "P")
13172 (cond
13173 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13174 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13175 ((org-at-item-p) (call-interactively 'org-move-item-down))
13176 (t (org-modifier-cursor-error))))
13177
13178 (defun org-metaleft (&optional arg)
13179 "Promote heading or move table column to left.
13180 Calls `org-do-promote' or `org-table-move-column', depending on context.
13181 With no specific context, calls the Emacs default `backward-word'.
13182 See the individual commands for more information."
13183 (interactive "P")
13184 (cond
13185 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13186 ((or (org-on-heading-p) (org-region-active-p))
13187 (call-interactively 'org-do-promote))
13188 ((org-at-item-p) (call-interactively 'org-outdent-item))
13189 (t (call-interactively 'backward-word))))
13190
13191 (defun org-metaright (&optional arg)
13192 "Demote subtree or move table column to right.
13193 Calls `org-do-demote' or `org-table-move-column', depending on context.
13194 With no specific context, calls the Emacs default `forward-word'.
13195 See the individual commands for more information."
13196 (interactive "P")
13197 (cond
13198 ((org-at-table-p) (call-interactively 'org-table-move-column))
13199 ((or (org-on-heading-p) (org-region-active-p))
13200 (call-interactively 'org-do-demote))
13201 ((org-at-item-p) (call-interactively 'org-indent-item))
13202 (t (call-interactively 'forward-word))))
13203
13204 (defun org-metaup (&optional arg)
13205 "Move subtree up or move table row up.
13206 Calls `org-move-subtree-up' or `org-table-move-row' or
13207 `org-move-item-up', depending on context. See the individual commands
13208 for more information."
13209 (interactive "P")
13210 (cond
13211 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13212 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13213 ((org-at-item-p) (call-interactively 'org-move-item-up))
13214 (t (transpose-lines 1) (beginning-of-line -1))))
13215
13216 (defun org-metadown (&optional arg)
13217 "Move subtree down or move table row down.
13218 Calls `org-move-subtree-down' or `org-table-move-row' or
13219 `org-move-item-down', depending on context. See the individual
13220 commands for more information."
13221 (interactive "P")
13222 (cond
13223 ((org-at-table-p) (call-interactively 'org-table-move-row))
13224 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13225 ((org-at-item-p) (call-interactively 'org-move-item-down))
13226 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13227
13228 (defun org-shiftup (&optional arg)
13229 "Increase item in timestamp or increase priority of current headline.
13230 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13231 depending on context. See the individual commands for more information."
13232 (interactive "P")
13233 (cond
13234 ((and org-support-shift-select (org-region-active-p))
13235 (org-call-for-shift-select 'previous-line))
13236 ((org-at-timestamp-p t)
13237 (call-interactively (if org-edit-timestamp-down-means-later
13238 'org-timestamp-down 'org-timestamp-up)))
13239 ((and (not (eq org-support-shift-select 'always))
13240 (org-on-heading-p))
13241 (call-interactively 'org-priority-up))
13242 ((and (not org-support-shift-select) (org-at-item-p))
13243 (call-interactively 'org-previous-item))
13244 ((org-clocktable-try-shift 'up arg))
13245 (org-support-shift-select
13246 (org-call-for-shift-select 'previous-line))
13247 (t (org-shiftselect-error))))
13248
13249 (defun org-shiftdown (&optional arg)
13250 "Decrease item in timestamp or decrease priority of current headline.
13251 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13252 depending on context. See the individual commands for more information."
13253 (interactive "P")
13254 (cond
13255 ((and org-support-shift-select (org-region-active-p))
13256 (org-call-for-shift-select 'next-line))
13257 ((org-at-timestamp-p t)
13258 (call-interactively (if org-edit-timestamp-down-means-later
13259 'org-timestamp-up 'org-timestamp-down)))
13260 ((and (not (eq org-support-shift-select 'always))
13261 (org-on-heading-p))
13262 (call-interactively 'org-priority-down))
13263 ((and (not org-support-shift-select) (org-at-item-p))
13264 (call-interactively 'org-next-item))
13265 ((org-clocktable-try-shift 'down arg))
13266 (org-support-shift-select
13267 (org-call-for-shift-select 'next-line))
13268 (t (org-shiftselect-error))))
13269
13270 (defun org-shiftright (&optional arg)
13271 "Cycle the thing at point or in the current line, depending on context.
13272 Depending on context, this does one of the following:
13273
13274 - switch a timestamp at point one day into the future
13275 - on a headline, switch to the next TODO keyword.
13276 - on an item, switch entire list to the next bullet type
13277 - on a property line, switch to the next allowed value
13278 - on a clocktable definition line, move time block into the future"
13279 (interactive "P")
13280 (cond
13281 ((and org-support-shift-select (org-region-active-p))
13282 (org-call-for-shift-select 'forward-char))
13283 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13284 ((and (not (eq org-support-shift-select 'always))
13285 (org-on-heading-p))
13286 (org-call-with-arg 'org-todo 'right))
13287 ((or (and org-support-shift-select
13288 (not (eq org-support-shift-select 'always))
13289 (org-at-item-bullet-p))
13290 (and (not org-support-shift-select) (org-at-item-p)))
13291 (org-call-with-arg 'org-cycle-list-bullet nil))
13292 ((and (not (eq org-support-shift-select 'always))
13293 (org-at-property-p))
13294 (call-interactively 'org-property-next-allowed-value))
13295 ((org-clocktable-try-shift 'right arg))
13296 (org-support-shift-select
13297 (org-call-for-shift-select 'forward-char))
13298 (t (org-shiftselect-error))))
13299
13300 (defun org-shiftleft (&optional arg)
13301 "Cycle the thing at point or in the current line, depending on context.
13302 Depending on context, this does one of the following:
13303
13304 - switch a timestamp at point one day into the past
13305 - on a headline, switch to the previous TODO keyword.
13306 - on an item, switch entire list to the previous bullet type
13307 - on a property line, switch to the previous allowed value
13308 - on a clocktable definition line, move time block into the past"
13309 (interactive "P")
13310 (cond
13311 ((and org-support-shift-select (org-region-active-p))
13312 (org-call-for-shift-select 'backward-char))
13313 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13314 ((and (not (eq org-support-shift-select 'always))
13315 (org-on-heading-p))
13316 (org-call-with-arg 'org-todo 'left))
13317 ((or (and org-support-shift-select
13318 (not (eq org-support-shift-select 'always))
13319 (org-at-item-bullet-p))
13320 (and (not org-support-shift-select) (org-at-item-p)))
13321 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13322 ((and (not (eq org-support-shift-select 'always))
13323 (org-at-property-p))
13324 (call-interactively 'org-property-previous-allowed-value))
13325 ((org-clocktable-try-shift 'left arg))
13326 (org-support-shift-select
13327 (org-call-for-shift-select 'backward-char))
13328 (t (org-shiftselect-error))))
13329
13330 (defun org-shiftcontrolright ()
13331 "Switch to next TODO set."
13332 (interactive)
13333 (cond
13334 ((and org-support-shift-select (org-region-active-p))
13335 (org-call-for-shift-select 'forward-word))
13336 ((and (not (eq org-support-shift-select 'always))
13337 (org-on-heading-p))
13338 (org-call-with-arg 'org-todo 'nextset))
13339 (org-support-shift-select
13340 (org-call-for-shift-select 'forward-word))
13341 (t (org-shiftselect-error))))
13342
13343 (defun org-shiftcontrolleft ()
13344 "Switch to previous TODO set."
13345 (interactive)
13346 (cond
13347 ((and org-support-shift-select (org-region-active-p))
13348 (org-call-for-shift-select 'backward-word))
13349 ((and (not (eq org-support-shift-select 'always))
13350 (org-on-heading-p))
13351 (org-call-with-arg 'org-todo 'previousset))
13352 (org-support-shift-select
13353 (org-call-for-shift-select 'backward-word))
13354 (t (org-shiftselect-error))))
13355
13356 (defun org-ctrl-c-ret ()
13357 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13358 (interactive)
13359 (cond
13360 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13361 (t (call-interactively 'org-insert-heading))))
13362
13363 (defun org-copy-special ()
13364 "Copy region in table or copy current subtree.
13365 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13366 See the individual commands for more information."
13367 (interactive)
13368 (call-interactively
13369 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13370
13371 (defun org-cut-special ()
13372 "Cut region in table or cut current subtree.
13373 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13374 See the individual commands for more information."
13375 (interactive)
13376 (call-interactively
13377 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13378
13379 (defun org-paste-special (arg)
13380 "Paste rectangular region into table, or past subtree relative to level.
13381 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13382 See the individual commands for more information."
13383 (interactive "P")
13384 (if (org-at-table-p)
13385 (org-table-paste-rectangle)
13386 (org-paste-subtree arg)))
13387
13388 (defun org-edit-special ()
13389 "Call a special editor for the stuff at point.
13390 When at a table, call the formula editor with `org-table-edit-formulas'.
13391 When at the first line of an src example, call `org-edit-src-code'.
13392 When in an #+include line, visit the include file. Otherwise call
13393 `ffap' to visit the file at point."
13394 (interactive)
13395 (cond
13396 ((org-at-table-p)
13397 (call-interactively 'org-table-edit-formulas))
13398 ((save-excursion
13399 (beginning-of-line 1)
13400 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13401 (find-file (org-trim (match-string 1))))
13402 ((org-edit-src-code))
13403 ((org-edit-fixed-width-region))
13404 (t (call-interactively 'ffap))))
13405
13406 (defun org-ctrl-c-ctrl-c (&optional arg)
13407 "Set tags in headline, or update according to changed information at point.
13408
13409 This command does many different things, depending on context:
13410
13411 - If the cursor is in a headline, prompt for tags and insert them
13412 into the current line, aligned to `org-tags-column'. When called
13413 with prefix arg, realign all tags in the current buffer.
13414
13415 - If the cursor is in one of the special #+KEYWORD lines, this
13416 triggers scanning the buffer for these lines and updating the
13417 information.
13418
13419 - If the cursor is inside a table, realign the table. This command
13420 works even if the automatic table editor has been turned off.
13421
13422 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13423 the entire table.
13424
13425 - If the cursor is at a footnote reference or definition, jump to
13426 the corresponding definition or references, respectively.
13427
13428 - If the cursor is a the beginning of a dynamic block, update it.
13429
13430 - If the cursor is inside a table created by the table.el package,
13431 activate that table.
13432
13433 - If the current buffer is a remember buffer, close note and file
13434 it. A prefix argument of 1 files to the default location
13435 without further interaction. A prefix argument of 2 files to
13436 the currently clocking task.
13437
13438 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13439 links in this buffer.
13440
13441 - If the cursor is on a numbered item in a plain list, renumber the
13442 ordered list.
13443
13444 - If the cursor is on a checkbox, toggle it."
13445 (interactive "P")
13446 (let ((org-enable-table-editor t))
13447 (cond
13448 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13449 org-occur-highlights
13450 org-latex-fragment-image-overlays)
13451 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13452 (org-remove-occur-highlights)
13453 (org-remove-latex-fragment-image-overlays)
13454 (message "Temporary highlights/overlays removed from current buffer"))
13455 ((and (local-variable-p 'org-finish-function (current-buffer))
13456 (fboundp org-finish-function))
13457 (funcall org-finish-function))
13458 ((org-at-property-p)
13459 (call-interactively 'org-property-action))
13460 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13461 ((org-on-heading-p) (call-interactively 'org-set-tags))
13462 ((org-at-table.el-p)
13463 (require 'table)
13464 (beginning-of-line 1)
13465 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13466 (call-interactively 'table-recognize-table))
13467 ((org-at-table-p)
13468 (org-table-maybe-eval-formula)
13469 (if arg
13470 (call-interactively 'org-table-recalculate)
13471 (org-table-maybe-recalculate-line))
13472 (call-interactively 'org-table-align))
13473 ((or (org-footnote-at-reference-p)
13474 (org-footnote-at-definition-p))
13475 (call-interactively 'org-footnote-action))
13476 ((org-at-item-checkbox-p)
13477 (call-interactively 'org-toggle-checkbox))
13478 ((org-at-item-p)
13479 (call-interactively 'org-maybe-renumber-ordered-list))
13480 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13481 ;; Dynamic block
13482 (beginning-of-line 1)
13483 (save-excursion (org-update-dblock)))
13484 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13485 (cond
13486 ((equal (match-string 1) "TBLFM")
13487 ;; Recalculate the table before this line
13488 (save-excursion
13489 (beginning-of-line 1)
13490 (skip-chars-backward " \r\n\t")
13491 (if (org-at-table-p)
13492 (org-call-with-arg 'org-table-recalculate t))))
13493 (t
13494 ; (org-set-regexps-and-options)
13495 ; (org-restart-font-lock)
13496 (let ((org-inhibit-startup t)) (org-mode-restart))
13497 (message "Local setup has been refreshed"))))
13498 (t (error "C-c C-c can do nothing useful at this location.")))))
13499
13500 (defun org-mode-restart ()
13501 "Restart Org-mode, to scan again for special lines.
13502 Also updates the keyword regular expressions."
13503 (interactive)
13504 (org-mode)
13505 (message "Org-mode restarted"))
13506
13507 (defun org-kill-note-or-show-branches ()
13508 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13509 (interactive)
13510 (if (not org-finish-function)
13511 (call-interactively 'show-branches)
13512 (let ((org-note-abort t))
13513 (funcall org-finish-function))))
13514
13515 (defun org-return (&optional indent)
13516 "Goto next table row or insert a newline.
13517 Calls `org-table-next-row' or `newline', depending on context.
13518 See the individual commands for more information."
13519 (interactive)
13520 (cond
13521 ((bobp) (if indent (newline-and-indent) (newline)))
13522 ((and (org-at-heading-p)
13523 (looking-at
13524 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13525 (org-show-entry)
13526 (end-of-line 1)
13527 (newline))
13528 ((org-at-table-p)
13529 (org-table-justify-field-maybe)
13530 (call-interactively 'org-table-next-row))
13531 (t (if indent (newline-and-indent) (newline)))))
13532
13533 (defun org-return-indent ()
13534 "Goto next table row or insert a newline and indent.
13535 Calls `org-table-next-row' or `newline-and-indent', depending on
13536 context. See the individual commands for more information."
13537 (interactive)
13538 (org-return t))
13539
13540 (defun org-ctrl-c-star ()
13541 "Compute table, or change heading status of lines.
13542 Calls `org-table-recalculate' or `org-toggle-heading',
13543 depending on context."
13544 (interactive)
13545 (cond
13546 ((org-at-table-p)
13547 (call-interactively 'org-table-recalculate))
13548 (t
13549 ;; Convert all lines in region to list items
13550 (call-interactively 'org-toggle-heading))))
13551
13552 (defun org-ctrl-c-minus ()
13553 "Insert separator line in table or modify bullet status of line.
13554 Also turns a plain line or a region of lines into list items.
13555 Calls `org-table-insert-hline', `org-toggle-item', or
13556 `org-cycle-list-bullet', depending on context."
13557 (interactive)
13558 (cond
13559 ((org-at-table-p)
13560 (call-interactively 'org-table-insert-hline))
13561 ((org-region-active-p)
13562 (call-interactively 'org-toggle-item))
13563 ((org-in-item-p)
13564 (call-interactively 'org-cycle-list-bullet))
13565 (t
13566 (call-interactively 'org-toggle-item))))
13567
13568 (defun org-toggle-item ()
13569 "Convert headings or normal lines to items, items to normal lines.
13570 If there is no active region, only the current line is considered.
13571
13572 If the first line in the region is a headline, convert all headlines to items.
13573
13574 If the first line in the region is an item, convert all items to normal lines.
13575
13576 If the first line is normal text, add an item bullet to each line."
13577 (interactive)
13578 (let (l2 l beg end)
13579 (if (org-region-active-p)
13580 (setq beg (region-beginning) end (region-end))
13581 (setq beg (point-at-bol)
13582 end (min (1+ (point-at-eol)) (point-max))))
13583 (save-excursion
13584 (goto-char end)
13585 (setq l2 (org-current-line))
13586 (goto-char beg)
13587 (beginning-of-line 1)
13588 (setq l (1- (org-current-line)))
13589 (if (org-at-item-p)
13590 ;; We already have items, de-itemize
13591 (while (< (setq l (1+ l)) l2)
13592 (when (org-at-item-p)
13593 (goto-char (match-beginning 2))
13594 (delete-region (match-beginning 2) (match-end 2))
13595 (and (looking-at "[ \t]+") (replace-match "")))
13596 (beginning-of-line 2))
13597 (if (org-on-heading-p)
13598 ;; Headings, convert to items
13599 (while (< (setq l (1+ l)) l2)
13600 (if (looking-at org-outline-regexp)
13601 (replace-match "- " t t))
13602 (beginning-of-line 2))
13603 ;; normal lines, turn them into items
13604 (while (< (setq l (1+ l)) l2)
13605 (unless (org-at-item-p)
13606 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13607 (replace-match "\\1- \\2")))
13608 (beginning-of-line 2)))))))
13609
13610 (defun org-toggle-heading (&optional nstars)
13611 "Convert headings to normal text, or items or text to headings.
13612 If there is no active region, only the current line is considered.
13613
13614 If the first line is a heading, remove the stars from all headlines
13615 in the region.
13616
13617 If the first line is a plain list item, turn all plain list items into
13618 headings.
13619
13620 If the first line is a normal line, turn each and every line in the region
13621 into a heading.
13622
13623 When converting a line into a heading, the number of stars is chosen
13624 such that the lines become children of the current entry. However, when
13625 a prefix argument is given, its value determines the number of stars to add."
13626 (interactive "P")
13627 (let (l2 l itemp beg end)
13628 (if (org-region-active-p)
13629 (setq beg (region-beginning) end (region-end))
13630 (setq beg (point-at-bol)
13631 end (min (1+ (point-at-eol)) (point-max))))
13632 (save-excursion
13633 (goto-char end)
13634 (setq l2 (org-current-line))
13635 (goto-char beg)
13636 (beginning-of-line 1)
13637 (setq l (1- (org-current-line)))
13638 (if (org-on-heading-p)
13639 ;; We already have headlines, de-star them
13640 (while (< (setq l (1+ l)) l2)
13641 (when (org-on-heading-p t)
13642 (and (looking-at outline-regexp) (replace-match "")))
13643 (beginning-of-line 2))
13644 (setq itemp (org-at-item-p))
13645 (let* ((stars
13646 (if nstars
13647 (make-string (prefix-numeric-value current-prefix-arg)
13648 ?*)
13649 (save-excursion
13650 (re-search-backward org-complex-heading-regexp nil t)
13651 (or (match-string 1) "*"))))
13652 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
13653 (rpl (concat stars add-stars " ")))
13654 (while (< (setq l (1+ l)) l2)
13655 (if itemp
13656 (and (org-at-item-p) (replace-match rpl t t))
13657 (unless (org-on-heading-p)
13658 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13659 (replace-match (concat rpl (match-string 2))))))
13660 (beginning-of-line 2)))))))
13661
13662 (defun org-meta-return (&optional arg)
13663 "Insert a new heading or wrap a region in a table.
13664 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13665 See the individual commands for more information."
13666 (interactive "P")
13667 (cond
13668 ((org-at-table-p)
13669 (call-interactively 'org-table-wrap-region))
13670 (t (call-interactively 'org-insert-heading))))
13671
13672 ;;; Menu entries
13673
13674 ;; Define the Org-mode menus
13675 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13676 '("Tbl"
13677 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13678 ["Next Field" org-cycle (org-at-table-p)]
13679 ["Previous Field" org-shifttab (org-at-table-p)]
13680 ["Next Row" org-return (org-at-table-p)]
13681 "--"
13682 ["Blank Field" org-table-blank-field (org-at-table-p)]
13683 ["Edit Field" org-table-edit-field (org-at-table-p)]
13684 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13685 "--"
13686 ("Column"
13687 ["Move Column Left" org-metaleft (org-at-table-p)]
13688 ["Move Column Right" org-metaright (org-at-table-p)]
13689 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13690 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13691 ("Row"
13692 ["Move Row Up" org-metaup (org-at-table-p)]
13693 ["Move Row Down" org-metadown (org-at-table-p)]
13694 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13695 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13696 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13697 "--"
13698 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13699 ("Rectangle"
13700 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13701 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13702 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13703 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13704 "--"
13705 ("Calculate"
13706 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13707 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13708 ["Edit Formulas" org-edit-special (org-at-table-p)]
13709 "--"
13710 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13711 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13712 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13713 "--"
13714 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13715 "--"
13716 ["Sum Column/Rectangle" org-table-sum
13717 (or (org-at-table-p) (org-region-active-p))]
13718 ["Which Column?" org-table-current-column (org-at-table-p)])
13719 ["Debug Formulas"
13720 org-table-toggle-formula-debugger
13721 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13722 ["Show Col/Row Numbers"
13723 org-table-toggle-coordinate-overlays
13724 :style toggle
13725 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13726 "--"
13727 ["Create" org-table-create (and (not (org-at-table-p))
13728 org-enable-table-editor)]
13729 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13730 ["Import from File" org-table-import (not (org-at-table-p))]
13731 ["Export to File" org-table-export (org-at-table-p)]
13732 "--"
13733 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13734
13735 (easy-menu-define org-org-menu org-mode-map "Org menu"
13736 '("Org"
13737 ("Show/Hide"
13738 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13739 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13740 ["Sparse Tree..." org-sparse-tree t]
13741 ["Reveal Context" org-reveal t]
13742 ["Show All" show-all t]
13743 "--"
13744 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13745 "--"
13746 ["New Heading" org-insert-heading t]
13747 ("Navigate Headings"
13748 ["Up" outline-up-heading t]
13749 ["Next" outline-next-visible-heading t]
13750 ["Previous" outline-previous-visible-heading t]
13751 ["Next Same Level" outline-forward-same-level t]
13752 ["Previous Same Level" outline-backward-same-level t]
13753 "--"
13754 ["Jump" org-goto t])
13755 ("Edit Structure"
13756 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13757 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13758 "--"
13759 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13760 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13761 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13762 "--"
13763 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13764 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13765 ["Demote Heading" org-metaright (not (org-at-table-p))]
13766 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13767 "--"
13768 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13769 "--"
13770 ["Convert to odd levels" org-convert-to-odd-levels t]
13771 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13772 ("Editing"
13773 ["Emphasis..." org-emphasize t]
13774 ["Edit Source Example" org-edit-special t]
13775 "--"
13776 ["Footnote new/jump" org-footnote-action t]
13777 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13778 ("Archive"
13779 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13780 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13781 ; :active t :keys "C-u C-c C-x C-a"]
13782 ["Sparse trees open ARCHIVE trees"
13783 (setq org-sparse-tree-open-archived-trees
13784 (not org-sparse-tree-open-archived-trees))
13785 :style toggle :selected org-sparse-tree-open-archived-trees]
13786 ["Cycling opens ARCHIVE trees"
13787 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13788 :style toggle :selected org-cycle-open-archived-trees]
13789 "--"
13790 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13791 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13792 ; ["Check and Move Children" (org-archive-subtree '(4))
13793 ; :active t :keys "C-u C-c C-x C-s"]
13794 )
13795 "--"
13796 ("TODO Lists"
13797 ["TODO/DONE/-" org-todo t]
13798 ("Select keyword"
13799 ["Next keyword" org-shiftright (org-on-heading-p)]
13800 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13801 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13802 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13803 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13804 ["Show TODO Tree" org-show-todo-tree t]
13805 ["Global TODO list" org-todo-list t]
13806 "--"
13807 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
13808 :selected org-enforce-todo-dependencies :style toggle :active t]
13809 "Settings for tree at point"
13810 ["Do Children sequentially" org-toggle-ordered-property :style radio
13811 :selected (ignore-errors (org-entry-get nil "ORDERED"))
13812 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
13813 ["Do Children parallel" org-toggle-ordered-property :style radio
13814 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
13815 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
13816 "--"
13817 ["Set Priority" org-priority t]
13818 ["Priority Up" org-shiftup t]
13819 ["Priority Down" org-shiftdown t])
13820 ("TAGS and Properties"
13821 ["Set Tags" org-set-tags-command t]
13822 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13823 "--"
13824 ["Set property" org-set-property t]
13825 ["Column view of properties" org-columns t]
13826 ["Insert Column View DBlock" org-insert-columns-dblock t])
13827 ("Dates and Scheduling"
13828 ["Timestamp" org-time-stamp t]
13829 ["Timestamp (inactive)" org-time-stamp-inactive t]
13830 ("Change Date"
13831 ["1 Day Later" org-shiftright t]
13832 ["1 Day Earlier" org-shiftleft t]
13833 ["1 ... Later" org-shiftup t]
13834 ["1 ... Earlier" org-shiftdown t])
13835 ["Compute Time Range" org-evaluate-time-range t]
13836 ["Schedule Item" org-schedule t]
13837 ["Deadline" org-deadline t]
13838 "--"
13839 ["Custom time format" org-toggle-time-stamp-overlays
13840 :style radio :selected org-display-custom-times]
13841 "--"
13842 ["Goto Calendar" org-goto-calendar t]
13843 ["Date from Calendar" org-date-from-calendar t]
13844 "--"
13845 ["Start/Restart Timer" org-timer-start t]
13846 ["Pause/Continue Timer" org-timer-pause-or-continue t]
13847 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
13848 ["Insert Timer String" org-timer t]
13849 ["Insert Timer Item" org-timer-item t])
13850 ("Logging work"
13851 ["Clock in" org-clock-in t]
13852 ["Clock out" org-clock-out t]
13853 ["Clock cancel" org-clock-cancel t]
13854 ["Goto running clock" org-clock-goto t]
13855 ["Display times" org-clock-display t]
13856 ["Create clock table" org-clock-report t]
13857 "--"
13858 ["Record DONE time"
13859 (progn (setq org-log-done (not org-log-done))
13860 (message "Switching to %s will %s record a timestamp"
13861 (car org-done-keywords)
13862 (if org-log-done "automatically" "not")))
13863 :style toggle :selected org-log-done])
13864 "--"
13865 ["Agenda Command..." org-agenda t]
13866 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13867 ("File List for Agenda")
13868 ("Special views current file"
13869 ["TODO Tree" org-show-todo-tree t]
13870 ["Check Deadlines" org-check-deadlines t]
13871 ["Timeline" org-timeline t]
13872 ["Tags Tree" org-tags-sparse-tree t])
13873 "--"
13874 ("Hyperlinks"
13875 ["Store Link (Global)" org-store-link t]
13876 ["Insert Link" org-insert-link t]
13877 ["Follow Link" org-open-at-point t]
13878 "--"
13879 ["Next link" org-next-link t]
13880 ["Previous link" org-previous-link t]
13881 "--"
13882 ["Descriptive Links"
13883 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13884 :style radio
13885 :selected (member '(org-link) buffer-invisibility-spec)]
13886 ["Literal Links"
13887 (progn
13888 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13889 :style radio
13890 :selected (not (member '(org-link) buffer-invisibility-spec))])
13891 "--"
13892 ["Export/Publish..." org-export t]
13893 ("LaTeX"
13894 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13895 :selected org-cdlatex-mode]
13896 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13897 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13898 ["Modify math symbol" org-cdlatex-math-modify
13899 (org-inside-LaTeX-fragment-p)]
13900 ["Export LaTeX fragments as images"
13901 (if (featurep 'org-exp)
13902 (setq org-export-with-LaTeX-fragments
13903 (not org-export-with-LaTeX-fragments))
13904 (require 'org-exp))
13905 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13906 org-export-with-LaTeX-fragments)])
13907 "--"
13908 ("Documentation"
13909 ["Show Version" org-version t]
13910 ["Info Documentation" org-info t])
13911 ("Customize"
13912 ["Browse Org Group" org-customize t]
13913 "--"
13914 ["Expand This Menu" org-create-customize-menu
13915 (fboundp 'customize-menu-create)])
13916 "--"
13917 ["Refresh setup" org-mode-restart t]
13918 ))
13919
13920 (defun org-info (&optional node)
13921 "Read documentation for Org-mode in the info system.
13922 With optional NODE, go directly to that node."
13923 (interactive)
13924 (info (format "(org)%s" (or node ""))))
13925
13926 (defun org-install-agenda-files-menu ()
13927 (let ((bl (buffer-list)))
13928 (save-excursion
13929 (while bl
13930 (set-buffer (pop bl))
13931 (if (org-mode-p) (setq bl nil)))
13932 (when (org-mode-p)
13933 (easy-menu-change
13934 '("Org") "File List for Agenda"
13935 (append
13936 (list
13937 ["Edit File List" (org-edit-agenda-file-list) t]
13938 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13939 ["Remove Current File from List" org-remove-file t]
13940 ["Cycle through agenda files" org-cycle-agenda-files t]
13941 ["Occur in all agenda files" org-occur-in-agenda-files t]
13942 "--")
13943 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13944
13945 ;;;; Documentation
13946
13947 ;;;###autoload
13948 (defun org-require-autoloaded-modules ()
13949 (interactive)
13950 (mapc 'require
13951 '(org-agenda org-archive org-attach org-clock org-colview
13952 org-exp org-id org-export-latex org-publish
13953 org-remember org-table org-timer)))
13954
13955 ;;;###autoload
13956 (defun org-customize ()
13957 "Call the customize function with org as argument."
13958 (interactive)
13959 (org-load-modules-maybe)
13960 (org-require-autoloaded-modules)
13961 (customize-browse 'org))
13962
13963 (defun org-create-customize-menu ()
13964 "Create a full customization menu for Org-mode, insert it into the menu."
13965 (interactive)
13966 (org-load-modules-maybe)
13967 (org-require-autoloaded-modules)
13968 (if (fboundp 'customize-menu-create)
13969 (progn
13970 (easy-menu-change
13971 '("Org") "Customize"
13972 `(["Browse Org group" org-customize t]
13973 "--"
13974 ,(customize-menu-create 'org)
13975 ["Set" Custom-set t]
13976 ["Save" Custom-save t]
13977 ["Reset to Current" Custom-reset-current t]
13978 ["Reset to Saved" Custom-reset-saved t]
13979 ["Reset to Standard Settings" Custom-reset-standard t]))
13980 (message "\"Org\"-menu now contains full customization menu"))
13981 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13982
13983 ;;;; Miscellaneous stuff
13984
13985 ;;; Generally useful functions
13986
13987 (defun org-find-text-property-in-string (prop s)
13988 "Return the first non-nil value of property PROP in string S."
13989 (or (get-text-property 0 prop s)
13990 (get-text-property (or (next-single-property-change 0 prop s) 0)
13991 prop s)))
13992
13993 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13994 "Display the given MESSAGE as a warning."
13995 (if (fboundp 'display-warning)
13996 (display-warning 'org message
13997 (if (featurep 'xemacs)
13998 'warning
13999 :warning))
14000 (let ((buf (get-buffer-create "*Org warnings*")))
14001 (with-current-buffer buf
14002 (goto-char (point-max))
14003 (insert "Warning (Org): " message)
14004 (unless (bolp)
14005 (newline)))
14006 (display-buffer buf)
14007 (sit-for 0))))
14008
14009 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14010 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14011 (if (and marker (marker-buffer marker)
14012 (buffer-live-p (marker-buffer marker)))
14013 (progn
14014 (switch-to-buffer (marker-buffer marker))
14015 (if (or (> marker (point-max)) (< marker (point-min)))
14016 (widen))
14017 (goto-char marker)
14018 (org-show-context 'org-goto))
14019 (if bookmark
14020 (bookmark-jump bookmark)
14021 (error "Cannot find location"))))
14022
14023 (defun org-quote-csv-field (s)
14024 "Quote field for inclusion in CSV material."
14025 (if (string-match "[\",]" s)
14026 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14027 s))
14028
14029 (defun org-plist-delete (plist property)
14030 "Delete PROPERTY from PLIST.
14031 This is in contrast to merely setting it to 0."
14032 (let (p)
14033 (while plist
14034 (if (not (eq property (car plist)))
14035 (setq p (plist-put p (car plist) (nth 1 plist))))
14036 (setq plist (cddr plist)))
14037 p))
14038
14039 (defun org-force-self-insert (N)
14040 "Needed to enforce self-insert under remapping."
14041 (interactive "p")
14042 (self-insert-command N))
14043
14044 (defun org-string-width (s)
14045 "Compute width of string, ignoring invisible characters.
14046 This ignores character with invisibility property `org-link', and also
14047 characters with property `org-cwidth', because these will become invisible
14048 upon the next fontification round."
14049 (let (b l)
14050 (when (or (eq t buffer-invisibility-spec)
14051 (assq 'org-link buffer-invisibility-spec))
14052 (while (setq b (text-property-any 0 (length s)
14053 'invisible 'org-link s))
14054 (setq s (concat (substring s 0 b)
14055 (substring s (or (next-single-property-change
14056 b 'invisible s) (length s)))))))
14057 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14058 (setq s (concat (substring s 0 b)
14059 (substring s (or (next-single-property-change
14060 b 'org-cwidth s) (length s))))))
14061 (setq l (string-width s) b -1)
14062 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14063 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14064 l))
14065
14066 (defun org-get-indentation (&optional line)
14067 "Get the indentation of the current line, interpreting tabs.
14068 When LINE is given, assume it represents a line and compute its indentation."
14069 (if line
14070 (if (string-match "^ *" (org-remove-tabs line))
14071 (match-end 0))
14072 (save-excursion
14073 (beginning-of-line 1)
14074 (skip-chars-forward " \t")
14075 (current-column))))
14076
14077 (defun org-remove-tabs (s &optional width)
14078 "Replace tabulators in S with spaces.
14079 Assumes that s is a single line, starting in column 0."
14080 (setq width (or width tab-width))
14081 (while (string-match "\t" s)
14082 (setq s (replace-match
14083 (make-string
14084 (- (* width (/ (+ (match-beginning 0) width) width))
14085 (match-beginning 0)) ?\ )
14086 t t s)))
14087 s)
14088
14089 (defun org-fix-indentation (line ind)
14090 "Fix indentation in LINE.
14091 IND is a cons cell with target and minimum indentation.
14092 If the current indentation in LINE is smaller than the minimum,
14093 leave it alone. If it is larger than ind, set it to the target."
14094 (let* ((l (org-remove-tabs line))
14095 (i (org-get-indentation l))
14096 (i1 (car ind)) (i2 (cdr ind)))
14097 (if (>= i i2) (setq l (substring line i2)))
14098 (if (> i1 0)
14099 (concat (make-string i1 ?\ ) l)
14100 l)))
14101
14102 (defun org-base-buffer (buffer)
14103 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14104 (if (not buffer)
14105 buffer
14106 (or (buffer-base-buffer buffer)
14107 buffer)))
14108
14109 (defun org-trim (s)
14110 "Remove whitespace at beginning and end of string."
14111 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14112 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14113 s)
14114
14115 (defun org-wrap (string &optional width lines)
14116 "Wrap string to either a number of lines, or a width in characters.
14117 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14118 that costs. If there is a word longer than WIDTH, the text is actually
14119 wrapped to the length of that word.
14120 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14121 many lines, whatever width that takes.
14122 The return value is a list of lines, without newlines at the end."
14123 (let* ((words (org-split-string string "[ \t\n]+"))
14124 (maxword (apply 'max (mapcar 'org-string-width words)))
14125 w ll)
14126 (cond (width
14127 (org-do-wrap words (max maxword width)))
14128 (lines
14129 (setq w maxword)
14130 (setq ll (org-do-wrap words maxword))
14131 (if (<= (length ll) lines)
14132 ll
14133 (setq ll words)
14134 (while (> (length ll) lines)
14135 (setq w (1+ w))
14136 (setq ll (org-do-wrap words w)))
14137 ll))
14138 (t (error "Cannot wrap this")))))
14139
14140 (defun org-do-wrap (words width)
14141 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14142 (let (lines line)
14143 (while words
14144 (setq line (pop words))
14145 (while (and words (< (+ (length line) (length (car words))) width))
14146 (setq line (concat line " " (pop words))))
14147 (setq lines (push line lines)))
14148 (nreverse lines)))
14149
14150 (defun org-split-string (string &optional separators)
14151 "Splits STRING into substrings at SEPARATORS.
14152 No empty strings are returned if there are matches at the beginning
14153 and end of string."
14154 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14155 (start 0)
14156 notfirst
14157 (list nil))
14158 (while (and (string-match rexp string
14159 (if (and notfirst
14160 (= start (match-beginning 0))
14161 (< start (length string)))
14162 (1+ start) start))
14163 (< (match-beginning 0) (length string)))
14164 (setq notfirst t)
14165 (or (eq (match-beginning 0) 0)
14166 (and (eq (match-beginning 0) (match-end 0))
14167 (eq (match-beginning 0) start))
14168 (setq list
14169 (cons (substring string start (match-beginning 0))
14170 list)))
14171 (setq start (match-end 0)))
14172 (or (eq start (length string))
14173 (setq list
14174 (cons (substring string start)
14175 list)))
14176 (nreverse list)))
14177
14178 (defun org-context ()
14179 "Return a list of contexts of the current cursor position.
14180 If several contexts apply, all are returned.
14181 Each context entry is a list with a symbol naming the context, and
14182 two positions indicating start and end of the context. Possible
14183 contexts are:
14184
14185 :headline anywhere in a headline
14186 :headline-stars on the leading stars in a headline
14187 :todo-keyword on a TODO keyword (including DONE) in a headline
14188 :tags on the TAGS in a headline
14189 :priority on the priority cookie in a headline
14190 :item on the first line of a plain list item
14191 :item-bullet on the bullet/number of a plain list item
14192 :checkbox on the checkbox in a plain list item
14193 :table in an org-mode table
14194 :table-special on a special filed in a table
14195 :table-table in a table.el table
14196 :link on a hyperlink
14197 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14198 :target on a <<target>>
14199 :radio-target on a <<<radio-target>>>
14200 :latex-fragment on a LaTeX fragment
14201 :latex-preview on a LaTeX fragment with overlayed preview image
14202
14203 This function expects the position to be visible because it uses font-lock
14204 faces as a help to recognize the following contexts: :table-special, :link,
14205 and :keyword."
14206 (let* ((f (get-text-property (point) 'face))
14207 (faces (if (listp f) f (list f)))
14208 (p (point)) clist o)
14209 ;; First the large context
14210 (cond
14211 ((org-on-heading-p t)
14212 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14213 (when (progn
14214 (beginning-of-line 1)
14215 (looking-at org-todo-line-tags-regexp))
14216 (push (org-point-in-group p 1 :headline-stars) clist)
14217 (push (org-point-in-group p 2 :todo-keyword) clist)
14218 (push (org-point-in-group p 4 :tags) clist))
14219 (goto-char p)
14220 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14221 (if (looking-at "\\[#[A-Z0-9]\\]")
14222 (push (org-point-in-group p 0 :priority) clist)))
14223
14224 ((org-at-item-p)
14225 (push (org-point-in-group p 2 :item-bullet) clist)
14226 (push (list :item (point-at-bol)
14227 (save-excursion (org-end-of-item) (point)))
14228 clist)
14229 (and (org-at-item-checkbox-p)
14230 (push (org-point-in-group p 0 :checkbox) clist)))
14231
14232 ((org-at-table-p)
14233 (push (list :table (org-table-begin) (org-table-end)) clist)
14234 (if (memq 'org-formula faces)
14235 (push (list :table-special
14236 (previous-single-property-change p 'face)
14237 (next-single-property-change p 'face)) clist)))
14238 ((org-at-table-p 'any)
14239 (push (list :table-table) clist)))
14240 (goto-char p)
14241
14242 ;; Now the small context
14243 (cond
14244 ((org-at-timestamp-p)
14245 (push (org-point-in-group p 0 :timestamp) clist))
14246 ((memq 'org-link faces)
14247 (push (list :link
14248 (previous-single-property-change p 'face)
14249 (next-single-property-change p 'face)) clist))
14250 ((memq 'org-special-keyword faces)
14251 (push (list :keyword
14252 (previous-single-property-change p 'face)
14253 (next-single-property-change p 'face)) clist))
14254 ((org-on-target-p)
14255 (push (org-point-in-group p 0 :target) clist)
14256 (goto-char (1- (match-beginning 0)))
14257 (if (looking-at org-radio-target-regexp)
14258 (push (org-point-in-group p 0 :radio-target) clist))
14259 (goto-char p))
14260 ((setq o (car (delq nil
14261 (mapcar
14262 (lambda (x)
14263 (if (memq x org-latex-fragment-image-overlays) x))
14264 (org-overlays-at (point))))))
14265 (push (list :latex-fragment
14266 (org-overlay-start o) (org-overlay-end o)) clist)
14267 (push (list :latex-preview
14268 (org-overlay-start o) (org-overlay-end o)) clist))
14269 ((org-inside-LaTeX-fragment-p)
14270 ;; FIXME: positions wrong.
14271 (push (list :latex-fragment (point) (point)) clist)))
14272
14273 (setq clist (nreverse (delq nil clist)))
14274 clist))
14275
14276 ;; FIXME: Compare with at-regexp-p Do we need both?
14277 (defun org-in-regexp (re &optional nlines visually)
14278 "Check if point is inside a match of regexp.
14279 Normally only the current line is checked, but you can include NLINES extra
14280 lines both before and after point into the search.
14281 If VISUALLY is set, require that the cursor is not after the match but
14282 really on, so that the block visually is on the match."
14283 (catch 'exit
14284 (let ((pos (point))
14285 (eol (point-at-eol (+ 1 (or nlines 0))))
14286 (inc (if visually 1 0)))
14287 (save-excursion
14288 (beginning-of-line (- 1 (or nlines 0)))
14289 (while (re-search-forward re eol t)
14290 (if (and (<= (match-beginning 0) pos)
14291 (>= (+ inc (match-end 0)) pos))
14292 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14293
14294 (defun org-at-regexp-p (regexp)
14295 "Is point inside a match of REGEXP in the current line?"
14296 (catch 'exit
14297 (save-excursion
14298 (let ((pos (point)) (end (point-at-eol)))
14299 (beginning-of-line 1)
14300 (while (re-search-forward regexp end t)
14301 (if (and (<= (match-beginning 0) pos)
14302 (>= (match-end 0) pos))
14303 (throw 'exit t)))
14304 nil))))
14305
14306 (defun org-occur-in-agenda-files (regexp &optional nlines)
14307 "Call `multi-occur' with buffers for all agenda files."
14308 (interactive "sOrg-files matching: \np")
14309 (let* ((files (org-agenda-files))
14310 (tnames (mapcar 'file-truename files))
14311 (extra org-agenda-text-search-extra-files)
14312 f)
14313 (when (eq (car extra) 'agenda-archives)
14314 (setq extra (cdr extra))
14315 (setq files (org-add-archive-files files)))
14316 (while (setq f (pop extra))
14317 (unless (member (file-truename f) tnames)
14318 (add-to-list 'files f 'append)
14319 (add-to-list 'tnames (file-truename f) 'append)))
14320 (multi-occur
14321 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14322 regexp)))
14323
14324 (if (boundp 'occur-mode-find-occurrence-hook)
14325 ;; Emacs 23
14326 (add-hook 'occur-mode-find-occurrence-hook
14327 (lambda ()
14328 (when (org-mode-p)
14329 (org-reveal))))
14330 ;; Emacs 22
14331 (defadvice occur-mode-goto-occurrence
14332 (after org-occur-reveal activate)
14333 (and (org-mode-p) (org-reveal)))
14334 (defadvice occur-mode-goto-occurrence-other-window
14335 (after org-occur-reveal activate)
14336 (and (org-mode-p) (org-reveal)))
14337 (defadvice occur-mode-display-occurrence
14338 (after org-occur-reveal activate)
14339 (when (org-mode-p)
14340 (let ((pos (occur-mode-find-occurrence)))
14341 (with-current-buffer (marker-buffer pos)
14342 (save-excursion
14343 (goto-char pos)
14344 (org-reveal)))))))
14345
14346 (defun org-uniquify (list)
14347 "Remove duplicate elements from LIST."
14348 (let (res)
14349 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14350 res))
14351
14352 (defun org-delete-all (elts list)
14353 "Remove all elements in ELTS from LIST."
14354 (while elts
14355 (setq list (delete (pop elts) list)))
14356 list)
14357
14358 (defun org-back-over-empty-lines ()
14359 "Move backwards over whitespace, to the beginning of the first empty line.
14360 Returns the number of empty lines passed."
14361 (let ((pos (point)))
14362 (skip-chars-backward " \t\n\r")
14363 (beginning-of-line 2)
14364 (goto-char (min (point) pos))
14365 (count-lines (point) pos)))
14366
14367 (defun org-skip-whitespace ()
14368 (skip-chars-forward " \t\n\r"))
14369
14370 (defun org-point-in-group (point group &optional context)
14371 "Check if POINT is in match-group GROUP.
14372 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14373 match. If the match group does ot exist or point is not inside it,
14374 return nil."
14375 (and (match-beginning group)
14376 (>= point (match-beginning group))
14377 (<= point (match-end group))
14378 (if context
14379 (list context (match-beginning group) (match-end group))
14380 t)))
14381
14382 (defun org-switch-to-buffer-other-window (&rest args)
14383 "Switch to buffer in a second window on the current frame.
14384 In particular, do not allow pop-up frames."
14385 (let (pop-up-frames special-display-buffer-names special-display-regexps
14386 special-display-function)
14387 (apply 'switch-to-buffer-other-window args)))
14388
14389 (defun org-combine-plists (&rest plists)
14390 "Create a single property list from all plists in PLISTS.
14391 The process starts by copying the first list, and then setting properties
14392 from the other lists. Settings in the last list are the most significant
14393 ones and overrule settings in the other lists."
14394 (let ((rtn (copy-sequence (pop plists)))
14395 p v ls)
14396 (while plists
14397 (setq ls (pop plists))
14398 (while ls
14399 (setq p (pop ls) v (pop ls))
14400 (setq rtn (plist-put rtn p v))))
14401 rtn))
14402
14403 (defun org-move-line-down (arg)
14404 "Move the current line down. With prefix argument, move it past ARG lines."
14405 (interactive "p")
14406 (let ((col (current-column))
14407 beg end pos)
14408 (beginning-of-line 1) (setq beg (point))
14409 (beginning-of-line 2) (setq end (point))
14410 (beginning-of-line (+ 1 arg))
14411 (setq pos (move-marker (make-marker) (point)))
14412 (insert (delete-and-extract-region beg end))
14413 (goto-char pos)
14414 (org-move-to-column col)))
14415
14416 (defun org-move-line-up (arg)
14417 "Move the current line up. With prefix argument, move it past ARG lines."
14418 (interactive "p")
14419 (let ((col (current-column))
14420 beg end pos)
14421 (beginning-of-line 1) (setq beg (point))
14422 (beginning-of-line 2) (setq end (point))
14423 (beginning-of-line (- arg))
14424 (setq pos (move-marker (make-marker) (point)))
14425 (insert (delete-and-extract-region beg end))
14426 (goto-char pos)
14427 (org-move-to-column col)))
14428
14429 (defun org-replace-escapes (string table)
14430 "Replace %-escapes in STRING with values in TABLE.
14431 TABLE is an association list with keys like \"%a\" and string values.
14432 The sequences in STRING may contain normal field width and padding information,
14433 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14434 so values can contain further %-escapes if they are define later in TABLE."
14435 (let ((case-fold-search nil)
14436 e re rpl)
14437 (while (setq e (pop table))
14438 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14439 (while (string-match re string)
14440 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14441 (cdr e)))
14442 (setq string (replace-match rpl t t string))))
14443 string))
14444
14445
14446 (defun org-sublist (list start end)
14447 "Return a section of LIST, from START to END.
14448 Counting starts at 1."
14449 (let (rtn (c start))
14450 (setq list (nthcdr (1- start) list))
14451 (while (and list (<= c end))
14452 (push (pop list) rtn)
14453 (setq c (1+ c)))
14454 (nreverse rtn)))
14455
14456 (defun org-find-base-buffer-visiting (file)
14457 "Like `find-buffer-visiting' but alway return the base buffer and
14458 not an indirect buffer."
14459 (let ((buf (find-buffer-visiting file)))
14460 (if buf
14461 (or (buffer-base-buffer buf) buf)
14462 nil)))
14463
14464 (defun org-image-file-name-regexp (&optional extensions)
14465 "Return regexp matching the file names of images.
14466 If EXTENSIONS is given, only match these."
14467 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14468 (image-file-name-regexp)
14469 (let ((image-file-name-extensions
14470 (or extensions
14471 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14472 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14473 (concat "\\."
14474 (regexp-opt (nconc (mapcar 'upcase
14475 image-file-name-extensions)
14476 image-file-name-extensions)
14477 t)
14478 "\\'"))))
14479
14480 (defun org-file-image-p (file &optional extensions)
14481 "Return non-nil if FILE is an image."
14482 (save-match-data
14483 (string-match (org-image-file-name-regexp extensions) file)))
14484
14485 (defun org-get-cursor-date ()
14486 "Return the date at cursor in as a time.
14487 This works in the calendar and in the agenda, anywhere else it just
14488 returns the current time."
14489 (let (date day defd)
14490 (cond
14491 ((eq major-mode 'calendar-mode)
14492 (setq date (calendar-cursor-to-date)
14493 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14494 ((eq major-mode 'org-agenda-mode)
14495 (setq day (get-text-property (point) 'day))
14496 (if day
14497 (setq date (calendar-gregorian-from-absolute day)
14498 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14499 (nth 2 date))))))
14500 (or defd (current-time))))
14501
14502 (defvar org-agenda-action-marker (make-marker)
14503 "Marker pointing to the entry for the next agenda action.")
14504
14505 (defun org-mark-entry-for-agenda-action ()
14506 "Mark the current entry as target of an agenda action.
14507 Agenda actions are actions executed from the agenda with the key `k',
14508 which make use of the date at the cursor."
14509 (interactive)
14510 (move-marker org-agenda-action-marker
14511 (save-excursion (org-back-to-heading t) (point))
14512 (current-buffer))
14513 (message
14514 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14515
14516 ;;; Paragraph filling stuff.
14517 ;; We want this to be just right, so use the full arsenal.
14518
14519 (defun org-indent-line-function ()
14520 "Indent line like previous, but further if previous was headline or item."
14521 (interactive)
14522 (let* ((pos (point))
14523 (itemp (org-at-item-p))
14524 column bpos bcol tpos tcol bullet btype bullet-type)
14525 ;; Find the previous relevant line
14526 (beginning-of-line 1)
14527 (cond
14528 ((looking-at "#") (setq column 0))
14529 ((looking-at "\\*+ ") (setq column 0))
14530 (t
14531 (beginning-of-line 0)
14532 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14533 (beginning-of-line 0))
14534 (cond
14535 ((looking-at "\\*+[ \t]+")
14536 (if (not org-adapt-indentation)
14537 (setq column 0)
14538 (goto-char (match-end 0))
14539 (setq column (current-column))))
14540 ((org-in-item-p)
14541 (org-beginning-of-item)
14542 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14543 (setq bpos (match-beginning 1) tpos (match-end 0)
14544 bcol (progn (goto-char bpos) (current-column))
14545 tcol (progn (goto-char tpos) (current-column))
14546 bullet (match-string 1)
14547 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14548 (if (> tcol (+ bcol org-description-max-indent))
14549 (setq tcol (+ bcol 5)))
14550 (if (not itemp)
14551 (setq column tcol)
14552 (goto-char pos)
14553 (beginning-of-line 1)
14554 (if (looking-at "\\S-")
14555 (progn
14556 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14557 (setq bullet (match-string 1)
14558 btype (if (string-match "[0-9]" bullet) "n" bullet))
14559 (setq column (if (equal btype bullet-type) bcol tcol)))
14560 (setq column (org-get-indentation)))))
14561 (t (setq column (org-get-indentation))))))
14562 (goto-char pos)
14563 (if (<= (current-column) (current-indentation))
14564 (org-indent-line-to column)
14565 (save-excursion (org-indent-line-to column)))
14566 (setq column (current-column))
14567 (beginning-of-line 1)
14568 (if (looking-at
14569 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14570 (replace-match (concat "\\1" (format org-property-format
14571 (match-string 2) (match-string 3)))
14572 t nil))
14573 (org-move-to-column column)))
14574
14575 (defun org-set-autofill-regexps ()
14576 (interactive)
14577 ;; In the paragraph separator we include headlines, because filling
14578 ;; text in a line directly attached to a headline would otherwise
14579 ;; fill the headline as well.
14580 (org-set-local 'comment-start-skip "^#+[ \t]*")
14581 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14582 ;; The paragraph starter includes hand-formatted lists.
14583 (org-set-local 'paragraph-start
14584 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14585 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14586 ;; But only if the user has not turned off tables or fixed-width regions
14587 (org-set-local
14588 'auto-fill-inhibit-regexp
14589 (concat "\\*+ \\|#\\+"
14590 "\\|[ \t]*" org-keyword-time-regexp
14591 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14592 (concat
14593 "\\|[ \t]*["
14594 (if org-enable-table-editor "|" "")
14595 (if org-enable-fixed-width-editor ":" "")
14596 "]"))))
14597 ;; We use our own fill-paragraph function, to make sure that tables
14598 ;; and fixed-width regions are not wrapped. That function will pass
14599 ;; through to `fill-paragraph' when appropriate.
14600 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14601 ; Adaptive filling: To get full control, first make sure that
14602 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14603 (org-set-local 'adaptive-fill-regexp "\000")
14604 (org-set-local 'adaptive-fill-function
14605 'org-adaptive-fill-function)
14606 (org-set-local
14607 'align-mode-rules-list
14608 '((org-in-buffer-settings
14609 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14610 (modes . '(org-mode))))))
14611
14612 (defun org-fill-paragraph (&optional justify)
14613 "Re-align a table, pass through to fill-paragraph if no table."
14614 (let ((table-p (org-at-table-p))
14615 (table.el-p (org-at-table.el-p)))
14616 (cond ((and (equal (char-after (point-at-bol)) ?*)
14617 (save-excursion (goto-char (point-at-bol))
14618 (looking-at outline-regexp)))
14619 t) ; skip headlines
14620 (table.el-p t) ; skip table.el tables
14621 (table-p (org-table-align) t) ; align org-mode tables
14622 (t nil)))) ; call paragraph-fill
14623
14624 ;; For reference, this is the default value of adaptive-fill-regexp
14625 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14626
14627 (defun org-adaptive-fill-function ()
14628 "Return a fill prefix for org-mode files.
14629 In particular, this makes sure hanging paragraphs for hand-formatted lists
14630 work correctly."
14631 (cond ((looking-at "#[ \t]+")
14632 (match-string 0))
14633 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14634 (save-excursion
14635 (if (> (match-end 1) (+ (match-beginning 1)
14636 org-description-max-indent))
14637 (goto-char (+ (match-beginning 1) 5))
14638 (goto-char (match-end 0)))
14639 (make-string (current-column) ?\ )))
14640 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14641 (save-excursion
14642 (goto-char (match-end 0))
14643 (make-string (current-column) ?\ )))
14644 (t nil)))
14645
14646 ;;; Other stuff.
14647
14648 (defun org-toggle-fixed-width-section (arg)
14649 "Toggle the fixed-width export.
14650 If there is no active region, the QUOTE keyword at the current headline is
14651 inserted or removed. When present, it causes the text between this headline
14652 and the next to be exported as fixed-width text, and unmodified.
14653 If there is an active region, this command adds or removes a colon as the
14654 first character of this line. If the first character of a line is a colon,
14655 this line is also exported in fixed-width font."
14656 (interactive "P")
14657 (let* ((cc 0)
14658 (regionp (org-region-active-p))
14659 (beg (if regionp (region-beginning) (point)))
14660 (end (if regionp (region-end)))
14661 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14662 (case-fold-search nil)
14663 (re "[ \t]*\\(:\\)")
14664 off)
14665 (if regionp
14666 (save-excursion
14667 (goto-char beg)
14668 (setq cc (current-column))
14669 (beginning-of-line 1)
14670 (setq off (looking-at re))
14671 (while (> nlines 0)
14672 (setq nlines (1- nlines))
14673 (beginning-of-line 1)
14674 (cond
14675 (arg
14676 (org-move-to-column cc t)
14677 (insert ":\n")
14678 (forward-line -1))
14679 ((and off (looking-at re))
14680 (replace-match "" t t nil 1))
14681 ((not off) (org-move-to-column cc t) (insert ":")))
14682 (forward-line 1)))
14683 (save-excursion
14684 (org-back-to-heading)
14685 (if (looking-at (concat outline-regexp
14686 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14687 (replace-match "" t t nil 1)
14688 (if (looking-at outline-regexp)
14689 (progn
14690 (goto-char (match-end 0))
14691 (insert org-quote-string " "))))))))
14692
14693 ;;;; Functions extending outline functionality
14694
14695 (defun org-beginning-of-line (&optional arg)
14696 "Go to the beginning of the current line. If that is invisible, continue
14697 to a visible line beginning. This makes the function of C-a more intuitive.
14698 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14699 first attempt, and only move to after the tags when the cursor is already
14700 beyond the end of the headline."
14701 (interactive "P")
14702 (let ((pos (point)) refpos)
14703 (beginning-of-line 1)
14704 (if (and arg (fboundp 'move-beginning-of-line))
14705 (call-interactively 'move-beginning-of-line)
14706 (if (bobp)
14707 nil
14708 (backward-char 1)
14709 (if (org-invisible-p)
14710 (while (and (not (bobp)) (org-invisible-p))
14711 (backward-char 1)
14712 (beginning-of-line 1))
14713 (forward-char 1))))
14714 (when org-special-ctrl-a/e
14715 (cond
14716 ((and (looking-at org-complex-heading-regexp)
14717 (= (char-after (match-end 1)) ?\ ))
14718 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14719 (point-at-eol)))
14720 (goto-char
14721 (if (eq org-special-ctrl-a/e t)
14722 (cond ((> pos refpos) refpos)
14723 ((= pos (point)) refpos)
14724 (t (point)))
14725 (cond ((> pos (point)) (point))
14726 ((not (eq last-command this-command)) (point))
14727 (t refpos)))))
14728 ((org-at-item-p)
14729 (goto-char
14730 (if (eq org-special-ctrl-a/e t)
14731 (cond ((> pos (match-end 4)) (match-end 4))
14732 ((= pos (point)) (match-end 4))
14733 (t (point)))
14734 (cond ((> pos (point)) (point))
14735 ((not (eq last-command this-command)) (point))
14736 (t (match-end 4))))))))
14737 (org-no-warnings
14738 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14739
14740 (defun org-end-of-line (&optional arg)
14741 "Go to the end of the line.
14742 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14743 first attempt, and only move to after the tags when the cursor is already
14744 beyond the end of the headline."
14745 (interactive "P")
14746 (if (or (not org-special-ctrl-a/e)
14747 (not (org-on-heading-p))
14748 arg)
14749 (call-interactively (if (fboundp 'move-end-of-line)
14750 'move-end-of-line
14751 'end-of-line))
14752 (let ((pos (point)))
14753 (beginning-of-line 1)
14754 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14755 (if (eq org-special-ctrl-a/e t)
14756 (if (or (< pos (match-beginning 1))
14757 (= pos (match-end 0)))
14758 (goto-char (match-beginning 1))
14759 (goto-char (match-end 0)))
14760 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14761 (goto-char (match-end 0))
14762 (goto-char (match-beginning 1))))
14763 (call-interactively (if (fboundp 'move-end-of-line)
14764 'move-end-of-line
14765 'end-of-line)))))
14766 (org-no-warnings
14767 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14768
14769 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14770 (define-key org-mode-map "\C-e" 'org-end-of-line)
14771
14772 (defun org-kill-line (&optional arg)
14773 "Kill line, to tags or end of line."
14774 (interactive "P")
14775 (cond
14776 ((or (not org-special-ctrl-k)
14777 (bolp)
14778 (not (org-on-heading-p)))
14779 (call-interactively 'kill-line))
14780 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14781 (kill-region (point) (match-beginning 1))
14782 (org-set-tags nil t))
14783 (t (kill-region (point) (point-at-eol)))))
14784
14785 (define-key org-mode-map "\C-k" 'org-kill-line)
14786
14787 (defun org-yank (&optional arg)
14788 "Yank. If the kill is a subtree, treat it specially.
14789 This command will look at the current kill and check if is a single
14790 subtree, or a series of subtrees[1]. If it passes the test, and if the
14791 cursor is at the beginning of a line or after the stars of a currently
14792 empty headline, then the yank is handled specially. How exactly depends
14793 on the value of the following variables, both set by default.
14794
14795 org-yank-folded-subtrees
14796 When set, the subtree(s) will be folded after insertion, but only
14797 if doing so would now swallow text after the yanked text.
14798
14799 org-yank-adjusted-subtrees
14800 When set, the subtree will be promoted or demoted in order to
14801 fit into the local outline tree structure, which means that the level
14802 will be adjusted so that it becomes the smaller one of the two
14803 *visible* surrounding headings.
14804
14805 Any prefix to this command will cause `yank' to be called directly with
14806 no special treatment. In particular, a simple `C-u' prefix will just
14807 plainly yank the text as it is.
14808
14809 \[1] Basically, the test checks if the first non-white line is a heading
14810 and if there are no other headings with fewer stars."
14811 (interactive "P")
14812 (setq this-command 'yank)
14813 (if arg
14814 (call-interactively 'yank)
14815 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14816 (and (org-kill-is-subtree-p)
14817 (or (bolp)
14818 (and (looking-at "[ \t]*$")
14819 (string-match
14820 "\\`\\*+\\'"
14821 (buffer-substring (point-at-bol) (point)))))))
14822 swallowp)
14823 (cond
14824 ((and subtreep org-yank-folded-subtrees)
14825 (let ((beg (point))
14826 end)
14827 (if (and subtreep org-yank-adjusted-subtrees)
14828 (org-paste-subtree nil nil 'for-yank)
14829 (call-interactively 'yank))
14830 (setq end (point))
14831 (goto-char beg)
14832 (when (and (bolp) subtreep
14833 (not (setq swallowp
14834 (org-yank-folding-would-swallow-text beg end))))
14835 (or (looking-at outline-regexp)
14836 (re-search-forward (concat "^" outline-regexp) end t))
14837 (while (and (< (point) end) (looking-at outline-regexp))
14838 (hide-subtree)
14839 (org-cycle-show-empty-lines 'folded)
14840 (condition-case nil
14841 (outline-forward-same-level 1)
14842 (error (goto-char end)))))
14843 (when swallowp
14844 (message
14845 "Yanked text not folded because that would swallow text"))
14846 (goto-char end)
14847 (skip-chars-forward " \t\n\r")
14848 (beginning-of-line 1)
14849 (push-mark beg 'nomsg)))
14850 ((and subtreep org-yank-adjusted-subtrees)
14851 (let ((beg (point-at-bol)))
14852 (org-paste-subtree nil nil 'for-yank)
14853 (push-mark beg 'nomsg)))
14854 (t
14855 (call-interactively 'yank))))))
14856
14857 (defun org-yank-folding-would-swallow-text (beg end)
14858 "Would hide-subtree at BEG swallow any text after END?"
14859 (let (level)
14860 (save-excursion
14861 (goto-char beg)
14862 (when (or (looking-at outline-regexp)
14863 (re-search-forward (concat "^" outline-regexp) end t))
14864 (setq level (org-outline-level)))
14865 (goto-char end)
14866 (skip-chars-forward " \t\r\n\v\f")
14867 (if (or (eobp)
14868 (and (bolp) (looking-at org-outline-regexp)
14869 (<= (org-outline-level) level)))
14870 nil ; Nothing would be swallowed
14871 t)))) ; something would swallow
14872
14873 (define-key org-mode-map "\C-y" 'org-yank)
14874
14875 (defun org-invisible-p ()
14876 "Check if point is at a character currently not visible."
14877 ;; Early versions of noutline don't have `outline-invisible-p'.
14878 (if (fboundp 'outline-invisible-p)
14879 (outline-invisible-p)
14880 (get-char-property (point) 'invisible)))
14881
14882 (defun org-invisible-p2 ()
14883 "Check if point is at a character currently not visible."
14884 (save-excursion
14885 (if (and (eolp) (not (bobp))) (backward-char 1))
14886 ;; Early versions of noutline don't have `outline-invisible-p'.
14887 (if (fboundp 'outline-invisible-p)
14888 (outline-invisible-p)
14889 (get-char-property (point) 'invisible))))
14890
14891 (defun org-back-to-heading (&optional invisible-ok)
14892 "Call `outline-back-to-heading', but provide a better error message."
14893 (condition-case nil
14894 (outline-back-to-heading invisible-ok)
14895 (error (error "Before first headline at position %d in buffer %s"
14896 (point) (current-buffer)))))
14897
14898 (defun org-before-first-heading-p ()
14899 "Before first heading?"
14900 (save-excursion
14901 (null (re-search-backward "^\\*+ " nil t))))
14902
14903 (defalias 'org-on-heading-p 'outline-on-heading-p)
14904 (defalias 'org-at-heading-p 'outline-on-heading-p)
14905 (defun org-at-heading-or-item-p ()
14906 (or (org-on-heading-p) (org-at-item-p)))
14907
14908 (defun org-on-target-p ()
14909 (or (org-in-regexp org-radio-target-regexp)
14910 (org-in-regexp org-target-regexp)))
14911
14912 (defun org-up-heading-all (arg)
14913 "Move to the heading line of which the present line is a subheading.
14914 This function considers both visible and invisible heading lines.
14915 With argument, move up ARG levels."
14916 (if (fboundp 'outline-up-heading-all)
14917 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14918 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14919
14920 (defun org-up-heading-safe ()
14921 "Move to the heading line of which the present line is a subheading.
14922 This version will not throw an error. It will return the level of the
14923 headline found, or nil if no higher level is found."
14924 (let (start-level re)
14925 (org-back-to-heading t)
14926 (setq start-level (funcall outline-level))
14927 (if (equal start-level 1)
14928 nil
14929 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14930 (if (re-search-backward re nil t)
14931 (funcall outline-level)))))
14932
14933 (defun org-first-sibling-p ()
14934 "Is this heading the first child of its parents?"
14935 (interactive)
14936 (let ((re (concat "^" outline-regexp))
14937 level l)
14938 (unless (org-at-heading-p t)
14939 (error "Not at a heading"))
14940 (setq level (funcall outline-level))
14941 (save-excursion
14942 (if (not (re-search-backward re nil t))
14943 t
14944 (setq l (funcall outline-level))
14945 (< l level)))))
14946
14947 (defun org-goto-sibling (&optional previous)
14948 "Goto the next sibling, even if it is invisible.
14949 When PREVIOUS is set, go to the previous sibling instead. Returns t
14950 when a sibling was found. When none is found, return nil and don't
14951 move point."
14952 (let ((fun (if previous 're-search-backward 're-search-forward))
14953 (pos (point))
14954 (re (concat "^" outline-regexp))
14955 level l)
14956 (when (condition-case nil (org-back-to-heading t) (error nil))
14957 (setq level (funcall outline-level))
14958 (catch 'exit
14959 (or previous (forward-char 1))
14960 (while (funcall fun re nil t)
14961 (setq l (funcall outline-level))
14962 (when (< l level) (goto-char pos) (throw 'exit nil))
14963 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14964 (goto-char pos)
14965 nil))))
14966
14967 (defun org-show-siblings ()
14968 "Show all siblings of the current headline."
14969 (save-excursion
14970 (while (org-goto-sibling) (org-flag-heading nil)))
14971 (save-excursion
14972 (while (org-goto-sibling 'previous)
14973 (org-flag-heading nil))))
14974
14975 (defun org-show-hidden-entry ()
14976 "Show an entry where even the heading is hidden."
14977 (save-excursion
14978 (org-show-entry)))
14979
14980 (defun org-flag-heading (flag &optional entry)
14981 "Flag the current heading. FLAG non-nil means make invisible.
14982 When ENTRY is non-nil, show the entire entry."
14983 (save-excursion
14984 (org-back-to-heading t)
14985 ;; Check if we should show the entire entry
14986 (if entry
14987 (progn
14988 (org-show-entry)
14989 (save-excursion
14990 (and (outline-next-heading)
14991 (org-flag-heading nil))))
14992 (outline-flag-region (max (point-min) (1- (point)))
14993 (save-excursion (outline-end-of-heading) (point))
14994 flag))))
14995
14996 (defun org-forward-same-level (arg)
14997 "Move forward to the ARG'th subheading at same level as this one.
14998 Stop at the first and last subheadings of a superior heading.
14999 This is like outline-forward-same-level, but invisible headings are ok."
15000 (interactive "p")
15001 (org-back-to-heading t)
15002 (while (> arg 0)
15003 (let ((point-to-move-to (save-excursion
15004 (org-get-next-sibling))))
15005 (if point-to-move-to
15006 (progn
15007 (goto-char point-to-move-to)
15008 (setq arg (1- arg)))
15009 (progn
15010 (setq arg 0)
15011 (error "No following same-level heading"))))))
15012
15013 (defun org-get-next-sibling ()
15014 "Move to next heading of the same level, and return point.
15015 If there is no such heading, return nil.
15016 This is like outline-next-sibling, but invisible headings are ok."
15017 (let ((level (funcall outline-level)))
15018 (outline-next-heading)
15019 (while (and (not (eobp)) (> (funcall outline-level) level))
15020 (outline-next-heading))
15021 (if (or (eobp) (< (funcall outline-level) level))
15022 nil
15023 (point))))
15024
15025 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15026 ;; This is an exact copy of the original function, but it uses
15027 ;; `org-back-to-heading', to make it work also in invisible
15028 ;; trees. And is uses an invisible-OK argument.
15029 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15030 (org-back-to-heading invisible-OK)
15031 (let ((first t)
15032 (level (funcall outline-level)))
15033 (while (and (not (eobp))
15034 (or first (> (funcall outline-level) level)))
15035 (setq first nil)
15036 (outline-next-heading))
15037 (unless to-heading
15038 (if (memq (preceding-char) '(?\n ?\^M))
15039 (progn
15040 ;; Go to end of line before heading
15041 (forward-char -1)
15042 (if (memq (preceding-char) '(?\n ?\^M))
15043 ;; leave blank line before heading
15044 (forward-char -1))))))
15045 (point))
15046
15047 (defun org-show-subtree ()
15048 "Show everything after this heading at deeper levels."
15049 (outline-flag-region
15050 (point)
15051 (save-excursion
15052 (outline-end-of-subtree) (outline-next-heading) (point))
15053 nil))
15054
15055 (defun org-show-entry ()
15056 "Show the body directly following this heading.
15057 Show the heading too, if it is currently invisible."
15058 (interactive)
15059 (save-excursion
15060 (condition-case nil
15061 (progn
15062 (org-back-to-heading t)
15063 (outline-flag-region
15064 (max (point-min) (1- (point)))
15065 (save-excursion
15066 (re-search-forward
15067 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
15068 (or (match-beginning 1) (point-max)))
15069 nil))
15070 (error nil))))
15071
15072 (defun org-make-options-regexp (kwds)
15073 "Make a regular expression for keyword lines."
15074 (concat
15075 "^"
15076 "#?[ \t]*\\+\\("
15077 (mapconcat 'regexp-quote kwds "\\|")
15078 "\\):[ \t]*"
15079 "\\(.+\\)"))
15080
15081 ;; Make isearch reveal the necessary context
15082 (defun org-isearch-end ()
15083 "Reveal context after isearch exits."
15084 (when isearch-success ; only if search was successful
15085 (if (featurep 'xemacs)
15086 ;; Under XEmacs, the hook is run in the correct place,
15087 ;; we directly show the context.
15088 (org-show-context 'isearch)
15089 ;; In Emacs the hook runs *before* restoring the overlays.
15090 ;; So we have to use a one-time post-command-hook to do this.
15091 ;; (Emacs 22 has a special variable, see function `org-mode')
15092 (unless (and (boundp 'isearch-mode-end-hook-quit)
15093 isearch-mode-end-hook-quit)
15094 ;; Only when the isearch was not quitted.
15095 (org-add-hook 'post-command-hook 'org-isearch-post-command
15096 'append 'local)))))
15097
15098 (defun org-isearch-post-command ()
15099 "Remove self from hook, and show context."
15100 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15101 (org-show-context 'isearch))
15102
15103
15104 ;;;; Integration with and fixes for other packages
15105
15106 ;;; Imenu support
15107
15108 (defvar org-imenu-markers nil
15109 "All markers currently used by Imenu.")
15110 (make-variable-buffer-local 'org-imenu-markers)
15111
15112 (defun org-imenu-new-marker (&optional pos)
15113 "Return a new marker for use by Imenu, and remember the marker."
15114 (let ((m (make-marker)))
15115 (move-marker m (or pos (point)))
15116 (push m org-imenu-markers)
15117 m))
15118
15119 (defun org-imenu-get-tree ()
15120 "Produce the index for Imenu."
15121 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15122 (setq org-imenu-markers nil)
15123 (let* ((n org-imenu-depth)
15124 (re (concat "^" outline-regexp))
15125 (subs (make-vector (1+ n) nil))
15126 (last-level 0)
15127 m level head)
15128 (save-excursion
15129 (save-restriction
15130 (widen)
15131 (goto-char (point-max))
15132 (while (re-search-backward re nil t)
15133 (setq level (org-reduced-level (funcall outline-level)))
15134 (when (<= level n)
15135 (looking-at org-complex-heading-regexp)
15136 (setq head (org-link-display-format
15137 (org-match-string-no-properties 4))
15138 m (org-imenu-new-marker))
15139 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15140 (if (>= level last-level)
15141 (push (cons head m) (aref subs level))
15142 (push (cons head (aref subs (1+ level))) (aref subs level))
15143 (loop for i from (1+ level) to n do (aset subs i nil)))
15144 (setq last-level level)))))
15145 (aref subs 1)))
15146
15147 (eval-after-load "imenu"
15148 '(progn
15149 (add-hook 'imenu-after-jump-hook
15150 (lambda ()
15151 (if (eq major-mode 'org-mode)
15152 (org-show-context 'org-goto))))))
15153
15154 (defun org-link-display-format (link)
15155 "Replace a link with either the description, or the link target
15156 if no description is present"
15157 (save-match-data
15158 (if (string-match org-bracket-link-analytic-regexp link)
15159 (replace-match (or (match-string 5 link)
15160 (concat (match-string 1 link)
15161 (match-string 3 link)))
15162 nil nil link)
15163 link)))
15164
15165 ;; Speedbar support
15166
15167 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15168 "Overlay marking the agenda restriction line in speedbar.")
15169 (org-overlay-put org-speedbar-restriction-lock-overlay
15170 'face 'org-agenda-restriction-lock)
15171 (org-overlay-put org-speedbar-restriction-lock-overlay
15172 'help-echo "Agendas are currently limited to this item.")
15173 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15174
15175 (defun org-speedbar-set-agenda-restriction ()
15176 "Restrict future agenda commands to the location at point in speedbar.
15177 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15178 (interactive)
15179 (require 'org-agenda)
15180 (let (p m tp np dir txt)
15181 (cond
15182 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15183 'org-imenu t))
15184 (setq m (get-text-property p 'org-imenu-marker))
15185 (save-excursion
15186 (save-restriction
15187 (set-buffer (marker-buffer m))
15188 (goto-char m)
15189 (org-agenda-set-restriction-lock 'subtree))))
15190 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15191 'speedbar-function 'speedbar-find-file))
15192 (setq tp (previous-single-property-change
15193 (1+ p) 'speedbar-function)
15194 np (next-single-property-change
15195 tp 'speedbar-function)
15196 dir (speedbar-line-directory)
15197 txt (buffer-substring-no-properties (or tp (point-min))
15198 (or np (point-max))))
15199 (save-excursion
15200 (save-restriction
15201 (set-buffer (find-file-noselect
15202 (let ((default-directory dir))
15203 (expand-file-name txt))))
15204 (unless (org-mode-p)
15205 (error "Cannot restrict to non-Org-mode file"))
15206 (org-agenda-set-restriction-lock 'file))))
15207 (t (error "Don't know how to restrict Org-mode's agenda")))
15208 (org-move-overlay org-speedbar-restriction-lock-overlay
15209 (point-at-bol) (point-at-eol))
15210 (setq current-prefix-arg nil)
15211 (org-agenda-maybe-redo)))
15212
15213 (eval-after-load "speedbar"
15214 '(progn
15215 (speedbar-add-supported-extension ".org")
15216 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15217 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15218 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15219 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15220 (add-hook 'speedbar-visiting-tag-hook
15221 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15222
15223
15224 ;;; Fixes and Hacks for problems with other packages
15225
15226 ;; Make flyspell not check words in links, to not mess up our keymap
15227 (defun org-mode-flyspell-verify ()
15228 "Don't let flyspell put overlays at active buttons."
15229 (not (get-text-property (point) 'keymap)))
15230
15231 ;; Make `bookmark-jump' show the jump location if it was hidden.
15232 (eval-after-load "bookmark"
15233 '(if (boundp 'bookmark-after-jump-hook)
15234 ;; We can use the hook
15235 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15236 ;; Hook not available, use advice
15237 (defadvice bookmark-jump (after org-make-visible activate)
15238 "Make the position visible."
15239 (org-bookmark-jump-unhide))))
15240
15241 ;; Make sure saveplace show the location if it was hidden
15242 (eval-after-load "saveplace"
15243 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15244 "Make the position visible."
15245 (org-bookmark-jump-unhide)))
15246
15247 (defun org-bookmark-jump-unhide ()
15248 "Unhide the current position, to show the bookmark location."
15249 (and (org-mode-p)
15250 (or (org-invisible-p)
15251 (save-excursion (goto-char (max (point-min) (1- (point))))
15252 (org-invisible-p)))
15253 (org-show-context 'bookmark-jump)))
15254
15255 ;; Make session.el ignore our circular variable
15256 (eval-after-load "session"
15257 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15258
15259 ;;;; Experimental code
15260
15261 (defun org-closed-in-range ()
15262 "Sparse tree of items closed in a certain time range.
15263 Still experimental, may disappear in the future."
15264 (interactive)
15265 ;; Get the time interval from the user.
15266 (let* ((time1 (time-to-seconds
15267 (org-read-date nil 'to-time nil "Starting date: ")))
15268 (time2 (time-to-seconds
15269 (org-read-date nil 'to-time nil "End date:")))
15270 ;; callback function
15271 (callback (lambda ()
15272 (let ((time
15273 (time-to-seconds
15274 (apply 'encode-time
15275 (org-parse-time-string
15276 (match-string 1))))))
15277 ;; check if time in interval
15278 (and (>= time time1) (<= time time2))))))
15279 ;; make tree, check each match with the callback
15280 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15281
15282
15283 ;;;; Finish up
15284
15285 (provide 'org)
15286
15287 (run-hooks 'org-load-hook)
15288
15289 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15290
15291 ;;; org.el ends here