2009-10-01 Carsten Dominik <carsten.dominik@gmail.com>
[bpt/emacs.git] / 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.31a
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-src)
92 (require 'org-footnote)
93
94 ;;;; Customization variables
95
96 ;;; Version
97
98 (defconst org-version "6.31a"
99 "The version number of the file org.el.")
100
101 (defun org-version (&optional here)
102 "Show the org-mode version in the echo area.
103 With prefix arg HERE, insert it at point."
104 (interactive "P")
105 (let* ((version org-version)
106 (git-version)
107 (dir (concat (file-name-directory (locate-library "org")) "../" )))
108 (if (and (file-exists-p (expand-file-name ".git" dir))
109 (executable-find "git"))
110 (let ((pwd (substring (pwd) 10)))
111 (cd dir)
112 (if (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
113 (save-excursion
114 (set-buffer "*Shell Command Output*")
115 (goto-char (point-min))
116 (re-search-forward "[^\n]+")
117 (setq git-version (match-string 0))
118 (subst-char-in-string ?- ?. git-version t)
119 (shell-command "git diff-index --name-only HEAD --")
120 (unless (eql 1 (point-max))
121 (setq git-version (concat git-version ".dirty")))
122 (setq version (concat version " (" git-version ")")))
123 (cd pwd))))
124 (setq version (format "Org-mode version %s" version))
125 (if here (insert version))
126 (message version)
127 version))
128
129 ;;; Compatibility constants
130
131 ;;; The custom variables
132
133 (defgroup org nil
134 "Outline-based notes management and organizer."
135 :tag "Org"
136 :group 'outlines
137 :group 'hypermedia
138 :group 'calendar)
139
140 (defcustom org-load-hook nil
141 "Hook that is run after org.el has been loaded."
142 :group 'org
143 :type 'hook)
144
145 (defvar org-modules) ; defined below
146 (defvar org-modules-loaded nil
147 "Have the modules been loaded already?")
148
149 (defun org-load-modules-maybe (&optional force)
150 "Load all extensions listed in `org-modules'."
151 (when (or force (not org-modules-loaded))
152 (mapc (lambda (ext)
153 (condition-case nil (require ext)
154 (error (message "Problems while trying to load feature `%s'" ext))))
155 org-modules)
156 (setq org-modules-loaded t)))
157
158 (defun org-set-modules (var value)
159 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
160 (set var value)
161 (when (featurep 'org)
162 (org-load-modules-maybe 'force)))
163
164 (when (org-bound-and-true-p org-modules)
165 (let ((a (member 'org-infojs org-modules)))
166 (and a (setcar a 'org-jsinfo))))
167
168 (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)
169 "Modules that should always be loaded together with org.el.
170 If a description starts with <C>, the file is not part of Emacs
171 and loading it will require that you have downloaded and properly installed
172 the org-mode distribution.
173
174 You can also use this system to load external packages (i.e. neither Org
175 core modules, nor modules from the CONTRIB directory). Just add symbols
176 to the end of the list. If the package is called org-xyz.el, then you need
177 to add the symbol `xyz', and the package must have a call to
178
179 (provide 'org-xyz)"
180 :group 'org
181 :set 'org-set-modules
182 :type
183 '(set :greedy t
184 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
185 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
186 (const :tag " crypt: Encryption of subtrees" org-crypt)
187 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
188 (const :tag " id: Global IDs for identifying entries" org-id)
189 (const :tag " info: Links to Info nodes" org-info)
190 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
191 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
192 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
193 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
194 (const :tag " mew Links to Mew folders/messages" org-mew)
195 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
196 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
197 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
198 (const :tag " vm: Links to VM folders/messages" org-vm)
199 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
200 (const :tag " w3m: Special cut/paste from w3m to Org." org-w3m)
201 (const :tag " mouse: Additional mouse support" org-mouse)
202
203 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
204 (const :tag "C annotation-helper: Call Remember directly from Browser\n\t\t\t(OBSOLETE, use org-protocol)" org-annotation-helper)
205 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
206 (const :tag "C browser-url: Store link, directly from Browser\n\t\t\t(OBSOLETE, use org-protocol)" org-browser-url)
207 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
208 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
209 (const :tag "C collector: Collect properties into tables" org-collector)
210 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
211 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
212 (const :tag "C eval: Include command output as text" org-eval)
213 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
214 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
215 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
216 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
217
218 (const :tag "C invoice Help manage client invoices in OrgMode" org-invoice)
219
220 (const :tag "C jira Add a jira:ticket protocol to Org" org-jira)
221 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
222 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
223 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
224 (const :tag "C mtags: Support for muse-like tags" org-mtags)
225 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
226 (const :tag "C R: Computation using the R language" org-R)
227 (const :tag "C registry: A registry for Org links" org-registry)
228 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
229 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
230 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
231 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
232 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
233 (const :tag "C track: Keep up with Org development" org-track)
234 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
235
236 (defcustom org-support-shift-select nil
237 "Non-nil means, make shift-cursor commands select text when possible.
238
239 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
240 selecting a region, or enlarge thusly regions started in this way.
241 In Org-mode, in special contexts, these same keys are used for other
242 purposes, important enough to compete with shift selection. Org tries
243 to balance these needs by supporting `shift-select-mode' outside these
244 special contexts, under control of this variable.
245
246 The default of this variable is nil, to avoid confusing behavior. Shifted
247 cursor keys will then execute Org commands in the following contexts:
248 - on a headline, changing TODO state (left/right) and priority (up/down)
249 - on a time stamp, changing the time
250 - in a plain list item, changing the bullet type
251 - in a property definition line, switching between allowed values
252 - in the BEGIN line of a clock table (changing the time block).
253 Outside these contexts, the commands will throw an error.
254
255 When this variable is t and the cursor is not in a special context,
256 Org-mode will support shift-selection for making and enlarging regions.
257 To make this more effective, the bullet cycling will no longer happen
258 anywhere in an item line, but only if the cursor is exactly on the bullet.
259
260 If you set this variable to the symbol `always', then the keys
261 will not be special in headlines, property lines, and item lines, to make
262 shift selection work there as well. If this is what you want, you can
263 use the following alternative commands: `C-c C-t' and `C-c ,' to
264 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
265 TODO sets, `C-c -' to cycle item bullet types, and properties can be
266 edited by hand or in column view.
267
268 However, when the cursor is on a timestamp, shift-cursor commands
269 will still edit the time stamp - this is just too good to give up.
270
271 XEmacs user should have this variable set to nil, because shift-select-mode
272 is Emacs 23 only."
273 :group 'org
274 :type '(choice
275 (const :tag "Never" nil)
276 (const :tag "When outside special context" t)
277 (const :tag "Everywhere except timestamps" always)))
278
279 (defgroup org-startup nil
280 "Options concerning startup of Org-mode."
281 :tag "Org Startup"
282 :group 'org)
283
284 (defcustom org-startup-folded t
285 "Non-nil means, entering Org-mode will switch to OVERVIEW.
286 This can also be configured on a per-file basis by adding one of
287 the following lines anywhere in the buffer:
288
289 #+STARTUP: fold (or `overview', this is equivalent)
290 #+STARTUP: nofold (or `showall', this is equivalent)
291 #+STARTUP: content
292 #+STARTUP: showeverything"
293 :group 'org-startup
294 :type '(choice
295 (const :tag "nofold: show all" nil)
296 (const :tag "fold: overview" t)
297 (const :tag "content: all headlines" content)
298 (const :tag "show everything, even drawers" showeverything)))
299
300 (defcustom org-startup-truncated t
301 "Non-nil means, entering Org-mode will set `truncate-lines'.
302 This is useful since some lines containing links can be very long and
303 uninteresting. Also tables look terrible when wrapped."
304 :group 'org-startup
305 :type 'boolean)
306
307 (defcustom org-startup-indented nil
308 "Non-nil means, turn on `org-indent-mode' on startup.
309 This can also be configured on a per-file basis by adding one of
310 the following lines anywhere in the buffer:
311
312 #+STARTUP: indent
313 #+STARTUP: noindent"
314 :group 'org-structure
315 :type '(choice
316 (const :tag "Not" nil)
317 (const :tag "Globally (slow on startup in large files)" t)))
318
319 (defcustom org-startup-align-all-tables nil
320 "Non-nil means, align all tables when visiting a file.
321 This is useful when the column width in tables is forced with <N> cookies
322 in table fields. Such tables will look correct only after the first re-align.
323 This can also be configured on a per-file basis by adding one of
324 the following lines anywhere in the buffer:
325 #+STARTUP: align
326 #+STARTUP: noalign"
327 :group 'org-startup
328 :type 'boolean)
329
330 (defcustom org-insert-mode-line-in-empty-file nil
331 "Non-nil means insert the first line setting Org-mode in empty files.
332 When the function `org-mode' is called interactively in an empty file, this
333 normally means that the file name does not automatically trigger Org-mode.
334 To ensure that the file will always be in Org-mode in the future, a
335 line enforcing Org-mode will be inserted into the buffer, if this option
336 has been set."
337 :group 'org-startup
338 :type 'boolean)
339
340 (defcustom org-replace-disputed-keys nil
341 "Non-nil means use alternative key bindings for some keys.
342 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
343 These keys are also used by other packages like shift-selection-mode'
344 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
345 If you want to use Org-mode together with one of these other modes,
346 or more generally if you would like to move some Org-mode commands to
347 other keys, set this variable and configure the keys with the variable
348 `org-disputed-keys'.
349
350 This option is only relevant at load-time of Org-mode, and must be set
351 *before* org.el is loaded. Changing it requires a restart of Emacs to
352 become effective."
353 :group 'org-startup
354 :type 'boolean)
355
356 (defcustom org-use-extra-keys nil
357 "Non-nil means use extra key sequence definitions for certain
358 commands. This happens automatically if you run XEmacs or if
359 window-system is nil. This variable lets you do the same
360 manually. You must set it before loading org.
361
362 Example: on Carbon Emacs 22 running graphically, with an external
363 keyboard on a Powerbook, the default way of setting M-left might
364 not work for either Alt or ESC. Setting this variable will make
365 it work for ESC."
366 :group 'org-startup
367 :type 'boolean)
368
369 (if (fboundp 'defvaralias)
370 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
371
372 (defcustom org-disputed-keys
373 '(([(shift up)] . [(meta p)])
374 ([(shift down)] . [(meta n)])
375 ([(shift left)] . [(meta -)])
376 ([(shift right)] . [(meta +)])
377 ([(control shift right)] . [(meta shift +)])
378 ([(control shift left)] . [(meta shift -)]))
379 "Keys for which Org-mode and other modes compete.
380 This is an alist, cars are the default keys, second element specifies
381 the alternative to use when `org-replace-disputed-keys' is t.
382
383 Keys can be specified in any syntax supported by `define-key'.
384 The value of this option takes effect only at Org-mode's startup,
385 therefore you'll have to restart Emacs to apply it after changing."
386 :group 'org-startup
387 :type 'alist)
388
389 (defun org-key (key)
390 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
391 Or return the original if not disputed."
392 (if org-replace-disputed-keys
393 (let* ((nkey (key-description key))
394 (x (org-find-if (lambda (x)
395 (equal (key-description (car x)) nkey))
396 org-disputed-keys)))
397 (if x (cdr x) key))
398 key))
399
400 (defun org-find-if (predicate seq)
401 (catch 'exit
402 (while seq
403 (if (funcall predicate (car seq))
404 (throw 'exit (car seq))
405 (pop seq)))))
406
407 (defun org-defkey (keymap key def)
408 "Define a key, possibly translated, as returned by `org-key'."
409 (define-key keymap (org-key key) def))
410
411 (defcustom org-ellipsis nil
412 "The ellipsis to use in the Org-mode outline.
413 When nil, just use the standard three dots. When a string, use that instead,
414 When a face, use the standard 3 dots, but with the specified face.
415 The change affects only Org-mode (which will then use its own display table).
416 Changing this requires executing `M-x org-mode' in a buffer to become
417 effective."
418 :group 'org-startup
419 :type '(choice (const :tag "Default" nil)
420 (face :tag "Face" :value org-warning)
421 (string :tag "String" :value "...#")))
422
423 (defvar org-display-table nil
424 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
425
426 (defgroup org-keywords nil
427 "Keywords in Org-mode."
428 :tag "Org Keywords"
429 :group 'org)
430
431 (defcustom org-deadline-string "DEADLINE:"
432 "String to mark deadline entries.
433 A deadline is this string, followed by a time stamp. Should be a word,
434 terminated by a colon. You can insert a schedule keyword and
435 a timestamp with \\[org-deadline].
436 Changes become only effective after restarting Emacs."
437 :group 'org-keywords
438 :type 'string)
439
440 (defcustom org-scheduled-string "SCHEDULED:"
441 "String to mark scheduled TODO entries.
442 A schedule is this string, followed by a time stamp. Should be a word,
443 terminated by a colon. You can insert a schedule keyword and
444 a timestamp with \\[org-schedule].
445 Changes become only effective after restarting Emacs."
446 :group 'org-keywords
447 :type 'string)
448
449 (defcustom org-closed-string "CLOSED:"
450 "String used as the prefix for timestamps logging closing a TODO entry."
451 :group 'org-keywords
452 :type 'string)
453
454 (defcustom org-clock-string "CLOCK:"
455 "String used as prefix for timestamps clocking work hours on an item."
456 :group 'org-keywords
457 :type 'string)
458
459 (defcustom org-comment-string "COMMENT"
460 "Entries starting with this keyword will never be exported.
461 An entry can be toggled between COMMENT and normal with
462 \\[org-toggle-comment].
463 Changes become only effective after restarting Emacs."
464 :group 'org-keywords
465 :type 'string)
466
467 (defcustom org-quote-string "QUOTE"
468 "Entries starting with this keyword will be exported in fixed-width font.
469 Quoting applies only to the text in the entry following the headline, and does
470 not extend beyond the next headline, even if that is lower level.
471 An entry can be toggled between QUOTE and normal with
472 \\[org-toggle-fixed-width-section]."
473 :group 'org-keywords
474 :type 'string)
475
476 (defconst org-repeat-re
477 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
478 "Regular expression for specifying repeated events.
479 After a match, group 1 contains the repeat expression.")
480
481 (defgroup org-structure nil
482 "Options concerning the general structure of Org-mode files."
483 :tag "Org Structure"
484 :group 'org)
485
486 (defgroup org-reveal-location nil
487 "Options about how to make context of a location visible."
488 :tag "Org Reveal Location"
489 :group 'org-structure)
490
491 (defconst org-context-choice
492 '(choice
493 (const :tag "Always" t)
494 (const :tag "Never" nil)
495 (repeat :greedy t :tag "Individual contexts"
496 (cons
497 (choice :tag "Context"
498 (const agenda)
499 (const org-goto)
500 (const occur-tree)
501 (const tags-tree)
502 (const link-search)
503 (const mark-goto)
504 (const bookmark-jump)
505 (const isearch)
506 (const default))
507 (boolean))))
508 "Contexts for the reveal options.")
509
510 (defcustom org-show-hierarchy-above '((default . t))
511 "Non-nil means, show full hierarchy 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 hierarchy of headings
514 above the exposed location is shown.
515 Turning this off for example for sparse trees makes them very compact.
516 Instead of t, this can also be an alist specifying this option for different
517 contexts. Valid contexts are
518 agenda when exposing an entry from the agenda
519 org-goto when using the command `org-goto' on key C-c C-j
520 occur-tree when using the command `org-occur' on key C-c /
521 tags-tree when constructing a sparse tree based on tags matches
522 link-search when exposing search matches associated with a link
523 mark-goto when exposing the jump goal of a mark
524 bookmark-jump when exposing a bookmark location
525 isearch when exiting from an incremental search
526 default default for all contexts not set explicitly"
527 :group 'org-reveal-location
528 :type org-context-choice)
529
530 (defcustom org-show-following-heading '((default . nil))
531 "Non-nil means, show following heading when revealing a location.
532 Org-mode often shows locations in an org-mode file which might have
533 been invisible before. When this is set, the heading following the
534 match is shown.
535 Turning this off for example for sparse trees makes them very compact,
536 but makes it harder to edit the location of the match. In such a case,
537 use the command \\[org-reveal] to show more context.
538 Instead of t, this can also be an alist specifying this option for different
539 contexts. See `org-show-hierarchy-above' for valid contexts."
540 :group 'org-reveal-location
541 :type org-context-choice)
542
543 (defcustom org-show-siblings '((default . nil) (isearch t))
544 "Non-nil means, show all sibling heading when revealing a location.
545 Org-mode often shows locations in an org-mode file which might have
546 been invisible before. When this is set, the sibling of the current entry
547 heading are all made visible. If `org-show-hierarchy-above' is t,
548 the same happens on each level of the hierarchy above the current entry.
549
550 By default this is on for the isearch context, off for all other contexts.
551 Turning this off for example for sparse trees makes them very compact,
552 but makes it harder to edit the location of the match. In such a case,
553 use the command \\[org-reveal] to show more context.
554 Instead of t, this can also be an alist specifying this option for different
555 contexts. See `org-show-hierarchy-above' for valid contexts."
556 :group 'org-reveal-location
557 :type org-context-choice)
558
559 (defcustom org-show-entry-below '((default . nil))
560 "Non-nil means, show the entry below a headline when revealing a location.
561 Org-mode often shows locations in an org-mode file which might have
562 been invisible before. When this is set, the text below the headline that is
563 exposed is also shown.
564
565 By default this is off for all contexts.
566 Instead of t, this can also be an alist specifying this option for different
567 contexts. See `org-show-hierarchy-above' for valid contexts."
568 :group 'org-reveal-location
569 :type org-context-choice)
570
571 (defcustom org-indirect-buffer-display 'other-window
572 "How should indirect tree buffers be displayed?
573 This applies to indirect buffers created with the commands
574 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
575 Valid values are:
576 current-window Display in the current window
577 other-window Just display in another window.
578 dedicated-frame Create one new frame, and re-use it each time.
579 new-frame Make a new frame each time. Note that in this case
580 previously-made indirect buffers are kept, and you need to
581 kill these buffers yourself."
582 :group 'org-structure
583 :group 'org-agenda-windows
584 :type '(choice
585 (const :tag "In current window" current-window)
586 (const :tag "In current frame, other window" other-window)
587 (const :tag "Each time a new frame" new-frame)
588 (const :tag "One dedicated frame" dedicated-frame)))
589
590 (defgroup org-cycle nil
591 "Options concerning visibility cycling in Org-mode."
592 :tag "Org Cycle"
593 :group 'org-structure)
594
595 (defcustom org-cycle-skip-children-state-if-no-children t
596 "Non-nil means, skip CHILDREN state in entries that don't have any."
597 :group 'org-cycle
598 :type 'boolean)
599
600 (defcustom org-cycle-max-level nil
601 "Maximum level which should still be subject to visibility cycling.
602 Levels higher than this will, for cycling, be treated as text, not a headline.
603 When `org-odd-levels-only' is set, a value of N in this variable actually
604 means 2N-1 stars as the limiting headline.
605 When nil, cycle all levels.
606 Note that the limiting level of cycling is also influenced by
607 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
608 `org-inlinetask-min-level' is, cycling will be limited to levels one less
609 than its value."
610 :group 'org-cycle
611 :type '(choice
612 (const :tag "No limit" nil)
613 (integer :tag "Maximum level")))
614
615 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
616 "Names of drawers. Drawers are not opened by cycling on the headline above.
617 Drawers only open with a TAB on the drawer line itself. A drawer looks like
618 this:
619 :DRAWERNAME:
620 .....
621 :END:
622 The drawer \"PROPERTIES\" is special for capturing properties through
623 the property API.
624
625 Drawers can be defined on the per-file basis with a line like:
626
627 #+DRAWERS: HIDDEN STATE PROPERTIES"
628 :group 'org-structure
629 :group 'org-cycle
630 :type '(repeat (string :tag "Drawer Name")))
631
632 (defcustom org-hide-block-startup nil
633 "Non-nil means, , entering Org-mode will fold all blocks.
634 This can also be set in on a per-file basis with
635
636 #+STARTUP: hideblocks
637 #+STARTUP: showblocks"
638 :group 'org-startup
639 :group 'org-cycle
640 :type 'boolean)
641
642 (defcustom org-cycle-global-at-bob nil
643 "Cycle globally if cursor is at beginning of buffer and not at a headline.
644 This makes it possible to do global cycling without having to use S-TAB or
645 C-u TAB. For this special case to work, the first line of the buffer
646 must not be a headline - it may be empty or some other text. When used in
647 this way, `org-cycle-hook' is disables temporarily, to make sure the
648 cursor stays at the beginning of the buffer.
649 When this option is nil, don't do anything special at the beginning
650 of the buffer."
651 :group 'org-cycle
652 :type 'boolean)
653
654 (defcustom org-cycle-emulate-tab t
655 "Where should `org-cycle' emulate TAB.
656 nil Never
657 white Only in completely white lines
658 whitestart Only at the beginning of lines, before the first non-white char
659 t Everywhere except in headlines
660 exc-hl-bol Everywhere except at the start of a headline
661 If TAB is used in a place where it does not emulate TAB, the current subtree
662 visibility is cycled."
663 :group 'org-cycle
664 :type '(choice (const :tag "Never" nil)
665 (const :tag "Only in completely white lines" white)
666 (const :tag "Before first char in a line" whitestart)
667 (const :tag "Everywhere except in headlines" t)
668 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
669 ))
670
671 (defcustom org-cycle-separator-lines 2
672 "Number of empty lines needed to keep an empty line between collapsed trees.
673 If you leave an empty line between the end of a subtree and the following
674 headline, this empty line is hidden when the subtree is folded.
675 Org-mode will leave (exactly) one empty line visible if the number of
676 empty lines is equal or larger to the number given in this variable.
677 So the default 2 means, at least 2 empty lines after the end of a subtree
678 are needed to produce free space between a collapsed subtree and the
679 following headline.
680
681 If the number is negative, and the number of empty lines is at least -N,
682 all empty lines are shown.
683
684 Special case: when 0, never leave empty lines in collapsed view."
685 :group 'org-cycle
686 :type 'integer)
687 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
688
689 (defcustom org-pre-cycle-hook nil
690 "Hook that is run before visibility cycling is happening.
691 The function(s) in this hook must accept a single argument which indicates
692 the new state that will be set right after running this hook. The
693 argument is a symbol. Before a global state change, it can have the values
694 `overview', `content', or `all'. Before a local state change, it can have
695 the values `folded', `children', or `subtree'."
696 :group 'org-cycle
697 :type 'hook)
698
699 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
700 org-cycle-hide-drawers
701 org-cycle-show-empty-lines
702 org-optimize-window-after-visibility-change)
703 "Hook that is run after `org-cycle' has changed the buffer visibility.
704 The function(s) in this hook must accept a single argument which indicates
705 the new state that was set by the most recent `org-cycle' command. The
706 argument is a symbol. After a global state change, it can have the values
707 `overview', `content', or `all'. After a local state change, it can have
708 the values `folded', `children', or `subtree'."
709 :group 'org-cycle
710 :type 'hook)
711
712 (defgroup org-edit-structure nil
713 "Options concerning structure editing in Org-mode."
714 :tag "Org Edit Structure"
715 :group 'org-structure)
716
717 (defcustom org-odd-levels-only nil
718 "Non-nil means, skip even levels and only use odd levels for the outline.
719 This has the effect that two stars are being added/taken away in
720 promotion/demotion commands. It also influences how levels are
721 handled by the exporters.
722 Changing it requires restart of `font-lock-mode' to become effective
723 for fontification also in regions already fontified.
724 You may also set this on a per-file basis by adding one of the following
725 lines to the buffer:
726
727 #+STARTUP: odd
728 #+STARTUP: oddeven"
729 :group 'org-edit-structure
730 :group 'org-font-lock
731 :type 'boolean)
732
733 (defcustom org-adapt-indentation t
734 "Non-nil means, adapt indentation to outline node level.
735
736 When this variable is set, Org assumes that you write outlines by
737 indenting text in each node to align with the headline (after the stars).
738 The following issues are influenced by this variable:
739
740 - When this is set and the *entire* text in an entry is indented, the
741 indentation is increased by one space in a demotion command, and
742 decreased by one in a promotion command. If any line in the entry
743 body starts with text at column 0, indentation is not changed at all.
744
745 - Property drawers and planning information is inserted indented when
746 this variable s set. When nil, they will not be indented.
747
748 - TAB indents a line relative to context. The lines below a headline
749 will be indented when this variable is set.
750
751 Note that this is all about true indentation, by adding and removing
752 space characters. See also `org-indent.el' which does level-dependent
753 indentation in a virtual way, i.e. at display time in Emacs."
754 :group 'org-edit-structure
755 :type 'boolean)
756
757 (defcustom org-special-ctrl-a/e nil
758 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
759
760 When t, `C-a' will bring back the cursor to the beginning of the
761 headline text, i.e. after the stars and after a possible TODO keyword.
762 In an item, this will be the position after the bullet.
763 When the cursor is already at that position, another `C-a' will bring
764 it to the beginning of the line.
765
766 `C-e' will jump to the end of the headline, ignoring the presence of tags
767 in the headline. A second `C-e' will then jump to the true end of the
768 line, after any tags. This also means that, when this variable is
769 non-nil, `C-e' also will never jump beyond the end of the heading of a
770 folded section, i.e. not after the ellipses.
771
772 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
773 going to the true line boundary first. Only a directly following, identical
774 keypress will bring the cursor to the special positions.
775
776 This may also be a cons cell where the behavior for `C-a' and `C-e' is
777 set separately."
778 :group 'org-edit-structure
779 :type '(choice
780 (const :tag "off" nil)
781 (const :tag "on: after stars/bullet and before tags first" t)
782 (const :tag "reversed: true line boundary first" reversed)
783 (cons :tag "Set C-a and C-e separately"
784 (choice :tag "Special C-a"
785 (const :tag "off" nil)
786 (const :tag "on: after stars/bullet first" t)
787 (const :tag "reversed: before stars/bullet first" reversed))
788 (choice :tag "Special C-e"
789 (const :tag "off" nil)
790 (const :tag "on: before tags first" t)
791 (const :tag "reversed: after tags first" reversed)))))
792 (if (fboundp 'defvaralias)
793 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
794
795 (defcustom org-special-ctrl-k nil
796 "Non-nil means `C-k' will behave specially in headlines.
797 When nil, `C-k' will call the default `kill-line' command.
798 When t, the following will happen while the cursor is in the headline:
799
800 - When the cursor is at the beginning of a headline, kill the entire
801 line and possible the folded subtree below the line.
802 - When in the middle of the headline text, kill the headline up to the tags.
803 - When after the headline text, kill the tags."
804 :group 'org-edit-structure
805 :type 'boolean)
806
807 (defcustom org-yank-folded-subtrees t
808 "Non-nil means, when yanking subtrees, fold them.
809 If the kill is a single subtree, or a sequence of subtrees, i.e. if
810 it starts with a heading and all other headings in it are either children
811 or siblings, then fold all the subtrees. However, do this only if no
812 text after the yank would be swallowed into a folded tree by this action."
813 :group 'org-edit-structure
814 :type 'boolean)
815
816 (defcustom org-yank-adjusted-subtrees nil
817 "Non-nil means, when yanking subtrees, adjust the level.
818 With this setting, `org-paste-subtree' is used to insert the subtree, see
819 this function for details."
820 :group 'org-edit-structure
821 :type 'boolean)
822
823 (defcustom org-M-RET-may-split-line '((default . t))
824 "Non-nil means, M-RET will split the line at the cursor position.
825 When nil, it will go to the end of the line before making a
826 new line.
827 You may also set this option in a different way for different
828 contexts. Valid contexts are:
829
830 headline when creating a new headline
831 item when creating a new item
832 table in a table field
833 default the value to be used for all contexts not explicitly
834 customized"
835 :group 'org-structure
836 :group 'org-table
837 :type '(choice
838 (const :tag "Always" t)
839 (const :tag "Never" nil)
840 (repeat :greedy t :tag "Individual contexts"
841 (cons
842 (choice :tag "Context"
843 (const headline)
844 (const item)
845 (const table)
846 (const default))
847 (boolean)))))
848
849
850 (defcustom org-insert-heading-respect-content nil
851 "Non-nil means, insert new headings after the current subtree.
852 When nil, the new heading is created directly after the current line.
853 The commands \\[org-insert-heading-respect-content] and
854 \\[org-insert-todo-heading-respect-content] turn this variable on
855 for the duration of the command."
856 :group 'org-structure
857 :type 'boolean)
858
859 (defcustom org-blank-before-new-entry '((heading . auto)
860 (plain-list-item . auto))
861 "Should `org-insert-heading' leave a blank line before new heading/item?
862 The value is an alist, with `heading' and `plain-list-item' as car,
863 and a boolean flag as cdr. For plain lists, if the variable
864 `org-empty-line-terminates-plain-lists' is set, the setting here
865 is ignored and no empty line is inserted, to keep the list in tact."
866 :group 'org-edit-structure
867 :type '(list
868 (cons (const heading)
869 (choice (const :tag "Never" nil)
870 (const :tag "Always" t)
871 (const :tag "Auto" auto)))
872 (cons (const plain-list-item)
873 (choice (const :tag "Never" nil)
874 (const :tag "Always" t)
875 (const :tag "Auto" auto)))))
876
877 (defcustom org-insert-heading-hook nil
878 "Hook being run after inserting a new heading."
879 :group 'org-edit-structure
880 :type 'hook)
881
882 (defcustom org-enable-fixed-width-editor t
883 "Non-nil means, lines starting with \":\" are treated as fixed-width.
884 This currently only means, they are never auto-wrapped.
885 When nil, such lines will be treated like ordinary lines.
886 See also the QUOTE keyword."
887 :group 'org-edit-structure
888 :type 'boolean)
889
890
891 (defcustom org-goto-auto-isearch t
892 "Non-nil means, typing characters in org-goto starts incremental search."
893 :group 'org-edit-structure
894 :type 'boolean)
895
896 (defgroup org-sparse-trees nil
897 "Options concerning sparse trees in Org-mode."
898 :tag "Org Sparse Trees"
899 :group 'org-structure)
900
901 (defcustom org-highlight-sparse-tree-matches t
902 "Non-nil means, highlight all matches that define a sparse tree.
903 The highlights will automatically disappear the next time the buffer is
904 changed by an edit command."
905 :group 'org-sparse-trees
906 :type 'boolean)
907
908 (defcustom org-remove-highlights-with-change t
909 "Non-nil means, any change to the buffer will remove temporary highlights.
910 Such highlights are created by `org-occur' and `org-clock-display'.
911 When nil, `C-c C-c needs to be used to get rid of the highlights.
912 The highlights created by `org-preview-latex-fragment' always need
913 `C-c C-c' to be removed."
914 :group 'org-sparse-trees
915 :group 'org-time
916 :type 'boolean)
917
918
919 (defcustom org-occur-hook '(org-first-headline-recenter)
920 "Hook that is run after `org-occur' has constructed a sparse tree.
921 This can be used to recenter the window to show as much of the structure
922 as possible."
923 :group 'org-sparse-trees
924 :type 'hook)
925
926 (defgroup org-imenu-and-speedbar nil
927 "Options concerning imenu and speedbar in Org-mode."
928 :tag "Org Imenu and Speedbar"
929 :group 'org-structure)
930
931 (defcustom org-imenu-depth 2
932 "The maximum level for Imenu access to Org-mode headlines.
933 This also applied for speedbar access."
934 :group 'org-imenu-and-speedbar
935 :type 'integer)
936
937 (defgroup org-table nil
938 "Options concerning tables in Org-mode."
939 :tag "Org Table"
940 :group 'org)
941
942 (defcustom org-enable-table-editor 'optimized
943 "Non-nil means, lines starting with \"|\" are handled by the table editor.
944 When nil, such lines will be treated like ordinary lines.
945
946 When equal to the symbol `optimized', the table editor will be optimized to
947 do the following:
948 - Automatic overwrite mode in front of whitespace in table fields.
949 This makes the structure of the table stay in tact as long as the edited
950 field does not exceed the column width.
951 - Minimize the number of realigns. Normally, the table is aligned each time
952 TAB or RET are pressed to move to another field. With optimization this
953 happens only if changes to a field might have changed the column width.
954 Optimization requires replacing the functions `self-insert-command',
955 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
956 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
957 very good at guessing when a re-align will be necessary, but you can always
958 force one with \\[org-ctrl-c-ctrl-c].
959
960 If you would like to use the optimized version in Org-mode, but the
961 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
962
963 This variable can be used to turn on and off the table editor during a session,
964 but in order to toggle optimization, a restart is required.
965
966 See also the variable `org-table-auto-blank-field'."
967 :group 'org-table
968 :type '(choice
969 (const :tag "off" nil)
970 (const :tag "on" t)
971 (const :tag "on, optimized" optimized)))
972
973 (defcustom org-self-insert-cluster-for-undo t
974 "Non-nil means cluster self-insert commands for undo when possible.
975 If this is set, then, like in the Emacs command loop, 20 consequtive
976 characters will be undone together.
977 This is configurable, because there is some impact on typing performance."
978 :group 'org-table
979 :type 'boolean)
980
981 (defcustom org-table-tab-recognizes-table.el t
982 "Non-nil means, TAB will automatically notice a table.el table.
983 When it sees such a table, it moves point into it and - if necessary -
984 calls `table-recognize-table'."
985 :group 'org-table-editing
986 :type 'boolean)
987
988 (defgroup org-link nil
989 "Options concerning links in Org-mode."
990 :tag "Org Link"
991 :group 'org)
992
993 (defvar org-link-abbrev-alist-local nil
994 "Buffer-local version of `org-link-abbrev-alist', which see.
995 The value of this is taken from the #+LINK lines.")
996 (make-variable-buffer-local 'org-link-abbrev-alist-local)
997
998 (defcustom org-link-abbrev-alist nil
999 "Alist of link abbreviations.
1000 The car of each element is a string, to be replaced at the start of a link.
1001 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1002 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1003
1004 [[linkkey:tag][description]]
1005
1006 The 'linkkey' must be a word word, starting with a letter, followed
1007 by letters, numbers, '-' or '_'.
1008
1009 If REPLACE is a string, the tag will simply be appended to create the link.
1010 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1011 the placeholder \"%h\" will cause a url-encoded version of the tag to
1012 be inserted at that point (see the function `url-hexify-string').
1013
1014 REPLACE may also be a function that will be called with the tag as the
1015 only argument to create the link, which should be returned as a string.
1016
1017 See the manual for examples."
1018 :group 'org-link
1019 :type '(repeat
1020 (cons
1021 (string :tag "Protocol")
1022 (choice
1023 (string :tag "Format")
1024 (function)))))
1025
1026 (defcustom org-descriptive-links t
1027 "Non-nil means, hide link part and only show description of bracket links.
1028 Bracket links are like [[link][description]]. This variable sets the initial
1029 state in new org-mode buffers. The setting can then be toggled on a
1030 per-buffer basis from the Org->Hyperlinks menu."
1031 :group 'org-link
1032 :type 'boolean)
1033
1034 (defcustom org-link-file-path-type 'adaptive
1035 "How the path name in file links should be stored.
1036 Valid values are:
1037
1038 relative Relative to the current directory, i.e. the directory of the file
1039 into which the link is being inserted.
1040 absolute Absolute path, if possible with ~ for home directory.
1041 noabbrev Absolute path, no abbreviation of home directory.
1042 adaptive Use relative path for files in the current directory and sub-
1043 directories of it. For other files, use an absolute path."
1044 :group 'org-link
1045 :type '(choice
1046 (const relative)
1047 (const absolute)
1048 (const noabbrev)
1049 (const adaptive)))
1050
1051 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1052 "Types of links that should be activated in Org-mode files.
1053 This is a list of symbols, each leading to the activation of a certain link
1054 type. In principle, it does not hurt to turn on most link types - there may
1055 be a small gain when turning off unused link types. The types are:
1056
1057 bracket The recommended [[link][description]] or [[link]] links with hiding.
1058 angular Links in angular brackets that may contain whitespace like
1059 <bbdb:Carsten Dominik>.
1060 plain Plain links in normal text, no whitespace, like http://google.com.
1061 radio Text that is matched by a radio target, see manual for details.
1062 tag Tag settings in a headline (link to tag search).
1063 date Time stamps (link to calendar).
1064 footnote Footnote labels.
1065
1066 Changing this variable requires a restart of Emacs to become effective."
1067 :group 'org-link
1068 :type '(set :greedy t
1069 (const :tag "Double bracket links (new style)" bracket)
1070 (const :tag "Angular bracket links (old style)" angular)
1071 (const :tag "Plain text links" plain)
1072 (const :tag "Radio target matches" radio)
1073 (const :tag "Tags" tag)
1074 (const :tag "Timestamps" date)
1075 (const :tag "Footnotes" footnote)))
1076
1077 (defcustom org-make-link-description-function nil
1078 "Function to use to generate link descriptions from links. If
1079 nil the link location will be used. This function must take two
1080 parameters; the first is the link and the second the description
1081 org-insert-link has generated, and should return the description
1082 to use."
1083 :group 'org-link
1084 :type 'function)
1085
1086 (defgroup org-link-store nil
1087 "Options concerning storing links in Org-mode."
1088 :tag "Org Store Link"
1089 :group 'org-link)
1090
1091 (defcustom org-email-link-description-format "Email %c: %.30s"
1092 "Format of the description part of a link to an email or usenet message.
1093 The following %-escapes will be replaced by corresponding information:
1094
1095 %F full \"From\" field
1096 %f name, taken from \"From\" field, address if no name
1097 %T full \"To\" field
1098 %t first name in \"To\" field, address if no name
1099 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1100 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1101 %s subject
1102 %m message-id.
1103
1104 You may use normal field width specification between the % and the letter.
1105 This is for example useful to limit the length of the subject.
1106
1107 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1108 :group 'org-link-store
1109 :type 'string)
1110
1111 (defcustom org-from-is-user-regexp
1112 (let (r1 r2)
1113 (when (and user-mail-address (not (string= user-mail-address "")))
1114 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1115 (when (and user-full-name (not (string= user-full-name "")))
1116 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1117 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1118 "Regexp matched against the \"From:\" header of an email or usenet message.
1119 It should match if the message is from the user him/herself."
1120 :group 'org-link-store
1121 :type 'regexp)
1122
1123 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1124 "Non-nil means, storing a link to an Org file will use entry IDs.
1125
1126 Note that before this variable is even considered, org-id must be loaded,
1127 so please customize `org-modules' and turn it on.
1128
1129 The variable can have the following values:
1130
1131 t Create an ID if needed to make a link to the current entry.
1132
1133 create-if-interactive
1134 If `org-store-link' is called directly (interactively, as a user
1135 command), do create an ID to support the link. But when doing the
1136 job for remember, only use the ID if it already exists. The
1137 purpose of this setting is to avoid proliferation of unwanted
1138 IDs, just because you happen to be in an Org file when you
1139 call `org-remember' that automatically and preemptively
1140 creates a link. If you do want to get an ID link in a remember
1141 template to an entry not having an ID, create it first by
1142 explicitly creating a link to it, using `C-c C-l' first.
1143
1144 create-if-interactive-and-no-custom-id
1145 Like create-if-interactive, but do not create an ID if there is
1146 a CUSTOM_ID property defined in the entry. This is the default.
1147
1148 use-existing
1149 Use existing ID, do not create one.
1150
1151 nil Never use an ID to make a link, instead link using a text search for
1152 the headline text."
1153 :group 'org-link-store
1154 :type '(choice
1155 (const :tag "Create ID to make link" t)
1156 (const :tag "Create if storing link interactively"
1157 create-if-interactive)
1158 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1159 create-if-interactive-and-no-custom-id)
1160 (const :tag "Only use existing" use-existing)
1161 (const :tag "Do not use ID to create link" nil)))
1162
1163 (defcustom org-context-in-file-links t
1164 "Non-nil means, file links from `org-store-link' contain context.
1165 A search string will be added to the file name with :: as separator and
1166 used to find the context when the link is activated by the command
1167 `org-open-at-point'.
1168 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1169 negates this setting for the duration of the command."
1170 :group 'org-link-store
1171 :type 'boolean)
1172
1173 (defcustom org-keep-stored-link-after-insertion nil
1174 "Non-nil means, keep link in list for entire session.
1175
1176 The command `org-store-link' adds a link pointing to the current
1177 location to an internal list. These links accumulate during a session.
1178 The command `org-insert-link' can be used to insert links into any
1179 Org-mode file (offering completion for all stored links). When this
1180 option is nil, every link which has been inserted once using \\[org-insert-link]
1181 will be removed from the list, to make completing the unused links
1182 more efficient."
1183 :group 'org-link-store
1184 :type 'boolean)
1185
1186 (defgroup org-link-follow nil
1187 "Options concerning following links in Org-mode."
1188 :tag "Org Follow Link"
1189 :group 'org-link)
1190
1191 (defcustom org-link-translation-function nil
1192 "Function to translate links with different syntax to Org syntax.
1193 This can be used to translate links created for example by the Planner
1194 or emacs-wiki packages to Org syntax.
1195 The function must accept two parameters, a TYPE containing the link
1196 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1197 which is everything after the link protocol. It should return a cons
1198 with possibly modified values of type and path.
1199 Org contains a function for this, so if you set this variable to
1200 `org-translate-link-from-planner', you should be able follow many
1201 links created by planner."
1202 :group 'org-link-follow
1203 :type 'function)
1204
1205 (defcustom org-follow-link-hook nil
1206 "Hook that is run after a link has been followed."
1207 :group 'org-link-follow
1208 :type 'hook)
1209
1210 (defcustom org-tab-follows-link nil
1211 "Non-nil means, on links TAB will follow the link.
1212 Needs to be set before org.el is loaded.
1213 This really should not be used, it does not make sense, and the
1214 implementation is bad."
1215 :group 'org-link-follow
1216 :type 'boolean)
1217
1218 (defcustom org-return-follows-link nil
1219 "Non-nil means, on links RET will follow the link.
1220 Needs to be set before org.el is loaded."
1221 :group 'org-link-follow
1222 :type 'boolean)
1223
1224 (defcustom org-mouse-1-follows-link
1225 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1226 "Non-nil means, mouse-1 on a link will follow the link.
1227 A longer mouse click will still set point. Does not work on XEmacs.
1228 Needs to be set before org.el is loaded."
1229 :group 'org-link-follow
1230 :type 'boolean)
1231
1232 (defcustom org-mark-ring-length 4
1233 "Number of different positions to be recorded in the ring
1234 Changing this requires a restart of Emacs to work correctly."
1235 :group 'org-link-follow
1236 :type 'integer)
1237
1238 (defcustom org-link-frame-setup
1239 '((vm . vm-visit-folder-other-frame)
1240 (gnus . gnus-other-frame)
1241 (file . find-file-other-window))
1242 "Setup the frame configuration for following links.
1243 When following a link with Emacs, it may often be useful to display
1244 this link in another window or frame. This variable can be used to
1245 set this up for the different types of links.
1246 For VM, use any of
1247 `vm-visit-folder'
1248 `vm-visit-folder-other-frame'
1249 For Gnus, use any of
1250 `gnus'
1251 `gnus-other-frame'
1252 `org-gnus-no-new-news'
1253 For FILE, use any of
1254 `find-file'
1255 `find-file-other-window'
1256 `find-file-other-frame'
1257 For the calendar, use the variable `calendar-setup'.
1258 For BBDB, it is currently only possible to display the matches in
1259 another window."
1260 :group 'org-link-follow
1261 :type '(list
1262 (cons (const vm)
1263 (choice
1264 (const vm-visit-folder)
1265 (const vm-visit-folder-other-window)
1266 (const vm-visit-folder-other-frame)))
1267 (cons (const gnus)
1268 (choice
1269 (const gnus)
1270 (const gnus-other-frame)
1271 (const org-gnus-no-new-news)))
1272 (cons (const file)
1273 (choice
1274 (const find-file)
1275 (const find-file-other-window)
1276 (const find-file-other-frame)))))
1277
1278 (defcustom org-display-internal-link-with-indirect-buffer nil
1279 "Non-nil means, use indirect buffer to display infile links.
1280 Activating internal links (from one location in a file to another location
1281 in the same file) normally just jumps to the location. When the link is
1282 activated with a C-u prefix (or with mouse-3), the link is displayed in
1283 another window. When this option is set, the other window actually displays
1284 an indirect buffer clone of the current buffer, to avoid any visibility
1285 changes to the current buffer."
1286 :group 'org-link-follow
1287 :type 'boolean)
1288
1289 (defcustom org-open-non-existing-files nil
1290 "Non-nil means, `org-open-file' will open non-existing files.
1291 When nil, an error will be generated.
1292 This variable applies only to external applications because they
1293 might choke on non-existing files. If the link is to a file that
1294 will be openend in Emacs, the variable is ignored."
1295 :group 'org-link-follow
1296 :type 'boolean)
1297
1298 (defcustom org-open-directory-means-index-dot-org nil
1299 "Non-nil means, a link to a directory really means to index.org.
1300 When nil, following a directory link will run dired or open a finder/explorer
1301 window on that directory."
1302 :group 'org-link-follow
1303 :type 'boolean)
1304
1305 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1306 "Function and arguments to call for following mailto links.
1307 This is a list with the first element being a lisp function, and the
1308 remaining elements being arguments to the function. In string arguments,
1309 %a will be replaced by the address, and %s will be replaced by the subject
1310 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1311 :group 'org-link-follow
1312 :type '(choice
1313 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1314 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1315 (const :tag "message-mail" (message-mail "%a" "%s"))
1316 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1317
1318 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1319 "Non-nil means, ask for confirmation before executing shell links.
1320 Shell links can be dangerous: just think about a link
1321
1322 [[shell:rm -rf ~/*][Google Search]]
1323
1324 This link would show up in your Org-mode document as \"Google Search\",
1325 but really it would remove your entire home directory.
1326 Therefore we advise against setting this variable to nil.
1327 Just change it to `y-or-n-p' if you want to confirm with a
1328 single keystroke rather than having to type \"yes\"."
1329 :group 'org-link-follow
1330 :type '(choice
1331 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1332 (const :tag "with y-or-n (faster)" y-or-n-p)
1333 (const :tag "no confirmation (dangerous)" nil)))
1334
1335 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1336 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1337 Elisp links can be dangerous: just think about a link
1338
1339 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1340
1341 This link would show up in your Org-mode document as \"Google Search\",
1342 but really it would remove your entire home directory.
1343 Therefore we advise against setting this variable to nil.
1344 Just change it to `y-or-n-p' if you want to confirm with a
1345 single keystroke rather than having to type \"yes\"."
1346 :group 'org-link-follow
1347 :type '(choice
1348 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1349 (const :tag "with y-or-n (faster)" y-or-n-p)
1350 (const :tag "no confirmation (dangerous)" nil)))
1351
1352 (defconst org-file-apps-defaults-gnu
1353 '((remote . emacs)
1354 (system . mailcap)
1355 (t . mailcap))
1356 "Default file applications on a UNIX or GNU/Linux system.
1357 See `org-file-apps'.")
1358
1359 (defconst org-file-apps-defaults-macosx
1360 '((remote . emacs)
1361 (t . "open %s")
1362 (system . "open %s")
1363 ("ps.gz" . "gv %s")
1364 ("eps.gz" . "gv %s")
1365 ("dvi" . "xdvi %s")
1366 ("fig" . "xfig %s"))
1367 "Default file applications on a MacOS X system.
1368 The system \"open\" is known as a default, but we use X11 applications
1369 for some files for which the OS does not have a good default.
1370 See `org-file-apps'.")
1371
1372 (defconst org-file-apps-defaults-windowsnt
1373 (list
1374 '(remote . emacs)
1375 (cons t
1376 (list (if (featurep 'xemacs)
1377 'mswindows-shell-execute
1378 'w32-shell-execute)
1379 "open" 'file))
1380 (cons 'system
1381 (list (if (featurep 'xemacs)
1382 'mswindows-shell-execute
1383 'w32-shell-execute)
1384 "open" 'file)))
1385 "Default file applications on a Windows NT system.
1386 The system \"open\" is used for most files.
1387 See `org-file-apps'.")
1388
1389 (defcustom org-file-apps
1390 '(
1391 (auto-mode . emacs)
1392 ("\\.x?html?\\'" . default)
1393 ("\\.pdf\\'" . default)
1394 )
1395 "External applications for opening `file:path' items in a document.
1396 Org-mode uses system defaults for different file types, but
1397 you can use this variable to set the application for a given file
1398 extension. The entries in this list are cons cells where the car identifies
1399 files and the cdr the corresponding command. Possible values for the
1400 file identifier are
1401 \"regex\" Regular expression matched against the file name. For backward
1402 compatibility, this can also be a string with only alphanumeric
1403 characters, which is then interpreted as an extension.
1404 `directory' Matches a directory
1405 `remote' Matches a remote file, accessible through tramp or efs.
1406 Remote files most likely should be visited through Emacs
1407 because external applications cannot handle such paths.
1408 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1409 so all files Emacs knows how to handle. Using this with
1410 command `emacs' will open most files in Emacs. Beware that this
1411 will also open html files inside Emacs, unless you add
1412 (\"html\" . default) to the list as well.
1413 t Default for files not matched by any of the other options.
1414 `system' The system command to open files, like `open' on Windows
1415 and Mac OS X, and mailcap under GNU/Linux. This is the command
1416 that will be selected if you call `C-c C-o' with a double
1417 `C-u C-u' prefix.
1418
1419 Possible values for the command are:
1420 `emacs' The file will be visited by the current Emacs process.
1421 `default' Use the default application for this file type, which is the
1422 association for t in the list, most likely in the system-specific
1423 part.
1424 This can be used to overrule an unwanted setting in the
1425 system-specific variable.
1426 `system' Use the system command for opening files, like \"open\".
1427 This command is specified by the entry whose car is `system'.
1428 Most likely, the system-specific version of this variable
1429 does define this command, but you can overrule/replace it
1430 here.
1431 string A command to be executed by a shell; %s will be replaced
1432 by the path to the file.
1433 sexp A Lisp form which will be evaluated. The file path will
1434 be available in the Lisp variable `file'.
1435 For more examples, see the system specific constants
1436 `org-file-apps-defaults-macosx'
1437 `org-file-apps-defaults-windowsnt'
1438 `org-file-apps-defaults-gnu'."
1439 :group 'org-link-follow
1440 :type '(repeat
1441 (cons (choice :value ""
1442 (string :tag "Extension")
1443 (const :tag "System command to open files" system)
1444 (const :tag "Default for unrecognized files" t)
1445 (const :tag "Remote file" remote)
1446 (const :tag "Links to a directory" directory)
1447 (const :tag "Any files that have Emacs modes"
1448 auto-mode))
1449 (choice :value ""
1450 (const :tag "Visit with Emacs" emacs)
1451 (const :tag "Use default" default)
1452 (const :tag "Use the system command" system)
1453 (string :tag "Command")
1454 (sexp :tag "Lisp form")))))
1455
1456 (defgroup org-refile nil
1457 "Options concerning refiling entries in Org-mode."
1458 :tag "Org Refile"
1459 :group 'org)
1460
1461 (defcustom org-directory "~/org"
1462 "Directory with org files.
1463 This is just a default location to look for Org files. There is no need
1464 at all to put your files into this directory. It is only used in the
1465 following situations:
1466
1467 1. When a remember template specifies a target file that is not an
1468 absolute path. The path will then be interpreted relative to
1469 `org-directory'
1470 2. When a remember note is filed away in an interactive way (when exiting the
1471 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1472 with `org-directory' as the default path."
1473 :group 'org-refile
1474 :group 'org-remember
1475 :type 'directory)
1476
1477 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1478 "Default target for storing notes.
1479 Used by the hooks for remember.el. This can be a string, or nil to mean
1480 the value of `remember-data-file'.
1481 You can set this on a per-template basis with the variable
1482 `org-remember-templates'."
1483 :group 'org-refile
1484 :group 'org-remember
1485 :type '(choice
1486 (const :tag "Default from remember-data-file" nil)
1487 file))
1488
1489 (defcustom org-goto-interface 'outline
1490 "The default interface to be used for `org-goto'.
1491 Allowed values are:
1492 outline The interface shows an outline of the relevant file
1493 and the correct heading is found by moving through
1494 the outline or by searching with incremental search.
1495 outline-path-completion Headlines in the current buffer are offered via
1496 completion. This is the interface also used by
1497 the refile command."
1498 :group 'org-refile
1499 :type '(choice
1500 (const :tag "Outline" outline)
1501 (const :tag "Outline-path-completion" outline-path-completion)))
1502
1503 (defcustom org-goto-max-level 5
1504 "Maximum level to be considered when running org-goto with refile interface."
1505 :group 'org-refile
1506 :type 'integer)
1507
1508 (defcustom org-reverse-note-order nil
1509 "Non-nil means, store new notes at the beginning of a file or entry.
1510 When nil, new notes will be filed to the end of a file or entry.
1511 This can also be a list with cons cells of regular expressions that
1512 are matched against file names, and values."
1513 :group 'org-remember
1514 :group 'org-refile
1515 :type '(choice
1516 (const :tag "Reverse always" t)
1517 (const :tag "Reverse never" nil)
1518 (repeat :tag "By file name regexp"
1519 (cons regexp boolean))))
1520
1521 (defcustom org-refile-targets nil
1522 "Targets for refiling entries with \\[org-refile].
1523 This is list of cons cells. Each cell contains:
1524 - a specification of the files to be considered, either a list of files,
1525 or a symbol whose function or variable value will be used to retrieve
1526 a file name or a list of file names. If you use `org-agenda-files' for
1527 that, all agenda files will be scanned for targets. Nil means, consider
1528 headings in the current buffer.
1529 - A specification of how to find candidate refile targets. This may be
1530 any of:
1531 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1532 This tag has to be present in all target headlines, inheritance will
1533 not be considered.
1534 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1535 todo keyword.
1536 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1537 headlines that are refiling targets.
1538 - a cons cell (:level . N). Any headline of level N is considered a target.
1539 Note that, when `org-odd-levels-only' is set, level corresponds to
1540 order in hierarchy, not to the number of stars.
1541 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1542 Note that, when `org-odd-levels-only' is set, level corresponds to
1543 order in hierarchy, not to the number of stars.
1544
1545 You can set the variable `org-refile-target-verify-function' to a function
1546 to verify each headline found by the simple critery above.
1547
1548 When this variable is nil, all top-level headlines in the current buffer
1549 are used, equivalent to the value `((nil . (:level . 1))'."
1550 :group 'org-refile
1551 :type '(repeat
1552 (cons
1553 (choice :value org-agenda-files
1554 (const :tag "All agenda files" org-agenda-files)
1555 (const :tag "Current buffer" nil)
1556 (function) (variable) (file))
1557 (choice :tag "Identify target headline by"
1558 (cons :tag "Specific tag" (const :value :tag) (string))
1559 (cons :tag "TODO keyword" (const :value :todo) (string))
1560 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1561 (cons :tag "Level number" (const :value :level) (integer))
1562 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1563
1564 (defcustom org-refile-target-verify-function nil
1565 "Function to verify if the headline at point should be a refile target.
1566 The function will be called without arguments, with point at the
1567 beginning of the headline. It should return t and leave point
1568 where it is if the headline is a valid target for refiling.
1569
1570 If the target should not be selected, the function must return nil.
1571 In addition to this, it may move point to a place from where the search
1572 should be continued. For example, the function may decide that the entire
1573 subtree of the current entry should be excluded and move point to the end
1574 of the subtree."
1575 :group 'org-refile
1576 :type 'function)
1577
1578 (defcustom org-refile-use-outline-path nil
1579 "Non-nil means, provide refile targets as paths.
1580 So a level 3 headline will be available as level1/level2/level3.
1581
1582 When the value is `file', also include the file name (without directory)
1583 into the path. In this case, you can also stop the completion after
1584 the file name, to get entries inserted as top level in the file.
1585
1586 When `full-file-path', include the full file path."
1587 :group 'org-refile
1588 :type '(choice
1589 (const :tag "Not" nil)
1590 (const :tag "Yes" t)
1591 (const :tag "Start with file name" file)
1592 (const :tag "Start with full file path" full-file-path)))
1593
1594 (defcustom org-outline-path-complete-in-steps t
1595 "Non-nil means, complete the outline path in hierarchical steps.
1596 When Org-mode uses the refile interface to select an outline path
1597 \(see variable `org-refile-use-outline-path'), the completion of
1598 the path can be done is a single go, or if can be done in steps down
1599 the headline hierarchy. Going in steps is probably the best if you
1600 do not use a special completion package like `ido' or `icicles'.
1601 However, when using these packages, going in one step can be very
1602 fast, while still showing the whole path to the entry."
1603 :group 'org-refile
1604 :type 'boolean)
1605
1606 (defcustom org-refile-allow-creating-parent-nodes nil
1607 "Non-nil means, allow to create new nodes as refile targets.
1608 New nodes are then created by adding \"/new node name\" to the completion
1609 of an existing node. When the value of this variable is `confirm',
1610 new node creation must be confirmed by the user (recommended)
1611 When nil, the completion must match an existing entry.
1612
1613 Note that, if the new heading is not seen by the criteria
1614 listed in `org-refile-targets', multiple instances of the same
1615 heading would be created by trying again to file under the new
1616 heading."
1617 :group 'org-refile
1618 :type '(choice
1619 (const :tag "Never" nil)
1620 (const :tag "Always" t)
1621 (const :tag "Prompt for confirmation" confirm)))
1622
1623 (defgroup org-todo nil
1624 "Options concerning TODO items in Org-mode."
1625 :tag "Org TODO"
1626 :group 'org)
1627
1628 (defgroup org-progress nil
1629 "Options concerning Progress logging in Org-mode."
1630 :tag "Org Progress"
1631 :group 'org-time)
1632
1633 (defvar org-todo-interpretation-widgets
1634 '(
1635 (:tag "Sequence (cycling hits every state)" sequence)
1636 (:tag "Type (cycling directly to DONE)" type))
1637 "The available interpretation symbols for customizing
1638 `org-todo-keywords'.
1639 Interested libraries should add to this list.")
1640
1641 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1642 "List of TODO entry keyword sequences and their interpretation.
1643 \\<org-mode-map>This is a list of sequences.
1644
1645 Each sequence starts with a symbol, either `sequence' or `type',
1646 indicating if the keywords should be interpreted as a sequence of
1647 action steps, or as different types of TODO items. The first
1648 keywords are states requiring action - these states will select a headline
1649 for inclusion into the global TODO list Org-mode produces. If one of
1650 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1651 signify that no further action is necessary. If \"|\" is not found,
1652 the last keyword is treated as the only DONE state of the sequence.
1653
1654 The command \\[org-todo] cycles an entry through these states, and one
1655 additional state where no keyword is present. For details about this
1656 cycling, see the manual.
1657
1658 TODO keywords and interpretation can also be set on a per-file basis with
1659 the special #+SEQ_TODO and #+TYP_TODO lines.
1660
1661 Each keyword can optionally specify a character for fast state selection
1662 \(in combination with the variable `org-use-fast-todo-selection')
1663 and specifiers for state change logging, using the same syntax
1664 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1665 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1666 indicates to record a time stamp each time this state is selected.
1667
1668 Each keyword may also specify if a timestamp or a note should be
1669 recorded when entering or leaving the state, by adding additional
1670 characters in the parenthesis after the keyword. This looks like this:
1671 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1672 record only the time of the state change. With X and Y being either
1673 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1674 Y when leaving the state if and only if the *target* state does not
1675 define X. You may omit any of the fast-selection key or X or /Y,
1676 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1677
1678 For backward compatibility, this variable may also be just a list
1679 of keywords - in this case the interpretation (sequence or type) will be
1680 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1681 :group 'org-todo
1682 :group 'org-keywords
1683 :type '(choice
1684 (repeat :tag "Old syntax, just keywords"
1685 (string :tag "Keyword"))
1686 (repeat :tag "New syntax"
1687 (cons
1688 (choice
1689 :tag "Interpretation"
1690 ;;Quick and dirty way to see
1691 ;;`org-todo-interpretations'. This takes the
1692 ;;place of item arguments
1693 :convert-widget
1694 (lambda (widget)
1695 (widget-put widget
1696 :args (mapcar
1697 #'(lambda (x)
1698 (widget-convert
1699 (cons 'const x)))
1700 org-todo-interpretation-widgets))
1701 widget))
1702 (repeat
1703 (string :tag "Keyword"))))))
1704
1705 (defvar org-todo-keywords-1 nil
1706 "All TODO and DONE keywords active in a buffer.")
1707 (make-variable-buffer-local 'org-todo-keywords-1)
1708 (defvar org-todo-keywords-for-agenda nil)
1709 (defvar org-done-keywords-for-agenda nil)
1710 (defvar org-drawers-for-agenda nil)
1711 (defvar org-todo-keyword-alist-for-agenda nil)
1712 (defvar org-tag-alist-for-agenda nil)
1713 (defvar org-agenda-contributing-files nil)
1714 (defvar org-not-done-keywords nil)
1715 (make-variable-buffer-local 'org-not-done-keywords)
1716 (defvar org-done-keywords nil)
1717 (make-variable-buffer-local 'org-done-keywords)
1718 (defvar org-todo-heads nil)
1719 (make-variable-buffer-local 'org-todo-heads)
1720 (defvar org-todo-sets nil)
1721 (make-variable-buffer-local 'org-todo-sets)
1722 (defvar org-todo-log-states nil)
1723 (make-variable-buffer-local 'org-todo-log-states)
1724 (defvar org-todo-kwd-alist nil)
1725 (make-variable-buffer-local 'org-todo-kwd-alist)
1726 (defvar org-todo-key-alist nil)
1727 (make-variable-buffer-local 'org-todo-key-alist)
1728 (defvar org-todo-key-trigger nil)
1729 (make-variable-buffer-local 'org-todo-key-trigger)
1730
1731 (defcustom org-todo-interpretation 'sequence
1732 "Controls how TODO keywords are interpreted.
1733 This variable is in principle obsolete and is only used for
1734 backward compatibility, if the interpretation of todo keywords is
1735 not given already in `org-todo-keywords'. See that variable for
1736 more information."
1737 :group 'org-todo
1738 :group 'org-keywords
1739 :type '(choice (const sequence)
1740 (const type)))
1741
1742 (defcustom org-use-fast-todo-selection t
1743 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1744 This variable describes if and under what circumstances the cycling
1745 mechanism for TODO keywords will be replaced by a single-key, direct
1746 selection scheme.
1747
1748 When nil, fast selection is never used.
1749
1750 When the symbol `prefix', it will be used when `org-todo' is called with
1751 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1752 in an agenda buffer.
1753
1754 When t, fast selection is used by default. In this case, the prefix
1755 argument forces cycling instead.
1756
1757 In all cases, the special interface is only used if access keys have actually
1758 been assigned by the user, i.e. if keywords in the configuration are followed
1759 by a letter in parenthesis, like TODO(t)."
1760 :group 'org-todo
1761 :type '(choice
1762 (const :tag "Never" nil)
1763 (const :tag "By default" t)
1764 (const :tag "Only with C-u C-c C-t" prefix)))
1765
1766 (defcustom org-provide-todo-statistics t
1767 "Non-nil means, update todo statistics after insert and toggle.
1768 ALL-HEADLINES means update todo statistics by including headlines
1769 with no TODO keyword as well, counting them as not done.
1770 A list of TODO keywords means the same, but skip keywords that are
1771 not in this list.
1772
1773 When this is set, todo statistics is updated in the parent of the
1774 current entry each time a todo state is changed."
1775 :group 'org-todo
1776 :type '(choice
1777 (const :tag "Yes, only for TODO entries" t)
1778 (const :tag "Yes, including all entries" 'all-headlines)
1779 (repeat :tag "Yes, for TODOs in this list"
1780 (string :tag "TODO keyword"))
1781 (other :tag "No TODO statistics" nil)))
1782
1783 (defcustom org-hierarchical-todo-statistics t
1784 "Non-nil means, TODO statistics covers just direct children.
1785 When nil, all entries in the subtree are considered.
1786 This has only an effect if `org-provide-todo-statistics' is set.
1787 To set this to nil for only a single subtree, use a COOKIE_DATA
1788 property and include the word \"recursive\" into the value."
1789 :group 'org-todo
1790 :type 'boolean)
1791
1792 (defcustom org-after-todo-state-change-hook nil
1793 "Hook which is run after the state of a TODO item was changed.
1794 The new state (a string with a TODO keyword, or nil) is available in the
1795 Lisp variable `state'."
1796 :group 'org-todo
1797 :type 'hook)
1798
1799 (defvar org-blocker-hook nil
1800 "Hook for functions that are allowed to block a state change.
1801
1802 Each function gets as its single argument a property list, see
1803 `org-trigger-hook' for more information about this list.
1804
1805 If any of the functions in this hook returns nil, the state change
1806 is blocked.")
1807
1808 (defvar org-trigger-hook nil
1809 "Hook for functions that are triggered by a state change.
1810
1811 Each function gets as its single argument a property list with at least
1812 the following elements:
1813
1814 (:type type-of-change :position pos-at-entry-start
1815 :from old-state :to new-state)
1816
1817 Depending on the type, more properties may be present.
1818
1819 This mechanism is currently implemented for:
1820
1821 TODO state changes
1822 ------------------
1823 :type todo-state-change
1824 :from previous state (keyword as a string), or nil, or a symbol
1825 'todo' or 'done', to indicate the general type of state.
1826 :to new state, like in :from")
1827
1828 (defcustom org-enforce-todo-dependencies nil
1829 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1830 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1831 be blocked if any prior sibling is not yet done.
1832 Finally, if the parent is blocked because of ordered siblings of its own,
1833 the child will also be blocked.
1834 This variable needs to be set before org.el is loaded, and you need to
1835 restart Emacs after a change to make the change effective. The only way
1836 to change is while Emacs is running is through the customize interface."
1837 :set (lambda (var val)
1838 (set var val)
1839 (if val
1840 (add-hook 'org-blocker-hook
1841 'org-block-todo-from-children-or-siblings-or-parent)
1842 (remove-hook 'org-blocker-hook
1843 'org-block-todo-from-children-or-siblings-or-parent)))
1844 :group 'org-todo
1845 :type 'boolean)
1846
1847 (defcustom org-enforce-todo-checkbox-dependencies nil
1848 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1849 When this is nil, checkboxes have no influence on switching TODO states.
1850 When non-nil, you first need to check off all check boxes before the TODO
1851 entry can be switched to DONE.
1852 This variable needs to be set before org.el is loaded, and you need to
1853 restart Emacs after a change to make the change effective. The only way
1854 to change is while Emacs is running is through the customize interface."
1855 :set (lambda (var val)
1856 (set var val)
1857 (if val
1858 (add-hook 'org-blocker-hook
1859 'org-block-todo-from-checkboxes)
1860 (remove-hook 'org-blocker-hook
1861 'org-block-todo-from-checkboxes)))
1862 :group 'org-todo
1863 :type 'boolean)
1864
1865 (defcustom org-treat-insert-todo-heading-as-state-change nil
1866 "Non-nil means, inserting a TODO heading is treated as state change.
1867 So when the command \\[org-insert-todo-heading] is used, state change
1868 logging will apply if appropriate. When nil, the new TODO item will
1869 be inserted directly, and no logging will take place."
1870 :group 'org-todo
1871 :type 'boolean)
1872
1873 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1874 "Non-nil means, switching TODO states with S-cursor counts as state change.
1875 This is the default behavior. However, setting this to nil allows a
1876 convenient way to select a TODO state and bypass any logging associated
1877 with that."
1878 :group 'org-todo
1879 :type 'boolean)
1880
1881 (defcustom org-todo-state-tags-triggers nil
1882 "Tag changes that should be triggered by TODO state changes.
1883 This is a list. Each entry is
1884
1885 (state-change (tag . flag) .......)
1886
1887 State-change can be a string with a state, and empty string to indicate the
1888 state that has no TODO keyword, or it can be one of the symbols `todo'
1889 or `done', meaning any not-done or done state, respectively."
1890 :group 'org-todo
1891 :group 'org-tags
1892 :type '(repeat
1893 (cons (choice :tag "When changing to"
1894 (const :tag "Not-done state" todo)
1895 (const :tag "Done state" done)
1896 (string :tag "State"))
1897 (repeat
1898 (cons :tag "Tag action"
1899 (string :tag "Tag")
1900 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1901
1902 (defcustom org-log-done nil
1903 "Information to record when a task moves to the DONE state.
1904
1905 Possible values are:
1906
1907 nil Don't add anything, just change the keyword
1908 time Add a time stamp to the task
1909 note Prompt a closing note and add it with template `org-log-note-headings'
1910
1911 This option can also be set with on a per-file-basis with
1912
1913 #+STARTUP: nologdone
1914 #+STARTUP: logdone
1915 #+STARTUP: lognotedone
1916
1917 You can have local logging settings for a subtree by setting the LOGGING
1918 property to one or more of these keywords."
1919 :group 'org-todo
1920 :group 'org-progress
1921 :type '(choice
1922 (const :tag "No logging" nil)
1923 (const :tag "Record CLOSED timestamp" time)
1924 (const :tag "Record CLOSED timestamp with closing note." note)))
1925
1926 ;; Normalize old uses of org-log-done.
1927 (cond
1928 ((eq org-log-done t) (setq org-log-done 'time))
1929 ((and (listp org-log-done) (memq 'done org-log-done))
1930 (setq org-log-done 'note)))
1931
1932 (defcustom org-log-note-clock-out nil
1933 "Non-nil means, record a note when clocking out of an item.
1934 This can also be configured on a per-file basis by adding one of
1935 the following lines anywhere in the buffer:
1936
1937 #+STARTUP: lognoteclock-out
1938 #+STARTUP: nolognoteclock-out"
1939 :group 'org-todo
1940 :group 'org-progress
1941 :type 'boolean)
1942
1943 (defcustom org-log-done-with-time t
1944 "Non-nil means, the CLOSED time stamp will contain date and time.
1945 When nil, only the date will be recorded."
1946 :group 'org-progress
1947 :type 'boolean)
1948
1949 (defcustom org-log-note-headings
1950 '((done . "CLOSING NOTE %t")
1951 (state . "State %-12s from %-12S %t")
1952 (note . "Note taken on %t")
1953 (clock-out . ""))
1954 "Headings for notes added to entries.
1955 The value is an alist, with the car being a symbol indicating the note
1956 context, and the cdr is the heading to be used. The heading may also be the
1957 empty string.
1958 %t in the heading will be replaced by a time stamp.
1959 %s will be replaced by the new TODO state, in double quotes.
1960 %S will be replaced by the old TODO state, in double quotes.
1961 %u will be replaced by the user name.
1962 %U will be replaced by the full user name."
1963 :group 'org-todo
1964 :group 'org-progress
1965 :type '(list :greedy t
1966 (cons (const :tag "Heading when closing an item" done) string)
1967 (cons (const :tag
1968 "Heading when changing todo state (todo sequence only)"
1969 state) string)
1970 (cons (const :tag "Heading when just taking a note" note) string)
1971 (cons (const :tag "Heading when clocking out" clock-out) string)))
1972
1973 (unless (assq 'note org-log-note-headings)
1974 (push '(note . "%t") org-log-note-headings))
1975
1976 (defcustom org-log-into-drawer nil
1977 "Non-nil means, insert state change notes and time stamps into a drawer.
1978 When nil, state changes notes will be inserted after the headline and
1979 any scheduling and clock lines, but not inside a drawer.
1980
1981 The value of this variable should be the name of the drawer to use.
1982 LOGBOOK is proposed at the default drawer for this purpose, you can
1983 also set this to a string to define the drawer of your choice.
1984
1985 A value of t is also allowed, representing \"LOGBOOK\".
1986
1987 If this variable is set, `org-log-state-notes-insert-after-drawers'
1988 will be ignored.
1989
1990 You can set the property LOG_INTO_DRAWER to overrule this setting for
1991 a subtree."
1992 :group 'org-todo
1993 :group 'org-progress
1994 :type '(choice
1995 (const :tag "Not into a drawer" nil)
1996 (const :tag "LOGBOOK" t)
1997 (string :tag "Other")))
1998
1999 (if (fboundp 'defvaralias)
2000 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2001
2002 (defun org-log-into-drawer ()
2003 "Return the value of `org-log-into-drawer', but let properties overrule.
2004 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2005 used instead of the default value."
2006 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2007 (cond
2008 ((or (not p) (equal p "nil")) org-log-into-drawer)
2009 ((equal p "t") "LOGBOOK")
2010 (t p))))
2011
2012 (defcustom org-log-state-notes-insert-after-drawers nil
2013 "Non-nil means, insert state change notes after any drawers in entry.
2014 Only the drawers that *immediately* follow the headline and the
2015 deadline/scheduled line are skipped.
2016 When nil, insert notes right after the heading and perhaps the line
2017 with deadline/scheduling if present.
2018
2019 This variable will have no effect if `org-log-into-drawer' is
2020 set."
2021 :group 'org-todo
2022 :group 'org-progress
2023 :type 'boolean)
2024
2025 (defcustom org-log-states-order-reversed t
2026 "Non-nil means, the latest state change note will be directly after heading.
2027 When nil, the notes will be orderer according to time."
2028 :group 'org-todo
2029 :group 'org-progress
2030 :type 'boolean)
2031
2032 (defcustom org-log-repeat 'time
2033 "Non-nil means, record moving through the DONE state when triggering repeat.
2034 An auto-repeating task is immediately switched back to TODO when
2035 marked DONE. If you are not logging state changes (by adding \"@\"
2036 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2037 record a closing note, there will be no record of the task moving
2038 through DONE. This variable forces taking a note anyway.
2039
2040 nil Don't force a record
2041 time Record a time stamp
2042 note Record a note
2043
2044 This option can also be set with on a per-file-basis with
2045
2046 #+STARTUP: logrepeat
2047 #+STARTUP: lognoterepeat
2048 #+STARTUP: nologrepeat
2049
2050 You can have local logging settings for a subtree by setting the LOGGING
2051 property to one or more of these keywords."
2052 :group 'org-todo
2053 :group 'org-progress
2054 :type '(choice
2055 (const :tag "Don't force a record" nil)
2056 (const :tag "Force recording the DONE state" time)
2057 (const :tag "Force recording a note with the DONE state" note)))
2058
2059
2060 (defgroup org-priorities nil
2061 "Priorities in Org-mode."
2062 :tag "Org Priorities"
2063 :group 'org-todo)
2064
2065 (defcustom org-enable-priority-commands t
2066 "Non-nil means, priority commands are active.
2067 When nil, these commands will be disabled, so that you never accidentally
2068 set a priority."
2069 :group 'org-priorities
2070 :type 'boolean)
2071
2072 (defcustom org-highest-priority ?A
2073 "The highest priority of TODO items. A character like ?A, ?B etc.
2074 Must have a smaller ASCII number than `org-lowest-priority'."
2075 :group 'org-priorities
2076 :type 'character)
2077
2078 (defcustom org-lowest-priority ?C
2079 "The lowest priority of TODO items. A character like ?A, ?B etc.
2080 Must have a larger ASCII number than `org-highest-priority'."
2081 :group 'org-priorities
2082 :type 'character)
2083
2084 (defcustom org-default-priority ?B
2085 "The default priority of TODO items.
2086 This is the priority an item get if no explicit priority is given."
2087 :group 'org-priorities
2088 :type 'character)
2089
2090 (defcustom org-priority-start-cycle-with-default t
2091 "Non-nil means, start with default priority when starting to cycle.
2092 When this is nil, the first step in the cycle will be (depending on the
2093 command used) one higher or lower that the default priority."
2094 :group 'org-priorities
2095 :type 'boolean)
2096
2097 (defgroup org-time nil
2098 "Options concerning time stamps and deadlines in Org-mode."
2099 :tag "Org Time"
2100 :group 'org)
2101
2102 (defcustom org-insert-labeled-timestamps-at-point nil
2103 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2104 When nil, these labeled time stamps are forces into the second line of an
2105 entry, just after the headline. When scheduling from the global TODO list,
2106 the time stamp will always be forced into the second line."
2107 :group 'org-time
2108 :type 'boolean)
2109
2110 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2111 "Formats for `format-time-string' which are used for time stamps.
2112 It is not recommended to change this constant.")
2113
2114 (defcustom org-time-stamp-rounding-minutes '(0 5)
2115 "Number of minutes to round time stamps to.
2116 These are two values, the first applies when first creating a time stamp.
2117 The second applies when changing it with the commands `S-up' and `S-down'.
2118 When changing the time stamp, this means that it will change in steps
2119 of N minutes, as given by the second value.
2120
2121 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2122 numbers should be factors of 60, so for example 5, 10, 15.
2123
2124 When this is larger than 1, you can still force an exact time-stamp by using
2125 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2126 and by using a prefix arg to `S-up/down' to specify the exact number
2127 of minutes to shift."
2128 :group 'org-time
2129 :get '(lambda (var) ; Make sure all entries have 5 elements
2130 (if (integerp (default-value var))
2131 (list (default-value var) 5)
2132 (default-value var)))
2133 :type '(list
2134 (integer :tag "when inserting times")
2135 (integer :tag "when modifying times")))
2136
2137 ;; Normalize old customizations of this variable.
2138 (when (integerp org-time-stamp-rounding-minutes)
2139 (setq org-time-stamp-rounding-minutes
2140 (list org-time-stamp-rounding-minutes
2141 org-time-stamp-rounding-minutes)))
2142
2143 (defcustom org-display-custom-times nil
2144 "Non-nil means, overlay custom formats over all time stamps.
2145 The formats are defined through the variable `org-time-stamp-custom-formats'.
2146 To turn this on on a per-file basis, insert anywhere in the file:
2147 #+STARTUP: customtime"
2148 :group 'org-time
2149 :set 'set-default
2150 :type 'sexp)
2151 (make-variable-buffer-local 'org-display-custom-times)
2152
2153 (defcustom org-time-stamp-custom-formats
2154 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2155 "Custom formats for time stamps. See `format-time-string' for the syntax.
2156 These are overlayed over the default ISO format if the variable
2157 `org-display-custom-times' is set. Time like %H:%M should be at the
2158 end of the second format. The custom formats are also honored by export
2159 commands, if custom time display is turned on at the time of export."
2160 :group 'org-time
2161 :type 'sexp)
2162
2163 (defun org-time-stamp-format (&optional long inactive)
2164 "Get the right format for a time string."
2165 (let ((f (if long (cdr org-time-stamp-formats)
2166 (car org-time-stamp-formats))))
2167 (if inactive
2168 (concat "[" (substring f 1 -1) "]")
2169 f)))
2170
2171 (defcustom org-time-clocksum-format "%d:%02d"
2172 "The format string used when creating CLOCKSUM lines, or when
2173 org-mode generates a time duration."
2174 :group 'org-time
2175 :type 'string)
2176
2177 (defcustom org-deadline-warning-days 14
2178 "No. of days before expiration during which a deadline becomes active.
2179 This variable governs the display in sparse trees and in the agenda.
2180 When 0 or negative, it means use this number (the absolute value of it)
2181 even if a deadline has a different individual lead time specified.
2182
2183 Custom commands can set this variable in the options section."
2184 :group 'org-time
2185 :group 'org-agenda-daily/weekly
2186 :type 'integer)
2187
2188 (defcustom org-read-date-prefer-future t
2189 "Non-nil means, assume future for incomplete date input from user.
2190 This affects the following situations:
2191 1. The user gives a day, but no month.
2192 For example, if today is the 15th, and you enter \"3\", Org-mode will
2193 read this as the third of *next* month. However, if you enter \"17\",
2194 it will be considered as *this* month.
2195 2. The user gives a month but not a year.
2196 For example, if it is april and you enter \"feb 2\", this will be read
2197 as feb 2, *next* year. \"May 5\", however, will be this year.
2198
2199 Currently this does not work for ISO week specifications.
2200
2201 When this option is nil, the current month and year will always be used
2202 as defaults."
2203 :group 'org-time
2204 :type 'boolean)
2205
2206 (defcustom org-read-date-display-live t
2207 "Non-nil means, display current interpretation of date prompt live.
2208 This display will be in an overlay, in the minibuffer."
2209 :group 'org-time
2210 :type 'boolean)
2211
2212 (defcustom org-read-date-popup-calendar t
2213 "Non-nil means, pop up a calendar when prompting for a date.
2214 In the calendar, the date can be selected with mouse-1. However, the
2215 minibuffer will also be active, and you can simply enter the date as well.
2216 When nil, only the minibuffer will be available."
2217 :group 'org-time
2218 :type 'boolean)
2219 (if (fboundp 'defvaralias)
2220 (defvaralias 'org-popup-calendar-for-date-prompt
2221 'org-read-date-popup-calendar))
2222
2223 (defcustom org-read-date-minibuffer-setup-hook nil
2224 "Hook to be used to set up keys for the date/time interface.
2225 Add key definitions to `minibuffer-local-map', which will be a temporary
2226 copy."
2227 :group 'org-time
2228 :type 'hook)
2229
2230 (defcustom org-extend-today-until 0
2231 "The hour when your day really ends. Must be an integer.
2232 This has influence for the following applications:
2233 - When switching the agenda to \"today\". It it is still earlier than
2234 the time given here, the day recognized as TODAY is actually yesterday.
2235 - When a date is read from the user and it is still before the time given
2236 here, the current date and time will be assumed to be yesterday, 23:59.
2237 Also, timestamps inserted in remember templates follow this rule.
2238
2239 IMPORTANT: This is a feature whose implementation is and likely will
2240 remain incomplete. Really, it is only here because past midnight seems to
2241 be the favorite working time of John Wiegley :-)"
2242 :group 'org-time
2243 :type 'integer)
2244
2245 (defcustom org-edit-timestamp-down-means-later nil
2246 "Non-nil means, S-down will increase the time in a time stamp.
2247 When nil, S-up will increase."
2248 :group 'org-time
2249 :type 'boolean)
2250
2251 (defcustom org-calendar-follow-timestamp-change t
2252 "Non-nil means, make the calendar window follow timestamp changes.
2253 When a timestamp is modified and the calendar window is visible, it will be
2254 moved to the new date."
2255 :group 'org-time
2256 :type 'boolean)
2257
2258 (defgroup org-tags nil
2259 "Options concerning tags in Org-mode."
2260 :tag "Org Tags"
2261 :group 'org)
2262
2263 (defcustom org-tag-alist nil
2264 "List of tags allowed in Org-mode files.
2265 When this list is nil, Org-mode will base TAG input on what is already in the
2266 buffer.
2267 The value of this variable is an alist, the car of each entry must be a
2268 keyword as a string, the cdr may be a character that is used to select
2269 that tag through the fast-tag-selection interface.
2270 See the manual for details."
2271 :group 'org-tags
2272 :type '(repeat
2273 (choice
2274 (cons (string :tag "Tag name")
2275 (character :tag "Access char"))
2276 (const :tag "Start radio group" (:startgroup))
2277 (const :tag "End radio group" (:endgroup))
2278 (const :tag "New line" (:newline)))))
2279
2280 (defcustom org-tag-persistent-alist nil
2281 "List of tags that will always appear in all Org-mode files.
2282 This is in addition to any in buffer settings or customizations
2283 of `org-tag-alist'.
2284 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2285 The value of this variable is an alist, the car of each entry must be a
2286 keyword as a string, the cdr may be a character that is used to select
2287 that tag through the fast-tag-selection interface.
2288 See the manual for details.
2289 To disable these tags on a per-file basis, insert anywhere in the file:
2290 #+STARTUP: noptag"
2291 :group 'org-tags
2292 :type '(repeat
2293 (choice
2294 (cons (string :tag "Tag name")
2295 (character :tag "Access char"))
2296 (const :tag "Start radio group" (:startgroup))
2297 (const :tag "End radio group" (:endgroup))
2298 (const :tag "New line" (:newline)))))
2299
2300 (defvar org-file-tags nil
2301 "List of tags that can be inherited by all entries in the file.
2302 The tags will be inherited if the variable `org-use-tag-inheritance'
2303 says they should be.
2304 This variable is populated from #+TAG lines.")
2305
2306 (defcustom org-use-fast-tag-selection 'auto
2307 "Non-nil means, use fast tag selection scheme.
2308 This is a special interface to select and deselect tags with single keys.
2309 When nil, fast selection is never used.
2310 When the symbol `auto', fast selection is used if and only if selection
2311 characters for tags have been configured, either through the variable
2312 `org-tag-alist' or through a #+TAGS line in the buffer.
2313 When t, fast selection is always used and selection keys are assigned
2314 automatically if necessary."
2315 :group 'org-tags
2316 :type '(choice
2317 (const :tag "Always" t)
2318 (const :tag "Never" nil)
2319 (const :tag "When selection characters are configured" 'auto)))
2320
2321 (defcustom org-fast-tag-selection-single-key nil
2322 "Non-nil means, fast tag selection exits after first change.
2323 When nil, you have to press RET to exit it.
2324 During fast tag selection, you can toggle this flag with `C-c'.
2325 This variable can also have the value `expert'. In this case, the window
2326 displaying the tags menu is not even shown, until you press C-c again."
2327 :group 'org-tags
2328 :type '(choice
2329 (const :tag "No" nil)
2330 (const :tag "Yes" t)
2331 (const :tag "Expert" expert)))
2332
2333 (defvar org-fast-tag-selection-include-todo nil
2334 "Non-nil means, fast tags selection interface will also offer TODO states.
2335 This is an undocumented feature, you should not rely on it.")
2336
2337 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2338 "The column to which tags should be indented in a headline.
2339 If this number is positive, it specifies the column. If it is negative,
2340 it means that the tags should be flushright to that column. For example,
2341 -80 works well for a normal 80 character screen."
2342 :group 'org-tags
2343 :type 'integer)
2344
2345 (defcustom org-auto-align-tags t
2346 "Non-nil means, realign tags after pro/demotion of TODO state change.
2347 These operations change the length of a headline and therefore shift
2348 the tags around. With this options turned on, after each such operation
2349 the tags are again aligned to `org-tags-column'."
2350 :group 'org-tags
2351 :type 'boolean)
2352
2353 (defcustom org-use-tag-inheritance t
2354 "Non-nil means, tags in levels apply also for sublevels.
2355 When nil, only the tags directly given in a specific line apply there.
2356 This may also be a list of tags that should be inherited, or a regexp that
2357 matches tags that should be inherited. Additional control is possible
2358 with the variable `org-tags-exclude-from-inheritance' which gives an
2359 explicit list of tags to be excluded from inheritance., even if the value of
2360 `org-use-tag-inheritance' would select it for inheritance.
2361
2362 If this option is t, a match early-on in a tree can lead to a large
2363 number of matches in the subtree when constructing the agenda or creating
2364 a sparse tree. If you only want to see the first match in a tree during
2365 a search, check out the variable `org-tags-match-list-sublevels'."
2366 :group 'org-tags
2367 :type '(choice
2368 (const :tag "Not" nil)
2369 (const :tag "Always" t)
2370 (repeat :tag "Specific tags" (string :tag "Tag"))
2371 (regexp :tag "Tags matched by regexp")))
2372
2373 (defcustom org-tags-exclude-from-inheritance nil
2374 "List of tags that should never be inherited.
2375 This is a way to exclude a few tags from inheritance. For way to do
2376 the opposite, to actively allow inheritance for selected tags,
2377 see the variable `org-use-tag-inheritance'."
2378 :group 'org-tags
2379 :type '(repeat (string :tag "Tag")))
2380
2381 (defun org-tag-inherit-p (tag)
2382 "Check if TAG is one that should be inherited."
2383 (cond
2384 ((member tag org-tags-exclude-from-inheritance) nil)
2385 ((eq org-use-tag-inheritance t) t)
2386 ((not org-use-tag-inheritance) nil)
2387 ((stringp org-use-tag-inheritance)
2388 (string-match org-use-tag-inheritance tag))
2389 ((listp org-use-tag-inheritance)
2390 (member tag org-use-tag-inheritance))
2391 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2392
2393 (defcustom org-tags-match-list-sublevels t
2394 "Non-nil means list also sublevels of headlines matching a search.
2395 This variable applies to tags/property searches, and also to stuck
2396 projects because this search is based on a tags match as well.
2397
2398 When set to the symbol `indented', sublevels are indented with
2399 leading dots.
2400
2401 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2402 the sublevels of a headline matching a tag search often also match
2403 the same search. Listing all of them can create very long lists.
2404 Setting this variable to nil causes subtrees of a match to be skipped.
2405
2406 This variable is semi-obsolete and probably should always be true. It
2407 is better to limit inheritance to certain tags using the variables
2408 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2409 :group 'org-tags
2410 :type '(choice
2411 (const :tag "No, don't list them" nil)
2412 (const :tag "Yes, do list them" t)
2413 (const :tag "List them, indented with leading dots" indented)))
2414
2415 (defcustom org-tags-sort-function nil
2416 "When set, tags are sorted using this function as a comparator"
2417 :group 'org-tags
2418 :type '(choice
2419 (const :tag "No sorting" nil)
2420 (const :tag "Alphabetical" string<)
2421 (const :tag "Reverse alphabetical" string>)
2422 (function :tag "Custom function" nil)))
2423
2424 (defvar org-tags-history nil
2425 "History of minibuffer reads for tags.")
2426 (defvar org-last-tags-completion-table nil
2427 "The last used completion table for tags.")
2428 (defvar org-after-tags-change-hook nil
2429 "Hook that is run after the tags in a line have changed.")
2430
2431 (defgroup org-properties nil
2432 "Options concerning properties in Org-mode."
2433 :tag "Org Properties"
2434 :group 'org)
2435
2436 (defcustom org-property-format "%-10s %s"
2437 "How property key/value pairs should be formatted by `indent-line'.
2438 When `indent-line' hits a property definition, it will format the line
2439 according to this format, mainly to make sure that the values are
2440 lined-up with respect to each other."
2441 :group 'org-properties
2442 :type 'string)
2443
2444 (defcustom org-use-property-inheritance nil
2445 "Non-nil means, properties apply also for sublevels.
2446
2447 This setting is chiefly used during property searches. Turning it on can
2448 cause significant overhead when doing a search, which is why it is not
2449 on by default.
2450
2451 When nil, only the properties directly given in the current entry count.
2452 When t, every property is inherited. The value may also be a list of
2453 properties that should have inheritance, or a regular expression matching
2454 properties that should be inherited.
2455
2456 However, note that some special properties use inheritance under special
2457 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2458 and the properties ending in \"_ALL\" when they are used as descriptor
2459 for valid values of a property.
2460
2461 Note for programmers:
2462 When querying an entry with `org-entry-get', you can control if inheritance
2463 should be used. By default, `org-entry-get' looks only at the local
2464 properties. You can request inheritance by setting the inherit argument
2465 to t (to force inheritance) or to `selective' (to respect the setting
2466 in this variable)."
2467 :group 'org-properties
2468 :type '(choice
2469 (const :tag "Not" nil)
2470 (const :tag "Always" t)
2471 (repeat :tag "Specific properties" (string :tag "Property"))
2472 (regexp :tag "Properties matched by regexp")))
2473
2474 (defun org-property-inherit-p (property)
2475 "Check if PROPERTY is one that should be inherited."
2476 (cond
2477 ((eq org-use-property-inheritance t) t)
2478 ((not org-use-property-inheritance) nil)
2479 ((stringp org-use-property-inheritance)
2480 (string-match org-use-property-inheritance property))
2481 ((listp org-use-property-inheritance)
2482 (member property org-use-property-inheritance))
2483 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2484
2485 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2486 "The default column format, if no other format has been defined.
2487 This variable can be set on the per-file basis by inserting a line
2488
2489 #+COLUMNS: %25ITEM ....."
2490 :group 'org-properties
2491 :type 'string)
2492
2493 (defcustom org-columns-ellipses ".."
2494 "The ellipses to be used when a field in column view is truncated.
2495 When this is the empty string, as many characters as possible are shown,
2496 but then there will be no visual indication that the field has been truncated.
2497 When this is a string of length N, the last N characters of a truncated
2498 field are replaced by this string. If the column is narrower than the
2499 ellipses string, only part of the ellipses string will be shown."
2500 :group 'org-properties
2501 :type 'string)
2502
2503 (defcustom org-columns-modify-value-for-display-function nil
2504 "Function that modifies values for display in column view.
2505 For example, it can be used to cut out a certain part from a time stamp.
2506 The function must take 2 arguments:
2507
2508 column-title The title of the column (*not* the property name)
2509 value The value that should be modified.
2510
2511 The function should return the value that should be displayed,
2512 or nil if the normal value should be used."
2513 :group 'org-properties
2514 :type 'function)
2515
2516 (defcustom org-effort-property "Effort"
2517 "The property that is being used to keep track of effort estimates.
2518 Effort estimates given in this property need to have the format H:MM."
2519 :group 'org-properties
2520 :group 'org-progress
2521 :type '(string :tag "Property"))
2522
2523 (defconst org-global-properties-fixed
2524 '(("VISIBILITY_ALL" . "folded children content all")
2525 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2526 "List of property/value pairs that can be inherited by any entry.
2527
2528 These are fixed values, for the preset properties. The user variable
2529 that can be used to add to this list is `org-global-properties'.
2530
2531 The entries in this list are cons cells where the car is a property
2532 name and cdr is a string with the value. If the value represents
2533 multiple items like an \"_ALL\" property, separate the items by
2534 spaces.")
2535
2536 (defcustom org-global-properties nil
2537 "List of property/value pairs that can be inherited by any entry.
2538
2539 This list will be combined with the constant `org-global-properties-fixed'.
2540
2541 The entries in this list are cons cells where the car is a property
2542 name and cdr is a string with the value.
2543
2544 You can set buffer-local values for the same purpose in the variable
2545 `org-file-properties' this by adding lines like
2546
2547 #+PROPERTY: NAME VALUE"
2548 :group 'org-properties
2549 :type '(repeat
2550 (cons (string :tag "Property")
2551 (string :tag "Value"))))
2552
2553 (defvar org-file-properties nil
2554 "List of property/value pairs that can be inherited by any entry.
2555 Valid for the current buffer.
2556 This variable is populated from #+PROPERTY lines.")
2557 (make-variable-buffer-local 'org-file-properties)
2558
2559 (defgroup org-agenda nil
2560 "Options concerning agenda views in Org-mode."
2561 :tag "Org Agenda"
2562 :group 'org)
2563
2564 (defvar org-category nil
2565 "Variable used by org files to set a category for agenda display.
2566 Such files should use a file variable to set it, for example
2567
2568 # -*- mode: org; org-category: \"ELisp\"
2569
2570 or contain a special line
2571
2572 #+CATEGORY: ELisp
2573
2574 If the file does not specify a category, then file's base name
2575 is used instead.")
2576 (make-variable-buffer-local 'org-category)
2577 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2578
2579 (defcustom org-agenda-files nil
2580 "The files to be used for agenda display.
2581 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2582 \\[org-remove-file]. You can also use customize to edit the list.
2583
2584 If an entry is a directory, all files in that directory that are matched by
2585 `org-agenda-file-regexp' will be part of the file list.
2586
2587 If the value of the variable is not a list but a single file name, then
2588 the list of agenda files is actually stored and maintained in that file, one
2589 agenda file per line."
2590 :group 'org-agenda
2591 :type '(choice
2592 (repeat :tag "List of files and directories" file)
2593 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2594
2595 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2596 "Regular expression to match files for `org-agenda-files'.
2597 If any element in the list in that variable contains a directory instead
2598 of a normal file, all files in that directory that are matched by this
2599 regular expression will be included."
2600 :group 'org-agenda
2601 :type 'regexp)
2602
2603 (defcustom org-agenda-text-search-extra-files nil
2604 "List of extra files to be searched by text search commands.
2605 These files will be search in addition to the agenda files by the
2606 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2607 Note that these files will only be searched for text search commands,
2608 not for the other agenda views like todo lists, tag searches or the weekly
2609 agenda. This variable is intended to list notes and possibly archive files
2610 that should also be searched by these two commands.
2611 In fact, if the first element in the list is the symbol `agenda-archives',
2612 than all archive files of all agenda files will be added to the search
2613 scope."
2614 :group 'org-agenda
2615 :type '(set :greedy t
2616 (const :tag "Agenda Archives" agenda-archives)
2617 (repeat :inline t (file))))
2618
2619 (if (fboundp 'defvaralias)
2620 (defvaralias 'org-agenda-multi-occur-extra-files
2621 'org-agenda-text-search-extra-files))
2622
2623 (defcustom org-agenda-skip-unavailable-files nil
2624 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2625 A nil value means to remove them, after a query, from the list."
2626 :group 'org-agenda
2627 :type 'boolean)
2628
2629 (defcustom org-calendar-to-agenda-key [?c]
2630 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2631 The command `org-calendar-goto-agenda' will be bound to this key. The
2632 default is the character `c' because then `c' can be used to switch back and
2633 forth between agenda and calendar."
2634 :group 'org-agenda
2635 :type 'sexp)
2636
2637 (defcustom org-calendar-agenda-action-key [?k]
2638 "The key to be installed in `calendar-mode-map' for agenda-action.
2639 The command `org-agenda-action' will be bound to this key. The
2640 default is the character `k' because we use the same key in the agenda."
2641 :group 'org-agenda
2642 :type 'sexp)
2643
2644 (eval-after-load "calendar"
2645 '(progn
2646 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2647 'org-calendar-goto-agenda)
2648 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2649 'org-agenda-action)))
2650
2651 (defgroup org-latex nil
2652 "Options for embedding LaTeX code into Org-mode."
2653 :tag "Org LaTeX"
2654 :group 'org)
2655
2656 (defcustom org-format-latex-options
2657 '(:foreground default :background default :scale 1.0
2658 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2659 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2660 "Options for creating images from LaTeX fragments.
2661 This is a property list with the following properties:
2662 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2663 `default' means use the foreground of the default face.
2664 :background the background color, or \"Transparent\".
2665 `default' means use the background of the default face.
2666 :scale a scaling factor for the size of the images.
2667 :html-foreground, :html-background, :html-scale
2668 the same numbers for HTML export.
2669 :matchers a list indicating which matchers should be used to
2670 find LaTeX fragments. Valid members of this list are:
2671 \"begin\" find environments
2672 \"$1\" find single characters surrounded by $.$
2673 \"$\" find math expressions surrounded by $...$
2674 \"$$\" find math expressions surrounded by $$....$$
2675 \"\\(\" find math expressions surrounded by \\(...\\)
2676 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2677 :group 'org-latex
2678 :type 'plist)
2679
2680 (defcustom org-format-latex-header "\\documentclass{article}
2681 \\usepackage{amssymb}
2682 \\usepackage[usenames]{color}
2683 \\usepackage{amsmath}
2684 \\usepackage{latexsym}
2685 \\usepackage[mathscr]{eucal}
2686 \\pagestyle{empty} % do not remove
2687 % The settings below are copied from fullpage.sty
2688 \\setlength{\\textwidth}{\\paperwidth}
2689 \\addtolength{\\textwidth}{-3cm}
2690 \\setlength{\\oddsidemargin}{1.5cm}
2691 \\addtolength{\\oddsidemargin}{-2.54cm}
2692 \\setlength{\\evensidemargin}{\\oddsidemargin}
2693 \\setlength{\\textheight}{\\paperheight}
2694 \\addtolength{\\textheight}{-\\headheight}
2695 \\addtolength{\\textheight}{-\\headsep}
2696 \\addtolength{\\textheight}{-\\footskip}
2697 \\addtolength{\\textheight}{-3cm}
2698 \\setlength{\\topmargin}{1.5cm}
2699 \\addtolength{\\topmargin}{-2.54cm}"
2700 "The document header used for processing LaTeX fragments.
2701 It is imperative that this header make sure that no page number
2702 appears on the page."
2703 :group 'org-latex
2704 :type 'string)
2705
2706
2707 (defgroup org-font-lock nil
2708 "Font-lock settings for highlighting in Org-mode."
2709 :tag "Org Font Lock"
2710 :group 'org)
2711
2712 (defcustom org-level-color-stars-only nil
2713 "Non-nil means fontify only the stars in each headline.
2714 When nil, the entire headline is fontified.
2715 Changing it requires restart of `font-lock-mode' to become effective
2716 also in regions already fontified."
2717 :group 'org-font-lock
2718 :type 'boolean)
2719
2720 (defcustom org-hide-leading-stars nil
2721 "Non-nil means, hide the first N-1 stars in a headline.
2722 This works by using the face `org-hide' for these stars. This
2723 face is white for a light background, and black for a dark
2724 background. You may have to customize the face `org-hide' to
2725 make this work.
2726 Changing it requires restart of `font-lock-mode' to become effective
2727 also in regions already fontified.
2728 You may also set this on a per-file basis by adding one of the following
2729 lines to the buffer:
2730
2731 #+STARTUP: hidestars
2732 #+STARTUP: showstars"
2733 :group 'org-font-lock
2734 :type 'boolean)
2735
2736 (defcustom org-fontify-done-headline nil
2737 "Non-nil means, change the face of a headline if it is marked DONE.
2738 Normally, only the TODO/DONE keyword indicates the state of a headline.
2739 When this is non-nil, the headline after the keyword is set to the
2740 `org-headline-done' as an additional indication."
2741 :group 'org-font-lock
2742 :type 'boolean)
2743
2744 (defcustom org-fontify-emphasized-text t
2745 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2746 Changing this variable requires a restart of Emacs to take effect."
2747 :group 'org-font-lock
2748 :type 'boolean)
2749
2750 (defcustom org-fontify-whole-heading-line nil
2751 "Non-nil means fontify the whole line for headings.
2752 This is useful when setting a background color for the
2753 org-leve-* faces."
2754 :group 'org-font-lock
2755 :type 'boolean)
2756
2757 (defcustom org-highlight-latex-fragments-and-specials nil
2758 "Non-nil means, fontify what is treated specially by the exporters."
2759 :group 'org-font-lock
2760 :type 'boolean)
2761
2762 (defcustom org-hide-emphasis-markers nil
2763 "Non-nil mean font-lock should hide the emphasis marker characters."
2764 :group 'org-font-lock
2765 :type 'boolean)
2766
2767 (defvar org-emph-re nil
2768 "Regular expression for matching emphasis.")
2769 (defvar org-verbatim-re nil
2770 "Regular expression for matching verbatim text.")
2771 (defvar org-emphasis-regexp-components) ; defined just below
2772 (defvar org-emphasis-alist) ; defined just below
2773 (defun org-set-emph-re (var val)
2774 "Set variable and compute the emphasis regular expression."
2775 (set var val)
2776 (when (and (boundp 'org-emphasis-alist)
2777 (boundp 'org-emphasis-regexp-components)
2778 org-emphasis-alist org-emphasis-regexp-components)
2779 (let* ((e org-emphasis-regexp-components)
2780 (pre (car e))
2781 (post (nth 1 e))
2782 (border (nth 2 e))
2783 (body (nth 3 e))
2784 (nl (nth 4 e))
2785 (body1 (concat body "*?"))
2786 (markers (mapconcat 'car org-emphasis-alist ""))
2787 (vmarkers (mapconcat
2788 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2789 org-emphasis-alist "")))
2790 ;; make sure special characters appear at the right position in the class
2791 (if (string-match "\\^" markers)
2792 (setq markers (concat (replace-match "" t t markers) "^")))
2793 (if (string-match "-" markers)
2794 (setq markers (concat (replace-match "" t t markers) "-")))
2795 (if (string-match "\\^" vmarkers)
2796 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2797 (if (string-match "-" vmarkers)
2798 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2799 (if (> nl 0)
2800 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2801 (int-to-string nl) "\\}")))
2802 ;; Make the regexp
2803 (setq org-emph-re
2804 (concat "\\([" pre "]\\|^\\)"
2805 "\\("
2806 "\\([" markers "]\\)"
2807 "\\("
2808 "[^" border "]\\|"
2809 "[^" border "]"
2810 body1
2811 "[^" border "]"
2812 "\\)"
2813 "\\3\\)"
2814 "\\([" post "]\\|$\\)"))
2815 (setq org-verbatim-re
2816 (concat "\\([" pre "]\\|^\\)"
2817 "\\("
2818 "\\([" vmarkers "]\\)"
2819 "\\("
2820 "[^" border "]\\|"
2821 "[^" border "]"
2822 body1
2823 "[^" border "]"
2824 "\\)"
2825 "\\3\\)"
2826 "\\([" post "]\\|$\\)")))))
2827
2828 (defcustom org-emphasis-regexp-components
2829 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2830 "Components used to build the regular expression for emphasis.
2831 This is a list with 6 entries. Terminology: In an emphasis string
2832 like \" *strong word* \", we call the initial space PREMATCH, the final
2833 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2834 and \"trong wor\" is the body. The different components in this variable
2835 specify what is allowed/forbidden in each part:
2836
2837 pre Chars allowed as prematch. Beginning of line will be allowed too.
2838 post Chars allowed as postmatch. End of line will be allowed too.
2839 border The chars *forbidden* as border characters.
2840 body-regexp A regexp like \".\" to match a body character. Don't use
2841 non-shy groups here, and don't allow newline here.
2842 newline The maximum number of newlines allowed in an emphasis exp.
2843
2844 Use customize to modify this, or restart Emacs after changing it."
2845 :group 'org-font-lock
2846 :set 'org-set-emph-re
2847 :type '(list
2848 (sexp :tag "Allowed chars in pre ")
2849 (sexp :tag "Allowed chars in post ")
2850 (sexp :tag "Forbidden chars in border ")
2851 (sexp :tag "Regexp for body ")
2852 (integer :tag "number of newlines allowed")
2853 (option (boolean :tag "Please ignore this button"))))
2854
2855 (defcustom org-emphasis-alist
2856 `(("*" bold "<b>" "</b>")
2857 ("/" italic "<i>" "</i>")
2858 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2859 ("=" org-code "<code>" "</code>" verbatim)
2860 ("~" org-verbatim "<code>" "</code>" verbatim)
2861 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2862 "<del>" "</del>")
2863 )
2864 "Special syntax for emphasized text.
2865 Text starting and ending with a special character will be emphasized, for
2866 example *bold*, _underlined_ and /italic/. This variable sets the marker
2867 characters, the face to be used by font-lock for highlighting in Org-mode
2868 Emacs buffers, and the HTML tags to be used for this.
2869 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2870 Use customize to modify this, or restart Emacs after changing it."
2871 :group 'org-font-lock
2872 :set 'org-set-emph-re
2873 :type '(repeat
2874 (list
2875 (string :tag "Marker character")
2876 (choice
2877 (face :tag "Font-lock-face")
2878 (plist :tag "Face property list"))
2879 (string :tag "HTML start tag")
2880 (string :tag "HTML end tag")
2881 (option (const verbatim)))))
2882
2883 (defvar org-protecting-blocks
2884 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
2885 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
2886 This is needed for font-lock setup.")
2887
2888 ;;; Miscellaneous options
2889
2890 (defgroup org-completion nil
2891 "Completion in Org-mode."
2892 :tag "Org Completion"
2893 :group 'org)
2894
2895 (defcustom org-completion-use-ido nil
2896 "Non-nil means, use ido completion wherever possible.
2897 Note that `ido-mode' must be active for this variable to be relevant.
2898 If you decide to turn this variable on, you might well want to turn off
2899 `org-outline-path-complete-in-steps'.
2900 See also `org-completion-use-iswitchb'."
2901 :group 'org-completion
2902 :type 'boolean)
2903
2904 (defcustom org-completion-use-iswitchb nil
2905 "Non-nil means, use iswitchb completion wherever possible.
2906 Note that `iswitchb-mode' must be active for this variable to be relevant.
2907 If you decide to turn this variable on, you might well want to turn off
2908 `org-outline-path-complete-in-steps'.
2909 Note that thi variable has only an effect if `org-completion-use-ido' is nil."
2910 :group 'org-completion
2911 :type 'boolean)
2912
2913 (defcustom org-completion-fallback-command 'hippie-expand
2914 "The expansion command called by \\[org-complete] in normal context.
2915 Normal means, no org-mode-specific context."
2916 :group 'org-completion
2917 :type 'function)
2918
2919 ;;; Functions and variables from ther packages
2920 ;; Declared here to avoid compiler warnings
2921
2922 ;; XEmacs only
2923 (defvar outline-mode-menu-heading)
2924 (defvar outline-mode-menu-show)
2925 (defvar outline-mode-menu-hide)
2926 (defvar zmacs-regions) ; XEmacs regions
2927
2928 ;; Emacs only
2929 (defvar mark-active)
2930
2931 ;; Various packages
2932 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2933 (declare-function calendar-forward-day "cal-move" (arg))
2934 (declare-function calendar-goto-date "cal-move" (date))
2935 (declare-function calendar-goto-today "cal-move" ())
2936 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2937 (defvar calc-embedded-close-formula)
2938 (defvar calc-embedded-open-formula)
2939 (declare-function cdlatex-tab "ext:cdlatex" ())
2940 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2941 (defvar font-lock-unfontify-region-function)
2942 (declare-function iswitchb-read-buffer "iswitchb"
2943 (prompt &optional default require-match start matches-set))
2944 (defvar iswitchb-temp-buflist)
2945 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2946 (defvar org-agenda-tags-todo-honor-ignore-options)
2947 (declare-function org-agenda-skip "org-agenda" ())
2948 (declare-function org-format-agenda-item "org-agenda"
2949 (extra txt &optional category tags dotime noprefix remove-re))
2950 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2951 (declare-function org-agenda-change-all-lines "org-agenda"
2952 (newhead hdmarker &optional fixface just-this))
2953 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2954 (declare-function org-agenda-maybe-redo "org-agenda" ())
2955 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2956 (beg end))
2957 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2958 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2959 "org-agenda" (&optional end))
2960 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
2961 (declare-function org-indent-mode "org-indent" (&optional arg))
2962 (declare-function parse-time-string "parse-time" (string))
2963 (defvar remember-data-file)
2964 (defvar texmathp-why)
2965 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2966 (declare-function table--at-cell-p "table" (position &optional object at-column))
2967
2968 (defvar w3m-current-url)
2969 (defvar w3m-current-title)
2970
2971 (defvar org-latex-regexps)
2972
2973 ;;; Autoload and prepare some org modules
2974
2975 ;; Some table stuff that needs to be defined here, because it is used
2976 ;; by the functions setting up org-mode or checking for table context.
2977
2978 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2979 "Detects an org-type or table-type table.")
2980 (defconst org-table-line-regexp "^[ \t]*|"
2981 "Detects an org-type table line.")
2982 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2983 "Detects an org-type table line.")
2984 (defconst org-table-hline-regexp "^[ \t]*|-"
2985 "Detects an org-type table hline.")
2986 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2987 "Detects a table-type table hline.")
2988 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2989 "Searching from within a table (any type) this finds the first line
2990 outside the table.")
2991
2992 ;; Autoload the functions in org-table.el that are needed by functions here.
2993
2994 (eval-and-compile
2995 (org-autoload "org-table"
2996 '(org-table-align org-table-begin org-table-blank-field
2997 org-table-convert org-table-convert-region org-table-copy-down
2998 org-table-copy-region org-table-create
2999 org-table-create-or-convert-from-region
3000 org-table-create-with-table.el org-table-current-dline
3001 org-table-cut-region org-table-delete-column org-table-edit-field
3002 org-table-edit-formulas org-table-end org-table-eval-formula
3003 org-table-export org-table-field-info
3004 org-table-get-stored-formulas org-table-goto-column
3005 org-table-hline-and-move org-table-import org-table-insert-column
3006 org-table-insert-hline org-table-insert-row org-table-iterate
3007 org-table-justify-field-maybe org-table-kill-row
3008 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3009 org-table-move-column org-table-move-column-left
3010 org-table-move-column-right org-table-move-row
3011 org-table-move-row-down org-table-move-row-up
3012 org-table-next-field org-table-next-row org-table-paste-rectangle
3013 org-table-previous-field org-table-recalculate
3014 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3015 org-table-toggle-coordinate-overlays
3016 org-table-toggle-formula-debugger org-table-wrap-region
3017 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3018
3019 (defun org-at-table-p (&optional table-type)
3020 "Return t if the cursor is inside an org-type table.
3021 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3022 (if org-enable-table-editor
3023 (save-excursion
3024 (beginning-of-line 1)
3025 (looking-at (if table-type org-table-any-line-regexp
3026 org-table-line-regexp)))
3027 nil))
3028 (defsubst org-table-p () (org-at-table-p))
3029
3030 (defun org-at-table.el-p ()
3031 "Return t if and only if we are at a table.el table."
3032 (and (org-at-table-p 'any)
3033 (save-excursion
3034 (goto-char (org-table-begin 'any))
3035 (looking-at org-table1-hline-regexp))))
3036 (defun org-table-recognize-table.el ()
3037 "If there is a table.el table nearby, recognize it and move into it."
3038 (if org-table-tab-recognizes-table.el
3039 (if (org-at-table.el-p)
3040 (progn
3041 (beginning-of-line 1)
3042 (if (looking-at org-table-dataline-regexp)
3043 nil
3044 (if (looking-at org-table1-hline-regexp)
3045 (progn
3046 (beginning-of-line 2)
3047 (if (looking-at org-table-any-border-regexp)
3048 (beginning-of-line -1)))))
3049 (if (re-search-forward "|" (org-table-end t) t)
3050 (progn
3051 (require 'table)
3052 (if (table--at-cell-p (point))
3053 t
3054 (message "recognizing table.el table...")
3055 (table-recognize-table)
3056 (message "recognizing table.el table...done")))
3057 (error "This should not happen..."))
3058 t)
3059 nil)
3060 nil))
3061
3062 (defun org-at-table-hline-p ()
3063 "Return t if the cursor is inside a hline in a table."
3064 (if org-enable-table-editor
3065 (save-excursion
3066 (beginning-of-line 1)
3067 (looking-at org-table-hline-regexp))
3068 nil))
3069
3070 (defvar org-table-clean-did-remove-column nil)
3071
3072 (defun org-table-map-tables (function)
3073 "Apply FUNCTION to the start of all tables in the buffer."
3074 (save-excursion
3075 (save-restriction
3076 (widen)
3077 (goto-char (point-min))
3078 (while (re-search-forward org-table-any-line-regexp nil t)
3079 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3080 (beginning-of-line 1)
3081 (when (looking-at org-table-line-regexp)
3082 (save-excursion (funcall function))
3083 (or (looking-at org-table-line-regexp)
3084 (forward-char 1)))
3085 (re-search-forward org-table-any-border-regexp nil 1))))
3086 (message "Mapping tables: done"))
3087
3088 ;; Declare and autoload functions from org-exp.el & Co
3089
3090 (declare-function org-default-export-plist "org-exp")
3091 (declare-function org-infile-export-plist "org-exp")
3092 (declare-function org-get-current-options "org-exp")
3093 (eval-and-compile
3094 (org-autoload "org-exp"
3095 '(org-export org-export-visible
3096 org-insert-export-options-template
3097 org-table-clean-before-export))
3098 (org-autoload "org-ascii"
3099 '(org-export-as-ascii org-export-ascii-preprocess
3100 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3101 org-export-region-as-ascii))
3102 (org-autoload "org-html"
3103 '(org-export-as-html-and-open
3104 org-export-as-html-batch org-export-as-html-to-buffer
3105 org-replace-region-by-html org-export-region-as-html
3106 org-export-as-html))
3107 (org-autoload "org-icalendar"
3108 '(org-export-icalendar-this-file
3109 org-export-icalendar-all-agenda-files
3110 org-export-icalendar-combine-agenda-files))
3111 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3112
3113 ;; Declare and autoload functions from org-agenda.el
3114
3115 (eval-and-compile
3116 (org-autoload "org-agenda"
3117 '(org-agenda org-agenda-list org-search-view
3118 org-todo-list org-tags-view org-agenda-list-stuck-projects
3119 org-diary org-agenda-to-appt
3120 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3121
3122 ;; Autoload org-remember
3123
3124 (eval-and-compile
3125 (org-autoload "org-remember"
3126 '(org-remember-insinuate org-remember-annotation
3127 org-remember-apply-template org-remember org-remember-handler)))
3128
3129 ;; Autoload org-clock.el
3130
3131
3132 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3133 (beg end))
3134 (declare-function org-clock-update-mode-line "org-clock" ())
3135 (defvar org-clock-start-time)
3136 (defvar org-clock-marker (make-marker)
3137 "Marker recording the last clock-in.")
3138 (defvar org-clock-hd-marker (make-marker)
3139 "Marker recording the last clock-in, but the headline position.")
3140 (defun org-clock-is-active ()
3141 "Return non-nil if clock is currently running.
3142 The return value is actually the clock marker."
3143 (marker-buffer org-clock-marker))
3144
3145 (eval-and-compile
3146 (org-autoload
3147 "org-clock"
3148 '(org-clock-in org-clock-out org-clock-cancel
3149 org-clock-goto org-clock-sum org-clock-display
3150 org-clock-remove-overlays org-clock-report
3151 org-clocktable-shift org-dblock-write:clocktable
3152 org-get-clocktable)))
3153
3154 (defun org-clock-update-time-maybe ()
3155 "If this is a CLOCK line, update it and return t.
3156 Otherwise, return nil."
3157 (interactive)
3158 (save-excursion
3159 (beginning-of-line 1)
3160 (skip-chars-forward " \t")
3161 (when (looking-at org-clock-string)
3162 (let ((re (concat "[ \t]*" org-clock-string
3163 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3164 "\\([ \t]*=>.*\\)?\\)?"))
3165 ts te h m s neg)
3166 (cond
3167 ((not (looking-at re))
3168 nil)
3169 ((not (match-end 2))
3170 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3171 (> org-clock-marker (point))
3172 (<= org-clock-marker (point-at-eol)))
3173 ;; The clock is running here
3174 (setq org-clock-start-time
3175 (apply 'encode-time
3176 (org-parse-time-string (match-string 1))))
3177 (org-clock-update-mode-line)))
3178 (t
3179 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3180 (end-of-line 1)
3181 (setq ts (match-string 1)
3182 te (match-string 3))
3183 (setq s (- (org-float-time
3184 (apply 'encode-time (org-parse-time-string te)))
3185 (org-float-time
3186 (apply 'encode-time (org-parse-time-string ts))))
3187 neg (< s 0)
3188 s (abs s)
3189 h (floor (/ s 3600))
3190 s (- s (* 3600 h))
3191 m (floor (/ s 60))
3192 s (- s (* 60 s)))
3193 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3194 t))))))
3195
3196 (defun org-check-running-clock ()
3197 "Check if the current buffer contains the running clock.
3198 If yes, offer to stop it and to save the buffer with the changes."
3199 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3200 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3201 (buffer-name))))
3202 (org-clock-out)
3203 (when (y-or-n-p "Save changed buffer?")
3204 (save-buffer))))
3205
3206 (defun org-clocktable-try-shift (dir n)
3207 "Check if this line starts a clock table, if yes, shift the time block."
3208 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3209 (org-clocktable-shift dir n)))
3210
3211 ;; Autoload org-timer.el
3212
3213 (eval-and-compile
3214 (org-autoload
3215 "org-timer"
3216 '(org-timer-start org-timer org-timer-item
3217 org-timer-change-times-in-region
3218 org-timer-set-timer
3219 org-timer-reset-timers
3220 org-timer-show-remaining-time)))
3221
3222 ;; Autoload org-feed.el
3223
3224 (eval-and-compile
3225 (org-autoload
3226 "org-feed"
3227 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3228
3229
3230 ;; Autoload org-indent.el
3231
3232 (eval-and-compile
3233 (org-autoload
3234 "org-indent"
3235 '(org-indent-mode)))
3236
3237 ;; Autoload org-mobile.el
3238
3239 (eval-and-compile
3240 (org-autoload
3241 "org-mobile"
3242 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3243
3244 ;; Autoload archiving code
3245 ;; The stuff that is needed for cycling and tags has to be defined here.
3246
3247 (defgroup org-archive nil
3248 "Options concerning archiving in Org-mode."
3249 :tag "Org Archive"
3250 :group 'org-structure)
3251
3252 (defcustom org-archive-location "%s_archive::"
3253 "The location where subtrees should be archived.
3254
3255 The value of this variable is a string, consisting of two parts,
3256 separated by a double-colon. The first part is a filename and
3257 the second part is a headline.
3258
3259 When the filename is omitted, archiving happens in the same file.
3260 %s in the filename will be replaced by the current file
3261 name (without the directory part). Archiving to a different file
3262 is useful to keep archived entries from contributing to the
3263 Org-mode Agenda.
3264
3265 The archived entries will be filed as subtrees of the specified
3266 headline. When the headline is omitted, the subtrees are simply
3267 filed away at the end of the file, as top-level entries. Also in
3268 the heading you can use %s to represent the file name, this can be
3269 useful when using the same archive for a number of different files.
3270
3271 Here are a few examples:
3272 \"%s_archive::\"
3273 If the current file is Projects.org, archive in file
3274 Projects.org_archive, as top-level trees. This is the default.
3275
3276 \"::* Archived Tasks\"
3277 Archive in the current file, under the top-level headline
3278 \"* Archived Tasks\".
3279
3280 \"~/org/archive.org::\"
3281 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3282
3283 \"~/org/archive.org::From %s\"
3284 Archive in file ~/org/archive.org (absolute path), und headlines
3285 \"From FILENAME\" where file name is the current file name.
3286
3287 \"basement::** Finished Tasks\"
3288 Archive in file ./basement (relative path), as level 3 trees
3289 below the level 2 heading \"** Finished Tasks\".
3290
3291 You may set this option on a per-file basis by adding to the buffer a
3292 line like
3293
3294 #+ARCHIVE: basement::** Finished Tasks
3295
3296 You may also define it locally for a subtree by setting an ARCHIVE property
3297 in the entry. If such a property is found in an entry, or anywhere up
3298 the hierarchy, it will be used."
3299 :group 'org-archive
3300 :type 'string)
3301
3302 (defcustom org-archive-tag "ARCHIVE"
3303 "The tag that marks a subtree as archived.
3304 An archived subtree does not open during visibility cycling, and does
3305 not contribute to the agenda listings.
3306 After changing this, font-lock must be restarted in the relevant buffers to
3307 get the proper fontification."
3308 :group 'org-archive
3309 :group 'org-keywords
3310 :type 'string)
3311
3312 (defcustom org-agenda-skip-archived-trees t
3313 "Non-nil means, the agenda will skip any items located in archived trees.
3314 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3315 variable is no longer recommended, you should leave it at the value t.
3316 Instead, use the key `v' to cycle the archives-mode in the agenda."
3317 :group 'org-archive
3318 :group 'org-agenda-skip
3319 :type 'boolean)
3320
3321 (defcustom org-columns-skip-arrchived-trees t
3322 "Non-nil means, irgnore archived trees when creating column view."
3323 :group 'org-archive
3324 :group 'org-properties
3325 :type 'boolean)
3326
3327 (defcustom org-cycle-open-archived-trees nil
3328 "Non-nil means, `org-cycle' will open archived trees.
3329 An archived tree is a tree marked with the tag ARCHIVE.
3330 When nil, archived trees will stay folded. You can still open them with
3331 normal outline commands like `show-all', but not with the cycling commands."
3332 :group 'org-archive
3333 :group 'org-cycle
3334 :type 'boolean)
3335
3336 (defcustom org-sparse-tree-open-archived-trees nil
3337 "Non-nil means sparse tree construction shows matches in archived trees.
3338 When nil, matches in these trees are highlighted, but the trees are kept in
3339 collapsed state."
3340 :group 'org-archive
3341 :group 'org-sparse-trees
3342 :type 'boolean)
3343
3344 (defun org-cycle-hide-archived-subtrees (state)
3345 "Re-hide all archived subtrees after a visibility state change."
3346 (when (and (not org-cycle-open-archived-trees)
3347 (not (memq state '(overview folded))))
3348 (save-excursion
3349 (let* ((globalp (memq state '(contents all)))
3350 (beg (if globalp (point-min) (point)))
3351 (end (if globalp (point-max) (org-end-of-subtree t))))
3352 (org-hide-archived-subtrees beg end)
3353 (goto-char beg)
3354 (if (looking-at (concat ".*:" org-archive-tag ":"))
3355 (message "%s" (substitute-command-keys
3356 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3357
3358 (defun org-force-cycle-archived ()
3359 "Cycle subtree even if it is archived."
3360 (interactive)
3361 (setq this-command 'org-cycle)
3362 (let ((org-cycle-open-archived-trees t))
3363 (call-interactively 'org-cycle)))
3364
3365 (defun org-hide-archived-subtrees (beg end)
3366 "Re-hide all archived subtrees after a visibility state change."
3367 (save-excursion
3368 (let* ((re (concat ":" org-archive-tag ":")))
3369 (goto-char beg)
3370 (while (re-search-forward re end t)
3371 (and (org-on-heading-p) (hide-subtree))
3372 (org-end-of-subtree t)))))
3373
3374 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3375
3376 (eval-and-compile
3377 (org-autoload "org-archive"
3378 '(org-add-archive-files org-archive-subtree
3379 org-archive-to-archive-sibling org-toggle-archive-tag)))
3380
3381 ;; Autoload Column View Code
3382
3383 (declare-function org-columns-number-to-string "org-colview")
3384 (declare-function org-columns-get-format-and-top-level "org-colview")
3385 (declare-function org-columns-compute "org-colview")
3386
3387 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3388 '(org-columns-number-to-string org-columns-get-format-and-top-level
3389 org-columns-compute org-agenda-columns org-columns-remove-overlays
3390 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3391
3392 ;; Autoload ID code
3393
3394 (declare-function org-id-store-link "org-id")
3395 (declare-function org-id-locations-load "org-id")
3396 (declare-function org-id-locations-save "org-id")
3397 (defvar org-id-track-globally)
3398 (org-autoload "org-id"
3399 '(org-id-get-create org-id-new org-id-copy org-id-get
3400 org-id-get-with-outline-path-completion
3401 org-id-get-with-outline-drilling
3402 org-id-goto org-id-find org-id-store-link))
3403
3404 ;; Autoload Plotting Code
3405
3406 (org-autoload "org-plot"
3407 '(org-plot/gnuplot))
3408
3409 ;;; Variables for pre-computed regular expressions, all buffer local
3410
3411 (defvar org-drawer-regexp nil
3412 "Matches first line of a hidden block.")
3413 (make-variable-buffer-local 'org-drawer-regexp)
3414 (defvar org-todo-regexp nil
3415 "Matches any of the TODO state keywords.")
3416 (make-variable-buffer-local 'org-todo-regexp)
3417 (defvar org-not-done-regexp nil
3418 "Matches any of the TODO state keywords except the last one.")
3419 (make-variable-buffer-local 'org-not-done-regexp)
3420 (defvar org-not-done-heading-regexp nil
3421 "Matches a TODO headline that is not done.")
3422 (make-variable-buffer-local 'org-not-done-regexp)
3423 (defvar org-todo-line-regexp nil
3424 "Matches a headline and puts TODO state into group 2 if present.")
3425 (make-variable-buffer-local 'org-todo-line-regexp)
3426 (defvar org-complex-heading-regexp nil
3427 "Matches a headline and puts everything into groups:
3428 group 1: the stars
3429 group 2: The todo keyword, maybe
3430 group 3: Priority cookie
3431 group 4: True headline
3432 group 5: Tags")
3433 (make-variable-buffer-local 'org-complex-heading-regexp)
3434 (defvar org-complex-heading-regexp-format nil)
3435 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3436 (defvar org-todo-line-tags-regexp nil
3437 "Matches a headline and puts TODO state into group 2 if present.
3438 Also put tags into group 4 if tags are present.")
3439 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3440 (defvar org-nl-done-regexp nil
3441 "Matches newline followed by a headline with the DONE keyword.")
3442 (make-variable-buffer-local 'org-nl-done-regexp)
3443 (defvar org-looking-at-done-regexp nil
3444 "Matches the DONE keyword a point.")
3445 (make-variable-buffer-local 'org-looking-at-done-regexp)
3446 (defvar org-ds-keyword-length 12
3447 "Maximum length of the Deadline and SCHEDULED keywords.")
3448 (make-variable-buffer-local 'org-ds-keyword-length)
3449 (defvar org-deadline-regexp nil
3450 "Matches the DEADLINE keyword.")
3451 (make-variable-buffer-local 'org-deadline-regexp)
3452 (defvar org-deadline-time-regexp nil
3453 "Matches the DEADLINE keyword together with a time stamp.")
3454 (make-variable-buffer-local 'org-deadline-time-regexp)
3455 (defvar org-deadline-line-regexp nil
3456 "Matches the DEADLINE keyword and the rest of the line.")
3457 (make-variable-buffer-local 'org-deadline-line-regexp)
3458 (defvar org-scheduled-regexp nil
3459 "Matches the SCHEDULED keyword.")
3460 (make-variable-buffer-local 'org-scheduled-regexp)
3461 (defvar org-scheduled-time-regexp nil
3462 "Matches the SCHEDULED keyword together with a time stamp.")
3463 (make-variable-buffer-local 'org-scheduled-time-regexp)
3464 (defvar org-closed-time-regexp nil
3465 "Matches the CLOSED keyword together with a time stamp.")
3466 (make-variable-buffer-local 'org-closed-time-regexp)
3467
3468 (defvar org-keyword-time-regexp nil
3469 "Matches any of the 4 keywords, together with the time stamp.")
3470 (make-variable-buffer-local 'org-keyword-time-regexp)
3471 (defvar org-keyword-time-not-clock-regexp nil
3472 "Matches any of the 3 keywords, together with the time stamp.")
3473 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3474 (defvar org-maybe-keyword-time-regexp nil
3475 "Matches a timestamp, possibly preceeded by a keyword.")
3476 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3477 (defvar org-planning-or-clock-line-re nil
3478 "Matches a line with planning or clock info.")
3479 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3480
3481 (defconst org-plain-time-of-day-regexp
3482 (concat
3483 "\\(\\<[012]?[0-9]"
3484 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3485 "\\(--?"
3486 "\\(\\<[012]?[0-9]"
3487 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3488 "\\)?")
3489 "Regular expression to match a plain time or time range.
3490 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3491 groups carry important information:
3492 0 the full match
3493 1 the first time, range or not
3494 8 the second time, if it is a range.")
3495
3496 (defconst org-plain-time-extension-regexp
3497 (concat
3498 "\\(\\<[012]?[0-9]"
3499 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3500 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3501 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3502 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3503 groups carry important information:
3504 0 the full match
3505 7 hours of duration
3506 9 minutes of duration")
3507
3508 (defconst org-stamp-time-of-day-regexp
3509 (concat
3510 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3511 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3512 "\\(--?"
3513 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3514 "Regular expression to match a timestamp time or time range.
3515 After a match, the following groups carry important information:
3516 0 the full match
3517 1 date plus weekday, for backreferencing to make sure both times on same day
3518 2 the first time, range or not
3519 4 the second time, if it is a range.")
3520
3521 (defconst org-startup-options
3522 '(("fold" org-startup-folded t)
3523 ("overview" org-startup-folded t)
3524 ("nofold" org-startup-folded nil)
3525 ("showall" org-startup-folded nil)
3526 ("showeverything" org-startup-folded showeverything)
3527 ("content" org-startup-folded content)
3528 ("indent" org-startup-indented t)
3529 ("noindent" org-startup-indented nil)
3530 ("hidestars" org-hide-leading-stars t)
3531 ("showstars" org-hide-leading-stars nil)
3532 ("odd" org-odd-levels-only t)
3533 ("oddeven" org-odd-levels-only nil)
3534 ("align" org-startup-align-all-tables t)
3535 ("noalign" org-startup-align-all-tables nil)
3536 ("customtime" org-display-custom-times t)
3537 ("logdone" org-log-done time)
3538 ("lognotedone" org-log-done note)
3539 ("nologdone" org-log-done nil)
3540 ("lognoteclock-out" org-log-note-clock-out t)
3541 ("nolognoteclock-out" org-log-note-clock-out nil)
3542 ("logrepeat" org-log-repeat state)
3543 ("lognoterepeat" org-log-repeat note)
3544 ("nologrepeat" org-log-repeat nil)
3545 ("fninline" org-footnote-define-inline t)
3546 ("nofninline" org-footnote-define-inline nil)
3547 ("fnlocal" org-footnote-section nil)
3548 ("fnauto" org-footnote-auto-label t)
3549 ("fnprompt" org-footnote-auto-label nil)
3550 ("fnconfirm" org-footnote-auto-label confirm)
3551 ("fnplain" org-footnote-auto-label plain)
3552 ("fnadjust" org-footnote-auto-adjust t)
3553 ("nofnadjust" org-footnote-auto-adjust nil)
3554 ("constcgs" constants-unit-system cgs)
3555 ("constSI" constants-unit-system SI)
3556 ("noptag" org-tag-persistent-alist nil)
3557 ("hideblocks" org-hide-block-startup t)
3558 ("nohideblocks" org-hide-block-startup nil))
3559 "Variable associated with STARTUP options for org-mode.
3560 Each element is a list of three items: The startup options as written
3561 in the #+STARTUP line, the corresponding variable, and the value to
3562 set this variable to if the option is found. An optional forth element PUSH
3563 means to push this value onto the list in the variable.")
3564
3565 (defun org-set-regexps-and-options ()
3566 "Precompute regular expressions for current buffer."
3567 (when (org-mode-p)
3568 (org-set-local 'org-todo-kwd-alist nil)
3569 (org-set-local 'org-todo-key-alist nil)
3570 (org-set-local 'org-todo-key-trigger nil)
3571 (org-set-local 'org-todo-keywords-1 nil)
3572 (org-set-local 'org-done-keywords nil)
3573 (org-set-local 'org-todo-heads nil)
3574 (org-set-local 'org-todo-sets nil)
3575 (org-set-local 'org-todo-log-states nil)
3576 (org-set-local 'org-file-properties nil)
3577 (org-set-local 'org-file-tags nil)
3578 (let ((re (org-make-options-regexp
3579 '("CATEGORY" "TODO" "COLUMNS"
3580 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3581 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3582 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3583 (splitre "[ \t]+")
3584 kwds kws0 kwsa key log value cat arch tags const links hw dws
3585 tail sep kws1 prio props ftags drawers
3586 ext-setup-or-nil setup-contents (start 0))
3587 (save-excursion
3588 (save-restriction
3589 (widen)
3590 (goto-char (point-min))
3591 (while (or (and ext-setup-or-nil
3592 (string-match re ext-setup-or-nil start)
3593 (setq start (match-end 0)))
3594 (and (setq ext-setup-or-nil nil start 0)
3595 (re-search-forward re nil t)))
3596 (setq key (upcase (match-string 1 ext-setup-or-nil))
3597 value (org-match-string-no-properties 2 ext-setup-or-nil))
3598 (cond
3599 ((equal key "CATEGORY")
3600 (if (string-match "[ \t]+$" value)
3601 (setq value (replace-match "" t t value)))
3602 (setq cat value))
3603 ((member key '("SEQ_TODO" "TODO"))
3604 (push (cons 'sequence (org-split-string value splitre)) kwds))
3605 ((equal key "TYP_TODO")
3606 (push (cons 'type (org-split-string value splitre)) kwds))
3607 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3608 ;; general TODO-like setup
3609 (push (cons (intern (downcase (match-string 1 key)))
3610 (org-split-string value splitre)) kwds))
3611 ((equal key "TAGS")
3612 (setq tags (append tags (if tags '("\\n") nil)
3613 (org-split-string value splitre))))
3614 ((equal key "COLUMNS")
3615 (org-set-local 'org-columns-default-format value))
3616 ((equal key "LINK")
3617 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3618 (push (cons (match-string 1 value)
3619 (org-trim (match-string 2 value)))
3620 links)))
3621 ((equal key "PRIORITIES")
3622 (setq prio (org-split-string value " +")))
3623 ((equal key "PROPERTY")
3624 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3625 (push (cons (match-string 1 value) (match-string 2 value))
3626 props)))
3627 ((equal key "FILETAGS")
3628 (when (string-match "\\S-" value)
3629 (setq ftags
3630 (append
3631 ftags
3632 (apply 'append
3633 (mapcar (lambda (x) (org-split-string x ":"))
3634 (org-split-string value)))))))
3635 ((equal key "DRAWERS")
3636 (setq drawers (org-split-string value splitre)))
3637 ((equal key "CONSTANTS")
3638 (setq const (append const (org-split-string value splitre))))
3639 ((equal key "STARTUP")
3640 (let ((opts (org-split-string value splitre))
3641 l var val)
3642 (while (setq l (pop opts))
3643 (when (setq l (assoc l org-startup-options))
3644 (setq var (nth 1 l) val (nth 2 l))
3645 (if (not (nth 3 l))
3646 (set (make-local-variable var) val)
3647 (if (not (listp (symbol-value var)))
3648 (set (make-local-variable var) nil))
3649 (set (make-local-variable var) (symbol-value var))
3650 (add-to-list var val))))))
3651 ((equal key "ARCHIVE")
3652 (string-match " *$" value)
3653 (setq arch (replace-match "" t t value))
3654 (remove-text-properties 0 (length arch)
3655 '(face t fontified t) arch))
3656 ((equal key "SETUPFILE")
3657 (setq setup-contents (org-file-contents
3658 (expand-file-name
3659 (org-remove-double-quotes value))
3660 'noerror))
3661 (if (not ext-setup-or-nil)
3662 (setq ext-setup-or-nil setup-contents start 0)
3663 (setq ext-setup-or-nil
3664 (concat (substring ext-setup-or-nil 0 start)
3665 "\n" setup-contents "\n"
3666 (substring ext-setup-or-nil start)))))
3667 ))))
3668 (when cat
3669 (org-set-local 'org-category (intern cat))
3670 (push (cons "CATEGORY" cat) props))
3671 (when prio
3672 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3673 (setq prio (mapcar 'string-to-char prio))
3674 (org-set-local 'org-highest-priority (nth 0 prio))
3675 (org-set-local 'org-lowest-priority (nth 1 prio))
3676 (org-set-local 'org-default-priority (nth 2 prio)))
3677 (and props (org-set-local 'org-file-properties (nreverse props)))
3678 (and ftags (org-set-local 'org-file-tags
3679 (mapcar 'org-add-prop-inherited ftags)))
3680 (and drawers (org-set-local 'org-drawers drawers))
3681 (and arch (org-set-local 'org-archive-location arch))
3682 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3683 ;; Process the TODO keywords
3684 (unless kwds
3685 ;; Use the global values as if they had been given locally.
3686 (setq kwds (default-value 'org-todo-keywords))
3687 (if (stringp (car kwds))
3688 (setq kwds (list (cons org-todo-interpretation
3689 (default-value 'org-todo-keywords)))))
3690 (setq kwds (reverse kwds)))
3691 (setq kwds (nreverse kwds))
3692 (let (inter kws kw)
3693 (while (setq kws (pop kwds))
3694 (let ((kws (or
3695 (run-hook-with-args-until-success
3696 'org-todo-setup-filter-hook kws)
3697 kws)))
3698 (setq inter (pop kws) sep (member "|" kws)
3699 kws0 (delete "|" (copy-sequence kws))
3700 kwsa nil
3701 kws1 (mapcar
3702 (lambda (x)
3703 ;; 1 2
3704 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3705 (progn
3706 (setq kw (match-string 1 x)
3707 key (and (match-end 2) (match-string 2 x))
3708 log (org-extract-log-state-settings x))
3709 (push (cons kw (and key (string-to-char key))) kwsa)
3710 (and log (push log org-todo-log-states))
3711 kw)
3712 (error "Invalid TODO keyword %s" x)))
3713 kws0)
3714 kwsa (if kwsa (append '((:startgroup))
3715 (nreverse kwsa)
3716 '((:endgroup))))
3717 hw (car kws1)
3718 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3719 tail (list inter hw (car dws) (org-last dws))))
3720 (add-to-list 'org-todo-heads hw 'append)
3721 (push kws1 org-todo-sets)
3722 (setq org-done-keywords (append org-done-keywords dws nil))
3723 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3724 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3725 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3726 (setq org-todo-sets (nreverse org-todo-sets)
3727 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3728 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3729 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3730 ;; Process the constants
3731 (when const
3732 (let (e cst)
3733 (while (setq e (pop const))
3734 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3735 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3736 (setq org-table-formula-constants-local cst)))
3737
3738 ;; Process the tags.
3739 (when tags
3740 (let (e tgs)
3741 (while (setq e (pop tags))
3742 (cond
3743 ((equal e "{") (push '(:startgroup) tgs))
3744 ((equal e "}") (push '(:endgroup) tgs))
3745 ((equal e "\\n") (push '(:newline) tgs))
3746 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3747 (push (cons (match-string 1 e)
3748 (string-to-char (match-string 2 e)))
3749 tgs))
3750 (t (push (list e) tgs))))
3751 (org-set-local 'org-tag-alist nil)
3752 (while (setq e (pop tgs))
3753 (or (and (stringp (car e))
3754 (assoc (car e) org-tag-alist))
3755 (push e org-tag-alist)))))
3756
3757 ;; Compute the regular expressions and other local variables
3758 (if (not org-done-keywords)
3759 (setq org-done-keywords (and org-todo-keywords-1
3760 (list (org-last org-todo-keywords-1)))))
3761 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3762 (length org-scheduled-string)
3763 (length org-clock-string)
3764 (length org-closed-string)))
3765 org-drawer-regexp
3766 (concat "^[ \t]*:\\("
3767 (mapconcat 'regexp-quote org-drawers "\\|")
3768 "\\):[ \t]*$")
3769 org-not-done-keywords
3770 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3771 org-todo-regexp
3772 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3773 "\\|") "\\)\\>")
3774 org-not-done-regexp
3775 (concat "\\<\\("
3776 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3777 "\\)\\>")
3778 org-not-done-heading-regexp
3779 (concat "^\\(\\*+\\)[ \t]+\\("
3780 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3781 "\\)\\>")
3782 org-todo-line-regexp
3783 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3784 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3785 "\\)\\>\\)?[ \t]*\\(.*\\)")
3786 org-complex-heading-regexp
3787 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3788 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3789 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3790 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3791 org-complex-heading-regexp-format
3792 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3793 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3794 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
3795 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3796 org-nl-done-regexp
3797 (concat "\n\\*+[ \t]+"
3798 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3799 "\\)" "\\>")
3800 org-todo-line-tags-regexp
3801 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3802 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3803 (org-re
3804 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3805 org-looking-at-done-regexp
3806 (concat "^" "\\(?:"
3807 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3808 "\\>")
3809 org-deadline-regexp (concat "\\<" org-deadline-string)
3810 org-deadline-time-regexp
3811 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3812 org-deadline-line-regexp
3813 (concat "\\<\\(" org-deadline-string "\\).*")
3814 org-scheduled-regexp
3815 (concat "\\<" org-scheduled-string)
3816 org-scheduled-time-regexp
3817 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3818 org-closed-time-regexp
3819 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3820 org-keyword-time-regexp
3821 (concat "\\<\\(" org-scheduled-string
3822 "\\|" org-deadline-string
3823 "\\|" org-closed-string
3824 "\\|" org-clock-string "\\)"
3825 " *[[<]\\([^]>]+\\)[]>]")
3826 org-keyword-time-not-clock-regexp
3827 (concat "\\<\\(" org-scheduled-string
3828 "\\|" org-deadline-string
3829 "\\|" org-closed-string
3830 "\\)"
3831 " *[[<]\\([^]>]+\\)[]>]")
3832 org-maybe-keyword-time-regexp
3833 (concat "\\(\\<\\(" org-scheduled-string
3834 "\\|" org-deadline-string
3835 "\\|" org-closed-string
3836 "\\|" org-clock-string "\\)\\)?"
3837 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3838 org-planning-or-clock-line-re
3839 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3840 "\\|" org-deadline-string
3841 "\\|" org-closed-string "\\|" org-clock-string
3842 "\\)\\>\\)")
3843 )
3844 (org-compute-latex-and-specials-regexp)
3845 (org-set-font-lock-defaults))))
3846
3847 (defun org-file-contents (file &optional noerror)
3848 "Return the contents of FILE, as a string."
3849 (if (or (not file)
3850 (not (file-readable-p file)))
3851 (if noerror
3852 (progn
3853 (message "Cannot read file %s" file)
3854 (ding) (sit-for 2)
3855 "")
3856 (error "Cannot read file %s" file))
3857 (with-temp-buffer
3858 (insert-file-contents file)
3859 (buffer-string))))
3860
3861 (defun org-extract-log-state-settings (x)
3862 "Extract the log state setting from a TODO keyword string.
3863 This will extract info from a string like \"WAIT(w@/!)\"."
3864 (let (kw key log1 log2)
3865 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3866 (setq kw (match-string 1 x)
3867 key (and (match-end 2) (match-string 2 x))
3868 log1 (and (match-end 3) (match-string 3 x))
3869 log2 (and (match-end 4) (match-string 4 x)))
3870 (and (or log1 log2)
3871 (list kw
3872 (and log1 (if (equal log1 "!") 'time 'note))
3873 (and log2 (if (equal log2 "!") 'time 'note)))))))
3874
3875 (defun org-remove-keyword-keys (list)
3876 "Remove a pair of parenthesis at the end of each string in LIST."
3877 (mapcar (lambda (x)
3878 (if (string-match "(.*)$" x)
3879 (substring x 0 (match-beginning 0))
3880 x))
3881 list))
3882
3883 ;; FIXME: this could be done much better, using second characters etc.
3884 (defun org-assign-fast-keys (alist)
3885 "Assign fast keys to a keyword-key alist.
3886 Respect keys that are already there."
3887 (let (new e k c c1 c2 (char ?a))
3888 (while (setq e (pop alist))
3889 (cond
3890 ((equal e '(:startgroup)) (push e new))
3891 ((equal e '(:endgroup)) (push e new))
3892 ((equal e '(:newline)) (push e new))
3893 (t
3894 (setq k (car e) c2 nil)
3895 (if (cdr e)
3896 (setq c (cdr e))
3897 ;; automatically assign a character.
3898 (setq c1 (string-to-char
3899 (downcase (substring
3900 k (if (= (string-to-char k) ?@) 1 0)))))
3901 (if (or (rassoc c1 new) (rassoc c1 alist))
3902 (while (or (rassoc char new) (rassoc char alist))
3903 (setq char (1+ char)))
3904 (setq c2 c1))
3905 (setq c (or c2 char)))
3906 (push (cons k c) new))))
3907 (nreverse new)))
3908
3909 ;;; Some variables used in various places
3910
3911 (defvar org-window-configuration nil
3912 "Used in various places to store a window configuration.")
3913 (defvar org-selected-window nil
3914 "Used in various places to store a window configuration.")
3915 (defvar org-finish-function nil
3916 "Function to be called when `C-c C-c' is used.
3917 This is for getting out of special buffers like remember.")
3918
3919
3920 ;; FIXME: Occasionally check by commenting these, to make sure
3921 ;; no other functions uses these, forgetting to let-bind them.
3922 (defvar entry)
3923 (defvar last-state)
3924 (defvar date)
3925
3926 ;; Defined somewhere in this file, but used before definition.
3927 (defvar org-html-entities)
3928 (defvar org-struct-menu)
3929 (defvar org-org-menu)
3930 (defvar org-tbl-menu)
3931 (defvar org-agenda-keymap)
3932
3933 ;;;; Define the Org-mode
3934
3935 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3936 (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."))
3937
3938
3939 ;; We use a before-change function to check if a table might need
3940 ;; an update.
3941 (defvar org-table-may-need-update t
3942 "Indicates that a table might need an update.
3943 This variable is set by `org-before-change-function'.
3944 `org-table-align' sets it back to nil.")
3945 (defun org-before-change-function (beg end)
3946 "Every change indicates that a table might need an update."
3947 (setq org-table-may-need-update t))
3948 (defvar org-mode-map)
3949 (defvar org-mode-hook nil
3950 "Mode hook for Org-mode, run after the mode was turned on.")
3951 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3952 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3953 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
3954 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
3955 (defvar org-table-buffer-is-an nil)
3956 (defconst org-outline-regexp "\\*+ ")
3957
3958 ;;;###autoload
3959 (define-derived-mode org-mode outline-mode "Org"
3960 "Outline-based notes management and organizer, alias
3961 \"Carsten's outline-mode for keeping track of everything.\"
3962
3963 Org-mode develops organizational tasks around a NOTES file which
3964 contains information about projects as plain text. Org-mode is
3965 implemented on top of outline-mode, which is ideal to keep the content
3966 of large files well structured. It supports ToDo items, deadlines and
3967 time stamps, which magically appear in the diary listing of the Emacs
3968 calendar. Tables are easily created with a built-in table editor.
3969 Plain text URL-like links connect to websites, emails (VM), Usenet
3970 messages (Gnus), BBDB entries, and any files related to the project.
3971 For printing and sharing of notes, an Org-mode file (or a part of it)
3972 can be exported as a structured ASCII or HTML file.
3973
3974 The following commands are available:
3975
3976 \\{org-mode-map}"
3977
3978 ;; Get rid of Outline menus, they are not needed
3979 ;; Need to do this here because define-derived-mode sets up
3980 ;; the keymap so late. Still, it is a waste to call this each time
3981 ;; we switch another buffer into org-mode.
3982 (if (featurep 'xemacs)
3983 (when (boundp 'outline-mode-menu-heading)
3984 ;; Assume this is Greg's port, it used easymenu
3985 (easy-menu-remove outline-mode-menu-heading)
3986 (easy-menu-remove outline-mode-menu-show)
3987 (easy-menu-remove outline-mode-menu-hide))
3988 (define-key org-mode-map [menu-bar headings] 'undefined)
3989 (define-key org-mode-map [menu-bar hide] 'undefined)
3990 (define-key org-mode-map [menu-bar show] 'undefined))
3991
3992 (org-load-modules-maybe)
3993 (easy-menu-add org-org-menu)
3994 (easy-menu-add org-tbl-menu)
3995 (org-install-agenda-files-menu)
3996 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3997 (org-add-to-invisibility-spec '(org-cwidth))
3998 (org-add-to-invisibility-spec '(org-hide-block . t))
3999 (when (featurep 'xemacs)
4000 (org-set-local 'line-move-ignore-invisible t))
4001 (org-set-local 'outline-regexp org-outline-regexp)
4002 (org-set-local 'outline-level 'org-outline-level)
4003 (when (and org-ellipsis
4004 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4005 (fboundp 'make-glyph-code))
4006 (unless org-display-table
4007 (setq org-display-table (make-display-table)))
4008 (set-display-table-slot
4009 org-display-table 4
4010 (vconcat (mapcar
4011 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4012 org-ellipsis)))
4013 (if (stringp org-ellipsis) org-ellipsis "..."))))
4014 (setq buffer-display-table org-display-table))
4015 (org-set-regexps-and-options)
4016 (when (and org-tag-faces (not org-tags-special-faces-re))
4017 ;; tag faces set outside customize.... force initialization.
4018 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4019 ;; Calc embedded
4020 (org-set-local 'calc-embedded-open-mode "# ")
4021 (modify-syntax-entry ?# "<")
4022 (modify-syntax-entry ?@ "w")
4023 (if org-startup-truncated (setq truncate-lines t))
4024 (org-set-local 'font-lock-unfontify-region-function
4025 'org-unfontify-region)
4026 ;; Activate before-change-function
4027 (org-set-local 'org-table-may-need-update t)
4028 (org-add-hook 'before-change-functions 'org-before-change-function nil
4029 'local)
4030 ;; Check for running clock before killing a buffer
4031 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4032 ;; Paragraphs and auto-filling
4033 (org-set-autofill-regexps)
4034 (setq indent-line-function 'org-indent-line-function)
4035 (org-update-radio-target-regexp)
4036 ;; Make sure dependence stuff works reliably, even for users who set it
4037 ;; too late :-(
4038 (if org-enforce-todo-dependencies
4039 (add-hook 'org-blocker-hook
4040 'org-block-todo-from-children-or-siblings-or-parent)
4041 (remove-hook 'org-blocker-hook
4042 'org-block-todo-from-children-or-siblings-or-parent))
4043 (if org-enforce-todo-checkbox-dependencies
4044 (add-hook 'org-blocker-hook
4045 'org-block-todo-from-checkboxes)
4046 (remove-hook 'org-blocker-hook
4047 'org-block-todo-from-checkboxes))
4048
4049 ;; Comment characters
4050 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4051 (org-set-local 'comment-padding " ")
4052
4053 ;; Align options lines
4054 (org-set-local
4055 'align-mode-rules-list
4056 '((org-in-buffer-settings
4057 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4058 (modes . '(org-mode)))))
4059
4060 ;; Imenu
4061 (org-set-local 'imenu-create-index-function
4062 'org-imenu-get-tree)
4063
4064 ;; Make isearch reveal context
4065 (if (or (featurep 'xemacs)
4066 (not (boundp 'outline-isearch-open-invisible-function)))
4067 ;; Emacs 21 and XEmacs make use of the hook
4068 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4069 ;; Emacs 22 deals with this through a special variable
4070 (org-set-local 'outline-isearch-open-invisible-function
4071 (lambda (&rest ignore) (org-show-context 'isearch))))
4072
4073 ;; If empty file that did not turn on org-mode automatically, make it to.
4074 (if (and org-insert-mode-line-in-empty-file
4075 (interactive-p)
4076 (= (point-min) (point-max)))
4077 (insert "# -*- mode: org -*-\n\n"))
4078
4079 (unless org-inhibit-startup
4080 (when org-startup-align-all-tables
4081 (let ((bmp (buffer-modified-p)))
4082 (org-table-map-tables 'org-table-align)
4083 (set-buffer-modified-p bmp)))
4084 (when org-startup-indented
4085 (require 'org-indent)
4086 (org-indent-mode 1))
4087 (org-set-startup-visibility)))
4088
4089 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4090
4091 (defun org-current-time ()
4092 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4093 (if (> (car org-time-stamp-rounding-minutes) 1)
4094 (let ((r (car org-time-stamp-rounding-minutes))
4095 (time (decode-time)))
4096 (apply 'encode-time
4097 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4098 (nthcdr 2 time))))
4099 (current-time)))
4100
4101 ;;;; Font-Lock stuff, including the activators
4102
4103 (defvar org-mouse-map (make-sparse-keymap))
4104 (org-defkey org-mouse-map
4105 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4106 (org-defkey org-mouse-map
4107 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4108 (when org-mouse-1-follows-link
4109 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4110 (when org-tab-follows-link
4111 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4112 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4113
4114 (require 'font-lock)
4115
4116 (defconst org-non-link-chars "]\t\n\r<>")
4117 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4118 "shell" "elisp"))
4119 (defvar org-link-types-re nil
4120 "Matches a link that has a url-like prefix like \"http:\"")
4121 (defvar org-link-re-with-space nil
4122 "Matches a link with spaces, optional angular brackets around it.")
4123 (defvar org-link-re-with-space2 nil
4124 "Matches a link with spaces, optional angular brackets around it.")
4125 (defvar org-link-re-with-space3 nil
4126 "Matches a link with spaces, only for internal part in bracket links.")
4127 (defvar org-angle-link-re nil
4128 "Matches link with angular brackets, spaces are allowed.")
4129 (defvar org-plain-link-re nil
4130 "Matches plain link, without spaces.")
4131 (defvar org-bracket-link-regexp nil
4132 "Matches a link in double brackets.")
4133 (defvar org-bracket-link-analytic-regexp nil
4134 "Regular expression used to analyze links.
4135 Here is what the match groups contain after a match:
4136 1: http:
4137 2: http
4138 3: path
4139 4: [desc]
4140 5: desc")
4141 (defvar org-bracket-link-analytic-regexp++ nil
4142 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4143 (defvar org-any-link-re nil
4144 "Regular expression matching any link.")
4145
4146 (defun org-make-link-regexps ()
4147 "Update the link regular expressions.
4148 This should be called after the variable `org-link-types' has changed."
4149 (setq org-link-types-re
4150 (concat
4151 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4152 org-link-re-with-space
4153 (concat
4154 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4155 "\\([^" org-non-link-chars " ]"
4156 "[^" org-non-link-chars "]*"
4157 "[^" org-non-link-chars " ]\\)>?")
4158 org-link-re-with-space2
4159 (concat
4160 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4161 "\\([^" org-non-link-chars " ]"
4162 "[^\t\n\r]*"
4163 "[^" org-non-link-chars " ]\\)>?")
4164 org-link-re-with-space3
4165 (concat
4166 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4167 "\\([^" org-non-link-chars " ]"
4168 "[^\t\n\r]*\\)")
4169 org-angle-link-re
4170 (concat
4171 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4172 "\\([^" org-non-link-chars " ]"
4173 "[^" org-non-link-chars "]*"
4174 "\\)>")
4175 org-plain-link-re
4176 (concat
4177 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4178 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4179 org-bracket-link-regexp
4180 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4181 org-bracket-link-analytic-regexp
4182 (concat
4183 "\\[\\["
4184 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4185 "\\([^]]+\\)"
4186 "\\]"
4187 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4188 "\\]")
4189 org-bracket-link-analytic-regexp++
4190 (concat
4191 "\\[\\["
4192 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4193 "\\([^]]+\\)"
4194 "\\]"
4195 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4196 "\\]")
4197 org-any-link-re
4198 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4199 org-angle-link-re "\\)\\|\\("
4200 org-plain-link-re "\\)")))
4201
4202 (org-make-link-regexps)
4203
4204 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4205 "Regular expression for fast time stamp matching.")
4206 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4207 "Regular expression for fast time stamp matching.")
4208 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4209 "Regular expression matching time strings for analysis.
4210 This one does not require the space after the date, so it can be used
4211 on a string that terminates immediately after the date.")
4212 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4213 "Regular expression matching time strings for analysis.")
4214 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4215 "Regular expression matching time stamps, with groups.")
4216 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4217 "Regular expression matching time stamps (also [..]), with groups.")
4218 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4219 "Regular expression matching a time stamp range.")
4220 (defconst org-tr-regexp-both
4221 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4222 "Regular expression matching a time stamp range.")
4223 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4224 org-ts-regexp "\\)?")
4225 "Regular expression matching a time stamp or time stamp range.")
4226 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4227 org-ts-regexp-both "\\)?")
4228 "Regular expression matching a time stamp or time stamp range.
4229 The time stamps may be either active or inactive.")
4230
4231 (defvar org-emph-face nil)
4232
4233 (defun org-do-emphasis-faces (limit)
4234 "Run through the buffer and add overlays to links."
4235 (let (rtn a)
4236 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4237 (if (not (= (char-after (match-beginning 3))
4238 (char-after (match-beginning 4))))
4239 (progn
4240 (setq rtn t)
4241 (setq a (assoc (match-string 3) org-emphasis-alist))
4242 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4243 'face
4244 (nth 1 a))
4245 (and (nth 4 a)
4246 (org-remove-flyspell-overlays-in
4247 (match-beginning 0) (match-end 0)))
4248 (add-text-properties (match-beginning 2) (match-end 2)
4249 '(font-lock-multiline t))
4250 (when org-hide-emphasis-markers
4251 (add-text-properties (match-end 4) (match-beginning 5)
4252 '(invisible org-link))
4253 (add-text-properties (match-beginning 3) (match-end 3)
4254 '(invisible org-link)))))
4255 (backward-char 1))
4256 rtn))
4257
4258 (defun org-emphasize (&optional char)
4259 "Insert or change an emphasis, i.e. a font like bold or italic.
4260 If there is an active region, change that region to a new emphasis.
4261 If there is no region, just insert the marker characters and position
4262 the cursor between them.
4263 CHAR should be either the marker character, or the first character of the
4264 HTML tag associated with that emphasis. If CHAR is a space, the means
4265 to remove the emphasis of the selected region.
4266 If char is not given (for example in an interactive call) it
4267 will be prompted for."
4268 (interactive)
4269 (let ((eal org-emphasis-alist) e det
4270 (erc org-emphasis-regexp-components)
4271 (prompt "")
4272 (string "") beg end move tag c s)
4273 (if (org-region-active-p)
4274 (setq beg (region-beginning) end (region-end)
4275 string (buffer-substring beg end))
4276 (setq move t))
4277
4278 (while (setq e (pop eal))
4279 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4280 c (aref tag 0))
4281 (push (cons c (string-to-char (car e))) det)
4282 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4283 (substring tag 1)))))
4284 (setq det (nreverse det))
4285 (unless char
4286 (message "%s" (concat "Emphasis marker or tag:" prompt))
4287 (setq char (read-char-exclusive)))
4288 (setq char (or (cdr (assoc char det)) char))
4289 (if (equal char ?\ )
4290 (setq s "" move nil)
4291 (unless (assoc (char-to-string char) org-emphasis-alist)
4292 (error "No such emphasis marker: \"%c\"" char))
4293 (setq s (char-to-string char)))
4294 (while (and (> (length string) 1)
4295 (equal (substring string 0 1) (substring string -1))
4296 (assoc (substring string 0 1) org-emphasis-alist))
4297 (setq string (substring string 1 -1)))
4298 (setq string (concat s string s))
4299 (if beg (delete-region beg end))
4300 (unless (or (bolp)
4301 (string-match (concat "[" (nth 0 erc) "\n]")
4302 (char-to-string (char-before (point)))))
4303 (insert " "))
4304 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4305 (char-to-string (char-after (point))))
4306 (insert " ") (backward-char 1))
4307 (insert string)
4308 (and move (backward-char 1))))
4309
4310 (defconst org-nonsticky-props
4311 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4312
4313 (defsubst org-rear-nonsticky-at (pos)
4314 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4315
4316 (defun org-activate-plain-links (limit)
4317 "Run through the buffer and add overlays to links."
4318 (catch 'exit
4319 (let (f)
4320 (if (re-search-forward org-plain-link-re limit t)
4321 (progn
4322 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4323 (setq f (get-text-property (match-beginning 0) 'face))
4324 (if (or (eq f 'org-tag)
4325 (and (listp f) (memq 'org-tag f)))
4326 nil
4327 (add-text-properties (match-beginning 0) (match-end 0)
4328 (list 'mouse-face 'highlight
4329 'keymap org-mouse-map))
4330 (org-rear-nonsticky-at (match-end 0)))
4331 t)))))
4332
4333 (defun org-activate-code (limit)
4334 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4335 (progn
4336 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4337 (remove-text-properties (match-beginning 0) (match-end 0)
4338 '(display t invisible t intangible t))
4339 t)))
4340
4341 (defun org-fontify-meta-lines-and-blocks (limit)
4342 "Fontify #+ lines and blocks, in the correct ways."
4343 (let ((case-fold-search t))
4344 (if (re-search-forward
4345 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4346 limit t)
4347 (let ((beg (match-beginning 0))
4348 (beg1 (line-beginning-position 2))
4349 (dc1 (downcase (match-string 2)))
4350 (dc3 (downcase (match-string 3)))
4351 end end1 quoting)
4352 (cond
4353 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4354 ;; a single line of backend-specific content
4355 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4356 (remove-text-properties (match-beginning 0) (match-end 0)
4357 '(display t invisible t intangible t))
4358 (add-text-properties (match-beginning 1) (match-end 3)
4359 '(font-lock-fontified t face org-meta-line))
4360 (add-text-properties (match-beginning 6) (match-end 6)
4361 '(font-lock-fontified t face org-block))
4362 t)
4363 ((and (match-end 4) (equal dc3 "begin"))
4364 ;; Truely a block
4365 (setq quoting (member (downcase (match-string 5))
4366 org-protecting-blocks))
4367 (when (re-search-forward
4368 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4369 nil t) ;; on purpose, we look further than LIMIT
4370 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4371 (when quoting
4372 (remove-text-properties beg end
4373 '(display t invisible t intangible t)))
4374 (add-text-properties
4375 beg end
4376 '(font-lock-fontified t font-lock-multiline t))
4377 (add-text-properties beg beg1 '(face org-meta-line))
4378 (add-text-properties end1 end '(face org-meta-line))
4379 (when quoting
4380 (add-text-properties beg1 end1 '(face org-block)))
4381 t))
4382 ((not (member (char-after beg) '(?\ ?\t)))
4383 ;; just any other in-buffer setting, but not indented
4384 (add-text-properties
4385 beg (match-end 0)
4386 '(font-lock-fontified t face org-meta-line))
4387 t)
4388 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4389 "orgtbl:" "tblfm:" "tblname:"))
4390 (and (match-end 4) (equal dc3 "attr")))
4391 (add-text-properties
4392 beg (match-end 0)
4393 '(font-lock-fontified t face org-meta-line))
4394 t)
4395 ((member dc3 '(" " ""))
4396 (add-text-properties
4397 beg (match-end 0)
4398 '(font-lock-fontified t face font-lock-comment-face)))
4399 (t nil))))))
4400
4401 (defun org-activate-angle-links (limit)
4402 "Run through the buffer and add overlays to links."
4403 (if (re-search-forward org-angle-link-re limit t)
4404 (progn
4405 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4406 (add-text-properties (match-beginning 0) (match-end 0)
4407 (list 'mouse-face 'highlight
4408 'keymap org-mouse-map))
4409 (org-rear-nonsticky-at (match-end 0))
4410 t)))
4411
4412 (defun org-activate-footnote-links (limit)
4413 "Run through the buffer and add overlays to links."
4414 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4415 limit t)
4416 (progn
4417 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4418 (add-text-properties (match-beginning 2) (match-end 2)
4419 (list 'mouse-face 'highlight
4420 'keymap org-mouse-map
4421 'help-echo
4422 (if (= (point-at-bol) (match-beginning 2))
4423 "Footnote definition"
4424 "Footnote reference")
4425 ))
4426 (org-rear-nonsticky-at (match-end 2))
4427 t)))
4428
4429 (defun org-activate-bracket-links (limit)
4430 "Run through the buffer and add overlays to bracketed links."
4431 (if (re-search-forward org-bracket-link-regexp limit t)
4432 (let* ((help (concat "LINK: "
4433 (org-match-string-no-properties 1)))
4434 ;; FIXME: above we should remove the escapes.
4435 ;; but that requires another match, protecting match data,
4436 ;; a lot of overhead for font-lock.
4437 (ip (org-maybe-intangible
4438 (list 'invisible 'org-link
4439 'keymap org-mouse-map 'mouse-face 'highlight
4440 'font-lock-multiline t 'help-echo help)))
4441 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4442 'font-lock-multiline t 'help-echo help)))
4443 ;; We need to remove the invisible property here. Table narrowing
4444 ;; may have made some of this invisible.
4445 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4446 (remove-text-properties (match-beginning 0) (match-end 0)
4447 '(invisible nil))
4448 (if (match-end 3)
4449 (progn
4450 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4451 (org-rear-nonsticky-at (match-beginning 3))
4452 (add-text-properties (match-beginning 3) (match-end 3) vp)
4453 (org-rear-nonsticky-at (match-end 3))
4454 (add-text-properties (match-end 3) (match-end 0) ip)
4455 (org-rear-nonsticky-at (match-end 0)))
4456 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4457 (org-rear-nonsticky-at (match-beginning 1))
4458 (add-text-properties (match-beginning 1) (match-end 1) vp)
4459 (org-rear-nonsticky-at (match-end 1))
4460 (add-text-properties (match-end 1) (match-end 0) ip)
4461 (org-rear-nonsticky-at (match-end 0)))
4462 t)))
4463
4464 (defun org-activate-dates (limit)
4465 "Run through the buffer and add overlays to dates."
4466 (if (re-search-forward org-tsr-regexp-both limit t)
4467 (progn
4468 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4469 (add-text-properties (match-beginning 0) (match-end 0)
4470 (list 'mouse-face 'highlight
4471 'keymap org-mouse-map))
4472 (org-rear-nonsticky-at (match-end 0))
4473 (when org-display-custom-times
4474 (if (match-end 3)
4475 (org-display-custom-time (match-beginning 3) (match-end 3)))
4476 (org-display-custom-time (match-beginning 1) (match-end 1)))
4477 t)))
4478
4479 (defvar org-target-link-regexp nil
4480 "Regular expression matching radio targets in plain text.")
4481 (make-variable-buffer-local 'org-target-link-regexp)
4482 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4483 "Regular expression matching a link target.")
4484 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4485 "Regular expression matching a radio target.")
4486 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4487 "Regular expression matching any target.")
4488
4489 (defun org-activate-target-links (limit)
4490 "Run through the buffer and add overlays to target matches."
4491 (when org-target-link-regexp
4492 (let ((case-fold-search t))
4493 (if (re-search-forward org-target-link-regexp limit t)
4494 (progn
4495 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4496 (add-text-properties (match-beginning 0) (match-end 0)
4497 (list 'mouse-face 'highlight
4498 'keymap org-mouse-map
4499 'help-echo "Radio target link"
4500 'org-linked-text t))
4501 (org-rear-nonsticky-at (match-end 0))
4502 t)))))
4503
4504 (defun org-update-radio-target-regexp ()
4505 "Find all radio targets in this file and update the regular expression."
4506 (interactive)
4507 (when (memq 'radio org-activate-links)
4508 (setq org-target-link-regexp
4509 (org-make-target-link-regexp (org-all-targets 'radio)))
4510 (org-restart-font-lock)))
4511
4512 (defun org-hide-wide-columns (limit)
4513 (let (s e)
4514 (setq s (text-property-any (point) (or limit (point-max))
4515 'org-cwidth t))
4516 (when s
4517 (setq e (next-single-property-change s 'org-cwidth))
4518 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4519 (goto-char e)
4520 t)))
4521
4522 (defvar org-latex-and-specials-regexp nil
4523 "Regular expression for highlighting export special stuff.")
4524 (defvar org-match-substring-regexp)
4525 (defvar org-match-substring-with-braces-regexp)
4526
4527 ;; This should be with the exporter code, but we also use if for font-locking
4528 (defconst org-export-html-special-string-regexps
4529 '(("\\\\-" . "&shy;")
4530 ("---\\([^-]\\)" . "&mdash;\\1")
4531 ("--\\([^-]\\)" . "&ndash;\\1")
4532 ("\\.\\.\\." . "&hellip;"))
4533 "Regular expressions for special string conversion.")
4534
4535
4536 (defun org-compute-latex-and-specials-regexp ()
4537 "Compute regular expression for stuff treated specially by exporters."
4538 (if (not org-highlight-latex-fragments-and-specials)
4539 (org-set-local 'org-latex-and-specials-regexp nil)
4540 (require 'org-exp)
4541 (let*
4542 ((matchers (plist-get org-format-latex-options :matchers))
4543 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4544 org-latex-regexps)))
4545 (options (org-combine-plists (org-default-export-plist)
4546 (org-infile-export-plist)))
4547 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4548 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4549 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4550 (org-export-html-expand (plist-get options :expand-quoted-html))
4551 (org-export-with-special-strings (plist-get options :special-strings))
4552 (re-sub
4553 (cond
4554 ((equal org-export-with-sub-superscripts '{})
4555 (list org-match-substring-with-braces-regexp))
4556 (org-export-with-sub-superscripts
4557 (list org-match-substring-regexp))
4558 (t nil)))
4559 (re-latex
4560 (if org-export-with-LaTeX-fragments
4561 (mapcar (lambda (x) (nth 1 x)) latexs)))
4562 (re-macros
4563 (if org-export-with-TeX-macros
4564 (list (concat "\\\\"
4565 (regexp-opt
4566 (append (mapcar 'car org-html-entities)
4567 (if (boundp 'org-latex-entities)
4568 (mapcar (lambda (x)
4569 (or (car-safe x) x))
4570 org-latex-entities)
4571 nil))
4572 'words))) ; FIXME
4573 ))
4574 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4575 (re-special (if org-export-with-special-strings
4576 (mapcar (lambda (x) (car x))
4577 org-export-html-special-string-regexps)))
4578 (re-rest
4579 (delq nil
4580 (list
4581 (if org-export-html-expand "@<[^>\n]+>")
4582 ))))
4583 (org-set-local
4584 'org-latex-and-specials-regexp
4585 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4586 re-rest) "\\|")))))
4587
4588 (defun org-do-latex-and-special-faces (limit)
4589 "Run through the buffer and add overlays to links."
4590 (when org-latex-and-specials-regexp
4591 (let (rtn d)
4592 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4593 limit t))
4594 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4595 'face))
4596 '(org-code org-verbatim underline)))
4597 (progn
4598 (setq rtn t
4599 d (cond ((member (char-after (1+ (match-beginning 0)))
4600 '(?_ ?^)) 1)
4601 (t 0)))
4602 (font-lock-prepend-text-property
4603 (+ d (match-beginning 0)) (match-end 0)
4604 'face 'org-latex-and-export-specials)
4605 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4606 '(font-lock-multiline t)))))
4607 rtn)))
4608
4609 (defun org-restart-font-lock ()
4610 "Restart font-lock-mode, to force refontification."
4611 (when (and (boundp 'font-lock-mode) font-lock-mode)
4612 (font-lock-mode -1)
4613 (font-lock-mode 1)))
4614
4615 (defun org-all-targets (&optional radio)
4616 "Return a list of all targets in this file.
4617 With optional argument RADIO, only find radio targets."
4618 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4619 rtn)
4620 (save-excursion
4621 (goto-char (point-min))
4622 (while (re-search-forward re nil t)
4623 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4624 rtn)))
4625
4626 (defun org-make-target-link-regexp (targets)
4627 "Make regular expression matching all strings in TARGETS.
4628 The regular expression finds the targets also if there is a line break
4629 between words."
4630 (and targets
4631 (concat
4632 "\\<\\("
4633 (mapconcat
4634 (lambda (x)
4635 (while (string-match " +" x)
4636 (setq x (replace-match "\\s-+" t t x)))
4637 x)
4638 targets
4639 "\\|")
4640 "\\)\\>")))
4641
4642 (defun org-activate-tags (limit)
4643 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4644 (progn
4645 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4646 (add-text-properties (match-beginning 1) (match-end 1)
4647 (list 'mouse-face 'highlight
4648 'keymap org-mouse-map))
4649 (org-rear-nonsticky-at (match-end 1))
4650 t)))
4651
4652 (defun org-outline-level ()
4653 (save-excursion
4654 (looking-at outline-regexp)
4655 (if (match-beginning 1)
4656 (+ (org-get-string-indentation (match-string 1)) 1000)
4657 (1- (- (match-end 0) (match-beginning 0))))))
4658
4659 (defvar org-font-lock-keywords nil)
4660
4661 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4662 "Regular expression matching a property line.")
4663
4664 (defvar org-font-lock-hook nil
4665 "Functions to be called for special font lock stuff.")
4666
4667 (defun org-font-lock-hook (limit)
4668 (run-hook-with-args 'org-font-lock-hook limit))
4669
4670 (defun org-set-font-lock-defaults ()
4671 (let* ((em org-fontify-emphasized-text)
4672 (lk org-activate-links)
4673 (org-font-lock-extra-keywords
4674 (list
4675 ;; Call the hook
4676 '(org-font-lock-hook)
4677 ;; Headlines
4678 `(,(if org-fontify-whole-heading-line
4679 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4680 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4681 (1 (org-get-level-face 1))
4682 (2 (org-get-level-face 2))
4683 (3 (org-get-level-face 3)))
4684 ;; Table lines
4685 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4686 (1 'org-table t))
4687 ;; Table internals
4688 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4689 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4690 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4691 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4692 ;; Drawers
4693 (list org-drawer-regexp '(0 'org-special-keyword t))
4694 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4695 ;; Properties
4696 (list org-property-re
4697 '(1 'org-special-keyword t)
4698 '(3 'org-property-value t))
4699 ;; Links
4700 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4701 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4702 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4703 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4704 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4705 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4706 (if (memq 'footnote lk) '(org-activate-footnote-links
4707 (2 'org-footnote t)))
4708 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4709 '(org-hide-wide-columns (0 nil append))
4710 ;; TODO lines
4711 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4712 '(1 (org-get-todo-face 1) t))
4713 ;; DONE
4714 (if org-fontify-done-headline
4715 (list (concat "^[*]+ +\\<\\("
4716 (mapconcat 'regexp-quote org-done-keywords "\\|")
4717 "\\)\\(.*\\)")
4718 '(2 'org-headline-done t))
4719 nil)
4720 ;; Priorities
4721 '(org-font-lock-add-priority-faces)
4722 ;; Tags
4723 '(org-font-lock-add-tag-faces)
4724 ;; Special keywords
4725 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4726 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4727 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4728 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4729 ;; Emphasis
4730 (if em
4731 (if (featurep 'xemacs)
4732 '(org-do-emphasis-faces (0 nil append))
4733 '(org-do-emphasis-faces)))
4734 ;; Checkboxes
4735 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4736 2 'org-checkbox prepend)
4737 (if org-provide-checkbox-statistics
4738 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4739 (0 (org-get-checkbox-statistics-face) t)))
4740 ;; Description list items
4741 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4742 2 'bold prepend)
4743 ;; ARCHIVEd headings
4744 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4745 '(1 'org-archived prepend))
4746 ;; Specials
4747 '(org-do-latex-and-special-faces)
4748 ;; Code
4749 '(org-activate-code (1 'org-code t))
4750 ;; COMMENT
4751 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4752 "\\|" org-quote-string "\\)\\>")
4753 '(1 'org-special-keyword t))
4754 '("^#.*" (0 'font-lock-comment-face t))
4755 ;; Blocks and meta lines
4756 '(org-fontify-meta-lines-and-blocks)
4757 )))
4758 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4759 ;; Now set the full font-lock-keywords
4760 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4761 (org-set-local 'font-lock-defaults
4762 '(org-font-lock-keywords t nil nil backward-paragraph))
4763 (kill-local-variable 'font-lock-keywords) nil))
4764
4765 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4766 "Fontify string S like in Org-mode"
4767 (with-temp-buffer
4768 (insert s)
4769 (let ((org-odd-levels-only odd-levels))
4770 (org-mode)
4771 (font-lock-fontify-buffer)
4772 (buffer-string))))
4773
4774 (defvar org-m nil)
4775 (defvar org-l nil)
4776 (defvar org-f nil)
4777 (defun org-get-level-face (n)
4778 "Get the right face for match N in font-lock matching of headlines."
4779 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4780 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4781 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4782 (cond
4783 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4784 ((eq n 2) org-f)
4785 (t (if org-level-color-stars-only nil org-f))))
4786
4787 (defun org-get-todo-face (kwd)
4788 "Get the right face for a TODO keyword KWD.
4789 If KWD is a number, get the corresponding match group."
4790 (if (numberp kwd) (setq kwd (match-string kwd)))
4791 (or (cdr (assoc kwd org-todo-keyword-faces))
4792 (and (member kwd org-done-keywords) 'org-done)
4793 'org-todo))
4794
4795 (defun org-font-lock-add-tag-faces (limit)
4796 "Add the special tag faces."
4797 (when (and org-tag-faces org-tags-special-faces-re)
4798 (while (re-search-forward org-tags-special-faces-re limit t)
4799 (add-text-properties (match-beginning 1) (match-end 1)
4800 (list 'face (org-get-tag-face 1)
4801 'font-lock-fontified t))
4802 (backward-char 1))))
4803
4804 (defun org-font-lock-add-priority-faces (limit)
4805 "Add the special priority faces."
4806 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4807 (add-text-properties
4808 (match-beginning 0) (match-end 0)
4809 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4810 org-priority-faces))
4811 'org-special-keyword)
4812 'font-lock-fontified t))))
4813
4814 (defun org-get-tag-face (kwd)
4815 "Get the right face for a TODO keyword KWD.
4816 If KWD is a number, get the corresponding match group."
4817 (if (numberp kwd) (setq kwd (match-string kwd)))
4818 (or (cdr (assoc kwd org-tag-faces))
4819 'org-tag))
4820
4821 (defun org-unfontify-region (beg end &optional maybe_loudly)
4822 "Remove fontification and activation overlays from links."
4823 (font-lock-default-unfontify-region beg end)
4824 (let* ((buffer-undo-list t)
4825 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4826 (inhibit-modification-hooks t)
4827 deactivate-mark buffer-file-name buffer-file-truename)
4828 (remove-text-properties beg end
4829 '(mouse-face t keymap t org-linked-text t
4830 invisible t intangible t
4831 line-prefix t wrap-prefix t
4832 org-no-flyspell t))))
4833
4834 ;;;; Visibility cycling, including org-goto and indirect buffer
4835
4836 ;;; Cycling
4837
4838 (defvar org-cycle-global-status nil)
4839 (make-variable-buffer-local 'org-cycle-global-status)
4840 (defvar org-cycle-subtree-status nil)
4841 (make-variable-buffer-local 'org-cycle-subtree-status)
4842
4843 ;;;###autoload
4844
4845 (defvar org-inlinetask-min-level)
4846
4847 (defun org-cycle (&optional arg)
4848 "TAB-action and visibility cycling for Org-mode.
4849
4850 This is the command invoked in Org-mode by the TAB key. Its main purpose
4851 is outine visibility cycling, but it also invokes other actions
4852 in special contexts.
4853
4854 - When this function is called with a prefix argument, rotate the entire
4855 buffer through 3 states (global cycling)
4856 1. OVERVIEW: Show only top-level headlines.
4857 2. CONTENTS: Show all headlines of all levels, but no body text.
4858 3. SHOW ALL: Show everything.
4859 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4860 determined by the variable `org-startup-folded', and by any VISIBILITY
4861 properties in the buffer.
4862 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4863 including any drawers.
4864
4865 - When inside a table, re-align the table and move to the next field.
4866
4867 - When point is at the beginning of a headline, rotate the subtree started
4868 by this line through 3 different states (local cycling)
4869 1. FOLDED: Only the main headline is shown.
4870 2. CHILDREN: The main headline and the direct children are shown.
4871 From this state, you can move to one of the children
4872 and zoom in further.
4873 3. SUBTREE: Show the entire subtree, including body text.
4874 If there is no subtree, switch directly from CHILDREN to FOLDED.
4875
4876 - When there is a numeric prefix, go up to a heading with level ARG, do
4877 a `show-subtree' and return to the previous cursor position. If ARG
4878 is negative, go up that many levels.
4879
4880 - When point is not at the beginning of a headline, execute the global
4881 binding for TAB, which is re-indenting the line. See the option
4882 `org-cycle-emulate-tab' for details.
4883
4884 - Special case: if point is at the beginning of the buffer and there is
4885 no headline in line 1, this function will act as if called with prefix arg.
4886 But only if also the variable `org-cycle-global-at-bob' is t."
4887 (interactive "P")
4888 (org-load-modules-maybe)
4889 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4890 (let* ((limit-level
4891 (or org-cycle-max-level
4892 (and (boundp 'org-inlinetask-min-level)
4893 org-inlinetask-min-level
4894 (1- org-inlinetask-min-level))))
4895 (nstars (and limit-level
4896 (if org-odd-levels-only
4897 (and limit-level (1- (* limit-level 2)))
4898 limit-level)))
4899 (outline-regexp
4900 (cond
4901 ((not (org-mode-p)) outline-regexp)
4902 ((or (eq org-cycle-include-plain-lists 'integrate)
4903 (and org-cycle-include-plain-lists (org-at-item-p)))
4904 (concat "\\(?:\\*"
4905 (if nstars (format "\\{1,%d\\}" nstars) "+")
4906 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4907 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4908 (bob-special (and org-cycle-global-at-bob (bobp)
4909 (not (looking-at outline-regexp))))
4910 (org-cycle-hook
4911 (if bob-special
4912 (delq 'org-optimize-window-after-visibility-change
4913 (copy-sequence org-cycle-hook))
4914 org-cycle-hook))
4915 (pos (point)))
4916
4917 (if (or bob-special (equal arg '(4)))
4918 ;; special case: use global cycling
4919 (setq arg t))
4920
4921 (cond
4922
4923 ((equal arg '(16))
4924 (org-set-startup-visibility)
4925 (message "Startup visibility, plus VISIBILITY properties"))
4926
4927 ((equal arg '(64))
4928 (show-all)
4929 (message "Entire buffer visible, including drawers"))
4930
4931 ((org-at-table-p 'any)
4932 ;; Enter the table or move to the next field in the table
4933 (or (org-table-recognize-table.el)
4934 (progn
4935 (if arg (org-table-edit-field t)
4936 (org-table-justify-field-maybe)
4937 (call-interactively 'org-table-next-field)))))
4938
4939 ((run-hook-with-args-until-success
4940 'org-tab-after-check-for-table-hook))
4941
4942 ((eq arg t) ;; Global cycling
4943 (org-cycle-internal-global))
4944
4945 ((and org-drawers org-drawer-regexp
4946 (save-excursion
4947 (beginning-of-line 1)
4948 (looking-at org-drawer-regexp)))
4949 ;; Toggle block visibility
4950 (org-flag-drawer
4951 (not (get-char-property (match-end 0) 'invisible))))
4952
4953 ((integerp arg)
4954 ;; Show-subtree, ARG levels up from here.
4955 (save-excursion
4956 (org-back-to-heading)
4957 (outline-up-heading (if (< arg 0) (- arg)
4958 (- (funcall outline-level) arg)))
4959 (org-show-subtree)))
4960
4961 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4962 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4963
4964 (org-cycle-internal-local))
4965
4966 ;; TAB emulation and template completion
4967 (buffer-read-only (org-back-to-heading))
4968
4969 ((run-hook-with-args-until-success
4970 'org-tab-after-check-for-cycling-hook))
4971
4972 ((org-try-structure-completion))
4973
4974 ((org-try-cdlatex-tab))
4975
4976 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4977 (or (not (bolp))
4978 (not (looking-at outline-regexp))))
4979 (call-interactively (global-key-binding "\t")))
4980
4981 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4982 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4983 (or (and (eq org-cycle-emulate-tab 'white)
4984 (= (match-end 0) (point-at-eol)))
4985 (and (eq org-cycle-emulate-tab 'whitestart)
4986 (>= (match-end 0) pos))))
4987 t
4988 (eq org-cycle-emulate-tab t))
4989 (call-interactively (global-key-binding "\t")))
4990
4991 (t (save-excursion
4992 (org-back-to-heading)
4993 (org-cycle)))))))
4994
4995 (defun org-cycle-internal-global ()
4996 "Do the global cycling action."
4997 (cond
4998 ((and (eq last-command this-command)
4999 (eq org-cycle-global-status 'overview))
5000 ;; We just created the overview - now do table of contents
5001 ;; This can be slow in very large buffers, so indicate action
5002 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5003 (message "CONTENTS...")
5004 (org-content)
5005 (message "CONTENTS...done")
5006 (setq org-cycle-global-status 'contents)
5007 (run-hook-with-args 'org-cycle-hook 'contents))
5008
5009 ((and (eq last-command this-command)
5010 (eq org-cycle-global-status 'contents))
5011 ;; We just showed the table of contents - now show everything
5012 (run-hook-with-args 'org-pre-cycle-hook 'all)
5013 (show-all)
5014 (message "SHOW ALL")
5015 (setq org-cycle-global-status 'all)
5016 (run-hook-with-args 'org-cycle-hook 'all))
5017
5018 (t
5019 ;; Default action: go to overview
5020 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5021 (org-overview)
5022 (message "OVERVIEW")
5023 (setq org-cycle-global-status 'overview)
5024 (run-hook-with-args 'org-cycle-hook 'overview))))
5025
5026 (defun org-cycle-internal-local ()
5027 "Do the local cycling action."
5028 (org-back-to-heading)
5029 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5030 ;; First, some boundaries
5031 (save-excursion
5032 (org-back-to-heading)
5033 (setq level (funcall outline-level))
5034 (save-excursion
5035 (beginning-of-line 2)
5036 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5037 ; XEmacs does not have `next-single-char-property-change'
5038 ; I'm not sure about Emacs 21.
5039 (while (and (not (eobp)) ;; this is like `next-line'
5040 (get-char-property (1- (point)) 'invisible))
5041 (beginning-of-line 2))
5042 (while (and (not (eobp)) ;; this is like `next-line'
5043 (get-char-property (1- (point)) 'invisible))
5044 (goto-char (next-single-char-property-change (point) 'invisible))
5045 ;;;??? (or (bolp) (beginning-of-line 2))))
5046 (and (eolp) (beginning-of-line 2))))
5047 (setq eol (point)))
5048 (outline-end-of-heading) (setq eoh (point))
5049 (save-excursion
5050 (outline-next-heading)
5051 (setq has-children (and (org-at-heading-p t)
5052 (> (funcall outline-level) level))))
5053 (org-end-of-subtree t)
5054 (unless (eobp)
5055 (skip-chars-forward " \t\n")
5056 (beginning-of-line 1) ; in case this is an item
5057 )
5058 (setq eos (if (eobp) (point) (1- (point)))))
5059 ;; Find out what to do next and set `this-command'
5060 (cond
5061 ((= eos eoh)
5062 ;; Nothing is hidden behind this heading
5063 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5064 (message "EMPTY ENTRY")
5065 (setq org-cycle-subtree-status nil)
5066 (save-excursion
5067 (goto-char eos)
5068 (outline-next-heading)
5069 (if (org-invisible-p) (org-flag-heading nil))))
5070 ((and (or (>= eol eos)
5071 (not (string-match "\\S-" (buffer-substring eol eos))))
5072 (or has-children
5073 (not (setq children-skipped
5074 org-cycle-skip-children-state-if-no-children))))
5075 ;; Entire subtree is hidden in one line: children view
5076 (run-hook-with-args 'org-pre-cycle-hook 'children)
5077 (org-show-entry)
5078 (show-children)
5079 (message "CHILDREN")
5080 (save-excursion
5081 (goto-char eos)
5082 (outline-next-heading)
5083 (if (org-invisible-p) (org-flag-heading nil)))
5084 (setq org-cycle-subtree-status 'children)
5085 (run-hook-with-args 'org-cycle-hook 'children))
5086 ((or children-skipped
5087 (and (eq last-command this-command)
5088 (eq org-cycle-subtree-status 'children)))
5089 ;; We just showed the children, or no children are there,
5090 ;; now show everything.
5091 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5092 (org-show-subtree)
5093 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5094 (setq org-cycle-subtree-status 'subtree)
5095 (run-hook-with-args 'org-cycle-hook 'subtree))
5096 (t
5097 ;; Default action: hide the subtree.
5098 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5099 (hide-subtree)
5100 (message "FOLDED")
5101 (setq org-cycle-subtree-status 'folded)
5102 (run-hook-with-args 'org-cycle-hook 'folded)))))
5103
5104 ;;;###autoload
5105 (defun org-global-cycle (&optional arg)
5106 "Cycle the global visibility. For details see `org-cycle'.
5107 With C-u prefix arg, switch to startup visibility.
5108 With a numeric prefix, show all headlines up to that level."
5109 (interactive "P")
5110 (let ((org-cycle-include-plain-lists
5111 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5112 (cond
5113 ((integerp arg)
5114 (show-all)
5115 (hide-sublevels arg)
5116 (setq org-cycle-global-status 'contents))
5117 ((equal arg '(4))
5118 (org-set-startup-visibility)
5119 (message "Startup visibility, plus VISIBILITY properties."))
5120 (t
5121 (org-cycle '(4))))))
5122
5123 (defun org-set-startup-visibility ()
5124 "Set the visibility required by startup options and properties."
5125 (cond
5126 ((eq org-startup-folded t)
5127 (org-cycle '(4)))
5128 ((eq org-startup-folded 'content)
5129 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5130 (org-cycle '(4)) (org-cycle '(4)))))
5131 (unless (eq org-startup-folded 'showeverything)
5132 (if org-hide-block-startup (org-hide-block-all))
5133 (org-set-visibility-according-to-property 'no-cleanup)
5134 (org-cycle-hide-archived-subtrees 'all)
5135 (org-cycle-hide-drawers 'all)
5136 (org-cycle-show-empty-lines 'all)))
5137
5138 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5139 "Switch subtree visibilities according to :VISIBILITY: property."
5140 (interactive)
5141 (let (org-show-entry-below state)
5142 (save-excursion
5143 (goto-char (point-min))
5144 (while (re-search-forward
5145 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5146 nil t)
5147 (setq state (match-string 1))
5148 (save-excursion
5149 (org-back-to-heading t)
5150 (hide-subtree)
5151 (org-reveal)
5152 (cond
5153 ((equal state '("fold" "folded"))
5154 (hide-subtree))
5155 ((equal state "children")
5156 (org-show-hidden-entry)
5157 (show-children))
5158 ((equal state "content")
5159 (save-excursion
5160 (save-restriction
5161 (org-narrow-to-subtree)
5162 (org-content))))
5163 ((member state '("all" "showall"))
5164 (show-subtree)))))
5165 (unless no-cleanup
5166 (org-cycle-hide-archived-subtrees 'all)
5167 (org-cycle-hide-drawers 'all)
5168 (org-cycle-show-empty-lines 'all)))))
5169
5170 (defun org-overview ()
5171 "Switch to overview mode, showing only top-level headlines.
5172 Really, this shows all headlines with level equal or greater than the level
5173 of the first headline in the buffer. This is important, because if the
5174 first headline is not level one, then (hide-sublevels 1) gives confusing
5175 results."
5176 (interactive)
5177 (let ((level (save-excursion
5178 (goto-char (point-min))
5179 (if (re-search-forward (concat "^" outline-regexp) nil t)
5180 (progn
5181 (goto-char (match-beginning 0))
5182 (funcall outline-level))))))
5183 (and level (hide-sublevels level))))
5184
5185 (defun org-content (&optional arg)
5186 "Show all headlines in the buffer, like a table of contents.
5187 With numerical argument N, show content up to level N."
5188 (interactive "P")
5189 (save-excursion
5190 ;; Visit all headings and show their offspring
5191 (and (integerp arg) (org-overview))
5192 (goto-char (point-max))
5193 (catch 'exit
5194 (while (and (progn (condition-case nil
5195 (outline-previous-visible-heading 1)
5196 (error (goto-char (point-min))))
5197 t)
5198 (looking-at outline-regexp))
5199 (if (integerp arg)
5200 (show-children (1- arg))
5201 (show-branches))
5202 (if (bobp) (throw 'exit nil))))))
5203
5204
5205 (defun org-optimize-window-after-visibility-change (state)
5206 "Adjust the window after a change in outline visibility.
5207 This function is the default value of the hook `org-cycle-hook'."
5208 (when (get-buffer-window (current-buffer))
5209 (cond
5210 ((eq state 'content) nil)
5211 ((eq state 'all) nil)
5212 ((eq state 'folded) nil)
5213 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5214 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5215
5216 ;; FIXME: no longer in use
5217 (defun org-compact-display-after-subtree-move ()
5218 "Show a compacter version of the tree of the entry's parent."
5219 (save-excursion
5220 (if (org-up-heading-safe)
5221 (progn
5222 (hide-subtree)
5223 (show-entry)
5224 (show-children)
5225 (org-cycle-show-empty-lines 'children)
5226 (org-cycle-hide-drawers 'children))
5227 (org-overview))))
5228
5229 (defun org-remove-empty-overlays-at (pos)
5230 "Remove outline overlays that do not contain non-white stuff."
5231 (mapc
5232 (lambda (o)
5233 (and (eq 'outline (org-overlay-get o 'invisible))
5234 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5235 (org-overlay-end o))))
5236 (org-delete-overlay o)))
5237 (org-overlays-at pos)))
5238
5239 (defun org-clean-visibility-after-subtree-move ()
5240 "Fix visibility issues after moving a subtree."
5241 ;; First, find a reasonable region to look at:
5242 ;; Start two siblings above, end three below
5243 (let* ((beg (save-excursion
5244 (and (org-get-last-sibling)
5245 (org-get-last-sibling))
5246 (point)))
5247 (end (save-excursion
5248 (and (org-get-next-sibling)
5249 (org-get-next-sibling)
5250 (org-get-next-sibling))
5251 (if (org-at-heading-p)
5252 (point-at-eol)
5253 (point))))
5254 (level (looking-at "\\*+"))
5255 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5256 (save-excursion
5257 (save-restriction
5258 (narrow-to-region beg end)
5259 (when re
5260 ;; Properly fold already folded siblings
5261 (goto-char (point-min))
5262 (while (re-search-forward re nil t)
5263 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5264 (hide-entry))))
5265 (org-cycle-show-empty-lines 'overview)
5266 (org-cycle-hide-drawers 'overview)))))
5267
5268 (defun org-cycle-show-empty-lines (state)
5269 "Show empty lines above all visible headlines.
5270 The region to be covered depends on STATE when called through
5271 `org-cycle-hook'. Lisp program can use t for STATE to get the
5272 entire buffer covered. Note that an empty line is only shown if there
5273 are at least `org-cycle-separator-lines' empty lines before the headline."
5274 (when (not (= org-cycle-separator-lines 0))
5275 (save-excursion
5276 (let* ((n (abs org-cycle-separator-lines))
5277 (re (cond
5278 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5279 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5280 (t (let ((ns (number-to-string (- n 2))))
5281 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5282 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5283 beg end b e)
5284 (cond
5285 ((memq state '(overview contents t))
5286 (setq beg (point-min) end (point-max)))
5287 ((memq state '(children folded))
5288 (setq beg (point) end (progn (org-end-of-subtree t t)
5289 (beginning-of-line 2)
5290 (point)))))
5291 (when beg
5292 (goto-char beg)
5293 (while (re-search-forward re end t)
5294 (unless (get-char-property (match-end 1) 'invisible)
5295 (setq e (match-end 1))
5296 (if (< org-cycle-separator-lines 0)
5297 (setq b (save-excursion
5298 (goto-char (match-beginning 0))
5299 (org-back-over-empty-lines)
5300 (if (save-excursion
5301 (goto-char (max (point-min) (1- (point))))
5302 (org-on-heading-p))
5303 (1- (point))
5304 (point))))
5305 (setq b (match-beginning 1)))
5306 (outline-flag-region b e nil)))))))
5307 ;; Never hide empty lines at the end of the file.
5308 (save-excursion
5309 (goto-char (point-max))
5310 (outline-previous-heading)
5311 (outline-end-of-heading)
5312 (if (and (looking-at "[ \t\n]+")
5313 (= (match-end 0) (point-max)))
5314 (outline-flag-region (point) (match-end 0) nil))))
5315
5316 (defun org-show-empty-lines-in-parent ()
5317 "Move to the parent and re-show empty lines before visible headlines."
5318 (save-excursion
5319 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5320 (org-cycle-show-empty-lines context))))
5321
5322 (defun org-cycle-hide-drawers (state)
5323 "Re-hide all drawers after a visibility state change."
5324 (when (and (org-mode-p)
5325 (not (memq state '(overview folded contents))))
5326 (save-excursion
5327 (let* ((globalp (memq state '(contents all)))
5328 (beg (if globalp (point-min) (point)))
5329 (end (if globalp (point-max)
5330 (if (eq state 'children)
5331 (save-excursion (outline-next-heading) (point))
5332 (org-end-of-subtree t)))))
5333 (goto-char beg)
5334 (while (re-search-forward org-drawer-regexp end t)
5335 (org-flag-drawer t))))))
5336
5337 (defun org-flag-drawer (flag)
5338 (save-excursion
5339 (beginning-of-line 1)
5340 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5341 (let ((b (match-end 0))
5342 (outline-regexp org-outline-regexp))
5343 (if (re-search-forward
5344 "^[ \t]*:END:"
5345 (save-excursion (outline-next-heading) (point)) t)
5346 (outline-flag-region b (point-at-eol) flag)
5347 (error ":END: line missing at position %s" b))))))
5348
5349 (defun org-subtree-end-visible-p ()
5350 "Is the end of the current subtree visible?"
5351 (pos-visible-in-window-p
5352 (save-excursion (org-end-of-subtree t) (point))))
5353
5354 (defun org-first-headline-recenter (&optional N)
5355 "Move cursor to the first headline and recenter the headline.
5356 Optional argument N means, put the headline into the Nth line of the window."
5357 (goto-char (point-min))
5358 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5359 (beginning-of-line)
5360 (recenter (prefix-numeric-value N))))
5361
5362 ;;; Folding of blocks
5363
5364 (defconst org-block-regexp
5365
5366 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5367 "Regular expression for hiding blocks.")
5368
5369 (defvar org-hide-block-overlays nil
5370 "Overays hiding blocks.")
5371 (make-variable-buffer-local 'org-hide-block-overlays)
5372
5373 (defun org-block-map (function &optional start end)
5374 "Call func at the head of all source blocks in the current
5375 buffer. Optional arguments START and END can be used to limit
5376 the range."
5377 (let ((start (or start (point-min)))
5378 (end (or end (point-max))))
5379 (save-excursion
5380 (goto-char start)
5381 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5382 (save-excursion
5383 (save-match-data
5384 (goto-char (match-beginning 0))
5385 (funcall function)))))))
5386
5387 (defun org-hide-block-toggle-all ()
5388 "Toggle the visibility of all blocks in the current buffer."
5389 (org-block-map #'org-hide-block-toggle))
5390
5391 (defun org-hide-block-all ()
5392 "Fold all blocks in the current buffer."
5393 (interactive)
5394 (org-show-block-all)
5395 (org-block-map #'org-hide-block-toggle-maybe))
5396
5397 (defun org-show-block-all ()
5398 "Unfold all blocks in the current buffer."
5399 (mapc 'org-delete-overlay org-hide-block-overlays)
5400 (setq org-hide-block-overlays nil))
5401
5402 (defun org-hide-block-toggle-maybe ()
5403 "Toggle visibility of block at point."
5404 (interactive)
5405 (let ((case-fold-search t))
5406 (if (save-excursion
5407 (beginning-of-line 1)
5408 (looking-at org-block-regexp))
5409 (progn (org-hide-block-toggle)
5410 t) ;; to signal that we took action
5411 nil))) ;; to signal that we did not
5412
5413 (defun org-hide-block-toggle (&optional force)
5414 "Toggle the visibility of the current block."
5415 (interactive)
5416 (save-excursion
5417 (beginning-of-line)
5418 (if (re-search-forward org-block-regexp nil t)
5419 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5420 (end (match-end 0)) ;; end of entire body
5421 ov)
5422 (if (memq t (mapcar (lambda (overlay)
5423 (eq (org-overlay-get overlay 'invisible)
5424 'org-hide-block))
5425 (org-overlays-at start)))
5426 (if (or (not force) (eq force 'off))
5427 (mapc (lambda (ov)
5428 (when (member ov org-hide-block-overlays)
5429 (setq org-hide-block-overlays
5430 (delq ov org-hide-block-overlays)))
5431 (when (eq (org-overlay-get ov 'invisible)
5432 'org-hide-block)
5433 (org-delete-overlay ov)))
5434 (org-overlays-at start)))
5435 (setq ov (org-make-overlay start end))
5436 (org-overlay-put ov 'invisible 'org-hide-block)
5437 ;; make the block accessible to isearch
5438 (org-overlay-put
5439 ov 'isearch-open-invisible
5440 (lambda (ov)
5441 (when (member ov org-hide-block-overlays)
5442 (setq org-hide-block-overlays
5443 (delq ov org-hide-block-overlays)))
5444 (when (eq (org-overlay-get ov 'invisible)
5445 'org-hide-block)
5446 (org-delete-overlay ov))))
5447 (push ov org-hide-block-overlays)))
5448 (error "Not looking at a source block"))))
5449
5450 ;; org-tab-after-check-for-cycling-hook
5451 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5452 ;; Remove overlays when changing major mode
5453 (add-hook 'org-mode-hook
5454 (lambda () (org-add-hook 'change-major-mode-hook
5455 'org-show-block-all 'append 'local)))
5456
5457 ;;; Org-goto
5458
5459 (defvar org-goto-window-configuration nil)
5460 (defvar org-goto-marker nil)
5461 (defvar org-goto-map
5462 (let ((map (make-sparse-keymap)))
5463 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5464 (while (setq cmd (pop cmds))
5465 (substitute-key-definition cmd cmd map global-map)))
5466 (suppress-keymap map)
5467 (org-defkey map "\C-m" 'org-goto-ret)
5468 (org-defkey map [(return)] 'org-goto-ret)
5469 (org-defkey map [(left)] 'org-goto-left)
5470 (org-defkey map [(right)] 'org-goto-right)
5471 (org-defkey map [(control ?g)] 'org-goto-quit)
5472 (org-defkey map "\C-i" 'org-cycle)
5473 (org-defkey map [(tab)] 'org-cycle)
5474 (org-defkey map [(down)] 'outline-next-visible-heading)
5475 (org-defkey map [(up)] 'outline-previous-visible-heading)
5476 (if org-goto-auto-isearch
5477 (if (fboundp 'define-key-after)
5478 (define-key-after map [t] 'org-goto-local-auto-isearch)
5479 nil)
5480 (org-defkey map "q" 'org-goto-quit)
5481 (org-defkey map "n" 'outline-next-visible-heading)
5482 (org-defkey map "p" 'outline-previous-visible-heading)
5483 (org-defkey map "f" 'outline-forward-same-level)
5484 (org-defkey map "b" 'outline-backward-same-level)
5485 (org-defkey map "u" 'outline-up-heading))
5486 (org-defkey map "/" 'org-occur)
5487 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5488 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5489 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5490 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5491 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5492 map))
5493
5494 (defconst org-goto-help
5495 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5496 RET=jump to location [Q]uit and return to previous location
5497 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5498
5499 (defvar org-goto-start-pos) ; dynamically scoped parameter
5500
5501 ;; FIXME: Docstring doe not mention both interfaces
5502 (defun org-goto (&optional alternative-interface)
5503 "Look up a different location in the current file, keeping current visibility.
5504
5505 When you want look-up or go to a different location in a document, the
5506 fastest way is often to fold the entire buffer and then dive into the tree.
5507 This method has the disadvantage, that the previous location will be folded,
5508 which may not be what you want.
5509
5510 This command works around this by showing a copy of the current buffer
5511 in an indirect buffer, in overview mode. You can dive into the tree in
5512 that copy, use org-occur and incremental search to find a location.
5513 When pressing RET or `Q', the command returns to the original buffer in
5514 which the visibility is still unchanged. After RET is will also jump to
5515 the location selected in the indirect buffer and expose the
5516 the headline hierarchy above."
5517 (interactive "P")
5518 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5519 (org-refile-use-outline-path t)
5520 (org-refile-target-verify-function nil)
5521 (interface
5522 (if (not alternative-interface)
5523 org-goto-interface
5524 (if (eq org-goto-interface 'outline)
5525 'outline-path-completion
5526 'outline)))
5527 (org-goto-start-pos (point))
5528 (selected-point
5529 (if (eq interface 'outline)
5530 (car (org-get-location (current-buffer) org-goto-help))
5531 (nth 3 (org-refile-get-location "Goto: ")))))
5532 (if selected-point
5533 (progn
5534 (org-mark-ring-push org-goto-start-pos)
5535 (goto-char selected-point)
5536 (if (or (org-invisible-p) (org-invisible-p2))
5537 (org-show-context 'org-goto)))
5538 (message "Quit"))))
5539
5540 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5541 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5542 (defvar org-goto-local-auto-isearch-map) ; defined below
5543
5544 (defun org-get-location (buf help)
5545 "Let the user select a location in the Org-mode buffer BUF.
5546 This function uses a recursive edit. It returns the selected position
5547 or nil."
5548 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5549 (isearch-hide-immediately nil)
5550 (isearch-search-fun-function
5551 (lambda () 'org-goto-local-search-headings))
5552 (org-goto-selected-point org-goto-exit-command))
5553 (save-excursion
5554 (save-window-excursion
5555 (delete-other-windows)
5556 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5557 (switch-to-buffer
5558 (condition-case nil
5559 (make-indirect-buffer (current-buffer) "*org-goto*")
5560 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5561 (with-output-to-temp-buffer "*Help*"
5562 (princ help))
5563 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5564 (setq buffer-read-only nil)
5565 (let ((org-startup-truncated t)
5566 (org-startup-folded nil)
5567 (org-startup-align-all-tables nil))
5568 (org-mode)
5569 (org-overview))
5570 (setq buffer-read-only t)
5571 (if (and (boundp 'org-goto-start-pos)
5572 (integer-or-marker-p org-goto-start-pos))
5573 (let ((org-show-hierarchy-above t)
5574 (org-show-siblings t)
5575 (org-show-following-heading t))
5576 (goto-char org-goto-start-pos)
5577 (and (org-invisible-p) (org-show-context)))
5578 (goto-char (point-min)))
5579 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5580 (message "Select location and press RET")
5581 (use-local-map org-goto-map)
5582 (recursive-edit)
5583 ))
5584 (kill-buffer "*org-goto*")
5585 (cons org-goto-selected-point org-goto-exit-command)))
5586
5587 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5588 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5589 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5590 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5591
5592 (defun org-goto-local-search-headings (string bound noerror)
5593 "Search and make sure that any matches are in headlines."
5594 (catch 'return
5595 (while (if isearch-forward
5596 (search-forward string bound noerror)
5597 (search-backward string bound noerror))
5598 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5599 (and (member :headline context)
5600 (not (member :tags context))))
5601 (throw 'return (point))))))
5602
5603 (defun org-goto-local-auto-isearch ()
5604 "Start isearch."
5605 (interactive)
5606 (goto-char (point-min))
5607 (let ((keys (this-command-keys)))
5608 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5609 (isearch-mode t)
5610 (isearch-process-search-char (string-to-char keys)))))
5611
5612 (defun org-goto-ret (&optional arg)
5613 "Finish `org-goto' by going to the new location."
5614 (interactive "P")
5615 (setq org-goto-selected-point (point)
5616 org-goto-exit-command 'return)
5617 (throw 'exit nil))
5618
5619 (defun org-goto-left ()
5620 "Finish `org-goto' by going to the new location."
5621 (interactive)
5622 (if (org-on-heading-p)
5623 (progn
5624 (beginning-of-line 1)
5625 (setq org-goto-selected-point (point)
5626 org-goto-exit-command 'left)
5627 (throw 'exit nil))
5628 (error "Not on a heading")))
5629
5630 (defun org-goto-right ()
5631 "Finish `org-goto' by going to the new location."
5632 (interactive)
5633 (if (org-on-heading-p)
5634 (progn
5635 (setq org-goto-selected-point (point)
5636 org-goto-exit-command 'right)
5637 (throw 'exit nil))
5638 (error "Not on a heading")))
5639
5640 (defun org-goto-quit ()
5641 "Finish `org-goto' without cursor motion."
5642 (interactive)
5643 (setq org-goto-selected-point nil)
5644 (setq org-goto-exit-command 'quit)
5645 (throw 'exit nil))
5646
5647 ;;; Indirect buffer display of subtrees
5648
5649 (defvar org-indirect-dedicated-frame nil
5650 "This is the frame being used for indirect tree display.")
5651 (defvar org-last-indirect-buffer nil)
5652
5653 (defun org-tree-to-indirect-buffer (&optional arg)
5654 "Create indirect buffer and narrow it to current subtree.
5655 With numerical prefix ARG, go up to this level and then take that tree.
5656 If ARG is negative, go up that many levels.
5657 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5658 indirect buffer previously made with this command, to avoid proliferation of
5659 indirect buffers. However, when you call the command with a `C-u' prefix, or
5660 when `org-indirect-buffer-display' is `new-frame', the last buffer
5661 is kept so that you can work with several indirect buffers at the same time.
5662 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5663 requests that a new frame be made for the new buffer, so that the dedicated
5664 frame is not changed."
5665 (interactive "P")
5666 (let ((cbuf (current-buffer))
5667 (cwin (selected-window))
5668 (pos (point))
5669 beg end level heading ibuf)
5670 (save-excursion
5671 (org-back-to-heading t)
5672 (when (numberp arg)
5673 (setq level (org-outline-level))
5674 (if (< arg 0) (setq arg (+ level arg)))
5675 (while (> (setq level (org-outline-level)) arg)
5676 (outline-up-heading 1 t)))
5677 (setq beg (point)
5678 heading (org-get-heading))
5679 (org-end-of-subtree t t) (setq end (point)))
5680 (if (and (buffer-live-p org-last-indirect-buffer)
5681 (not (eq org-indirect-buffer-display 'new-frame))
5682 (not arg))
5683 (kill-buffer org-last-indirect-buffer))
5684 (setq ibuf (org-get-indirect-buffer cbuf)
5685 org-last-indirect-buffer ibuf)
5686 (cond
5687 ((or (eq org-indirect-buffer-display 'new-frame)
5688 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5689 (select-frame (make-frame))
5690 (delete-other-windows)
5691 (switch-to-buffer ibuf)
5692 (org-set-frame-title heading))
5693 ((eq org-indirect-buffer-display 'dedicated-frame)
5694 (raise-frame
5695 (select-frame (or (and org-indirect-dedicated-frame
5696 (frame-live-p org-indirect-dedicated-frame)
5697 org-indirect-dedicated-frame)
5698 (setq org-indirect-dedicated-frame (make-frame)))))
5699 (delete-other-windows)
5700 (switch-to-buffer ibuf)
5701 (org-set-frame-title (concat "Indirect: " heading)))
5702 ((eq org-indirect-buffer-display 'current-window)
5703 (switch-to-buffer ibuf))
5704 ((eq org-indirect-buffer-display 'other-window)
5705 (pop-to-buffer ibuf))
5706 (t (error "Invalid value")))
5707 (if (featurep 'xemacs)
5708 (save-excursion (org-mode) (turn-on-font-lock)))
5709 (narrow-to-region beg end)
5710 (show-all)
5711 (goto-char pos)
5712 (and (window-live-p cwin) (select-window cwin))))
5713
5714 (defun org-get-indirect-buffer (&optional buffer)
5715 (setq buffer (or buffer (current-buffer)))
5716 (let ((n 1) (base (buffer-name buffer)) bname)
5717 (while (buffer-live-p
5718 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5719 (setq n (1+ n)))
5720 (condition-case nil
5721 (make-indirect-buffer buffer bname 'clone)
5722 (error (make-indirect-buffer buffer bname)))))
5723
5724 (defun org-set-frame-title (title)
5725 "Set the title of the current frame to the string TITLE."
5726 ;; FIXME: how to name a single frame in XEmacs???
5727 (unless (featurep 'xemacs)
5728 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5729
5730 ;;;; Structure editing
5731
5732 ;;; Inserting headlines
5733
5734 (defun org-previous-line-empty-p ()
5735 (save-excursion
5736 (and (not (bobp))
5737 (or (beginning-of-line 0) t)
5738 (save-match-data
5739 (looking-at "[ \t]*$")))))
5740
5741 (defun org-insert-heading (&optional force-heading)
5742 "Insert a new heading or item with same depth at point.
5743 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5744 If point is at the beginning of a headline, insert a sibling before the
5745 current headline. If point is not at the beginning, do not split the line,
5746 but create the new headline after the current line."
5747 (interactive "P")
5748 (if (= (buffer-size) 0)
5749 (insert "\n* ")
5750 (when (or force-heading (not (org-insert-item)))
5751 (let* ((empty-line-p nil)
5752 (head (save-excursion
5753 (condition-case nil
5754 (progn
5755 (org-back-to-heading)
5756 (setq empty-line-p (org-previous-line-empty-p))
5757 (match-string 0))
5758 (error "*"))))
5759 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5760 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5761 pos hide-previous previous-pos)
5762 (cond
5763 ((and (org-on-heading-p) (bolp)
5764 (or (bobp)
5765 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5766 ;; insert before the current line
5767 (open-line (if blank 2 1)))
5768 ((and (bolp)
5769 (not org-insert-heading-respect-content)
5770 (or (bobp)
5771 (save-excursion
5772 (backward-char 1) (not (org-invisible-p)))))
5773 ;; insert right here
5774 nil)
5775 (t
5776 ;; somewhere in the line
5777 (save-excursion
5778 (setq previous-pos (point-at-bol))
5779 (end-of-line)
5780 (setq hide-previous (org-invisible-p)))
5781 (and org-insert-heading-respect-content (org-show-subtree))
5782 (let ((split
5783 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5784 (save-excursion
5785 (let ((p (point)))
5786 (goto-char (point-at-bol))
5787 (and (looking-at org-complex-heading-regexp)
5788 (> p (match-beginning 4)))))))
5789 tags pos)
5790 (cond
5791 (org-insert-heading-respect-content
5792 (org-end-of-subtree nil t)
5793 (or (bolp) (newline))
5794 (or (org-previous-line-empty-p)
5795 (and blank (newline)))
5796 (open-line 1))
5797 ((org-on-heading-p)
5798 (when hide-previous
5799 (show-children)
5800 (org-show-entry))
5801 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5802 (setq tags (and (match-end 2) (match-string 2)))
5803 (and (match-end 1)
5804 (delete-region (match-beginning 1) (match-end 1)))
5805 (setq pos (point-at-bol))
5806 (or split (end-of-line 1))
5807 (delete-horizontal-space)
5808 (newline (if blank 2 1))
5809 (when tags
5810 (save-excursion
5811 (goto-char pos)
5812 (end-of-line 1)
5813 (insert " " tags)
5814 (org-set-tags nil 'align))))
5815 (t
5816 (or split (end-of-line 1))
5817 (newline (if blank 2 1)))))))
5818 (insert head) (just-one-space)
5819 (setq pos (point))
5820 (end-of-line 1)
5821 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5822 (when (and org-insert-heading-respect-content hide-previous)
5823 (save-excursion
5824 (goto-char previous-pos)
5825 (hide-subtree)))
5826 (run-hooks 'org-insert-heading-hook)))))
5827
5828 (defun org-get-heading (&optional no-tags)
5829 "Return the heading of the current entry, without the stars."
5830 (save-excursion
5831 (org-back-to-heading t)
5832 (if (looking-at
5833 (if no-tags
5834 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5835 "\\*+[ \t]+\\([^\r\n]*\\)"))
5836 (match-string 1) "")))
5837
5838 (defun org-heading-components ()
5839 "Return the components of the current heading.
5840 This is a list with the following elements:
5841 - the level as an integer
5842 - the reduced level, different if `org-odd-levels-only' is set.
5843 - the TODO keyword, or nil
5844 - the priority character, like ?A, or nil if no priority is given
5845 - the headline text itself, or the tags string if no headline text
5846 - the tags string, or nil."
5847 (save-excursion
5848 (org-back-to-heading t)
5849 (if (looking-at org-complex-heading-regexp)
5850 (list (length (match-string 1))
5851 (org-reduced-level (length (match-string 1)))
5852 (org-match-string-no-properties 2)
5853 (and (match-end 3) (aref (match-string 3) 2))
5854 (org-match-string-no-properties 4)
5855 (org-match-string-no-properties 5)))))
5856
5857 (defun org-get-entry ()
5858 "Get the entry text, after heading, entire subtree."
5859 (save-excursion
5860 (org-back-to-heading t)
5861 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5862
5863 (defun org-insert-heading-after-current ()
5864 "Insert a new heading with same level as current, after current subtree."
5865 (interactive)
5866 (org-back-to-heading)
5867 (org-insert-heading)
5868 (org-move-subtree-down)
5869 (end-of-line 1))
5870
5871 (defun org-insert-heading-respect-content ()
5872 (interactive)
5873 (let ((org-insert-heading-respect-content t))
5874 (org-insert-heading t)))
5875
5876 (defun org-insert-todo-heading-respect-content (&optional force-state)
5877 (interactive "P")
5878 (let ((org-insert-heading-respect-content t))
5879 (org-insert-todo-heading force-state t)))
5880
5881 (defun org-insert-todo-heading (arg &optional force-heading)
5882 "Insert a new heading with the same level and TODO state as current heading.
5883 If the heading has no TODO state, or if the state is DONE, use the first
5884 state (TODO by default). Also with prefix arg, force first state."
5885 (interactive "P")
5886 (when (or force-heading (not (org-insert-item 'checkbox)))
5887 (org-insert-heading force-heading)
5888 (save-excursion
5889 (org-back-to-heading)
5890 (outline-previous-heading)
5891 (looking-at org-todo-line-regexp))
5892 (let*
5893 ((new-mark-x
5894 (if (or arg
5895 (not (match-beginning 2))
5896 (member (match-string 2) org-done-keywords))
5897 (car org-todo-keywords-1)
5898 (match-string 2)))
5899 (new-mark
5900 (or
5901 (run-hook-with-args-until-success
5902 'org-todo-get-default-hook new-mark-x nil)
5903 new-mark-x)))
5904 (beginning-of-line 1)
5905 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5906 (if org-treat-insert-todo-heading-as-state-change
5907 (org-todo new-mark)
5908 (insert new-mark " "))))
5909 (when org-provide-todo-statistics
5910 (org-update-parent-todo-statistics))))
5911
5912 (defun org-insert-subheading (arg)
5913 "Insert a new subheading and demote it.
5914 Works for outline headings and for plain lists alike."
5915 (interactive "P")
5916 (org-insert-heading arg)
5917 (cond
5918 ((org-on-heading-p) (org-do-demote))
5919 ((org-at-item-p) (org-indent-item 1))))
5920
5921 (defun org-insert-todo-subheading (arg)
5922 "Insert a new subheading with TODO keyword or checkbox and demote it.
5923 Works for outline headings and for plain lists alike."
5924 (interactive "P")
5925 (org-insert-todo-heading arg)
5926 (cond
5927 ((org-on-heading-p) (org-do-demote))
5928 ((org-at-item-p) (org-indent-item 1))))
5929
5930 ;;; Promotion and Demotion
5931
5932 (defvar org-after-demote-entry-hook nil
5933 "Hook run after an entry has been demoted.
5934 The cursor will be at the beginning of the entry.
5935 When a subtree is being demoted, the hook will be called for each node.")
5936
5937 (defvar org-after-promote-entry-hook nil
5938 "Hook run after an entry has been promoted.
5939 The cursor will be at the beginning of the entry.
5940 When a subtree is being promoted, the hook will be called for each node.")
5941
5942 (defun org-promote-subtree ()
5943 "Promote the entire subtree.
5944 See also `org-promote'."
5945 (interactive)
5946 (save-excursion
5947 (org-map-tree 'org-promote))
5948 (org-fix-position-after-promote))
5949
5950 (defun org-demote-subtree ()
5951 "Demote the entire subtree. See `org-demote'.
5952 See also `org-promote'."
5953 (interactive)
5954 (save-excursion
5955 (org-map-tree 'org-demote))
5956 (org-fix-position-after-promote))
5957
5958
5959 (defun org-do-promote ()
5960 "Promote the current heading higher up the tree.
5961 If the region is active in `transient-mark-mode', promote all headings
5962 in the region."
5963 (interactive)
5964 (save-excursion
5965 (if (org-region-active-p)
5966 (org-map-region 'org-promote (region-beginning) (region-end))
5967 (org-promote)))
5968 (org-fix-position-after-promote))
5969
5970 (defun org-do-demote ()
5971 "Demote the current heading lower down the tree.
5972 If the region is active in `transient-mark-mode', demote all headings
5973 in the region."
5974 (interactive)
5975 (save-excursion
5976 (if (org-region-active-p)
5977 (org-map-region 'org-demote (region-beginning) (region-end))
5978 (org-demote)))
5979 (org-fix-position-after-promote))
5980
5981 (defun org-fix-position-after-promote ()
5982 "Make sure that after pro/demotion cursor position is right."
5983 (let ((pos (point)))
5984 (when (save-excursion
5985 (beginning-of-line 1)
5986 (looking-at org-todo-line-regexp)
5987 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5988 (cond ((eobp) (insert " "))
5989 ((eolp) (insert " "))
5990 ((equal (char-after) ?\ ) (forward-char 1))))))
5991
5992 (defun org-reduced-level (l)
5993 "Compute the effective level of a heading.
5994 This takes into account the setting of `org-odd-levels-only'."
5995 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5996
5997 (defun org-get-valid-level (level &optional change)
5998 "Rectify a level change under the influence of `org-odd-levels-only'
5999 LEVEL is a current level, CHANGE is by how much the level should be
6000 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6001 even level numbers will become the next higher odd number."
6002 (if org-odd-levels-only
6003 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6004 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6005 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6006 (max 1 (+ level (or change 0)))))
6007
6008 (if (boundp 'define-obsolete-function-alias)
6009 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6010 (define-obsolete-function-alias 'org-get-legal-level
6011 'org-get-valid-level)
6012 (define-obsolete-function-alias 'org-get-legal-level
6013 'org-get-valid-level "23.1")))
6014
6015 (defun org-promote ()
6016 "Promote the current heading higher up the tree.
6017 If the region is active in `transient-mark-mode', promote all headings
6018 in the region."
6019 (org-back-to-heading t)
6020 (let* ((level (save-match-data (funcall outline-level)))
6021 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6022 (diff (abs (- level (length up-head) -1))))
6023 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6024 (replace-match up-head nil t)
6025 ;; Fixup tag positioning
6026 (and org-auto-align-tags (org-set-tags nil t))
6027 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6028 (run-hooks 'org-after-promote-entry-hook)))
6029
6030 (defun org-demote ()
6031 "Demote the current heading lower down the tree.
6032 If the region is active in `transient-mark-mode', demote all headings
6033 in the region."
6034 (org-back-to-heading t)
6035 (let* ((level (save-match-data (funcall outline-level)))
6036 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6037 (diff (abs (- level (length down-head) -1))))
6038 (replace-match down-head nil t)
6039 ;; Fixup tag positioning
6040 (and org-auto-align-tags (org-set-tags nil t))
6041 (if org-adapt-indentation (org-fixup-indentation diff))
6042 (run-hooks 'org-after-demote-entry-hook)))
6043
6044 (defun org-map-tree (fun)
6045 "Call FUN for every heading underneath the current one."
6046 (org-back-to-heading)
6047 (let ((level (funcall outline-level)))
6048 (save-excursion
6049 (funcall fun)
6050 (while (and (progn
6051 (outline-next-heading)
6052 (> (funcall outline-level) level))
6053 (not (eobp)))
6054 (funcall fun)))))
6055
6056 (defun org-map-region (fun beg end)
6057 "Call FUN for every heading between BEG and END."
6058 (let ((org-ignore-region t))
6059 (save-excursion
6060 (setq end (copy-marker end))
6061 (goto-char beg)
6062 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6063 (< (point) end))
6064 (funcall fun))
6065 (while (and (progn
6066 (outline-next-heading)
6067 (< (point) end))
6068 (not (eobp)))
6069 (funcall fun)))))
6070
6071 (defun org-fixup-indentation (diff)
6072 "Change the indentation in the current entry by DIFF
6073 However, if any line in the current entry has no indentation, or if it
6074 would end up with no indentation after the change, nothing at all is done."
6075 (save-excursion
6076 (let ((end (save-excursion (outline-next-heading)
6077 (point-marker)))
6078 (prohibit (if (> diff 0)
6079 "^\\S-"
6080 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6081 col)
6082 (unless (save-excursion (end-of-line 1)
6083 (re-search-forward prohibit end t))
6084 (while (and (< (point) end)
6085 (re-search-forward "^[ \t]+" end t))
6086 (goto-char (match-end 0))
6087 (setq col (current-column))
6088 (if (< diff 0) (replace-match ""))
6089 (org-indent-to-column (+ diff col))))
6090 (move-marker end nil))))
6091
6092 (defun org-convert-to-odd-levels ()
6093 "Convert an org-mode file with all levels allowed to one with odd levels.
6094 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6095 level 5 etc."
6096 (interactive)
6097 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6098 (let ((outline-regexp org-outline-regexp)
6099 (outline-level 'org-outline-level)
6100 (org-odd-levels-only nil) n)
6101 (save-excursion
6102 (goto-char (point-min))
6103 (while (re-search-forward "^\\*\\*+ " nil t)
6104 (setq n (- (length (match-string 0)) 2))
6105 (while (>= (setq n (1- n)) 0)
6106 (org-demote))
6107 (end-of-line 1))))))
6108
6109 (defun org-convert-to-oddeven-levels ()
6110 "Convert an org-mode file with only odd levels to one with odd and even levels.
6111 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6112 section with an even level, conversion would destroy the structure of the file. An error
6113 is signaled in this case."
6114 (interactive)
6115 (goto-char (point-min))
6116 ;; First check if there are no even levels
6117 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6118 (org-show-context t)
6119 (error "Not all levels are odd in this file. Conversion not possible"))
6120 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6121 (let ((outline-regexp org-outline-regexp)
6122 (outline-level 'org-outline-level)
6123 (org-odd-levels-only nil) n)
6124 (save-excursion
6125 (goto-char (point-min))
6126 (while (re-search-forward "^\\*\\*+ " nil t)
6127 (setq n (/ (1- (length (match-string 0))) 2))
6128 (while (>= (setq n (1- n)) 0)
6129 (org-promote))
6130 (end-of-line 1))))))
6131
6132 (defun org-tr-level (n)
6133 "Make N odd if required."
6134 (if org-odd-levels-only (1+ (/ n 2)) n))
6135
6136 ;;; Vertical tree motion, cutting and pasting of subtrees
6137
6138 (defun org-move-subtree-up (&optional arg)
6139 "Move the current subtree up past ARG headlines of the same level."
6140 (interactive "p")
6141 (org-move-subtree-down (- (prefix-numeric-value arg))))
6142
6143 (defun org-move-subtree-down (&optional arg)
6144 "Move the current subtree down past ARG headlines of the same level."
6145 (interactive "p")
6146 (setq arg (prefix-numeric-value arg))
6147 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6148 'org-get-last-sibling))
6149 (ins-point (make-marker))
6150 (cnt (abs arg))
6151 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6152 ;; Select the tree
6153 (org-back-to-heading)
6154 (setq beg0 (point))
6155 (save-excursion
6156 (setq ne-beg (org-back-over-empty-lines))
6157 (setq beg (point)))
6158 (save-match-data
6159 (save-excursion (outline-end-of-heading)
6160 (setq folded (org-invisible-p)))
6161 (outline-end-of-subtree))
6162 (outline-next-heading)
6163 (setq ne-end (org-back-over-empty-lines))
6164 (setq end (point))
6165 (goto-char beg0)
6166 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6167 ;; include less whitespace
6168 (save-excursion
6169 (goto-char beg)
6170 (forward-line (- ne-beg ne-end))
6171 (setq beg (point))))
6172 ;; Find insertion point, with error handling
6173 (while (> cnt 0)
6174 (or (and (funcall movfunc) (looking-at outline-regexp))
6175 (progn (goto-char beg0)
6176 (error "Cannot move past superior level or buffer limit")))
6177 (setq cnt (1- cnt)))
6178 (if (> arg 0)
6179 ;; Moving forward - still need to move over subtree
6180 (progn (org-end-of-subtree t t)
6181 (save-excursion
6182 (org-back-over-empty-lines)
6183 (or (bolp) (newline)))))
6184 (setq ne-ins (org-back-over-empty-lines))
6185 (move-marker ins-point (point))
6186 (setq txt (buffer-substring beg end))
6187 (org-save-markers-in-region beg end)
6188 (delete-region beg end)
6189 (org-remove-empty-overlays-at beg)
6190 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6191 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6192 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6193 (let ((bbb (point)))
6194 (insert-before-markers txt)
6195 (org-reinstall-markers-in-region bbb)
6196 (move-marker ins-point bbb))
6197 (or (bolp) (insert "\n"))
6198 (setq ins-end (point))
6199 (goto-char ins-point)
6200 (org-skip-whitespace)
6201 (when (and (< arg 0)
6202 (org-first-sibling-p)
6203 (> ne-ins ne-beg))
6204 ;; Move whitespace back to beginning
6205 (save-excursion
6206 (goto-char ins-end)
6207 (let ((kill-whole-line t))
6208 (kill-line (- ne-ins ne-beg)) (point)))
6209 (insert (make-string (- ne-ins ne-beg) ?\n)))
6210 (move-marker ins-point nil)
6211 (if folded
6212 (hide-subtree)
6213 (org-show-entry)
6214 (show-children)
6215 (org-cycle-hide-drawers 'children))
6216 (org-clean-visibility-after-subtree-move)))
6217
6218 (defvar org-subtree-clip ""
6219 "Clipboard for cut and paste of subtrees.
6220 This is actually only a copy of the kill, because we use the normal kill
6221 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6222
6223 (defvar org-subtree-clip-folded nil
6224 "Was the last copied subtree folded?
6225 This is used to fold the tree back after pasting.")
6226
6227 (defun org-cut-subtree (&optional n)
6228 "Cut the current subtree into the clipboard.
6229 With prefix arg N, cut this many sequential subtrees.
6230 This is a short-hand for marking the subtree and then cutting it."
6231 (interactive "p")
6232 (org-copy-subtree n 'cut))
6233
6234 (defun org-copy-subtree (&optional n cut force-store-markers)
6235 "Cut the current subtree into the clipboard.
6236 With prefix arg N, cut this many sequential subtrees.
6237 This is a short-hand for marking the subtree and then copying it.
6238 If CUT is non-nil, actually cut the subtree.
6239 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6240 of some markers in the region, even if CUT is non-nil. This is
6241 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6242 (interactive "p")
6243 (let (beg end folded (beg0 (point)))
6244 (if (interactive-p)
6245 (org-back-to-heading nil) ; take what looks like a subtree
6246 (org-back-to-heading t)) ; take what is really there
6247 (org-back-over-empty-lines)
6248 (setq beg (point))
6249 (skip-chars-forward " \t\r\n")
6250 (save-match-data
6251 (save-excursion (outline-end-of-heading)
6252 (setq folded (org-invisible-p)))
6253 (condition-case nil
6254 (org-forward-same-level (1- n) t)
6255 (error nil))
6256 (org-end-of-subtree t t))
6257 (org-back-over-empty-lines)
6258 (setq end (point))
6259 (goto-char beg0)
6260 (when (> end beg)
6261 (setq org-subtree-clip-folded folded)
6262 (when (or cut force-store-markers)
6263 (org-save-markers-in-region beg end))
6264 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6265 (setq org-subtree-clip (current-kill 0))
6266 (message "%s: Subtree(s) with %d characters"
6267 (if cut "Cut" "Copied")
6268 (length org-subtree-clip)))))
6269
6270 (defun org-paste-subtree (&optional level tree for-yank)
6271 "Paste the clipboard as a subtree, with modification of headline level.
6272 The entire subtree is promoted or demoted in order to match a new headline
6273 level.
6274
6275 If the cursor is at the beginning of a headline, the same level as
6276 that headline is used to paste the tree
6277
6278 If not, the new level is derived from the *visible* headings
6279 before and after the insertion point, and taken to be the inferior headline
6280 level of the two. So if the previous visible heading is level 3 and the
6281 next is level 4 (or vice versa), level 4 will be used for insertion.
6282 This makes sure that the subtree remains an independent subtree and does
6283 not swallow low level entries.
6284
6285 You can also force a different level, either by using a numeric prefix
6286 argument, or by inserting the heading marker by hand. For example, if the
6287 cursor is after \"*****\", then the tree will be shifted to level 5.
6288
6289 If optional TREE is given, use this text instead of the kill ring.
6290
6291 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6292 move back over whitespace before inserting, and move point to the end of
6293 the inserted text when done."
6294 (interactive "P")
6295 (setq tree (or tree (and kill-ring (current-kill 0))))
6296 (unless (org-kill-is-subtree-p tree)
6297 (error "%s"
6298 (substitute-command-keys
6299 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6300 (let* ((visp (not (org-invisible-p)))
6301 (txt tree)
6302 (^re (concat "^\\(" outline-regexp "\\)"))
6303 (re (concat "\\(" outline-regexp "\\)"))
6304 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6305
6306 (old-level (if (string-match ^re txt)
6307 (- (match-end 0) (match-beginning 0) 1)
6308 -1))
6309 (force-level (cond (level (prefix-numeric-value level))
6310 ((and (looking-at "[ \t]*$")
6311 (string-match
6312 ^re_ (buffer-substring
6313 (point-at-bol) (point))))
6314 (- (match-end 1) (match-beginning 1)))
6315 ((and (bolp)
6316 (looking-at org-outline-regexp))
6317 (- (match-end 0) (point) 1))
6318 (t nil)))
6319 (previous-level (save-excursion
6320 (condition-case nil
6321 (progn
6322 (outline-previous-visible-heading 1)
6323 (if (looking-at re)
6324 (- (match-end 0) (match-beginning 0) 1)
6325 1))
6326 (error 1))))
6327 (next-level (save-excursion
6328 (condition-case nil
6329 (progn
6330 (or (looking-at outline-regexp)
6331 (outline-next-visible-heading 1))
6332 (if (looking-at re)
6333 (- (match-end 0) (match-beginning 0) 1)
6334 1))
6335 (error 1))))
6336 (new-level (or force-level (max previous-level next-level)))
6337 (shift (if (or (= old-level -1)
6338 (= new-level -1)
6339 (= old-level new-level))
6340 0
6341 (- new-level old-level)))
6342 (delta (if (> shift 0) -1 1))
6343 (func (if (> shift 0) 'org-demote 'org-promote))
6344 (org-odd-levels-only nil)
6345 beg end newend)
6346 ;; Remove the forced level indicator
6347 (if force-level
6348 (delete-region (point-at-bol) (point)))
6349 ;; Paste
6350 (beginning-of-line 1)
6351 (unless for-yank (org-back-over-empty-lines))
6352 (setq beg (point))
6353 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6354 (insert-before-markers txt)
6355 (unless (string-match "\n\\'" txt) (insert "\n"))
6356 (setq newend (point))
6357 (org-reinstall-markers-in-region beg)
6358 (setq end (point))
6359 (goto-char beg)
6360 (skip-chars-forward " \t\n\r")
6361 (setq beg (point))
6362 (if (and (org-invisible-p) visp)
6363 (save-excursion (outline-show-heading)))
6364 ;; Shift if necessary
6365 (unless (= shift 0)
6366 (save-restriction
6367 (narrow-to-region beg end)
6368 (while (not (= shift 0))
6369 (org-map-region func (point-min) (point-max))
6370 (setq shift (+ delta shift)))
6371 (goto-char (point-min))
6372 (setq newend (point-max))))
6373 (when (or (interactive-p) for-yank)
6374 (message "Clipboard pasted as level %d subtree" new-level))
6375 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6376 kill-ring
6377 (eq org-subtree-clip (current-kill 0))
6378 org-subtree-clip-folded)
6379 ;; The tree was folded before it was killed/copied
6380 (hide-subtree))
6381 (and for-yank (goto-char newend))))
6382
6383 (defun org-kill-is-subtree-p (&optional txt)
6384 "Check if the current kill is an outline subtree, or a set of trees.
6385 Returns nil if kill does not start with a headline, or if the first
6386 headline level is not the largest headline level in the tree.
6387 So this will actually accept several entries of equal levels as well,
6388 which is OK for `org-paste-subtree'.
6389 If optional TXT is given, check this string instead of the current kill."
6390 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6391 (start-level (and kill
6392 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6393 org-outline-regexp "\\)")
6394 kill)
6395 (- (match-end 2) (match-beginning 2) 1)))
6396 (re (concat "^" org-outline-regexp))
6397 (start (1+ (or (match-beginning 2) -1))))
6398 (if (not start-level)
6399 (progn
6400 nil) ;; does not even start with a heading
6401 (catch 'exit
6402 (while (setq start (string-match re kill (1+ start)))
6403 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6404 (throw 'exit nil)))
6405 t))))
6406
6407 (defvar org-markers-to-move nil
6408 "Markers that should be moved with a cut-and-paste operation.
6409 Those markers are stored together with their positions relative to
6410 the start of the region.")
6411
6412 (defun org-save-markers-in-region (beg end)
6413 "Check markers in region.
6414 If these markers are between BEG and END, record their position relative
6415 to BEG, so that after moving the block of text, we can put the markers back
6416 into place.
6417 This function gets called just before an entry or tree gets cut from the
6418 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6419 called immediately, to move the markers with the entries."
6420 (setq org-markers-to-move nil)
6421 (when (featurep 'org-clock)
6422 (org-clock-save-markers-for-cut-and-paste beg end))
6423 (when (featurep 'org-agenda)
6424 (org-agenda-save-markers-for-cut-and-paste beg end)))
6425
6426 (defun org-check-and-save-marker (marker beg end)
6427 "Check if MARKER is between BEG and END.
6428 If yes, remember the marker and the distance to BEG."
6429 (when (and (marker-buffer marker)
6430 (equal (marker-buffer marker) (current-buffer)))
6431 (if (and (>= marker beg) (< marker end))
6432 (push (cons marker (- marker beg)) org-markers-to-move))))
6433
6434 (defun org-reinstall-markers-in-region (beg)
6435 "Move all remembered markers to their position relative to BEG."
6436 (mapc (lambda (x)
6437 (move-marker (car x) (+ beg (cdr x))))
6438 org-markers-to-move)
6439 (setq org-markers-to-move nil))
6440
6441 (defun org-narrow-to-subtree ()
6442 "Narrow buffer to the current subtree."
6443 (interactive)
6444 (save-excursion
6445 (save-match-data
6446 (narrow-to-region
6447 (progn (org-back-to-heading t) (point))
6448 (progn (org-end-of-subtree t t) (point))))))
6449
6450 (defun org-clone-subtree-with-time-shift (n &optional shift)
6451 "Clone the task (subtree) at point N times.
6452 The clones will be inserted as siblings.
6453
6454 In interactive use, the user will be prompted for the number of clones
6455 to be produced, and for a time SHIFT, which may be a repeater as used
6456 in time stamps, for example `+3d'.
6457
6458 When a valid repeater is given and the entry contains any time stamps,
6459 the clones will become a sequence in time, with time stamps in the
6460 subtree shifted for each clone produced. If SHIFT is nil or the
6461 empty string, time stamps will be left alone.
6462
6463 If the original subtree did contain time stamps with a repeater,
6464 the following will happen:
6465 - the repeater will be removed in each clone
6466 - an additional clone will be produced, with the current, unshifted
6467 date(s) in the entry.
6468 - the original entry will be placed *after* all the clones, with
6469 repeater intact.
6470 - the start days in the repeater in the original entry will be shifted
6471 to past the last clone.
6472 I this way you can spell out a number of instances of a repeating task,
6473 and still retain the repeater to cover future instances of the task."
6474 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6475 (let (beg end template task
6476 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6477 (if (not (and (integerp n) (> n 0)))
6478 (error "Invalid number of replications %s" n))
6479 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6480 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6481 shift)))
6482 (error "Invalid shift specification %s" shift))
6483 (when doshift
6484 (setq shift-n (string-to-number (match-string 1 shift))
6485 shift-what (cdr (assoc (match-string 2 shift)
6486 '(("d" . day) ("w" . week)
6487 ("m" . month) ("y" . year))))))
6488 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6489 (setq nmin 1 nmax n)
6490 (org-back-to-heading t)
6491 (setq beg (point))
6492 (org-end-of-subtree t t)
6493 (setq end (point))
6494 (setq template (buffer-substring beg end))
6495 (when (and doshift
6496 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6497 (delete-region beg end)
6498 (setq end beg)
6499 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6500 (goto-char end)
6501 (loop for n from nmin to nmax do
6502 (if (not doshift)
6503 (setq task template)
6504 (with-temp-buffer
6505 (insert template)
6506 (org-mode)
6507 (goto-char (point-min))
6508 (while (re-search-forward org-ts-regexp-both nil t)
6509 (org-timestamp-change (* n shift-n) shift-what))
6510 (unless (= n n-no-remove)
6511 (goto-char (point-min))
6512 (while (re-search-forward org-ts-regexp nil t)
6513 (save-excursion
6514 (goto-char (match-beginning 0))
6515 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6516 (delete-region (match-beginning 1) (match-end 1))))))
6517 (setq task (buffer-string))))
6518 (insert task))
6519 (goto-char beg)))
6520
6521 ;;; Outline Sorting
6522
6523 (defun org-sort (with-case)
6524 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6525 Optional argument WITH-CASE means sort case-sensitively.
6526 With a double prefix argument, also remove duplicate entries."
6527 (interactive "P")
6528 (if (org-at-table-p)
6529 (org-call-with-arg 'org-table-sort-lines with-case)
6530 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6531
6532 (defun org-sort-remove-invisible (s)
6533 (remove-text-properties 0 (length s) org-rm-props s)
6534 (while (string-match org-bracket-link-regexp s)
6535 (setq s (replace-match (if (match-end 2)
6536 (match-string 3 s)
6537 (match-string 1 s)) t t s)))
6538 s)
6539
6540 (defvar org-priority-regexp) ; defined later in the file
6541
6542 (defvar org-after-sorting-entries-or-items-hook nil
6543 "Hook that is run after a bunch of entries or items have been sorted.
6544 When children are sorted, the cursor is in the parent line when this
6545 hook gets called. When a region or a plain list is sorted, the cursor
6546 will be in the first entry of the sorted region/list.")
6547
6548 (defun org-sort-entries-or-items
6549 (&optional with-case sorting-type getkey-func compare-func property)
6550 "Sort entries on a certain level of an outline tree, or plain list items.
6551 If there is an active region, the entries in the region are sorted.
6552 Else, if the cursor is before the first entry, sort the top-level items.
6553 Else, the children of the entry at point are sorted.
6554 If the cursor is at the first item in a plain list, the list items will be
6555 sorted.
6556
6557 Sorting can be alphabetically, numerically, by date/time as given by
6558 a time stamp, by a property or by priority.
6559
6560 The command prompts for the sorting type unless it has been given to the
6561 function through the SORTING-TYPE argument, which needs to a character,
6562 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6563 precise meaning of each character:
6564
6565 n Numerically, by converting the beginning of the entry/item to a number.
6566 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6567 t By date/time, either the first active time stamp in the entry, or, if
6568 none exist, by the first inactive one.
6569 In items, only the first line will be chekced.
6570 s By the scheduled date/time.
6571 d By deadline date/time.
6572 c By creation time, which is assumed to be the first inactive time stamp
6573 at the beginning of a line.
6574 p By priority according to the cookie.
6575 r By the value of a property.
6576
6577 Capital letters will reverse the sort order.
6578
6579 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6580 called with point at the beginning of the record. It must return either
6581 a string or a number that should serve as the sorting key for that record.
6582
6583 Comparing entries ignores case by default. However, with an optional argument
6584 WITH-CASE, the sorting considers case as well."
6585 (interactive "P")
6586 (let ((case-func (if with-case 'identity 'downcase))
6587 start beg end stars re re2
6588 txt what tmp plain-list-p)
6589 ;; Find beginning and end of region to sort
6590 (cond
6591 ((org-region-active-p)
6592 ;; we will sort the region
6593 (setq end (region-end)
6594 what "region")
6595 (goto-char (region-beginning))
6596 (if (not (org-on-heading-p)) (outline-next-heading))
6597 (setq start (point)))
6598 ((org-at-item-p)
6599 ;; we will sort this plain list
6600 (org-beginning-of-item-list) (setq start (point))
6601 (org-end-of-item-list) (setq end (point))
6602 (goto-char start)
6603 (setq plain-list-p t
6604 what "plain list"))
6605 ((or (org-on-heading-p)
6606 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6607 ;; we will sort the children of the current headline
6608 (org-back-to-heading)
6609 (setq start (point)
6610 end (progn (org-end-of-subtree t t)
6611 (org-back-over-empty-lines)
6612 (point))
6613 what "children")
6614 (goto-char start)
6615 (show-subtree)
6616 (outline-next-heading))
6617 (t
6618 ;; we will sort the top-level entries in this file
6619 (goto-char (point-min))
6620 (or (org-on-heading-p) (outline-next-heading))
6621 (setq start (point) end (point-max) what "top-level")
6622 (goto-char start)
6623 (show-all)))
6624
6625 (setq beg (point))
6626 (if (>= beg end) (error "Nothing to sort"))
6627
6628 (unless plain-list-p
6629 (looking-at "\\(\\*+\\)")
6630 (setq stars (match-string 1)
6631 re (concat "^" (regexp-quote stars) " +")
6632 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6633 txt (buffer-substring beg end))
6634 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6635 (if (and (not (equal stars "*")) (string-match re2 txt))
6636 (error "Region to sort contains a level above the first entry")))
6637
6638 (unless sorting-type
6639 (message
6640 (if plain-list-p
6641 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6642 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6643 [t]ime [s]cheduled [d]eadline [c]reated
6644 A/N/T/S/D/C/P/O/F means reversed:")
6645 what)
6646 (setq sorting-type (read-char-exclusive))
6647
6648 (and (= (downcase sorting-type) ?f)
6649 (setq getkey-func
6650 (org-icompleting-read "Sort using function: "
6651 obarray 'fboundp t nil nil))
6652 (setq getkey-func (intern getkey-func)))
6653
6654 (and (= (downcase sorting-type) ?r)
6655 (setq property
6656 (org-icompleting-read "Property: "
6657 (mapcar 'list (org-buffer-property-keys t))
6658 nil t))))
6659
6660 (message "Sorting entries...")
6661
6662 (save-restriction
6663 (narrow-to-region start end)
6664
6665 (let ((dcst (downcase sorting-type))
6666 (case-fold-search nil)
6667 (now (current-time)))
6668 (sort-subr
6669 (/= dcst sorting-type)
6670 ;; This function moves to the beginning character of the "record" to
6671 ;; be sorted.
6672 (if plain-list-p
6673 (lambda nil
6674 (if (org-at-item-p) t (goto-char (point-max))))
6675 (lambda nil
6676 (if (re-search-forward re nil t)
6677 (goto-char (match-beginning 0))
6678 (goto-char (point-max)))))
6679 ;; This function moves to the last character of the "record" being
6680 ;; sorted.
6681 (if plain-list-p
6682 'org-end-of-item
6683 (lambda nil
6684 (save-match-data
6685 (condition-case nil
6686 (outline-forward-same-level 1)
6687 (error
6688 (goto-char (point-max)))))))
6689
6690 ;; This function returns the value that gets sorted against.
6691 (if plain-list-p
6692 (lambda nil
6693 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6694 (cond
6695 ((= dcst ?n)
6696 (string-to-number (buffer-substring (match-end 0)
6697 (point-at-eol))))
6698 ((= dcst ?a)
6699 (buffer-substring (match-end 0) (point-at-eol)))
6700 ((= dcst ?t)
6701 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6702 (re-search-forward org-ts-regexp-both
6703 (point-at-eol) t))
6704 (org-time-string-to-seconds (match-string 0))
6705 (org-float-time now)))
6706 ((= dcst ?f)
6707 (if getkey-func
6708 (progn
6709 (setq tmp (funcall getkey-func))
6710 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6711 tmp)
6712 (error "Invalid key function `%s'" getkey-func)))
6713 (t (error "Invalid sorting type `%c'" sorting-type)))))
6714 (lambda nil
6715 (cond
6716 ((= dcst ?n)
6717 (if (looking-at org-complex-heading-regexp)
6718 (string-to-number (match-string 4))
6719 nil))
6720 ((= dcst ?a)
6721 (if (looking-at org-complex-heading-regexp)
6722 (funcall case-func (match-string 4))
6723 nil))
6724 ((= dcst ?t)
6725 (let ((end (save-excursion (outline-next-heading) (point))))
6726 (if (or (re-search-forward org-ts-regexp end t)
6727 (re-search-forward org-ts-regexp-both end t))
6728 (org-time-string-to-seconds (match-string 0))
6729 (org-float-time now))))
6730 ((= dcst ?c)
6731 (let ((end (save-excursion (outline-next-heading) (point))))
6732 (if (re-search-forward
6733 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6734 end t)
6735 (org-time-string-to-seconds (match-string 0))
6736 (org-float-time now))))
6737 ((= dcst ?s)
6738 (let ((end (save-excursion (outline-next-heading) (point))))
6739 (if (re-search-forward org-scheduled-time-regexp end t)
6740 (org-time-string-to-seconds (match-string 1))
6741 (org-float-time now))))
6742 ((= dcst ?d)
6743 (let ((end (save-excursion (outline-next-heading) (point))))
6744 (if (re-search-forward org-deadline-time-regexp end t)
6745 (org-time-string-to-seconds (match-string 1))
6746 (org-float-time now))))
6747 ((= dcst ?p)
6748 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6749 (string-to-char (match-string 2))
6750 org-default-priority))
6751 ((= dcst ?r)
6752 (or (org-entry-get nil property) ""))
6753 ((= dcst ?o)
6754 (if (looking-at org-complex-heading-regexp)
6755 (- 9999 (length (member (match-string 2)
6756 org-todo-keywords-1)))))
6757 ((= dcst ?f)
6758 (if getkey-func
6759 (progn
6760 (setq tmp (funcall getkey-func))
6761 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6762 tmp)
6763 (error "Invalid key function `%s'" getkey-func)))
6764 (t (error "Invalid sorting type `%c'" sorting-type)))))
6765 nil
6766 (cond
6767 ((= dcst ?a) 'string<)
6768 ((= dcst ?f) compare-func)
6769 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6770 (t nil)))))
6771 (run-hooks 'org-after-sorting-entries-or-items-hook)
6772 (message "Sorting entries...done")))
6773
6774 (defun org-do-sort (table what &optional with-case sorting-type)
6775 "Sort TABLE of WHAT according to SORTING-TYPE.
6776 The user will be prompted for the SORTING-TYPE if the call to this
6777 function does not specify it. WHAT is only for the prompt, to indicate
6778 what is being sorted. The sorting key will be extracted from
6779 the car of the elements of the table.
6780 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6781 (unless sorting-type
6782 (message
6783 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6784 what)
6785 (setq sorting-type (read-char-exclusive)))
6786 (let ((dcst (downcase sorting-type))
6787 extractfun comparefun)
6788 ;; Define the appropriate functions
6789 (cond
6790 ((= dcst ?n)
6791 (setq extractfun 'string-to-number
6792 comparefun (if (= dcst sorting-type) '< '>)))
6793 ((= dcst ?a)
6794 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6795 (lambda(x) (downcase (org-sort-remove-invisible x))))
6796 comparefun (if (= dcst sorting-type)
6797 'string<
6798 (lambda (a b) (and (not (string< a b))
6799 (not (string= a b)))))))
6800 ((= dcst ?t)
6801 (setq extractfun
6802 (lambda (x)
6803 (if (or (string-match org-ts-regexp x)
6804 (string-match org-ts-regexp-both x))
6805 (org-float-time
6806 (org-time-string-to-time (match-string 0 x)))
6807 0))
6808 comparefun (if (= dcst sorting-type) '< '>)))
6809 (t (error "Invalid sorting type `%c'" sorting-type)))
6810
6811 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6812 table)
6813 (lambda (a b) (funcall comparefun (car a) (car b))))))
6814
6815
6816 ;;; The orgstruct minor mode
6817
6818 ;; Define a minor mode which can be used in other modes in order to
6819 ;; integrate the org-mode structure editing commands.
6820
6821 ;; This is really a hack, because the org-mode structure commands use
6822 ;; keys which normally belong to the major mode. Here is how it
6823 ;; works: The minor mode defines all the keys necessary to operate the
6824 ;; structure commands, but wraps the commands into a function which
6825 ;; tests if the cursor is currently at a headline or a plain list
6826 ;; item. If that is the case, the structure command is used,
6827 ;; temporarily setting many Org-mode variables like regular
6828 ;; expressions for filling etc. However, when any of those keys is
6829 ;; used at a different location, function uses `key-binding' to look
6830 ;; up if the key has an associated command in another currently active
6831 ;; keymap (minor modes, major mode, global), and executes that
6832 ;; command. There might be problems if any of the keys is otherwise
6833 ;; used as a prefix key.
6834
6835 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6836 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6837 ;; addresses this by checking explicitly for both bindings.
6838
6839 (defvar orgstruct-mode-map (make-sparse-keymap)
6840 "Keymap for the minor `orgstruct-mode'.")
6841
6842 (defvar org-local-vars nil
6843 "List of local variables, for use by `orgstruct-mode'")
6844
6845 ;;;###autoload
6846 (define-minor-mode orgstruct-mode
6847 "Toggle the minor more `orgstruct-mode'.
6848 This mode is for using Org-mode structure commands in other modes.
6849 The following key behave as if Org-mode was active, if the cursor
6850 is on a headline, or on a plain list item (both in the definition
6851 of Org-mode).
6852
6853 M-up Move entry/item up
6854 M-down Move entry/item down
6855 M-left Promote
6856 M-right Demote
6857 M-S-up Move entry/item up
6858 M-S-down Move entry/item down
6859 M-S-left Promote subtree
6860 M-S-right Demote subtree
6861 M-q Fill paragraph and items like in Org-mode
6862 C-c ^ Sort entries
6863 C-c - Cycle list bullet
6864 TAB Cycle item visibility
6865 M-RET Insert new heading/item
6866 S-M-RET Insert new TODO heading / Checkbox item
6867 C-c C-c Set tags / toggle checkbox"
6868 nil " OrgStruct" nil
6869 (org-load-modules-maybe)
6870 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6871
6872 ;;;###autoload
6873 (defun turn-on-orgstruct ()
6874 "Unconditionally turn on `orgstruct-mode'."
6875 (orgstruct-mode 1))
6876
6877 (defun orgstruct++-mode (&optional arg)
6878 "Toggle `orgstruct-mode', the enhanced version of it.
6879 In addition to setting orgstruct-mode, this also exports all indentation
6880 and autofilling variables from org-mode into the buffer. It will also
6881 recognize item context in multiline items.
6882 Note that turning off orgstruct-mode will *not* remove the
6883 indentation/paragraph settings. This can only be done by refreshing the
6884 major mode, for example with \\[normal-mode]."
6885 (interactive "P")
6886 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6887 (if (< arg 1)
6888 (orgstruct-mode -1)
6889 (orgstruct-mode 1)
6890 (let (var val)
6891 (mapc
6892 (lambda (x)
6893 (when (string-match
6894 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6895 (symbol-name (car x)))
6896 (setq var (car x) val (nth 1 x))
6897 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6898 org-local-vars)
6899 (org-set-local 'orgstruct-is-++ t))))
6900
6901 (defvar orgstruct-is-++ nil
6902 "Is orgstruct-mode in ++ version in the current-buffer?")
6903 (make-variable-buffer-local 'orgstruct-is-++)
6904
6905 ;;;###autoload
6906 (defun turn-on-orgstruct++ ()
6907 "Unconditionally turn on `orgstruct++-mode'."
6908 (orgstruct++-mode 1))
6909
6910 (defun orgstruct-error ()
6911 "Error when there is no default binding for a structure key."
6912 (interactive)
6913 (error "This key has no function outside structure elements"))
6914
6915 (defun orgstruct-setup ()
6916 "Setup orgstruct keymaps."
6917 (let ((nfunc 0)
6918 (bindings
6919 (list
6920 '([(meta up)] org-metaup)
6921 '([(meta down)] org-metadown)
6922 '([(meta left)] org-metaleft)
6923 '([(meta right)] org-metaright)
6924 '([(meta shift up)] org-shiftmetaup)
6925 '([(meta shift down)] org-shiftmetadown)
6926 '([(meta shift left)] org-shiftmetaleft)
6927 '([(meta shift right)] org-shiftmetaright)
6928 '([?\e (up)] org-metaup)
6929 '([?\e (down)] org-metadown)
6930 '([?\e (left)] org-metaleft)
6931 '([?\e (right)] org-metaright)
6932 '([?\e (shift up)] org-shiftmetaup)
6933 '([?\e (shift down)] org-shiftmetadown)
6934 '([?\e (shift left)] org-shiftmetaleft)
6935 '([?\e (shift right)] org-shiftmetaright)
6936 '([(shift up)] org-shiftup)
6937 '([(shift down)] org-shiftdown)
6938 '([(shift left)] org-shiftleft)
6939 '([(shift right)] org-shiftright)
6940 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6941 '("\M-q" fill-paragraph)
6942 '("\C-c^" org-sort)
6943 '("\C-c-" org-cycle-list-bullet)))
6944 elt key fun cmd)
6945 (while (setq elt (pop bindings))
6946 (setq nfunc (1+ nfunc))
6947 (setq key (org-key (car elt))
6948 fun (nth 1 elt)
6949 cmd (orgstruct-make-binding fun nfunc key))
6950 (org-defkey orgstruct-mode-map key cmd))
6951
6952 ;; Special treatment needed for TAB and RET
6953 (org-defkey orgstruct-mode-map [(tab)]
6954 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6955 (org-defkey orgstruct-mode-map "\C-i"
6956 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6957
6958 (org-defkey orgstruct-mode-map "\M-\C-m"
6959 (orgstruct-make-binding 'org-insert-heading 105
6960 "\M-\C-m" [(meta return)]))
6961 (org-defkey orgstruct-mode-map [(meta return)]
6962 (orgstruct-make-binding 'org-insert-heading 106
6963 [(meta return)] "\M-\C-m"))
6964
6965 (org-defkey orgstruct-mode-map [(shift meta return)]
6966 (orgstruct-make-binding 'org-insert-todo-heading 107
6967 [(meta return)] "\M-\C-m"))
6968
6969 (org-defkey orgstruct-mode-map "\e\C-m"
6970 (orgstruct-make-binding 'org-insert-heading 108
6971 "\e\C-m" [?\e (return)]))
6972 (org-defkey orgstruct-mode-map [?\e (return)]
6973 (orgstruct-make-binding 'org-insert-heading 109
6974 [?\e (return)] "\e\C-m"))
6975 (org-defkey orgstruct-mode-map [?\e (shift return)]
6976 (orgstruct-make-binding 'org-insert-todo-heading 110
6977 [?\e (return)] "\e\C-m"))
6978
6979 (unless org-local-vars
6980 (setq org-local-vars (org-get-local-variables)))
6981
6982 t))
6983
6984 (defun orgstruct-make-binding (fun n &rest keys)
6985 "Create a function for binding in the structure minor mode.
6986 FUN is the command to call inside a table. N is used to create a unique
6987 command name. KEYS are keys that should be checked in for a command
6988 to execute outside of tables."
6989 (eval
6990 (list 'defun
6991 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6992 '(arg)
6993 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6994 "Outside of structure, run the binding of `"
6995 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6996 "'.")
6997 '(interactive "p")
6998 (list 'if
6999 `(org-context-p 'headline 'item
7000 (and orgstruct-is-++
7001 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7002 'item-body))
7003 (list 'org-run-like-in-org-mode (list 'quote fun))
7004 (list 'let '(orgstruct-mode)
7005 (list 'call-interactively
7006 (append '(or)
7007 (mapcar (lambda (k)
7008 (list 'key-binding k))
7009 keys)
7010 '('orgstruct-error))))))))
7011
7012 (defun org-context-p (&rest contexts)
7013 "Check if local context is any of CONTEXTS.
7014 Possible values in the list of contexts are `table', `headline', and `item'."
7015 (let ((pos (point)))
7016 (goto-char (point-at-bol))
7017 (prog1 (or (and (memq 'table contexts)
7018 (looking-at "[ \t]*|"))
7019 (and (memq 'headline contexts)
7020 ;;????????? (looking-at "\\*+"))
7021 (looking-at outline-regexp))
7022 (and (memq 'item contexts)
7023 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7024 (and (memq 'item-body contexts)
7025 (org-in-item-p)))
7026 (goto-char pos))))
7027
7028 (defun org-get-local-variables ()
7029 "Return a list of all local variables in an org-mode buffer."
7030 (let (varlist)
7031 (with-current-buffer (get-buffer-create "*Org tmp*")
7032 (erase-buffer)
7033 (org-mode)
7034 (setq varlist (buffer-local-variables)))
7035 (kill-buffer "*Org tmp*")
7036 (delq nil
7037 (mapcar
7038 (lambda (x)
7039 (setq x
7040 (if (symbolp x)
7041 (list x)
7042 (list (car x) (list 'quote (cdr x)))))
7043 (if (string-match
7044 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7045 (symbol-name (car x)))
7046 x nil))
7047 varlist))))
7048
7049 ;;;###autoload
7050 (defun org-run-like-in-org-mode (cmd)
7051 "Run a command, pretending that the current buffer is in Org-mode.
7052 This will temporarily bind local variables that are typically bound in
7053 Org-mode to the values they have in Org-mode, and then interactively
7054 call CMD."
7055 (org-load-modules-maybe)
7056 (unless org-local-vars
7057 (setq org-local-vars (org-get-local-variables)))
7058 (eval (list 'let org-local-vars
7059 (list 'call-interactively (list 'quote cmd)))))
7060
7061 ;;;; Archiving
7062
7063 (defun org-get-category (&optional pos)
7064 "Get the category applying to position POS."
7065 (get-text-property (or pos (point)) 'org-category))
7066
7067 (defun org-refresh-category-properties ()
7068 "Refresh category text properties in the buffer."
7069 (let ((def-cat (cond
7070 ((null org-category)
7071 (if buffer-file-name
7072 (file-name-sans-extension
7073 (file-name-nondirectory buffer-file-name))
7074 "???"))
7075 ((symbolp org-category) (symbol-name org-category))
7076 (t org-category)))
7077 beg end cat pos optionp)
7078 (org-unmodified
7079 (save-excursion
7080 (save-restriction
7081 (widen)
7082 (goto-char (point-min))
7083 (put-text-property (point) (point-max) 'org-category def-cat)
7084 (while (re-search-forward
7085 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7086 (setq pos (match-end 0)
7087 optionp (equal (char-after (match-beginning 0)) ?#)
7088 cat (org-trim (match-string 2)))
7089 (if optionp
7090 (setq beg (point-at-bol) end (point-max))
7091 (org-back-to-heading t)
7092 (setq beg (point) end (org-end-of-subtree t t)))
7093 (put-text-property beg end 'org-category cat)
7094 (goto-char pos)))))))
7095
7096
7097 ;;;; Link Stuff
7098
7099 ;;; Link abbreviations
7100
7101 (defun org-link-expand-abbrev (link)
7102 "Apply replacements as defined in `org-link-abbrev-alist."
7103 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7104 (let* ((key (match-string 1 link))
7105 (as (or (assoc key org-link-abbrev-alist-local)
7106 (assoc key org-link-abbrev-alist)))
7107 (tag (and (match-end 2) (match-string 3 link)))
7108 rpl)
7109 (if (not as)
7110 link
7111 (setq rpl (cdr as))
7112 (cond
7113 ((symbolp rpl) (funcall rpl tag))
7114 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7115 ((string-match "%h" rpl)
7116 (replace-match (url-hexify-string (or tag "")) t t rpl))
7117 (t (concat rpl tag)))))
7118 link))
7119
7120 ;;; Storing and inserting links
7121
7122 (defvar org-insert-link-history nil
7123 "Minibuffer history for links inserted with `org-insert-link'.")
7124
7125 (defvar org-stored-links nil
7126 "Contains the links stored with `org-store-link'.")
7127
7128 (defvar org-store-link-plist nil
7129 "Plist with info about the most recently link created with `org-store-link'.")
7130
7131 (defvar org-link-protocols nil
7132 "Link protocols added to Org-mode using `org-add-link-type'.")
7133
7134 (defvar org-store-link-functions nil
7135 "List of functions that are called to create and store a link.
7136 Each function will be called in turn until one returns a non-nil
7137 value. Each function should check if it is responsible for creating
7138 this link (for example by looking at the major mode).
7139 If not, it must exit and return nil.
7140 If yes, it should return a non-nil value after a calling
7141 `org-store-link-props' with a list of properties and values.
7142 Special properties are:
7143
7144 :type The link prefix. like \"http\". This must be given.
7145 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7146 This is obligatory as well.
7147 :description Optional default description for the second pair
7148 of brackets in an Org-mode link. The user can still change
7149 this when inserting this link into an Org-mode buffer.
7150
7151 In addition to these, any additional properties can be specified
7152 and then used in remember templates.")
7153
7154 (defun org-add-link-type (type &optional follow export)
7155 "Add TYPE to the list of `org-link-types'.
7156 Re-compute all regular expressions depending on `org-link-types'
7157
7158 FOLLOW and EXPORT are two functions.
7159
7160 FOLLOW should take the link path as the single argument and do whatever
7161 is necessary to follow the link, for example find a file or display
7162 a mail message.
7163
7164 EXPORT should format the link path for export to one of the export formats.
7165 It should be a function accepting three arguments:
7166
7167 path the path of the link, the text after the prefix (like \"http:\")
7168 desc the description of the link, if any, nil if there was no description
7169 format the export format, a symbol like `html' or `latex'.
7170
7171 The function may use the FORMAT information to return different values
7172 depending on the format. The return value will be put literally into
7173 the exported file.
7174 Org-mode has a built-in default for exporting links. If you are happy with
7175 this default, there is no need to define an export function for the link
7176 type. For a simple example of an export function, see `org-bbdb.el'."
7177 (add-to-list 'org-link-types type t)
7178 (org-make-link-regexps)
7179 (if (assoc type org-link-protocols)
7180 (setcdr (assoc type org-link-protocols) (list follow export))
7181 (push (list type follow export) org-link-protocols)))
7182
7183 (defvar org-agenda-buffer-name)
7184
7185 ;;;###autoload
7186 (defun org-store-link (arg)
7187 "\\<org-mode-map>Store an org-link to the current location.
7188 This link is added to `org-stored-links' and can later be inserted
7189 into an org-buffer with \\[org-insert-link].
7190
7191 For some link types, a prefix arg is interpreted:
7192 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7193 For file links, arg negates `org-context-in-file-links'."
7194 (interactive "P")
7195 (org-load-modules-maybe)
7196 (setq org-store-link-plist nil) ; reset
7197 (let ((outline-regexp (org-get-limited-outline-regexp))
7198 link cpltxt desc description search txt custom-id)
7199 (cond
7200
7201 ((run-hook-with-args-until-success 'org-store-link-functions)
7202 (setq link (plist-get org-store-link-plist :link)
7203 desc (or (plist-get org-store-link-plist :description) link)))
7204
7205 ((equal (buffer-name) "*Org Edit Src Example*")
7206 (let (label gc)
7207 (while (or (not label)
7208 (save-excursion
7209 (save-restriction
7210 (widen)
7211 (goto-char (point-min))
7212 (re-search-forward
7213 (regexp-quote (format org-coderef-label-format label))
7214 nil t))))
7215 (when label (message "Label exists already") (sit-for 2))
7216 (setq label (read-string "Code line label: " label)))
7217 (end-of-line 1)
7218 (setq link (format org-coderef-label-format label))
7219 (setq gc (- 79 (length link)))
7220 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7221 (insert link)
7222 (setq link (concat "(" label ")") desc nil)))
7223
7224 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7225 ;; We are in the agenda, link to referenced location
7226 (let ((m (or (get-text-property (point) 'org-hd-marker)
7227 (get-text-property (point) 'org-marker))))
7228 (when m
7229 (org-with-point-at m
7230 (call-interactively 'org-store-link)))))
7231
7232 ((eq major-mode 'calendar-mode)
7233 (let ((cd (calendar-cursor-to-date)))
7234 (setq link
7235 (format-time-string
7236 (car org-time-stamp-formats)
7237 (apply 'encode-time
7238 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7239 nil nil nil))))
7240 (org-store-link-props :type "calendar" :date cd)))
7241
7242 ((eq major-mode 'w3-mode)
7243 (setq cpltxt (if (and (buffer-name)
7244 (not (string-match "Untitled" (buffer-name))))
7245 (buffer-name)
7246 (url-view-url t))
7247 link (org-make-link (url-view-url t)))
7248 (org-store-link-props :type "w3" :url (url-view-url t)))
7249
7250 ((eq major-mode 'w3m-mode)
7251 (setq cpltxt (or w3m-current-title w3m-current-url)
7252 link (org-make-link w3m-current-url))
7253 (org-store-link-props :type "w3m" :url (url-view-url t)))
7254
7255 ((setq search (run-hook-with-args-until-success
7256 'org-create-file-search-functions))
7257 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7258 "::" search))
7259 (setq cpltxt (or description link)))
7260
7261 ((eq major-mode 'image-mode)
7262 (setq cpltxt (concat "file:"
7263 (abbreviate-file-name buffer-file-name))
7264 link (org-make-link cpltxt))
7265 (org-store-link-props :type "image" :file buffer-file-name))
7266
7267 ((eq major-mode 'dired-mode)
7268 ;; link to the file in the current line
7269 (setq cpltxt (concat "file:"
7270 (abbreviate-file-name
7271 (expand-file-name
7272 (dired-get-filename nil t))))
7273 link (org-make-link cpltxt)))
7274
7275 ((and buffer-file-name (org-mode-p))
7276 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7277 (cond
7278 ((org-in-regexp "<<\\(.*?\\)>>")
7279 (setq cpltxt
7280 (concat "file:"
7281 (abbreviate-file-name buffer-file-name)
7282 "::" (match-string 1))
7283 link (org-make-link cpltxt)))
7284 ((and (featurep 'org-id)
7285 (or (eq org-link-to-org-use-id t)
7286 (and (eq org-link-to-org-use-id 'create-if-interactive)
7287 (interactive-p))
7288 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7289 (interactive-p)
7290 (not custom-id))
7291 (and org-link-to-org-use-id
7292 (condition-case nil
7293 (org-entry-get nil "ID")
7294 (error nil)))))
7295 ;; We can make a link using the ID.
7296 (setq link (condition-case nil
7297 (prog1 (org-id-store-link)
7298 (setq desc (plist-get org-store-link-plist
7299 :description)))
7300 (error
7301 ;; probably before first headline, link to file only
7302 (concat "file:"
7303 (abbreviate-file-name buffer-file-name))))))
7304 (t
7305 ;; Just link to current headline
7306 (setq cpltxt (concat "file:"
7307 (abbreviate-file-name buffer-file-name)))
7308 ;; Add a context search string
7309 (when (org-xor org-context-in-file-links arg)
7310 (setq txt (cond
7311 ((org-on-heading-p) nil)
7312 ((org-region-active-p)
7313 (buffer-substring (region-beginning) (region-end)))
7314 (t nil)))
7315 (when (or (null txt) (string-match "\\S-" txt))
7316 (setq cpltxt
7317 (concat cpltxt "::"
7318 (condition-case nil
7319 (org-make-org-heading-search-string txt)
7320 (error "")))
7321 desc (or (nth 4 (ignore-errors
7322 (org-heading-components))) "NONE"))))
7323 (if (string-match "::\\'" cpltxt)
7324 (setq cpltxt (substring cpltxt 0 -2)))
7325 (setq link (org-make-link cpltxt)))))
7326
7327 ((buffer-file-name (buffer-base-buffer))
7328 ;; Just link to this file here.
7329 (setq cpltxt (concat "file:"
7330 (abbreviate-file-name
7331 (buffer-file-name (buffer-base-buffer)))))
7332 ;; Add a context string
7333 (when (org-xor org-context-in-file-links arg)
7334 (setq txt (if (org-region-active-p)
7335 (buffer-substring (region-beginning) (region-end))
7336 (buffer-substring (point-at-bol) (point-at-eol))))
7337 ;; Only use search option if there is some text.
7338 (when (string-match "\\S-" txt)
7339 (setq cpltxt
7340 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7341 desc "NONE")))
7342 (setq link (org-make-link cpltxt)))
7343
7344 ((interactive-p)
7345 (error "Cannot link to a buffer which is not visiting a file"))
7346
7347 (t (setq link nil)))
7348
7349 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7350 (setq link (or link cpltxt)
7351 desc (or desc cpltxt))
7352 (if (equal desc "NONE") (setq desc nil))
7353
7354 (if (and (or (interactive-p) executing-kbd-macro) link)
7355 (progn
7356 (setq org-stored-links
7357 (cons (list link desc) org-stored-links))
7358 (message "Stored: %s" (or desc link))
7359 (when custom-id
7360 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7361 "::#" custom-id))
7362 (setq org-stored-links
7363 (cons (list link desc) org-stored-links))))
7364 (and link (org-make-link-string link desc)))))
7365
7366 (defun org-store-link-props (&rest plist)
7367 "Store link properties, extract names and addresses."
7368 (let (x adr)
7369 (when (setq x (plist-get plist :from))
7370 (setq adr (mail-extract-address-components x))
7371 (setq plist (plist-put plist :fromname (car adr)))
7372 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7373 (when (setq x (plist-get plist :to))
7374 (setq adr (mail-extract-address-components x))
7375 (setq plist (plist-put plist :toname (car adr)))
7376 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7377 (let ((from (plist-get plist :from))
7378 (to (plist-get plist :to)))
7379 (when (and from to org-from-is-user-regexp)
7380 (setq plist
7381 (plist-put plist :fromto
7382 (if (string-match org-from-is-user-regexp from)
7383 (concat "to %t")
7384 (concat "from %f"))))))
7385 (setq org-store-link-plist plist))
7386
7387 (defun org-add-link-props (&rest plist)
7388 "Add these properties to the link property list."
7389 (let (key value)
7390 (while plist
7391 (setq key (pop plist) value (pop plist))
7392 (setq org-store-link-plist
7393 (plist-put org-store-link-plist key value)))))
7394
7395 (defun org-email-link-description (&optional fmt)
7396 "Return the description part of an email link.
7397 This takes information from `org-store-link-plist' and formats it
7398 according to FMT (default from `org-email-link-description-format')."
7399 (setq fmt (or fmt org-email-link-description-format))
7400 (let* ((p org-store-link-plist)
7401 (to (plist-get p :toaddress))
7402 (from (plist-get p :fromaddress))
7403 (table
7404 (list
7405 (cons "%c" (plist-get p :fromto))
7406 (cons "%F" (plist-get p :from))
7407 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7408 (cons "%T" (plist-get p :to))
7409 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7410 (cons "%s" (plist-get p :subject))
7411 (cons "%m" (plist-get p :message-id)))))
7412 (when (string-match "%c" fmt)
7413 ;; Check if the user wrote this message
7414 (if (and org-from-is-user-regexp from to
7415 (save-match-data (string-match org-from-is-user-regexp from)))
7416 (setq fmt (replace-match "to %t" t t fmt))
7417 (setq fmt (replace-match "from %f" t t fmt))))
7418 (org-replace-escapes fmt table)))
7419
7420 (defun org-make-org-heading-search-string (&optional string heading)
7421 "Make search string for STRING or current headline."
7422 (interactive)
7423 (let ((s (or string (org-get-heading))))
7424 (unless (and string (not heading))
7425 ;; We are using a headline, clean up garbage in there.
7426 (if (string-match org-todo-regexp s)
7427 (setq s (replace-match "" t t s)))
7428 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7429 (setq s (replace-match "" t t s)))
7430 (setq s (org-trim s))
7431 (if (string-match (concat "^\\(" org-quote-string "\\|"
7432 org-comment-string "\\)") s)
7433 (setq s (replace-match "" t t s)))
7434 (while (string-match org-ts-regexp s)
7435 (setq s (replace-match "" t t s))))
7436 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7437 (setq s (replace-match " " t t s)))
7438 (or string (setq s (concat "*" s))) ; Add * for headlines
7439 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7440
7441 (defun org-make-link (&rest strings)
7442 "Concatenate STRINGS."
7443 (apply 'concat strings))
7444
7445 (defun org-make-link-string (link &optional description)
7446 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7447 (unless (string-match "\\S-" link)
7448 (error "Empty link"))
7449 (when (stringp description)
7450 ;; Remove brackets from the description, they are fatal.
7451 (while (string-match "\\[" description)
7452 (setq description (replace-match "{" t t description)))
7453 (while (string-match "\\]" description)
7454 (setq description (replace-match "}" t t description))))
7455 (when (equal (org-link-escape link) description)
7456 ;; No description needed, it is identical
7457 (setq description nil))
7458 (when (and (not description)
7459 (not (equal link (org-link-escape link))))
7460 (setq description (org-extract-attributes link)))
7461 (concat "[[" (org-link-escape link) "]"
7462 (if description (concat "[" description "]") "")
7463 "]"))
7464
7465 (defconst org-link-escape-chars
7466 '((?\ . "%20")
7467 (?\[ . "%5B")
7468 (?\] . "%5D")
7469 (?\340 . "%E0") ; `a
7470 (?\342 . "%E2") ; ^a
7471 (?\347 . "%E7") ; ,c
7472 (?\350 . "%E8") ; `e
7473 (?\351 . "%E9") ; 'e
7474 (?\352 . "%EA") ; ^e
7475 (?\356 . "%EE") ; ^i
7476 (?\364 . "%F4") ; ^o
7477 (?\371 . "%F9") ; `u
7478 (?\373 . "%FB") ; ^u
7479 (?\; . "%3B")
7480 (?? . "%3F")
7481 (?= . "%3D")
7482 (?+ . "%2B")
7483 )
7484 "Association list of escapes for some characters problematic in links.
7485 This is the list that is used for internal purposes.")
7486
7487 (defvar org-url-encoding-use-url-hexify nil)
7488
7489 (defconst org-link-escape-chars-browser
7490 '((?\ . "%20")) ; 32 for the SPC char
7491 "Association list of escapes for some characters problematic in links.
7492 This is the list that is used before handing over to the browser.")
7493
7494 (defun org-link-escape (text &optional table)
7495 "Escape characters in TEXT that are problematic for links."
7496 (if org-url-encoding-use-url-hexify
7497 (url-hexify-string text)
7498 (setq table (or table org-link-escape-chars))
7499 (when text
7500 (let ((re (mapconcat (lambda (x) (regexp-quote
7501 (char-to-string (car x))))
7502 table "\\|")))
7503 (while (string-match re text)
7504 (setq text
7505 (replace-match
7506 (cdr (assoc (string-to-char (match-string 0 text))
7507 table))
7508 t t text)))
7509 text))))
7510
7511 (defun org-link-unescape (text &optional table)
7512 "Reverse the action of `org-link-escape'."
7513 (if org-url-encoding-use-url-hexify
7514 (url-unhex-string text)
7515 (setq table (or table org-link-escape-chars))
7516 (when text
7517 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7518 table "\\|")))
7519 (while (string-match re text)
7520 (setq text
7521 (replace-match
7522 (char-to-string (car (rassoc (match-string 0 text) table)))
7523 t t text)))
7524 text))))
7525
7526 (defun org-xor (a b)
7527 "Exclusive or."
7528 (if a (not b) b))
7529
7530 (defun org-fixup-message-id-for-http (s)
7531 "Replace special characters in a message id, so it can be used in an http query."
7532 (while (string-match "<" s)
7533 (setq s (replace-match "%3C" t t s)))
7534 (while (string-match ">" s)
7535 (setq s (replace-match "%3E" t t s)))
7536 (while (string-match "@" s)
7537 (setq s (replace-match "%40" t t s)))
7538 s)
7539
7540 ;;;###autoload
7541 (defun org-insert-link-global ()
7542 "Insert a link like Org-mode does.
7543 This command can be called in any mode to insert a link in Org-mode syntax."
7544 (interactive)
7545 (org-load-modules-maybe)
7546 (org-run-like-in-org-mode 'org-insert-link))
7547
7548 (defun org-insert-link (&optional complete-file link-location)
7549 "Insert a link. At the prompt, enter the link.
7550
7551 Completion can be used to insert any of the link protocol prefixes like
7552 http or ftp in use.
7553
7554 The history can be used to select a link previously stored with
7555 `org-store-link'. When the empty string is entered (i.e. if you just
7556 press RET at the prompt), the link defaults to the most recently
7557 stored link. As SPC triggers completion in the minibuffer, you need to
7558 use M-SPC or C-q SPC to force the insertion of a space character.
7559
7560 You will also be prompted for a description, and if one is given, it will
7561 be displayed in the buffer instead of the link.
7562
7563 If there is already a link at point, this command will allow you to edit link
7564 and description parts.
7565
7566 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7567 be selected using completion. The path to the file will be relative to the
7568 current directory if the file is in the current directory or a subdirectory.
7569 Otherwise, the link will be the absolute path as completed in the minibuffer
7570 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7571 option `org-link-file-path-type'.
7572
7573 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7574 the current directory or below.
7575
7576 With three \\[universal-argument] prefixes, negate the meaning of
7577 `org-keep-stored-link-after-insertion'.
7578
7579 If `org-make-link-description-function' is non-nil, this function will be
7580 called with the link target, and the result will be the default
7581 link description.
7582
7583 If the LINK-LOCATION parameter is non-nil, this value will be
7584 used as the link location instead of reading one interactively."
7585 (interactive "P")
7586 (let* ((wcf (current-window-configuration))
7587 (region (if (org-region-active-p)
7588 (buffer-substring (region-beginning) (region-end))))
7589 (remove (and region (list (region-beginning) (region-end))))
7590 (desc region)
7591 tmphist ; byte-compile incorrectly complains about this
7592 (link link-location)
7593 entry file all-prefixes)
7594 (cond
7595 (link-location) ; specified by arg, just use it.
7596 ((org-in-regexp org-bracket-link-regexp 1)
7597 ;; We do have a link at point, and we are going to edit it.
7598 (setq remove (list (match-beginning 0) (match-end 0)))
7599 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7600 (setq link (read-string "Link: "
7601 (org-link-unescape
7602 (org-match-string-no-properties 1)))))
7603 ((or (org-in-regexp org-angle-link-re)
7604 (org-in-regexp org-plain-link-re))
7605 ;; Convert to bracket link
7606 (setq remove (list (match-beginning 0) (match-end 0))
7607 link (read-string "Link: "
7608 (org-remove-angle-brackets (match-string 0)))))
7609 ((member complete-file '((4) (16)))
7610 ;; Completing read for file names.
7611 (setq link (org-file-complete-link complete-file)))
7612 (t
7613 ;; Read link, with completion for stored links.
7614 (with-output-to-temp-buffer "*Org Links*"
7615 (princ "Insert a link.
7616 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7617 (when org-stored-links
7618 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7619 (princ (mapconcat
7620 (lambda (x)
7621 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7622 (reverse org-stored-links) "\n"))))
7623 (let ((cw (selected-window)))
7624 (select-window (get-buffer-window "*Org Links*"))
7625 (setq truncate-lines t)
7626 (unless (pos-visible-in-window-p (point-max))
7627 (org-fit-window-to-buffer))
7628 (and (window-live-p cw) (select-window cw)))
7629 ;; Fake a link history, containing the stored links.
7630 (setq tmphist (append (mapcar 'car org-stored-links)
7631 org-insert-link-history))
7632 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7633 (mapcar 'car org-link-abbrev-alist)
7634 org-link-types))
7635 (unwind-protect
7636 (progn
7637 (setq link
7638 (let ((org-completion-use-ido nil)
7639 (org-completion-use-iswitchb nil))
7640 (org-completing-read
7641 "Link: "
7642 (append
7643 (mapcar (lambda (x) (list (concat x ":")))
7644 all-prefixes)
7645 (mapcar 'car org-stored-links))
7646 nil nil nil
7647 'tmphist
7648 (car (car org-stored-links)))))
7649 (if (or (member link all-prefixes)
7650 (and (equal ":" (substring link -1))
7651 (member (substring link 0 -1) all-prefixes)
7652 (setq link (substring link 0 -1))))
7653 (setq link (org-link-try-special-completion link))))
7654 (set-window-configuration wcf)
7655 (kill-buffer "*Org Links*"))
7656 (setq entry (assoc link org-stored-links))
7657 (or entry (push link org-insert-link-history))
7658 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7659 (not org-keep-stored-link-after-insertion))
7660 (setq org-stored-links (delq (assoc link org-stored-links)
7661 org-stored-links)))
7662 (setq desc (or desc (nth 1 entry)))))
7663
7664 (if (string-match org-plain-link-re link)
7665 ;; URL-like link, normalize the use of angular brackets.
7666 (setq link (org-make-link (org-remove-angle-brackets link))))
7667
7668 ;; Check if we are linking to the current file with a search option
7669 ;; If yes, simplify the link by using only the search option.
7670 (when (and buffer-file-name
7671 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7672 (let* ((path (match-string 1 link))
7673 (case-fold-search nil)
7674 (search (match-string 2 link)))
7675 (save-match-data
7676 (if (equal (file-truename buffer-file-name) (file-truename path))
7677 ;; We are linking to this same file, with a search option
7678 (setq link search)))))
7679
7680 ;; Check if we can/should use a relative path. If yes, simplify the link
7681 (when (string-match "^file:\\(.*\\)" link)
7682 (let* ((path (match-string 1 link))
7683 (origpath path)
7684 (case-fold-search nil))
7685 (cond
7686 ((or (eq org-link-file-path-type 'absolute)
7687 (equal complete-file '(16)))
7688 (setq path (abbreviate-file-name (expand-file-name path))))
7689 ((eq org-link-file-path-type 'noabbrev)
7690 (setq path (expand-file-name path)))
7691 ((eq org-link-file-path-type 'relative)
7692 (setq path (file-relative-name path)))
7693 (t
7694 (save-match-data
7695 (if (string-match (concat "^" (regexp-quote
7696 (file-name-as-directory
7697 (expand-file-name "."))))
7698 (expand-file-name path))
7699 ;; We are linking a file with relative path name.
7700 (setq path (substring (expand-file-name path)
7701 (match-end 0)))
7702 (setq path (abbreviate-file-name (expand-file-name path)))))))
7703 (setq link (concat "file:" path))
7704 (if (equal desc origpath)
7705 (setq desc path))))
7706
7707 (if org-make-link-description-function
7708 (setq desc (funcall org-make-link-description-function link desc)))
7709
7710 (setq desc (read-string "Description: " desc))
7711 (unless (string-match "\\S-" desc) (setq desc nil))
7712 (if remove (apply 'delete-region remove))
7713 (insert (org-make-link-string link desc))))
7714
7715 (defun org-link-try-special-completion (type)
7716 "If there is completion support for link type TYPE, offer it."
7717 (let ((fun (intern (concat "org-" type "-complete-link"))))
7718 (if (functionp fun)
7719 (funcall fun)
7720 (read-string "Link (no completion support): " (concat type ":")))))
7721
7722 (defun org-file-complete-link (&optional arg)
7723 "Create a file link using completion."
7724 (let (file link)
7725 (setq file (read-file-name "File: "))
7726 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7727 (pwd1 (file-name-as-directory (abbreviate-file-name
7728 (expand-file-name ".")))))
7729 (cond
7730 ((equal arg '(16))
7731 (setq link (org-make-link
7732 "file:"
7733 (abbreviate-file-name (expand-file-name file)))))
7734 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7735 (setq link (org-make-link "file:" (match-string 1 file))))
7736 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7737 (expand-file-name file))
7738 (setq link (org-make-link
7739 "file:" (match-string 1 (expand-file-name file)))))
7740 (t (setq link (org-make-link "file:" file)))))
7741 link))
7742
7743 (defun org-completing-read (&rest args)
7744 "Completing-read with SPACE being a normal character."
7745 (let ((minibuffer-local-completion-map
7746 (copy-keymap minibuffer-local-completion-map)))
7747 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7748 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7749 (apply 'org-icompleting-read args)))
7750
7751 (defun org-completing-read-no-i (&rest args)
7752 (let (org-completion-use-ido org-completion-use-iswitchb)
7753 (apply 'org-completing-read args)))
7754
7755 (defun org-iswitchb-completing-read (prompt choices &rest args)
7756 "Use iswitch as a completing-read replacement to choose from choices.
7757 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
7758 from."
7759 (let* ((iswitchb-use-virtual-buffers nil)
7760 (iswitchb-make-buflist-hook
7761 (lambda ()
7762 (setq iswitchb-temp-buflist choices))))
7763 (iswitchb-read-buffer prompt)))
7764
7765 (defun org-icompleting-read (&rest args)
7766 "Completing-read using `ido-mode' or `iswitchb' speedups if available"
7767 (if (and org-completion-use-ido
7768 (fboundp 'ido-completing-read)
7769 (boundp 'ido-mode) ido-mode
7770 (listp (second args)))
7771 (let ((ido-enter-matching-directory nil))
7772 (apply 'ido-completing-read (concat (car args))
7773 (if (consp (car (nth 1 args)))
7774 (mapcar (lambda (x) (car x)) (nth 1 args))
7775 (nth 1 args))
7776 (cddr args)))
7777 (if (and org-completion-use-iswitchb
7778 (boundp 'iswitchb-mode) iswitchb-mode
7779 (listp (second args)))
7780 (apply 'org-iswitchb-completing-read (concat (car args))
7781 (mapcar (lambda (x) (car x)) (nth 1 args))
7782 (cddr args))
7783 (apply 'completing-read args))))
7784
7785 (defun org-extract-attributes (s)
7786 "Extract the attributes cookie from a string and set as text property."
7787 (let (a attr (start 0) key value)
7788 (save-match-data
7789 (when (string-match "{{\\([^}]+\\)}}$" s)
7790 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7791 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7792 (setq key (match-string 1 a) value (match-string 2 a)
7793 start (match-end 0)
7794 attr (plist-put attr (intern key) value))))
7795 (org-add-props s nil 'org-attr attr))
7796 s))
7797
7798 (defun org-extract-attributes-from-string (tag)
7799 (let (key value attr)
7800 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7801 (setq key (match-string 1 tag) value (match-string 2 tag)
7802 tag (replace-match "" t t tag)
7803 attr (plist-put attr (intern key) value)))
7804 (cons tag attr)))
7805
7806 (defun org-attributes-to-string (plist)
7807 "Format a property list into an HTML attribute list."
7808 (let ((s "") key value)
7809 (while plist
7810 (setq key (pop plist) value (pop plist))
7811 (and value
7812 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7813 s))
7814
7815 ;;; Opening/following a link
7816
7817 (defvar org-link-search-failed nil)
7818
7819 (defun org-next-link ()
7820 "Move forward to the next link.
7821 If the link is in hidden text, expose it."
7822 (interactive)
7823 (when (and org-link-search-failed (eq this-command last-command))
7824 (goto-char (point-min))
7825 (message "Link search wrapped back to beginning of buffer"))
7826 (setq org-link-search-failed nil)
7827 (let* ((pos (point))
7828 (ct (org-context))
7829 (a (assoc :link ct)))
7830 (if a (goto-char (nth 2 a)))
7831 (if (re-search-forward org-any-link-re nil t)
7832 (progn
7833 (goto-char (match-beginning 0))
7834 (if (org-invisible-p) (org-show-context)))
7835 (goto-char pos)
7836 (setq org-link-search-failed t)
7837 (error "No further link found"))))
7838
7839 (defun org-previous-link ()
7840 "Move backward to the previous link.
7841 If the link is in hidden text, expose it."
7842 (interactive)
7843 (when (and org-link-search-failed (eq this-command last-command))
7844 (goto-char (point-max))
7845 (message "Link search wrapped back to end of buffer"))
7846 (setq org-link-search-failed nil)
7847 (let* ((pos (point))
7848 (ct (org-context))
7849 (a (assoc :link ct)))
7850 (if a (goto-char (nth 1 a)))
7851 (if (re-search-backward org-any-link-re nil t)
7852 (progn
7853 (goto-char (match-beginning 0))
7854 (if (org-invisible-p) (org-show-context)))
7855 (goto-char pos)
7856 (setq org-link-search-failed t)
7857 (error "No further link found"))))
7858
7859 (defun org-translate-link (s)
7860 "Translate a link string if a translation function has been defined."
7861 (if (and org-link-translation-function
7862 (fboundp org-link-translation-function)
7863 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7864 (progn
7865 (setq s (funcall org-link-translation-function
7866 (match-string 1) (match-string 2)))
7867 (concat (car s) ":" (cdr s)))
7868 s))
7869
7870 (defun org-translate-link-from-planner (type path)
7871 "Translate a link from Emacs Planner syntax so that Org can follow it.
7872 This is still an experimental function, your mileage may vary."
7873 (cond
7874 ((member type '("http" "https" "news" "ftp"))
7875 ;; standard Internet links are the same.
7876 nil)
7877 ((and (equal type "irc") (string-match "^//" path))
7878 ;; Planner has two / at the beginning of an irc link, we have 1.
7879 ;; We should have zero, actually....
7880 (setq path (substring path 1)))
7881 ((and (equal type "lisp") (string-match "^/" path))
7882 ;; Planner has a slash, we do not.
7883 (setq type "elisp" path (substring path 1)))
7884 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7885 ;; A typical message link. Planner has the id after the fina slash,
7886 ;; we separate it with a hash mark
7887 (setq path (concat (match-string 1 path) "#"
7888 (org-remove-angle-brackets (match-string 2 path)))))
7889 )
7890 (cons type path))
7891
7892 (defun org-find-file-at-mouse (ev)
7893 "Open file link or URL at mouse."
7894 (interactive "e")
7895 (mouse-set-point ev)
7896 (org-open-at-point 'in-emacs))
7897
7898 (defun org-open-at-mouse (ev)
7899 "Open file link or URL at mouse."
7900 (interactive "e")
7901 (mouse-set-point ev)
7902 (if (eq major-mode 'org-agenda-mode)
7903 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7904 (org-open-at-point))
7905
7906 (defvar org-window-config-before-follow-link nil
7907 "The window configuration before following a link.
7908 This is saved in case the need arises to restore it.")
7909
7910 (defvar org-open-link-marker (make-marker)
7911 "Marker pointing to the location where `org-open-at-point; was called.")
7912
7913 ;;;###autoload
7914 (defun org-open-at-point-global ()
7915 "Follow a link like Org-mode does.
7916 This command can be called in any mode to follow a link that has
7917 Org-mode syntax."
7918 (interactive)
7919 (org-run-like-in-org-mode 'org-open-at-point))
7920
7921 ;;;###autoload
7922 (defun org-open-link-from-string (s &optional arg reference-buffer)
7923 "Open a link in the string S, as if it was in Org-mode."
7924 (interactive "sLink: \nP")
7925 (let ((reference-buffer (or reference-buffer (current-buffer))))
7926 (with-temp-buffer
7927 (let ((org-inhibit-startup t))
7928 (org-mode)
7929 (insert s)
7930 (goto-char (point-min))
7931 (org-open-at-point arg reference-buffer)))))
7932
7933 (defun org-open-at-point (&optional in-emacs reference-buffer)
7934 "Open link at or after point.
7935 If there is no link at point, this function will search forward up to
7936 the end of the current line.
7937 Normally, files will be opened by an appropriate application. If the
7938 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7939 With a double prefix argument, try to open outside of Emacs, in the
7940 application the system uses for this file type."
7941 (interactive "P")
7942 (org-load-modules-maybe)
7943 (move-marker org-open-link-marker (point))
7944 (setq org-window-config-before-follow-link (current-window-configuration))
7945 (org-remove-occur-highlights nil nil t)
7946 (cond
7947 ((and (org-on-heading-p)
7948 (not (org-in-regexp
7949 (concat org-plain-link-re "\\|"
7950 org-bracket-link-regexp "\\|"
7951 org-angle-link-re "\\|"
7952 "[ \t]:[^ \t\n]+:[ \t]*$"))))
7953 (org-offer-links-in-entry in-emacs))
7954 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7955 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7956 (org-footnote-action))
7957 (t
7958 (let (type path link line search (pos (point)))
7959 (catch 'match
7960 (save-excursion
7961 (skip-chars-forward "^]\n\r")
7962 (when (org-in-regexp org-bracket-link-regexp)
7963 (setq link (org-extract-attributes
7964 (org-link-unescape (org-match-string-no-properties 1))))
7965 (while (string-match " *\n *" link)
7966 (setq link (replace-match " " t t link)))
7967 (setq link (org-link-expand-abbrev link))
7968 (cond
7969 ((or (file-name-absolute-p link)
7970 (string-match "^\\.\\.?/" link))
7971 (setq type "file" path link))
7972 ((string-match org-link-re-with-space3 link)
7973 (setq type (match-string 1 link) path (match-string 2 link)))
7974 (t (setq type "thisfile" path link)))
7975 (throw 'match t)))
7976
7977 (when (get-text-property (point) 'org-linked-text)
7978 (setq type "thisfile"
7979 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7980 (1+ (point)) (point))
7981 path (buffer-substring
7982 (previous-single-property-change pos 'org-linked-text)
7983 (next-single-property-change pos 'org-linked-text)))
7984 (throw 'match t))
7985
7986 (save-excursion
7987 (when (or (org-in-regexp org-angle-link-re)
7988 (org-in-regexp org-plain-link-re))
7989 (setq type (match-string 1) path (match-string 2))
7990 (throw 'match t)))
7991 (save-excursion
7992 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7993 (setq type "tags"
7994 path (match-string 1))
7995 (while (string-match ":" path)
7996 (setq path (replace-match "+" t t path)))
7997 (throw 'match t)))
7998 (when (org-in-regexp "<\\([^><\n]+\\)>")
7999 (setq type "tree-match"
8000 path (match-string 1))
8001 (throw 'match t)))
8002 (unless path
8003 (error "No link found"))
8004
8005 ;; switch back to reference buffer
8006 ;; needed when if called in a temporary buffer through
8007 ;; org-open-link-from-string
8008 (with-current-buffer (or reference-buffer (current-buffer))
8009
8010 ;; Remove any trailing spaces in path
8011 (if (string-match " +\\'" path)
8012 (setq path (replace-match "" t t path)))
8013 (if (and org-link-translation-function
8014 (fboundp org-link-translation-function))
8015 ;; Check if we need to translate the link
8016 (let ((tmp (funcall org-link-translation-function type path)))
8017 (setq type (car tmp) path (cdr tmp))))
8018
8019 (cond
8020
8021 ((assoc type org-link-protocols)
8022 (funcall (nth 1 (assoc type org-link-protocols)) path))
8023
8024 ((equal type "mailto")
8025 (let ((cmd (car org-link-mailto-program))
8026 (args (cdr org-link-mailto-program)) args1
8027 (address path) (subject "") a)
8028 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8029 (setq address (match-string 1 path)
8030 subject (org-link-escape (match-string 2 path))))
8031 (while args
8032 (cond
8033 ((not (stringp (car args))) (push (pop args) args1))
8034 (t (setq a (pop args))
8035 (if (string-match "%a" a)
8036 (setq a (replace-match address t t a)))
8037 (if (string-match "%s" a)
8038 (setq a (replace-match subject t t a)))
8039 (push a args1))))
8040 (apply cmd (nreverse args1))))
8041
8042 ((member type '("http" "https" "ftp" "news"))
8043 (browse-url (concat type ":" (org-link-escape
8044 path org-link-escape-chars-browser))))
8045
8046 ((member type '("message"))
8047 (browse-url (concat type ":" path)))
8048
8049 ((string= type "tags")
8050 (org-tags-view in-emacs path))
8051 ((string= type "thisfile")
8052 (if in-emacs
8053 (switch-to-buffer-other-window
8054 (org-get-buffer-for-internal-link (current-buffer)))
8055 (org-mark-ring-push))
8056 (let ((cmd `(org-link-search
8057 ,path
8058 ,(cond ((equal in-emacs '(4)) 'occur)
8059 ((equal in-emacs '(16)) 'org-occur)
8060 (t nil))
8061 ,pos)))
8062 (condition-case nil (eval cmd)
8063 (error (progn (widen) (eval cmd))))))
8064
8065 ((string= type "tree-match")
8066 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8067
8068 ((string= type "file")
8069 (if (string-match "::\\([0-9]+\\)\\'" path)
8070 (setq line (string-to-number (match-string 1 path))
8071 path (substring path 0 (match-beginning 0)))
8072 (if (string-match "::\\(.+\\)\\'" path)
8073 (setq search (match-string 1 path)
8074 path (substring path 0 (match-beginning 0)))))
8075 (if (string-match "[*?{]" (file-name-nondirectory path))
8076 (dired path)
8077 (org-open-file path in-emacs line search)))
8078
8079 ((string= type "news")
8080 (require 'org-gnus)
8081 (org-gnus-follow-link path))
8082
8083 ((string= type "shell")
8084 (let ((cmd path))
8085 (if (or (not org-confirm-shell-link-function)
8086 (funcall org-confirm-shell-link-function
8087 (format "Execute \"%s\" in shell? "
8088 (org-add-props cmd nil
8089 'face 'org-warning))))
8090 (progn
8091 (message "Executing %s" cmd)
8092 (shell-command cmd))
8093 (error "Abort"))))
8094
8095 ((string= type "elisp")
8096 (let ((cmd path))
8097 (if (or (not org-confirm-elisp-link-function)
8098 (funcall org-confirm-elisp-link-function
8099 (format "Execute \"%s\" as elisp? "
8100 (org-add-props cmd nil
8101 'face 'org-warning))))
8102 (message "%s => %s" cmd
8103 (if (equal (string-to-char cmd) ?\()
8104 (eval (read cmd))
8105 (call-interactively (read cmd))))
8106 (error "Abort"))))
8107
8108 (t
8109 (browse-url-at-point)))))))
8110 (move-marker org-open-link-marker nil)
8111 (run-hook-with-args 'org-follow-link-hook))
8112
8113 (defun org-offer-links-in-entry (&optional nth zero)
8114 "Offer links in the curren entry and follow the selected link.
8115 If there is only one link, follow it immediately as well.
8116 If NTH is an integer, immediately pick the NTH link found.
8117 If ZERO is a string, check also this string for a link, and if
8118 there is one, offer it as link number zero."
8119 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8120 "\\(" org-angle-link-re "\\)\\|"
8121 "\\(" org-plain-link-re "\\)"))
8122 (cnt ?0)
8123 (in-emacs (if (integerp nth) nil nth))
8124 have-zero end links link c)
8125 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8126 (push (match-string 0 zero) links)
8127 (setq cnt (1- cnt) have-zero t))
8128 (save-excursion
8129 (org-back-to-heading t)
8130 (setq end (save-excursion (outline-next-heading) (point)))
8131 (while (re-search-forward re end t)
8132 (push (match-string 0) links))
8133 (setq links (org-uniquify (reverse links))))
8134
8135 (cond
8136 ((null links) (error "No links"))
8137 ((equal (length links) 1)
8138 (setq link (car links)))
8139 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8140 (setq link (nth (if have-zero nth (1- nth)) links)))
8141 (t ; we have to select a link
8142 (save-excursion
8143 (save-window-excursion
8144 (delete-other-windows)
8145 (with-output-to-temp-buffer "*Select Link*"
8146 (mapc (lambda (l)
8147 (if (not (string-match org-bracket-link-regexp l))
8148 (princ (format "[%c] %s\n" (incf cnt)
8149 (org-remove-angle-brackets l)))
8150 (if (match-end 3)
8151 (princ (format "[%c] %s (%s)\n" (incf cnt)
8152 (match-string 3 l) (match-string 1 l)))
8153 (princ (format "[%c] %s\n" (incf cnt)
8154 (match-string 1 l))))))
8155 links))
8156 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8157 (message "Select link to open:")
8158 (setq c (read-char-exclusive))
8159 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8160 (when (equal c ?q) (error "Abort"))
8161 (setq nth (- c ?0))
8162 (if have-zero (setq nth (1+ nth)))
8163 (unless (and (integerp nth) (>= (length links) nth))
8164 (error "Invalid link selection"))
8165 (setq link (nth (1- nth) links))))
8166 (org-open-link-from-string link in-emacs (current-buffer))))
8167
8168 ;;;; Time estimates
8169
8170 (defun org-get-effort (&optional pom)
8171 "Get the effort estimate for the current entry."
8172 (org-entry-get pom org-effort-property))
8173
8174 ;;; File search
8175
8176 (defvar org-create-file-search-functions nil
8177 "List of functions to construct the right search string for a file link.
8178 These functions are called in turn with point at the location to
8179 which the link should point.
8180
8181 A function in the hook should first test if it would like to
8182 handle this file type, for example by checking the major-mode or
8183 the file extension. If it decides not to handle this file, it
8184 should just return nil to give other functions a chance. If it
8185 does handle the file, it must return the search string to be used
8186 when following the link. The search string will be part of the
8187 file link, given after a double colon, and `org-open-at-point'
8188 will automatically search for it. If special measures must be
8189 taken to make the search successful, another function should be
8190 added to the companion hook `org-execute-file-search-functions',
8191 which see.
8192
8193 A function in this hook may also use `setq' to set the variable
8194 `description' to provide a suggestion for the descriptive text to
8195 be used for this link when it gets inserted into an Org-mode
8196 buffer with \\[org-insert-link].")
8197
8198 (defvar org-execute-file-search-functions nil
8199 "List of functions to execute a file search triggered by a link.
8200
8201 Functions added to this hook must accept a single argument, the
8202 search string that was part of the file link, the part after the
8203 double colon. The function must first check if it would like to
8204 handle this search, for example by checking the major-mode or the
8205 file extension. If it decides not to handle this search, it
8206 should just return nil to give other functions a chance. If it
8207 does handle the search, it must return a non-nil value to keep
8208 other functions from trying.
8209
8210 Each function can access the current prefix argument through the
8211 variable `current-prefix-argument'. Note that a single prefix is
8212 used to force opening a link in Emacs, so it may be good to only
8213 use a numeric or double prefix to guide the search function.
8214
8215 In case this is needed, a function in this hook can also restore
8216 the window configuration before `org-open-at-point' was called using:
8217
8218 (set-window-configuration org-window-config-before-follow-link)")
8219
8220 (defun org-link-search (s &optional type avoid-pos)
8221 "Search for a link search option.
8222 If S is surrounded by forward slashes, it is interpreted as a
8223 regular expression. In org-mode files, this will create an `org-occur'
8224 sparse tree. In ordinary files, `occur' will be used to list matches.
8225 If the current buffer is in `dired-mode', grep will be used to search
8226 in all files. If AVOID-POS is given, ignore matches near that position."
8227 (let ((case-fold-search t)
8228 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8229 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8230 (append '(("") (" ") ("\t") ("\n"))
8231 org-emphasis-alist)
8232 "\\|") "\\)"))
8233 (pos (point))
8234 (pre nil) (post nil)
8235 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8236 (cond
8237 ;; First check if there are any special
8238 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8239 ;; Now try the builtin stuff
8240 ((and (equal (string-to-char s0) ?#)
8241 (> (length s0) 1)
8242 (save-excursion
8243 (goto-char (point-min))
8244 (and
8245 (re-search-forward
8246 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8247 (setq type 'dedicated
8248 pos (match-beginning 0))))
8249 ;; There is an exact target for this
8250 (goto-char pos)
8251 (org-back-to-heading t)))
8252 ((save-excursion
8253 (goto-char (point-min))
8254 (and
8255 (re-search-forward
8256 (concat "<<" (regexp-quote s0) ">>") nil t)
8257 (setq type 'dedicated
8258 pos (match-beginning 0))))
8259 ;; There is an exact target for this
8260 (goto-char pos))
8261 ((and (string-match "^(\\(.*\\))$" s0)
8262 (save-excursion
8263 (goto-char (point-min))
8264 (and
8265 (re-search-forward
8266 (concat "[^[]" (regexp-quote
8267 (format org-coderef-label-format
8268 (match-string 1 s0))))
8269 nil t)
8270 (setq type 'dedicated
8271 pos (1+ (match-beginning 0))))))
8272 ;; There is a coderef target for this
8273 (goto-char pos))
8274 ((string-match "^/\\(.*\\)/$" s)
8275 ;; A regular expression
8276 (cond
8277 ((org-mode-p)
8278 (org-occur (match-string 1 s)))
8279 ;;((eq major-mode 'dired-mode)
8280 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8281 (t (org-do-occur (match-string 1 s)))))
8282 (t
8283 ;; A normal search strings
8284 (when (equal (string-to-char s) ?*)
8285 ;; Anchor on headlines, post may include tags.
8286 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8287 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8288 s (substring s 1)))
8289 (remove-text-properties
8290 0 (length s)
8291 '(face nil mouse-face nil keymap nil fontified nil) s)
8292 ;; Make a series of regular expressions to find a match
8293 (setq words (org-split-string s "[ \n\r\t]+")
8294
8295 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8296 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8297 "\\)" markers)
8298 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8299 re2a (concat "[ \t\r\n]" re2a_)
8300 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8301 re4 (concat "[^a-zA-Z_]" re4_)
8302
8303 re1 (concat pre re2 post)
8304 re3 (concat pre (if pre re4_ re4) post)
8305 re5 (concat pre ".*" re4)
8306 re2 (concat pre re2)
8307 re2a (concat pre (if pre re2a_ re2a))
8308 re4 (concat pre (if pre re4_ re4))
8309 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8310 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8311 re5 "\\)"
8312 ))
8313 (cond
8314 ((eq type 'org-occur) (org-occur reall))
8315 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8316 (t (goto-char (point-min))
8317 (setq type 'fuzzy)
8318 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8319 (org-search-not-self 1 re1 nil t)
8320 (org-search-not-self 1 re2 nil t)
8321 (org-search-not-self 1 re2a nil t)
8322 (org-search-not-self 1 re3 nil t)
8323 (org-search-not-self 1 re4 nil t)
8324 (org-search-not-self 1 re5 nil t)
8325 )
8326 (goto-char (match-beginning 1))
8327 (goto-char pos)
8328 (error "No match")))))
8329 (t
8330 ;; Normal string-search
8331 (goto-char (point-min))
8332 (if (search-forward s nil t)
8333 (goto-char (match-beginning 0))
8334 (error "No match"))))
8335 (and (org-mode-p) (org-show-context 'link-search))
8336 type))
8337
8338 (defun org-search-not-self (group &rest args)
8339 "Execute `re-search-forward', but only accept matches that do not
8340 enclose the position of `org-open-link-marker'."
8341 (let ((m org-open-link-marker))
8342 (catch 'exit
8343 (while (apply 're-search-forward args)
8344 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8345 (goto-char (match-end group))
8346 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8347 (> (match-beginning 0) (marker-position m))
8348 (< (match-end 0) (marker-position m)))
8349 (save-match-data
8350 (or (not (org-in-regexp
8351 org-bracket-link-analytic-regexp 1))
8352 (not (match-end 4)) ; no description
8353 (and (<= (match-beginning 4) (point))
8354 (>= (match-end 4) (point))))))
8355 (throw 'exit (point))))))))
8356
8357 (defun org-get-buffer-for-internal-link (buffer)
8358 "Return a buffer to be used for displaying the link target of internal links."
8359 (cond
8360 ((not org-display-internal-link-with-indirect-buffer)
8361 buffer)
8362 ((string-match "(Clone)$" (buffer-name buffer))
8363 (message "Buffer is already a clone, not making another one")
8364 ;; we also do not modify visibility in this case
8365 buffer)
8366 (t ; make a new indirect buffer for displaying the link
8367 (let* ((bn (buffer-name buffer))
8368 (ibn (concat bn "(Clone)"))
8369 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8370 (with-current-buffer ib (org-overview))
8371 ib))))
8372
8373 (defun org-do-occur (regexp &optional cleanup)
8374 "Call the Emacs command `occur'.
8375 If CLEANUP is non-nil, remove the printout of the regular expression
8376 in the *Occur* buffer. This is useful if the regex is long and not useful
8377 to read."
8378 (occur regexp)
8379 (when cleanup
8380 (let ((cwin (selected-window)) win beg end)
8381 (when (setq win (get-buffer-window "*Occur*"))
8382 (select-window win))
8383 (goto-char (point-min))
8384 (when (re-search-forward "match[a-z]+" nil t)
8385 (setq beg (match-end 0))
8386 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8387 (setq end (1- (match-beginning 0)))))
8388 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8389 (goto-char (point-min))
8390 (select-window cwin))))
8391
8392 ;;; The mark ring for links jumps
8393
8394 (defvar org-mark-ring nil
8395 "Mark ring for positions before jumps in Org-mode.")
8396 (defvar org-mark-ring-last-goto nil
8397 "Last position in the mark ring used to go back.")
8398 ;; Fill and close the ring
8399 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8400 (loop for i from 1 to org-mark-ring-length do
8401 (push (make-marker) org-mark-ring))
8402 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8403 org-mark-ring)
8404
8405 (defun org-mark-ring-push (&optional pos buffer)
8406 "Put the current position or POS into the mark ring and rotate it."
8407 (interactive)
8408 (setq pos (or pos (point)))
8409 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8410 (move-marker (car org-mark-ring)
8411 (or pos (point))
8412 (or buffer (current-buffer)))
8413 (message "%s"
8414 (substitute-command-keys
8415 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8416
8417 (defun org-mark-ring-goto (&optional n)
8418 "Jump to the previous position in the mark ring.
8419 With prefix arg N, jump back that many stored positions. When
8420 called several times in succession, walk through the entire ring.
8421 Org-mode commands jumping to a different position in the current file,
8422 or to another Org-mode file, automatically push the old position
8423 onto the ring."
8424 (interactive "p")
8425 (let (p m)
8426 (if (eq last-command this-command)
8427 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8428 (setq p org-mark-ring))
8429 (setq org-mark-ring-last-goto p)
8430 (setq m (car p))
8431 (switch-to-buffer (marker-buffer m))
8432 (goto-char m)
8433 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8434
8435 (defun org-remove-angle-brackets (s)
8436 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8437 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8438 s)
8439 (defun org-add-angle-brackets (s)
8440 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8441 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8442 s)
8443 (defun org-remove-double-quotes (s)
8444 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8445 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8446 s)
8447
8448 ;;; Following specific links
8449
8450 (defun org-follow-timestamp-link ()
8451 (cond
8452 ((org-at-date-range-p t)
8453 (let ((org-agenda-start-on-weekday)
8454 (t1 (match-string 1))
8455 (t2 (match-string 2)))
8456 (setq t1 (time-to-days (org-time-string-to-time t1))
8457 t2 (time-to-days (org-time-string-to-time t2)))
8458 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8459 ((org-at-timestamp-p t)
8460 (org-agenda-list nil (time-to-days (org-time-string-to-time
8461 (substring (match-string 1) 0 10)))
8462 1))
8463 (t (error "This should not happen"))))
8464
8465
8466 ;;; Following file links
8467 (defvar org-wait nil)
8468 (defun org-open-file (path &optional in-emacs line search)
8469 "Open the file at PATH.
8470 First, this expands any special file name abbreviations. Then the
8471 configuration variable `org-file-apps' is checked if it contains an
8472 entry for this file type, and if yes, the corresponding command is launched.
8473
8474 If no application is found, Emacs simply visits the file.
8475
8476 With optional prefix argument IN-EMACS, Emacs will visit the file.
8477 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8478 and o use an external application to visit the file.
8479
8480 Optional LINE specifies a line to go to, optional SEARCH a string to
8481 search for. If LINE or SEARCH is given, the file will always be
8482 opened in Emacs.
8483 If the file does not exist, an error is thrown."
8484 (setq in-emacs (or in-emacs line search))
8485 (let* ((file (if (equal path "")
8486 buffer-file-name
8487 (substitute-in-file-name (expand-file-name path))))
8488 (apps (append org-file-apps (org-default-apps)))
8489 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8490 (dirp (if remp nil (file-directory-p file)))
8491 (file (if (and dirp org-open-directory-means-index-dot-org)
8492 (concat (file-name-as-directory file) "index.org")
8493 file))
8494 (a-m-a-p (assq 'auto-mode apps))
8495 (dfile (downcase file))
8496 (old-buffer (current-buffer))
8497 (old-pos (point))
8498 (old-mode major-mode)
8499 ext cmd)
8500 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8501 (setq ext (match-string 1 dfile))
8502 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8503 (setq ext (match-string 1 dfile))))
8504 (cond
8505 ((equal in-emacs '(16))
8506 (setq cmd (cdr (assoc 'system apps))))
8507 (in-emacs (setq cmd 'emacs))
8508 (t
8509 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8510 (and dirp (cdr (assoc 'directory apps)))
8511 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8512 'string-match)
8513 (cdr (assoc ext apps))
8514 (cdr (assoc t apps))))))
8515 (when (eq cmd 'system)
8516 (setq cmd (cdr (assoc 'system apps))))
8517 (when (eq cmd 'default)
8518 (setq cmd (cdr (assoc t apps))))
8519 (when (eq cmd 'mailcap)
8520 (require 'mailcap)
8521 (mailcap-parse-mailcaps)
8522 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8523 (command (mailcap-mime-info mime-type)))
8524 (if (stringp command)
8525 (setq cmd command)
8526 (setq cmd 'emacs))))
8527 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8528 (not (file-exists-p file))
8529 (not org-open-non-existing-files))
8530 (error "No such file: %s" file))
8531 (cond
8532 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8533 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8534 (while (string-match "['\"]%s['\"]" cmd)
8535 (setq cmd (replace-match "%s" t t cmd)))
8536 (while (string-match "%s" cmd)
8537 (setq cmd (replace-match
8538 (save-match-data
8539 (shell-quote-argument
8540 (convert-standard-filename file)))
8541 t t cmd)))
8542 (save-window-excursion
8543 (start-process-shell-command cmd nil cmd)
8544 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8545 ))
8546 ((or (stringp cmd)
8547 (eq cmd 'emacs))
8548 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8549 (widen)
8550 (if line (org-goto-line line)
8551 (if search (org-link-search search))))
8552 ((consp cmd)
8553 (let ((file (convert-standard-filename file)))
8554 (eval cmd)))
8555 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8556 (and (org-mode-p) (eq old-mode 'org-mode)
8557 (or (not (equal old-buffer (current-buffer)))
8558 (not (equal old-pos (point))))
8559 (org-mark-ring-push old-pos old-buffer))))
8560
8561 (defun org-default-apps ()
8562 "Return the default applications for this operating system."
8563 (cond
8564 ((eq system-type 'darwin)
8565 org-file-apps-defaults-macosx)
8566 ((eq system-type 'windows-nt)
8567 org-file-apps-defaults-windowsnt)
8568 (t org-file-apps-defaults-gnu)))
8569
8570 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8571 "Convert extensions to regular expressions in the cars of LIST.
8572 Also, weed out any non-string entries, because the return value is used
8573 only for regexp matching.
8574 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8575 point to the symbol `emacs', indicating that the file should
8576 be opened in Emacs."
8577 (append
8578 (delq nil
8579 (mapcar (lambda (x)
8580 (if (not (stringp (car x)))
8581 nil
8582 (if (string-match "\\W" (car x))
8583 x
8584 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8585 list))
8586 (if add-auto-mode
8587 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8588
8589 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8590 (defun org-file-remote-p (file)
8591 "Test whether FILE specifies a location on a remote system.
8592 Return non-nil if the location is indeed remote.
8593
8594 For example, the filename \"/user@host:/foo\" specifies a location
8595 on the system \"/user@host:\"."
8596 (cond ((fboundp 'file-remote-p)
8597 (file-remote-p file))
8598 ((fboundp 'tramp-handle-file-remote-p)
8599 (tramp-handle-file-remote-p file))
8600 ((and (boundp 'ange-ftp-name-format)
8601 (string-match (car ange-ftp-name-format) file))
8602 t)
8603 (t nil)))
8604
8605
8606 ;;;; Refiling
8607
8608 (defun org-get-org-file ()
8609 "Read a filename, with default directory `org-directory'."
8610 (let ((default (or org-default-notes-file remember-data-file)))
8611 (read-file-name (format "File name [%s]: " default)
8612 (file-name-as-directory org-directory)
8613 default)))
8614
8615 (defun org-notes-order-reversed-p ()
8616 "Check if the current file should receive notes in reversed order."
8617 (cond
8618 ((not org-reverse-note-order) nil)
8619 ((eq t org-reverse-note-order) t)
8620 ((not (listp org-reverse-note-order)) nil)
8621 (t (catch 'exit
8622 (let ((all org-reverse-note-order)
8623 entry)
8624 (while (setq entry (pop all))
8625 (if (string-match (car entry) buffer-file-name)
8626 (throw 'exit (cdr entry))))
8627 nil)))))
8628
8629 (defvar org-refile-target-table nil
8630 "The list of refile targets, created by `org-refile'.")
8631
8632 (defvar org-agenda-new-buffers nil
8633 "Buffers created to visit agenda files.")
8634
8635 (defun org-get-refile-targets (&optional default-buffer)
8636 "Produce a table with refile targets."
8637 (let ((case-fold-search nil)
8638 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8639 (entries (or org-refile-targets '((nil . (:level . 1)))))
8640 targets txt re files f desc descre fast-path-p level pos0)
8641 (message "Getting targets...")
8642 (with-current-buffer (or default-buffer (current-buffer))
8643 (while (setq entry (pop entries))
8644 (setq files (car entry) desc (cdr entry))
8645 (setq fast-path-p nil)
8646 (cond
8647 ((null files) (setq files (list (current-buffer))))
8648 ((eq files 'org-agenda-files)
8649 (setq files (org-agenda-files 'unrestricted)))
8650 ((and (symbolp files) (fboundp files))
8651 (setq files (funcall files)))
8652 ((and (symbolp files) (boundp files))
8653 (setq files (symbol-value files))))
8654 (if (stringp files) (setq files (list files)))
8655 (cond
8656 ((eq (car desc) :tag)
8657 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8658 ((eq (car desc) :todo)
8659 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8660 ((eq (car desc) :regexp)
8661 (setq descre (cdr desc)))
8662 ((eq (car desc) :level)
8663 (setq descre (concat "^\\*\\{" (number-to-string
8664 (if org-odd-levels-only
8665 (1- (* 2 (cdr desc)))
8666 (cdr desc)))
8667 "\\}[ \t]")))
8668 ((eq (car desc) :maxlevel)
8669 (setq fast-path-p t)
8670 (setq descre (concat "^\\*\\{1," (number-to-string
8671 (if org-odd-levels-only
8672 (1- (* 2 (cdr desc)))
8673 (cdr desc)))
8674 "\\}[ \t]")))
8675 (t (error "Bad refiling target description %s" desc)))
8676 (while (setq f (pop files))
8677 (save-excursion
8678 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8679 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8680 (setq f (expand-file-name f))
8681 (if (eq org-refile-use-outline-path 'file)
8682 (push (list (file-name-nondirectory f) f nil nil) targets))
8683 (save-excursion
8684 (save-restriction
8685 (widen)
8686 (goto-char (point-min))
8687 (while (re-search-forward descre nil t)
8688 (goto-char (setq pos0 (point-at-bol)))
8689 (catch 'next
8690 (when org-refile-target-verify-function
8691 (save-match-data
8692 (or (funcall org-refile-target-verify-function)
8693 (throw 'next t))))
8694 (when (looking-at org-complex-heading-regexp)
8695 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8696 txt (org-link-display-format (match-string 4))
8697 re (concat "^" (regexp-quote
8698 (buffer-substring (match-beginning 1)
8699 (match-end 4)))))
8700 (if (match-end 5) (setq re (concat re "[ \t]+"
8701 (regexp-quote
8702 (match-string 5)))))
8703 (setq re (concat re "[ \t]*$"))
8704 (when org-refile-use-outline-path
8705 (setq txt (mapconcat 'org-protect-slash
8706 (append
8707 (if (eq org-refile-use-outline-path 'file)
8708 (list (file-name-nondirectory
8709 (buffer-file-name (buffer-base-buffer))))
8710 (if (eq org-refile-use-outline-path 'full-file-path)
8711 (list (buffer-file-name (buffer-base-buffer)))))
8712 (org-get-outline-path fast-path-p level txt)
8713 (list txt))
8714 "/")))
8715 (push (list txt f re (point)) targets)))
8716 (when (= (point) pos0)
8717 ;; verification function has not moved point
8718 (goto-char (point-at-eol))))))))))
8719 (message "Getting targets...done")
8720 (nreverse targets)))
8721
8722 (defun org-protect-slash (s)
8723 (while (string-match "/" s)
8724 (setq s (replace-match "\\" t t s)))
8725 s)
8726
8727 (defvar org-olpa (make-vector 20 nil))
8728
8729 (defun org-get-outline-path (&optional fastp level heading)
8730 "Return the outline path to the current entry, as a list."
8731 (if fastp
8732 (progn
8733 (if (> level 19)
8734 (error "Outline path failure, more than 19 levels."))
8735 (loop for i from level upto 19 do
8736 (aset org-olpa i nil))
8737 (prog1
8738 (delq nil (append org-olpa nil))
8739 (aset org-olpa level heading)))
8740 (let (rtn)
8741 (save-excursion
8742 (while (org-up-heading-safe)
8743 (when (looking-at org-complex-heading-regexp)
8744 (push (org-match-string-no-properties 4) rtn)))
8745 rtn))))
8746
8747 (defvar org-refile-history nil
8748 "History for refiling operations.")
8749
8750 (defvar org-after-refile-insert-hook nil
8751 "Hook run after `org-refile' has inserted its stuff at the new location.
8752 Note that this is still *before* the stuff will be removed from
8753 the *old* location.")
8754
8755 (defun org-refile (&optional goto default-buffer rfloc)
8756 "Move the entry at point to another heading.
8757 The list of target headings is compiled using the information in
8758 `org-refile-targets', which see. This list is created before each use
8759 and will therefore always be up-to-date.
8760
8761 At the target location, the entry is filed as a subitem of the target heading.
8762 Depending on `org-reverse-note-order', the new subitem will either be the
8763 first or the last subitem.
8764
8765 If there is an active region, all entries in that region will be moved.
8766 However, the region must fulfil the requirement that the first heading
8767 is the first one sets the top-level of the moved text - at most siblings
8768 below it are allowed.
8769
8770 With prefix arg GOTO, the command will only visit the target location,
8771 not actually move anything.
8772 With a double prefix `C-u C-u', go to the location where the last refiling
8773 operation has put the subtree.
8774
8775 RFLOC can be a refile location obtained in a different way.
8776
8777 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8778 (interactive "P")
8779 (let* ((cbuf (current-buffer))
8780 (regionp (org-region-active-p))
8781 (region-start (and regionp (region-beginning)))
8782 (region-end (and regionp (region-end)))
8783 (region-length (and regionp (- region-end region-start)))
8784 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8785 pos it nbuf file re level reversed)
8786 (when regionp
8787 (goto-char region-start)
8788 (or (bolp) (goto-char (point-at-bol)))
8789 (setq region-start (point))
8790 (unless (org-kill-is-subtree-p
8791 (buffer-substring region-start region-end))
8792 (error "The region is not a (sequence of) subtree(s)")))
8793 (if (equal goto '(16))
8794 (org-refile-goto-last-stored)
8795 (when (setq it (or rfloc
8796 (save-excursion
8797 (org-refile-get-location
8798 (if goto "Goto: " "Refile to: ") default-buffer
8799 org-refile-allow-creating-parent-nodes))))
8800 (setq file (nth 1 it)
8801 re (nth 2 it)
8802 pos (nth 3 it))
8803 (if (and (not goto)
8804 pos
8805 (equal (buffer-file-name) file)
8806 (if regionp
8807 (and (>= pos region-start)
8808 (<= pos region-end))
8809 (and (>= pos (point))
8810 (< pos (save-excursion
8811 (org-end-of-subtree t t))))))
8812 (error "Cannot refile to position inside the tree or region"))
8813
8814 (setq nbuf (or (find-buffer-visiting file)
8815 (find-file-noselect file)))
8816 (if goto
8817 (progn
8818 (switch-to-buffer nbuf)
8819 (goto-char pos)
8820 (org-show-context 'org-goto))
8821 (if regionp
8822 (progn
8823 (org-kill-new (buffer-substring region-start region-end))
8824 (org-save-markers-in-region region-start region-end))
8825 (org-copy-subtree 1 nil t))
8826 (save-excursion
8827 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8828 (find-file-noselect file))))
8829 (setq reversed (org-notes-order-reversed-p))
8830 (save-excursion
8831 (save-restriction
8832 (widen)
8833 (if pos
8834 (progn
8835 (goto-char pos)
8836 (looking-at outline-regexp)
8837 (setq level (org-get-valid-level (funcall outline-level) 1))
8838 (goto-char
8839 (if reversed
8840 (or (outline-next-heading) (point-max))
8841 (or (save-excursion (org-get-next-sibling))
8842 (org-end-of-subtree t t)
8843 (point-max)))))
8844 (setq level 1)
8845 (if (not reversed)
8846 (goto-char (point-max))
8847 (goto-char (point-min))
8848 (or (outline-next-heading) (goto-char (point-max)))))
8849 (if (not (bolp)) (newline))
8850 (bookmark-set "org-refile-last-stored")
8851 (org-paste-subtree level)
8852 (if (fboundp 'deactivate-mark) (deactivate-mark))
8853 (run-hooks 'org-after-refile-insert-hook))))
8854 (if regionp
8855 (delete-region (point) (+ (point) region-length))
8856 (org-cut-subtree))
8857 (when (featurep 'org-inlinetask)
8858 (org-inlinetask-remove-END-maybe))
8859 (setq org-markers-to-move nil)
8860 (message "Refiled to \"%s\"" (car it))))))
8861 (org-reveal))
8862
8863 (defun org-refile-goto-last-stored ()
8864 "Go to the location where the last refile was stored."
8865 (interactive)
8866 (bookmark-jump "org-refile-last-stored")
8867 (message "This is the location of the last refile"))
8868
8869 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8870 "Prompt the user for a refile location, using PROMPT."
8871 (let ((org-refile-targets org-refile-targets)
8872 (org-refile-use-outline-path org-refile-use-outline-path))
8873 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8874 (unless org-refile-target-table
8875 (error "No refile targets"))
8876 (let* ((cbuf (current-buffer))
8877 (partial-completion-mode nil)
8878 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8879 (cfunc (if (and org-refile-use-outline-path
8880 org-outline-path-complete-in-steps)
8881 'org-olpath-completing-read
8882 'org-icompleting-read))
8883 (extra (if org-refile-use-outline-path "/" ""))
8884 (filename (and cfn (expand-file-name cfn)))
8885 (tbl (mapcar
8886 (lambda (x)
8887 (if (and (not (member org-refile-use-outline-path
8888 '(file full-file-path)))
8889 (not (equal filename (nth 1 x))))
8890 (cons (concat (car x) extra " ("
8891 (file-name-nondirectory (nth 1 x)) ")")
8892 (cdr x))
8893 (cons (concat (car x) extra) (cdr x))))
8894 org-refile-target-table))
8895 (completion-ignore-case t)
8896 pa answ parent-target child parent old-hist)
8897 (setq old-hist org-refile-history)
8898 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8899 nil 'org-refile-history))
8900 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8901 (if pa
8902 (progn
8903 (when (or (not org-refile-history)
8904 (not (eq old-hist org-refile-history))
8905 (not (equal (car pa) (car org-refile-history))))
8906 (setq org-refile-history
8907 (cons (car pa) (if (assoc (car org-refile-history) tbl)
8908 org-refile-history
8909 (cdr org-refile-history))))
8910 (if (equal (car org-refile-history) (nth 1 org-refile-history))
8911 (pop org-refile-history)))
8912 pa)
8913 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8914 (setq parent (match-string 1 answ)
8915 child (match-string 2 answ))
8916 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8917 (when (and parent-target
8918 (or (eq new-nodes t)
8919 (and (eq new-nodes 'confirm)
8920 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8921 (org-refile-new-child parent-target child))))))
8922
8923 (defun org-refile-new-child (parent-target child)
8924 "Use refile target PARENT-TARGET to add new CHILD below it."
8925 (unless parent-target
8926 (error "Cannot find parent for new node"))
8927 (let ((file (nth 1 parent-target))
8928 (pos (nth 3 parent-target))
8929 level)
8930 (with-current-buffer (or (find-buffer-visiting file)
8931 (find-file-noselect file))
8932 (save-excursion
8933 (save-restriction
8934 (widen)
8935 (if pos
8936 (goto-char pos)
8937 (goto-char (point-max))
8938 (if (not (bolp)) (newline)))
8939 (when (looking-at outline-regexp)
8940 (setq level (funcall outline-level))
8941 (org-end-of-subtree t t))
8942 (org-back-over-empty-lines)
8943 (insert "\n" (make-string
8944 (if pos (org-get-valid-level level 1) 1) ?*)
8945 " " child "\n")
8946 (beginning-of-line 0)
8947 (list (concat (car parent-target) "/" child) file "" (point)))))))
8948
8949 (defun org-olpath-completing-read (prompt collection &rest args)
8950 "Read an outline path like a file name."
8951 (let ((thetable collection)
8952 (org-completion-use-ido nil) ; does not work with ido.
8953 (org-completion-use-iswitchb nil)) ; or iswitchb
8954 (apply
8955 'org-icompleting-read prompt
8956 (lambda (string predicate &optional flag)
8957 (let (rtn r f (l (length string)))
8958 (cond
8959 ((eq flag nil)
8960 ;; try completion
8961 (try-completion string thetable))
8962 ((eq flag t)
8963 ;; all-completions
8964 (setq rtn (all-completions string thetable predicate))
8965 (mapcar
8966 (lambda (x)
8967 (setq r (substring x l))
8968 (if (string-match " ([^)]*)$" x)
8969 (setq f (match-string 0 x))
8970 (setq f ""))
8971 (if (string-match "/" r)
8972 (concat string (substring r 0 (match-end 0)) f)
8973 x))
8974 rtn))
8975 ((eq flag 'lambda)
8976 ;; exact match?
8977 (assoc string thetable)))
8978 ))
8979 args)))
8980
8981 ;;;; Dynamic blocks
8982
8983 (defun org-find-dblock (name)
8984 "Find the first dynamic block with name NAME in the buffer.
8985 If not found, stay at current position and return nil."
8986 (let (pos)
8987 (save-excursion
8988 (goto-char (point-min))
8989 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8990 nil t)
8991 (match-beginning 0))))
8992 (if pos (goto-char pos))
8993 pos))
8994
8995 (defconst org-dblock-start-re
8996 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8997 "Matches the startline of a dynamic block, with parameters.")
8998
8999 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9000 "Matches the end of a dynamic block.")
9001
9002 (defun org-create-dblock (plist)
9003 "Create a dynamic block section, with parameters taken from PLIST.
9004 PLIST must contain a :name entry which is used as name of the block."
9005 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9006 (end-of-line 1)
9007 (newline))
9008 (let ((col (current-column))
9009 (name (plist-get plist :name)))
9010 (insert "#+BEGIN: " name)
9011 (while plist
9012 (if (eq (car plist) :name)
9013 (setq plist (cddr plist))
9014 (insert " " (prin1-to-string (pop plist)))))
9015 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9016 (beginning-of-line -2)))
9017
9018 (defun org-prepare-dblock ()
9019 "Prepare dynamic block for refresh.
9020 This empties the block, puts the cursor at the insert position and returns
9021 the property list including an extra property :name with the block name."
9022 (unless (looking-at org-dblock-start-re)
9023 (error "Not at a dynamic block"))
9024 (let* ((begdel (1+ (match-end 0)))
9025 (name (org-no-properties (match-string 1)))
9026 (params (append (list :name name)
9027 (read (concat "(" (match-string 3) ")")))))
9028 (save-excursion
9029 (beginning-of-line 1)
9030 (skip-chars-forward " \t")
9031 (setq params (plist-put params :indentation-column (current-column))))
9032 (unless (re-search-forward org-dblock-end-re nil t)
9033 (error "Dynamic block not terminated"))
9034 (setq params
9035 (append params
9036 (list :content (buffer-substring
9037 begdel (match-beginning 0)))))
9038 (delete-region begdel (match-beginning 0))
9039 (goto-char begdel)
9040 (open-line 1)
9041 params))
9042
9043 (defun org-map-dblocks (&optional command)
9044 "Apply COMMAND to all dynamic blocks in the current buffer.
9045 If COMMAND is not given, use `org-update-dblock'."
9046 (let ((cmd (or command 'org-update-dblock))
9047 pos)
9048 (save-excursion
9049 (goto-char (point-min))
9050 (while (re-search-forward org-dblock-start-re nil t)
9051 (goto-char (setq pos (match-beginning 0)))
9052 (condition-case nil
9053 (funcall cmd)
9054 (error (message "Error during update of dynamic block")))
9055 (goto-char pos)
9056 (unless (re-search-forward org-dblock-end-re nil t)
9057 (error "Dynamic block not terminated"))))))
9058
9059 (defun org-dblock-update (&optional arg)
9060 "User command for updating dynamic blocks.
9061 Update the dynamic block at point. With prefix ARG, update all dynamic
9062 blocks in the buffer."
9063 (interactive "P")
9064 (if arg
9065 (org-update-all-dblocks)
9066 (or (looking-at org-dblock-start-re)
9067 (org-beginning-of-dblock))
9068 (org-update-dblock)))
9069
9070 (defun org-update-dblock ()
9071 "Update the dynamic block at point
9072 This means to empty the block, parse for parameters and then call
9073 the correct writing function."
9074 (save-window-excursion
9075 (let* ((pos (point))
9076 (line (org-current-line))
9077 (params (org-prepare-dblock))
9078 (name (plist-get params :name))
9079 (indent (plist-get params :indentation-column))
9080 (cmd (intern (concat "org-dblock-write:" name))))
9081 (message "Updating dynamic block `%s' at line %d..." name line)
9082 (funcall cmd params)
9083 (message "Updating dynamic block `%s' at line %d...done" name line)
9084 (goto-char pos)
9085 (when (and indent (> indent 0))
9086 (setq indent (make-string indent ?\ ))
9087 (save-excursion
9088 (org-beginning-of-dblock)
9089 (forward-line 1)
9090 (while (not (looking-at org-dblock-end-re))
9091 (insert indent)
9092 (beginning-of-line 2))
9093 (when (looking-at org-dblock-end-re)
9094 (and (looking-at "[ \t]+")
9095 (replace-match ""))
9096 (insert indent)))))))
9097
9098 (defun org-beginning-of-dblock ()
9099 "Find the beginning of the dynamic block at point.
9100 Error if there is no such block at point."
9101 (let ((pos (point))
9102 beg)
9103 (end-of-line 1)
9104 (if (and (re-search-backward org-dblock-start-re nil t)
9105 (setq beg (match-beginning 0))
9106 (re-search-forward org-dblock-end-re nil t)
9107 (> (match-end 0) pos))
9108 (goto-char beg)
9109 (goto-char pos)
9110 (error "Not in a dynamic block"))))
9111
9112 (defun org-update-all-dblocks ()
9113 "Update all dynamic blocks in the buffer.
9114 This function can be used in a hook."
9115 (when (org-mode-p)
9116 (org-map-dblocks 'org-update-dblock)))
9117
9118
9119 ;;;; Completion
9120
9121 (defconst org-additional-option-like-keywords
9122 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9123 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9124 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "LATEX_CLASS:" "ATTR_LaTeX"
9125 "BEGIN:" "END:"
9126 "ORGTBL" "TBLFM:" "TBLNAME:"
9127 "BEGIN_EXAMPLE" "END_EXAMPLE"
9128 "BEGIN_QUOTE" "END_QUOTE"
9129 "BEGIN_VERSE" "END_VERSE"
9130 "BEGIN_CENTER" "END_CENTER"
9131 "BEGIN_SRC" "END_SRC"
9132 "CATEGORY" "COLUMNS"
9133 "CAPTION" "LABEL"
9134 "BIND"
9135 "MACRO"))
9136
9137 (defcustom org-structure-template-alist
9138 '(
9139 ("s" "#+begin_src ?\n\n#+end_src"
9140 "<src lang=\"?\">\n\n</src>")
9141 ("e" "#+begin_example\n?\n#+end_example"
9142 "<example>\n?\n</example>")
9143 ("q" "#+begin_quote\n?\n#+end_quote"
9144 "<quote>\n?\n</quote>")
9145 ("v" "#+begin_verse\n?\n#+end_verse"
9146 "<verse>\n?\n/verse>")
9147 ("c" "#+begin_center\n?\n#+end_center"
9148 "<center>\n?\n/center>")
9149 ("l" "#+begin_latex\n?\n#+end_latex"
9150 "<literal style=\"latex\">\n?\n</literal>")
9151 ("L" "#+latex: "
9152 "<literal style=\"latex\">?</literal>")
9153 ("h" "#+begin_html\n?\n#+end_html"
9154 "<literal style=\"html\">\n?\n</literal>")
9155 ("H" "#+html: "
9156 "<literal style=\"html\">?</literal>")
9157 ("a" "#+begin_ascii\n?\n#+end_ascii")
9158 ("A" "#+ascii: ")
9159 ("i" "#+include %file ?"
9160 "<include file=%file markup=\"?\">")
9161 )
9162 "Structure completion elements.
9163 This is a list of abbreviation keys and values. The value gets inserted
9164 it you type @samp{.} followed by the key and then the completion key,
9165 usually `M-TAB'. %file will be replaced by a file name after prompting
9166 for the file using completion.
9167 There are two templates for each key, the first uses the original Org syntax,
9168 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9169 the default when the /org-mtags.el/ module has been loaded. See also the
9170 variable `org-mtags-prefer-muse-templates'.
9171 This is an experimental feature, it is undecided if it is going to stay in."
9172 :group 'org-completion
9173 :type '(repeat
9174 (string :tag "Key")
9175 (string :tag "Template")
9176 (string :tag "Muse Template")))
9177
9178 (defun org-try-structure-completion ()
9179 "Try to complete a structure template before point.
9180 This looks for strings like \"<e\" on an otherwise empty line and
9181 expands them."
9182 (let ((l (buffer-substring (point-at-bol) (point)))
9183 a)
9184 (when (and (looking-at "[ \t]*$")
9185 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9186 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9187 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9188 (match-beginning 1)) a)
9189 t)))
9190
9191 (defun org-complete-expand-structure-template (start cell)
9192 "Expand a structure template."
9193 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9194 (rpl (nth (if musep 2 1) cell))
9195 (ind ""))
9196 (delete-region start (point))
9197 (when (string-match "\\`#\\+" rpl)
9198 (cond
9199 ((bolp))
9200 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9201 (setq ind (buffer-substring (point-at-bol) (point))))
9202 (t (newline))))
9203 (setq start (point))
9204 (if (string-match "%file" rpl)
9205 (setq rpl (replace-match
9206 (concat
9207 "\""
9208 (save-match-data
9209 (abbreviate-file-name (read-file-name "Include file: ")))
9210 "\"")
9211 t t rpl)))
9212 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9213 (concat "\n" ind)))
9214 (insert rpl)
9215 (if (re-search-backward "\\?" start t) (delete-char 1))))
9216
9217
9218 (defun org-complete (&optional arg)
9219 "Perform completion on word at point.
9220 At the beginning of a headline, this completes TODO keywords as given in
9221 `org-todo-keywords'.
9222 If the current word is preceded by a backslash, completes the TeX symbols
9223 that are supported for HTML support.
9224 If the current word is preceded by \"#+\", completes special words for
9225 setting file options.
9226 In the line after \"#+STARTUP:, complete valid keywords.\"
9227 At all other locations, this simply calls the value of
9228 `org-completion-fallback-command'."
9229 (interactive "P")
9230 (org-without-partial-completion
9231 (catch 'exit
9232 (let* ((a nil)
9233 (end (point))
9234 (beg1 (save-excursion
9235 (skip-chars-backward (org-re "[:alnum:]_@"))
9236 (point)))
9237 (beg (save-excursion
9238 (skip-chars-backward "a-zA-Z0-9_:$")
9239 (point)))
9240 (confirm (lambda (x) (stringp (car x))))
9241 (searchhead (equal (char-before beg) ?*))
9242 (struct
9243 (when (and (member (char-before beg1) '(?. ?<))
9244 (setq a (assoc (buffer-substring beg1 (point))
9245 org-structure-template-alist)))
9246 (org-complete-expand-structure-template (1- beg1) a)
9247 (throw 'exit t)))
9248 (tag (and (equal (char-before beg1) ?:)
9249 (equal (char-after (point-at-bol)) ?*)))
9250 (prop (and (equal (char-before beg1) ?:)
9251 (not (equal (char-after (point-at-bol)) ?*))))
9252 (texp (equal (char-before beg) ?\\))
9253 (link (equal (char-before beg) ?\[))
9254 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9255 beg)
9256 "#+"))
9257 (startup (string-match "^#\\+STARTUP:.*"
9258 (buffer-substring (point-at-bol) (point))))
9259 (completion-ignore-case opt)
9260 (type nil)
9261 (tbl nil)
9262 (table (cond
9263 (opt
9264 (setq type :opt)
9265 (require 'org-exp)
9266 (append
9267 (delq nil
9268 (mapcar
9269 (lambda (x)
9270 (if (string-match
9271 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9272 (cons (match-string 2 x)
9273 (match-string 1 x))))
9274 (org-split-string (org-get-current-options) "\n")))
9275 (mapcar 'list org-additional-option-like-keywords)))
9276 (startup
9277 (setq type :startup)
9278 org-startup-options)
9279 (link (append org-link-abbrev-alist-local
9280 org-link-abbrev-alist))
9281 (texp
9282 (setq type :tex)
9283 org-html-entities)
9284 ((string-match "\\`\\*+[ \t]+\\'"
9285 (buffer-substring (point-at-bol) beg))
9286 (setq type :todo)
9287 (mapcar 'list org-todo-keywords-1))
9288 (searchhead
9289 (setq type :searchhead)
9290 (save-excursion
9291 (goto-char (point-min))
9292 (while (re-search-forward org-todo-line-regexp nil t)
9293 (push (list
9294 (org-make-org-heading-search-string
9295 (match-string 3) t))
9296 tbl)))
9297 tbl)
9298 (tag (setq type :tag beg beg1)
9299 (or org-tag-alist (org-get-buffer-tags)))
9300 (prop (setq type :prop beg beg1)
9301 (mapcar 'list (org-buffer-property-keys nil t t)))
9302 (t (progn
9303 (call-interactively org-completion-fallback-command)
9304 (throw 'exit nil)))))
9305 (pattern (buffer-substring-no-properties beg end))
9306 (completion (try-completion pattern table confirm)))
9307 (cond ((eq completion t)
9308 (if (not (assoc (upcase pattern) table))
9309 (message "Already complete")
9310 (if (and (equal type :opt)
9311 (not (member (car (assoc (upcase pattern) table))
9312 org-additional-option-like-keywords)))
9313 (insert (substring (cdr (assoc (upcase pattern) table))
9314 (length pattern)))
9315 (if (memq type '(:tag :prop)) (insert ":")))))
9316 ((null completion)
9317 (message "Can't find completion for \"%s\"" pattern)
9318 (ding))
9319 ((not (string= pattern completion))
9320 (delete-region beg end)
9321 (if (string-match " +$" completion)
9322 (setq completion (replace-match "" t t completion)))
9323 (insert completion)
9324 (if (get-buffer-window "*Completions*")
9325 (delete-window (get-buffer-window "*Completions*")))
9326 (if (assoc completion table)
9327 (if (eq type :todo) (insert " ")
9328 (if (memq type '(:tag :prop)) (insert ":"))))
9329 (if (and (equal type :opt) (assoc completion table))
9330 (message "%s" (substitute-command-keys
9331 "Press \\[org-complete] again to insert example settings"))))
9332 (t
9333 (message "Making completion list...")
9334 (let ((list (sort (all-completions pattern table confirm)
9335 'string<)))
9336 (with-output-to-temp-buffer "*Completions*"
9337 (condition-case nil
9338 ;; Protection needed for XEmacs and emacs 21
9339 (display-completion-list list pattern)
9340 (error (display-completion-list list)))))
9341 (message "Making completion list...%s" "done")))))))
9342
9343 ;;;; TODO, DEADLINE, Comments
9344
9345 (defun org-toggle-comment ()
9346 "Change the COMMENT state of an entry."
9347 (interactive)
9348 (save-excursion
9349 (org-back-to-heading)
9350 (let (case-fold-search)
9351 (if (looking-at (concat outline-regexp
9352 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9353 (replace-match "" t t nil 1)
9354 (if (looking-at outline-regexp)
9355 (progn
9356 (goto-char (match-end 0))
9357 (insert org-comment-string " ")))))))
9358
9359 (defvar org-last-todo-state-is-todo nil
9360 "This is non-nil when the last TODO state change led to a TODO state.
9361 If the last change removed the TODO tag or switched to DONE, then
9362 this is nil.")
9363
9364 (defvar org-setting-tags nil) ; dynamically skipped
9365
9366 (defun org-parse-local-options (string var)
9367 "Parse STRING for startup setting relevant for variable VAR."
9368 (let ((rtn (symbol-value var))
9369 e opts)
9370 (save-match-data
9371 (if (or (not string) (not (string-match "\\S-" string)))
9372 rtn
9373 (setq opts (delq nil (mapcar (lambda (x)
9374 (setq e (assoc x org-startup-options))
9375 (if (eq (nth 1 e) var) e nil))
9376 (org-split-string string "[ \t]+"))))
9377 (if (not opts)
9378 rtn
9379 (setq rtn nil)
9380 (while (setq e (pop opts))
9381 (if (not (nth 3 e))
9382 (setq rtn (nth 2 e))
9383 (if (not (listp rtn)) (setq rtn nil))
9384 (push (nth 2 e) rtn)))
9385 rtn)))))
9386
9387 (defvar org-todo-setup-filter-hook nil
9388 "Hook for functions that pre-filter todo specs.
9389
9390 Each function takes a todo spec and returns either `nil' or the spec
9391 transformed into canonical form." )
9392
9393 (defvar org-todo-get-default-hook nil
9394 "Hook for functions that get a default item for todo.
9395
9396 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9397 `nil' or a string to be used for the todo mark." )
9398
9399 (defvar org-agenda-headline-snapshot-before-repeat)
9400
9401 (defun org-todo (&optional arg)
9402 "Change the TODO state of an item.
9403 The state of an item is given by a keyword at the start of the heading,
9404 like
9405 *** TODO Write paper
9406 *** DONE Call mom
9407
9408 The different keywords are specified in the variable `org-todo-keywords'.
9409 By default the available states are \"TODO\" and \"DONE\".
9410 So for this example: when the item starts with TODO, it is changed to DONE.
9411 When it starts with DONE, the DONE is removed. And when neither TODO nor
9412 DONE are present, add TODO at the beginning of the heading.
9413
9414 With C-u prefix arg, use completion to determine the new state.
9415 With numeric prefix arg, switch to that state.
9416 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9417 With a tripple C-u prefix, circumvent any state blocking.
9418
9419 For calling through lisp, arg is also interpreted in the following way:
9420 'none -> empty state
9421 \"\"(empty string) -> switch to empty state
9422 'done -> switch to DONE
9423 'nextset -> switch to the next set of keywords
9424 'previousset -> switch to the previous set of keywords
9425 \"WAITING\" -> switch to the specified keyword, but only if it
9426 really is a member of `org-todo-keywords'."
9427 (interactive "P")
9428 (if (equal arg '(16)) (setq arg 'nextset))
9429 (let ((org-blocker-hook org-blocker-hook)
9430 (case-fold-search nil))
9431 (when (equal arg '(64))
9432 (setq arg nil org-blocker-hook nil))
9433 (when (and org-blocker-hook
9434 (or org-inhibit-blocking
9435 (org-entry-get nil "NOBLOCKING")))
9436 (setq org-blocker-hook nil))
9437 (save-excursion
9438 (catch 'exit
9439 (org-back-to-heading)
9440 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9441 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9442 (looking-at " *"))
9443 (let* ((match-data (match-data))
9444 (startpos (point-at-bol))
9445 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9446 (org-log-done org-log-done)
9447 (org-log-repeat org-log-repeat)
9448 (org-todo-log-states org-todo-log-states)
9449 (this (match-string 1))
9450 (hl-pos (match-beginning 0))
9451 (head (org-get-todo-sequence-head this))
9452 (ass (assoc head org-todo-kwd-alist))
9453 (interpret (nth 1 ass))
9454 (done-word (nth 3 ass))
9455 (final-done-word (nth 4 ass))
9456 (last-state (or this ""))
9457 (completion-ignore-case t)
9458 (member (member this org-todo-keywords-1))
9459 (tail (cdr member))
9460 (state (cond
9461 ((and org-todo-key-trigger
9462 (or (and (equal arg '(4))
9463 (eq org-use-fast-todo-selection 'prefix))
9464 (and (not arg) org-use-fast-todo-selection
9465 (not (eq org-use-fast-todo-selection
9466 'prefix)))))
9467 ;; Use fast selection
9468 (org-fast-todo-selection))
9469 ((and (equal arg '(4))
9470 (or (not org-use-fast-todo-selection)
9471 (not org-todo-key-trigger)))
9472 ;; Read a state with completion
9473 (org-icompleting-read
9474 "State: " (mapcar (lambda(x) (list x))
9475 org-todo-keywords-1)
9476 nil t))
9477 ((eq arg 'right)
9478 (if this
9479 (if tail (car tail) nil)
9480 (car org-todo-keywords-1)))
9481 ((eq arg 'left)
9482 (if (equal member org-todo-keywords-1)
9483 nil
9484 (if this
9485 (nth (- (length org-todo-keywords-1)
9486 (length tail) 2)
9487 org-todo-keywords-1)
9488 (org-last org-todo-keywords-1))))
9489 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9490 (setq arg nil))) ; hack to fall back to cycling
9491 (arg
9492 ;; user or caller requests a specific state
9493 (cond
9494 ((equal arg "") nil)
9495 ((eq arg 'none) nil)
9496 ((eq arg 'done) (or done-word (car org-done-keywords)))
9497 ((eq arg 'nextset)
9498 (or (car (cdr (member head org-todo-heads)))
9499 (car org-todo-heads)))
9500 ((eq arg 'previousset)
9501 (let ((org-todo-heads (reverse org-todo-heads)))
9502 (or (car (cdr (member head org-todo-heads)))
9503 (car org-todo-heads))))
9504 ((car (member arg org-todo-keywords-1)))
9505 ((nth (1- (prefix-numeric-value arg))
9506 org-todo-keywords-1))))
9507 ((null member) (or head (car org-todo-keywords-1)))
9508 ((equal this final-done-word) nil) ;; -> make empty
9509 ((null tail) nil) ;; -> first entry
9510 ((memq interpret '(type priority))
9511 (if (eq this-command last-command)
9512 (car tail)
9513 (if (> (length tail) 0)
9514 (or done-word (car org-done-keywords))
9515 nil)))
9516 (t
9517 (car tail))))
9518 (state (or
9519 (run-hook-with-args-until-success
9520 'org-todo-get-default-hook state last-state)
9521 state))
9522 (next (if state (concat " " state " ") " "))
9523 (change-plist (list :type 'todo-state-change :from this :to state
9524 :position startpos))
9525 dolog now-done-p)
9526 (when org-blocker-hook
9527 (setq org-last-todo-state-is-todo
9528 (not (member this org-done-keywords)))
9529 (unless (save-excursion
9530 (save-match-data
9531 (run-hook-with-args-until-failure
9532 'org-blocker-hook change-plist)))
9533 (if (interactive-p)
9534 (error "TODO state change from %s to %s blocked" this state)
9535 ;; fail silently
9536 (message "TODO state change from %s to %s blocked" this state)
9537 (throw 'exit nil))))
9538 (store-match-data match-data)
9539 (replace-match next t t)
9540 (unless (pos-visible-in-window-p hl-pos)
9541 (message "TODO state changed to %s" (org-trim next)))
9542 (unless head
9543 (setq head (org-get-todo-sequence-head state)
9544 ass (assoc head org-todo-kwd-alist)
9545 interpret (nth 1 ass)
9546 done-word (nth 3 ass)
9547 final-done-word (nth 4 ass)))
9548 (when (memq arg '(nextset previousset))
9549 (message "Keyword-Set %d/%d: %s"
9550 (- (length org-todo-sets) -1
9551 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9552 (length org-todo-sets)
9553 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9554 (setq org-last-todo-state-is-todo
9555 (not (member state org-done-keywords)))
9556 (setq now-done-p (and (member state org-done-keywords)
9557 (not (member this org-done-keywords))))
9558 (and logging (org-local-logging logging))
9559 (when (and (or org-todo-log-states org-log-done)
9560 (not (eq org-inhibit-logging t))
9561 (not (memq arg '(nextset previousset))))
9562 ;; we need to look at recording a time and note
9563 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9564 (nth 2 (assoc this org-todo-log-states))))
9565 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9566 (setq dolog 'time))
9567 (when (and state
9568 (member state org-not-done-keywords)
9569 (not (member this org-not-done-keywords)))
9570 ;; This is now a todo state and was not one before
9571 ;; If there was a CLOSED time stamp, get rid of it.
9572 (org-add-planning-info nil nil 'closed))
9573 (when (and now-done-p org-log-done)
9574 ;; It is now done, and it was not done before
9575 (org-add-planning-info 'closed (org-current-time))
9576 (if (and (not dolog) (eq 'note org-log-done))
9577 (org-add-log-setup 'done state this 'findpos 'note)))
9578 (when (and state dolog)
9579 ;; This is a non-nil state, and we need to log it
9580 (org-add-log-setup 'state state this 'findpos dolog)))
9581 ;; Fixup tag positioning
9582 (org-todo-trigger-tag-changes state)
9583 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9584 (when org-provide-todo-statistics
9585 (org-update-parent-todo-statistics))
9586 (run-hooks 'org-after-todo-state-change-hook)
9587 (if (and arg (not (member state org-done-keywords)))
9588 (setq head (org-get-todo-sequence-head state)))
9589 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9590 ;; Do we need to trigger a repeat?
9591 (when now-done-p
9592 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9593 ;; This is for the agenda, take a snapshot of the headline.
9594 (save-match-data
9595 (setq org-agenda-headline-snapshot-before-repeat
9596 (org-get-heading))))
9597 (org-auto-repeat-maybe state))
9598 ;; Fixup cursor location if close to the keyword
9599 (if (and (outline-on-heading-p)
9600 (not (bolp))
9601 (save-excursion (beginning-of-line 1)
9602 (looking-at org-todo-line-regexp))
9603 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9604 (progn
9605 (goto-char (or (match-end 2) (match-end 1)))
9606 (and (looking-at " ") (just-one-space))))
9607 (when org-trigger-hook
9608 (save-excursion
9609 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9610
9611 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9612 "Block turning an entry into a TODO, using the hierarchy.
9613 This checks whether the current task should be blocked from state
9614 changes. Such blocking occurs when:
9615
9616 1. The task has children which are not all in a completed state.
9617
9618 2. A task has a parent with the property :ORDERED:, and there
9619 are siblings prior to the current task with incomplete
9620 status.
9621
9622 3. The parent of the task is blocked because it has siblings that should
9623 be done first, or is child of a block grandparent TODO entry."
9624
9625 (catch 'dont-block
9626 ;; If this is not a todo state change, or if this entry is already DONE,
9627 ;; do not block
9628 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9629 (member (plist-get change-plist :from)
9630 (cons 'done org-done-keywords))
9631 (member (plist-get change-plist :to)
9632 (cons 'todo org-not-done-keywords)))
9633 (throw 'dont-block t))
9634 ;; If this task has children, and any are undone, it's blocked
9635 (save-excursion
9636 (org-back-to-heading t)
9637 (let ((this-level (funcall outline-level)))
9638 (outline-next-heading)
9639 (let ((child-level (funcall outline-level)))
9640 (while (and (not (eobp))
9641 (> child-level this-level))
9642 ;; this todo has children, check whether they are all
9643 ;; completed
9644 (if (and (not (org-entry-is-done-p))
9645 (org-entry-is-todo-p))
9646 (throw 'dont-block nil))
9647 (outline-next-heading)
9648 (setq child-level (funcall outline-level))))))
9649 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9650 ;; any previous siblings are undone, it's blocked
9651 (save-excursion
9652 (org-back-to-heading t)
9653 (let* ((pos (point))
9654 (parent-pos (and (org-up-heading-safe) (point))))
9655 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9656 (when (and (org-entry-get (point) "ORDERED")
9657 (forward-line 1)
9658 (re-search-forward org-not-done-heading-regexp pos t))
9659 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9660 ;; Search further up the hierarchy, to see if an anchestor is blocked
9661 (while t
9662 (goto-char parent-pos)
9663 (if (not (looking-at org-not-done-heading-regexp))
9664 (throw 'dont-block t)) ; do not block, parent is not a TODO
9665 (setq pos (point))
9666 (setq parent-pos (and (org-up-heading-safe) (point)))
9667 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9668 (when (and (org-entry-get (point) "ORDERED")
9669 (forward-line 1)
9670 (re-search-forward org-not-done-heading-regexp pos t))
9671 (throw 'dont-block nil))))))) ; block, older sibling not done.
9672
9673 (defcustom org-track-ordered-property-with-tag nil
9674 "Should the ORDERED property also be shown as a tag?
9675 The ORDERED property decides if an entry should require subtasks to be
9676 completed in sequence. Since a property is not very visible, setting
9677 this option means that toggling the ORDERED property with the command
9678 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9679 not relevant for the behavior, but it makes things more visible.
9680
9681 Note that toggling the tag with tags commands will not change the property
9682 and therefore not influence behavior!
9683
9684 This can be t, meaning the tag ORDERED should be used, It can also be a
9685 string to select a different tag for this task."
9686 :group 'org-todo
9687 :type '(choice
9688 (const :tag "No tracking" nil)
9689 (const :tag "Track with ORDERED tag" t)
9690 (string :tag "Use other tag")))
9691
9692 (defun org-toggle-ordered-property ()
9693 "Toggle the ORDERED property of the current entry.
9694 For better visibility, you can track the value of this property with a tag.
9695 See variable `org-track-ordered-property-with-tag'."
9696 (interactive)
9697 (let* ((t1 org-track-ordered-property-with-tag)
9698 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9699 (save-excursion
9700 (org-back-to-heading)
9701 (if (org-entry-get nil "ORDERED")
9702 (progn
9703 (org-delete-property "ORDERED")
9704 (and tag (org-toggle-tag tag 'off))
9705 (message "Subtasks can be completed in arbitrary order"))
9706 (org-entry-put nil "ORDERED" "t")
9707 (and tag (org-toggle-tag tag 'on))
9708 (message "Subtasks must be completed in sequence")))))
9709
9710 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9711 (defun org-block-todo-from-checkboxes (change-plist)
9712 "Block turning an entry into a TODO, using checkboxes.
9713 This checks whether the current task should be blocked from state
9714 changes because there are uncheckd boxes in this entry."
9715 (catch 'dont-block
9716 ;; If this is not a todo state change, or if this entry is already DONE,
9717 ;; do not block
9718 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9719 (member (plist-get change-plist :from)
9720 (cons 'done org-done-keywords))
9721 (member (plist-get change-plist :to)
9722 (cons 'todo org-not-done-keywords)))
9723 (throw 'dont-block t))
9724 ;; If this task has checkboxes that are not checked, it's blocked
9725 (save-excursion
9726 (org-back-to-heading t)
9727 (let ((beg (point)) end)
9728 (outline-next-heading)
9729 (setq end (point))
9730 (goto-char beg)
9731 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9732 end t)
9733 (progn
9734 (if (boundp 'org-blocked-by-checkboxes)
9735 (setq org-blocked-by-checkboxes t))
9736 (throw 'dont-block nil)))))
9737 t)) ; do not block
9738
9739 (defun org-update-statistics-cookies (all)
9740 "Update the statistics cookie, either from TODO or from checkboxes.
9741 This should be called with the cursor in a line with a statistics cookie."
9742 (interactive "P")
9743 (if all
9744 (progn
9745 (org-update-checkbox-count 'all)
9746 (org-map-entries 'org-update-parent-todo-statistics))
9747 (if (not (org-on-heading-p))
9748 (org-update-checkbox-count)
9749 (let ((pos (move-marker (make-marker) (point)))
9750 end l1 l2)
9751 (ignore-errors (org-back-to-heading t))
9752 (if (not (org-on-heading-p))
9753 (org-update-checkbox-count)
9754 (setq l1 (org-outline-level))
9755 (setq end (save-excursion
9756 (outline-next-heading)
9757 (if (org-on-heading-p) (setq l2 (org-outline-level)))
9758 (point)))
9759 (if (and (save-excursion (re-search-forward
9760 "^[ \t]*[-+*] \\[[- X]\\]" end t))
9761 (not (save-excursion (re-search-forward
9762 ":COOKIE_DATA:.*\\<todo\\>" end t))))
9763 (org-update-checkbox-count)
9764 (if (and l2 (> l2 l1))
9765 (progn
9766 (goto-char end)
9767 (org-update-parent-todo-statistics))
9768 (error "No data for statistics cookie"))))
9769 (goto-char pos)
9770 (move-marker pos nil)))))
9771
9772 (defvar org-entry-property-inherited-from) ;; defined below
9773 (defun org-update-parent-todo-statistics ()
9774 "Update any statistics cookie in the parent of the current headline.
9775 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9776 the entire subtree and this will travel up the hierarchy and update
9777 statistics everywhere."
9778 (interactive)
9779 (let* ((lim 0) prop
9780 (recursive (or (not org-hierarchical-todo-statistics)
9781 (string-match
9782 "\\<recursive\\>"
9783 (or (setq prop (org-entry-get
9784 nil "COOKIE_DATA" 'inherit)) ""))))
9785 (lim (or (and prop (marker-position
9786 org-entry-property-inherited-from))
9787 lim))
9788 (first t)
9789 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9790 level ltoggle l1 new ndel
9791 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9792 (catch 'exit
9793 (save-excursion
9794 (beginning-of-line 1)
9795 (if (org-at-heading-p)
9796 (setq ltoggle (funcall outline-level))
9797 (error "This should not happen"))
9798 (while (and (setq level (org-up-heading-safe))
9799 (or recursive first)
9800 (>= (point) lim))
9801 (setq first nil)
9802 (unless (and level
9803 (not (string-match
9804 "\\<checkbox\\>"
9805 (downcase
9806 (or (org-entry-get
9807 nil "COOKIE_DATA")
9808 "")))))
9809 (throw 'exit nil))
9810 (while (re-search-forward box-re (point-at-eol) t)
9811 (setq cnt-all 0 cnt-done 0 cookie-present t)
9812 (setq is-percent (match-end 2))
9813 (save-match-data
9814 (unless (outline-next-heading) (throw 'exit nil))
9815 (while (and (looking-at org-complex-heading-regexp)
9816 (> (setq l1 (length (match-string 1))) level))
9817 (setq kwd (and (or recursive (= l1 ltoggle))
9818 (match-string 2)))
9819 (if (or (eq org-provide-todo-statistics 'all-headlines)
9820 (and (listp org-provide-todo-statistics)
9821 (or (member kwd org-provide-todo-statistics)
9822 (member kwd org-done-keywords))))
9823 (setq cnt-all (1+ cnt-all))
9824 (if (eq org-provide-todo-statistics t)
9825 (and kwd (setq cnt-all (1+ cnt-all)))))
9826 (and (member kwd org-done-keywords)
9827 (setq cnt-done (1+ cnt-done)))
9828 (outline-next-heading)))
9829 (setq new
9830 (if is-percent
9831 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9832 (format "[%d/%d]" cnt-done cnt-all))
9833 ndel (- (match-end 0) (match-beginning 0)))
9834 (goto-char (match-beginning 0))
9835 (insert new)
9836 (delete-region (point) (+ (point) ndel))))
9837 (when cookie-present
9838 (run-hook-with-args 'org-after-todo-statistics-hook
9839 cnt-done (- cnt-all cnt-done)))))
9840 (run-hooks 'org-todo-statistics-hook)))
9841
9842 (defvar org-after-todo-statistics-hook nil
9843 "Hook that is called after a TODO statistics cookie has been updated.
9844 Each function is called with two arguments: the number of not-done entries
9845 and the number of done entries.
9846
9847 For example, the following function, when added to this hook, will switch
9848 an entry to DONE when all children are done, and back to TODO when new
9849 entries are set to a TODO status. Note that this hook is only called
9850 when there is a statistics cookie in the headline!
9851
9852 (defun org-summary-todo (n-done n-not-done)
9853 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9854 (let (org-log-done org-log-states) ; turn off logging
9855 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9856 ")
9857
9858 (defvar org-todo-statistics-hook nil
9859 "Hook that is run whenever Org thinks TODO statistics should be updated.
9860 This hook runs even if there is no statisics cookie present, in which case
9861 `org-after-todo-statistics-hook' would not run.")
9862
9863 (defun org-todo-trigger-tag-changes (state)
9864 "Apply the changes defined in `org-todo-state-tags-triggers'."
9865 (let ((l org-todo-state-tags-triggers)
9866 changes)
9867 (when (or (not state) (equal state ""))
9868 (setq changes (append changes (cdr (assoc "" l)))))
9869 (when (and (stringp state) (> (length state) 0))
9870 (setq changes (append changes (cdr (assoc state l)))))
9871 (when (member state org-not-done-keywords)
9872 (setq changes (append changes (cdr (assoc 'todo l)))))
9873 (when (member state org-done-keywords)
9874 (setq changes (append changes (cdr (assoc 'done l)))))
9875 (dolist (c changes)
9876 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9877
9878 (defun org-local-logging (value)
9879 "Get logging settings from a property VALUE."
9880 (let* (words w a)
9881 ;; directly set the variables, they are already local.
9882 (setq org-log-done nil
9883 org-log-repeat nil
9884 org-todo-log-states nil)
9885 (setq words (org-split-string value))
9886 (while (setq w (pop words))
9887 (cond
9888 ((setq a (assoc w org-startup-options))
9889 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9890 (set (nth 1 a) (nth 2 a))))
9891 ((setq a (org-extract-log-state-settings w))
9892 (and (member (car a) org-todo-keywords-1)
9893 (push a org-todo-log-states)))))))
9894
9895 (defun org-get-todo-sequence-head (kwd)
9896 "Return the head of the TODO sequence to which KWD belongs.
9897 If KWD is not set, check if there is a text property remembering the
9898 right sequence."
9899 (let (p)
9900 (cond
9901 ((not kwd)
9902 (or (get-text-property (point-at-bol) 'org-todo-head)
9903 (progn
9904 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9905 nil (point-at-eol)))
9906 (get-text-property p 'org-todo-head))))
9907 ((not (member kwd org-todo-keywords-1))
9908 (car org-todo-keywords-1))
9909 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9910
9911 (defun org-fast-todo-selection ()
9912 "Fast TODO keyword selection with single keys.
9913 Returns the new TODO keyword, or nil if no state change should occur."
9914 (let* ((fulltable org-todo-key-alist)
9915 (done-keywords org-done-keywords) ;; needed for the faces.
9916 (maxlen (apply 'max (mapcar
9917 (lambda (x)
9918 (if (stringp (car x)) (string-width (car x)) 0))
9919 fulltable)))
9920 (expert nil)
9921 (fwidth (+ maxlen 3 1 3))
9922 (ncol (/ (- (window-width) 4) fwidth))
9923 tg cnt e c tbl
9924 groups ingroup)
9925 (save-excursion
9926 (save-window-excursion
9927 (if expert
9928 (set-buffer (get-buffer-create " *Org todo*"))
9929 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9930 (erase-buffer)
9931 (org-set-local 'org-done-keywords done-keywords)
9932 (setq tbl fulltable cnt 0)
9933 (while (setq e (pop tbl))
9934 (cond
9935 ((equal e '(:startgroup))
9936 (push '() groups) (setq ingroup t)
9937 (when (not (= cnt 0))
9938 (setq cnt 0)
9939 (insert "\n"))
9940 (insert "{ "))
9941 ((equal e '(:endgroup))
9942 (setq ingroup nil cnt 0)
9943 (insert "}\n"))
9944 ((equal e '(:newline))
9945 (when (not (= cnt 0))
9946 (setq cnt 0)
9947 (insert "\n")
9948 (setq e (car tbl))
9949 (while (equal (car tbl) '(:newline))
9950 (insert "\n")
9951 (setq tbl (cdr tbl)))))
9952 (t
9953 (setq tg (car e) c (cdr e))
9954 (if ingroup (push tg (car groups)))
9955 (setq tg (org-add-props tg nil 'face
9956 (org-get-todo-face tg)))
9957 (if (and (= cnt 0) (not ingroup)) (insert " "))
9958 (insert "[" c "] " tg (make-string
9959 (- fwidth 4 (length tg)) ?\ ))
9960 (when (= (setq cnt (1+ cnt)) ncol)
9961 (insert "\n")
9962 (if ingroup (insert " "))
9963 (setq cnt 0)))))
9964 (insert "\n")
9965 (goto-char (point-min))
9966 (if (not expert) (org-fit-window-to-buffer))
9967 (message "[a-z..]:Set [SPC]:clear")
9968 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9969 (cond
9970 ((or (= c ?\C-g)
9971 (and (= c ?q) (not (rassoc c fulltable))))
9972 (setq quit-flag t))
9973 ((= c ?\ ) nil)
9974 ((setq e (rassoc c fulltable) tg (car e))
9975 tg)
9976 (t (setq quit-flag t)))))))
9977
9978 (defun org-entry-is-todo-p ()
9979 (member (org-get-todo-state) org-not-done-keywords))
9980
9981 (defun org-entry-is-done-p ()
9982 (member (org-get-todo-state) org-done-keywords))
9983
9984 (defun org-get-todo-state ()
9985 (save-excursion
9986 (org-back-to-heading t)
9987 (and (looking-at org-todo-line-regexp)
9988 (match-end 2)
9989 (match-string 2))))
9990
9991 (defun org-at-date-range-p (&optional inactive-ok)
9992 "Is the cursor inside a date range?"
9993 (interactive)
9994 (save-excursion
9995 (catch 'exit
9996 (let ((pos (point)))
9997 (skip-chars-backward "^[<\r\n")
9998 (skip-chars-backward "<[")
9999 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10000 (>= (match-end 0) pos)
10001 (throw 'exit t))
10002 (skip-chars-backward "^<[\r\n")
10003 (skip-chars-backward "<[")
10004 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10005 (>= (match-end 0) pos)
10006 (throw 'exit t)))
10007 nil)))
10008
10009 (defun org-get-repeat ()
10010 "Check if there is a deadline/schedule with repeater in this entry."
10011 (save-match-data
10012 (save-excursion
10013 (org-back-to-heading t)
10014 (if (re-search-forward
10015 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
10016 (match-string 1)))))
10017
10018 (defvar org-last-changed-timestamp)
10019 (defvar org-last-inserted-timestamp)
10020 (defvar org-log-post-message)
10021 (defvar org-log-note-purpose)
10022 (defvar org-log-note-how)
10023 (defvar org-log-note-extra)
10024 (defun org-auto-repeat-maybe (done-word)
10025 "Check if the current headline contains a repeated deadline/schedule.
10026 If yes, set TODO state back to what it was and change the base date
10027 of repeating deadline/scheduled time stamps to new date.
10028 This function is run automatically after each state change to a DONE state."
10029 ;; last-state is dynamically scoped into this function
10030 (let* ((repeat (org-get-repeat))
10031 (aa (assoc last-state org-todo-kwd-alist))
10032 (interpret (nth 1 aa))
10033 (head (nth 2 aa))
10034 (whata '(("d" . day) ("m" . month) ("y" . year)))
10035 (msg "Entry repeats: ")
10036 (org-log-done nil)
10037 (org-todo-log-states nil)
10038 (nshiftmax 10) (nshift 0)
10039 re type n what ts time)
10040 (when repeat
10041 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10042 (org-todo (if (eq interpret 'type) last-state head))
10043 (org-entry-put nil "LAST_REPEAT" (format-time-string
10044 (org-time-stamp-format t t)))
10045 (when org-log-repeat
10046 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10047 (memq 'org-add-log-note post-command-hook))
10048 ;; OK, we are already setup for some record
10049 (if (eq org-log-repeat 'note)
10050 ;; make sure we take a note, not only a time stamp
10051 (setq org-log-note-how 'note))
10052 ;; Set up for taking a record
10053 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10054 last-state
10055 'findpos org-log-repeat)))
10056 (org-back-to-heading t)
10057 (org-add-planning-info nil nil 'closed)
10058 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10059 org-deadline-time-regexp "\\)\\|\\("
10060 org-ts-regexp "\\)"))
10061 (while (re-search-forward
10062 re (save-excursion (outline-next-heading) (point)) t)
10063 (setq type (if (match-end 1) org-scheduled-string
10064 (if (match-end 3) org-deadline-string "Plain:"))
10065 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10066 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10067 (setq n (string-to-number (match-string 2 ts))
10068 what (match-string 3 ts))
10069 (if (equal what "w") (setq n (* n 7) what "d"))
10070 ;; Preparation, see if we need to modify the start date for the change
10071 (when (match-end 1)
10072 (setq time (save-match-data (org-time-string-to-time ts)))
10073 (cond
10074 ((equal (match-string 1 ts) ".")
10075 ;; Shift starting date to today
10076 (org-timestamp-change
10077 (- (time-to-days (current-time)) (time-to-days time))
10078 'day))
10079 ((equal (match-string 1 ts) "+")
10080 (while (or (= nshift 0)
10081 (<= (time-to-days time) (time-to-days (current-time))))
10082 (when (= (incf nshift) nshiftmax)
10083 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10084 (error "Abort")))
10085 (org-timestamp-change n (cdr (assoc what whata)))
10086 (org-at-timestamp-p t)
10087 (setq ts (match-string 1))
10088 (setq time (save-match-data (org-time-string-to-time ts))))
10089 (org-timestamp-change (- n) (cdr (assoc what whata)))
10090 ;; rematch, so that we have everything in place for the real shift
10091 (org-at-timestamp-p t)
10092 (setq ts (match-string 1))
10093 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10094 (org-timestamp-change n (cdr (assoc what whata)))
10095 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10096 (setq org-log-post-message msg)
10097 (message "%s" msg))))
10098
10099 (defun org-show-todo-tree (arg)
10100 "Make a compact tree which shows all headlines marked with TODO.
10101 The tree will show the lines where the regexp matches, and all higher
10102 headlines above the match.
10103 With a \\[universal-argument] prefix, prompt for a regexp to match.
10104 With a numeric prefix N, construct a sparse tree for the Nth element
10105 of `org-todo-keywords-1'."
10106 (interactive "P")
10107 (let ((case-fold-search nil)
10108 (kwd-re
10109 (cond ((null arg) org-not-done-regexp)
10110 ((equal arg '(4))
10111 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10112 (mapcar 'list org-todo-keywords-1))))
10113 (concat "\\("
10114 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10115 "\\)\\>")))
10116 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10117 (regexp-quote (nth (1- (prefix-numeric-value arg))
10118 org-todo-keywords-1)))
10119 (t (error "Invalid prefix argument: %s" arg)))))
10120 (message "%d TODO entries found"
10121 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10122
10123 (defun org-deadline (&optional remove time)
10124 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10125 With argument REMOVE, remove any deadline from the item.
10126 When TIME is set, it should be an internal time specification, and the
10127 scheduling will use the corresponding date."
10128 (interactive "P")
10129 (if remove
10130 (progn
10131 (org-remove-timestamp-with-keyword org-deadline-string)
10132 (message "Item no longer has a deadline."))
10133 (if (org-get-repeat)
10134 (error "Cannot change deadline on task with repeater, please do that by hand")
10135 (org-add-planning-info 'deadline time 'closed)
10136 (message "Deadline on %s" org-last-inserted-timestamp))))
10137
10138 (defun org-schedule (&optional remove time)
10139 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10140 With argument REMOVE, remove any scheduling date from the item.
10141 When TIME is set, it should be an internal time specification, and the
10142 scheduling will use the corresponding date."
10143 (interactive "P")
10144 (if remove
10145 (progn
10146 (org-remove-timestamp-with-keyword org-scheduled-string)
10147 (message "Item is no longer scheduled."))
10148 (if (org-get-repeat)
10149 (error "Cannot reschedule task with repeater, please do that by hand")
10150 (org-add-planning-info 'scheduled time 'closed)
10151 (message "Scheduled to %s" org-last-inserted-timestamp))))
10152
10153 (defun org-get-scheduled-time (pom &optional inherit)
10154 "Get the scheduled time as a time tuple, of a format suitable
10155 for calling org-schedule with, or if there is no scheduling,
10156 returns nil."
10157 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
10158 (when time
10159 (apply 'encode-time (org-parse-time-string time)))))
10160
10161 (defun org-get-deadline-time (pom &optional inherit)
10162 "Get the deadine as a time tuple, of a format suitable for
10163 calling org-deadlin with, or if there is no scheduling, returns
10164 nil."
10165 (let ((time (org-entry-get pom "DEADLINE" inherit)))
10166 (when time
10167 (apply 'encode-time (org-parse-time-string time)))))
10168
10169 (defun org-remove-timestamp-with-keyword (keyword)
10170 "Remove all time stamps with KEYWORD in the current entry."
10171 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
10172 beg)
10173 (save-excursion
10174 (org-back-to-heading t)
10175 (setq beg (point))
10176 (outline-next-heading)
10177 (while (re-search-backward re beg t)
10178 (replace-match "")
10179 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
10180 (equal (char-before) ?\ ))
10181 (backward-delete-char 1)
10182 (if (string-match "^[ \t]*$" (buffer-substring
10183 (point-at-bol) (point-at-eol)))
10184 (delete-region (point-at-bol)
10185 (min (point-max) (1+ (point-at-eol))))))))))
10186
10187 (defun org-add-planning-info (what &optional time &rest remove)
10188 "Insert new timestamp with keyword in the line directly after the headline.
10189 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
10190 If non is given, the user is prompted for a date.
10191 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
10192 be removed."
10193 (interactive)
10194 (let (org-time-was-given org-end-time-was-given ts
10195 end default-time default-input)
10196
10197 (catch 'exit
10198 (when (and (not time) (memq what '(scheduled deadline)))
10199 ;; Try to get a default date/time from existing timestamp
10200 (save-excursion
10201 (org-back-to-heading t)
10202 (setq end (save-excursion (outline-next-heading) (point)))
10203 (when (re-search-forward (if (eq what 'scheduled)
10204 org-scheduled-time-regexp
10205 org-deadline-time-regexp)
10206 end t)
10207 (setq ts (match-string 1)
10208 default-time
10209 (apply 'encode-time (org-parse-time-string ts))
10210 default-input (and ts (org-get-compact-tod ts))))))
10211 (when what
10212 ;; If necessary, get the time from the user
10213 (setq time (or time (org-read-date nil 'to-time nil nil
10214 default-time default-input))))
10215
10216 (when (and org-insert-labeled-timestamps-at-point
10217 (member what '(scheduled deadline)))
10218 (insert
10219 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
10220 (org-insert-time-stamp time org-time-was-given
10221 nil nil nil (list org-end-time-was-given))
10222 (setq what nil))
10223 (save-excursion
10224 (save-restriction
10225 (let (col list elt ts buffer-invisibility-spec)
10226 (org-back-to-heading t)
10227 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
10228 (goto-char (match-end 1))
10229 (setq col (current-column))
10230 (goto-char (match-end 0))
10231 (if (eobp) (insert "\n") (forward-char 1))
10232 (when (and (not what)
10233 (not (looking-at
10234 (concat "[ \t]*"
10235 org-keyword-time-not-clock-regexp))))
10236 ;; Nothing to add, nothing to remove...... :-)
10237 (throw 'exit nil))
10238 (if (and (not (looking-at outline-regexp))
10239 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
10240 "[^\r\n]*"))
10241 (not (equal (match-string 1) org-clock-string)))
10242 (narrow-to-region (match-beginning 0) (match-end 0))
10243 (insert-before-markers "\n")
10244 (backward-char 1)
10245 (narrow-to-region (point) (point))
10246 (and org-adapt-indentation (org-indent-to-column col)))
10247 ;; Check if we have to remove something.
10248 (setq list (cons what remove))
10249 (while list
10250 (setq elt (pop list))
10251 (goto-char (point-min))
10252 (when (or (and (eq elt 'scheduled)
10253 (re-search-forward org-scheduled-time-regexp nil t))
10254 (and (eq elt 'deadline)
10255 (re-search-forward org-deadline-time-regexp nil t))
10256 (and (eq elt 'closed)
10257 (re-search-forward org-closed-time-regexp nil t)))
10258 (replace-match "")
10259 (if (looking-at "--+<[^>]+>") (replace-match ""))
10260 (skip-chars-backward " ")
10261 (if (looking-at " +") (replace-match ""))))
10262 (goto-char (point-max))
10263 (when what
10264 (insert
10265 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10266 (cond ((eq what 'scheduled) org-scheduled-string)
10267 ((eq what 'deadline) org-deadline-string)
10268 ((eq what 'closed) org-closed-string))
10269 " ")
10270 (setq ts (org-insert-time-stamp
10271 time
10272 (or org-time-was-given
10273 (and (eq what 'closed) org-log-done-with-time))
10274 (eq what 'closed)
10275 nil nil (list org-end-time-was-given)))
10276 (end-of-line 1))
10277 (goto-char (point-min))
10278 (widen)
10279 (if (and (looking-at "[ \t]+\n")
10280 (equal (char-before) ?\n))
10281 (delete-region (1- (point)) (point-at-eol)))
10282 ts))))))
10283
10284 (defvar org-log-note-marker (make-marker))
10285 (defvar org-log-note-purpose nil)
10286 (defvar org-log-note-state nil)
10287 (defvar org-log-note-previous-state nil)
10288 (defvar org-log-note-how nil)
10289 (defvar org-log-note-extra nil)
10290 (defvar org-log-note-window-configuration nil)
10291 (defvar org-log-note-return-to (make-marker))
10292 (defvar org-log-post-message nil
10293 "Message to be displayed after a log note has been stored.
10294 The auto-repeater uses this.")
10295
10296 (defun org-add-note ()
10297 "Add a note to the current entry.
10298 This is done in the same way as adding a state change note."
10299 (interactive)
10300 (org-add-log-setup 'note nil nil 'findpos nil))
10301
10302 (defvar org-property-end-re)
10303 (defun org-add-log-setup (&optional purpose state prev-state
10304 findpos how &optional extra)
10305 "Set up the post command hook to take a note.
10306 If this is about to TODO state change, the new state is expected in STATE.
10307 When FINDPOS is non-nil, find the correct position for the note in
10308 the current entry. If not, assume that it can be inserted at point.
10309 HOW is an indicator what kind of note should be created.
10310 EXTRA is additional text that will be inserted into the notes buffer."
10311 (let* ((org-log-into-drawer (org-log-into-drawer))
10312 (drawer (cond ((stringp org-log-into-drawer)
10313 org-log-into-drawer)
10314 (org-log-into-drawer "LOGBOOK")
10315 (t nil))))
10316 (save-restriction
10317 (save-excursion
10318 (when findpos
10319 (org-back-to-heading t)
10320 (narrow-to-region (point) (save-excursion
10321 (outline-next-heading) (point)))
10322 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10323 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10324 "[^\r\n]*\\)?"))
10325 (goto-char (match-end 0))
10326 (cond
10327 (drawer
10328 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10329 nil t)
10330 (progn
10331 (goto-char (match-end 0))
10332 (or org-log-states-order-reversed
10333 (and (re-search-forward org-property-end-re nil t)
10334 (goto-char (1- (match-beginning 0))))))
10335 (insert "\n:" drawer ":\n:END:")
10336 (beginning-of-line 0)
10337 (org-indent-line-function)
10338 (beginning-of-line 2)
10339 (org-indent-line-function)
10340 (end-of-line 0)))
10341 ((and org-log-state-notes-insert-after-drawers
10342 (save-excursion
10343 (forward-line) (looking-at org-drawer-regexp)))
10344 (forward-line)
10345 (while (looking-at org-drawer-regexp)
10346 (goto-char (match-end 0))
10347 (re-search-forward org-property-end-re (point-max) t)
10348 (forward-line))
10349 (forward-line -1)))
10350 (unless org-log-states-order-reversed
10351 (and (= (char-after) ?\n) (forward-char 1))
10352 (org-skip-over-state-notes)
10353 (skip-chars-backward " \t\n\r")))
10354 (move-marker org-log-note-marker (point))
10355 (setq org-log-note-purpose purpose
10356 org-log-note-state state
10357 org-log-note-previous-state prev-state
10358 org-log-note-how how
10359 org-log-note-extra extra)
10360 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10361
10362 (defun org-skip-over-state-notes ()
10363 "Skip past the list of State notes in an entry."
10364 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10365 (while (looking-at "[ \t]*- State")
10366 (condition-case nil
10367 (org-next-item)
10368 (error (org-end-of-item)))))
10369
10370 (defun org-add-log-note (&optional purpose)
10371 "Pop up a window for taking a note, and add this note later at point."
10372 (remove-hook 'post-command-hook 'org-add-log-note)
10373 (setq org-log-note-window-configuration (current-window-configuration))
10374 (delete-other-windows)
10375 (move-marker org-log-note-return-to (point))
10376 (switch-to-buffer (marker-buffer org-log-note-marker))
10377 (goto-char org-log-note-marker)
10378 (org-switch-to-buffer-other-window "*Org Note*")
10379 (erase-buffer)
10380 (if (memq org-log-note-how '(time state))
10381 (let (current-prefix-arg) (org-store-log-note))
10382 (let ((org-inhibit-startup t)) (org-mode))
10383 (insert (format "# Insert note for %s.
10384 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10385 (cond
10386 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10387 ((eq org-log-note-purpose 'done) "closed todo item")
10388 ((eq org-log-note-purpose 'state)
10389 (format "state change from \"%s\" to \"%s\""
10390 (or org-log-note-previous-state "")
10391 (or org-log-note-state "")))
10392 ((eq org-log-note-purpose 'note)
10393 "this entry")
10394 (t (error "This should not happen")))))
10395 (if org-log-note-extra (insert org-log-note-extra))
10396 (org-set-local 'org-finish-function 'org-store-log-note)))
10397
10398 (defvar org-note-abort nil) ; dynamically scoped
10399 (defun org-store-log-note ()
10400 "Finish taking a log note, and insert it to where it belongs."
10401 (let ((txt (buffer-string))
10402 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10403 lines ind)
10404 (kill-buffer (current-buffer))
10405 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10406 (setq txt (replace-match "" t t txt)))
10407 (if (string-match "\\s-+\\'" txt)
10408 (setq txt (replace-match "" t t txt)))
10409 (setq lines (org-split-string txt "\n"))
10410 (when (and note (string-match "\\S-" note))
10411 (setq note
10412 (org-replace-escapes
10413 note
10414 (list (cons "%u" (user-login-name))
10415 (cons "%U" user-full-name)
10416 (cons "%t" (format-time-string
10417 (org-time-stamp-format 'long 'inactive)
10418 (current-time)))
10419 (cons "%s" (if org-log-note-state
10420 (concat "\"" org-log-note-state "\"")
10421 ""))
10422 (cons "%S" (if org-log-note-previous-state
10423 (concat "\"" org-log-note-previous-state "\"")
10424 "\"\"")))))
10425 (if lines (setq note (concat note " \\\\")))
10426 (push note lines))
10427 (when (or current-prefix-arg org-note-abort)
10428 (when org-log-into-drawer
10429 (org-remove-empty-drawer-at
10430 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10431 org-log-note-marker))
10432 (setq lines nil))
10433 (when lines
10434 (save-excursion
10435 (set-buffer (marker-buffer org-log-note-marker))
10436 (save-excursion
10437 (goto-char org-log-note-marker)
10438 (move-marker org-log-note-marker nil)
10439 (end-of-line 1)
10440 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10441 (insert "- " (pop lines))
10442 (org-indent-line-function)
10443 (beginning-of-line 1)
10444 (looking-at "[ \t]*")
10445 (setq ind (concat (match-string 0) " "))
10446 (end-of-line 1)
10447 (while lines (insert "\n" ind (pop lines)))
10448 (message "Note stored")
10449 (org-back-to-heading t)
10450 (org-cycle-hide-drawers 'children)))))
10451 (set-window-configuration org-log-note-window-configuration)
10452 (with-current-buffer (marker-buffer org-log-note-return-to)
10453 (goto-char org-log-note-return-to))
10454 (move-marker org-log-note-return-to nil)
10455 (and org-log-post-message (message "%s" org-log-post-message)))
10456
10457 (defun org-remove-empty-drawer-at (drawer pos)
10458 "Remove an emptyr DARWER drawer at position POS.
10459 POS may also be a marker."
10460 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10461 (save-excursion
10462 (save-restriction
10463 (widen)
10464 (goto-char pos)
10465 (if (org-in-regexp
10466 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10467 (replace-match ""))))))
10468
10469 (defun org-sparse-tree (&optional arg)
10470 "Create a sparse tree, prompt for the details.
10471 This command can create sparse trees. You first need to select the type
10472 of match used to create the tree:
10473
10474 t Show entries with a specific TODO keyword.
10475 m Show entries selected by a tags/property match.
10476 p Enter a property name and its value (both with completion on existing
10477 names/values) and show entries with that property.
10478 r Show entries matching a regular expression.
10479 d Show deadlines due within `org-deadline-warning-days'.
10480 b Show deadlines and scheduled items before a date.
10481 a Show deadlines and scheduled items after a date."
10482 (interactive "P")
10483 (let (ans kwd value)
10484 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10485 (setq ans (read-char-exclusive))
10486 (cond
10487 ((equal ans ?d)
10488 (call-interactively 'org-check-deadlines))
10489 ((equal ans ?b)
10490 (call-interactively 'org-check-before-date))
10491 ((equal ans ?a)
10492 (call-interactively 'org-check-after-date))
10493 ((equal ans ?t)
10494 (org-show-todo-tree '(4)))
10495 ((member ans '(?T ?m))
10496 (call-interactively 'org-match-sparse-tree))
10497 ((member ans '(?p ?P))
10498 (setq kwd (org-icompleting-read "Property: "
10499 (mapcar 'list (org-buffer-property-keys))))
10500 (setq value (org-icompleting-read "Value: "
10501 (mapcar 'list (org-property-values kwd))))
10502 (unless (string-match "\\`{.*}\\'" value)
10503 (setq value (concat "\"" value "\"")))
10504 (org-match-sparse-tree arg (concat kwd "=" value)))
10505 ((member ans '(?r ?R ?/))
10506 (call-interactively 'org-occur))
10507 (t (error "No such sparse tree command \"%c\"" ans)))))
10508
10509 (defvar org-occur-highlights nil
10510 "List of overlays used for occur matches.")
10511 (make-variable-buffer-local 'org-occur-highlights)
10512 (defvar org-occur-parameters nil
10513 "Parameters of the active org-occur calls.
10514 This is a list, each call to org-occur pushes as cons cell,
10515 containing the regular expression and the callback, onto the list.
10516 The list can contain several entries if `org-occur' has been called
10517 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10518 will only contain one set of parameters. When the highlights are
10519 removed (for example with `C-c C-c', or with the next edit (depending
10520 on `org-remove-highlights-with-change'), this variable is emptied
10521 as well.")
10522 (make-variable-buffer-local 'org-occur-parameters)
10523
10524 (defun org-occur (regexp &optional keep-previous callback)
10525 "Make a compact tree which shows all matches of REGEXP.
10526 The tree will show the lines where the regexp matches, and all higher
10527 headlines above the match. It will also show the heading after the match,
10528 to make sure editing the matching entry is easy.
10529 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10530 call to `org-occur' will be kept, to allow stacking of calls to this
10531 command.
10532 If CALLBACK is non-nil, it is a function which is called to confirm
10533 that the match should indeed be shown."
10534 (interactive "sRegexp: \nP")
10535 (when (equal regexp "")
10536 (error "Regexp cannot be empty"))
10537 (unless keep-previous
10538 (org-remove-occur-highlights nil nil t))
10539 (push (cons regexp callback) org-occur-parameters)
10540 (let ((cnt 0))
10541 (save-excursion
10542 (goto-char (point-min))
10543 (if (or (not keep-previous) ; do not want to keep
10544 (not org-occur-highlights)) ; no previous matches
10545 ;; hide everything
10546 (org-overview))
10547 (while (re-search-forward regexp nil t)
10548 (when (or (not callback)
10549 (save-match-data (funcall callback)))
10550 (setq cnt (1+ cnt))
10551 (when org-highlight-sparse-tree-matches
10552 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10553 (org-show-context 'occur-tree))))
10554 (when org-remove-highlights-with-change
10555 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10556 nil 'local))
10557 (unless org-sparse-tree-open-archived-trees
10558 (org-hide-archived-subtrees (point-min) (point-max)))
10559 (run-hooks 'org-occur-hook)
10560 (if (interactive-p)
10561 (message "%d match(es) for regexp %s" cnt regexp))
10562 cnt))
10563
10564 (defun org-show-context (&optional key)
10565 "Make sure point and context and visible.
10566 How much context is shown depends upon the variables
10567 `org-show-hierarchy-above', `org-show-following-heading'. and
10568 `org-show-siblings'."
10569 (let ((heading-p (org-on-heading-p t))
10570 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10571 (following-p (org-get-alist-option org-show-following-heading key))
10572 (entry-p (org-get-alist-option org-show-entry-below key))
10573 (siblings-p (org-get-alist-option org-show-siblings key)))
10574 (catch 'exit
10575 ;; Show heading or entry text
10576 (if (and heading-p (not entry-p))
10577 (org-flag-heading nil) ; only show the heading
10578 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10579 (org-show-hidden-entry))) ; show entire entry
10580 (when following-p
10581 ;; Show next sibling, or heading below text
10582 (save-excursion
10583 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10584 (org-flag-heading nil))))
10585 (when siblings-p (org-show-siblings))
10586 (when hierarchy-p
10587 ;; show all higher headings, possibly with siblings
10588 (save-excursion
10589 (while (and (condition-case nil
10590 (progn (org-up-heading-all 1) t)
10591 (error nil))
10592 (not (bobp)))
10593 (org-flag-heading nil)
10594 (when siblings-p (org-show-siblings))))))))
10595
10596 (defun org-reveal (&optional siblings)
10597 "Show current entry, hierarchy above it, and the following headline.
10598 This can be used to show a consistent set of context around locations
10599 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10600 not t for the search context.
10601
10602 With optional argument SIBLINGS, on each level of the hierarchy all
10603 siblings are shown. This repairs the tree structure to what it would
10604 look like when opened with hierarchical calls to `org-cycle'."
10605 (interactive "P")
10606 (let ((org-show-hierarchy-above t)
10607 (org-show-following-heading t)
10608 (org-show-siblings (if siblings t org-show-siblings)))
10609 (org-show-context nil)))
10610
10611 (defun org-highlight-new-match (beg end)
10612 "Highlight from BEG to END and mark the highlight is an occur headline."
10613 (let ((ov (org-make-overlay beg end)))
10614 (org-overlay-put ov 'face 'secondary-selection)
10615 (push ov org-occur-highlights)))
10616
10617 (defun org-remove-occur-highlights (&optional beg end noremove)
10618 "Remove the occur highlights from the buffer.
10619 BEG and END are ignored. If NOREMOVE is nil, remove this function
10620 from the `before-change-functions' in the current buffer."
10621 (interactive)
10622 (unless org-inhibit-highlight-removal
10623 (mapc 'org-delete-overlay org-occur-highlights)
10624 (setq org-occur-highlights nil)
10625 (setq org-occur-parameters nil)
10626 (unless noremove
10627 (remove-hook 'before-change-functions
10628 'org-remove-occur-highlights 'local))))
10629
10630 ;;;; Priorities
10631
10632 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10633 "Regular expression matching the priority indicator.")
10634
10635 (defvar org-remove-priority-next-time nil)
10636
10637 (defun org-priority-up ()
10638 "Increase the priority of the current item."
10639 (interactive)
10640 (org-priority 'up))
10641
10642 (defun org-priority-down ()
10643 "Decrease the priority of the current item."
10644 (interactive)
10645 (org-priority 'down))
10646
10647 (defun org-priority (&optional action)
10648 "Change the priority of an item by ARG.
10649 ACTION can be `set', `up', `down', or a character."
10650 (interactive)
10651 (unless org-enable-priority-commands
10652 (error "Priority commands are disabled"))
10653 (setq action (or action 'set))
10654 (let (current new news have remove)
10655 (save-excursion
10656 (org-back-to-heading t)
10657 (if (looking-at org-priority-regexp)
10658 (setq current (string-to-char (match-string 2))
10659 have t)
10660 (setq current org-default-priority))
10661 (cond
10662 ((or (eq action 'set)
10663 (if (featurep 'xemacs) (characterp action) (integerp action)))
10664 (if (not (eq action 'set))
10665 (setq new action)
10666 (message "Priority %c-%c, SPC to remove: "
10667 org-highest-priority org-lowest-priority)
10668 (setq new (read-char-exclusive)))
10669 (if (and (= (upcase org-highest-priority) org-highest-priority)
10670 (= (upcase org-lowest-priority) org-lowest-priority))
10671 (setq new (upcase new)))
10672 (cond ((equal new ?\ ) (setq remove t))
10673 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10674 (error "Priority must be between `%c' and `%c'"
10675 org-highest-priority org-lowest-priority))))
10676 ((eq action 'up)
10677 (if (and (not have) (eq last-command this-command))
10678 (setq new org-lowest-priority)
10679 (setq new (if (and org-priority-start-cycle-with-default (not have))
10680 org-default-priority (1- current)))))
10681 ((eq action 'down)
10682 (if (and (not have) (eq last-command this-command))
10683 (setq new org-highest-priority)
10684 (setq new (if (and org-priority-start-cycle-with-default (not have))
10685 org-default-priority (1+ current)))))
10686 (t (error "Invalid action")))
10687 (if (or (< (upcase new) org-highest-priority)
10688 (> (upcase new) org-lowest-priority))
10689 (setq remove t))
10690 (setq news (format "%c" new))
10691 (if have
10692 (if remove
10693 (replace-match "" t t nil 1)
10694 (replace-match news t t nil 2))
10695 (if remove
10696 (error "No priority cookie found in line")
10697 (let ((case-fold-search nil))
10698 (looking-at org-todo-line-regexp))
10699 (if (match-end 2)
10700 (progn
10701 (goto-char (match-end 2))
10702 (insert " [#" news "]"))
10703 (goto-char (match-beginning 3))
10704 (insert "[#" news "] "))))
10705 (org-preserve-lc (org-set-tags nil 'align)))
10706 (if remove
10707 (message "Priority removed")
10708 (message "Priority of current item set to %s" news))))
10709
10710 (defun org-get-priority (s)
10711 "Find priority cookie and return priority."
10712 (save-match-data
10713 (if (not (string-match org-priority-regexp s))
10714 (* 1000 (- org-lowest-priority org-default-priority))
10715 (* 1000 (- org-lowest-priority
10716 (string-to-char (match-string 2 s)))))))
10717
10718 ;;;; Tags
10719
10720 (defvar org-agenda-archives-mode)
10721 (defvar org-map-continue-from nil
10722 "Position from where mapping should continue.
10723 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10724
10725 (defvar org-scanner-tags nil
10726 "The current tag list while the tags scanner is running.")
10727 (defvar org-trust-scanner-tags nil
10728 "Should `org-get-tags-at' use the tags fro the scanner.
10729 This is for internal dynamical scoping only.
10730 When this is non-nil, the function `org-get-tags-at' will return the value
10731 of `org-scanner-tags' instead of building the list by itself. This
10732 can lead to large speed-ups when the tags scanner is used in a file with
10733 many entries, and when the list of tags is retrieved, for example to
10734 obtain a list of properties. Building the tags list for each entry in such
10735 a file becomes an N^2 operation - but with this variable set, it scales
10736 as N.")
10737
10738 (defun org-scan-tags (action matcher &optional todo-only)
10739 "Scan headline tags with inheritance and produce output ACTION.
10740
10741 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10742 or `agenda' to produce an entry list for an agenda view. It can also be
10743 a Lisp form or a function that should be called at each matched headline, in
10744 this case the return value is a list of all return values from these calls.
10745
10746 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10747 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10748 only lines with a TODO keyword are included in the output."
10749 (require 'org-agenda)
10750 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10751 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10752 (org-re
10753 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10754 (props (list 'face 'default
10755 'done-face 'org-agenda-done
10756 'undone-face 'default
10757 'mouse-face 'highlight
10758 'org-not-done-regexp org-not-done-regexp
10759 'org-todo-regexp org-todo-regexp
10760 'keymap org-agenda-keymap
10761 'help-echo
10762 (format "mouse-2 or RET jump to org file %s"
10763 (abbreviate-file-name
10764 (or (buffer-file-name (buffer-base-buffer))
10765 (buffer-name (buffer-base-buffer)))))))
10766 (case-fold-search nil)
10767 (org-map-continue-from nil)
10768 lspos tags tags-list
10769 (tags-alist (list (cons 0 org-file-tags)))
10770 (llast 0) rtn rtn1 level category i txt
10771 todo marker entry priority)
10772 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10773 (setq action (list 'lambda nil action)))
10774 (save-excursion
10775 (goto-char (point-min))
10776 (when (eq action 'sparse-tree)
10777 (org-overview)
10778 (org-remove-occur-highlights))
10779 (while (re-search-forward re nil t)
10780 (catch :skip
10781 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10782 tags (if (match-end 4) (org-match-string-no-properties 4)))
10783 (goto-char (setq lspos (match-beginning 0)))
10784 (setq level (org-reduced-level (funcall outline-level))
10785 category (org-get-category))
10786 (setq i llast llast level)
10787 ;; remove tag lists from same and sublevels
10788 (while (>= i level)
10789 (when (setq entry (assoc i tags-alist))
10790 (setq tags-alist (delete entry tags-alist)))
10791 (setq i (1- i)))
10792 ;; add the next tags
10793 (when tags
10794 (setq tags (org-split-string tags ":")
10795 tags-alist
10796 (cons (cons level tags) tags-alist)))
10797 ;; compile tags for current headline
10798 (setq tags-list
10799 (if org-use-tag-inheritance
10800 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10801 tags)
10802 org-scanner-tags tags-list)
10803 (when org-use-tag-inheritance
10804 (setcdr (car tags-alist)
10805 (mapcar (lambda (x)
10806 (setq x (copy-sequence x))
10807 (org-add-prop-inherited x))
10808 (cdar tags-alist))))
10809 (when (and tags org-use-tag-inheritance
10810 (or (not (eq t org-use-tag-inheritance))
10811 org-tags-exclude-from-inheritance))
10812 ;; selective inheritance, remove uninherited ones
10813 (setcdr (car tags-alist)
10814 (org-remove-uniherited-tags (cdar tags-alist))))
10815 (when (and (or (not todo-only)
10816 (and (member todo org-not-done-keywords)
10817 (or (not org-agenda-tags-todo-honor-ignore-options)
10818 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10819 (let ((case-fold-search t)) (eval matcher))
10820 (or
10821 (not (member org-archive-tag tags-list))
10822 ;; we have an archive tag, should we use this anyway?
10823 (or (not org-agenda-skip-archived-trees)
10824 (and (eq action 'agenda) org-agenda-archives-mode))))
10825 (unless (eq action 'sparse-tree) (org-agenda-skip))
10826
10827 ;; select this headline
10828
10829 (cond
10830 ((eq action 'sparse-tree)
10831 (and org-highlight-sparse-tree-matches
10832 (org-get-heading) (match-end 0)
10833 (org-highlight-new-match
10834 (match-beginning 0) (match-beginning 1)))
10835 (org-show-context 'tags-tree))
10836 ((eq action 'agenda)
10837 (setq txt (org-format-agenda-item
10838 ""
10839 (concat
10840 (if (eq org-tags-match-list-sublevels 'indented)
10841 (make-string (1- level) ?.) "")
10842 (org-get-heading))
10843 category
10844 tags-list
10845 )
10846 priority (org-get-priority txt))
10847 (goto-char lspos)
10848 (setq marker (org-agenda-new-marker))
10849 (org-add-props txt props
10850 'org-marker marker 'org-hd-marker marker 'org-category category
10851 'todo-state todo
10852 'priority priority 'type "tagsmatch")
10853 (push txt rtn))
10854 ((functionp action)
10855 (setq org-map-continue-from nil)
10856 (save-excursion
10857 (setq rtn1 (funcall action))
10858 (push rtn1 rtn)))
10859 (t (error "Invalid action")))
10860
10861 ;; if we are to skip sublevels, jump to end of subtree
10862 (unless org-tags-match-list-sublevels
10863 (org-end-of-subtree t)
10864 (backward-char 1))))
10865 ;; Get the correct position from where to continue
10866 (if org-map-continue-from
10867 (goto-char org-map-continue-from)
10868 (and (= (point) lspos) (end-of-line 1)))))
10869 (when (and (eq action 'sparse-tree)
10870 (not org-sparse-tree-open-archived-trees))
10871 (org-hide-archived-subtrees (point-min) (point-max)))
10872 (nreverse rtn)))
10873
10874 (defun org-remove-uniherited-tags (tags)
10875 "Remove all tags that are not inherited from the list TAGS."
10876 (cond
10877 ((eq org-use-tag-inheritance t)
10878 (if org-tags-exclude-from-inheritance
10879 (org-delete-all org-tags-exclude-from-inheritance tags)
10880 tags))
10881 ((not org-use-tag-inheritance) nil)
10882 ((stringp org-use-tag-inheritance)
10883 (delq nil (mapcar
10884 (lambda (x)
10885 (if (and (string-match org-use-tag-inheritance x)
10886 (not (member x org-tags-exclude-from-inheritance)))
10887 x nil))
10888 tags)))
10889 ((listp org-use-tag-inheritance)
10890 (delq nil (mapcar
10891 (lambda (x)
10892 (if (member x org-use-tag-inheritance) x nil))
10893 tags)))))
10894
10895 (defvar todo-only) ;; dynamically scoped
10896
10897 (defun org-match-sparse-tree (&optional todo-only match)
10898 "Create a sparse tree according to tags string MATCH.
10899 MATCH can contain positive and negative selection of tags, like
10900 \"+WORK+URGENT-WITHBOSS\".
10901 If optional argument TODO-ONLY is non-nil, only select lines that are
10902 also TODO lines."
10903 (interactive "P")
10904 (org-prepare-agenda-buffers (list (current-buffer)))
10905 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10906
10907 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10908
10909 (defvar org-cached-props nil)
10910 (defun org-cached-entry-get (pom property)
10911 (if (or (eq t org-use-property-inheritance)
10912 (and (stringp org-use-property-inheritance)
10913 (string-match org-use-property-inheritance property))
10914 (and (listp org-use-property-inheritance)
10915 (member property org-use-property-inheritance)))
10916 ;; Caching is not possible, check it directly
10917 (org-entry-get pom property 'inherit)
10918 ;; Get all properties, so that we can do complicated checks easily
10919 (cdr (assoc property (or org-cached-props
10920 (setq org-cached-props
10921 (org-entry-properties pom)))))))
10922
10923 (defun org-global-tags-completion-table (&optional files)
10924 "Return the list of all tags in all agenda buffer/files."
10925 (save-excursion
10926 (org-uniquify
10927 (delq nil
10928 (apply 'append
10929 (mapcar
10930 (lambda (file)
10931 (set-buffer (find-file-noselect file))
10932 (append (org-get-buffer-tags)
10933 (mapcar (lambda (x) (if (stringp (car-safe x))
10934 (list (car-safe x)) nil))
10935 org-tag-alist)))
10936 (if (and files (car files))
10937 files
10938 (org-agenda-files))))))))
10939
10940 (defun org-make-tags-matcher (match)
10941 "Create the TAGS//TODO matcher form for the selection string MATCH."
10942 ;; todo-only is scoped dynamically into this function, and the function
10943 ;; may change it if the matcher asks for it.
10944 (unless match
10945 ;; Get a new match request, with completion
10946 (let ((org-last-tags-completion-table
10947 (org-global-tags-completion-table)))
10948 (setq match (org-completing-read-no-i
10949 "Match: " 'org-tags-completion-function nil nil nil
10950 'org-tags-history))))
10951
10952 ;; Parse the string and create a lisp form
10953 (let ((match0 match)
10954 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10955 minus tag mm
10956 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10957 orterms term orlist re-p str-p level-p level-op time-p
10958 prop-p pn pv po cat-p gv rest)
10959 (if (string-match "/+" match)
10960 ;; match contains also a todo-matching request
10961 (progn
10962 (setq tagsmatch (substring match 0 (match-beginning 0))
10963 todomatch (substring match (match-end 0)))
10964 (if (string-match "^!" todomatch)
10965 (setq todo-only t todomatch (substring todomatch 1)))
10966 (if (string-match "^\\s-*$" todomatch)
10967 (setq todomatch nil)))
10968 ;; only matching tags
10969 (setq tagsmatch match todomatch nil))
10970
10971 ;; Make the tags matcher
10972 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10973 (setq tagsmatcher t)
10974 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10975 (while (setq term (pop orterms))
10976 (while (and (equal (substring term -1) "\\") orterms)
10977 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10978 (while (string-match re term)
10979 (setq rest (substring term (match-end 0))
10980 minus (and (match-end 1)
10981 (equal (match-string 1 term) "-"))
10982 tag (match-string 2 term)
10983 re-p (equal (string-to-char tag) ?{)
10984 level-p (match-end 4)
10985 prop-p (match-end 5)
10986 mm (cond
10987 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10988 (level-p
10989 (setq level-op (org-op-to-function (match-string 3 term)))
10990 `(,level-op level ,(string-to-number
10991 (match-string 4 term))))
10992 (prop-p
10993 (setq pn (match-string 5 term)
10994 po (match-string 6 term)
10995 pv (match-string 7 term)
10996 cat-p (equal pn "CATEGORY")
10997 re-p (equal (string-to-char pv) ?{)
10998 str-p (equal (string-to-char pv) ?\")
10999 time-p (save-match-data
11000 (string-match "^\"[[<].*[]>]\"$" pv))
11001 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11002 (if time-p (setq pv (org-matcher-time pv)))
11003 (setq po (org-op-to-function po (if time-p 'time str-p)))
11004 (cond
11005 ((equal pn "CATEGORY")
11006 (setq gv '(get-text-property (point) 'org-category)))
11007 ((equal pn "TODO")
11008 (setq gv 'todo))
11009 (t
11010 (setq gv `(org-cached-entry-get nil ,pn))))
11011 (if re-p
11012 (if (eq po 'org<>)
11013 `(not (string-match ,pv (or ,gv "")))
11014 `(string-match ,pv (or ,gv "")))
11015 (if str-p
11016 `(,po (or ,gv "") ,pv)
11017 `(,po (string-to-number (or ,gv ""))
11018 ,(string-to-number pv) ))))
11019 (t `(member ,tag tags-list)))
11020 mm (if minus (list 'not mm) mm)
11021 term rest)
11022 (push mm tagsmatcher))
11023 (push (if (> (length tagsmatcher) 1)
11024 (cons 'and tagsmatcher)
11025 (car tagsmatcher))
11026 orlist)
11027 (setq tagsmatcher nil))
11028 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11029 (setq tagsmatcher
11030 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11031 ;; Make the todo matcher
11032 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11033 (setq todomatcher t)
11034 (setq orterms (org-split-string todomatch "|") orlist nil)
11035 (while (setq term (pop orterms))
11036 (while (string-match re term)
11037 (setq minus (and (match-end 1)
11038 (equal (match-string 1 term) "-"))
11039 kwd (match-string 2 term)
11040 re-p (equal (string-to-char kwd) ?{)
11041 term (substring term (match-end 0))
11042 mm (if re-p
11043 `(string-match ,(substring kwd 1 -1) todo)
11044 (list 'equal 'todo kwd))
11045 mm (if minus (list 'not mm) mm))
11046 (push mm todomatcher))
11047 (push (if (> (length todomatcher) 1)
11048 (cons 'and todomatcher)
11049 (car todomatcher))
11050 orlist)
11051 (setq todomatcher nil))
11052 (setq todomatcher (if (> (length orlist) 1)
11053 (cons 'or orlist) (car orlist))))
11054
11055 ;; Return the string and lisp forms of the matcher
11056 (setq matcher (if todomatcher
11057 (list 'and tagsmatcher todomatcher)
11058 tagsmatcher))
11059 (cons match0 matcher)))
11060
11061 (defun org-op-to-function (op &optional stringp)
11062 "Turn an operator into the appropriate function."
11063 (setq op
11064 (cond
11065 ((equal op "<" ) '(< string< org-time<))
11066 ((equal op ">" ) '(> org-string> org-time>))
11067 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11068 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11069 ((member op '("=" "==")) '(= string= org-time=))
11070 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11071 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11072
11073 (defun org<> (a b) (not (= a b)))
11074 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11075 (defun org-string>= (a b) (not (string< a b)))
11076 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11077 (defun org-string<> (a b) (not (string= a b)))
11078 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11079 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11080 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11081 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11082 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11083 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11084 (defun org-2ft (s)
11085 "Convert S to a floating point time.
11086 If S is already a number, just return it. If it is a string, parse
11087 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11088 (cond
11089 ((numberp s) s)
11090 ((stringp s)
11091 (condition-case nil
11092 (float-time (apply 'encode-time (org-parse-time-string s)))
11093 (error 0.)))
11094 (t 0.)))
11095
11096 (defun org-time-today ()
11097 "Time in seconds today at 0:00.
11098 Returns the float number of seconds since the beginning of the
11099 epoch to the beginning of today (00:00)."
11100 (float-time (apply 'encode-time
11101 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11102
11103 (defun org-matcher-time (s)
11104 "Interpret a time comparison value."
11105 (save-match-data
11106 (cond
11107 ((string= s "<now>") (float-time))
11108 ((string= s "<today>") (org-time-today))
11109 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11110 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11111 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11112 (+ (org-time-today)
11113 (* (string-to-number (match-string 1 s))
11114 (cdr (assoc (match-string 2 s)
11115 '(("d" . 86400.0) ("w" . 604800.0)
11116 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11117 (t (org-2ft s)))))
11118
11119 (defun org-match-any-p (re list)
11120 "Does re match any element of list?"
11121 (setq list (mapcar (lambda (x) (string-match re x)) list))
11122 (delq nil list))
11123
11124 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11125 (defvar org-tags-overlay (org-make-overlay 1 1))
11126 (org-detach-overlay org-tags-overlay)
11127
11128 (defun org-get-local-tags-at (&optional pos)
11129 "Get a list of tags defined in the current headline."
11130 (org-get-tags-at pos 'local))
11131
11132 (defun org-get-local-tags ()
11133 "Get a list of tags defined in the current headline."
11134 (org-get-tags-at nil 'local))
11135
11136 (defun org-get-tags-at (&optional pos local)
11137 "Get a list of all headline tags applicable at POS.
11138 POS defaults to point. If tags are inherited, the list contains
11139 the targets in the same sequence as the headlines appear, i.e.
11140 the tags of the current headline come last.
11141 When LOCAL is non-nil, only return tags from the current headline,
11142 ignore inherited ones."
11143 (interactive)
11144 (if (and org-trust-scanner-tags
11145 (or (not pos) (equal pos (point)))
11146 (not local))
11147 org-scanner-tags
11148 (let (tags ltags lastpos parent)
11149 (save-excursion
11150 (save-restriction
11151 (widen)
11152 (goto-char (or pos (point)))
11153 (save-match-data
11154 (catch 'done
11155 (condition-case nil
11156 (progn
11157 (org-back-to-heading t)
11158 (while (not (equal lastpos (point)))
11159 (setq lastpos (point))
11160 (when (looking-at
11161 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
11162 (setq ltags (org-split-string
11163 (org-match-string-no-properties 1) ":"))
11164 (when parent
11165 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
11166 (setq tags (append
11167 (if parent
11168 (org-remove-uniherited-tags ltags)
11169 ltags)
11170 tags)))
11171 (or org-use-tag-inheritance (throw 'done t))
11172 (if local (throw 'done t))
11173 (or (org-up-heading-safe) (error nil))
11174 (setq parent t)))
11175 (error nil)))))
11176 (append (org-remove-uniherited-tags org-file-tags) tags)))))
11177
11178 (defun org-add-prop-inherited (s)
11179 (add-text-properties 0 (length s) '(inherited t) s)
11180 s)
11181
11182 (defun org-toggle-tag (tag &optional onoff)
11183 "Toggle the tag TAG for the current line.
11184 If ONOFF is `on' or `off', don't toggle but set to this state."
11185 (let (res current)
11186 (save-excursion
11187 (org-back-to-heading t)
11188 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
11189 (point-at-eol) t)
11190 (progn
11191 (setq current (match-string 1))
11192 (replace-match ""))
11193 (setq current ""))
11194 (setq current (nreverse (org-split-string current ":")))
11195 (cond
11196 ((eq onoff 'on)
11197 (setq res t)
11198 (or (member tag current) (push tag current)))
11199 ((eq onoff 'off)
11200 (or (not (member tag current)) (setq current (delete tag current))))
11201 (t (if (member tag current)
11202 (setq current (delete tag current))
11203 (setq res t)
11204 (push tag current))))
11205 (end-of-line 1)
11206 (if current
11207 (progn
11208 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
11209 (org-set-tags nil t))
11210 (delete-horizontal-space))
11211 (run-hooks 'org-after-tags-change-hook))
11212 res))
11213
11214 (defun org-align-tags-here (to-col)
11215 ;; Assumes that this is a headline
11216 (let ((pos (point)) (col (current-column)) ncol tags-l p)
11217 (beginning-of-line 1)
11218 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11219 (< pos (match-beginning 2)))
11220 (progn
11221 (setq tags-l (- (match-end 2) (match-beginning 2)))
11222 (goto-char (match-beginning 1))
11223 (insert " ")
11224 (delete-region (point) (1+ (match-beginning 2)))
11225 (setq ncol (max (1+ (current-column))
11226 (1+ col)
11227 (if (> to-col 0)
11228 to-col
11229 (- (abs to-col) tags-l))))
11230 (setq p (point))
11231 (insert (make-string (- ncol (current-column)) ?\ ))
11232 (setq ncol (current-column))
11233 (when indent-tabs-mode (tabify p (point-at-eol)))
11234 (org-move-to-column (min ncol col) t))
11235 (goto-char pos))))
11236
11237 (defun org-set-tags-command (&optional arg just-align)
11238 "Call the set-tags command for the current entry."
11239 (interactive "P")
11240 (if (org-on-heading-p)
11241 (org-set-tags arg just-align)
11242 (save-excursion
11243 (org-back-to-heading t)
11244 (org-set-tags arg just-align))))
11245
11246 (defun org-set-tags-to (data)
11247 "Set the tags of the current entry to DATA, replacing the current tags.
11248 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
11249 If DATA is nil or the empty string, any tags will be removed."
11250 (interactive "sTags: ")
11251 (setq data
11252 (cond
11253 ((eq data nil) "")
11254 ((equal data "") "")
11255 ((stringp data)
11256 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
11257 ":"))
11258 ((listp data)
11259 (concat ":" (mapconcat 'identity data ":") ":"))
11260 (t nil)))
11261 (when data
11262 (save-excursion
11263 (org-back-to-heading t)
11264 (when (looking-at org-complex-heading-regexp)
11265 (if (match-end 5)
11266 (progn
11267 (goto-char (match-beginning 5))
11268 (insert data)
11269 (delete-region (point) (point-at-eol))
11270 (org-set-tags nil 'align))
11271 (goto-char (point-at-eol))
11272 (insert " " data)
11273 (org-set-tags nil 'align)))
11274 (beginning-of-line 1)
11275 (if (looking-at ".*?\\([ \t]+\\)$")
11276 (delete-region (match-beginning 1) (match-end 1))))))
11277
11278 (defun org-set-tags (&optional arg just-align)
11279 "Set the tags for the current headline.
11280 With prefix ARG, realign all tags in headings in the current buffer."
11281 (interactive "P")
11282 (let* ((re (concat "^" outline-regexp))
11283 (current (org-get-tags-string))
11284 (col (current-column))
11285 (org-setting-tags t)
11286 table current-tags inherited-tags ; computed below when needed
11287 tags p0 c0 c1 rpl)
11288 (if arg
11289 (save-excursion
11290 (goto-char (point-min))
11291 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
11292 (while (re-search-forward re nil t)
11293 (org-set-tags nil t)
11294 (end-of-line 1)))
11295 (message "All tags realigned to column %d" org-tags-column))
11296 (if just-align
11297 (setq tags current)
11298 ;; Get a new set of tags from the user
11299 (save-excursion
11300 (setq table (append org-tag-persistent-alist
11301 (or org-tag-alist (org-get-buffer-tags)))
11302 org-last-tags-completion-table table
11303 current-tags (org-split-string current ":")
11304 inherited-tags (nreverse
11305 (nthcdr (length current-tags)
11306 (nreverse (org-get-tags-at))))
11307 tags
11308 (if (or (eq t org-use-fast-tag-selection)
11309 (and org-use-fast-tag-selection
11310 (delq nil (mapcar 'cdr table))))
11311 (org-fast-tag-selection
11312 current-tags inherited-tags table
11313 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11314 (let ((org-add-colon-after-tag-completion t))
11315 (org-trim
11316 (org-without-partial-completion
11317 (org-icompleting-read "Tags: " 'org-tags-completion-function
11318 nil nil current 'org-tags-history)))))))
11319 (while (string-match "[-+&]+" tags)
11320 ;; No boolean logic, just a list
11321 (setq tags (replace-match ":" t t tags))))
11322
11323 (if org-tags-sort-function
11324 (setq tags (mapconcat 'identity
11325 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11326 org-tags-sort-function) ":")))
11327
11328 (if (string-match "\\`[\t ]*\\'" tags)
11329 (setq tags "")
11330 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11331 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11332
11333 ;; Insert new tags at the correct column
11334 (beginning-of-line 1)
11335 (cond
11336 ((and (equal current "") (equal tags "")))
11337 ((re-search-forward
11338 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11339 (point-at-eol) t)
11340 (if (equal tags "")
11341 (setq rpl "")
11342 (goto-char (match-beginning 0))
11343 (setq c0 (current-column) p0 (point)
11344 c1 (max (1+ c0) (if (> org-tags-column 0)
11345 org-tags-column
11346 (- (- org-tags-column) (length tags))))
11347 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11348 (replace-match rpl t t)
11349 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11350 tags)
11351 (t (error "Tags alignment failed")))
11352 (org-move-to-column col)
11353 (unless just-align
11354 (run-hooks 'org-after-tags-change-hook)))))
11355
11356 (defun org-change-tag-in-region (beg end tag off)
11357 "Add or remove TAG for each entry in the region.
11358 This works in the agenda, and also in an org-mode buffer."
11359 (interactive
11360 (list (region-beginning) (region-end)
11361 (let ((org-last-tags-completion-table
11362 (if (org-mode-p)
11363 (org-get-buffer-tags)
11364 (org-global-tags-completion-table))))
11365 (org-icompleting-read
11366 "Tag: " 'org-tags-completion-function nil nil nil
11367 'org-tags-history))
11368 (progn
11369 (message "[s]et or [r]emove? ")
11370 (equal (read-char-exclusive) ?r))))
11371 (if (fboundp 'deactivate-mark) (deactivate-mark))
11372 (let ((agendap (equal major-mode 'org-agenda-mode))
11373 l1 l2 m buf pos newhead (cnt 0))
11374 (goto-char end)
11375 (setq l2 (1- (org-current-line)))
11376 (goto-char beg)
11377 (setq l1 (org-current-line))
11378 (loop for l from l1 to l2 do
11379 (org-goto-line l)
11380 (setq m (get-text-property (point) 'org-hd-marker))
11381 (when (or (and (org-mode-p) (org-on-heading-p))
11382 (and agendap m))
11383 (setq buf (if agendap (marker-buffer m) (current-buffer))
11384 pos (if agendap m (point)))
11385 (with-current-buffer buf
11386 (save-excursion
11387 (save-restriction
11388 (goto-char pos)
11389 (setq cnt (1+ cnt))
11390 (org-toggle-tag tag (if off 'off 'on))
11391 (setq newhead (org-get-heading)))))
11392 (and agendap (org-agenda-change-all-lines newhead m))))
11393 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11394
11395 (defun org-tags-completion-function (string predicate &optional flag)
11396 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11397 (confirm (lambda (x) (stringp (car x)))))
11398 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11399 (setq s1 (match-string 1 string)
11400 s2 (match-string 2 string))
11401 (setq s1 "" s2 string))
11402 (cond
11403 ((eq flag nil)
11404 ;; try completion
11405 (setq rtn (try-completion s2 ctable confirm))
11406 (if (stringp rtn)
11407 (setq rtn
11408 (concat s1 s2 (substring rtn (length s2))
11409 (if (and org-add-colon-after-tag-completion
11410 (assoc rtn ctable))
11411 ":" ""))))
11412 rtn)
11413 ((eq flag t)
11414 ;; all-completions
11415 (all-completions s2 ctable confirm)
11416 )
11417 ((eq flag 'lambda)
11418 ;; exact match?
11419 (assoc s2 ctable)))
11420 ))
11421
11422 (defun org-fast-tag-insert (kwd tags face &optional end)
11423 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11424 (insert (format "%-12s" (concat kwd ":"))
11425 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11426 (or end "")))
11427
11428 (defun org-fast-tag-show-exit (flag)
11429 (save-excursion
11430 (org-goto-line 3)
11431 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11432 (replace-match ""))
11433 (when flag
11434 (end-of-line 1)
11435 (org-move-to-column (- (window-width) 19) t)
11436 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11437
11438 (defun org-set-current-tags-overlay (current prefix)
11439 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11440 (if (featurep 'xemacs)
11441 (org-overlay-display org-tags-overlay (concat prefix s)
11442 'secondary-selection)
11443 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11444 (org-overlay-display org-tags-overlay (concat prefix s)))))
11445
11446 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11447 "Fast tag selection with single keys.
11448 CURRENT is the current list of tags in the headline, INHERITED is the
11449 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11450 possibly with grouping information. TODO-TABLE is a similar table with
11451 TODO keywords, should these have keys assigned to them.
11452 If the keys are nil, a-z are automatically assigned.
11453 Returns the new tags string, or nil to not change the current settings."
11454 (let* ((fulltable (append table todo-table))
11455 (maxlen (apply 'max (mapcar
11456 (lambda (x)
11457 (if (stringp (car x)) (string-width (car x)) 0))
11458 fulltable)))
11459 (buf (current-buffer))
11460 (expert (eq org-fast-tag-selection-single-key 'expert))
11461 (buffer-tags nil)
11462 (fwidth (+ maxlen 3 1 3))
11463 (ncol (/ (- (window-width) 4) fwidth))
11464 (i-face 'org-done)
11465 (c-face 'org-todo)
11466 tg cnt e c char c1 c2 ntable tbl rtn
11467 ov-start ov-end ov-prefix
11468 (exit-after-next org-fast-tag-selection-single-key)
11469 (done-keywords org-done-keywords)
11470 groups ingroup)
11471 (save-excursion
11472 (beginning-of-line 1)
11473 (if (looking-at
11474 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11475 (setq ov-start (match-beginning 1)
11476 ov-end (match-end 1)
11477 ov-prefix "")
11478 (setq ov-start (1- (point-at-eol))
11479 ov-end (1+ ov-start))
11480 (skip-chars-forward "^\n\r")
11481 (setq ov-prefix
11482 (concat
11483 (buffer-substring (1- (point)) (point))
11484 (if (> (current-column) org-tags-column)
11485 " "
11486 (make-string (- org-tags-column (current-column)) ?\ ))))))
11487 (org-move-overlay org-tags-overlay ov-start ov-end)
11488 (save-window-excursion
11489 (if expert
11490 (set-buffer (get-buffer-create " *Org tags*"))
11491 (delete-other-windows)
11492 (split-window-vertically)
11493 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11494 (erase-buffer)
11495 (org-set-local 'org-done-keywords done-keywords)
11496 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11497 (org-fast-tag-insert "Current" current c-face "\n\n")
11498 (org-fast-tag-show-exit exit-after-next)
11499 (org-set-current-tags-overlay current ov-prefix)
11500 (setq tbl fulltable char ?a cnt 0)
11501 (while (setq e (pop tbl))
11502 (cond
11503 ((equal e '(:startgroup))
11504 (push '() groups) (setq ingroup t)
11505 (when (not (= cnt 0))
11506 (setq cnt 0)
11507 (insert "\n"))
11508 (insert "{ "))
11509 ((equal e '(:endgroup))
11510 (setq ingroup nil cnt 0)
11511 (insert "}\n"))
11512 ((equal e '(:newline))
11513 (when (not (= cnt 0))
11514 (setq cnt 0)
11515 (insert "\n")
11516 (setq e (car tbl))
11517 (while (equal (car tbl) '(:newline))
11518 (insert "\n")
11519 (setq tbl (cdr tbl)))))
11520 (t
11521 (setq tg (copy-sequence (car e)) c2 nil)
11522 (if (cdr e)
11523 (setq c (cdr e))
11524 ;; automatically assign a character.
11525 (setq c1 (string-to-char
11526 (downcase (substring
11527 tg (if (= (string-to-char tg) ?@) 1 0)))))
11528 (if (or (rassoc c1 ntable) (rassoc c1 table))
11529 (while (or (rassoc char ntable) (rassoc char table))
11530 (setq char (1+ char)))
11531 (setq c2 c1))
11532 (setq c (or c2 char)))
11533 (if ingroup (push tg (car groups)))
11534 (setq tg (org-add-props tg nil 'face
11535 (cond
11536 ((not (assoc tg table))
11537 (org-get-todo-face tg))
11538 ((member tg current) c-face)
11539 ((member tg inherited) i-face)
11540 (t nil))))
11541 (if (and (= cnt 0) (not ingroup)) (insert " "))
11542 (insert "[" c "] " tg (make-string
11543 (- fwidth 4 (length tg)) ?\ ))
11544 (push (cons tg c) ntable)
11545 (when (= (setq cnt (1+ cnt)) ncol)
11546 (insert "\n")
11547 (if ingroup (insert " "))
11548 (setq cnt 0)))))
11549 (setq ntable (nreverse ntable))
11550 (insert "\n")
11551 (goto-char (point-min))
11552 (if (not expert) (org-fit-window-to-buffer))
11553 (setq rtn
11554 (catch 'exit
11555 (while t
11556 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11557 (if groups " [!] no groups" " [!]groups")
11558 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11559 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11560 (cond
11561 ((= c ?\r) (throw 'exit t))
11562 ((= c ?!)
11563 (setq groups (not groups))
11564 (goto-char (point-min))
11565 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11566 ((= c ?\C-c)
11567 (if (not expert)
11568 (org-fast-tag-show-exit
11569 (setq exit-after-next (not exit-after-next)))
11570 (setq expert nil)
11571 (delete-other-windows)
11572 (split-window-vertically)
11573 (org-switch-to-buffer-other-window " *Org tags*")
11574 (org-fit-window-to-buffer)))
11575 ((or (= c ?\C-g)
11576 (and (= c ?q) (not (rassoc c ntable))))
11577 (org-detach-overlay org-tags-overlay)
11578 (setq quit-flag t))
11579 ((= c ?\ )
11580 (setq current nil)
11581 (if exit-after-next (setq exit-after-next 'now)))
11582 ((= c ?\t)
11583 (condition-case nil
11584 (setq tg (org-icompleting-read
11585 "Tag: "
11586 (or buffer-tags
11587 (with-current-buffer buf
11588 (org-get-buffer-tags)))))
11589 (quit (setq tg "")))
11590 (when (string-match "\\S-" tg)
11591 (add-to-list 'buffer-tags (list tg))
11592 (if (member tg current)
11593 (setq current (delete tg current))
11594 (push tg current)))
11595 (if exit-after-next (setq exit-after-next 'now)))
11596 ((setq e (rassoc c todo-table) tg (car e))
11597 (with-current-buffer buf
11598 (save-excursion (org-todo tg)))
11599 (if exit-after-next (setq exit-after-next 'now)))
11600 ((setq e (rassoc c ntable) tg (car e))
11601 (if (member tg current)
11602 (setq current (delete tg current))
11603 (loop for g in groups do
11604 (if (member tg g)
11605 (mapc (lambda (x)
11606 (setq current (delete x current)))
11607 g)))
11608 (push tg current))
11609 (if exit-after-next (setq exit-after-next 'now))))
11610
11611 ;; Create a sorted list
11612 (setq current
11613 (sort current
11614 (lambda (a b)
11615 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11616 (if (eq exit-after-next 'now) (throw 'exit t))
11617 (goto-char (point-min))
11618 (beginning-of-line 2)
11619 (delete-region (point) (point-at-eol))
11620 (org-fast-tag-insert "Current" current c-face)
11621 (org-set-current-tags-overlay current ov-prefix)
11622 (while (re-search-forward
11623 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11624 (setq tg (match-string 1))
11625 (add-text-properties
11626 (match-beginning 1) (match-end 1)
11627 (list 'face
11628 (cond
11629 ((member tg current) c-face)
11630 ((member tg inherited) i-face)
11631 (t (get-text-property (match-beginning 1) 'face))))))
11632 (goto-char (point-min)))))
11633 (org-detach-overlay org-tags-overlay)
11634 (if rtn
11635 (mapconcat 'identity current ":")
11636 nil))))
11637
11638 (defun org-get-tags-string ()
11639 "Get the TAGS string in the current headline."
11640 (unless (org-on-heading-p t)
11641 (error "Not on a heading"))
11642 (save-excursion
11643 (beginning-of-line 1)
11644 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11645 (org-match-string-no-properties 1)
11646 "")))
11647
11648 (defun org-get-tags ()
11649 "Get the list of tags specified in the current headline."
11650 (org-split-string (org-get-tags-string) ":"))
11651
11652 (defun org-get-buffer-tags ()
11653 "Get a table of all tags used in the buffer, for completion."
11654 (let (tags)
11655 (save-excursion
11656 (goto-char (point-min))
11657 (while (re-search-forward
11658 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11659 (when (equal (char-after (point-at-bol 0)) ?*)
11660 (mapc (lambda (x) (add-to-list 'tags x))
11661 (org-split-string (org-match-string-no-properties 1) ":")))))
11662 (mapcar 'list tags)))
11663
11664 ;;;; The mapping API
11665
11666 ;;;###autoload
11667 (defun org-map-entries (func &optional match scope &rest skip)
11668 "Call FUNC at each headline selected by MATCH in SCOPE.
11669
11670 FUNC is a function or a lisp form. The function will be called without
11671 arguments, with the cursor positioned at the beginning of the headline.
11672 The return values of all calls to the function will be collected and
11673 returned as a list.
11674
11675 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11676 does not need to preserve point. After evaluation, the cursor will be
11677 moved to the end of the line (presumably of the headline of the
11678 processed entry) and search continues from there. Under some
11679 circumstances, this may not produce the wanted results. For example,
11680 if you have removed (e.g. archived) the current (sub)tree it could
11681 mean that the next entry will be skipped entirely. In such cases, you
11682 can specify the position from where search should continue by making
11683 FUNC set the variable `org-map-continue-from' to the desired buffer
11684 position.
11685
11686 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11687 Only headlines that are matched by this query will be considered during
11688 the iteration. When MATCH is nil or t, all headlines will be
11689 visited by the iteration.
11690
11691 SCOPE determines the scope of this command. It can be any of:
11692
11693 nil The current buffer, respecting the restriction if any
11694 tree The subtree started with the entry at point
11695 file The current buffer, without restriction
11696 file-with-archives
11697 The current buffer, and any archives associated with it
11698 agenda All agenda files
11699 agenda-with-archives
11700 All agenda files with any archive files associated with them
11701 \(file1 file2 ...)
11702 If this is a list, all files in the list will be scanned
11703
11704 The remaining args are treated as settings for the skipping facilities of
11705 the scanner. The following items can be given here:
11706
11707 archive skip trees with the archive tag.
11708 comment skip trees with the COMMENT keyword
11709 function or Emacs Lisp form:
11710 will be used as value for `org-agenda-skip-function', so whenever
11711 the the function returns t, FUNC will not be called for that
11712 entry and search will continue from the point where the
11713 function leaves it.
11714
11715 If your function needs to retrieve the tags including inherited tags
11716 at the *current* entry, you can use the value of the variable
11717 `org-scanner-tags' which will be much faster than getting the value
11718 with `org-get-tags-at'. If your function gets properties with
11719 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11720 to t around the call to `org-entry-properties' to get the same speedup.
11721 Note that if your function moves around to retrieve tags and properties at
11722 a *different* entry, you cannot use these techniques."
11723 (let* ((org-agenda-archives-mode nil) ; just to make sure
11724 (org-agenda-skip-archived-trees (memq 'archive skip))
11725 (org-agenda-skip-comment-trees (memq 'comment skip))
11726 (org-agenda-skip-function
11727 (car (org-delete-all '(comment archive) skip)))
11728 (org-tags-match-list-sublevels t)
11729 matcher file res
11730 org-todo-keywords-for-agenda
11731 org-done-keywords-for-agenda
11732 org-todo-keyword-alist-for-agenda
11733 org-drawers-for-agenda
11734 org-tag-alist-for-agenda)
11735
11736 (cond
11737 ((eq match t) (setq matcher t))
11738 ((eq match nil) (setq matcher t))
11739 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11740
11741 (save-excursion
11742 (save-restriction
11743 (when (eq scope 'tree)
11744 (org-back-to-heading t)
11745 (org-narrow-to-subtree)
11746 (setq scope nil))
11747
11748 (if (not scope)
11749 (progn
11750 (org-prepare-agenda-buffers
11751 (list (buffer-file-name (current-buffer))))
11752 (setq res (org-scan-tags func matcher)))
11753 ;; Get the right scope
11754 (cond
11755 ((and scope (listp scope) (symbolp (car scope)))
11756 (setq scope (eval scope)))
11757 ((eq scope 'agenda)
11758 (setq scope (org-agenda-files t)))
11759 ((eq scope 'agenda-with-archives)
11760 (setq scope (org-agenda-files t))
11761 (setq scope (org-add-archive-files scope)))
11762 ((eq scope 'file)
11763 (setq scope (list (buffer-file-name))))
11764 ((eq scope 'file-with-archives)
11765 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11766 (org-prepare-agenda-buffers scope)
11767 (while (setq file (pop scope))
11768 (with-current-buffer (org-find-base-buffer-visiting file)
11769 (save-excursion
11770 (save-restriction
11771 (widen)
11772 (goto-char (point-min))
11773 (setq res (append res (org-scan-tags func matcher))))))))))
11774 res))
11775
11776 ;;;; Properties
11777
11778 ;;; Setting and retrieving properties
11779
11780 (defconst org-special-properties
11781 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11782 "TIMESTAMP" "TIMESTAMP_IA")
11783 "The special properties valid in Org-mode.
11784
11785 These are properties that are not defined in the property drawer,
11786 but in some other way.")
11787
11788 (defconst org-default-properties
11789 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11790 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11791 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11792 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11793 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11794 "CLOCK_MODELINE_TOTAL")
11795 "Some properties that are used by Org-mode for various purposes.
11796 Being in this list makes sure that they are offered for completion.")
11797
11798 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11799 "Regular expression matching the first line of a property drawer.")
11800
11801 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11802 "Regular expression matching the first line of a property drawer.")
11803
11804 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11805 "Regular expression matching the first line of a property drawer.")
11806
11807 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11808 "Regular expression matching the first line of a property drawer.")
11809
11810 (defconst org-property-drawer-re
11811 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11812 org-property-end-re "\\)\n?")
11813 "Matches an entire property drawer.")
11814
11815 (defconst org-clock-drawer-re
11816 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11817 org-property-end-re "\\)\n?")
11818 "Matches an entire clock drawer.")
11819
11820 (defun org-property-action ()
11821 "Do an action on properties."
11822 (interactive)
11823 (let (c)
11824 (org-at-property-p)
11825 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11826 (setq c (read-char-exclusive))
11827 (cond
11828 ((equal c ?s)
11829 (call-interactively 'org-set-property))
11830 ((equal c ?d)
11831 (call-interactively 'org-delete-property))
11832 ((equal c ?D)
11833 (call-interactively 'org-delete-property-globally))
11834 ((equal c ?c)
11835 (call-interactively 'org-compute-property-at-point))
11836 (t (error "No such property action %c" c)))))
11837
11838 (defun org-set-effort (&optional value)
11839 "Set the effort property of the current entry.
11840 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
11841 allowed value."
11842 (interactive "P")
11843 (if (equal value 0) (setq value 10))
11844 (let* ((completion-ignore-case t)
11845 (prop org-effort-property)
11846 (cur (org-entry-get nil prop))
11847 (allowed (org-property-get-allowed-values nil prop 'table))
11848 (existing (mapcar 'list (org-property-values prop)))
11849 (val (cond
11850 ((stringp value) value)
11851 ((and allowed (integerp value))
11852 (or (car (nth (1- value) allowed))
11853 (car (org-last allowed))))
11854 (allowed
11855 (org-completing-read "Value: " allowed nil 'req-match))
11856 (t
11857 (let (org-completion-use-ido org-completion-use-iswitchb)
11858 (org-completing-read
11859 (concat "Value " (if (and cur (string-match "\\S-" cur))
11860 (concat "[" cur "]") "")
11861 ": ")
11862 existing nil nil "" nil cur))))))
11863 (unless (equal (org-entry-get nil prop) val)
11864 (org-entry-put nil prop val))
11865 (message "%s is now %s" prop val)))
11866
11867 (defun org-at-property-p ()
11868 "Is the cursor in a property line?"
11869 ;; FIXME: Does not check if we are actually in the drawer.
11870 ;; FIXME: also returns true on any drawers.....
11871 ;; This is used by C-c C-c for property action.
11872 (save-excursion
11873 (beginning-of-line 1)
11874 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11875
11876 (defun org-get-property-block (&optional beg end force)
11877 "Return the (beg . end) range of the body of the property drawer.
11878 BEG and END can be beginning and end of subtree, if not given
11879 they will be found.
11880 If the drawer does not exist and FORCE is non-nil, create the drawer."
11881 (catch 'exit
11882 (save-excursion
11883 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11884 (end (or end (progn (outline-next-heading) (point)))))
11885 (goto-char beg)
11886 (if (re-search-forward org-property-start-re end t)
11887 (setq beg (1+ (match-end 0)))
11888 (if force
11889 (save-excursion
11890 (org-insert-property-drawer)
11891 (setq end (progn (outline-next-heading) (point))))
11892 (throw 'exit nil))
11893 (goto-char beg)
11894 (if (re-search-forward org-property-start-re end t)
11895 (setq beg (1+ (match-end 0)))))
11896 (if (re-search-forward org-property-end-re end t)
11897 (setq end (match-beginning 0))
11898 (or force (throw 'exit nil))
11899 (goto-char beg)
11900 (setq end beg)
11901 (org-indent-line-function)
11902 (insert ":END:\n"))
11903 (cons beg end)))))
11904
11905 (defun org-entry-properties (&optional pom which)
11906 "Get all properties of the entry at point-or-marker POM.
11907 This includes the TODO keyword, the tags, time strings for deadline,
11908 scheduled, and clocking, and any additional properties defined in the
11909 entry. The return value is an alist, keys may occur multiple times
11910 if the property key was used several times.
11911 POM may also be nil, in which case the current entry is used.
11912 If WHICH is nil or `all', get all properties. If WHICH is
11913 `special' or `standard', only get that subclass."
11914 (setq which (or which 'all))
11915 (org-with-point-at pom
11916 (let ((clockstr (substring org-clock-string 0 -1))
11917 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11918 beg end range props sum-props key value string clocksum)
11919 (save-excursion
11920 (when (condition-case nil
11921 (and (org-mode-p) (org-back-to-heading t))
11922 (error nil))
11923 (setq beg (point))
11924 (setq sum-props (get-text-property (point) 'org-summaries))
11925 (setq clocksum (get-text-property (point) :org-clock-minutes))
11926 (outline-next-heading)
11927 (setq end (point))
11928 (when (memq which '(all special))
11929 ;; Get the special properties, like TODO and tags
11930 (goto-char beg)
11931 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11932 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11933 (when (looking-at org-priority-regexp)
11934 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11935 (when (and (setq value (org-get-tags-string))
11936 (string-match "\\S-" value))
11937 (push (cons "TAGS" value) props))
11938 (when (setq value (org-get-tags-at))
11939 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11940 props))
11941 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11942 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11943 string (if (equal key clockstr)
11944 (org-no-properties
11945 (org-trim
11946 (buffer-substring
11947 (match-beginning 3) (goto-char (point-at-eol)))))
11948 (substring (org-match-string-no-properties 3) 1 -1)))
11949 (unless key
11950 (if (= (char-after (match-beginning 3)) ?\[)
11951 (setq key "TIMESTAMP_IA")
11952 (setq key "TIMESTAMP")))
11953 (when (or (equal key clockstr) (not (assoc key props)))
11954 (push (cons key string) props)))
11955
11956 )
11957
11958 (when (memq which '(all standard))
11959 ;; Get the standard properties, like :PROP: ...
11960 (setq range (org-get-property-block beg end))
11961 (when range
11962 (goto-char (car range))
11963 (while (re-search-forward
11964 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11965 (cdr range) t)
11966 (setq key (org-match-string-no-properties 1)
11967 value (org-trim (or (org-match-string-no-properties 2) "")))
11968 (unless (member key excluded)
11969 (push (cons key (or value "")) props)))))
11970 (if clocksum
11971 (push (cons "CLOCKSUM"
11972 (org-columns-number-to-string (/ (float clocksum) 60.)
11973 'add_times))
11974 props))
11975 (unless (assoc "CATEGORY" props)
11976 (setq value (or (org-get-category)
11977 (progn (org-refresh-category-properties)
11978 (org-get-category))))
11979 (push (cons "CATEGORY" value) props))
11980 (append sum-props (nreverse props)))))))
11981
11982 (defun org-entry-get (pom property &optional inherit)
11983 "Get value of PROPERTY for entry at point-or-marker POM.
11984 If INHERIT is non-nil and the entry does not have the property,
11985 then also check higher levels of the hierarchy.
11986 If INHERIT is the symbol `selective', use inheritance only if the setting
11987 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11988 If the property is present but empty, the return value is the empty string.
11989 If the property is not present at all, nil is returned."
11990 (org-with-point-at pom
11991 (if (and inherit (if (eq inherit 'selective)
11992 (org-property-inherit-p property)
11993 t))
11994 (org-entry-get-with-inheritance property)
11995 (if (member property org-special-properties)
11996 ;; We need a special property. Use brute force, get all properties.
11997 (cdr (assoc property (org-entry-properties nil 'special)))
11998 (let ((range (org-get-property-block)))
11999 (if (and range
12000 (goto-char (car range))
12001 (re-search-forward
12002 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12003 (cdr range) t))
12004 ;; Found the property, return it.
12005 (if (match-end 1)
12006 (org-match-string-no-properties 1)
12007 "")))))))
12008
12009 (defun org-property-or-variable-value (var &optional inherit)
12010 "Check if there is a property fixing the value of VAR.
12011 If yes, return this value. If not, return the current value of the variable."
12012 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12013 (if (and prop (stringp prop) (string-match "\\S-" prop))
12014 (read prop)
12015 (symbol-value var))))
12016
12017 (defun org-entry-delete (pom property)
12018 "Delete the property PROPERTY from entry at point-or-marker POM."
12019 (org-with-point-at pom
12020 (if (member property org-special-properties)
12021 nil ; cannot delete these properties.
12022 (let ((range (org-get-property-block)))
12023 (if (and range
12024 (goto-char (car range))
12025 (re-search-forward
12026 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12027 (cdr range) t))
12028 (progn
12029 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12030 t)
12031 nil)))))
12032
12033 ;; Multi-values properties are properties that contain multiple values
12034 ;; These values are assumed to be single words, separated by whitespace.
12035 (defun org-entry-add-to-multivalued-property (pom property value)
12036 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12037 (let* ((old (org-entry-get pom property))
12038 (values (and old (org-split-string old "[ \t]"))))
12039 (setq value (org-entry-protect-space value))
12040 (unless (member value values)
12041 (setq values (cons value values))
12042 (org-entry-put pom property
12043 (mapconcat 'identity values " ")))))
12044
12045 (defun org-entry-remove-from-multivalued-property (pom property value)
12046 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12047 (let* ((old (org-entry-get pom property))
12048 (values (and old (org-split-string old "[ \t]"))))
12049 (setq value (org-entry-protect-space value))
12050 (when (member value values)
12051 (setq values (delete value values))
12052 (org-entry-put pom property
12053 (mapconcat 'identity values " ")))))
12054
12055 (defun org-entry-member-in-multivalued-property (pom property value)
12056 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12057 (let* ((old (org-entry-get pom property))
12058 (values (and old (org-split-string old "[ \t]"))))
12059 (setq value (org-entry-protect-space value))
12060 (member value values)))
12061
12062 (defun org-entry-get-multivalued-property (pom property)
12063 "Return a list of values in a multivalued property."
12064 (let* ((value (org-entry-get pom property))
12065 (values (and value (org-split-string value "[ \t]"))))
12066 (mapcar 'org-entry-restore-space values)))
12067
12068 (defun org-entry-put-multivalued-property (pom property &rest values)
12069 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12070 VALUES should be a list of strings. Spaces will be protected."
12071 (org-entry-put pom property
12072 (mapconcat 'org-entry-protect-space values " "))
12073 (let* ((value (org-entry-get pom property))
12074 (values (and value (org-split-string value "[ \t]"))))
12075 (mapcar 'org-entry-restore-space values)))
12076
12077 (defun org-entry-protect-space (s)
12078 "Protect spaces and newline in string S."
12079 (while (string-match " " s)
12080 (setq s (replace-match "%20" t t s)))
12081 (while (string-match "\n" s)
12082 (setq s (replace-match "%0A" t t s)))
12083 s)
12084
12085 (defun org-entry-restore-space (s)
12086 "Restore spaces and newline in string S."
12087 (while (string-match "%20" s)
12088 (setq s (replace-match " " t t s)))
12089 (while (string-match "%0A" s)
12090 (setq s (replace-match "\n" t t s)))
12091 s)
12092
12093 (defvar org-entry-property-inherited-from (make-marker)
12094 "Marker pointing to the entry from where a property was inherited.
12095 Each call to `org-entry-get-with-inheritance' will set this marker to the
12096 location of the entry where the inheritance search matched. If there was
12097 no match, the marker will point nowhere.
12098 Note that also `org-entry-get' calls this function, if the INHERIT flag
12099 is set.")
12100
12101 (defun org-entry-get-with-inheritance (property)
12102 "Get entry property, and search higher levels if not present."
12103 (move-marker org-entry-property-inherited-from nil)
12104 (let (tmp)
12105 (save-excursion
12106 (save-restriction
12107 (widen)
12108 (catch 'ex
12109 (while t
12110 (when (setq tmp (org-entry-get nil property))
12111 (org-back-to-heading t)
12112 (move-marker org-entry-property-inherited-from (point))
12113 (throw 'ex tmp))
12114 (or (org-up-heading-safe) (throw 'ex nil)))))
12115 (or tmp
12116 (cdr (assoc property org-file-properties))
12117 (cdr (assoc property org-global-properties))
12118 (cdr (assoc property org-global-properties-fixed))))))
12119
12120 (defun org-entry-put (pom property value)
12121 "Set PROPERTY to VALUE for entry at point-or-marker POM."
12122 (org-with-point-at pom
12123 (org-back-to-heading t)
12124 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
12125 range)
12126 (cond
12127 ((equal property "TODO")
12128 (when (and (stringp value) (string-match "\\S-" value)
12129 (not (member value org-todo-keywords-1)))
12130 (error "\"%s\" is not a valid TODO state" value))
12131 (if (or (not value)
12132 (not (string-match "\\S-" value)))
12133 (setq value 'none))
12134 (org-todo value)
12135 (org-set-tags nil 'align))
12136 ((equal property "PRIORITY")
12137 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
12138 (string-to-char value) ?\ ))
12139 (org-set-tags nil 'align))
12140 ((equal property "SCHEDULED")
12141 (if (re-search-forward org-scheduled-time-regexp end t)
12142 (cond
12143 ((eq value 'earlier) (org-timestamp-change -1 'day))
12144 ((eq value 'later) (org-timestamp-change 1 'day))
12145 (t (call-interactively 'org-schedule)))
12146 (call-interactively 'org-schedule)))
12147 ((equal property "DEADLINE")
12148 (if (re-search-forward org-deadline-time-regexp end t)
12149 (cond
12150 ((eq value 'earlier) (org-timestamp-change -1 'day))
12151 ((eq value 'later) (org-timestamp-change 1 'day))
12152 (t (call-interactively 'org-deadline)))
12153 (call-interactively 'org-deadline)))
12154 ((member property org-special-properties)
12155 (error "The %s property can not yet be set with `org-entry-put'"
12156 property))
12157 (t ; a non-special property
12158 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
12159 (setq range (org-get-property-block beg end 'force))
12160 (goto-char (car range))
12161 (if (re-search-forward
12162 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
12163 (progn
12164 (delete-region (match-beginning 1) (match-end 1))
12165 (goto-char (match-beginning 1)))
12166 (goto-char (cdr range))
12167 (insert "\n")
12168 (backward-char 1)
12169 (org-indent-line-function)
12170 (insert ":" property ":"))
12171 (and value (insert " " value))
12172 (org-indent-line-function)))))))
12173
12174 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
12175 "Get all property keys in the current buffer.
12176 With INCLUDE-SPECIALS, also list the special properties that reflect things
12177 like tags and TODO state.
12178 With INCLUDE-DEFAULTS, also include properties that has special meaning
12179 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
12180 With INCLUDE-COLUMNS, also include property names given in COLUMN
12181 formats in the current buffer."
12182 (let (rtn range cfmt s p)
12183 (save-excursion
12184 (save-restriction
12185 (widen)
12186 (goto-char (point-min))
12187 (while (re-search-forward org-property-start-re nil t)
12188 (setq range (org-get-property-block))
12189 (goto-char (car range))
12190 (while (re-search-forward
12191 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
12192 (cdr range) t)
12193 (add-to-list 'rtn (org-match-string-no-properties 1)))
12194 (outline-next-heading))))
12195
12196 (when include-specials
12197 (setq rtn (append org-special-properties rtn)))
12198
12199 (when include-defaults
12200 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
12201 (add-to-list 'rtn org-effort-property))
12202
12203 (when include-columns
12204 (save-excursion
12205 (save-restriction
12206 (widen)
12207 (goto-char (point-min))
12208 (while (re-search-forward
12209 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
12210 nil t)
12211 (setq cfmt (match-string 2) s 0)
12212 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
12213 cfmt s)
12214 (setq s (match-end 0)
12215 p (match-string 1 cfmt))
12216 (unless (or (equal p "ITEM")
12217 (member p org-special-properties))
12218 (add-to-list 'rtn (match-string 1 cfmt))))))))
12219
12220 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
12221
12222 (defun org-property-values (key)
12223 "Return a list of all values of property KEY."
12224 (save-excursion
12225 (save-restriction
12226 (widen)
12227 (goto-char (point-min))
12228 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
12229 values)
12230 (while (re-search-forward re nil t)
12231 (add-to-list 'values (org-trim (match-string 1))))
12232 (delete "" values)))))
12233
12234 (defun org-insert-property-drawer ()
12235 "Insert a property drawer into the current entry."
12236 (interactive)
12237 (org-back-to-heading t)
12238 (looking-at outline-regexp)
12239 (let ((indent (if org-adapt-indentation
12240 (- (match-end 0)(match-beginning 0))
12241 0))
12242 (beg (point))
12243 (re (concat "^[ \t]*" org-keyword-time-regexp))
12244 end hiddenp)
12245 (outline-next-heading)
12246 (setq end (point))
12247 (goto-char beg)
12248 (while (re-search-forward re end t))
12249 (setq hiddenp (org-invisible-p))
12250 (end-of-line 1)
12251 (and (equal (char-after) ?\n) (forward-char 1))
12252 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
12253 (if (member (match-string 1) '("CLOCK:" ":END:"))
12254 ;; just skip this line
12255 (beginning-of-line 2)
12256 ;; Drawer start, find the end
12257 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
12258 (beginning-of-line 1)))
12259 (org-skip-over-state-notes)
12260 (skip-chars-backward " \t\n\r")
12261 (if (eq (char-before) ?*) (forward-char 1))
12262 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
12263 (beginning-of-line 0)
12264 (org-indent-to-column indent)
12265 (beginning-of-line 2)
12266 (org-indent-to-column indent)
12267 (beginning-of-line 0)
12268 (if hiddenp
12269 (save-excursion
12270 (org-back-to-heading t)
12271 (hide-entry))
12272 (org-flag-drawer t))))
12273
12274 (defun org-set-property (property value)
12275 "In the current entry, set PROPERTY to VALUE.
12276 When called interactively, this will prompt for a property name, offering
12277 completion on existing and default properties. And then it will prompt
12278 for a value, offering completion either on allowed values (via an inherited
12279 xxx_ALL property) or on existing values in other instances of this property
12280 in the current file."
12281 (interactive
12282 (let* ((completion-ignore-case t)
12283 (keys (org-buffer-property-keys nil t t))
12284 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
12285 (prop (if (member prop0 keys)
12286 prop0
12287 (or (cdr (assoc (downcase prop0)
12288 (mapcar (lambda (x) (cons (downcase x) x))
12289 keys)))
12290 prop0)))
12291 (cur (org-entry-get nil prop))
12292 (allowed (org-property-get-allowed-values nil prop 'table))
12293 (existing (mapcar 'list (org-property-values prop)))
12294 (val (if allowed
12295 (org-completing-read "Value: " allowed nil 'req-match)
12296 (let (org-completion-use-ido org-completion-use-iswitchb)
12297 (org-completing-read
12298 (concat "Value " (if (and cur (string-match "\\S-" cur))
12299 (concat "[" cur "]") "")
12300 ": ")
12301 existing nil nil "" nil cur)))))
12302 (list prop (if (equal val "") cur val))))
12303 (unless (equal (org-entry-get nil property) value)
12304 (org-entry-put nil property value)))
12305
12306 (defun org-delete-property (property)
12307 "In the current entry, delete PROPERTY."
12308 (interactive
12309 (let* ((completion-ignore-case t)
12310 (prop (org-icompleting-read
12311 "Property: " (org-entry-properties nil 'standard))))
12312 (list prop)))
12313 (message "Property %s %s" property
12314 (if (org-entry-delete nil property)
12315 "deleted"
12316 "was not present in the entry")))
12317
12318 (defun org-delete-property-globally (property)
12319 "Remove PROPERTY globally, from all entries."
12320 (interactive
12321 (let* ((completion-ignore-case t)
12322 (prop (org-icompleting-read
12323 "Globally remove property: "
12324 (mapcar 'list (org-buffer-property-keys)))))
12325 (list prop)))
12326 (save-excursion
12327 (save-restriction
12328 (widen)
12329 (goto-char (point-min))
12330 (let ((cnt 0))
12331 (while (re-search-forward
12332 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12333 nil t)
12334 (setq cnt (1+ cnt))
12335 (replace-match ""))
12336 (message "Property \"%s\" removed from %d entries" property cnt)))))
12337
12338 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12339
12340 (defun org-compute-property-at-point ()
12341 "Compute the property at point.
12342 This looks for an enclosing column format, extracts the operator and
12343 then applies it to the property in the column format's scope."
12344 (interactive)
12345 (unless (org-at-property-p)
12346 (error "Not at a property"))
12347 (let ((prop (org-match-string-no-properties 2)))
12348 (org-columns-get-format-and-top-level)
12349 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12350 (error "No operator defined for property %s" prop))
12351 (org-columns-compute prop)))
12352
12353 (defun org-property-get-allowed-values (pom property &optional table)
12354 "Get allowed values for the property PROPERTY.
12355 When TABLE is non-nil, return an alist that can directly be used for
12356 completion."
12357 (let (vals)
12358 (cond
12359 ((equal property "TODO")
12360 (setq vals (org-with-point-at pom
12361 (append org-todo-keywords-1 '("")))))
12362 ((equal property "PRIORITY")
12363 (let ((n org-lowest-priority))
12364 (while (>= n org-highest-priority)
12365 (push (char-to-string n) vals)
12366 (setq n (1- n)))))
12367 ((member property org-special-properties))
12368 (t
12369 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12370
12371 (when (and vals (string-match "\\S-" vals))
12372 (setq vals (car (read-from-string (concat "(" vals ")"))))
12373 (setq vals (mapcar (lambda (x)
12374 (cond ((stringp x) x)
12375 ((numberp x) (number-to-string x))
12376 ((symbolp x) (symbol-name x))
12377 (t "???")))
12378 vals)))))
12379 (if table (mapcar 'list vals) vals)))
12380
12381 (defun org-property-previous-allowed-value (&optional previous)
12382 "Switch to the next allowed value for this property."
12383 (interactive)
12384 (org-property-next-allowed-value t))
12385
12386 (defun org-property-next-allowed-value (&optional previous)
12387 "Switch to the next allowed value for this property."
12388 (interactive)
12389 (unless (org-at-property-p)
12390 (error "Not at a property"))
12391 (let* ((key (match-string 2))
12392 (value (match-string 3))
12393 (allowed (or (org-property-get-allowed-values (point) key)
12394 (and (member value '("[ ]" "[-]" "[X]"))
12395 '("[ ]" "[X]"))))
12396 nval)
12397 (unless allowed
12398 (error "Allowed values for this property have not been defined"))
12399 (if previous (setq allowed (reverse allowed)))
12400 (if (member value allowed)
12401 (setq nval (car (cdr (member value allowed)))))
12402 (setq nval (or nval (car allowed)))
12403 (if (equal nval value)
12404 (error "Only one allowed value for this property"))
12405 (org-at-property-p)
12406 (replace-match (concat " :" key ": " nval) t t)
12407 (org-indent-line-function)
12408 (beginning-of-line 1)
12409 (skip-chars-forward " \t")))
12410
12411 (defun org-find-entry-with-id (ident)
12412 "Locate the entry that contains the ID property with exact value IDENT.
12413 IDENT can be a string, a symbol or a number, this function will search for
12414 the string representation of it.
12415 Return the position where this entry starts, or nil if there is no such entry."
12416 (interactive "sID: ")
12417 (let ((id (cond
12418 ((stringp ident) ident)
12419 ((symbol-name ident) (symbol-name ident))
12420 ((numberp ident) (number-to-string ident))
12421 (t (error "IDENT %s must be a string, symbol or number" ident))))
12422 (case-fold-search nil))
12423 (save-excursion
12424 (save-restriction
12425 (widen)
12426 (goto-char (point-min))
12427 (when (re-search-forward
12428 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12429 nil t)
12430 (org-back-to-heading t)
12431 (point))))))
12432
12433 ;;;; Timestamps
12434
12435 (defvar org-last-changed-timestamp nil)
12436 (defvar org-last-inserted-timestamp nil
12437 "The last time stamp inserted with `org-insert-time-stamp'.")
12438 (defvar org-time-was-given) ; dynamically scoped parameter
12439 (defvar org-end-time-was-given) ; dynamically scoped parameter
12440 (defvar org-ts-what) ; dynamically scoped parameter
12441
12442 (defun org-time-stamp (arg &optional inactive)
12443 "Prompt for a date/time and insert a time stamp.
12444 If the user specifies a time like HH:MM, or if this command is called
12445 with a prefix argument, the time stamp will contain date and time.
12446 Otherwise, only the date will be included. All parts of a date not
12447 specified by the user will be filled in from the current date/time.
12448 So if you press just return without typing anything, the time stamp
12449 will represent the current date/time. If there is already a timestamp
12450 at the cursor, it will be modified."
12451 (interactive "P")
12452 (let* ((ts nil)
12453 (default-time
12454 ;; Default time is either today, or, when entering a range,
12455 ;; the range start.
12456 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12457 (save-excursion
12458 (re-search-backward
12459 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12460 (- (point) 20) t)))
12461 (apply 'encode-time (org-parse-time-string (match-string 1)))
12462 (current-time)))
12463 (default-input (and ts (org-get-compact-tod ts)))
12464 org-time-was-given org-end-time-was-given time)
12465 (cond
12466 ((and (org-at-timestamp-p t)
12467 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12468 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12469 (insert "--")
12470 (setq time (let ((this-command this-command))
12471 (org-read-date arg 'totime nil nil
12472 default-time default-input)))
12473 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12474 ((org-at-timestamp-p t)
12475 (setq time (let ((this-command this-command))
12476 (org-read-date arg 'totime nil nil default-time default-input)))
12477 (when (org-at-timestamp-p t) ; just to get the match data
12478 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12479 (replace-match "")
12480 (setq org-last-changed-timestamp
12481 (org-insert-time-stamp
12482 time (or org-time-was-given arg)
12483 inactive nil nil (list org-end-time-was-given))))
12484 (message "Timestamp updated"))
12485 (t
12486 (setq time (let ((this-command this-command))
12487 (org-read-date arg 'totime nil nil default-time default-input)))
12488 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12489 nil nil (list org-end-time-was-given))))))
12490
12491 ;; FIXME: can we use this for something else, like computing time differences?
12492 (defun org-get-compact-tod (s)
12493 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12494 (let* ((t1 (match-string 1 s))
12495 (h1 (string-to-number (match-string 2 s)))
12496 (m1 (string-to-number (match-string 3 s)))
12497 (t2 (and (match-end 4) (match-string 5 s)))
12498 (h2 (and t2 (string-to-number (match-string 6 s))))
12499 (m2 (and t2 (string-to-number (match-string 7 s))))
12500 dh dm)
12501 (if (not t2)
12502 t1
12503 (setq dh (- h2 h1) dm (- m2 m1))
12504 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12505 (concat t1 "+" (number-to-string dh)
12506 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12507
12508 (defun org-time-stamp-inactive (&optional arg)
12509 "Insert an inactive time stamp.
12510 An inactive time stamp is enclosed in square brackets instead of angle
12511 brackets. It is inactive in the sense that it does not trigger agenda entries,
12512 does not link to the calendar and cannot be changed with the S-cursor keys.
12513 So these are more for recording a certain time/date."
12514 (interactive "P")
12515 (org-time-stamp arg 'inactive))
12516
12517 (defvar org-date-ovl (org-make-overlay 1 1))
12518 (org-overlay-put org-date-ovl 'face 'org-warning)
12519 (org-detach-overlay org-date-ovl)
12520
12521 (defvar org-ans1) ; dynamically scoped parameter
12522 (defvar org-ans2) ; dynamically scoped parameter
12523
12524 (defvar org-plain-time-of-day-regexp) ; defined below
12525
12526 (defvar org-overriding-default-time nil) ; dynamically scoped
12527 (defvar org-read-date-overlay nil)
12528 (defvar org-dcst nil) ; dynamically scoped
12529 (defvar org-read-date-history nil)
12530 (defvar org-read-date-final-answer nil)
12531
12532 (defun org-read-date (&optional with-time to-time from-string prompt
12533 default-time default-input)
12534 "Read a date, possibly a time, and make things smooth for the user.
12535 The prompt will suggest to enter an ISO date, but you can also enter anything
12536 which will at least partially be understood by `parse-time-string'.
12537 Unrecognized parts of the date will default to the current day, month, year,
12538 hour and minute. If this command is called to replace a timestamp at point,
12539 of to enter the second timestamp of a range, the default time is taken from the
12540 existing stamp. For example,
12541 3-2-5 --> 2003-02-05
12542 feb 15 --> currentyear-02-15
12543 sep 12 9 --> 2009-09-12
12544 12:45 --> today 12:45
12545 22 sept 0:34 --> currentyear-09-22 0:34
12546 12 --> currentyear-currentmonth-12
12547 Fri --> nearest Friday (today or later)
12548 etc.
12549
12550 Furthermore you can specify a relative date by giving, as the *first* thing
12551 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12552 change in days weeks, months, years.
12553 With a single plus or minus, the date is relative to today. With a double
12554 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12555 +4d --> four days from today
12556 +4 --> same as above
12557 +2w --> two weeks from today
12558 ++5 --> five days from default date
12559
12560 The function understands only English month and weekday abbreviations,
12561 but this can be configured with the variables `parse-time-months' and
12562 `parse-time-weekdays'.
12563
12564 While prompting, a calendar is popped up - you can also select the
12565 date with the mouse (button 1). The calendar shows a period of three
12566 months. To scroll it to other months, use the keys `>' and `<'.
12567 If you don't like the calendar, turn it off with
12568 \(setq org-read-date-popup-calendar nil)
12569
12570 With optional argument TO-TIME, the date will immediately be converted
12571 to an internal time.
12572 With an optional argument WITH-TIME, the prompt will suggest to also
12573 insert a time. Note that when WITH-TIME is not set, you can still
12574 enter a time, and this function will inform the calling routine about
12575 this change. The calling routine may then choose to change the format
12576 used to insert the time stamp into the buffer to include the time.
12577 With optional argument FROM-STRING, read from this string instead from
12578 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12579 the time/date that is used for everything that is not specified by the
12580 user."
12581 (require 'parse-time)
12582 (let* ((org-time-stamp-rounding-minutes
12583 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12584 (org-dcst org-display-custom-times)
12585 (ct (org-current-time))
12586 (def (or org-overriding-default-time default-time ct))
12587 (defdecode (decode-time def))
12588 (dummy (progn
12589 (when (< (nth 2 defdecode) org-extend-today-until)
12590 (setcar (nthcdr 2 defdecode) -1)
12591 (setcar (nthcdr 1 defdecode) 59)
12592 (setq def (apply 'encode-time defdecode)
12593 defdecode (decode-time def)))))
12594 (calendar-frame-setup nil)
12595 (calendar-move-hook nil)
12596 (calendar-view-diary-initially-flag nil)
12597 (view-diary-entries-initially nil)
12598 (calendar-view-holidays-initially-flag nil)
12599 (view-calendar-holidays-initially nil)
12600 (timestr (format-time-string
12601 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12602 (prompt (concat (if prompt (concat prompt " ") "")
12603 (format "Date+time [%s]: " timestr)))
12604 ans (org-ans0 "") org-ans1 org-ans2 final)
12605
12606 (cond
12607 (from-string (setq ans from-string))
12608 (org-read-date-popup-calendar
12609 (save-excursion
12610 (save-window-excursion
12611 (calendar)
12612 (calendar-forward-day (- (time-to-days def)
12613 (calendar-absolute-from-gregorian
12614 (calendar-current-date))))
12615 (org-eval-in-calendar nil t)
12616 (let* ((old-map (current-local-map))
12617 (map (copy-keymap calendar-mode-map))
12618 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12619 (org-defkey map (kbd "RET") 'org-calendar-select)
12620 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12621 'org-calendar-select-mouse)
12622 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12623 'org-calendar-select-mouse)
12624 (org-defkey minibuffer-local-map [(meta shift left)]
12625 (lambda () (interactive)
12626 (org-eval-in-calendar '(calendar-backward-month 1))))
12627 (org-defkey minibuffer-local-map [(meta shift right)]
12628 (lambda () (interactive)
12629 (org-eval-in-calendar '(calendar-forward-month 1))))
12630 (org-defkey minibuffer-local-map [(meta shift up)]
12631 (lambda () (interactive)
12632 (org-eval-in-calendar '(calendar-backward-year 1))))
12633 (org-defkey minibuffer-local-map [(meta shift down)]
12634 (lambda () (interactive)
12635 (org-eval-in-calendar '(calendar-forward-year 1))))
12636 (org-defkey minibuffer-local-map [?\e (shift left)]
12637 (lambda () (interactive)
12638 (org-eval-in-calendar '(calendar-backward-month 1))))
12639 (org-defkey minibuffer-local-map [?\e (shift right)]
12640 (lambda () (interactive)
12641 (org-eval-in-calendar '(calendar-forward-month 1))))
12642 (org-defkey minibuffer-local-map [?\e (shift up)]
12643 (lambda () (interactive)
12644 (org-eval-in-calendar '(calendar-backward-year 1))))
12645 (org-defkey minibuffer-local-map [?\e (shift down)]
12646 (lambda () (interactive)
12647 (org-eval-in-calendar '(calendar-forward-year 1))))
12648 (org-defkey minibuffer-local-map [(shift up)]
12649 (lambda () (interactive)
12650 (org-eval-in-calendar '(calendar-backward-week 1))))
12651 (org-defkey minibuffer-local-map [(shift down)]
12652 (lambda () (interactive)
12653 (org-eval-in-calendar '(calendar-forward-week 1))))
12654 (org-defkey minibuffer-local-map [(shift left)]
12655 (lambda () (interactive)
12656 (org-eval-in-calendar '(calendar-backward-day 1))))
12657 (org-defkey minibuffer-local-map [(shift right)]
12658 (lambda () (interactive)
12659 (org-eval-in-calendar '(calendar-forward-day 1))))
12660 (org-defkey minibuffer-local-map ">"
12661 (lambda () (interactive)
12662 (org-eval-in-calendar '(scroll-calendar-left 1))))
12663 (org-defkey minibuffer-local-map "<"
12664 (lambda () (interactive)
12665 (org-eval-in-calendar '(scroll-calendar-right 1))))
12666 (run-hooks 'org-read-date-minibuffer-setup-hook)
12667 (unwind-protect
12668 (progn
12669 (use-local-map map)
12670 (add-hook 'post-command-hook 'org-read-date-display)
12671 (setq org-ans0 (read-string prompt default-input
12672 'org-read-date-history nil))
12673 ;; org-ans0: from prompt
12674 ;; org-ans1: from mouse click
12675 ;; org-ans2: from calendar motion
12676 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12677 (remove-hook 'post-command-hook 'org-read-date-display)
12678 (use-local-map old-map)
12679 (when org-read-date-overlay
12680 (org-delete-overlay org-read-date-overlay)
12681 (setq org-read-date-overlay nil)))))))
12682
12683 (t ; Naked prompt only
12684 (unwind-protect
12685 (setq ans (read-string prompt default-input
12686 'org-read-date-history timestr))
12687 (when org-read-date-overlay
12688 (org-delete-overlay org-read-date-overlay)
12689 (setq org-read-date-overlay nil)))))
12690
12691 (setq final (org-read-date-analyze ans def defdecode))
12692 (setq org-read-date-final-answer ans)
12693
12694 (if to-time
12695 (apply 'encode-time final)
12696 (if (and (boundp 'org-time-was-given) org-time-was-given)
12697 (format "%04d-%02d-%02d %02d:%02d"
12698 (nth 5 final) (nth 4 final) (nth 3 final)
12699 (nth 2 final) (nth 1 final))
12700 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12701
12702 (defvar def)
12703 (defvar defdecode)
12704 (defvar with-time)
12705 (defun org-read-date-display ()
12706 "Display the current date prompt interpretation in the minibuffer."
12707 (when org-read-date-display-live
12708 (when org-read-date-overlay
12709 (org-delete-overlay org-read-date-overlay))
12710 (let ((p (point)))
12711 (end-of-line 1)
12712 (while (not (equal (buffer-substring
12713 (max (point-min) (- (point) 4)) (point))
12714 " "))
12715 (insert " "))
12716 (goto-char p))
12717 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12718 " " (or org-ans1 org-ans2)))
12719 (org-end-time-was-given nil)
12720 (f (org-read-date-analyze ans def defdecode))
12721 (fmts (if org-dcst
12722 org-time-stamp-custom-formats
12723 org-time-stamp-formats))
12724 (fmt (if (or with-time
12725 (and (boundp 'org-time-was-given) org-time-was-given))
12726 (cdr fmts)
12727 (car fmts)))
12728 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12729 (when (and org-end-time-was-given
12730 (string-match org-plain-time-of-day-regexp txt))
12731 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12732 org-end-time-was-given
12733 (substring txt (match-end 0)))))
12734 (setq org-read-date-overlay
12735 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12736 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12737
12738 (defun org-read-date-analyze (ans def defdecode)
12739 "Analyse the combined answer of the date prompt."
12740 ;; FIXME: cleanup and comment
12741 (let (delta deltan deltaw deltadef year month day
12742 hour minute second wday pm h2 m2 tl wday1
12743 iso-year iso-weekday iso-week iso-year iso-date)
12744
12745 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12746 (setq ans "+0"))
12747
12748 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12749 (setq ans (replace-match "" t t ans)
12750 deltan (car delta)
12751 deltaw (nth 1 delta)
12752 deltadef (nth 2 delta)))
12753
12754 ;; Check if there is an iso week date in there
12755 ;; If yes, sore the info and postpone interpreting it until the rest
12756 ;; of the parsing is done
12757 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12758 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12759 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12760 iso-week (string-to-number (match-string 2 ans)))
12761 (setq ans (replace-match "" t t ans)))
12762
12763 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12764 (when (string-match
12765 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12766 (setq year (if (match-end 2)
12767 (string-to-number (match-string 2 ans))
12768 (string-to-number (format-time-string "%Y")))
12769 month (string-to-number (match-string 3 ans))
12770 day (string-to-number (match-string 4 ans)))
12771 (if (< year 100) (setq year (+ 2000 year)))
12772 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12773 t nil ans)))
12774 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12775 ;; If there is a time with am/pm, and *no* time without it, we convert
12776 ;; so that matching will be successful.
12777 (loop for i from 1 to 2 do ; twice, for end time as well
12778 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12779 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12780 (setq hour (string-to-number (match-string 1 ans))
12781 minute (if (match-end 3)
12782 (string-to-number (match-string 3 ans))
12783 0)
12784 pm (equal ?p
12785 (string-to-char (downcase (match-string 4 ans)))))
12786 (if (and (= hour 12) (not pm))
12787 (setq hour 0)
12788 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12789 (setq ans (replace-match (format "%02d:%02d" hour minute)
12790 t t ans))))
12791
12792 ;; Check if a time range is given as a duration
12793 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12794 (setq hour (string-to-number (match-string 1 ans))
12795 h2 (+ hour (string-to-number (match-string 3 ans)))
12796 minute (string-to-number (match-string 2 ans))
12797 m2 (+ minute (if (match-end 5) (string-to-number
12798 (match-string 5 ans))0)))
12799 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12800 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12801 t t ans)))
12802
12803 ;; Check if there is a time range
12804 (when (boundp 'org-end-time-was-given)
12805 (setq org-time-was-given nil)
12806 (when (and (string-match org-plain-time-of-day-regexp ans)
12807 (match-end 8))
12808 (setq org-end-time-was-given (match-string 8 ans))
12809 (setq ans (concat (substring ans 0 (match-beginning 7))
12810 (substring ans (match-end 7))))))
12811
12812 (setq tl (parse-time-string ans)
12813 day (or (nth 3 tl) (nth 3 defdecode))
12814 month (or (nth 4 tl)
12815 (if (and org-read-date-prefer-future
12816 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12817 (1+ (nth 4 defdecode))
12818 (nth 4 defdecode)))
12819 year (or (nth 5 tl)
12820 (if (and org-read-date-prefer-future
12821 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12822 (1+ (nth 5 defdecode))
12823 (nth 5 defdecode)))
12824 hour (or (nth 2 tl) (nth 2 defdecode))
12825 minute (or (nth 1 tl) (nth 1 defdecode))
12826 second (or (nth 0 tl) 0)
12827 wday (nth 6 tl))
12828
12829 ;; Special date definitions below
12830 (cond
12831 (iso-week
12832 ;; There was an iso week
12833 (setq year (or iso-year year)
12834 day (or iso-weekday wday 1)
12835 wday nil ; to make sure that the trigger below does not match
12836 iso-date (calendar-gregorian-from-absolute
12837 (calendar-absolute-from-iso
12838 (list iso-week day year))))
12839 ; FIXME: Should we also push ISO weeks into the future?
12840 ; (when (and org-read-date-prefer-future
12841 ; (not iso-year)
12842 ; (< (calendar-absolute-from-gregorian iso-date)
12843 ; (time-to-days (current-time))))
12844 ; (setq year (1+ year)
12845 ; iso-date (calendar-gregorian-from-absolute
12846 ; (calendar-absolute-from-iso
12847 ; (list iso-week day year)))))
12848 (setq month (car iso-date)
12849 year (nth 2 iso-date)
12850 day (nth 1 iso-date)))
12851 (deltan
12852 (unless deltadef
12853 (let ((now (decode-time (current-time))))
12854 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12855 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12856 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12857 ((equal deltaw "m") (setq month (+ month deltan)))
12858 ((equal deltaw "y") (setq year (+ year deltan)))))
12859 ((and wday (not (nth 3 tl)))
12860 ;; Weekday was given, but no day, so pick that day in the week
12861 ;; on or after the derived date.
12862 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12863 (unless (equal wday wday1)
12864 (setq day (+ day (% (- wday wday1 -7) 7))))))
12865 (if (and (boundp 'org-time-was-given)
12866 (nth 2 tl))
12867 (setq org-time-was-given t))
12868 (if (< year 100) (setq year (+ 2000 year)))
12869 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12870 (list second minute hour day month year)))
12871
12872 (defvar parse-time-weekdays)
12873
12874 (defun org-read-date-get-relative (s today default)
12875 "Check string S for special relative date string.
12876 TODAY and DEFAULT are internal times, for today and for a default.
12877 Return shift list (N what def-flag)
12878 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12879 N is the number of WHATs to shift.
12880 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12881 the DEFAULT date rather than TODAY."
12882 (when (and
12883 (string-match
12884 (concat
12885 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12886 "\\([0-9]+\\)?"
12887 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12888 "\\([ \t]\\|$\\)") s)
12889 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12890 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12891 (string-to-char (substring (match-string 1 s) -1))
12892 ?+))
12893 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12894 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12895 (what (if (match-end 3) (match-string 3 s) "d"))
12896 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12897 (date (if rel default today))
12898 (wday (nth 6 (decode-time date)))
12899 delta)
12900 (if wday1
12901 (progn
12902 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12903 (if (= dir ?-) (setq delta (- delta 7)))
12904 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12905 (list delta "d" rel))
12906 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12907
12908 (defun org-eval-in-calendar (form &optional keepdate)
12909 "Eval FORM in the calendar window and return to current window.
12910 Also, store the cursor date in variable org-ans2."
12911 (let ((sf (selected-frame))
12912 (sw (selected-window)))
12913 (select-window (get-buffer-window "*Calendar*" t))
12914 (eval form)
12915 (when (and (not keepdate) (calendar-cursor-to-date))
12916 (let* ((date (calendar-cursor-to-date))
12917 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12918 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12919 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12920 (select-window sw)
12921 (org-select-frame-set-input-focus sf)))
12922
12923 (defun org-calendar-select ()
12924 "Return to `org-read-date' with the date currently selected.
12925 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12926 (interactive)
12927 (when (calendar-cursor-to-date)
12928 (let* ((date (calendar-cursor-to-date))
12929 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12930 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12931 (if (active-minibuffer-window) (exit-minibuffer))))
12932
12933 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12934 "Insert a date stamp for the date given by the internal TIME.
12935 WITH-HM means, use the stamp format that includes the time of the day.
12936 INACTIVE means use square brackets instead of angular ones, so that the
12937 stamp will not contribute to the agenda.
12938 PRE and POST are optional strings to be inserted before and after the
12939 stamp.
12940 The command returns the inserted time stamp."
12941 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12942 stamp)
12943 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12944 (insert-before-markers (or pre ""))
12945 (insert-before-markers (setq stamp (format-time-string fmt time)))
12946 (when (listp extra)
12947 (setq extra (car extra))
12948 (if (and (stringp extra)
12949 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12950 (setq extra (format "-%02d:%02d"
12951 (string-to-number (match-string 1 extra))
12952 (string-to-number (match-string 2 extra))))
12953 (setq extra nil)))
12954 (when extra
12955 (backward-char 1)
12956 (insert-before-markers extra)
12957 (forward-char 1))
12958 (insert-before-markers (or post ""))
12959 (setq org-last-inserted-timestamp stamp)))
12960
12961 (defun org-toggle-time-stamp-overlays ()
12962 "Toggle the use of custom time stamp formats."
12963 (interactive)
12964 (setq org-display-custom-times (not org-display-custom-times))
12965 (unless org-display-custom-times
12966 (let ((p (point-min)) (bmp (buffer-modified-p)))
12967 (while (setq p (next-single-property-change p 'display))
12968 (if (and (get-text-property p 'display)
12969 (eq (get-text-property p 'face) 'org-date))
12970 (remove-text-properties
12971 p (setq p (next-single-property-change p 'display))
12972 '(display t))))
12973 (set-buffer-modified-p bmp)))
12974 (if (featurep 'xemacs)
12975 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12976 (org-restart-font-lock)
12977 (setq org-table-may-need-update t)
12978 (if org-display-custom-times
12979 (message "Time stamps are overlayed with custom format")
12980 (message "Time stamp overlays removed")))
12981
12982 (defun org-display-custom-time (beg end)
12983 "Overlay modified time stamp format over timestamp between BEG and END."
12984 (let* ((ts (buffer-substring beg end))
12985 t1 w1 with-hm tf time str w2 (off 0))
12986 (save-match-data
12987 (setq t1 (org-parse-time-string ts t))
12988 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12989 (setq off (- (match-end 0) (match-beginning 0)))))
12990 (setq end (- end off))
12991 (setq w1 (- end beg)
12992 with-hm (and (nth 1 t1) (nth 2 t1))
12993 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12994 time (org-fix-decoded-time t1)
12995 str (org-add-props
12996 (format-time-string
12997 (substring tf 1 -1) (apply 'encode-time time))
12998 nil 'mouse-face 'highlight)
12999 w2 (length str))
13000 (if (not (= w2 w1))
13001 (add-text-properties (1+ beg) (+ 2 beg)
13002 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13003 (if (featurep 'xemacs)
13004 (progn
13005 (put-text-property beg end 'invisible t)
13006 (put-text-property beg end 'end-glyph (make-glyph str)))
13007 (put-text-property beg end 'display str))))
13008
13009 (defun org-translate-time (string)
13010 "Translate all timestamps in STRING to custom format.
13011 But do this only if the variable `org-display-custom-times' is set."
13012 (when org-display-custom-times
13013 (save-match-data
13014 (let* ((start 0)
13015 (re org-ts-regexp-both)
13016 t1 with-hm inactive tf time str beg end)
13017 (while (setq start (string-match re string start))
13018 (setq beg (match-beginning 0)
13019 end (match-end 0)
13020 t1 (save-match-data
13021 (org-parse-time-string (substring string beg end) t))
13022 with-hm (and (nth 1 t1) (nth 2 t1))
13023 inactive (equal (substring string beg (1+ beg)) "[")
13024 tf (funcall (if with-hm 'cdr 'car)
13025 org-time-stamp-custom-formats)
13026 time (org-fix-decoded-time t1)
13027 str (format-time-string
13028 (concat
13029 (if inactive "[" "<") (substring tf 1 -1)
13030 (if inactive "]" ">"))
13031 (apply 'encode-time time))
13032 string (replace-match str t t string)
13033 start (+ start (length str)))))))
13034 string)
13035
13036 (defun org-fix-decoded-time (time)
13037 "Set 0 instead of nil for the first 6 elements of time.
13038 Don't touch the rest."
13039 (let ((n 0))
13040 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
13041
13042 (defun org-days-to-time (timestamp-string)
13043 "Difference between TIMESTAMP-STRING and now in days."
13044 (- (time-to-days (org-time-string-to-time timestamp-string))
13045 (time-to-days (current-time))))
13046
13047 (defun org-deadline-close (timestamp-string &optional ndays)
13048 "Is the time in TIMESTAMP-STRING close to the current date?"
13049 (setq ndays (or ndays (org-get-wdays timestamp-string)))
13050 (and (< (org-days-to-time timestamp-string) ndays)
13051 (not (org-entry-is-done-p))))
13052
13053 (defun org-get-wdays (ts)
13054 "Get the deadline lead time appropriate for timestring TS."
13055 (cond
13056 ((<= org-deadline-warning-days 0)
13057 ;; 0 or negative, enforce this value no matter what
13058 (- org-deadline-warning-days))
13059 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
13060 ;; lead time is specified.
13061 (floor (* (string-to-number (match-string 1 ts))
13062 (cdr (assoc (match-string 2 ts)
13063 '(("d" . 1) ("w" . 7)
13064 ("m" . 30.4) ("y" . 365.25)))))))
13065 ;; go for the default.
13066 (t org-deadline-warning-days)))
13067
13068 (defun org-calendar-select-mouse (ev)
13069 "Return to `org-read-date' with the date currently selected.
13070 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13071 (interactive "e")
13072 (mouse-set-point ev)
13073 (when (calendar-cursor-to-date)
13074 (let* ((date (calendar-cursor-to-date))
13075 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13076 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13077 (if (active-minibuffer-window) (exit-minibuffer))))
13078
13079 (defun org-check-deadlines (ndays)
13080 "Check if there are any deadlines due or past due.
13081 A deadline is considered due if it happens within `org-deadline-warning-days'
13082 days from today's date. If the deadline appears in an entry marked DONE,
13083 it is not shown. The prefix arg NDAYS can be used to test that many
13084 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
13085 (interactive "P")
13086 (let* ((org-warn-days
13087 (cond
13088 ((equal ndays '(4)) 100000)
13089 (ndays (prefix-numeric-value ndays))
13090 (t (abs org-deadline-warning-days))))
13091 (case-fold-search nil)
13092 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
13093 (callback
13094 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
13095
13096 (message "%d deadlines past-due or due within %d days"
13097 (org-occur regexp nil callback)
13098 org-warn-days)))
13099
13100 (defun org-check-before-date (date)
13101 "Check if there are deadlines or scheduled entries before DATE."
13102 (interactive (list (org-read-date)))
13103 (let ((case-fold-search nil)
13104 (regexp (concat "\\<\\(" org-deadline-string
13105 "\\|" org-scheduled-string
13106 "\\) *<\\([^>]+\\)>"))
13107 (callback
13108 (lambda () (time-less-p
13109 (org-time-string-to-time (match-string 2))
13110 (org-time-string-to-time date)))))
13111 (message "%d entries before %s"
13112 (org-occur regexp nil callback) date)))
13113
13114 (defun org-check-after-date (date)
13115 "Check if there are deadlines or scheduled entries after DATE."
13116 (interactive (list (org-read-date)))
13117 (let ((case-fold-search nil)
13118 (regexp (concat "\\<\\(" org-deadline-string
13119 "\\|" org-scheduled-string
13120 "\\) *<\\([^>]+\\)>"))
13121 (callback
13122 (lambda () (not
13123 (time-less-p
13124 (org-time-string-to-time (match-string 2))
13125 (org-time-string-to-time date))))))
13126 (message "%d entries after %s"
13127 (org-occur regexp nil callback) date)))
13128
13129 (defun org-evaluate-time-range (&optional to-buffer)
13130 "Evaluate a time range by computing the difference between start and end.
13131 Normally the result is just printed in the echo area, but with prefix arg
13132 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
13133 If the time range is actually in a table, the result is inserted into the
13134 next column.
13135 For time difference computation, a year is assumed to be exactly 365
13136 days in order to avoid rounding problems."
13137 (interactive "P")
13138 (or
13139 (org-clock-update-time-maybe)
13140 (save-excursion
13141 (unless (org-at-date-range-p t)
13142 (goto-char (point-at-bol))
13143 (re-search-forward org-tr-regexp-both (point-at-eol) t))
13144 (if (not (org-at-date-range-p t))
13145 (error "Not at a time-stamp range, and none found in current line")))
13146 (let* ((ts1 (match-string 1))
13147 (ts2 (match-string 2))
13148 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
13149 (match-end (match-end 0))
13150 (time1 (org-time-string-to-time ts1))
13151 (time2 (org-time-string-to-time ts2))
13152 (t1 (org-float-time time1))
13153 (t2 (org-float-time time2))
13154 (diff (abs (- t2 t1)))
13155 (negative (< (- t2 t1) 0))
13156 ;; (ys (floor (* 365 24 60 60)))
13157 (ds (* 24 60 60))
13158 (hs (* 60 60))
13159 (fy "%dy %dd %02d:%02d")
13160 (fy1 "%dy %dd")
13161 (fd "%dd %02d:%02d")
13162 (fd1 "%dd")
13163 (fh "%02d:%02d")
13164 y d h m align)
13165 (if havetime
13166 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13167 y 0
13168 d (floor (/ diff ds)) diff (mod diff ds)
13169 h (floor (/ diff hs)) diff (mod diff hs)
13170 m (floor (/ diff 60)))
13171 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
13172 y 0
13173 d (floor (+ (/ diff ds) 0.5))
13174 h 0 m 0))
13175 (if (not to-buffer)
13176 (message "%s" (org-make-tdiff-string y d h m))
13177 (if (org-at-table-p)
13178 (progn
13179 (goto-char match-end)
13180 (setq align t)
13181 (and (looking-at " *|") (goto-char (match-end 0))))
13182 (goto-char match-end))
13183 (if (looking-at
13184 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
13185 (replace-match ""))
13186 (if negative (insert " -"))
13187 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
13188 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
13189 (insert " " (format fh h m))))
13190 (if align (org-table-align))
13191 (message "Time difference inserted")))))
13192
13193 (defun org-make-tdiff-string (y d h m)
13194 (let ((fmt "")
13195 (l nil))
13196 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
13197 l (push y l)))
13198 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
13199 l (push d l)))
13200 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
13201 l (push h l)))
13202 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
13203 l (push m l)))
13204 (apply 'format fmt (nreverse l))))
13205
13206 (defun org-time-string-to-time (s)
13207 (apply 'encode-time (org-parse-time-string s)))
13208 (defun org-time-string-to-seconds (s)
13209 (org-float-time (org-time-string-to-time s)))
13210
13211 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
13212 "Convert a time stamp to an absolute day number.
13213 If there is a specifyer for a cyclic time stamp, get the closest date to
13214 DAYNR.
13215 PREFER and SHOW-ALL are passed through to `org-closest-date'.
13216 the variable date is bound by the calendar when this is called."
13217 (cond
13218 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
13219 (if (org-diary-sexp-entry (match-string 1 s) "" date)
13220 daynr
13221 (+ daynr 1000)))
13222 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
13223 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
13224 (time-to-days (current-time))) (match-string 0 s)
13225 prefer show-all))
13226 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
13227
13228 (defun org-days-to-iso-week (days)
13229 "Return the iso week number."
13230 (require 'cal-iso)
13231 (car (calendar-iso-from-absolute days)))
13232
13233 (defun org-small-year-to-year (year)
13234 "Convert 2-digit years into 4-digit years.
13235 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
13236 The year 2000 cannot be abbreviated. Any year larger than 99
13237 is returned unchanged."
13238 (if (< year 38)
13239 (setq year (+ 2000 year))
13240 (if (< year 100)
13241 (setq year (+ 1900 year))))
13242 year)
13243
13244 (defun org-time-from-absolute (d)
13245 "Return the time corresponding to date D.
13246 D may be an absolute day number, or a calendar-type list (month day year)."
13247 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
13248 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
13249
13250 (defun org-calendar-holiday ()
13251 "List of holidays, for Diary display in Org-mode."
13252 (require 'holidays)
13253 (let ((hl (funcall
13254 (if (fboundp 'calendar-check-holidays)
13255 'calendar-check-holidays 'check-calendar-holidays) date)))
13256 (if hl (mapconcat 'identity hl "; "))))
13257
13258 (defun org-diary-sexp-entry (sexp entry date)
13259 "Process a SEXP diary ENTRY for DATE."
13260 (require 'diary-lib)
13261 (let ((result (if calendar-debug-sexp
13262 (let ((stack-trace-on-error t))
13263 (eval (car (read-from-string sexp))))
13264 (condition-case nil
13265 (eval (car (read-from-string sexp)))
13266 (error
13267 (beep)
13268 (message "Bad sexp at line %d in %s: %s"
13269 (org-current-line)
13270 (buffer-file-name) sexp)
13271 (sleep-for 2))))))
13272 (cond ((stringp result) result)
13273 ((and (consp result)
13274 (stringp (cdr result))) (cdr result))
13275 (result entry)
13276 (t nil))))
13277
13278 (defun org-diary-to-ical-string (frombuf)
13279 "Get iCalendar entries from diary entries in buffer FROMBUF.
13280 This uses the icalendar.el library."
13281 (let* ((tmpdir (if (featurep 'xemacs)
13282 (temp-directory)
13283 temporary-file-directory))
13284 (tmpfile (make-temp-name
13285 (expand-file-name "orgics" tmpdir)))
13286 buf rtn b e)
13287 (save-excursion
13288 (set-buffer frombuf)
13289 (icalendar-export-region (point-min) (point-max) tmpfile)
13290 (setq buf (find-buffer-visiting tmpfile))
13291 (set-buffer buf)
13292 (goto-char (point-min))
13293 (if (re-search-forward "^BEGIN:VEVENT" nil t)
13294 (setq b (match-beginning 0)))
13295 (goto-char (point-max))
13296 (if (re-search-backward "^END:VEVENT" nil t)
13297 (setq e (match-end 0)))
13298 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
13299 (kill-buffer buf)
13300 (delete-file tmpfile)
13301 rtn))
13302
13303 (defun org-closest-date (start current change prefer show-all)
13304 "Find the date closest to CURRENT that is consistent with START and CHANGE.
13305 When PREFER is `past' return a date that is either CURRENT or past.
13306 When PREFER is `future', return a date that is either CURRENT or future.
13307 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
13308 ;; Make the proper lists from the dates
13309 (catch 'exit
13310 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
13311 dn dw sday cday n1 n2 n0
13312 d m y y1 y2 date1 date2 nmonths nm ny m2)
13313
13314 (setq start (org-date-to-gregorian start)
13315 current (org-date-to-gregorian
13316 (if show-all
13317 current
13318 (time-to-days (current-time))))
13319 sday (calendar-absolute-from-gregorian start)
13320 cday (calendar-absolute-from-gregorian current))
13321
13322 (if (<= cday sday) (throw 'exit sday))
13323
13324 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13325 (setq dn (string-to-number (match-string 1 change))
13326 dw (cdr (assoc (match-string 2 change) a1)))
13327 (error "Invalid change specifyer: %s" change))
13328 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13329 (cond
13330 ((eq dw 'day)
13331 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13332 n2 (+ n1 dn)))
13333 ((eq dw 'year)
13334 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13335 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13336 (setq date1 (list m d y1)
13337 n1 (calendar-absolute-from-gregorian date1)
13338 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13339 n2 (calendar-absolute-from-gregorian date2)))
13340 ((eq dw 'month)
13341 ;; approx number of month between the two dates
13342 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13343 ;; How often does dn fit in there?
13344 (setq d (nth 1 start) m (car start) y (nth 2 start)
13345 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13346 m (+ m nm)
13347 ny (floor (/ m 12))
13348 y (+ y ny)
13349 m (- m (* ny 12)))
13350 (while (> m 12) (setq m (- m 12) y (1+ y)))
13351 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13352 (setq m2 (+ m dn) y2 y)
13353 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13354 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13355 (while (<= n2 cday)
13356 (setq n1 n2 m m2 y y2)
13357 (setq m2 (+ m dn) y2 y)
13358 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13359 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13360 ;; Make sure n1 is the earlier date
13361 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13362 (if show-all
13363 (cond
13364 ((eq prefer 'past) (if (= cday n2) n2 n1))
13365 ((eq prefer 'future) (if (= cday n1) n1 n2))
13366 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13367 (cond
13368 ((eq prefer 'past) (if (= cday n2) n2 n1))
13369 ((eq prefer 'future) (if (= cday n1) n1 n2))
13370 (t (if (= cday n1) n1 n2)))))))
13371
13372 (defun org-date-to-gregorian (date)
13373 "Turn any specification of DATE into a gregorian date for the calendar."
13374 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13375 ((and (listp date) (= (length date) 3)) date)
13376 ((stringp date)
13377 (setq date (org-parse-time-string date))
13378 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13379 ((listp date)
13380 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13381
13382 (defun org-parse-time-string (s &optional nodefault)
13383 "Parse the standard Org-mode time string.
13384 This should be a lot faster than the normal `parse-time-string'.
13385 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13386 hour and minute fields will be nil if not given."
13387 (if (string-match org-ts-regexp0 s)
13388 (list 0
13389 (if (or (match-beginning 8) (not nodefault))
13390 (string-to-number (or (match-string 8 s) "0")))
13391 (if (or (match-beginning 7) (not nodefault))
13392 (string-to-number (or (match-string 7 s) "0")))
13393 (string-to-number (match-string 4 s))
13394 (string-to-number (match-string 3 s))
13395 (string-to-number (match-string 2 s))
13396 nil nil nil)
13397 (error "Not a standard Org-mode time string: %s" s)))
13398
13399 (defun org-timestamp-up (&optional arg)
13400 "Increase the date item at the cursor by one.
13401 If the cursor is on the year, change the year. If it is on the month or
13402 the day, change that.
13403 With prefix ARG, change by that many units."
13404 (interactive "p")
13405 (org-timestamp-change (prefix-numeric-value arg)))
13406
13407 (defun org-timestamp-down (&optional arg)
13408 "Decrease the date item at the cursor by one.
13409 If the cursor is on the year, change the year. If it is on the month or
13410 the day, change that.
13411 With prefix ARG, change by that many units."
13412 (interactive "p")
13413 (org-timestamp-change (- (prefix-numeric-value arg))))
13414
13415 (defun org-timestamp-up-day (&optional arg)
13416 "Increase the date in the time stamp by one day.
13417 With prefix ARG, change that many days."
13418 (interactive "p")
13419 (if (and (not (org-at-timestamp-p t))
13420 (org-on-heading-p))
13421 (org-todo 'up)
13422 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13423
13424 (defun org-timestamp-down-day (&optional arg)
13425 "Decrease the date in the time stamp by one day.
13426 With prefix ARG, change that many days."
13427 (interactive "p")
13428 (if (and (not (org-at-timestamp-p t))
13429 (org-on-heading-p))
13430 (org-todo 'down)
13431 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13432
13433 (defun org-at-timestamp-p (&optional inactive-ok)
13434 "Determine if the cursor is in or at a timestamp."
13435 (interactive)
13436 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13437 (pos (point))
13438 (ans (or (looking-at tsr)
13439 (save-excursion
13440 (skip-chars-backward "^[<\n\r\t")
13441 (if (> (point) (point-min)) (backward-char 1))
13442 (and (looking-at tsr)
13443 (> (- (match-end 0) pos) -1))))))
13444 (and ans
13445 (boundp 'org-ts-what)
13446 (setq org-ts-what
13447 (cond
13448 ((= pos (match-beginning 0)) 'bracket)
13449 ((= pos (1- (match-end 0))) 'bracket)
13450 ((org-pos-in-match-range pos 2) 'year)
13451 ((org-pos-in-match-range pos 3) 'month)
13452 ((org-pos-in-match-range pos 7) 'hour)
13453 ((org-pos-in-match-range pos 8) 'minute)
13454 ((or (org-pos-in-match-range pos 4)
13455 (org-pos-in-match-range pos 5)) 'day)
13456 ((and (> pos (or (match-end 8) (match-end 5)))
13457 (< pos (match-end 0)))
13458 (- pos (or (match-end 8) (match-end 5))))
13459 (t 'day))))
13460 ans))
13461
13462 (defun org-toggle-timestamp-type ()
13463 "Toggle the type (<active> or [inactive]) of a time stamp."
13464 (interactive)
13465 (when (org-at-timestamp-p t)
13466 (let ((beg (match-beginning 0)) (end (match-end 0))
13467 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13468 (save-excursion
13469 (goto-char beg)
13470 (while (re-search-forward "[][<>]" end t)
13471 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13472 t t)))
13473 (message "Timestamp is now %sactive"
13474 (if (equal (char-after beg) ?<) "" "in")))))
13475
13476 (defun org-timestamp-change (n &optional what)
13477 "Change the date in the time stamp at point.
13478 The date will be changed by N times WHAT. WHAT can be `day', `month',
13479 `year', `minute', `second'. If WHAT is not given, the cursor position
13480 in the timestamp determines what will be changed."
13481 (let ((pos (point))
13482 with-hm inactive
13483 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13484 org-ts-what
13485 extra rem
13486 ts time time0)
13487 (if (not (org-at-timestamp-p t))
13488 (error "Not at a timestamp"))
13489 (if (and (not what) (eq org-ts-what 'bracket))
13490 (org-toggle-timestamp-type)
13491 (if (and (not what) (not (eq org-ts-what 'day))
13492 org-display-custom-times
13493 (get-text-property (point) 'display)
13494 (not (get-text-property (1- (point)) 'display)))
13495 (setq org-ts-what 'day))
13496 (setq org-ts-what (or what org-ts-what)
13497 inactive (= (char-after (match-beginning 0)) ?\[)
13498 ts (match-string 0))
13499 (replace-match "")
13500 (if (string-match
13501 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
13502 ts)
13503 (setq extra (match-string 1 ts)))
13504 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13505 (setq with-hm t))
13506 (setq time0 (org-parse-time-string ts))
13507 (when (and (eq org-ts-what 'minute)
13508 (eq current-prefix-arg nil))
13509 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13510 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13511 (setcar (cdr time0) (+ (nth 1 time0)
13512 (if (> n 0) (- rem) (- dm rem))))))
13513 (setq time
13514 (encode-time (or (car time0) 0)
13515 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13516 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13517 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13518 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13519 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13520 (nthcdr 6 time0)))
13521 (when (and (member org-ts-what '(hour minute))
13522 extra
13523 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13524 (setq extra (org-modify-ts-extra
13525 extra
13526 (if (eq org-ts-what 'hour) 2 5)
13527 n dm)))
13528 (when (integerp org-ts-what)
13529 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13530 (if (eq what 'calendar)
13531 (let ((cal-date (org-get-date-from-calendar)))
13532 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13533 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13534 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13535 (setcar time0 (or (car time0) 0))
13536 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13537 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13538 (setq time (apply 'encode-time time0))))
13539 (setq org-last-changed-timestamp
13540 (org-insert-time-stamp time with-hm inactive nil nil extra))
13541 (org-clock-update-time-maybe)
13542 (goto-char pos)
13543 ;; Try to recenter the calendar window, if any
13544 (if (and org-calendar-follow-timestamp-change
13545 (get-buffer-window "*Calendar*" t)
13546 (memq org-ts-what '(day month year)))
13547 (org-recenter-calendar (time-to-days time))))))
13548
13549 (defun org-modify-ts-extra (s pos n dm)
13550 "Change the different parts of the lead-time and repeat fields in timestamp."
13551 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13552 ng h m new rem)
13553 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13554 (cond
13555 ((or (org-pos-in-match-range pos 2)
13556 (org-pos-in-match-range pos 3))
13557 (setq m (string-to-number (match-string 3 s))
13558 h (string-to-number (match-string 2 s)))
13559 (if (org-pos-in-match-range pos 2)
13560 (setq h (+ h n))
13561 (setq n (* dm (org-no-warnings (signum n))))
13562 (when (not (= 0 (setq rem (% m dm))))
13563 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13564 (setq m (+ m n)))
13565 (if (< m 0) (setq m (+ m 60) h (1- h)))
13566 (if (> m 59) (setq m (- m 60) h (1+ h)))
13567 (setq h (min 24 (max 0 h)))
13568 (setq ng 1 new (format "-%02d:%02d" h m)))
13569 ((org-pos-in-match-range pos 6)
13570 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13571 ((org-pos-in-match-range pos 5)
13572 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13573
13574 ((org-pos-in-match-range pos 9)
13575 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13576 ((org-pos-in-match-range pos 8)
13577 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13578
13579 (when ng
13580 (setq s (concat
13581 (substring s 0 (match-beginning ng))
13582 new
13583 (substring s (match-end ng))))))
13584 s))
13585
13586 (defun org-recenter-calendar (date)
13587 "If the calendar is visible, recenter it to DATE."
13588 (let* ((win (selected-window))
13589 (cwin (get-buffer-window "*Calendar*" t))
13590 (calendar-move-hook nil))
13591 (when cwin
13592 (select-window cwin)
13593 (calendar-goto-date (if (listp date) date
13594 (calendar-gregorian-from-absolute date)))
13595 (select-window win))))
13596
13597 (defun org-goto-calendar (&optional arg)
13598 "Go to the Emacs calendar at the current date.
13599 If there is a time stamp in the current line, go to that date.
13600 A prefix ARG can be used to force the current date."
13601 (interactive "P")
13602 (let ((tsr org-ts-regexp) diff
13603 (calendar-move-hook nil)
13604 (calendar-view-holidays-initially-flag nil)
13605 (view-calendar-holidays-initially nil)
13606 (calendar-view-diary-initially-flag nil)
13607 (view-diary-entries-initially nil))
13608 (if (or (org-at-timestamp-p)
13609 (save-excursion
13610 (beginning-of-line 1)
13611 (looking-at (concat ".*" tsr))))
13612 (let ((d1 (time-to-days (current-time)))
13613 (d2 (time-to-days
13614 (org-time-string-to-time (match-string 1)))))
13615 (setq diff (- d2 d1))))
13616 (calendar)
13617 (calendar-goto-today)
13618 (if (and diff (not arg)) (calendar-forward-day diff))))
13619
13620 (defun org-get-date-from-calendar ()
13621 "Return a list (month day year) of date at point in calendar."
13622 (with-current-buffer "*Calendar*"
13623 (save-match-data
13624 (calendar-cursor-to-date))))
13625
13626 (defun org-date-from-calendar ()
13627 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13628 If there is already a time stamp at the cursor position, update it."
13629 (interactive)
13630 (if (org-at-timestamp-p t)
13631 (org-timestamp-change 0 'calendar)
13632 (let ((cal-date (org-get-date-from-calendar)))
13633 (org-insert-time-stamp
13634 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13635
13636 (defun org-minutes-to-hh:mm-string (m)
13637 "Compute H:MM from a number of minutes."
13638 (let ((h (/ m 60)))
13639 (setq m (- m (* 60 h)))
13640 (format org-time-clocksum-format h m)))
13641
13642 (defun org-hh:mm-string-to-minutes (s)
13643 "Convert a string H:MM to a number of minutes.
13644 If the string is just a number, interprete it as minutes.
13645 In fact, the first hh:mm or number in the string will be taken,
13646 there can be extra stuff in the string.
13647 If no number is found, the return value is 0."
13648 (cond
13649 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13650 (+ (* (string-to-number (match-string 1 s)) 60)
13651 (string-to-number (match-string 2 s))))
13652 ((string-match "\\([0-9]+\\)" s)
13653 (string-to-number (match-string 1 s)))
13654 (t 0)))
13655
13656 ;;;; Files
13657
13658 (defun org-save-all-org-buffers ()
13659 "Save all Org-mode buffers without user confirmation."
13660 (interactive)
13661 (message "Saving all Org-mode buffers...")
13662 (save-some-buffers t 'org-mode-p)
13663 (when (featurep 'org-id) (org-id-locations-save))
13664 (message "Saving all Org-mode buffers... done"))
13665
13666 (defun org-revert-all-org-buffers ()
13667 "Revert all Org-mode buffers.
13668 Prompt for confirmation when there are unsaved changes.
13669 Be sure you know what you are doing before letting this function
13670 overwrite your changes.
13671
13672 This function is useful in a setup where one tracks org files
13673 with a version control system, to revert on one machine after pulling
13674 changes from another. I believe the procedure must be like this:
13675
13676 1. M-x org-save-all-org-buffers
13677 2. Pull changes from the other machine, resolve conflicts
13678 3. M-x org-revert-all-org-buffers"
13679 (interactive)
13680 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13681 (error "Abort"))
13682 (save-excursion
13683 (save-window-excursion
13684 (mapc
13685 (lambda (b)
13686 (when (and (with-current-buffer b (org-mode-p))
13687 (with-current-buffer b buffer-file-name))
13688 (switch-to-buffer b)
13689 (revert-buffer t 'no-confirm)))
13690 (buffer-list))
13691 (when (and (featurep 'org-id) org-id-track-globally)
13692 (org-id-locations-load)))))
13693
13694 ;;;; Agenda files
13695
13696 ;;;###autoload
13697 (defun org-iswitchb (&optional arg)
13698 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
13699 With a prefix argument, restrict available to files.
13700 With two prefix arguments, restrict available buffers to agenda files."
13701 (interactive "P")
13702 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13703 ((equal arg '(16)) (org-buffer-list 'agenda))
13704 (t (org-buffer-list)))))
13705 (switch-to-buffer
13706 (org-icompleting-read "Org buffer: "
13707 (mapcar 'list (mapcar 'buffer-name blist))
13708 nil t))))
13709
13710 ;;;###autoload
13711 (defalias 'org-ido-switchb 'org-iswitchb)
13712
13713 (defun org-buffer-list (&optional predicate exclude-tmp)
13714 "Return a list of Org buffers.
13715 PREDICATE can be `export', `files' or `agenda'.
13716
13717 export restrict the list to Export buffers.
13718 files restrict the list to buffers visiting Org files.
13719 agenda restrict the list to buffers visiting agenda files.
13720
13721 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13722 (let* ((bfn nil)
13723 (agenda-files (and (eq predicate 'agenda)
13724 (mapcar 'file-truename (org-agenda-files t))))
13725 (filter
13726 (cond
13727 ((eq predicate 'files)
13728 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13729 ((eq predicate 'export)
13730 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13731 ((eq predicate 'agenda)
13732 (lambda (b)
13733 (with-current-buffer b
13734 (and (eq major-mode 'org-mode)
13735 (setq bfn (buffer-file-name b))
13736 (member (file-truename bfn) agenda-files)))))
13737 (t (lambda (b) (with-current-buffer b
13738 (or (eq major-mode 'org-mode)
13739 (string-match "\*Org .*Export"
13740 (buffer-name b)))))))))
13741 (delq nil
13742 (mapcar
13743 (lambda(b)
13744 (if (and (funcall filter b)
13745 (or (not exclude-tmp)
13746 (not (string-match "tmp" (buffer-name b)))))
13747 b
13748 nil))
13749 (buffer-list)))))
13750
13751 (defun org-agenda-files (&optional unrestricted archives)
13752 "Get the list of agenda files.
13753 Optional UNRESTRICTED means return the full list even if a restriction
13754 is currently in place.
13755 When ARCHIVES is t, include all archive files hat are really being
13756 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13757 `org-agenda-archives-mode' is t."
13758 (let ((files
13759 (cond
13760 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13761 ((stringp org-agenda-files) (org-read-agenda-file-list))
13762 ((listp org-agenda-files) org-agenda-files)
13763 (t (error "Invalid value of `org-agenda-files'")))))
13764 (setq files (apply 'append
13765 (mapcar (lambda (f)
13766 (if (file-directory-p f)
13767 (directory-files
13768 f t org-agenda-file-regexp)
13769 (list f)))
13770 files)))
13771 (when org-agenda-skip-unavailable-files
13772 (setq files (delq nil
13773 (mapcar (function
13774 (lambda (file)
13775 (and (file-readable-p file) file)))
13776 files))))
13777 (when (or (eq archives t)
13778 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13779 (setq files (org-add-archive-files files)))
13780 files))
13781
13782 (defun org-edit-agenda-file-list ()
13783 "Edit the list of agenda files.
13784 Depending on setup, this either uses customize to edit the variable
13785 `org-agenda-files', or it visits the file that is holding the list. In the
13786 latter case, the buffer is set up in a way that saving it automatically kills
13787 the buffer and restores the previous window configuration."
13788 (interactive)
13789 (if (stringp org-agenda-files)
13790 (let ((cw (current-window-configuration)))
13791 (find-file org-agenda-files)
13792 (org-set-local 'org-window-configuration cw)
13793 (org-add-hook 'after-save-hook
13794 (lambda ()
13795 (set-window-configuration
13796 (prog1 org-window-configuration
13797 (kill-buffer (current-buffer))))
13798 (org-install-agenda-files-menu)
13799 (message "New agenda file list installed"))
13800 nil 'local)
13801 (message "%s" (substitute-command-keys
13802 "Edit list and finish with \\[save-buffer]")))
13803 (customize-variable 'org-agenda-files)))
13804
13805 (defun org-store-new-agenda-file-list (list)
13806 "Set new value for the agenda file list and save it correctly."
13807 (if (stringp org-agenda-files)
13808 (let ((f org-agenda-files) b)
13809 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13810 (with-temp-file f
13811 (insert (mapconcat 'identity list "\n") "\n")))
13812 (let ((org-mode-hook nil) (org-inhibit-startup t)
13813 (org-insert-mode-line-in-empty-file nil))
13814 (setq org-agenda-files list)
13815 (customize-save-variable 'org-agenda-files org-agenda-files))))
13816
13817 (defun org-read-agenda-file-list ()
13818 "Read the list of agenda files from a file."
13819 (when (file-directory-p org-agenda-files)
13820 (error "`org-agenda-files' cannot be a single directory"))
13821 (when (stringp org-agenda-files)
13822 (with-temp-buffer
13823 (insert-file-contents org-agenda-files)
13824 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13825
13826
13827 ;;;###autoload
13828 (defun org-cycle-agenda-files ()
13829 "Cycle through the files in `org-agenda-files'.
13830 If the current buffer visits an agenda file, find the next one in the list.
13831 If the current buffer does not, find the first agenda file."
13832 (interactive)
13833 (let* ((fs (org-agenda-files t))
13834 (files (append fs (list (car fs))))
13835 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13836 file)
13837 (unless files (error "No agenda files"))
13838 (catch 'exit
13839 (while (setq file (pop files))
13840 (if (equal (file-truename file) tcf)
13841 (when (car files)
13842 (find-file (car files))
13843 (throw 'exit t))))
13844 (find-file (car fs)))
13845 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13846
13847 (defun org-agenda-file-to-front (&optional to-end)
13848 "Move/add the current file to the top of the agenda file list.
13849 If the file is not present in the list, it is added to the front. If it is
13850 present, it is moved there. With optional argument TO-END, add/move to the
13851 end of the list."
13852 (interactive "P")
13853 (let ((org-agenda-skip-unavailable-files nil)
13854 (file-alist (mapcar (lambda (x)
13855 (cons (file-truename x) x))
13856 (org-agenda-files t)))
13857 (ctf (file-truename buffer-file-name))
13858 x had)
13859 (setq x (assoc ctf file-alist) had x)
13860
13861 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13862 (if to-end
13863 (setq file-alist (append (delq x file-alist) (list x)))
13864 (setq file-alist (cons x (delq x file-alist))))
13865 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13866 (org-install-agenda-files-menu)
13867 (message "File %s to %s of agenda file list"
13868 (if had "moved" "added") (if to-end "end" "front"))))
13869
13870 (defun org-remove-file (&optional file)
13871 "Remove current file from the list of files in variable `org-agenda-files'.
13872 These are the files which are being checked for agenda entries.
13873 Optional argument FILE means, use this file instead of the current."
13874 (interactive)
13875 (let* ((org-agenda-skip-unavailable-files nil)
13876 (file (or file buffer-file-name))
13877 (true-file (file-truename file))
13878 (afile (abbreviate-file-name file))
13879 (files (delq nil (mapcar
13880 (lambda (x)
13881 (if (equal true-file
13882 (file-truename x))
13883 nil x))
13884 (org-agenda-files t)))))
13885 (if (not (= (length files) (length (org-agenda-files t))))
13886 (progn
13887 (org-store-new-agenda-file-list files)
13888 (org-install-agenda-files-menu)
13889 (message "Removed file: %s" afile))
13890 (message "File was not in list: %s (not removed)" afile))))
13891
13892 (defun org-file-menu-entry (file)
13893 (vector file (list 'find-file file) t))
13894
13895 (defun org-check-agenda-file (file)
13896 "Make sure FILE exists. If not, ask user what to do."
13897 (when (not (file-exists-p file))
13898 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
13899 (abbreviate-file-name file))
13900 (let ((r (downcase (read-char-exclusive))))
13901 (cond
13902 ((equal r ?r)
13903 (org-remove-file file)
13904 (throw 'nextfile t))
13905 (t (error "Abort"))))))
13906
13907 (defun org-get-agenda-file-buffer (file)
13908 "Get a buffer visiting FILE. If the buffer needs to be created, add
13909 it to the list of buffers which might be released later."
13910 (let ((buf (org-find-base-buffer-visiting file)))
13911 (if buf
13912 buf ; just return it
13913 ;; Make a new buffer and remember it
13914 (setq buf (find-file-noselect file))
13915 (if buf (push buf org-agenda-new-buffers))
13916 buf)))
13917
13918 (defun org-release-buffers (blist)
13919 "Release all buffers in list, asking the user for confirmation when needed.
13920 When a buffer is unmodified, it is just killed. When modified, it is saved
13921 \(if the user agrees) and then killed."
13922 (let (buf file)
13923 (while (setq buf (pop blist))
13924 (setq file (buffer-file-name buf))
13925 (when (and (buffer-modified-p buf)
13926 file
13927 (y-or-n-p (format "Save file %s? " file)))
13928 (with-current-buffer buf (save-buffer)))
13929 (kill-buffer buf))))
13930
13931 (defun org-prepare-agenda-buffers (files)
13932 "Create buffers for all agenda files, protect archived trees and comments."
13933 (interactive)
13934 (let ((pa '(:org-archived t))
13935 (pc '(:org-comment t))
13936 (pall '(:org-archived t :org-comment t))
13937 (inhibit-read-only t)
13938 (rea (concat ":" org-archive-tag ":"))
13939 bmp file re)
13940 (save-excursion
13941 (save-restriction
13942 (while (setq file (pop files))
13943 (catch 'nextfile
13944 (if (bufferp file)
13945 (set-buffer file)
13946 (org-check-agenda-file file)
13947 (set-buffer (org-get-agenda-file-buffer file)))
13948 (widen)
13949 (setq bmp (buffer-modified-p))
13950 (org-refresh-category-properties)
13951 (setq org-todo-keywords-for-agenda
13952 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13953 (setq org-done-keywords-for-agenda
13954 (append org-done-keywords-for-agenda org-done-keywords))
13955 (setq org-todo-keyword-alist-for-agenda
13956 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13957 (setq org-drawers-for-agenda
13958 (append org-drawers-for-agenda org-drawers))
13959 (setq org-tag-alist-for-agenda
13960 (append org-tag-alist-for-agenda org-tag-alist))
13961
13962 (save-excursion
13963 (remove-text-properties (point-min) (point-max) pall)
13964 (when org-agenda-skip-archived-trees
13965 (goto-char (point-min))
13966 (while (re-search-forward rea nil t)
13967 (if (org-on-heading-p t)
13968 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13969 (goto-char (point-min))
13970 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13971 (while (re-search-forward re nil t)
13972 (add-text-properties
13973 (match-beginning 0) (org-end-of-subtree t) pc)))
13974 (set-buffer-modified-p bmp)))))
13975 (setq org-todo-keyword-alist-for-agenda
13976 (org-uniquify org-todo-keyword-alist-for-agenda)
13977 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13978
13979 ;;;; Embedded LaTeX
13980
13981 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13982 "Keymap for the minor `org-cdlatex-mode'.")
13983
13984 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13985 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13986 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13987 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13988 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13989
13990 (defvar org-cdlatex-texmathp-advice-is-done nil
13991 "Flag remembering if we have applied the advice to texmathp already.")
13992
13993 (define-minor-mode org-cdlatex-mode
13994 "Toggle the minor `org-cdlatex-mode'.
13995 This mode supports entering LaTeX environment and math in LaTeX fragments
13996 in Org-mode.
13997 \\{org-cdlatex-mode-map}"
13998 nil " OCDL" nil
13999 (when org-cdlatex-mode (require 'cdlatex))
14000 (unless org-cdlatex-texmathp-advice-is-done
14001 (setq org-cdlatex-texmathp-advice-is-done t)
14002 (defadvice texmathp (around org-math-always-on activate)
14003 "Always return t in org-mode buffers.
14004 This is because we want to insert math symbols without dollars even outside
14005 the LaTeX math segments. If Orgmode thinks that point is actually inside
14006 an embedded LaTeX fragment, let texmathp do its job.
14007 \\[org-cdlatex-mode-map]"
14008 (interactive)
14009 (let (p)
14010 (cond
14011 ((not (org-mode-p)) ad-do-it)
14012 ((eq this-command 'cdlatex-math-symbol)
14013 (setq ad-return-value t
14014 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
14015 (t
14016 (let ((p (org-inside-LaTeX-fragment-p)))
14017 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
14018 (setq ad-return-value t
14019 texmathp-why '("Org-mode embedded math" . 0))
14020 (if p ad-do-it)))))))))
14021
14022 (defun turn-on-org-cdlatex ()
14023 "Unconditionally turn on `org-cdlatex-mode'."
14024 (org-cdlatex-mode 1))
14025
14026 (defun org-inside-LaTeX-fragment-p ()
14027 "Test if point is inside a LaTeX fragment.
14028 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
14029 sequence appearing also before point.
14030 Even though the matchers for math are configurable, this function assumes
14031 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
14032 delimiters are skipped when they have been removed by customization.
14033 The return value is nil, or a cons cell with the delimiter and
14034 and the position of this delimiter.
14035
14036 This function does a reasonably good job, but can locally be fooled by
14037 for example currency specifications. For example it will assume being in
14038 inline math after \"$22.34\". The LaTeX fragment formatter will only format
14039 fragments that are properly closed, but during editing, we have to live
14040 with the uncertainty caused by missing closing delimiters. This function
14041 looks only before point, not after."
14042 (catch 'exit
14043 (let ((pos (point))
14044 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
14045 (lim (progn
14046 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
14047 (point)))
14048 dd-on str (start 0) m re)
14049 (goto-char pos)
14050 (when dodollar
14051 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
14052 re (nth 1 (assoc "$" org-latex-regexps)))
14053 (while (string-match re str start)
14054 (cond
14055 ((= (match-end 0) (length str))
14056 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
14057 ((= (match-end 0) (- (length str) 5))
14058 (throw 'exit nil))
14059 (t (setq start (match-end 0))))))
14060 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
14061 (goto-char pos)
14062 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
14063 (and (match-beginning 2) (throw 'exit nil))
14064 ;; count $$
14065 (while (re-search-backward "\\$\\$" lim t)
14066 (setq dd-on (not dd-on)))
14067 (goto-char pos)
14068 (if dd-on (cons "$$" m))))))
14069
14070
14071 (defun org-try-cdlatex-tab ()
14072 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
14073 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
14074 - inside a LaTeX fragment, or
14075 - after the first word in a line, where an abbreviation expansion could
14076 insert a LaTeX environment."
14077 (when org-cdlatex-mode
14078 (cond
14079 ((save-excursion
14080 (skip-chars-backward "a-zA-Z0-9*")
14081 (skip-chars-backward " \t")
14082 (bolp))
14083 (cdlatex-tab) t)
14084 ((org-inside-LaTeX-fragment-p)
14085 (cdlatex-tab) t)
14086 (t nil))))
14087
14088 (defun org-cdlatex-underscore-caret (&optional arg)
14089 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
14090 Revert to the normal definition outside of these fragments."
14091 (interactive "P")
14092 (if (org-inside-LaTeX-fragment-p)
14093 (call-interactively 'cdlatex-sub-superscript)
14094 (let (org-cdlatex-mode)
14095 (call-interactively (key-binding (vector last-input-event))))))
14096
14097 (defun org-cdlatex-math-modify (&optional arg)
14098 "Execute `cdlatex-math-modify' in LaTeX fragments.
14099 Revert to the normal definition outside of these fragments."
14100 (interactive "P")
14101 (if (org-inside-LaTeX-fragment-p)
14102 (call-interactively 'cdlatex-math-modify)
14103 (let (org-cdlatex-mode)
14104 (call-interactively (key-binding (vector last-input-event))))))
14105
14106 (defvar org-latex-fragment-image-overlays nil
14107 "List of overlays carrying the images of latex fragments.")
14108 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
14109
14110 (defun org-remove-latex-fragment-image-overlays ()
14111 "Remove all overlays with LaTeX fragment images in current buffer."
14112 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
14113 (setq org-latex-fragment-image-overlays nil))
14114
14115 (defun org-preview-latex-fragment (&optional subtree)
14116 "Preview the LaTeX fragment at point, or all locally or globally.
14117 If the cursor is in a LaTeX fragment, create the image and overlay
14118 it over the source code. If there is no fragment at point, display
14119 all fragments in the current text, from one headline to the next. With
14120 prefix SUBTREE, display all fragments in the current subtree. With a
14121 double prefix `C-u C-u', or when the cursor is before the first headline,
14122 display all fragments in the buffer.
14123 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
14124 (interactive "P")
14125 (org-remove-latex-fragment-image-overlays)
14126 (save-excursion
14127 (save-restriction
14128 (let (beg end at msg)
14129 (cond
14130 ((or (equal subtree '(16))
14131 (not (save-excursion
14132 (re-search-backward (concat "^" outline-regexp) nil t))))
14133 (setq beg (point-min) end (point-max)
14134 msg "Creating images for buffer...%s"))
14135 ((equal subtree '(4))
14136 (org-back-to-heading)
14137 (setq beg (point) end (org-end-of-subtree t)
14138 msg "Creating images for subtree...%s"))
14139 (t
14140 (if (setq at (org-inside-LaTeX-fragment-p))
14141 (goto-char (max (point-min) (- (cdr at) 2)))
14142 (org-back-to-heading))
14143 (setq beg (point) end (progn (outline-next-heading) (point))
14144 msg (if at "Creating image...%s"
14145 "Creating images for entry...%s"))))
14146 (message msg "")
14147 (narrow-to-region beg end)
14148 (goto-char beg)
14149 (org-format-latex
14150 (concat "ltxpng/" (file-name-sans-extension
14151 (file-name-nondirectory
14152 buffer-file-name)))
14153 default-directory 'overlays msg at 'forbuffer)
14154 (message msg "done. Use `C-c C-c' to remove images.")))))
14155
14156 (defvar org-latex-regexps
14157 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
14158 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
14159 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
14160 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14161 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
14162 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
14163 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
14164 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
14165 "Regular expressions for matching embedded LaTeX.")
14166
14167 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
14168 "Replace LaTeX fragments with links to an image, and produce images.
14169 Some of the options can be changed using the variable
14170 `org-format-latex-options'."
14171 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
14172 (let* ((prefixnodir (file-name-nondirectory prefix))
14173 (absprefix (expand-file-name prefix dir))
14174 (todir (file-name-directory absprefix))
14175 (opt org-format-latex-options)
14176 (matchers (plist-get opt :matchers))
14177 (re-list org-latex-regexps)
14178 (cnt 0) txt link beg end re e checkdir
14179 executables-checked
14180 m n block linkfile movefile ov)
14181 ;; Check if there are old images files with this prefix, and remove them
14182 (when (file-directory-p todir)
14183 (mapc 'delete-file
14184 (directory-files
14185 todir 'full
14186 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
14187 ;; Check the different regular expressions
14188 (while (setq e (pop re-list))
14189 (setq m (car e) re (nth 1 e) n (nth 2 e)
14190 block (if (nth 3 e) "\n\n" ""))
14191 (when (member m matchers)
14192 (goto-char (point-min))
14193 (while (re-search-forward re nil t)
14194 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
14195 (not (get-text-property (match-beginning n)
14196 'org-protected))
14197 (or (not overlays)
14198 (not (eq (get-char-property (match-beginning n)
14199 'org-overlay-type)
14200 'org-latex-overlay))))
14201 (setq txt (match-string n)
14202 beg (match-beginning n) end (match-end n)
14203 cnt (1+ cnt)
14204 linkfile (format "%s_%04d.png" prefix cnt)
14205 movefile (format "%s_%04d.png" absprefix cnt)
14206 link (concat block "[[file:" linkfile "]]" block))
14207 (if msg (message msg cnt))
14208 (goto-char beg)
14209 (unless checkdir ; make sure the directory exists
14210 (setq checkdir t)
14211 (or (file-directory-p todir) (make-directory todir)))
14212
14213 (unless executables-checked
14214 (org-check-external-command
14215 "latex" "needed to convert LaTeX fragments to images")
14216 (org-check-external-command
14217 "dvipng" "needed to convert LaTeX fragments to images")
14218 (setq executables-checked t))
14219
14220 (org-create-formula-image
14221 txt movefile opt forbuffer)
14222 (if overlays
14223 (progn
14224 (mapc (lambda (o)
14225 (if (eq (org-overlay-get o 'org-overlay-type)
14226 'org-latex-overlay)
14227 (org-delete-overlay o)))
14228 (org-overlays-in beg end))
14229 (setq ov (org-make-overlay beg end))
14230 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
14231 (if (featurep 'xemacs)
14232 (progn
14233 (org-overlay-put ov 'invisible t)
14234 (org-overlay-put
14235 ov 'end-glyph
14236 (make-glyph (vector 'png :file movefile))))
14237 (org-overlay-put
14238 ov 'display
14239 (list 'image :type 'png :file movefile :ascent 'center)))
14240 (push ov org-latex-fragment-image-overlays)
14241 (goto-char end))
14242 (delete-region beg end)
14243 (insert link))))))))
14244
14245 (defvar org-export-latex-packages-alist) ;; defined in org-latex.el
14246 ;; This function borrows from Ganesh Swami's latex2png.el
14247 (defun org-create-formula-image (string tofile options buffer)
14248 "This calls dvipng."
14249 (require 'org-latex)
14250 (let* ((tmpdir (if (featurep 'xemacs)
14251 (temp-directory)
14252 temporary-file-directory))
14253 (texfilebase (make-temp-name
14254 (expand-file-name "orgtex" tmpdir)))
14255 (texfile (concat texfilebase ".tex"))
14256 (dvifile (concat texfilebase ".dvi"))
14257 (pngfile (concat texfilebase ".png"))
14258 (fnh (if (featurep 'xemacs)
14259 (font-height (get-face-font 'default))
14260 (face-attribute 'default :height nil)))
14261 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
14262 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
14263 (fg (or (plist-get options (if buffer :foreground :html-foreground))
14264 "Black"))
14265 (bg (or (plist-get options (if buffer :background :html-background))
14266 "Transparent")))
14267 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
14268 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
14269 (with-temp-file texfile
14270 (insert org-format-latex-header
14271 (if org-export-latex-packages-alist
14272 (concat "\n"
14273 (mapconcat (lambda(p)
14274 (if (equal "" (car p))
14275 (format "\\usepackage{%s}" (cadr p))
14276 (format "\\usepackage[%s]{%s}"
14277 (car p) (cadr p))))
14278 org-export-latex-packages-alist "\n"))
14279 "")
14280 "\n\\begin{document}\n" string "\n\\end{document}\n"))
14281 (let ((dir default-directory))
14282 (condition-case nil
14283 (progn
14284 (cd tmpdir)
14285 (call-process "latex" nil nil nil texfile))
14286 (error nil))
14287 (cd dir))
14288 (if (not (file-exists-p dvifile))
14289 (progn (message "Failed to create dvi file from %s" texfile) nil)
14290 (condition-case nil
14291 (call-process "dvipng" nil nil nil
14292 "-fg" fg "-bg" bg
14293 "-D" dpi
14294 ;;"-x" scale "-y" scale
14295 "-T" "tight"
14296 "-o" pngfile
14297 dvifile)
14298 (error nil))
14299 (if (not (file-exists-p pngfile))
14300 (progn (message "Failed to create png file from %s" texfile) nil)
14301 ;; Use the requested file name and clean up
14302 (copy-file pngfile tofile 'replace)
14303 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
14304 (delete-file (concat texfilebase e)))
14305 pngfile))))
14306
14307 (defun org-dvipng-color (attr)
14308 "Return an rgb color specification for dvipng."
14309 (apply 'format "rgb %s %s %s"
14310 (mapcar 'org-normalize-color
14311 (color-values (face-attribute 'default attr nil)))))
14312
14313 (defun org-normalize-color (value)
14314 "Return string to be used as color value for an RGB component."
14315 (format "%g" (/ value 65535.0)))
14316
14317 ;;;; Key bindings
14318
14319 ;; Make `C-c C-x' a prefix key
14320 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
14321
14322 ;; TAB key with modifiers
14323 (org-defkey org-mode-map "\C-i" 'org-cycle)
14324 (org-defkey org-mode-map [(tab)] 'org-cycle)
14325 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
14326 (org-defkey org-mode-map [(meta tab)] 'org-complete)
14327 (org-defkey org-mode-map "\M-\t" 'org-complete)
14328 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14329 ;; The following line is necessary under Suse GNU/Linux
14330 (unless (featurep 'xemacs)
14331 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14332 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14333 (define-key org-mode-map [backtab] 'org-shifttab)
14334
14335 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14336 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14337 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14338
14339 ;; Cursor keys with modifiers
14340 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14341 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14342 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14343 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14344
14345 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14346 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14347 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14348 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14349
14350 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14351 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14352 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14353 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14354
14355 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14356 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14357
14358 ;;; Extra keys for tty access.
14359 ;; We only set them when really needed because otherwise the
14360 ;; menus don't show the simple keys
14361
14362 (when (or org-use-extra-keys
14363 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14364 (not window-system))
14365 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14366 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14367 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14368 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14369 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14370 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14371 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14372 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14373 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14374 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14375 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14376 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14377 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14378 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14379 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14380 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14381 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14382 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14383 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14384 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14385 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14386 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14387 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14388 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14389 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14390 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14391 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14392 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14393
14394 ;; All the other keys
14395
14396 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14397 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14398 (if (boundp 'narrow-map)
14399 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14400 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14401 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14402 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14403 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14404 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14405 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
14406 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14407 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14408 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14409 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14410 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14411 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14412 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14413 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14414 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14415 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14416 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14417 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14418 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14419 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14420 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14421 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14422 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14423 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14424 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14425 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14426 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14427 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14428 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14429 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14430 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14431 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14432 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14433 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14434 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14435 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14436 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14437 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14438 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14439 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14440 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14441 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14442 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14443 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14444 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14445 (org-defkey org-mode-map "\C-c^" 'org-sort)
14446 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14447 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14448 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
14449 (org-defkey org-mode-map "\C-m" 'org-return)
14450 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14451 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14452 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14453 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14454 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14455 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14456 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14457 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14458 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14459 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14460 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14461 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14462 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14463 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14464 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14465 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14466 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14467 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
14468 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
14469 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14470 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14471
14472 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14473 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14474 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14475 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14476
14477 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14478 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14479 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14480 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14481 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14482 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14483 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14484 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14485 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14486 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14487 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14488 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
14489 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14490 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14491 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14492
14493 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14494 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14495 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14496 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14497
14498 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14499
14500 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14501
14502 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14503 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14504
14505 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14506
14507
14508 (when (featurep 'xemacs)
14509 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14510
14511
14512 (defvar org-self-insert-command-undo-counter 0)
14513
14514 (defvar org-table-auto-blank-field) ; defined in org-table.el
14515 (defun org-self-insert-command (N)
14516 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14517 If the cursor is in a table looking at whitespace, the whitespace is
14518 overwritten, and the table is not marked as requiring realignment."
14519 (interactive "p")
14520 (if (and
14521 (org-table-p)
14522 (progn
14523 ;; check if we blank the field, and if that triggers align
14524 (and (featurep 'org-table) org-table-auto-blank-field
14525 (member last-command
14526 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14527 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14528 ;; got extra space, this field does not determine column width
14529 (let (org-table-may-need-update) (org-table-blank-field))
14530 ;; no extra space, this field may determine column width
14531 (org-table-blank-field)))
14532 t)
14533 (eq N 1)
14534 (looking-at "[^|\n]* |"))
14535 (let (org-table-may-need-update)
14536 (goto-char (1- (match-end 0)))
14537 (delete-backward-char 1)
14538 (goto-char (match-beginning 0))
14539 (self-insert-command N))
14540 (setq org-table-may-need-update t)
14541 (self-insert-command N)
14542 (org-fix-tags-on-the-fly)
14543 (if org-self-insert-cluster-for-undo
14544 (if (not (eq last-command 'org-self-insert-command))
14545 (setq org-self-insert-command-undo-counter 1)
14546 (if (>= org-self-insert-command-undo-counter 20)
14547 (setq org-self-insert-command-undo-counter 1)
14548 (and (> org-self-insert-command-undo-counter 0)
14549 buffer-undo-list
14550 (not (cadr buffer-undo-list)) ; remove nil entry
14551 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14552 (setq org-self-insert-command-undo-counter
14553 (1+ org-self-insert-command-undo-counter)))))))
14554
14555 (defun org-fix-tags-on-the-fly ()
14556 (when (and (equal (char-after (point-at-bol)) ?*)
14557 (org-on-heading-p))
14558 (org-align-tags-here org-tags-column)))
14559
14560 (defun org-delete-backward-char (N)
14561 "Like `delete-backward-char', insert whitespace at field end in tables.
14562 When deleting backwards, in tables this function will insert whitespace in
14563 front of the next \"|\" separator, to keep the table aligned. The table will
14564 still be marked for re-alignment if the field did fill the entire column,
14565 because, in this case the deletion might narrow the column."
14566 (interactive "p")
14567 (if (and (org-table-p)
14568 (eq N 1)
14569 (string-match "|" (buffer-substring (point-at-bol) (point)))
14570 (looking-at ".*?|"))
14571 (let ((pos (point))
14572 (noalign (looking-at "[^|\n\r]* |"))
14573 (c org-table-may-need-update))
14574 (backward-delete-char N)
14575 (skip-chars-forward "^|")
14576 (insert " ")
14577 (goto-char (1- pos))
14578 ;; noalign: if there were two spaces at the end, this field
14579 ;; does not determine the width of the column.
14580 (if noalign (setq org-table-may-need-update c)))
14581 (backward-delete-char N)
14582 (org-fix-tags-on-the-fly)))
14583
14584 (defun org-delete-char (N)
14585 "Like `delete-char', but insert whitespace at field end in tables.
14586 When deleting characters, in tables this function will insert whitespace in
14587 front of the next \"|\" separator, to keep the table aligned. The table will
14588 still be marked for re-alignment if the field did fill the entire column,
14589 because, in this case the deletion might narrow the column."
14590 (interactive "p")
14591 (if (and (org-table-p)
14592 (not (bolp))
14593 (not (= (char-after) ?|))
14594 (eq N 1))
14595 (if (looking-at ".*?|")
14596 (let ((pos (point))
14597 (noalign (looking-at "[^|\n\r]* |"))
14598 (c org-table-may-need-update))
14599 (replace-match (concat
14600 (substring (match-string 0) 1 -1)
14601 " |"))
14602 (goto-char pos)
14603 ;; noalign: if there were two spaces at the end, this field
14604 ;; does not determine the width of the column.
14605 (if noalign (setq org-table-may-need-update c)))
14606 (delete-char N))
14607 (delete-char N)
14608 (org-fix-tags-on-the-fly)))
14609
14610 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14611 (put 'org-self-insert-command 'delete-selection t)
14612 (put 'orgtbl-self-insert-command 'delete-selection t)
14613 (put 'org-delete-char 'delete-selection 'supersede)
14614 (put 'org-delete-backward-char 'delete-selection 'supersede)
14615 (put 'org-yank 'delete-selection 'yank)
14616
14617 ;; Make `flyspell-mode' delay after some commands
14618 (put 'org-self-insert-command 'flyspell-delayed t)
14619 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14620 (put 'org-delete-char 'flyspell-delayed t)
14621 (put 'org-delete-backward-char 'flyspell-delayed t)
14622
14623 ;; Make pabbrev-mode expand after org-mode commands
14624 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14625 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14626
14627 ;; How to do this: Measure non-white length of current string
14628 ;; If equal to column width, we should realign.
14629
14630 (defun org-remap (map &rest commands)
14631 "In MAP, remap the functions given in COMMANDS.
14632 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14633 (let (new old)
14634 (while commands
14635 (setq old (pop commands) new (pop commands))
14636 (if (fboundp 'command-remapping)
14637 (org-defkey map (vector 'remap old) new)
14638 (substitute-key-definition old new map global-map)))))
14639
14640 (when (eq org-enable-table-editor 'optimized)
14641 ;; If the user wants maximum table support, we need to hijack
14642 ;; some standard editing functions
14643 (org-remap org-mode-map
14644 'self-insert-command 'org-self-insert-command
14645 'delete-char 'org-delete-char
14646 'delete-backward-char 'org-delete-backward-char)
14647 (org-defkey org-mode-map "|" 'org-force-self-insert))
14648
14649 (defvar org-ctrl-c-ctrl-c-hook nil
14650 "Hook for functions attaching themselves to `C-c C-c'.
14651 This can be used to add additional functionality to the C-c C-c key which
14652 executes context-dependent commands.
14653 Each function will be called with no arguments. The function must check
14654 if the context is appropriate for it to act. If yes, it should do its
14655 thing and then return a non-nil value. If the context is wrong,
14656 just do nothing and return nil.")
14657
14658 (defvar org-tab-first-hook nil
14659 "Hook for functions to attach themselves to TAB.
14660 See `org-ctrl-c-ctrl-c-hook' for more information.
14661 This hook runs as the first action when TAB is pressed, even before
14662 `org-cycle' messes around with the `outline-regexp' to cater for
14663 inline tasks and plain list item folding.
14664 If any function in this hook returns t, not other actions like table
14665 field motion visibility cycling will be done.")
14666
14667 (defvar org-tab-after-check-for-table-hook nil
14668 "Hook for functions to attach themselves to TAB.
14669 See `org-ctrl-c-ctrl-c-hook' for more information.
14670 This hook runs after it has been established that the cursor is not in a
14671 table, but before checking if the cursor is in a headline or if global cycling
14672 should be done.
14673 If any function in this hook returns t, not other actions like visibility
14674 cycling will be done.")
14675
14676 (defvar org-tab-after-check-for-cycling-hook nil
14677 "Hook for functions to attach themselves to TAB.
14678 See `org-ctrl-c-ctrl-c-hook' for more information.
14679 This hook runs after it has been established that not table field motion and
14680 not visibility should be done because of current context. This is probably
14681 the place where a package like yasnippets can hook in.")
14682
14683 (defvar org-metaleft-hook nil
14684 "Hook for functions attaching themselves to `M-left'.
14685 See `org-ctrl-c-ctrl-c-hook' for more information.")
14686 (defvar org-metaright-hook nil
14687 "Hook for functions attaching themselves to `M-right'.
14688 See `org-ctrl-c-ctrl-c-hook' for more information.")
14689 (defvar org-metaup-hook nil
14690 "Hook for functions attaching themselves to `M-up'.
14691 See `org-ctrl-c-ctrl-c-hook' for more information.")
14692 (defvar org-metadown-hook nil
14693 "Hook for functions attaching themselves to `M-down'.
14694 See `org-ctrl-c-ctrl-c-hook' for more information.")
14695 (defvar org-shiftmetaleft-hook nil
14696 "Hook for functions attaching themselves to `M-S-left'.
14697 See `org-ctrl-c-ctrl-c-hook' for more information.")
14698 (defvar org-shiftmetaright-hook nil
14699 "Hook for functions attaching themselves to `M-S-right'.
14700 See `org-ctrl-c-ctrl-c-hook' for more information.")
14701 (defvar org-shiftmetaup-hook nil
14702 "Hook for functions attaching themselves to `M-S-up'.
14703 See `org-ctrl-c-ctrl-c-hook' for more information.")
14704 (defvar org-shiftmetadown-hook nil
14705 "Hook for functions attaching themselves to `M-S-down'.
14706 See `org-ctrl-c-ctrl-c-hook' for more information.")
14707 (defvar org-metareturn-hook nil
14708 "Hook for functions attaching themselves to `M-RET'.
14709 See `org-ctrl-c-ctrl-c-hook' for more information.")
14710
14711 (defun org-modifier-cursor-error ()
14712 "Throw an error, a modified cursor command was applied in wrong context."
14713 (error "This command is active in special context like tables, headlines or items"))
14714
14715 (defun org-shiftselect-error ()
14716 "Throw an error because Shift-Cursor command was applied in wrong context."
14717 (if (and (boundp 'shift-select-mode) shift-select-mode)
14718 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
14719 (error "This command works only in special context like headlines or timestamps")))
14720
14721 (defun org-call-for-shift-select (cmd)
14722 (let ((this-command-keys-shift-translated t))
14723 (call-interactively cmd)))
14724
14725 (defun org-shifttab (&optional arg)
14726 "Global visibility cycling or move to previous table field.
14727 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14728 on context.
14729 See the individual commands for more information."
14730 (interactive "P")
14731 (cond
14732 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14733 ((integerp arg)
14734 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
14735 (message "Content view to level: %d" arg)
14736 (org-content (prefix-numeric-value arg2))
14737 (setq org-cycle-global-status 'overview)))
14738 (t (call-interactively 'org-global-cycle))))
14739
14740 (defun org-shiftmetaleft ()
14741 "Promote subtree or delete table column.
14742 Calls `org-promote-subtree', `org-outdent-item',
14743 or `org-table-delete-column', depending on context.
14744 See the individual commands for more information."
14745 (interactive)
14746 (cond
14747 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14748 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14749 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14750 ((org-at-item-p) (call-interactively 'org-outdent-item))
14751 (t (org-modifier-cursor-error))))
14752
14753 (defun org-shiftmetaright ()
14754 "Demote subtree or insert table column.
14755 Calls `org-demote-subtree', `org-indent-item',
14756 or `org-table-insert-column', depending on context.
14757 See the individual commands for more information."
14758 (interactive)
14759 (cond
14760 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14761 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14762 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14763 ((org-at-item-p) (call-interactively 'org-indent-item))
14764 (t (org-modifier-cursor-error))))
14765
14766 (defun org-shiftmetaup (&optional arg)
14767 "Move subtree up or kill table row.
14768 Calls `org-move-subtree-up' or `org-table-kill-row' or
14769 `org-move-item-up' depending on context. See the individual commands
14770 for more information."
14771 (interactive "P")
14772 (cond
14773 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14774 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14775 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14776 ((org-at-item-p) (call-interactively 'org-move-item-up))
14777 (t (org-modifier-cursor-error))))
14778
14779 (defun org-shiftmetadown (&optional arg)
14780 "Move subtree down or insert table row.
14781 Calls `org-move-subtree-down' or `org-table-insert-row' or
14782 `org-move-item-down', depending on context. See the individual
14783 commands for more information."
14784 (interactive "P")
14785 (cond
14786 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14787 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14788 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14789 ((org-at-item-p) (call-interactively 'org-move-item-down))
14790 (t (org-modifier-cursor-error))))
14791
14792 (defun org-metaleft (&optional arg)
14793 "Promote heading or move table column to left.
14794 Calls `org-do-promote' or `org-table-move-column', depending on context.
14795 With no specific context, calls the Emacs default `backward-word'.
14796 See the individual commands for more information."
14797 (interactive "P")
14798 (cond
14799 ((run-hook-with-args-until-success 'org-metaleft-hook))
14800 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14801 ((or (org-on-heading-p)
14802 (and (org-region-active-p)
14803 (save-excursion
14804 (goto-char (region-beginning))
14805 (org-on-heading-p))))
14806 (call-interactively 'org-do-promote))
14807 ((or (org-at-item-p)
14808 (and (org-region-active-p)
14809 (save-excursion
14810 (goto-char (region-beginning))
14811 (org-at-item-p))))
14812 (call-interactively 'org-outdent-item))
14813 (t (call-interactively 'backward-word))))
14814
14815 (defun org-metaright (&optional arg)
14816 "Demote subtree or move table column to right.
14817 Calls `org-do-demote' or `org-table-move-column', depending on context.
14818 With no specific context, calls the Emacs default `forward-word'.
14819 See the individual commands for more information."
14820 (interactive "P")
14821 (cond
14822 ((run-hook-with-args-until-success 'org-metaright-hook))
14823 ((org-at-table-p) (call-interactively 'org-table-move-column))
14824 ((or (org-on-heading-p)
14825 (and (org-region-active-p)
14826 (save-excursion
14827 (goto-char (region-beginning))
14828 (org-on-heading-p))))
14829 (call-interactively 'org-do-demote))
14830 ((or (org-at-item-p)
14831 (and (org-region-active-p)
14832 (save-excursion
14833 (goto-char (region-beginning))
14834 (org-at-item-p))))
14835 (call-interactively 'org-indent-item))
14836 (t (call-interactively 'forward-word))))
14837
14838 (defun org-metaup (&optional arg)
14839 "Move subtree up or move table row up.
14840 Calls `org-move-subtree-up' or `org-table-move-row' or
14841 `org-move-item-up', depending on context. See the individual commands
14842 for more information."
14843 (interactive "P")
14844 (cond
14845 ((run-hook-with-args-until-success 'org-metaup-hook))
14846 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14847 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14848 ((org-at-item-p) (call-interactively 'org-move-item-up))
14849 (t (transpose-lines 1) (beginning-of-line -1))))
14850
14851 (defun org-metadown (&optional arg)
14852 "Move subtree down or move table row down.
14853 Calls `org-move-subtree-down' or `org-table-move-row' or
14854 `org-move-item-down', depending on context. See the individual
14855 commands for more information."
14856 (interactive "P")
14857 (cond
14858 ((run-hook-with-args-until-success 'org-metadown-hook))
14859 ((org-at-table-p) (call-interactively 'org-table-move-row))
14860 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14861 ((org-at-item-p) (call-interactively 'org-move-item-down))
14862 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14863
14864 (defun org-shiftup (&optional arg)
14865 "Increase item in timestamp or increase priority of current headline.
14866 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14867 depending on context. See the individual commands for more information."
14868 (interactive "P")
14869 (cond
14870 ((and org-support-shift-select (org-region-active-p))
14871 (org-call-for-shift-select 'previous-line))
14872 ((org-at-timestamp-p t)
14873 (call-interactively (if org-edit-timestamp-down-means-later
14874 'org-timestamp-down 'org-timestamp-up)))
14875 ((and (not (eq org-support-shift-select 'always))
14876 org-enable-priority-commands
14877 (org-on-heading-p))
14878 (call-interactively 'org-priority-up))
14879 ((and (not org-support-shift-select) (org-at-item-p))
14880 (call-interactively 'org-previous-item))
14881 ((org-clocktable-try-shift 'up arg))
14882 (org-support-shift-select
14883 (org-call-for-shift-select 'previous-line))
14884 (t (org-shiftselect-error))))
14885
14886 (defun org-shiftdown (&optional arg)
14887 "Decrease item in timestamp or decrease priority of current headline.
14888 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14889 depending on context. See the individual commands for more information."
14890 (interactive "P")
14891 (cond
14892 ((and org-support-shift-select (org-region-active-p))
14893 (org-call-for-shift-select 'next-line))
14894 ((org-at-timestamp-p t)
14895 (call-interactively (if org-edit-timestamp-down-means-later
14896 'org-timestamp-up 'org-timestamp-down)))
14897 ((and (not (eq org-support-shift-select 'always))
14898 org-enable-priority-commands
14899 (org-on-heading-p))
14900 (call-interactively 'org-priority-down))
14901 ((and (not org-support-shift-select) (org-at-item-p))
14902 (call-interactively 'org-next-item))
14903 ((org-clocktable-try-shift 'down arg))
14904 (org-support-shift-select
14905 (org-call-for-shift-select 'next-line))
14906 (t (org-shiftselect-error))))
14907
14908 (defun org-shiftright (&optional arg)
14909 "Cycle the thing at point or in the current line, depending on context.
14910 Depending on context, this does one of the following:
14911
14912 - switch a timestamp at point one day into the future
14913 - on a headline, switch to the next TODO keyword.
14914 - on an item, switch entire list to the next bullet type
14915 - on a property line, switch to the next allowed value
14916 - on a clocktable definition line, move time block into the future"
14917 (interactive "P")
14918 (cond
14919 ((and org-support-shift-select (org-region-active-p))
14920 (org-call-for-shift-select 'forward-char))
14921 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14922 ((and (not (eq org-support-shift-select 'always))
14923 (org-on-heading-p))
14924 (let ((org-inhibit-logging
14925 (not org-treat-S-cursor-todo-selection-as-state-change))
14926 (org-inhibit-blocking
14927 (not org-treat-S-cursor-todo-selection-as-state-change)))
14928 (org-call-with-arg 'org-todo 'right)))
14929 ((or (and org-support-shift-select
14930 (not (eq org-support-shift-select 'always))
14931 (org-at-item-bullet-p))
14932 (and (not org-support-shift-select) (org-at-item-p)))
14933 (org-call-with-arg 'org-cycle-list-bullet nil))
14934 ((and (not (eq org-support-shift-select 'always))
14935 (org-at-property-p))
14936 (call-interactively 'org-property-next-allowed-value))
14937 ((org-clocktable-try-shift 'right arg))
14938 (org-support-shift-select
14939 (org-call-for-shift-select 'forward-char))
14940 (t (org-shiftselect-error))))
14941
14942 (defun org-shiftleft (&optional arg)
14943 "Cycle the thing at point or in the current line, depending on context.
14944 Depending on context, this does one of the following:
14945
14946 - switch a timestamp at point one day into the past
14947 - on a headline, switch to the previous TODO keyword.
14948 - on an item, switch entire list to the previous bullet type
14949 - on a property line, switch to the previous allowed value
14950 - on a clocktable definition line, move time block into the past"
14951 (interactive "P")
14952 (cond
14953 ((and org-support-shift-select (org-region-active-p))
14954 (org-call-for-shift-select 'backward-char))
14955 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14956 ((and (not (eq org-support-shift-select 'always))
14957 (org-on-heading-p))
14958 (let ((org-inhibit-logging
14959 (not org-treat-S-cursor-todo-selection-as-state-change))
14960 (org-inhibit-blocking
14961 (not org-treat-S-cursor-todo-selection-as-state-change)))
14962 (org-call-with-arg 'org-todo 'left)))
14963 ((or (and org-support-shift-select
14964 (not (eq org-support-shift-select 'always))
14965 (org-at-item-bullet-p))
14966 (and (not org-support-shift-select) (org-at-item-p)))
14967 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14968 ((and (not (eq org-support-shift-select 'always))
14969 (org-at-property-p))
14970 (call-interactively 'org-property-previous-allowed-value))
14971 ((org-clocktable-try-shift 'left arg))
14972 (org-support-shift-select
14973 (org-call-for-shift-select 'backward-char))
14974 (t (org-shiftselect-error))))
14975
14976 (defun org-shiftcontrolright ()
14977 "Switch to next TODO set."
14978 (interactive)
14979 (cond
14980 ((and org-support-shift-select (org-region-active-p))
14981 (org-call-for-shift-select 'forward-word))
14982 ((and (not (eq org-support-shift-select 'always))
14983 (org-on-heading-p))
14984 (org-call-with-arg 'org-todo 'nextset))
14985 (org-support-shift-select
14986 (org-call-for-shift-select 'forward-word))
14987 (t (org-shiftselect-error))))
14988
14989 (defun org-shiftcontrolleft ()
14990 "Switch to previous TODO set."
14991 (interactive)
14992 (cond
14993 ((and org-support-shift-select (org-region-active-p))
14994 (org-call-for-shift-select 'backward-word))
14995 ((and (not (eq org-support-shift-select 'always))
14996 (org-on-heading-p))
14997 (org-call-with-arg 'org-todo 'previousset))
14998 (org-support-shift-select
14999 (org-call-for-shift-select 'backward-word))
15000 (t (org-shiftselect-error))))
15001
15002 (defun org-ctrl-c-ret ()
15003 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
15004 (interactive)
15005 (cond
15006 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
15007 (t (call-interactively 'org-insert-heading))))
15008
15009 (defun org-copy-special ()
15010 "Copy region in table or copy current subtree.
15011 Calls `org-table-copy' or `org-copy-subtree', depending on context.
15012 See the individual commands for more information."
15013 (interactive)
15014 (call-interactively
15015 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
15016
15017 (defun org-cut-special ()
15018 "Cut region in table or cut current subtree.
15019 Calls `org-table-copy' or `org-cut-subtree', depending on context.
15020 See the individual commands for more information."
15021 (interactive)
15022 (call-interactively
15023 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
15024
15025 (defun org-paste-special (arg)
15026 "Paste rectangular region into table, or past subtree relative to level.
15027 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
15028 See the individual commands for more information."
15029 (interactive "P")
15030 (if (org-at-table-p)
15031 (org-table-paste-rectangle)
15032 (org-paste-subtree arg)))
15033
15034 (defun org-edit-special ()
15035 "Call a special editor for the stuff at point.
15036 When at a table, call the formula editor with `org-table-edit-formulas'.
15037 When at the first line of an src example, call `org-edit-src-code'.
15038 When in an #+include line, visit the include file. Otherwise call
15039 `ffap' to visit the file at point."
15040 (interactive)
15041 (cond
15042 ((org-at-table-p)
15043 (call-interactively 'org-table-edit-formulas))
15044 ((save-excursion
15045 (beginning-of-line 1)
15046 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
15047 (find-file (org-trim (match-string 1))))
15048 ((org-edit-src-code))
15049 ((org-edit-fixed-width-region))
15050 (t (call-interactively 'ffap))))
15051
15052
15053 (defun org-ctrl-c-ctrl-c (&optional arg)
15054 "Set tags in headline, or update according to changed information at point.
15055
15056 This command does many different things, depending on context:
15057
15058 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
15059 this is what we do.
15060
15061 - If the cursor is on a statistics cookie, update it.
15062
15063 - If the cursor is in a headline, prompt for tags and insert them
15064 into the current line, aligned to `org-tags-column'. When called
15065 with prefix arg, realign all tags in the current buffer.
15066
15067 - If the cursor is in one of the special #+KEYWORD lines, this
15068 triggers scanning the buffer for these lines and updating the
15069 information.
15070
15071 - If the cursor is inside a table, realign the table. This command
15072 works even if the automatic table editor has been turned off.
15073
15074 - If the cursor is on a #+TBLFM line, re-apply the formulas to
15075 the entire table.
15076
15077 - If the cursor is at a footnote reference or definition, jump to
15078 the corresponding definition or references, respectively.
15079
15080 - If the cursor is a the beginning of a dynamic block, update it.
15081
15082 - If the cursor is inside a table created by the table.el package,
15083 activate that table.
15084
15085 - If the current buffer is a remember buffer, close note and file
15086 it. A prefix argument of 1 files to the default location
15087 without further interaction. A prefix argument of 2 files to
15088 the currently clocking task.
15089
15090 - If the cursor is on a <<<target>>>, update radio targets and corresponding
15091 links in this buffer.
15092
15093 - If the cursor is on a numbered item in a plain list, renumber the
15094 ordered list.
15095
15096 - If the cursor is on a checkbox, toggle it."
15097 (interactive "P")
15098 (let ((org-enable-table-editor t))
15099 (cond
15100 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
15101 org-occur-highlights
15102 org-latex-fragment-image-overlays)
15103 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
15104 (org-remove-occur-highlights)
15105 (org-remove-latex-fragment-image-overlays)
15106 (message "Temporary highlights/overlays removed from current buffer"))
15107 ((and (local-variable-p 'org-finish-function (current-buffer))
15108 (fboundp org-finish-function))
15109 (funcall org-finish-function))
15110 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
15111 ((org-at-property-p)
15112 (call-interactively 'org-property-action))
15113 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
15114 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
15115 (or (org-on-heading-p) (org-at-item-p)))
15116 (call-interactively 'org-update-statistics-cookies))
15117 ((org-on-heading-p) (call-interactively 'org-set-tags))
15118 ((org-at-table.el-p)
15119 (require 'table)
15120 (beginning-of-line 1)
15121 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
15122 (call-interactively 'table-recognize-table))
15123 ((org-at-table-p)
15124 (org-table-maybe-eval-formula)
15125 (if arg
15126 (call-interactively 'org-table-recalculate)
15127 (org-table-maybe-recalculate-line))
15128 (call-interactively 'org-table-align))
15129 ((or (org-footnote-at-reference-p)
15130 (org-footnote-at-definition-p))
15131 (call-interactively 'org-footnote-action))
15132 ((org-at-item-checkbox-p)
15133 (call-interactively 'org-toggle-checkbox))
15134 ((org-at-item-p)
15135 (if arg
15136 (call-interactively 'org-toggle-checkbox)
15137 (call-interactively 'org-maybe-renumber-ordered-list)))
15138 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
15139 ;; Dynamic block
15140 (beginning-of-line 1)
15141 (save-excursion (org-update-dblock)))
15142 ((save-excursion
15143 (beginning-of-line 1)
15144 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
15145 (cond
15146 ((equal (match-string 1) "TBLFM")
15147 ;; Recalculate the table before this line
15148 (save-excursion
15149 (beginning-of-line 1)
15150 (skip-chars-backward " \r\n\t")
15151 (if (org-at-table-p)
15152 (org-call-with-arg 'org-table-recalculate (or arg t)))))
15153 (t
15154 ; (org-set-regexps-and-options)
15155 ; (org-restart-font-lock)
15156 (let ((org-inhibit-startup t)) (org-mode-restart))
15157 (message "Local setup has been refreshed"))))
15158 ((org-clock-update-time-maybe))
15159 (t (error "C-c C-c can do nothing useful at this location")))))
15160
15161 (defun org-mode-restart ()
15162 "Restart Org-mode, to scan again for special lines.
15163 Also updates the keyword regular expressions."
15164 (interactive)
15165 (org-mode)
15166 (message "Org-mode restarted"))
15167
15168 (defun org-kill-note-or-show-branches ()
15169 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
15170 (interactive)
15171 (if (not org-finish-function)
15172 (call-interactively 'show-branches)
15173 (let ((org-note-abort t))
15174 (funcall org-finish-function))))
15175
15176 (defun org-return (&optional indent)
15177 "Goto next table row or insert a newline.
15178 Calls `org-table-next-row' or `newline', depending on context.
15179 See the individual commands for more information."
15180 (interactive)
15181 (cond
15182 ((bobp) (if indent (newline-and-indent) (newline)))
15183 ((org-at-table-p)
15184 (org-table-justify-field-maybe)
15185 (call-interactively 'org-table-next-row))
15186 ((and org-return-follows-link
15187 (eq (get-text-property (point) 'face) 'org-link))
15188 (call-interactively 'org-open-at-point))
15189 ((and (org-at-heading-p)
15190 (looking-at
15191 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
15192 (org-show-entry)
15193 (end-of-line 1)
15194 (newline))
15195 (t (if indent (newline-and-indent) (newline)))))
15196
15197 (defun org-return-indent ()
15198 "Goto next table row or insert a newline and indent.
15199 Calls `org-table-next-row' or `newline-and-indent', depending on
15200 context. See the individual commands for more information."
15201 (interactive)
15202 (org-return t))
15203
15204 (defun org-ctrl-c-star ()
15205 "Compute table, or change heading status of lines.
15206 Calls `org-table-recalculate' or `org-toggle-heading',
15207 depending on context."
15208 (interactive)
15209 (cond
15210 ((org-at-table-p)
15211 (call-interactively 'org-table-recalculate))
15212 (t
15213 ;; Convert all lines in region to list items
15214 (call-interactively 'org-toggle-heading))))
15215
15216 (defun org-ctrl-c-minus ()
15217 "Insert separator line in table or modify bullet status of line.
15218 Also turns a plain line or a region of lines into list items.
15219 Calls `org-table-insert-hline', `org-toggle-item', or
15220 `org-cycle-list-bullet', depending on context."
15221 (interactive)
15222 (cond
15223 ((org-at-table-p)
15224 (call-interactively 'org-table-insert-hline))
15225 ((org-region-active-p)
15226 (call-interactively 'org-toggle-item))
15227 ((org-in-item-p)
15228 (call-interactively 'org-cycle-list-bullet))
15229 (t
15230 (call-interactively 'org-toggle-item))))
15231
15232 (defun org-toggle-item ()
15233 "Convert headings or normal lines to items, items to normal lines.
15234 If there is no active region, only the current line is considered.
15235
15236 If the first line in the region is a headline, convert all headlines to items.
15237
15238 If the first line in the region is an item, convert all items to normal lines.
15239
15240 If the first line is normal text, add an item bullet to each line."
15241 (interactive)
15242 (let (l2 l beg end)
15243 (if (org-region-active-p)
15244 (setq beg (region-beginning) end (region-end))
15245 (setq beg (point-at-bol)
15246 end (min (1+ (point-at-eol)) (point-max))))
15247 (save-excursion
15248 (goto-char end)
15249 (setq l2 (org-current-line))
15250 (goto-char beg)
15251 (beginning-of-line 1)
15252 (setq l (1- (org-current-line)))
15253 (if (org-at-item-p)
15254 ;; We already have items, de-itemize
15255 (while (< (setq l (1+ l)) l2)
15256 (when (org-at-item-p)
15257 (goto-char (match-beginning 2))
15258 (delete-region (match-beginning 2) (match-end 2))
15259 (and (looking-at "[ \t]+") (replace-match "")))
15260 (beginning-of-line 2))
15261 (if (org-on-heading-p)
15262 ;; Headings, convert to items
15263 (while (< (setq l (1+ l)) l2)
15264 (if (looking-at org-outline-regexp)
15265 (replace-match "- " t t))
15266 (beginning-of-line 2))
15267 ;; normal lines, turn them into items
15268 (while (< (setq l (1+ l)) l2)
15269 (unless (org-at-item-p)
15270 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15271 (replace-match "\\1- \\2")))
15272 (beginning-of-line 2)))))))
15273
15274 (defun org-toggle-heading (&optional nstars)
15275 "Convert headings to normal text, or items or text to headings.
15276 If there is no active region, only the current line is considered.
15277
15278 If the first line is a heading, remove the stars from all headlines
15279 in the region.
15280
15281 If the first line is a plain list item, turn all plain list items
15282 into headings.
15283
15284 If the first line is a normal line, turn each and every line in the
15285 region into a heading.
15286
15287 When converting a line into a heading, the number of stars is chosen
15288 such that the lines become children of the current entry. However,
15289 when a prefix argument is given, its value determines the number of
15290 stars to add."
15291 (interactive "P")
15292 (let (l2 l itemp beg end)
15293 (if (org-region-active-p)
15294 (setq beg (region-beginning) end (region-end))
15295 (setq beg (point-at-bol)
15296 end (min (1+ (point-at-eol)) (point-max))))
15297 (save-excursion
15298 (goto-char end)
15299 (setq l2 (org-current-line))
15300 (goto-char beg)
15301 (beginning-of-line 1)
15302 (setq l (1- (org-current-line)))
15303 (if (org-on-heading-p)
15304 ;; We already have headlines, de-star them
15305 (while (< (setq l (1+ l)) l2)
15306 (when (org-on-heading-p t)
15307 (and (looking-at outline-regexp) (replace-match "")))
15308 (beginning-of-line 2))
15309 (setq itemp (org-at-item-p))
15310 (let* ((stars
15311 (if nstars
15312 (make-string (prefix-numeric-value current-prefix-arg)
15313 ?*)
15314 (save-excursion
15315 (if (re-search-backward org-complex-heading-regexp nil t)
15316 (match-string 1) ""))))
15317 (add-stars (cond (nstars "")
15318 ((equal stars "") "*")
15319 (org-odd-levels-only "**")
15320 (t "*")))
15321 (rpl (concat stars add-stars " ")))
15322 (while (< (setq l (1+ l)) l2)
15323 (if itemp
15324 (and (org-at-item-p) (replace-match rpl t t))
15325 (unless (org-on-heading-p)
15326 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
15327 (replace-match (concat rpl (match-string 2))))))
15328 (beginning-of-line 2)))))))
15329
15330 (defun org-meta-return (&optional arg)
15331 "Insert a new heading or wrap a region in a table.
15332 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
15333 See the individual commands for more information."
15334 (interactive "P")
15335 (cond
15336 ((run-hook-with-args-until-success 'org-metareturn-hook))
15337 ((org-at-table-p)
15338 (call-interactively 'org-table-wrap-region))
15339 (t (call-interactively 'org-insert-heading))))
15340
15341 ;;; Menu entries
15342
15343 ;; Define the Org-mode menus
15344 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15345 '("Tbl"
15346 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15347 ["Next Field" org-cycle (org-at-table-p)]
15348 ["Previous Field" org-shifttab (org-at-table-p)]
15349 ["Next Row" org-return (org-at-table-p)]
15350 "--"
15351 ["Blank Field" org-table-blank-field (org-at-table-p)]
15352 ["Edit Field" org-table-edit-field (org-at-table-p)]
15353 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15354 "--"
15355 ("Column"
15356 ["Move Column Left" org-metaleft (org-at-table-p)]
15357 ["Move Column Right" org-metaright (org-at-table-p)]
15358 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15359 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15360 ("Row"
15361 ["Move Row Up" org-metaup (org-at-table-p)]
15362 ["Move Row Down" org-metadown (org-at-table-p)]
15363 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15364 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15365 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15366 "--"
15367 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15368 ("Rectangle"
15369 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15370 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15371 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15372 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15373 "--"
15374 ("Calculate"
15375 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15376 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15377 ["Edit Formulas" org-edit-special (org-at-table-p)]
15378 "--"
15379 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15380 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15381 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15382 "--"
15383 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15384 "--"
15385 ["Sum Column/Rectangle" org-table-sum
15386 (or (org-at-table-p) (org-region-active-p))]
15387 ["Which Column?" org-table-current-column (org-at-table-p)])
15388 ["Debug Formulas"
15389 org-table-toggle-formula-debugger
15390 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15391 ["Show Col/Row Numbers"
15392 org-table-toggle-coordinate-overlays
15393 :style toggle
15394 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15395 "--"
15396 ["Create" org-table-create (and (not (org-at-table-p))
15397 org-enable-table-editor)]
15398 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15399 ["Import from File" org-table-import (not (org-at-table-p))]
15400 ["Export to File" org-table-export (org-at-table-p)]
15401 "--"
15402 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15403
15404 (easy-menu-define org-org-menu org-mode-map "Org menu"
15405 '("Org"
15406 ("Show/Hide"
15407 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15408 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15409 ["Sparse Tree..." org-sparse-tree t]
15410 ["Reveal Context" org-reveal t]
15411 ["Show All" show-all t]
15412 "--"
15413 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15414 "--"
15415 ["New Heading" org-insert-heading t]
15416 ("Navigate Headings"
15417 ["Up" outline-up-heading t]
15418 ["Next" outline-next-visible-heading t]
15419 ["Previous" outline-previous-visible-heading t]
15420 ["Next Same Level" outline-forward-same-level t]
15421 ["Previous Same Level" outline-backward-same-level t]
15422 "--"
15423 ["Jump" org-goto t])
15424 ("Edit Structure"
15425 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15426 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15427 "--"
15428 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15429 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15430 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15431 "--"
15432 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15433 "--"
15434 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15435 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15436 ["Demote Heading" org-metaright (not (org-at-table-p))]
15437 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15438 "--"
15439 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15440 "--"
15441 ["Convert to odd levels" org-convert-to-odd-levels t]
15442 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15443 ("Editing"
15444 ["Emphasis..." org-emphasize t]
15445 ["Edit Source Example" org-edit-special t]
15446 "--"
15447 ["Footnote new/jump" org-footnote-action t]
15448 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15449 ("Archive"
15450 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15451 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
15452 ; :active t :keys "C-u C-c C-x C-a"]
15453 ["Sparse trees open ARCHIVE trees"
15454 (setq org-sparse-tree-open-archived-trees
15455 (not org-sparse-tree-open-archived-trees))
15456 :style toggle :selected org-sparse-tree-open-archived-trees]
15457 ["Cycling opens ARCHIVE trees"
15458 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15459 :style toggle :selected org-cycle-open-archived-trees]
15460 "--"
15461 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
15462 ["Move Subtree to Archive" org-advertized-archive-subtree t]
15463 ; ["Check and Move Children" (org-archive-subtree '(4))
15464 ; :active t :keys "C-u C-c C-x C-s"]
15465 )
15466 "--"
15467 ("Hyperlinks"
15468 ["Store Link (Global)" org-store-link t]
15469 ["Find existing link to here" org-occur-link-in-agenda-files t]
15470 ["Insert Link" org-insert-link t]
15471 ["Follow Link" org-open-at-point t]
15472 "--"
15473 ["Next link" org-next-link t]
15474 ["Previous link" org-previous-link t]
15475 "--"
15476 ["Descriptive Links"
15477 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15478 :style radio
15479 :selected (member '(org-link) buffer-invisibility-spec)]
15480 ["Literal Links"
15481 (progn
15482 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15483 :style radio
15484 :selected (not (member '(org-link) buffer-invisibility-spec))])
15485 "--"
15486 ("TODO Lists"
15487 ["TODO/DONE/-" org-todo t]
15488 ("Select keyword"
15489 ["Next keyword" org-shiftright (org-on-heading-p)]
15490 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15491 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15492 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15493 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15494 ["Show TODO Tree" org-show-todo-tree t]
15495 ["Global TODO list" org-todo-list t]
15496 "--"
15497 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15498 :selected org-enforce-todo-dependencies :style toggle :active t]
15499 "Settings for tree at point"
15500 ["Do Children sequentially" org-toggle-ordered-property :style radio
15501 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15502 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15503 ["Do Children parallel" org-toggle-ordered-property :style radio
15504 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15505 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15506 "--"
15507 ["Set Priority" org-priority t]
15508 ["Priority Up" org-shiftup t]
15509 ["Priority Down" org-shiftdown t]
15510 "--"
15511 ["Get news from all feeds" org-feed-update-all t]
15512 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15513 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15514 ("TAGS and Properties"
15515 ["Set Tags" org-set-tags-command t]
15516 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15517 "--"
15518 ["Set property" org-set-property t]
15519 ["Column view of properties" org-columns t]
15520 ["Insert Column View DBlock" org-insert-columns-dblock t])
15521 ("Dates and Scheduling"
15522 ["Timestamp" org-time-stamp t]
15523 ["Timestamp (inactive)" org-time-stamp-inactive t]
15524 ("Change Date"
15525 ["1 Day Later" org-shiftright t]
15526 ["1 Day Earlier" org-shiftleft t]
15527 ["1 ... Later" org-shiftup t]
15528 ["1 ... Earlier" org-shiftdown t])
15529 ["Compute Time Range" org-evaluate-time-range t]
15530 ["Schedule Item" org-schedule t]
15531 ["Deadline" org-deadline t]
15532 "--"
15533 ["Custom time format" org-toggle-time-stamp-overlays
15534 :style radio :selected org-display-custom-times]
15535 "--"
15536 ["Goto Calendar" org-goto-calendar t]
15537 ["Date from Calendar" org-date-from-calendar t]
15538 "--"
15539 ["Start/Restart Timer" org-timer-start t]
15540 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15541 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15542 ["Insert Timer String" org-timer t]
15543 ["Insert Timer Item" org-timer-item t])
15544 ("Logging work"
15545 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15546 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15547 ["Clock out" org-clock-out t]
15548 ["Clock cancel" org-clock-cancel t]
15549 "--"
15550 ["Mark as default task" org-clock-mark-default-task t]
15551 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15552 ["Goto running clock" org-clock-goto t]
15553 "--"
15554 ["Display times" org-clock-display t]
15555 ["Create clock table" org-clock-report t]
15556 "--"
15557 ["Record DONE time"
15558 (progn (setq org-log-done (not org-log-done))
15559 (message "Switching to %s will %s record a timestamp"
15560 (car org-done-keywords)
15561 (if org-log-done "automatically" "not")))
15562 :style toggle :selected org-log-done])
15563 "--"
15564 ["Agenda Command..." org-agenda t]
15565 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15566 ("File List for Agenda")
15567 ("Special views current file"
15568 ["TODO Tree" org-show-todo-tree t]
15569 ["Check Deadlines" org-check-deadlines t]
15570 ["Timeline" org-timeline t]
15571 ["Tags/Property tree" org-match-sparse-tree t])
15572 "--"
15573 ["Export/Publish..." org-export t]
15574 ("LaTeX"
15575 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15576 :selected org-cdlatex-mode]
15577 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15578 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15579 ["Modify math symbol" org-cdlatex-math-modify
15580 (org-inside-LaTeX-fragment-p)]
15581 ["Insert citation" org-reftex-citation t]
15582 "--"
15583 ["Export LaTeX fragments as images"
15584 (if (featurep 'org-exp)
15585 (setq org-export-with-LaTeX-fragments
15586 (not org-export-with-LaTeX-fragments))
15587 (require 'org-exp))
15588 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15589 org-export-with-LaTeX-fragments)])
15590 "--"
15591 ("MobileOrg"
15592 ["Push Files and Views" org-mobile-push t]
15593 ["Get Captured and Flagged" org-mobile-pull t]
15594 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
15595 "--"
15596 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
15597 "--"
15598 ("Documentation"
15599 ["Show Version" org-version t]
15600 ["Info Documentation" org-info t])
15601 ("Customize"
15602 ["Browse Org Group" org-customize t]
15603 "--"
15604 ["Expand This Menu" org-create-customize-menu
15605 (fboundp 'customize-menu-create)])
15606 ["Send bug report" org-submit-bug-report t]
15607 "--"
15608 ("Refresh/Reload"
15609 ["Refresh setup current buffer" org-mode-restart t]
15610 ["Reload Org (after update)" org-reload t]
15611 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15612 ))
15613
15614 (defun org-info (&optional node)
15615 "Read documentation for Org-mode in the info system.
15616 With optional NODE, go directly to that node."
15617 (interactive)
15618 (info (format "(org)%s" (or node ""))))
15619
15620 ;;;###autoload
15621 (defun org-submit-bug-report ()
15622 "Submit a bug report on Org-mode via mail.
15623
15624 Don't hesitate to report any problems or inaccurate documentation.
15625
15626 If you don't have setup sending mail from (X)Emacs, please copy the
15627 output buffer into your mail program, as it gives us important
15628 information about your Org-mode version and configuration."
15629 (interactive)
15630 (require 'reporter)
15631 (org-load-modules-maybe)
15632 (org-require-autoloaded-modules)
15633 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
15634 (reporter-submit-bug-report
15635 "emacs-orgmode@gnu.org"
15636 (org-version)
15637 (let (list)
15638 (save-window-excursion
15639 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
15640 (delete-other-windows)
15641 (erase-buffer)
15642 (insert "You are about to submit a bug report to the Org-mode mailing list.
15643
15644 We would like to add your full Org-mode and Outline configuration to the
15645 bug report. This greatly simplifies the work of the maintainer and
15646 other experts on the mailing list.
15647
15648 HOWEVER, some variables you have customized may contain private
15649 information. The names of customers, colleagues, or friends, might
15650 appear in the form of file names, tags, todo states, or search strings.
15651 If you answer yes to the prompt, you might want to check and remove
15652 such private information before sending the email.")
15653 (add-text-properties (point-min) (point-max) '(face org-warning))
15654 (when (yes-or-no-p "Include your Org-mode configuration ")
15655 (mapatoms
15656 (lambda (v)
15657 (and (boundp v)
15658 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
15659 (or (and (symbol-value v)
15660 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
15661 (and
15662 (get v 'custom-type) (get v 'standard-value)
15663 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
15664 (push v list)))))
15665 (kill-buffer (get-buffer "*Warn about privacy*"))
15666 list))
15667 nil nil
15668 "Remember to cover the basics, that is, what you expected to happen and
15669 what in fact did happen. You don't know how to make a good report? See
15670
15671 http://orgmode.org/manual/Feedback.html#Feedback
15672
15673 Your bug report will be posted to the Org-mode mailing list.
15674 ------------------------------------------------------------------------")))
15675
15676 (defun org-install-agenda-files-menu ()
15677 (let ((bl (buffer-list)))
15678 (save-excursion
15679 (while bl
15680 (set-buffer (pop bl))
15681 (if (org-mode-p) (setq bl nil)))
15682 (when (org-mode-p)
15683 (easy-menu-change
15684 '("Org") "File List for Agenda"
15685 (append
15686 (list
15687 ["Edit File List" (org-edit-agenda-file-list) t]
15688 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15689 ["Remove Current File from List" org-remove-file t]
15690 ["Cycle through agenda files" org-cycle-agenda-files t]
15691 ["Occur in all agenda files" org-occur-in-agenda-files t]
15692 "--")
15693 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15694
15695 ;;;; Documentation
15696
15697 ;;;###autoload
15698 (defun org-require-autoloaded-modules ()
15699 (interactive)
15700 (mapc 'require
15701 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15702 org-docbook org-exp org-html org-icalendar
15703 org-id org-latex
15704 org-publish org-remember org-table
15705 org-timer org-xoxo)))
15706
15707 ;;;###autoload
15708 (defun org-reload (&optional uncompiled)
15709 "Reload all org lisp files.
15710 With prefix arg UNCOMPILED, load the uncompiled versions."
15711 (interactive "P")
15712 (require 'find-func)
15713 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15714 (dir-org (file-name-directory (org-find-library-name "org")))
15715 (dir-org-contrib (ignore-errors
15716 (file-name-directory
15717 (org-find-library-name "org-contribdir"))))
15718 (files
15719 (append (directory-files dir-org t file-re)
15720 (and dir-org-contrib
15721 (directory-files dir-org-contrib t file-re))))
15722 (remove-re (concat (if (featurep 'xemacs)
15723 "org-colview" "org-colview-xemacs")
15724 "\\'")))
15725 (setq files (mapcar 'file-name-sans-extension files))
15726 (setq files (mapcar
15727 (lambda (x) (if (string-match remove-re x) nil x))
15728 files))
15729 (setq files (delq nil files))
15730 (mapc
15731 (lambda (f)
15732 (when (featurep (intern (file-name-nondirectory f)))
15733 (if (and (not uncompiled)
15734 (file-exists-p (concat f ".elc")))
15735 (load (concat f ".elc") nil nil t)
15736 (load (concat f ".el") nil nil t))))
15737 files))
15738 (org-version))
15739
15740 ;;;###autoload
15741 (defun org-customize ()
15742 "Call the customize function with org as argument."
15743 (interactive)
15744 (org-load-modules-maybe)
15745 (org-require-autoloaded-modules)
15746 (customize-browse 'org))
15747
15748 (defun org-create-customize-menu ()
15749 "Create a full customization menu for Org-mode, insert it into the menu."
15750 (interactive)
15751 (org-load-modules-maybe)
15752 (org-require-autoloaded-modules)
15753 (if (fboundp 'customize-menu-create)
15754 (progn
15755 (easy-menu-change
15756 '("Org") "Customize"
15757 `(["Browse Org group" org-customize t]
15758 "--"
15759 ,(customize-menu-create 'org)
15760 ["Set" Custom-set t]
15761 ["Save" Custom-save t]
15762 ["Reset to Current" Custom-reset-current t]
15763 ["Reset to Saved" Custom-reset-saved t]
15764 ["Reset to Standard Settings" Custom-reset-standard t]))
15765 (message "\"Org\"-menu now contains full customization menu"))
15766 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15767
15768 ;;;; Miscellaneous stuff
15769
15770 ;;; Generally useful functions
15771
15772 (defun org-get-at-bol (property)
15773 "Get text property PROPERTY at beginning of line."
15774 (get-text-property (point-at-bol) property))
15775
15776 (defun org-find-text-property-in-string (prop s)
15777 "Return the first non-nil value of property PROP in string S."
15778 (or (get-text-property 0 prop s)
15779 (get-text-property (or (next-single-property-change 0 prop s) 0)
15780 prop s)))
15781
15782 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15783 "Display the given MESSAGE as a warning."
15784 (if (fboundp 'display-warning)
15785 (display-warning 'org message
15786 (if (featurep 'xemacs)
15787 'warning
15788 :warning))
15789 (let ((buf (get-buffer-create "*Org warnings*")))
15790 (with-current-buffer buf
15791 (goto-char (point-max))
15792 (insert "Warning (Org): " message)
15793 (unless (bolp)
15794 (newline)))
15795 (display-buffer buf)
15796 (sit-for 0))))
15797
15798 (defun org-in-commented-line ()
15799 "Is point in a line starting with `#'?"
15800 (equal (char-after (point-at-bol)) ?#))
15801
15802 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15803 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15804 (if (and marker (marker-buffer marker)
15805 (buffer-live-p (marker-buffer marker)))
15806 (progn
15807 (switch-to-buffer (marker-buffer marker))
15808 (if (or (> marker (point-max)) (< marker (point-min)))
15809 (widen))
15810 (goto-char marker)
15811 (org-show-context 'org-goto))
15812 (if bookmark
15813 (bookmark-jump bookmark)
15814 (error "Cannot find location"))))
15815
15816 (defun org-quote-csv-field (s)
15817 "Quote field for inclusion in CSV material."
15818 (if (string-match "[\",]" s)
15819 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15820 s))
15821
15822 (defun org-plist-delete (plist property)
15823 "Delete PROPERTY from PLIST.
15824 This is in contrast to merely setting it to 0."
15825 (let (p)
15826 (while plist
15827 (if (not (eq property (car plist)))
15828 (setq p (plist-put p (car plist) (nth 1 plist))))
15829 (setq plist (cddr plist)))
15830 p))
15831
15832 (defun org-force-self-insert (N)
15833 "Needed to enforce self-insert under remapping."
15834 (interactive "p")
15835 (self-insert-command N))
15836
15837 (defun org-string-width (s)
15838 "Compute width of string, ignoring invisible characters.
15839 This ignores character with invisibility property `org-link', and also
15840 characters with property `org-cwidth', because these will become invisible
15841 upon the next fontification round."
15842 (let (b l)
15843 (when (or (eq t buffer-invisibility-spec)
15844 (assq 'org-link buffer-invisibility-spec))
15845 (while (setq b (text-property-any 0 (length s)
15846 'invisible 'org-link s))
15847 (setq s (concat (substring s 0 b)
15848 (substring s (or (next-single-property-change
15849 b 'invisible s) (length s)))))))
15850 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15851 (setq s (concat (substring s 0 b)
15852 (substring s (or (next-single-property-change
15853 b 'org-cwidth s) (length s))))))
15854 (setq l (string-width s) b -1)
15855 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15856 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15857 l))
15858
15859 (defun org-get-indentation (&optional line)
15860 "Get the indentation of the current line, interpreting tabs.
15861 When LINE is given, assume it represents a line and compute its indentation."
15862 (if line
15863 (if (string-match "^ *" (org-remove-tabs line))
15864 (match-end 0))
15865 (save-excursion
15866 (beginning-of-line 1)
15867 (skip-chars-forward " \t")
15868 (current-column))))
15869
15870 (defun org-remove-tabs (s &optional width)
15871 "Replace tabulators in S with spaces.
15872 Assumes that s is a single line, starting in column 0."
15873 (setq width (or width tab-width))
15874 (while (string-match "\t" s)
15875 (setq s (replace-match
15876 (make-string
15877 (- (* width (/ (+ (match-beginning 0) width) width))
15878 (match-beginning 0)) ?\ )
15879 t t s)))
15880 s)
15881
15882 (defun org-fix-indentation (line ind)
15883 "Fix indentation in LINE.
15884 IND is a cons cell with target and minimum indentation.
15885 If the current indentation in LINE is smaller than the minimum,
15886 leave it alone. If it is larger than ind, set it to the target."
15887 (let* ((l (org-remove-tabs line))
15888 (i (org-get-indentation l))
15889 (i1 (car ind)) (i2 (cdr ind)))
15890 (if (>= i i2) (setq l (substring line i2)))
15891 (if (> i1 0)
15892 (concat (make-string i1 ?\ ) l)
15893 l)))
15894
15895 (defun org-remove-indentation (code &optional n)
15896 "Remove the maximum common indentation from the lines in CODE.
15897 N may optionally be the number of spaces to remove."
15898 (with-temp-buffer
15899 (insert code)
15900 (org-do-remove-indentation n)
15901 (buffer-string)))
15902
15903 (defun org-do-remove-indentation (&optional n)
15904 "Remove the maximum common indentation from the buffer."
15905 (untabify (point-min) (point-max))
15906 (let ((min 10000) re)
15907 (if n
15908 (setq min n)
15909 (goto-char (point-min))
15910 (while (re-search-forward "^ *[^ \n]" nil t)
15911 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
15912 (unless (or (= min 0) (= min 10000))
15913 (setq re (format "^ \\{%d\\}" min))
15914 (goto-char (point-min))
15915 (while (re-search-forward re nil t)
15916 (replace-match "")
15917 (end-of-line 1))
15918 min)))
15919
15920 (defun org-base-buffer (buffer)
15921 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15922 (if (not buffer)
15923 buffer
15924 (or (buffer-base-buffer buffer)
15925 buffer)))
15926
15927 (defun org-trim (s)
15928 "Remove whitespace at beginning and end of string."
15929 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15930 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15931 s)
15932
15933 (defun org-wrap (string &optional width lines)
15934 "Wrap string to either a number of lines, or a width in characters.
15935 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15936 that costs. If there is a word longer than WIDTH, the text is actually
15937 wrapped to the length of that word.
15938 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15939 many lines, whatever width that takes.
15940 The return value is a list of lines, without newlines at the end."
15941 (let* ((words (org-split-string string "[ \t\n]+"))
15942 (maxword (apply 'max (mapcar 'org-string-width words)))
15943 w ll)
15944 (cond (width
15945 (org-do-wrap words (max maxword width)))
15946 (lines
15947 (setq w maxword)
15948 (setq ll (org-do-wrap words maxword))
15949 (if (<= (length ll) lines)
15950 ll
15951 (setq ll words)
15952 (while (> (length ll) lines)
15953 (setq w (1+ w))
15954 (setq ll (org-do-wrap words w)))
15955 ll))
15956 (t (error "Cannot wrap this")))))
15957
15958 (defun org-do-wrap (words width)
15959 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15960 (let (lines line)
15961 (while words
15962 (setq line (pop words))
15963 (while (and words (< (+ (length line) (length (car words))) width))
15964 (setq line (concat line " " (pop words))))
15965 (setq lines (push line lines)))
15966 (nreverse lines)))
15967
15968 (defun org-split-string (string &optional separators)
15969 "Splits STRING into substrings at SEPARATORS.
15970 No empty strings are returned if there are matches at the beginning
15971 and end of string."
15972 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15973 (start 0)
15974 notfirst
15975 (list nil))
15976 (while (and (string-match rexp string
15977 (if (and notfirst
15978 (= start (match-beginning 0))
15979 (< start (length string)))
15980 (1+ start) start))
15981 (< (match-beginning 0) (length string)))
15982 (setq notfirst t)
15983 (or (eq (match-beginning 0) 0)
15984 (and (eq (match-beginning 0) (match-end 0))
15985 (eq (match-beginning 0) start))
15986 (setq list
15987 (cons (substring string start (match-beginning 0))
15988 list)))
15989 (setq start (match-end 0)))
15990 (or (eq start (length string))
15991 (setq list
15992 (cons (substring string start)
15993 list)))
15994 (nreverse list)))
15995
15996 (defun org-quote-vert (s)
15997 "Replace \"|\" with \"\\vert\"."
15998 (while (string-match "|" s)
15999 (setq s (replace-match "\\vert" t t s)))
16000 s)
16001
16002 (defun org-uuidgen-p (s)
16003 "Is S an ID created by UUIDGEN?"
16004 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
16005
16006 (defun org-context ()
16007 "Return a list of contexts of the current cursor position.
16008 If several contexts apply, all are returned.
16009 Each context entry is a list with a symbol naming the context, and
16010 two positions indicating start and end of the context. Possible
16011 contexts are:
16012
16013 :headline anywhere in a headline
16014 :headline-stars on the leading stars in a headline
16015 :todo-keyword on a TODO keyword (including DONE) in a headline
16016 :tags on the TAGS in a headline
16017 :priority on the priority cookie in a headline
16018 :item on the first line of a plain list item
16019 :item-bullet on the bullet/number of a plain list item
16020 :checkbox on the checkbox in a plain list item
16021 :table in an org-mode table
16022 :table-special on a special filed in a table
16023 :table-table in a table.el table
16024 :link on a hyperlink
16025 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
16026 :target on a <<target>>
16027 :radio-target on a <<<radio-target>>>
16028 :latex-fragment on a LaTeX fragment
16029 :latex-preview on a LaTeX fragment with overlayed preview image
16030
16031 This function expects the position to be visible because it uses font-lock
16032 faces as a help to recognize the following contexts: :table-special, :link,
16033 and :keyword."
16034 (let* ((f (get-text-property (point) 'face))
16035 (faces (if (listp f) f (list f)))
16036 (p (point)) clist o)
16037 ;; First the large context
16038 (cond
16039 ((org-on-heading-p t)
16040 (push (list :headline (point-at-bol) (point-at-eol)) clist)
16041 (when (progn
16042 (beginning-of-line 1)
16043 (looking-at org-todo-line-tags-regexp))
16044 (push (org-point-in-group p 1 :headline-stars) clist)
16045 (push (org-point-in-group p 2 :todo-keyword) clist)
16046 (push (org-point-in-group p 4 :tags) clist))
16047 (goto-char p)
16048 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
16049 (if (looking-at "\\[#[A-Z0-9]\\]")
16050 (push (org-point-in-group p 0 :priority) clist)))
16051
16052 ((org-at-item-p)
16053 (push (org-point-in-group p 2 :item-bullet) clist)
16054 (push (list :item (point-at-bol)
16055 (save-excursion (org-end-of-item) (point)))
16056 clist)
16057 (and (org-at-item-checkbox-p)
16058 (push (org-point-in-group p 0 :checkbox) clist)))
16059
16060 ((org-at-table-p)
16061 (push (list :table (org-table-begin) (org-table-end)) clist)
16062 (if (memq 'org-formula faces)
16063 (push (list :table-special
16064 (previous-single-property-change p 'face)
16065 (next-single-property-change p 'face)) clist)))
16066 ((org-at-table-p 'any)
16067 (push (list :table-table) clist)))
16068 (goto-char p)
16069
16070 ;; Now the small context
16071 (cond
16072 ((org-at-timestamp-p)
16073 (push (org-point-in-group p 0 :timestamp) clist))
16074 ((memq 'org-link faces)
16075 (push (list :link
16076 (previous-single-property-change p 'face)
16077 (next-single-property-change p 'face)) clist))
16078 ((memq 'org-special-keyword faces)
16079 (push (list :keyword
16080 (previous-single-property-change p 'face)
16081 (next-single-property-change p 'face)) clist))
16082 ((org-on-target-p)
16083 (push (org-point-in-group p 0 :target) clist)
16084 (goto-char (1- (match-beginning 0)))
16085 (if (looking-at org-radio-target-regexp)
16086 (push (org-point-in-group p 0 :radio-target) clist))
16087 (goto-char p))
16088 ((setq o (car (delq nil
16089 (mapcar
16090 (lambda (x)
16091 (if (memq x org-latex-fragment-image-overlays) x))
16092 (org-overlays-at (point))))))
16093 (push (list :latex-fragment
16094 (org-overlay-start o) (org-overlay-end o)) clist)
16095 (push (list :latex-preview
16096 (org-overlay-start o) (org-overlay-end o)) clist))
16097 ((org-inside-LaTeX-fragment-p)
16098 ;; FIXME: positions wrong.
16099 (push (list :latex-fragment (point) (point)) clist)))
16100
16101 (setq clist (nreverse (delq nil clist)))
16102 clist))
16103
16104 ;; FIXME: Compare with at-regexp-p Do we need both?
16105 (defun org-in-regexp (re &optional nlines visually)
16106 "Check if point is inside a match of regexp.
16107 Normally only the current line is checked, but you can include NLINES extra
16108 lines both before and after point into the search.
16109 If VISUALLY is set, require that the cursor is not after the match but
16110 really on, so that the block visually is on the match."
16111 (catch 'exit
16112 (let ((pos (point))
16113 (eol (point-at-eol (+ 1 (or nlines 0))))
16114 (inc (if visually 1 0)))
16115 (save-excursion
16116 (beginning-of-line (- 1 (or nlines 0)))
16117 (while (re-search-forward re eol t)
16118 (if (and (<= (match-beginning 0) pos)
16119 (>= (+ inc (match-end 0)) pos))
16120 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
16121
16122 (defun org-at-regexp-p (regexp)
16123 "Is point inside a match of REGEXP in the current line?"
16124 (catch 'exit
16125 (save-excursion
16126 (let ((pos (point)) (end (point-at-eol)))
16127 (beginning-of-line 1)
16128 (while (re-search-forward regexp end t)
16129 (if (and (<= (match-beginning 0) pos)
16130 (>= (match-end 0) pos))
16131 (throw 'exit t)))
16132 nil))))
16133
16134 (defun org-occur-in-agenda-files (regexp &optional nlines)
16135 "Call `multi-occur' with buffers for all agenda files."
16136 (interactive "sOrg-files matching: \np")
16137 (let* ((files (org-agenda-files))
16138 (tnames (mapcar 'file-truename files))
16139 (extra org-agenda-text-search-extra-files)
16140 f)
16141 (when (eq (car extra) 'agenda-archives)
16142 (setq extra (cdr extra))
16143 (setq files (org-add-archive-files files)))
16144 (while (setq f (pop extra))
16145 (unless (member (file-truename f) tnames)
16146 (add-to-list 'files f 'append)
16147 (add-to-list 'tnames (file-truename f) 'append)))
16148 (multi-occur
16149 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
16150 regexp)))
16151
16152 (if (boundp 'occur-mode-find-occurrence-hook)
16153 ;; Emacs 23
16154 (add-hook 'occur-mode-find-occurrence-hook
16155 (lambda ()
16156 (when (org-mode-p)
16157 (org-reveal))))
16158 ;; Emacs 22
16159 (defadvice occur-mode-goto-occurrence
16160 (after org-occur-reveal activate)
16161 (and (org-mode-p) (org-reveal)))
16162 (defadvice occur-mode-goto-occurrence-other-window
16163 (after org-occur-reveal activate)
16164 (and (org-mode-p) (org-reveal)))
16165 (defadvice occur-mode-display-occurrence
16166 (after org-occur-reveal activate)
16167 (when (org-mode-p)
16168 (let ((pos (occur-mode-find-occurrence)))
16169 (with-current-buffer (marker-buffer pos)
16170 (save-excursion
16171 (goto-char pos)
16172 (org-reveal)))))))
16173
16174 (defun org-occur-link-in-agenda-files ()
16175 "Create a link and search for it in the agendas.
16176 The link is not stored in `org-stored-links', it is just created
16177 for the search purpose."
16178 (interactive)
16179 (let ((link (condition-case nil
16180 (org-store-link nil)
16181 (error "Unable to create a link to here"))))
16182 (org-occur-in-agenda-files (regexp-quote link))))
16183
16184 (defun org-uniquify (list)
16185 "Remove duplicate elements from LIST."
16186 (let (res)
16187 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
16188 res))
16189
16190 (defun org-delete-all (elts list)
16191 "Remove all elements in ELTS from LIST."
16192 (while elts
16193 (setq list (delete (pop elts) list)))
16194 list)
16195
16196 (defun org-back-over-empty-lines ()
16197 "Move backwards over whitespace, to the beginning of the first empty line.
16198 Returns the number of empty lines passed."
16199 (let ((pos (point)))
16200 (skip-chars-backward " \t\n\r")
16201 (beginning-of-line 2)
16202 (goto-char (min (point) pos))
16203 (count-lines (point) pos)))
16204
16205 (defun org-skip-whitespace ()
16206 (skip-chars-forward " \t\n\r"))
16207
16208 (defun org-point-in-group (point group &optional context)
16209 "Check if POINT is in match-group GROUP.
16210 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
16211 match. If the match group does ot exist or point is not inside it,
16212 return nil."
16213 (and (match-beginning group)
16214 (>= point (match-beginning group))
16215 (<= point (match-end group))
16216 (if context
16217 (list context (match-beginning group) (match-end group))
16218 t)))
16219
16220 (defun org-switch-to-buffer-other-window (&rest args)
16221 "Switch to buffer in a second window on the current frame.
16222 In particular, do not allow pop-up frames."
16223 (let (pop-up-frames special-display-buffer-names special-display-regexps
16224 special-display-function)
16225 (apply 'switch-to-buffer-other-window args)))
16226
16227 (defun org-combine-plists (&rest plists)
16228 "Create a single property list from all plists in PLISTS.
16229 The process starts by copying the first list, and then setting properties
16230 from the other lists. Settings in the last list are the most significant
16231 ones and overrule settings in the other lists."
16232 (let ((rtn (copy-sequence (pop plists)))
16233 p v ls)
16234 (while plists
16235 (setq ls (pop plists))
16236 (while ls
16237 (setq p (pop ls) v (pop ls))
16238 (setq rtn (plist-put rtn p v))))
16239 rtn))
16240
16241 (defun org-move-line-down (arg)
16242 "Move the current line down. With prefix argument, move it past ARG lines."
16243 (interactive "p")
16244 (let ((col (current-column))
16245 beg end pos)
16246 (beginning-of-line 1) (setq beg (point))
16247 (beginning-of-line 2) (setq end (point))
16248 (beginning-of-line (+ 1 arg))
16249 (setq pos (move-marker (make-marker) (point)))
16250 (insert (delete-and-extract-region beg end))
16251 (goto-char pos)
16252 (org-move-to-column col)))
16253
16254 (defun org-move-line-up (arg)
16255 "Move the current line up. With prefix argument, move it past ARG lines."
16256 (interactive "p")
16257 (let ((col (current-column))
16258 beg end pos)
16259 (beginning-of-line 1) (setq beg (point))
16260 (beginning-of-line 2) (setq end (point))
16261 (beginning-of-line (- arg))
16262 (setq pos (move-marker (make-marker) (point)))
16263 (insert (delete-and-extract-region beg end))
16264 (goto-char pos)
16265 (org-move-to-column col)))
16266
16267 (defun org-replace-escapes (string table)
16268 "Replace %-escapes in STRING with values in TABLE.
16269 TABLE is an association list with keys like \"%a\" and string values.
16270 The sequences in STRING may contain normal field width and padding information,
16271 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
16272 so values can contain further %-escapes if they are define later in TABLE."
16273 (let ((case-fold-search nil)
16274 e re rpl)
16275 (while (setq e (pop table))
16276 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
16277 (while (string-match re string)
16278 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
16279 (cdr e)))
16280 (setq string (replace-match rpl t t string))))
16281 string))
16282
16283
16284 (defun org-sublist (list start end)
16285 "Return a section of LIST, from START to END.
16286 Counting starts at 1."
16287 (let (rtn (c start))
16288 (setq list (nthcdr (1- start) list))
16289 (while (and list (<= c end))
16290 (push (pop list) rtn)
16291 (setq c (1+ c)))
16292 (nreverse rtn)))
16293
16294 (defun org-find-base-buffer-visiting (file)
16295 "Like `find-buffer-visiting' but always return the base buffer and
16296 not an indirect buffer."
16297 (let ((buf (or (get-file-buffer file)
16298 (find-buffer-visiting file))))
16299 (if buf
16300 (or (buffer-base-buffer buf) buf)
16301 nil)))
16302
16303 (defun org-image-file-name-regexp (&optional extensions)
16304 "Return regexp matching the file names of images.
16305 If EXTENSIONS is given, only match these."
16306 (if (and (not extensions) (fboundp 'image-file-name-regexp))
16307 (image-file-name-regexp)
16308 (let ((image-file-name-extensions
16309 (or extensions
16310 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
16311 "xbm" "xpm" "pbm" "pgm" "ppm"))))
16312 (concat "\\."
16313 (regexp-opt (nconc (mapcar 'upcase
16314 image-file-name-extensions)
16315 image-file-name-extensions)
16316 t)
16317 "\\'"))))
16318
16319 (defun org-file-image-p (file &optional extensions)
16320 "Return non-nil if FILE is an image."
16321 (save-match-data
16322 (string-match (org-image-file-name-regexp extensions) file)))
16323
16324 (defun org-get-cursor-date ()
16325 "Return the date at cursor in as a time.
16326 This works in the calendar and in the agenda, anywhere else it just
16327 returns the current time."
16328 (let (date day defd)
16329 (cond
16330 ((eq major-mode 'calendar-mode)
16331 (setq date (calendar-cursor-to-date)
16332 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
16333 ((eq major-mode 'org-agenda-mode)
16334 (setq day (get-text-property (point) 'day))
16335 (if day
16336 (setq date (calendar-gregorian-from-absolute day)
16337 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
16338 (nth 2 date))))))
16339 (or defd (current-time))))
16340
16341 (defvar org-agenda-action-marker (make-marker)
16342 "Marker pointing to the entry for the next agenda action.")
16343
16344 (defun org-mark-entry-for-agenda-action ()
16345 "Mark the current entry as target of an agenda action.
16346 Agenda actions are actions executed from the agenda with the key `k',
16347 which make use of the date at the cursor."
16348 (interactive)
16349 (move-marker org-agenda-action-marker
16350 (save-excursion (org-back-to-heading t) (point))
16351 (current-buffer))
16352 (message
16353 "Entry marked for action; press `k' at desired date in agenda or calendar"))
16354
16355 ;;; Paragraph filling stuff.
16356 ;; We want this to be just right, so use the full arsenal.
16357
16358 (defun org-indent-line-function ()
16359 "Indent line like previous, but further if previous was headline or item."
16360 (interactive)
16361 (let* ((pos (point))
16362 (itemp (org-at-item-p))
16363 (case-fold-search t)
16364 (org-drawer-regexp (or org-drawer-regexp "\000"))
16365 column bpos bcol tpos tcol bullet btype bullet-type)
16366 ;; Find the previous relevant line
16367 (beginning-of-line 1)
16368 (cond
16369 ((looking-at "#") (setq column 0))
16370 ((looking-at "\\*+ ") (setq column 0))
16371 ((and (looking-at "[ \t]*:END:")
16372 (save-excursion (re-search-backward org-drawer-regexp nil t)))
16373 (save-excursion
16374 (goto-char (1- (match-beginning 1)))
16375 (setq column (current-column))))
16376 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
16377 (save-excursion
16378 (re-search-backward
16379 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
16380 (setq column (org-get-indentation (match-string 0))))
16381 (t
16382 (beginning-of-line 0)
16383 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
16384 (not (looking-at "[ \t]*:END:"))
16385 (not (looking-at org-drawer-regexp)))
16386 (beginning-of-line 0))
16387 (cond
16388 ((looking-at "\\*+[ \t]+")
16389 (if (not org-adapt-indentation)
16390 (setq column 0)
16391 (goto-char (match-end 0))
16392 (setq column (current-column))))
16393 ((looking-at org-drawer-regexp)
16394 (goto-char (1- (match-beginning 1)))
16395 (setq column (current-column)))
16396 ((looking-at "\\([ \t]*\\):END:")
16397 (goto-char (match-end 1))
16398 (setq column (current-column)))
16399 ((org-in-item-p)
16400 (org-beginning-of-item)
16401 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
16402 (setq bpos (match-beginning 1) tpos (match-end 0)
16403 bcol (progn (goto-char bpos) (current-column))
16404 tcol (progn (goto-char tpos) (current-column))
16405 bullet (match-string 1)
16406 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
16407 (if (> tcol (+ bcol org-description-max-indent))
16408 (setq tcol (+ bcol 5)))
16409 (if (not itemp)
16410 (setq column tcol)
16411 (goto-char pos)
16412 (beginning-of-line 1)
16413 (if (looking-at "\\S-")
16414 (progn
16415 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16416 (setq bullet (match-string 1)
16417 btype (if (string-match "[0-9]" bullet) "n" bullet))
16418 (setq column (if (equal btype bullet-type) bcol tcol)))
16419 (setq column (org-get-indentation)))))
16420 (t (setq column (org-get-indentation))))))
16421 (goto-char pos)
16422 (if (<= (current-column) (current-indentation))
16423 (org-indent-line-to column)
16424 (save-excursion (org-indent-line-to column)))
16425 (setq column (current-column))
16426 (beginning-of-line 1)
16427 (if (looking-at
16428 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16429 (replace-match (concat "\\1" (format org-property-format
16430 (match-string 2) (match-string 3)))
16431 t nil))
16432 (org-move-to-column column)))
16433
16434 (defun org-set-autofill-regexps ()
16435 (interactive)
16436 ;; In the paragraph separator we include headlines, because filling
16437 ;; text in a line directly attached to a headline would otherwise
16438 ;; fill the headline as well.
16439 (org-set-local 'comment-start-skip "^#+[ \t]*")
16440 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
16441 ;; The paragraph starter includes hand-formatted lists.
16442 (org-set-local
16443 'paragraph-start
16444 (concat
16445 "\f" "\\|"
16446 "[ ]*$" "\\|"
16447 "\\*+ " "\\|"
16448 "[ \t]*#" "\\|"
16449 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16450 "[ \t]*[:|]" "\\|"
16451 "\\$\\$" "\\|"
16452 "\\\\\\(begin\\|end\\|[][]\\)"))
16453 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16454 ;; But only if the user has not turned off tables or fixed-width regions
16455 (org-set-local
16456 'auto-fill-inhibit-regexp
16457 (concat "\\*+ \\|#\\+"
16458 "\\|[ \t]*" org-keyword-time-regexp
16459 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16460 (concat
16461 "\\|[ \t]*["
16462 (if org-enable-table-editor "|" "")
16463 (if org-enable-fixed-width-editor ":" "")
16464 "]"))))
16465 ;; We use our own fill-paragraph function, to make sure that tables
16466 ;; and fixed-width regions are not wrapped. That function will pass
16467 ;; through to `fill-paragraph' when appropriate.
16468 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16469 ; Adaptive filling: To get full control, first make sure that
16470 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16471 (org-set-local 'adaptive-fill-regexp "\000")
16472 (org-set-local 'adaptive-fill-function
16473 'org-adaptive-fill-function)
16474 (org-set-local
16475 'align-mode-rules-list
16476 '((org-in-buffer-settings
16477 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16478 (modes . '(org-mode))))))
16479
16480 (defun org-fill-paragraph (&optional justify)
16481 "Re-align a table, pass through to fill-paragraph if no table."
16482 (let ((table-p (org-at-table-p))
16483 (table.el-p (org-at-table.el-p)))
16484 (cond ((and (equal (char-after (point-at-bol)) ?*)
16485 (save-excursion (goto-char (point-at-bol))
16486 (looking-at outline-regexp)))
16487 t) ; skip headlines
16488 (table.el-p t) ; skip table.el tables
16489 (table-p (org-table-align) t) ; align org-mode tables
16490 (t nil)))) ; call paragraph-fill
16491
16492 ;; For reference, this is the default value of adaptive-fill-regexp
16493 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16494
16495 (defun org-adaptive-fill-function ()
16496 "Return a fill prefix for org-mode files.
16497 In particular, this makes sure hanging paragraphs for hand-formatted lists
16498 work correctly."
16499 (cond ((looking-at "#[ \t]+")
16500 (match-string 0))
16501 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16502 (save-excursion
16503 (if (> (match-end 1) (+ (match-beginning 1)
16504 org-description-max-indent))
16505 (goto-char (+ (match-beginning 1) 5))
16506 (goto-char (match-end 0)))
16507 (make-string (current-column) ?\ )))
16508 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
16509 (save-excursion
16510 (goto-char (match-end 0))
16511 (make-string (current-column) ?\ )))
16512 (t nil)))
16513
16514 ;;; Other stuff.
16515
16516 (defun org-toggle-fixed-width-section (arg)
16517 "Toggle the fixed-width export.
16518 If there is no active region, the QUOTE keyword at the current headline is
16519 inserted or removed. When present, it causes the text between this headline
16520 and the next to be exported as fixed-width text, and unmodified.
16521 If there is an active region, this command adds or removes a colon as the
16522 first character of this line. If the first character of a line is a colon,
16523 this line is also exported in fixed-width font."
16524 (interactive "P")
16525 (let* ((cc 0)
16526 (regionp (org-region-active-p))
16527 (beg (if regionp (region-beginning) (point)))
16528 (end (if regionp (region-end)))
16529 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16530 (case-fold-search nil)
16531 (re "[ \t]*\\(: \\)")
16532 off)
16533 (if regionp
16534 (save-excursion
16535 (goto-char beg)
16536 (setq cc (current-column))
16537 (beginning-of-line 1)
16538 (setq off (looking-at re))
16539 (while (> nlines 0)
16540 (setq nlines (1- nlines))
16541 (beginning-of-line 1)
16542 (cond
16543 (arg
16544 (org-move-to-column cc t)
16545 (insert ": \n")
16546 (forward-line -1))
16547 ((and off (looking-at re))
16548 (replace-match "" t t nil 1))
16549 ((not off) (org-move-to-column cc t) (insert ": ")))
16550 (forward-line 1)))
16551 (save-excursion
16552 (org-back-to-heading)
16553 (if (looking-at (concat outline-regexp
16554 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
16555 (replace-match "" t t nil 1)
16556 (if (looking-at outline-regexp)
16557 (progn
16558 (goto-char (match-end 0))
16559 (insert org-quote-string " "))))))))
16560
16561 (defun org-reftex-citation ()
16562 "Use reftex-citation to insert a citation into the buffer.
16563 This looks for a line like
16564
16565 #+BIBLIOGRAPHY: foo plain option:-d
16566
16567 and derives from it that foo.bib is the bbliography file relevant
16568 for this document. It then installs the necessary environment for RefTeX
16569 to work in this buffer and calls `reftex-citation' to insert a citation
16570 into the buffer.
16571
16572 Export of such citations to both LaTeX and HTML is handled by the contributed
16573 package org-exp-bibtex by Taru Karttunen."
16574 (interactive)
16575 (let ((reftex-docstruct-symbol 'rds)
16576 (reftex-cite-format "\\cite{%l}")
16577 rds bib)
16578 (save-excursion
16579 (save-restriction
16580 (widen)
16581 (let ((case-fold-search t)
16582 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16583 (if (not (save-excursion
16584 (or (re-search-forward re nil t)
16585 (re-search-backward re nil t))))
16586 (error "No bibliography defined in file")
16587 (setq bib (concat (match-string 1) ".bib")
16588 rds (list (list 'bib bib)))))))
16589 (call-interactively 'reftex-citation)))
16590
16591 ;;;; Functions extending outline functionality
16592
16593 (defun org-beginning-of-line (&optional arg)
16594 "Go to the beginning of the current line. If that is invisible, continue
16595 to a visible line beginning. This makes the function of C-a more intuitive.
16596 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16597 first attempt, and only move to after the tags when the cursor is already
16598 beyond the end of the headline."
16599 (interactive "P")
16600 (let ((pos (point))
16601 (special (if (consp org-special-ctrl-a/e)
16602 (car org-special-ctrl-a/e)
16603 org-special-ctrl-a/e))
16604 refpos)
16605 (if (org-bound-and-true-p line-move-visual)
16606 (beginning-of-visual-line 1)
16607 (beginning-of-line 1))
16608 (if (and arg (fboundp 'move-beginning-of-line))
16609 (call-interactively 'move-beginning-of-line)
16610 (if (bobp)
16611 nil
16612 (backward-char 1)
16613 (if (org-invisible-p)
16614 (while (and (not (bobp)) (org-invisible-p))
16615 (backward-char 1)
16616 (beginning-of-line 1))
16617 (forward-char 1))))
16618 (when special
16619 (cond
16620 ((and (looking-at org-complex-heading-regexp)
16621 (= (char-after (match-end 1)) ?\ ))
16622 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16623 (point-at-eol)))
16624 (goto-char
16625 (if (eq special t)
16626 (cond ((> pos refpos) refpos)
16627 ((= pos (point)) refpos)
16628 (t (point)))
16629 (cond ((> pos (point)) (point))
16630 ((not (eq last-command this-command)) (point))
16631 (t refpos)))))
16632 ((org-at-item-p)
16633 (goto-char
16634 (if (eq special t)
16635 (cond ((> pos (match-end 4)) (match-end 4))
16636 ((= pos (point)) (match-end 4))
16637 (t (point)))
16638 (cond ((> pos (point)) (point))
16639 ((not (eq last-command this-command)) (point))
16640 (t (match-end 4))))))))
16641 (org-no-warnings
16642 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16643
16644 (defun org-end-of-line (&optional arg)
16645 "Go to the end of the line.
16646 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16647 first attempt, and only move to after the tags when the cursor is already
16648 beyond the end of the headline."
16649 (interactive "P")
16650 (let ((special (if (consp org-special-ctrl-a/e)
16651 (cdr org-special-ctrl-a/e)
16652 org-special-ctrl-a/e)))
16653 (if (or (not special)
16654 (not (org-on-heading-p))
16655 arg)
16656 (call-interactively
16657 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
16658 ((fboundp 'move-end-of-line) 'move-end-of-line)
16659 (t 'end-of-line)))
16660 (let ((pos (point)))
16661 (beginning-of-line 1)
16662 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
16663 (if (eq special t)
16664 (if (or (< pos (match-beginning 1))
16665 (= pos (match-end 0)))
16666 (goto-char (match-beginning 1))
16667 (goto-char (match-end 0)))
16668 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16669 (goto-char (match-end 0))
16670 (goto-char (match-beginning 1))))
16671 (call-interactively (if (fboundp 'move-end-of-line)
16672 'move-end-of-line
16673 'end-of-line)))))
16674 (org-no-warnings
16675 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16676
16677 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16678 (define-key org-mode-map "\C-e" 'org-end-of-line)
16679 (define-key org-mode-map [home] 'org-beginning-of-line)
16680 (define-key org-mode-map [end] 'org-end-of-line)
16681
16682 (defun org-backward-sentence (&optional arg)
16683 "Go to beginning of sentence, or beginning of table field.
16684 This will call `backward-sentence' or `org-table-beginning-of-field',
16685 depending on context."
16686 (interactive "P")
16687 (cond
16688 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16689 (t (call-interactively 'backward-sentence))))
16690
16691 (defun org-forward-sentence (&optional arg)
16692 "Go to end of sentence, or end of table field.
16693 This will call `forward-sentence' or `org-table-end-of-field',
16694 depending on context."
16695 (interactive "P")
16696 (cond
16697 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16698 (t (call-interactively 'forward-sentence))))
16699
16700 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16701 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16702
16703 (defun org-kill-line (&optional arg)
16704 "Kill line, to tags or end of line."
16705 (interactive "P")
16706 (cond
16707 ((or (not org-special-ctrl-k)
16708 (bolp)
16709 (not (org-on-heading-p)))
16710 (call-interactively 'kill-line))
16711 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16712 (kill-region (point) (match-beginning 1))
16713 (org-set-tags nil t))
16714 (t (kill-region (point) (point-at-eol)))))
16715
16716 (define-key org-mode-map "\C-k" 'org-kill-line)
16717
16718 (defun org-yank (&optional arg)
16719 "Yank. If the kill is a subtree, treat it specially.
16720 This command will look at the current kill and check if is a single
16721 subtree, or a series of subtrees[1]. If it passes the test, and if the
16722 cursor is at the beginning of a line or after the stars of a currently
16723 empty headline, then the yank is handled specially. How exactly depends
16724 on the value of the following variables, both set by default.
16725
16726 org-yank-folded-subtrees
16727 When set, the subtree(s) will be folded after insertion, but only
16728 if doing so would now swallow text after the yanked text.
16729
16730 org-yank-adjusted-subtrees
16731 When set, the subtree will be promoted or demoted in order to
16732 fit into the local outline tree structure, which means that the level
16733 will be adjusted so that it becomes the smaller one of the two
16734 *visible* surrounding headings.
16735
16736 Any prefix to this command will cause `yank' to be called directly with
16737 no special treatment. In particular, a simple `C-u' prefix will just
16738 plainly yank the text as it is.
16739
16740 \[1] The test checks if the first non-white line is a heading
16741 and if there are no other headings with fewer stars."
16742 (interactive "P")
16743 (org-yank-generic 'yank arg))
16744
16745 (defun org-yank-generic (command arg)
16746 "Perform some yank-like command.
16747
16748 This function implements the behavior described in the `org-yank'
16749 documentation. However, it has been generalized to work for any
16750 interactive command with similar behavior."
16751
16752 ;; pretend to be command COMMAND
16753 (setq this-command command)
16754
16755 (if arg
16756 (call-interactively command)
16757
16758 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16759 (and (org-kill-is-subtree-p)
16760 (or (bolp)
16761 (and (looking-at "[ \t]*$")
16762 (string-match
16763 "\\`\\*+\\'"
16764 (buffer-substring (point-at-bol) (point)))))))
16765 swallowp)
16766 (cond
16767 ((and subtreep org-yank-folded-subtrees)
16768 (let ((beg (point))
16769 end)
16770 (if (and subtreep org-yank-adjusted-subtrees)
16771 (org-paste-subtree nil nil 'for-yank)
16772 (call-interactively command))
16773
16774 (setq end (point))
16775 (goto-char beg)
16776 (when (and (bolp) subtreep
16777 (not (setq swallowp
16778 (org-yank-folding-would-swallow-text beg end))))
16779 (or (looking-at outline-regexp)
16780 (re-search-forward (concat "^" outline-regexp) end t))
16781 (while (and (< (point) end) (looking-at outline-regexp))
16782 (hide-subtree)
16783 (org-cycle-show-empty-lines 'folded)
16784 (condition-case nil
16785 (outline-forward-same-level 1)
16786 (error (goto-char end)))))
16787 (when swallowp
16788 (message
16789 "Inserted text not folded because that would swallow text"))
16790
16791 (goto-char end)
16792 (skip-chars-forward " \t\n\r")
16793 (beginning-of-line 1)
16794 (push-mark beg 'nomsg)))
16795 ((and subtreep org-yank-adjusted-subtrees)
16796 (let ((beg (point-at-bol)))
16797 (org-paste-subtree nil nil 'for-yank)
16798 (push-mark beg 'nomsg)))
16799 (t
16800 (call-interactively command))))))
16801
16802 (defun org-yank-folding-would-swallow-text (beg end)
16803 "Would hide-subtree at BEG swallow any text after END?"
16804 (let (level)
16805 (save-excursion
16806 (goto-char beg)
16807 (when (or (looking-at outline-regexp)
16808 (re-search-forward (concat "^" outline-regexp) end t))
16809 (setq level (org-outline-level)))
16810 (goto-char end)
16811 (skip-chars-forward " \t\r\n\v\f")
16812 (if (or (eobp)
16813 (and (bolp) (looking-at org-outline-regexp)
16814 (<= (org-outline-level) level)))
16815 nil ; Nothing would be swallowed
16816 t)))) ; something would swallow
16817
16818 (define-key org-mode-map "\C-y" 'org-yank)
16819
16820 (defun org-invisible-p ()
16821 "Check if point is at a character currently not visible."
16822 ;; Early versions of noutline don't have `outline-invisible-p'.
16823 (if (fboundp 'outline-invisible-p)
16824 (outline-invisible-p)
16825 (get-char-property (point) 'invisible)))
16826
16827 (defun org-invisible-p2 ()
16828 "Check if point is at a character currently not visible."
16829 (save-excursion
16830 (if (and (eolp) (not (bobp))) (backward-char 1))
16831 ;; Early versions of noutline don't have `outline-invisible-p'.
16832 (if (fboundp 'outline-invisible-p)
16833 (outline-invisible-p)
16834 (get-char-property (point) 'invisible))))
16835
16836 (defun org-back-to-heading (&optional invisible-ok)
16837 "Call `outline-back-to-heading', but provide a better error message."
16838 (condition-case nil
16839 (outline-back-to-heading invisible-ok)
16840 (error (error "Before first headline at position %d in buffer %s"
16841 (point) (current-buffer)))))
16842
16843 (defun org-before-first-heading-p ()
16844 "Before first heading?"
16845 (save-excursion
16846 (null (re-search-backward "^\\*+ " nil t))))
16847
16848 (defun org-on-heading-p (&optional ignored)
16849 (outline-on-heading-p t))
16850 (defun org-at-heading-p (&optional ignored)
16851 (outline-on-heading-p t))
16852
16853 (defun org-at-heading-or-item-p ()
16854 (or (org-on-heading-p) (org-at-item-p)))
16855
16856 (defun org-on-target-p ()
16857 (or (org-in-regexp org-radio-target-regexp)
16858 (org-in-regexp org-target-regexp)))
16859
16860 (defun org-up-heading-all (arg)
16861 "Move to the heading line of which the present line is a subheading.
16862 This function considers both visible and invisible heading lines.
16863 With argument, move up ARG levels."
16864 (if (fboundp 'outline-up-heading-all)
16865 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16866 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16867
16868 (defun org-up-heading-safe ()
16869 "Move to the heading line of which the present line is a subheading.
16870 This version will not throw an error. It will return the level of the
16871 headline found, or nil if no higher level is found.
16872
16873 Also, this function will be a lot faster than `outline-up-heading',
16874 because it relies on stars being the outline starters. This can really
16875 make a significant difference in outlines with very many siblings."
16876 (let (start-level re)
16877 (org-back-to-heading t)
16878 (setq start-level (funcall outline-level))
16879 (if (equal start-level 1)
16880 nil
16881 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16882 (if (re-search-backward re nil t)
16883 (funcall outline-level)))))
16884
16885 (defun org-first-sibling-p ()
16886 "Is this heading the first child of its parents?"
16887 (interactive)
16888 (let ((re (concat "^" outline-regexp))
16889 level l)
16890 (unless (org-at-heading-p t)
16891 (error "Not at a heading"))
16892 (setq level (funcall outline-level))
16893 (save-excursion
16894 (if (not (re-search-backward re nil t))
16895 t
16896 (setq l (funcall outline-level))
16897 (< l level)))))
16898
16899 (defun org-goto-sibling (&optional previous)
16900 "Goto the next sibling, even if it is invisible.
16901 When PREVIOUS is set, go to the previous sibling instead. Returns t
16902 when a sibling was found. When none is found, return nil and don't
16903 move point."
16904 (let ((fun (if previous 're-search-backward 're-search-forward))
16905 (pos (point))
16906 (re (concat "^" outline-regexp))
16907 level l)
16908 (when (condition-case nil (org-back-to-heading t) (error nil))
16909 (setq level (funcall outline-level))
16910 (catch 'exit
16911 (or previous (forward-char 1))
16912 (while (funcall fun re nil t)
16913 (setq l (funcall outline-level))
16914 (when (< l level) (goto-char pos) (throw 'exit nil))
16915 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16916 (goto-char pos)
16917 nil))))
16918
16919 (defun org-show-siblings ()
16920 "Show all siblings of the current headline."
16921 (save-excursion
16922 (while (org-goto-sibling) (org-flag-heading nil)))
16923 (save-excursion
16924 (while (org-goto-sibling 'previous)
16925 (org-flag-heading nil))))
16926
16927 (defun org-show-hidden-entry ()
16928 "Show an entry where even the heading is hidden."
16929 (save-excursion
16930 (org-show-entry)))
16931
16932 (defun org-flag-heading (flag &optional entry)
16933 "Flag the current heading. FLAG non-nil means make invisible.
16934 When ENTRY is non-nil, show the entire entry."
16935 (save-excursion
16936 (org-back-to-heading t)
16937 ;; Check if we should show the entire entry
16938 (if entry
16939 (progn
16940 (org-show-entry)
16941 (save-excursion
16942 (and (outline-next-heading)
16943 (org-flag-heading nil))))
16944 (outline-flag-region (max (point-min) (1- (point)))
16945 (save-excursion (outline-end-of-heading) (point))
16946 flag))))
16947
16948 (defun org-get-next-sibling ()
16949 "Move to next heading of the same level, and return point.
16950 If there is no such heading, return nil.
16951 This is like outline-next-sibling, but invisible headings are ok."
16952 (let ((level (funcall outline-level)))
16953 (outline-next-heading)
16954 (while (and (not (eobp)) (> (funcall outline-level) level))
16955 (outline-next-heading))
16956 (if (or (eobp) (< (funcall outline-level) level))
16957 nil
16958 (point))))
16959
16960 (defun org-get-last-sibling ()
16961 "Move to previous heading of the same level, and return point.
16962 If there is no such heading, return nil."
16963 (let ((opoint (point))
16964 (level (funcall outline-level)))
16965 (outline-previous-heading)
16966 (when (and (/= (point) opoint) (outline-on-heading-p t))
16967 (while (and (> (funcall outline-level) level)
16968 (not (bobp)))
16969 (outline-previous-heading))
16970 (if (< (funcall outline-level) level)
16971 nil
16972 (point)))))
16973
16974 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16975 ;; This contains an exact copy of the original function, but it uses
16976 ;; `org-back-to-heading', to make it work also in invisible
16977 ;; trees. And is uses an invisible-OK argument.
16978 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16979 ;; Furthermore, when used inside Org, finding the end of a large subtree
16980 ;; with many children and grandchildren etc, this can be much faster
16981 ;; than the outline version.
16982 (org-back-to-heading invisible-OK)
16983 (let ((first t)
16984 (level (funcall outline-level)))
16985 (if (and (org-mode-p) (< level 1000))
16986 ;; A true heading (not a plain list item), in Org-mode
16987 ;; This means we can easily find the end by looking
16988 ;; only for the right number of stars. Using a regexp to do
16989 ;; this is so much faster than using a Lisp loop.
16990 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16991 (forward-char 1)
16992 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16993 ;; something else, do it the slow way
16994 (while (and (not (eobp))
16995 (or first (> (funcall outline-level) level)))
16996 (setq first nil)
16997 (outline-next-heading)))
16998 (unless to-heading
16999 (if (memq (preceding-char) '(?\n ?\^M))
17000 (progn
17001 ;; Go to end of line before heading
17002 (forward-char -1)
17003 (if (memq (preceding-char) '(?\n ?\^M))
17004 ;; leave blank line before heading
17005 (forward-char -1))))))
17006 (point))
17007
17008 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
17009 "Use Org version in org-mode, for dramatic speed-up."
17010 (if (eq major-mode 'org-mode)
17011 (progn
17012 (org-end-of-subtree nil t)
17013 (unless (eobp) (backward-char 1)))
17014 ad-do-it))
17015
17016 (defun org-forward-same-level (arg &optional invisible-ok)
17017 "Move forward to the arg'th subheading at same level as this one.
17018 Stop at the first and last subheadings of a superior heading."
17019 (interactive "p")
17020 (org-back-to-heading invisible-ok)
17021 (org-on-heading-p)
17022 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17023 (re (format "^\\*\\{1,%d\\} " level))
17024 l)
17025 (forward-char 1)
17026 (while (> arg 0)
17027 (while (and (re-search-forward re nil 'move)
17028 (setq l (- (match-end 0) (match-beginning 0) 1))
17029 (= l level)
17030 (not invisible-ok)
17031 (org-invisible-p))
17032 (if (< l level) (setq arg 1)))
17033 (setq arg (1- arg)))
17034 (beginning-of-line 1)))
17035
17036 (defun org-backward-same-level (arg &optional invisible-ok)
17037 "Move backward to the arg'th subheading at same level as this one.
17038 Stop at the first and last subheadings of a superior heading."
17039 (interactive "p")
17040 (org-back-to-heading)
17041 (org-on-heading-p)
17042 (let* ((level (- (match-end 0) (match-beginning 0) 1))
17043 (re (format "^\\*\\{1,%d\\} " level))
17044 l)
17045 (while (> arg 0)
17046 (while (and (re-search-backward re nil 'move)
17047 (setq l (- (match-end 0) (match-beginning 0) 1))
17048 (= l level)
17049 (not invisible-ok)
17050 (org-invisible-p))
17051 (if (< l level) (setq arg 1)))
17052 (setq arg (1- arg)))))
17053
17054 (defun org-show-subtree ()
17055 "Show everything after this heading at deeper levels."
17056 (outline-flag-region
17057 (point)
17058 (save-excursion
17059 (org-end-of-subtree t t))
17060 nil))
17061
17062 (defun org-show-entry ()
17063 "Show the body directly following this heading.
17064 Show the heading too, if it is currently invisible."
17065 (interactive)
17066 (save-excursion
17067 (condition-case nil
17068 (progn
17069 (org-back-to-heading t)
17070 (outline-flag-region
17071 (max (point-min) (1- (point)))
17072 (save-excursion
17073 (if (re-search-forward
17074 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
17075 (match-beginning 1)
17076 (point-max)))
17077 nil)
17078 (org-cycle-hide-drawers 'children))
17079 (error nil))))
17080
17081 (defun org-make-options-regexp (kwds &optional extra)
17082 "Make a regular expression for keyword lines."
17083 (concat
17084 "^"
17085 "#?[ \t]*\\+\\("
17086 (mapconcat 'regexp-quote kwds "\\|")
17087 (if extra (concat "\\|" extra))
17088 "\\):[ \t]*"
17089 "\\(.*\\)"))
17090
17091 ;; Make isearch reveal the necessary context
17092 (defun org-isearch-end ()
17093 "Reveal context after isearch exits."
17094 (when isearch-success ; only if search was successful
17095 (if (featurep 'xemacs)
17096 ;; Under XEmacs, the hook is run in the correct place,
17097 ;; we directly show the context.
17098 (org-show-context 'isearch)
17099 ;; In Emacs the hook runs *before* restoring the overlays.
17100 ;; So we have to use a one-time post-command-hook to do this.
17101 ;; (Emacs 22 has a special variable, see function `org-mode')
17102 (unless (and (boundp 'isearch-mode-end-hook-quit)
17103 isearch-mode-end-hook-quit)
17104 ;; Only when the isearch was not quitted.
17105 (org-add-hook 'post-command-hook 'org-isearch-post-command
17106 'append 'local)))))
17107
17108 (defun org-isearch-post-command ()
17109 "Remove self from hook, and show context."
17110 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
17111 (org-show-context 'isearch))
17112
17113
17114 ;;;; Integration with and fixes for other packages
17115
17116 ;;; Imenu support
17117
17118 (defvar org-imenu-markers nil
17119 "All markers currently used by Imenu.")
17120 (make-variable-buffer-local 'org-imenu-markers)
17121
17122 (defun org-imenu-new-marker (&optional pos)
17123 "Return a new marker for use by Imenu, and remember the marker."
17124 (let ((m (make-marker)))
17125 (move-marker m (or pos (point)))
17126 (push m org-imenu-markers)
17127 m))
17128
17129 (defun org-imenu-get-tree ()
17130 "Produce the index for Imenu."
17131 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
17132 (setq org-imenu-markers nil)
17133 (let* ((n org-imenu-depth)
17134 (re (concat "^" outline-regexp))
17135 (subs (make-vector (1+ n) nil))
17136 (last-level 0)
17137 m level head)
17138 (save-excursion
17139 (save-restriction
17140 (widen)
17141 (goto-char (point-max))
17142 (while (re-search-backward re nil t)
17143 (setq level (org-reduced-level (funcall outline-level)))
17144 (when (<= level n)
17145 (looking-at org-complex-heading-regexp)
17146 (setq head (org-link-display-format
17147 (org-match-string-no-properties 4))
17148 m (org-imenu-new-marker))
17149 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
17150 (if (>= level last-level)
17151 (push (cons head m) (aref subs level))
17152 (push (cons head (aref subs (1+ level))) (aref subs level))
17153 (loop for i from (1+ level) to n do (aset subs i nil)))
17154 (setq last-level level)))))
17155 (aref subs 1)))
17156
17157 (eval-after-load "imenu"
17158 '(progn
17159 (add-hook 'imenu-after-jump-hook
17160 (lambda ()
17161 (if (eq major-mode 'org-mode)
17162 (org-show-context 'org-goto))))))
17163
17164 (defun org-link-display-format (link)
17165 "Replace a link with either the description, or the link target
17166 if no description is present"
17167 (save-match-data
17168 (if (string-match org-bracket-link-analytic-regexp link)
17169 (replace-match (or (match-string 5 link)
17170 (concat (match-string 1 link)
17171 (match-string 3 link)))
17172 nil nil link)
17173 link)))
17174
17175 ;; Speedbar support
17176
17177 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
17178 "Overlay marking the agenda restriction line in speedbar.")
17179 (org-overlay-put org-speedbar-restriction-lock-overlay
17180 'face 'org-agenda-restriction-lock)
17181 (org-overlay-put org-speedbar-restriction-lock-overlay
17182 'help-echo "Agendas are currently limited to this item.")
17183 (org-detach-overlay org-speedbar-restriction-lock-overlay)
17184
17185 (defun org-speedbar-set-agenda-restriction ()
17186 "Restrict future agenda commands to the location at point in speedbar.
17187 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
17188 (interactive)
17189 (require 'org-agenda)
17190 (let (p m tp np dir txt)
17191 (cond
17192 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17193 'org-imenu t))
17194 (setq m (get-text-property p 'org-imenu-marker))
17195 (save-excursion
17196 (save-restriction
17197 (set-buffer (marker-buffer m))
17198 (goto-char m)
17199 (org-agenda-set-restriction-lock 'subtree))))
17200 ((setq p (text-property-any (point-at-bol) (point-at-eol)
17201 'speedbar-function 'speedbar-find-file))
17202 (setq tp (previous-single-property-change
17203 (1+ p) 'speedbar-function)
17204 np (next-single-property-change
17205 tp 'speedbar-function)
17206 dir (speedbar-line-directory)
17207 txt (buffer-substring-no-properties (or tp (point-min))
17208 (or np (point-max))))
17209 (save-excursion
17210 (save-restriction
17211 (set-buffer (find-file-noselect
17212 (let ((default-directory dir))
17213 (expand-file-name txt))))
17214 (unless (org-mode-p)
17215 (error "Cannot restrict to non-Org-mode file"))
17216 (org-agenda-set-restriction-lock 'file))))
17217 (t (error "Don't know how to restrict Org-mode's agenda")))
17218 (org-move-overlay org-speedbar-restriction-lock-overlay
17219 (point-at-bol) (point-at-eol))
17220 (setq current-prefix-arg nil)
17221 (org-agenda-maybe-redo)))
17222
17223 (eval-after-load "speedbar"
17224 '(progn
17225 (speedbar-add-supported-extension ".org")
17226 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
17227 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
17228 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
17229 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
17230 (add-hook 'speedbar-visiting-tag-hook
17231 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
17232
17233
17234 ;;; Fixes and Hacks for problems with other packages
17235
17236 ;; Make flyspell not check words in links, to not mess up our keymap
17237 (defun org-mode-flyspell-verify ()
17238 "Don't let flyspell put overlays at active buttons."
17239 (and (not (get-text-property (point) 'keymap))
17240 (not (get-text-property (point) 'org-no-flyspell))))
17241
17242 (defun org-remove-flyspell-overlays-in (beg end)
17243 "Remove flyspell overlays in region."
17244 (and (org-bound-and-true-p flyspell-mode)
17245 (fboundp 'flyspell-delete-region-overlays)
17246 (flyspell-delete-region-overlays beg end))
17247 (add-text-properties beg end '(org-no-flyspell t)))
17248
17249 ;; Make `bookmark-jump' show the jump location if it was hidden.
17250 (eval-after-load "bookmark"
17251 '(if (boundp 'bookmark-after-jump-hook)
17252 ;; We can use the hook
17253 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
17254 ;; Hook not available, use advice
17255 (defadvice bookmark-jump (after org-make-visible activate)
17256 "Make the position visible."
17257 (org-bookmark-jump-unhide))))
17258
17259 ;; Make sure saveplace show the location if it was hidden
17260 (eval-after-load "saveplace"
17261 '(defadvice save-place-find-file-hook (after org-make-visible activate)
17262 "Make the position visible."
17263 (org-bookmark-jump-unhide)))
17264
17265 (defun org-bookmark-jump-unhide ()
17266 "Unhide the current position, to show the bookmark location."
17267 (and (org-mode-p)
17268 (or (org-invisible-p)
17269 (save-excursion (goto-char (max (point-min) (1- (point))))
17270 (org-invisible-p)))
17271 (org-show-context 'bookmark-jump)))
17272
17273 ;; Make session.el ignore our circular variable
17274 (eval-after-load "session"
17275 '(add-to-list 'session-globals-exclude 'org-mark-ring))
17276
17277 ;;;; Experimental code
17278
17279 (defun org-closed-in-range ()
17280 "Sparse tree of items closed in a certain time range.
17281 Still experimental, may disappear in the future."
17282 (interactive)
17283 ;; Get the time interval from the user.
17284 (let* ((time1 (org-float-time
17285 (org-read-date nil 'to-time nil "Starting date: ")))
17286 (time2 (org-float-time
17287 (org-read-date nil 'to-time nil "End date:")))
17288 ;; callback function
17289 (callback (lambda ()
17290 (let ((time
17291 (org-float-time
17292 (apply 'encode-time
17293 (org-parse-time-string
17294 (match-string 1))))))
17295 ;; check if time in interval
17296 (and (>= time time1) (<= time time2))))))
17297 ;; make tree, check each match with the callback
17298 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
17299
17300 ;;;; Finish up
17301
17302 (provide 'org)
17303
17304 (run-hooks 'org-load-hook)
17305
17306 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
17307
17308 ;;; org.el ends here