]> code.delx.au - gnu-emacs/blob - lisp/org/org.el
22db64a6ad69f8e3a597cccb6f15e89a1ad4d11c
[gnu-emacs] / lisp / org / org.el
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.19a
10 ;;
11 ;; This file is part of GNU Emacs.
12 ;;
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;
27 ;;; Commentary:
28 ;;
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
31 ;;
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
46 ;;
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
50 ;;
51 ;; http://orgmode.org/org.html#Installation
52 ;;
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
60 ;;
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
63 ;;
64 ;;; Code:
65
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
70
71 ;;;; Require other packages
72
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
86
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-footnote)
92
93 ;;;; Customization variables
94
95 ;;; Version
96
97 (defconst org-version "6.19a"
98 "The version number of the file org.el.")
99
100 (defun org-version (&optional here)
101 "Show the org-mode version in the echo area.
102 With prefix arg HERE, insert it at point."
103 (interactive "P")
104 (let ((version (format "Org-mode version %s" org-version)))
105 (message version)
106 (if here
107 (insert version))))
108
109 ;;; Compatibility constants
110
111 ;;; The custom variables
112
113 (defgroup org nil
114 "Outline-based notes management and organizer."
115 :tag "Org"
116 :group 'outlines
117 :group 'hypermedia
118 :group 'calendar)
119
120 (defcustom org-load-hook nil
121 "Hook that is run after org.el has been loaded."
122 :group 'org
123 :type 'hook)
124
125 (defvar org-modules) ; defined below
126 (defvar org-modules-loaded nil
127 "Have the modules been loaded already?")
128
129 (defun org-load-modules-maybe (&optional force)
130 "Load all extensions listed in `org-modules'."
131 (when (or force (not org-modules-loaded))
132 (mapc (lambda (ext)
133 (condition-case nil (require ext)
134 (error (message "Problems while trying to load feature `%s'" ext))))
135 org-modules)
136 (setq org-modules-loaded t)))
137
138 (defun org-set-modules (var value)
139 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
140 (set var value)
141 (when (featurep 'org)
142 (org-load-modules-maybe 'force)))
143
144 (when (org-bound-and-true-p org-modules)
145 (let ((a (member 'org-infojs org-modules)))
146 (and a (setcar a 'org-jsinfo))))
147
148 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
149 "Modules that should always be loaded together with org.el.
150 If a description starts with <C>, the file is not part of Emacs
151 and loading it will require that you have downloaded and properly installed
152 the org-mode distribution.
153
154 You can also use this system to load external packages (i.e. neither Org
155 core modules, not modules from the CONTRIB directory). Just add symbols
156 to the end of the list. If the package is called org-xyz.el, then you need
157 to add the symbol `xyz', and the package must have a call to
158
159 (provide 'org-xyz)"
160 :group 'org
161 :set 'org-set-modules
162 :type
163 '(set :greedy t
164 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
165 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
166 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
167 (const :tag " id: Global IDs for identifying entries" org-id)
168 (const :tag " info: Links to Info nodes" org-info)
169 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
170 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
171 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
172 (const :tag " mew Links to Mew folders/messages" org-mew)
173 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
174 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
175 (const :tag " vm: Links to VM folders/messages" org-vm)
176 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
177 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
178 (const :tag " mouse: Additional mouse support" org-mouse)
179
180 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
181 (const :tag "C annotation-helper: Call Remember directly from Browser" org-annotation-helper)
182 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
183 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
184 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
185 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
186 (const :tag "C eval: Include command output as text" org-eval)
187 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
188 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
189 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
190 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
191 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
192 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
193 (const :tag "C mtags: Support for muse-like tags" org-mtags)
194 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
195 (const :tag "C registry: A registry for Org links" org-registry)
196 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
197 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
198 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
199 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
200 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
201
202
203 (defgroup org-startup nil
204 "Options concerning startup of Org-mode."
205 :tag "Org Startup"
206 :group 'org)
207
208 (defcustom org-startup-folded t
209 "Non-nil means, entering Org-mode will switch to OVERVIEW.
210 This can also be configured on a per-file basis by adding one of
211 the following lines anywhere in the buffer:
212
213 #+STARTUP: fold
214 #+STARTUP: nofold
215 #+STARTUP: content"
216 :group 'org-startup
217 :type '(choice
218 (const :tag "nofold: show all" nil)
219 (const :tag "fold: overview" t)
220 (const :tag "content: all headlines" content)))
221
222 (defcustom org-startup-truncated t
223 "Non-nil means, entering Org-mode will set `truncate-lines'.
224 This is useful since some lines containing links can be very long and
225 uninteresting. Also tables look terrible when wrapped."
226 :group 'org-startup
227 :type 'boolean)
228
229 (defcustom org-startup-align-all-tables nil
230 "Non-nil means, align all tables when visiting a file.
231 This is useful when the column width in tables is forced with <N> cookies
232 in table fields. Such tables will look correct only after the first re-align.
233 This can also be configured on a per-file basis by adding one of
234 the following lines anywhere in the buffer:
235 #+STARTUP: align
236 #+STARTUP: noalign"
237 :group 'org-startup
238 :type 'boolean)
239
240 (defcustom org-insert-mode-line-in-empty-file nil
241 "Non-nil means insert the first line setting Org-mode in empty files.
242 When the function `org-mode' is called interactively in an empty file, this
243 normally means that the file name does not automatically trigger Org-mode.
244 To ensure that the file will always be in Org-mode in the future, a
245 line enforcing Org-mode will be inserted into the buffer, if this option
246 has been set."
247 :group 'org-startup
248 :type 'boolean)
249
250 (defcustom org-replace-disputed-keys nil
251 "Non-nil means use alternative key bindings for some keys.
252 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
253 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
254 If you want to use Org-mode together with one of these other modes,
255 or more generally if you would like to move some Org-mode commands to
256 other keys, set this variable and configure the keys with the variable
257 `org-disputed-keys'.
258
259 This option is only relevant at load-time of Org-mode, and must be set
260 *before* org.el is loaded. Changing it requires a restart of Emacs to
261 become effective."
262 :group 'org-startup
263 :type 'boolean)
264
265 (defcustom org-use-extra-keys nil
266 "Non-nil means use extra key sequence definitions for certain
267 commands. This happens automatically if you run XEmacs or if
268 window-system is nil. This variable lets you do the same
269 manually. You must set it before loading org.
270
271 Example: on Carbon Emacs 22 running graphically, with an external
272 keyboard on a Powerbook, the default way of setting M-left might
273 not work for either Alt or ESC. Setting this variable will make
274 it work for ESC."
275 :group 'org-startup
276 :type 'boolean)
277
278 (if (fboundp 'defvaralias)
279 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
280
281 (defcustom org-disputed-keys
282 '(([(shift up)] . [(meta p)])
283 ([(shift down)] . [(meta n)])
284 ([(shift left)] . [(meta -)])
285 ([(shift right)] . [(meta +)])
286 ([(control shift right)] . [(meta shift +)])
287 ([(control shift left)] . [(meta shift -)]))
288 "Keys for which Org-mode and other modes compete.
289 This is an alist, cars are the default keys, second element specifies
290 the alternative to use when `org-replace-disputed-keys' is t.
291
292 Keys can be specified in any syntax supported by `define-key'.
293 The value of this option takes effect only at Org-mode's startup,
294 therefore you'll have to restart Emacs to apply it after changing."
295 :group 'org-startup
296 :type 'alist)
297
298 (defun org-key (key)
299 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
300 Or return the original if not disputed."
301 (if org-replace-disputed-keys
302 (let* ((nkey (key-description key))
303 (x (org-find-if (lambda (x)
304 (equal (key-description (car x)) nkey))
305 org-disputed-keys)))
306 (if x (cdr x) key))
307 key))
308
309 (defun org-find-if (predicate seq)
310 (catch 'exit
311 (while seq
312 (if (funcall predicate (car seq))
313 (throw 'exit (car seq))
314 (pop seq)))))
315
316 (defun org-defkey (keymap key def)
317 "Define a key, possibly translated, as returned by `org-key'."
318 (define-key keymap (org-key key) def))
319
320 (defcustom org-ellipsis nil
321 "The ellipsis to use in the Org-mode outline.
322 When nil, just use the standard three dots. When a string, use that instead,
323 When a face, use the standard 3 dots, but with the specified face.
324 The change affects only Org-mode (which will then use its own display table).
325 Changing this requires executing `M-x org-mode' in a buffer to become
326 effective."
327 :group 'org-startup
328 :type '(choice (const :tag "Default" nil)
329 (face :tag "Face" :value org-warning)
330 (string :tag "String" :value "...#")))
331
332 (defvar org-display-table nil
333 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
334
335 (defgroup org-keywords nil
336 "Keywords in Org-mode."
337 :tag "Org Keywords"
338 :group 'org)
339
340 (defcustom org-deadline-string "DEADLINE:"
341 "String to mark deadline entries.
342 A deadline is this string, followed by a time stamp. Should be a word,
343 terminated by a colon. You can insert a schedule keyword and
344 a timestamp with \\[org-deadline].
345 Changes become only effective after restarting Emacs."
346 :group 'org-keywords
347 :type 'string)
348
349 (defcustom org-scheduled-string "SCHEDULED:"
350 "String to mark scheduled TODO entries.
351 A schedule is this string, followed by a time stamp. Should be a word,
352 terminated by a colon. You can insert a schedule keyword and
353 a timestamp with \\[org-schedule].
354 Changes become only effective after restarting Emacs."
355 :group 'org-keywords
356 :type 'string)
357
358 (defcustom org-closed-string "CLOSED:"
359 "String used as the prefix for timestamps logging closing a TODO entry."
360 :group 'org-keywords
361 :type 'string)
362
363 (defcustom org-clock-string "CLOCK:"
364 "String used as prefix for timestamps clocking work hours on an item."
365 :group 'org-keywords
366 :type 'string)
367
368 (defcustom org-comment-string "COMMENT"
369 "Entries starting with this keyword will never be exported.
370 An entry can be toggled between COMMENT and normal with
371 \\[org-toggle-comment].
372 Changes become only effective after restarting Emacs."
373 :group 'org-keywords
374 :type 'string)
375
376 (defcustom org-quote-string "QUOTE"
377 "Entries starting with this keyword will be exported in fixed-width font.
378 Quoting applies only to the text in the entry following the headline, and does
379 not extend beyond the next headline, even if that is lower level.
380 An entry can be toggled between QUOTE and normal with
381 \\[org-toggle-fixed-width-section]."
382 :group 'org-keywords
383 :type 'string)
384
385 (defconst org-repeat-re
386 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
387 "Regular expression for specifying repeated events.
388 After a match, group 1 contains the repeat expression.")
389
390 (defgroup org-structure nil
391 "Options concerning the general structure of Org-mode files."
392 :tag "Org Structure"
393 :group 'org)
394
395 (defgroup org-reveal-location nil
396 "Options about how to make context of a location visible."
397 :tag "Org Reveal Location"
398 :group 'org-structure)
399
400 (defconst org-context-choice
401 '(choice
402 (const :tag "Always" t)
403 (const :tag "Never" nil)
404 (repeat :greedy t :tag "Individual contexts"
405 (cons
406 (choice :tag "Context"
407 (const agenda)
408 (const org-goto)
409 (const occur-tree)
410 (const tags-tree)
411 (const link-search)
412 (const mark-goto)
413 (const bookmark-jump)
414 (const isearch)
415 (const default))
416 (boolean))))
417 "Contexts for the reveal options.")
418
419 (defcustom org-show-hierarchy-above '((default . t))
420 "Non-nil means, show full hierarchy when revealing a location.
421 Org-mode often shows locations in an org-mode file which might have
422 been invisible before. When this is set, the hierarchy of headings
423 above the exposed location is shown.
424 Turning this off for example for sparse trees makes them very compact.
425 Instead of t, this can also be an alist specifying this option for different
426 contexts. Valid contexts are
427 agenda when exposing an entry from the agenda
428 org-goto when using the command `org-goto' on key C-c C-j
429 occur-tree when using the command `org-occur' on key C-c /
430 tags-tree when constructing a sparse tree based on tags matches
431 link-search when exposing search matches associated with a link
432 mark-goto when exposing the jump goal of a mark
433 bookmark-jump when exposing a bookmark location
434 isearch when exiting from an incremental search
435 default default for all contexts not set explicitly"
436 :group 'org-reveal-location
437 :type org-context-choice)
438
439 (defcustom org-show-following-heading '((default . nil))
440 "Non-nil means, show following heading when revealing a location.
441 Org-mode often shows locations in an org-mode file which might have
442 been invisible before. When this is set, the heading following the
443 match is shown.
444 Turning this off for example for sparse trees makes them very compact,
445 but makes it harder to edit the location of the match. In such a case,
446 use the command \\[org-reveal] to show more context.
447 Instead of t, this can also be an alist specifying this option for different
448 contexts. See `org-show-hierarchy-above' for valid contexts."
449 :group 'org-reveal-location
450 :type org-context-choice)
451
452 (defcustom org-show-siblings '((default . nil) (isearch t))
453 "Non-nil means, show all sibling heading when revealing a location.
454 Org-mode often shows locations in an org-mode file which might have
455 been invisible before. When this is set, the sibling of the current entry
456 heading are all made visible. If `org-show-hierarchy-above' is t,
457 the same happens on each level of the hierarchy above the current entry.
458
459 By default this is on for the isearch context, off for all other contexts.
460 Turning this off for example for sparse trees makes them very compact,
461 but makes it harder to edit the location of the match. In such a case,
462 use the command \\[org-reveal] to show more context.
463 Instead of t, this can also be an alist specifying this option for different
464 contexts. See `org-show-hierarchy-above' for valid contexts."
465 :group 'org-reveal-location
466 :type org-context-choice)
467
468 (defcustom org-show-entry-below '((default . nil))
469 "Non-nil means, show the entry below a headline when revealing a location.
470 Org-mode often shows locations in an org-mode file which might have
471 been invisible before. When this is set, the text below the headline that is
472 exposed is also shown.
473
474 By default this is off for all contexts.
475 Instead of t, this can also be an alist specifying this option for different
476 contexts. See `org-show-hierarchy-above' for valid contexts."
477 :group 'org-reveal-location
478 :type org-context-choice)
479
480 (defcustom org-indirect-buffer-display 'other-window
481 "How should indirect tree buffers be displayed?
482 This applies to indirect buffers created with the commands
483 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
484 Valid values are:
485 current-window Display in the current window
486 other-window Just display in another window.
487 dedicated-frame Create one new frame, and re-use it each time.
488 new-frame Make a new frame each time. Note that in this case
489 previously-made indirect buffers are kept, and you need to
490 kill these buffers yourself."
491 :group 'org-structure
492 :group 'org-agenda-windows
493 :type '(choice
494 (const :tag "In current window" current-window)
495 (const :tag "In current frame, other window" other-window)
496 (const :tag "Each time a new frame" new-frame)
497 (const :tag "One dedicated frame" dedicated-frame)))
498
499 (defgroup org-cycle nil
500 "Options concerning visibility cycling in Org-mode."
501 :tag "Org Cycle"
502 :group 'org-structure)
503
504 (defcustom org-drawers '("PROPERTIES" "CLOCK")
505 "Names of drawers. Drawers are not opened by cycling on the headline above.
506 Drawers only open with a TAB on the drawer line itself. A drawer looks like
507 this:
508 :DRAWERNAME:
509 .....
510 :END:
511 The drawer \"PROPERTIES\" is special for capturing properties through
512 the property API.
513
514 Drawers can be defined on the per-file basis with a line like:
515
516 #+DRAWERS: HIDDEN STATE PROPERTIES"
517 :group 'org-structure
518 :type '(repeat (string :tag "Drawer Name")))
519
520 (defcustom org-cycle-global-at-bob nil
521 "Cycle globally if cursor is at beginning of buffer and not at a headline.
522 This makes it possible to do global cycling without having to use S-TAB or
523 C-u TAB. For this special case to work, the first line of the buffer
524 must not be a headline - it may be empty ot some other text. When used in
525 this way, `org-cycle-hook' is disables temporarily, to make sure the
526 cursor stays at the beginning of the buffer.
527 When this option is nil, don't do anything special at the beginning
528 of the buffer."
529 :group 'org-cycle
530 :type 'boolean)
531
532 (defcustom org-cycle-emulate-tab t
533 "Where should `org-cycle' emulate TAB.
534 nil Never
535 white Only in completely white lines
536 whitestart Only at the beginning of lines, before the first non-white char
537 t Everywhere except in headlines
538 exc-hl-bol Everywhere except at the start of a headline
539 If TAB is used in a place where it does not emulate TAB, the current subtree
540 visibility is cycled."
541 :group 'org-cycle
542 :type '(choice (const :tag "Never" nil)
543 (const :tag "Only in completely white lines" white)
544 (const :tag "Before first char in a line" whitestart)
545 (const :tag "Everywhere except in headlines" t)
546 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
547 ))
548
549 (defcustom org-cycle-separator-lines 2
550 "Number of empty lines needed to keep an empty line between collapsed trees.
551 If you leave an empty line between the end of a subtree and the following
552 headline, this empty line is hidden when the subtree is folded.
553 Org-mode will leave (exactly) one empty line visible if the number of
554 empty lines is equal or larger to the number given in this variable.
555 So the default 2 means, at least 2 empty lines after the end of a subtree
556 are needed to produce free space between a collapsed subtree and the
557 following headline.
558
559 Special case: when 0, never leave empty lines in collapsed view."
560 :group 'org-cycle
561 :type 'integer)
562 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
563
564 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
565 org-cycle-hide-drawers
566 org-cycle-show-empty-lines
567 org-optimize-window-after-visibility-change)
568 "Hook that is run after `org-cycle' has changed the buffer visibility.
569 The function(s) in this hook must accept a single argument which indicates
570 the new state that was set by the most recent `org-cycle' command. The
571 argument is a symbol. After a global state change, it can have the values
572 `overview', `content', or `all'. After a local state change, it can have
573 the values `folded', `children', or `subtree'."
574 :group 'org-cycle
575 :type 'hook)
576
577 (defgroup org-edit-structure nil
578 "Options concerning structure editing in Org-mode."
579 :tag "Org Edit Structure"
580 :group 'org-structure)
581
582 (defcustom org-odd-levels-only nil
583 "Non-nil means, skip even levels and only use odd levels for the outline.
584 This has the effect that two stars are being added/taken away in
585 promotion/demotion commands. It also influences how levels are
586 handled by the exporters.
587 Changing it requires restart of `font-lock-mode' to become effective
588 for fontification also in regions already fontified.
589 You may also set this on a per-file basis by adding one of the following
590 lines to the buffer:
591
592 #+STARTUP: odd
593 #+STARTUP: oddeven"
594 :group 'org-edit-structure
595 :group 'org-font-lock
596 :type 'boolean)
597
598 (defcustom org-adapt-indentation t
599 "Non-nil means, adapt indentation when promoting and demoting.
600 When this is set and the *entire* text in an entry is indented, the
601 indentation is increased by one space in a demotion command, and
602 decreased by one in a promotion command. If any line in the entry
603 body starts at column 0, indentation is not changed at all."
604 :group 'org-edit-structure
605 :type 'boolean)
606
607 (defcustom org-special-ctrl-a/e nil
608 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
609 When t, `C-a' will bring back the cursor to the beginning of the
610 headline text, i.e. after the stars and after a possible TODO keyword.
611 In an item, this will be the position after the bullet.
612 When the cursor is already at that position, another `C-a' will bring
613 it to the beginning of the line.
614 `C-e' will jump to the end of the headline, ignoring the presence of tags
615 in the headline. A second `C-e' will then jump to the true end of the
616 line, after any tags.
617 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
618 and only a directly following, identical keypress will bring the cursor
619 to the special positions."
620 :group 'org-edit-structure
621 :type '(choice
622 (const :tag "off" nil)
623 (const :tag "after bullet first" t)
624 (const :tag "border first" reversed)))
625
626 (if (fboundp 'defvaralias)
627 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
628
629 (defcustom org-special-ctrl-k nil
630 "Non-nil means `C-k' will behave specially in headlines.
631 When nil, `C-k' will call the default `kill-line' command.
632 When t, the following will happen while the cursor is in the headline:
633
634 - When the cursor is at the beginning of a headline, kill the entire
635 line and possible the folded subtree below the line.
636 - When in the middle of the headline text, kill the headline up to the tags.
637 - When after the headline text, kill the tags."
638 :group 'org-edit-structure
639 :type 'boolean)
640
641 (defcustom org-yank-folded-subtrees t
642 "Non-nil means, when yanking subtrees, fold them.
643 If the kill is a single subtree, or a sequence of subtrees, i.e. if
644 it starts with a heading and all other headings in it are either children
645 or siblings, then fold all the subtrees. However, do this only if no
646 text after the yank would be swallowed into a folded tree by this action."
647 :group 'org-edit-structure
648 :type 'boolean)
649
650 (defcustom org-yank-adjusted-subtrees t
651 "Non-nil means, when yanking subtrees, adjust the level.
652 With this setting, `org-paste-subtree' is used to insert the subtree, see
653 this function for details."
654 :group 'org-edit-structure
655 :type 'boolean)
656
657 (defcustom org-M-RET-may-split-line '((default . t))
658 "Non-nil means, M-RET will split the line at the cursor position.
659 When nil, it will go to the end of the line before making a
660 new line.
661 You may also set this option in a different way for different
662 contexts. Valid contexts are:
663
664 headline when creating a new headline
665 item when creating a new item
666 table in a table field
667 default the value to be used for all contexts not explicitly
668 customized"
669 :group 'org-structure
670 :group 'org-table
671 :type '(choice
672 (const :tag "Always" t)
673 (const :tag "Never" nil)
674 (repeat :greedy t :tag "Individual contexts"
675 (cons
676 (choice :tag "Context"
677 (const headline)
678 (const item)
679 (const table)
680 (const default))
681 (boolean)))))
682
683
684 (defcustom org-insert-heading-respect-content nil
685 "Non-nil means, insert new headings after the current subtree.
686 When nil, the new heading is created directly after the current line.
687 The commands \\[org-insert-heading-respect-content] and
688 \\[org-insert-todo-heading-respect-content] turn this variable on
689 for the duration of the command."
690 :group 'org-structure
691 :type 'boolean)
692
693 (defcustom org-blank-before-new-entry '((heading . auto)
694 (plain-list-item . auto))
695 "Should `org-insert-heading' leave a blank line before new heading/item?
696 The value is an alist, with `heading' and `plain-list-item' as car,
697 and a boolean flag as cdr."
698 :group 'org-edit-structure
699 :type '(list
700 (cons (const heading)
701 (choice (const :tag "Never" nil)
702 (const :tag "Always" t)
703 (const :tag "Auto" auto)))
704 (cons (const plain-list-item)
705 (choice (const :tag "Never" nil)
706 (const :tag "Always" t)
707 (const :tag "Auto" auto)))))
708
709 (defcustom org-insert-heading-hook nil
710 "Hook being run after inserting a new heading."
711 :group 'org-edit-structure
712 :type 'hook)
713
714 (defcustom org-enable-fixed-width-editor t
715 "Non-nil means, lines starting with \":\" are treated as fixed-width.
716 This currently only means, they are never auto-wrapped.
717 When nil, such lines will be treated like ordinary lines.
718 See also the QUOTE keyword."
719 :group 'org-edit-structure
720 :type 'boolean)
721
722 (defcustom org-edit-src-region-extra nil
723 "Additional regexps to identify regions for editing with `org-edit-src-code'.
724 For examples see the function `org-edit-src-find-region-and-lang'.
725 The regular expression identifying the begin marker should end with a newline,
726 and the regexp marking the end line should start with a newline, to make sure
727 there are kept outside the narrowed region."
728 :group 'org-edit-structure
729 :type '(repeat
730 (list
731 (regexp :tag "begin regexp")
732 (regexp :tag "end regexp")
733 (choice :tag "language"
734 (string :tag "specify")
735 (integer :tag "from match group")
736 (const :tag "from `lang' element")
737 (const :tag "from `style' element")))))
738
739 (defcustom org-coderef-label-format "(ref:%s)"
740 "The default coderef format.
741 This format string will be used to search for coderef labels in literal
742 examples (EXAMPLE and SRC blocks). The format can be overwritten
743 an individual literal example with the -f option, like
744
745 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
746 ...
747 #+END_SRC
748
749 If you want to use this for HTML export, make sure that the format does
750 not introduce special font-locking, and avoid the HTML special
751 characters `<', `>', and `&'. The reason for this restriction is that
752 the labels are searched for only after htmlize has done its job."
753 :group 'org-edit-structure ; FIXME this is not in the right group
754 :type 'string)
755
756 (defcustom org-edit-fixed-width-region-mode 'artist-mode
757 "The mode that should be used to edit fixed-width regions.
758 These are the regions where each line starts with a colon."
759 :group 'org-edit-structure
760 :type '(choice
761 (const artist-mode)
762 (const picture-mode)
763 (const fundamental-mode)
764 (function :tag "Other (specify)")))
765
766 (defcustom org-goto-auto-isearch t
767 "Non-nil means, typing characters in org-goto starts incremental search."
768 :group 'org-edit-structure
769 :type 'boolean)
770
771 (defgroup org-sparse-trees nil
772 "Options concerning sparse trees in Org-mode."
773 :tag "Org Sparse Trees"
774 :group 'org-structure)
775
776 (defcustom org-highlight-sparse-tree-matches t
777 "Non-nil means, highlight all matches that define a sparse tree.
778 The highlights will automatically disappear the next time the buffer is
779 changed by an edit command."
780 :group 'org-sparse-trees
781 :type 'boolean)
782
783 (defcustom org-remove-highlights-with-change t
784 "Non-nil means, any change to the buffer will remove temporary highlights.
785 Such highlights are created by `org-occur' and `org-clock-display'.
786 When nil, `C-c C-c needs to be used to get rid of the highlights.
787 The highlights created by `org-preview-latex-fragment' always need
788 `C-c C-c' to be removed."
789 :group 'org-sparse-trees
790 :group 'org-time
791 :type 'boolean)
792
793
794 (defcustom org-occur-hook '(org-first-headline-recenter)
795 "Hook that is run after `org-occur' has constructed a sparse tree.
796 This can be used to recenter the window to show as much of the structure
797 as possible."
798 :group 'org-sparse-trees
799 :type 'hook)
800
801 (defgroup org-imenu-and-speedbar nil
802 "Options concerning imenu and speedbar in Org-mode."
803 :tag "Org Imenu and Speedbar"
804 :group 'org-structure)
805
806 (defcustom org-imenu-depth 2
807 "The maximum level for Imenu access to Org-mode headlines.
808 This also applied for speedbar access."
809 :group 'org-imenu-and-speedbar
810 :type 'number)
811
812 (defgroup org-table nil
813 "Options concerning tables in Org-mode."
814 :tag "Org Table"
815 :group 'org)
816
817 (defcustom org-enable-table-editor 'optimized
818 "Non-nil means, lines starting with \"|\" are handled by the table editor.
819 When nil, such lines will be treated like ordinary lines.
820
821 When equal to the symbol `optimized', the table editor will be optimized to
822 do the following:
823 - Automatic overwrite mode in front of whitespace in table fields.
824 This makes the structure of the table stay in tact as long as the edited
825 field does not exceed the column width.
826 - Minimize the number of realigns. Normally, the table is aligned each time
827 TAB or RET are pressed to move to another field. With optimization this
828 happens only if changes to a field might have changed the column width.
829 Optimization requires replacing the functions `self-insert-command',
830 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
831 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
832 very good at guessing when a re-align will be necessary, but you can always
833 force one with \\[org-ctrl-c-ctrl-c].
834
835 If you would like to use the optimized version in Org-mode, but the
836 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
837
838 This variable can be used to turn on and off the table editor during a session,
839 but in order to toggle optimization, a restart is required.
840
841 See also the variable `org-table-auto-blank-field'."
842 :group 'org-table
843 :type '(choice
844 (const :tag "off" nil)
845 (const :tag "on" t)
846 (const :tag "on, optimized" optimized)))
847
848 (defcustom org-table-tab-recognizes-table.el t
849 "Non-nil means, TAB will automatically notice a table.el table.
850 When it sees such a table, it moves point into it and - if necessary -
851 calls `table-recognize-table'."
852 :group 'org-table-editing
853 :type 'boolean)
854
855 (defgroup org-link nil
856 "Options concerning links in Org-mode."
857 :tag "Org Link"
858 :group 'org)
859
860 (defvar org-link-abbrev-alist-local nil
861 "Buffer-local version of `org-link-abbrev-alist', which see.
862 The value of this is taken from the #+LINK lines.")
863 (make-variable-buffer-local 'org-link-abbrev-alist-local)
864
865 (defcustom org-link-abbrev-alist nil
866 "Alist of link abbreviations.
867 The car of each element is a string, to be replaced at the start of a link.
868 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
869 links in Org-mode buffers can have an optional tag after a double colon, e.g.
870
871 [[linkkey:tag][description]]
872
873 If REPLACE is a string, the tag will simply be appended to create the link.
874 If the string contains \"%s\", the tag will be inserted there. Alternatively,
875 the placeholder \"%h\" will cause a url-encoded version of the tag to
876 be inserted at that point (see the function `url-hexify-string').
877
878 REPLACE may also be a function that will be called with the tag as the
879 only argument to create the link, which should be returned as a string.
880
881 See the manual for examples."
882 :group 'org-link
883 :type '(repeat
884 (cons
885 (string :tag "Protocol")
886 (choice
887 (string :tag "Format")
888 (function)))))
889
890 (defcustom org-descriptive-links t
891 "Non-nil means, hide link part and only show description of bracket links.
892 Bracket links are like [[link][description]]. This variable sets the initial
893 state in new org-mode buffers. The setting can then be toggled on a
894 per-buffer basis from the Org->Hyperlinks menu."
895 :group 'org-link
896 :type 'boolean)
897
898 (defcustom org-link-file-path-type 'adaptive
899 "How the path name in file links should be stored.
900 Valid values are:
901
902 relative Relative to the current directory, i.e. the directory of the file
903 into which the link is being inserted.
904 absolute Absolute path, if possible with ~ for home directory.
905 noabbrev Absolute path, no abbreviation of home directory.
906 adaptive Use relative path for files in the current directory and sub-
907 directories of it. For other files, use an absolute path."
908 :group 'org-link
909 :type '(choice
910 (const relative)
911 (const absolute)
912 (const noabbrev)
913 (const adaptive)))
914
915 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
916 "Types of links that should be activated in Org-mode files.
917 This is a list of symbols, each leading to the activation of a certain link
918 type. In principle, it does not hurt to turn on most link types - there may
919 be a small gain when turning off unused link types. The types are:
920
921 bracket The recommended [[link][description]] or [[link]] links with hiding.
922 angular Links in angular brackets that may contain whitespace like
923 <bbdb:Carsten Dominik>.
924 plain Plain links in normal text, no whitespace, like http://google.com.
925 radio Text that is matched by a radio target, see manual for details.
926 tag Tag settings in a headline (link to tag search).
927 date Time stamps (link to calendar).
928 footnote Footnote labels.
929
930 Changing this variable requires a restart of Emacs to become effective."
931 :group 'org-link
932 :type '(set :greedy t
933 (const :tag "Double bracket links (new style)" bracket)
934 (const :tag "Angular bracket links (old style)" angular)
935 (const :tag "Plain text links" plain)
936 (const :tag "Radio target matches" radio)
937 (const :tag "Tags" tag)
938 (const :tag "Timestamps" date)
939 (const :tag "Footnotes" footnote)))
940
941 (defcustom org-make-link-description-function nil
942 "Function to use to generate link descriptions from links. If
943 nil the link location will be used. This function must take two
944 parameters; the first is the link and the second the description
945 org-insert-link has generated, and should return the description
946 to use."
947 :group 'org-link
948 :type 'function)
949
950 (defgroup org-link-store nil
951 "Options concerning storing links in Org-mode."
952 :tag "Org Store Link"
953 :group 'org-link)
954
955 (defcustom org-email-link-description-format "Email %c: %.30s"
956 "Format of the description part of a link to an email or usenet message.
957 The following %-escapes will be replaced by corresponding information:
958
959 %F full \"From\" field
960 %f name, taken from \"From\" field, address if no name
961 %T full \"To\" field
962 %t first name in \"To\" field, address if no name
963 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
964 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
965 %s subject
966 %m message-id.
967
968 You may use normal field width specification between the % and the letter.
969 This is for example useful to limit the length of the subject.
970
971 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
972 :group 'org-link-store
973 :type 'string)
974
975 (defcustom org-from-is-user-regexp
976 (let (r1 r2)
977 (when (and user-mail-address (not (string= user-mail-address "")))
978 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
979 (when (and user-full-name (not (string= user-full-name "")))
980 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
981 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
982 "Regexp matched against the \"From:\" header of an email or usenet message.
983 It should match if the message is from the user him/herself."
984 :group 'org-link-store
985 :type 'regexp)
986
987 (defcustom org-link-to-org-use-id 'create-if-interactive
988 "Non-nil means, storing a link to an Org file will use entry IDs.
989
990 Note that before this variable is even considered, org-id must be loaded,
991 to please customize `org-modules' and turn it on.
992
993 The variable can have the following values:
994
995 t Create an ID if needed to make a link to the current entry.
996
997 create-if-interactive
998 If `org-store-link' is called directly (interactively, as a user
999 command), do create an ID to support the link. But when doing the
1000 job for remember, only use the ID if it already exists. The
1001 purpose of this setting is to avoid proliferation of unwanted
1002 IDs, just because you happen to be in an Org file when you
1003 call `org-remember' that automatically and preemptively
1004 creates a link. If you do want to get an ID link in a remember
1005 template to an entry not having an ID, create it first by
1006 explicitly creating a link to it, using `C-c C-l' first.
1007
1008 use-existing
1009 Use existing ID, do not create one.
1010
1011 nil Never use an ID to make a link, instead link using a text search for
1012 the headline text."
1013 :group 'org-link-store
1014 :type '(choice
1015 (const :tag "Create ID to make link" t)
1016 (const :tag "Create if string link interactively"
1017 'create-if-interactive)
1018 (const :tag "Only use existing" 'use-existing)
1019 (const :tag "Do not use ID to create link" nil)))
1020
1021 (defcustom org-context-in-file-links t
1022 "Non-nil means, file links from `org-store-link' contain context.
1023 A search string will be added to the file name with :: as separator and
1024 used to find the context when the link is activated by the command
1025 `org-open-at-point'.
1026 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1027 negates this setting for the duration of the command."
1028 :group 'org-link-store
1029 :type 'boolean)
1030
1031 (defcustom org-keep-stored-link-after-insertion nil
1032 "Non-nil means, keep link in list for entire session.
1033
1034 The command `org-store-link' adds a link pointing to the current
1035 location to an internal list. These links accumulate during a session.
1036 The command `org-insert-link' can be used to insert links into any
1037 Org-mode file (offering completion for all stored links). When this
1038 option is nil, every link which has been inserted once using \\[org-insert-link]
1039 will be removed from the list, to make completing the unused links
1040 more efficient."
1041 :group 'org-link-store
1042 :type 'boolean)
1043
1044 (defgroup org-link-follow nil
1045 "Options concerning following links in Org-mode."
1046 :tag "Org Follow Link"
1047 :group 'org-link)
1048
1049 (defcustom org-link-translation-function nil
1050 "Function to translate links with different syntax to Org syntax.
1051 This can be used to translate links created for example by the Planner
1052 or emacs-wiki packages to Org syntax.
1053 The function must accept two parameters, a TYPE containing the link
1054 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1055 which is everything after the link protocol. It should return a cons
1056 with possibly modified values of type and path.
1057 Org contains a function for this, so if you set this variable to
1058 `org-translate-link-from-planner', you should be able follow many
1059 links created by planner."
1060 :group 'org-link-follow
1061 :type 'function)
1062
1063 (defcustom org-follow-link-hook nil
1064 "Hook that is run after a link has been followed."
1065 :group 'org-link-follow
1066 :type 'hook)
1067
1068 (defcustom org-tab-follows-link nil
1069 "Non-nil means, on links TAB will follow the link.
1070 Needs to be set before org.el is loaded."
1071 :group 'org-link-follow
1072 :type 'boolean)
1073
1074 (defcustom org-return-follows-link nil
1075 "Non-nil means, on links RET will follow the link.
1076 Needs to be set before org.el is loaded."
1077 :group 'org-link-follow
1078 :type 'boolean)
1079
1080 (defcustom org-mouse-1-follows-link
1081 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1082 "Non-nil means, mouse-1 on a link will follow the link.
1083 A longer mouse click will still set point. Does not work on XEmacs.
1084 Needs to be set before org.el is loaded."
1085 :group 'org-link-follow
1086 :type 'boolean)
1087
1088 (defcustom org-mark-ring-length 4
1089 "Number of different positions to be recorded in the ring
1090 Changing this requires a restart of Emacs to work correctly."
1091 :group 'org-link-follow
1092 :type 'integer)
1093
1094 (defcustom org-link-frame-setup
1095 '((vm . vm-visit-folder-other-frame)
1096 (gnus . gnus-other-frame)
1097 (file . find-file-other-window))
1098 "Setup the frame configuration for following links.
1099 When following a link with Emacs, it may often be useful to display
1100 this link in another window or frame. This variable can be used to
1101 set this up for the different types of links.
1102 For VM, use any of
1103 `vm-visit-folder'
1104 `vm-visit-folder-other-frame'
1105 For Gnus, use any of
1106 `gnus'
1107 `gnus-other-frame'
1108 `org-gnus-no-new-news'
1109 For FILE, use any of
1110 `find-file'
1111 `find-file-other-window'
1112 `find-file-other-frame'
1113 For the calendar, use the variable `calendar-setup'.
1114 For BBDB, it is currently only possible to display the matches in
1115 another window."
1116 :group 'org-link-follow
1117 :type '(list
1118 (cons (const vm)
1119 (choice
1120 (const vm-visit-folder)
1121 (const vm-visit-folder-other-window)
1122 (const vm-visit-folder-other-frame)))
1123 (cons (const gnus)
1124 (choice
1125 (const gnus)
1126 (const gnus-other-frame)
1127 (const org-gnus-no-new-news)))
1128 (cons (const file)
1129 (choice
1130 (const find-file)
1131 (const find-file-other-window)
1132 (const find-file-other-frame)))))
1133
1134 (defcustom org-display-internal-link-with-indirect-buffer nil
1135 "Non-nil means, use indirect buffer to display infile links.
1136 Activating internal links (from one location in a file to another location
1137 in the same file) normally just jumps to the location. When the link is
1138 activated with a C-u prefix (or with mouse-3), the link is displayed in
1139 another window. When this option is set, the other window actually displays
1140 an indirect buffer clone of the current buffer, to avoid any visibility
1141 changes to the current buffer."
1142 :group 'org-link-follow
1143 :type 'boolean)
1144
1145 (defcustom org-open-non-existing-files nil
1146 "Non-nil means, `org-open-file' will open non-existing files.
1147 When nil, an error will be generated."
1148 :group 'org-link-follow
1149 :type 'boolean)
1150
1151 (defcustom org-open-directory-means-index-dot-org nil
1152 "Non-nil means, a link to a directory really means to index.org.
1153 When nil, following a directory link will run dired or open a finder/explorer
1154 window on that directory."
1155 :group 'org-link-follow
1156 :type 'boolean)
1157
1158 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1159 "Function and arguments to call for following mailto links.
1160 This is a list with the first element being a lisp function, and the
1161 remaining elements being arguments to the function. In string arguments,
1162 %a will be replaced by the address, and %s will be replaced by the subject
1163 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1164 :group 'org-link-follow
1165 :type '(choice
1166 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1167 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1168 (const :tag "message-mail" (message-mail "%a" "%s"))
1169 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1170
1171 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1172 "Non-nil means, ask for confirmation before executing shell links.
1173 Shell links can be dangerous: just think about a link
1174
1175 [[shell:rm -rf ~/*][Google Search]]
1176
1177 This link would show up in your Org-mode document as \"Google Search\",
1178 but really it would remove your entire home directory.
1179 Therefore we advise against setting this variable to nil.
1180 Just change it to `y-or-n-p' of you want to confirm with a
1181 single keystroke rather than having to type \"yes\"."
1182 :group 'org-link-follow
1183 :type '(choice
1184 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1185 (const :tag "with y-or-n (faster)" y-or-n-p)
1186 (const :tag "no confirmation (dangerous)" nil)))
1187
1188 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1189 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1190 Elisp links can be dangerous: just think about a link
1191
1192 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1193
1194 This link would show up in your Org-mode document as \"Google Search\",
1195 but really it would remove your entire home directory.
1196 Therefore we advise against setting this variable to nil.
1197 Just change it to `y-or-n-p' of you want to confirm with a
1198 single keystroke rather than having to type \"yes\"."
1199 :group 'org-link-follow
1200 :type '(choice
1201 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1202 (const :tag "with y-or-n (faster)" y-or-n-p)
1203 (const :tag "no confirmation (dangerous)" nil)))
1204
1205 (defconst org-file-apps-defaults-gnu
1206 '((remote . emacs)
1207 (system . mailcap)
1208 (t . mailcap))
1209 "Default file applications on a UNIX or GNU/Linux system.
1210 See `org-file-apps'.")
1211
1212 (defconst org-file-apps-defaults-macosx
1213 '((remote . emacs)
1214 (t . "open %s")
1215 (system . "open %s")
1216 ("ps.gz" . "gv %s")
1217 ("eps.gz" . "gv %s")
1218 ("dvi" . "xdvi %s")
1219 ("fig" . "xfig %s"))
1220 "Default file applications on a MacOS X system.
1221 The system \"open\" is known as a default, but we use X11 applications
1222 for some files for which the OS does not have a good default.
1223 See `org-file-apps'.")
1224
1225 (defconst org-file-apps-defaults-windowsnt
1226 (list
1227 '(remote . emacs)
1228 (cons t
1229 (list (if (featurep 'xemacs)
1230 'mswindows-shell-execute
1231 'w32-shell-execute)
1232 "open" 'file))
1233 (cons 'system
1234 (list (if (featurep 'xemacs)
1235 'mswindows-shell-execute
1236 'w32-shell-execute)
1237 "open" 'file)))
1238 "Default file applications on a Windows NT system.
1239 The system \"open\" is used for most files.
1240 See `org-file-apps'.")
1241
1242 (defcustom org-file-apps
1243 '(
1244 (auto-mode . emacs)
1245 ("\\.x?html?\\'" . default)
1246 ("\\.pdf\\'" . default)
1247 )
1248 "External applications for opening `file:path' items in a document.
1249 Org-mode uses system defaults for different file types, but
1250 you can use this variable to set the application for a given file
1251 extension. The entries in this list are cons cells where the car identifies
1252 files and the cdr the corresponding command. Possible values for the
1253 file identifier are
1254 \"regex\" Regular expression matched against the file name. For backward
1255 compatibility, this can also be a string with only alphanumeric
1256 characters, which is then interpreted as an extension.
1257 `directory' Matches a directory
1258 `remote' Matches a remote file, accessible through tramp or efs.
1259 Remote files most likely should be visited through Emacs
1260 because external applications cannot handle such paths.
1261 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1262 so all files Emacs knows how to handle. Using this with
1263 command `emacs' will open most files in Emacs. Beware that this
1264 will also open html files inside Emacs, unless you add
1265 (\"html\" . default) to the list as well.
1266 t Default for files not matched by any of the other options.
1267 `system' The system command to open files, like `open' on Windows
1268 and Mac OS X, and mailcap under GNU/Linux. This is the command
1269 that will be selected if you call `C-c C-o' with a double
1270 `C-u C-u' prefix.
1271
1272 Possible values for the command are:
1273 `emacs' The file will be visited by the current Emacs process.
1274 `default' Use the default application for this file type, which is the
1275 association for t in the list, most likely in the system-specific
1276 part.
1277 This can be used to overrule an unwanted setting in the
1278 system-specific variable.
1279 `system' Use the system command for opening files, like \"open\".
1280 This command is specified by the entry whose car is `system'.
1281 Most likely, the system-specific version of this variable
1282 does define this command, but you can overrule/replace it
1283 here.
1284 string A command to be executed by a shell; %s will be replaced
1285 by the path to the file.
1286 sexp A Lisp form which will be evaluated. The file path will
1287 be available in the Lisp variable `file'.
1288 For more examples, see the system specific constants
1289 `org-file-apps-defaults-macosx'
1290 `org-file-apps-defaults-windowsnt'
1291 `org-file-apps-defaults-gnu'."
1292 :group 'org-link-follow
1293 :type '(repeat
1294 (cons (choice :value ""
1295 (string :tag "Extension")
1296 (const :tag "System command to open files" system)
1297 (const :tag "Default for unrecognized files" t)
1298 (const :tag "Remote file" remote)
1299 (const :tag "Links to a directory" directory)
1300 (const :tag "Any files that have Emacs modes"
1301 auto-mode))
1302 (choice :value ""
1303 (const :tag "Visit with Emacs" emacs)
1304 (const :tag "Use default" default)
1305 (const :tag "Use the system command" system)
1306 (string :tag "Command")
1307 (sexp :tag "Lisp form")))))
1308
1309 (defgroup org-refile nil
1310 "Options concerning refiling entries in Org-mode."
1311 :tag "Org Refile"
1312 :group 'org)
1313
1314 (defcustom org-directory "~/org"
1315 "Directory with org files.
1316 This directory will be used as default to prompt for org files.
1317 Used by the hooks for remember.el."
1318 :group 'org-refile
1319 :group 'org-remember
1320 :type 'directory)
1321
1322 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1323 "Default target for storing notes.
1324 Used by the hooks for remember.el. This can be a string, or nil to mean
1325 the value of `remember-data-file'.
1326 You can set this on a per-template basis with the variable
1327 `org-remember-templates'."
1328 :group 'org-refile
1329 :group 'org-remember
1330 :type '(choice
1331 (const :tag "Default from remember-data-file" nil)
1332 file))
1333
1334 (defcustom org-goto-interface 'outline
1335 "The default interface to be used for `org-goto'.
1336 Allowed values are:
1337 outline The interface shows an outline of the relevant file
1338 and the correct heading is found by moving through
1339 the outline or by searching with incremental search.
1340 outline-path-completion Headlines in the current buffer are offered via
1341 completion. This is the interface also used by
1342 the refile command."
1343 :group 'org-refile
1344 :type '(choice
1345 (const :tag "Outline" outline)
1346 (const :tag "Outline-path-completion" outline-path-completion)))
1347
1348 (defcustom org-goto-max-level 5
1349 "Maximum level to be considered when running org-goto with refile interface."
1350 :group 'org-refile
1351 :type 'number)
1352
1353 (defcustom org-reverse-note-order nil
1354 "Non-nil means, store new notes at the beginning of a file or entry.
1355 When nil, new notes will be filed to the end of a file or entry.
1356 This can also be a list with cons cells of regular expressions that
1357 are matched against file names, and values."
1358 :group 'org-remember
1359 :group 'org-refile
1360 :type '(choice
1361 (const :tag "Reverse always" t)
1362 (const :tag "Reverse never" nil)
1363 (repeat :tag "By file name regexp"
1364 (cons regexp boolean))))
1365
1366 (defcustom org-refile-targets nil
1367 "Targets for refiling entries with \\[org-refile].
1368 This is list of cons cells. Each cell contains:
1369 - a specification of the files to be considered, either a list of files,
1370 or a symbol whose function or variable value will be used to retrieve
1371 a file name or a list of file names. If you use `org-agenda-files' for
1372 that, all agenda files will be scanned for targets. Nil means, consider
1373 headings in the current buffer.
1374 - A specification of how to select find candidate refile targets. This
1375 may be any of
1376 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1377 This tag has to be present in all target headlines, inheritance will
1378 not be considered.
1379 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1380 todo keyword.
1381 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1382 headlines that are refiling targets.
1383 - a cons cell (:level . N). Any headline of level N is considered a target.
1384 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1385
1386 When this variable is nil, all top-level headlines in the current buffer
1387 are used, equivalent to the value `((nil . (:level . 1))'."
1388 :group 'org-refile
1389 :type '(repeat
1390 (cons
1391 (choice :value org-agenda-files
1392 (const :tag "All agenda files" org-agenda-files)
1393 (const :tag "Current buffer" nil)
1394 (function) (variable) (file))
1395 (choice :tag "Identify target headline by"
1396 (cons :tag "Specific tag" (const :value :tag) (string))
1397 (cons :tag "TODO keyword" (const :value :todo) (string))
1398 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1399 (cons :tag "Level number" (const :value :level) (integer))
1400 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1401
1402 (defcustom org-refile-use-outline-path nil
1403 "Non-nil means, provide refile targets as paths.
1404 So a level 3 headline will be available as level1/level2/level3.
1405 When the value is `file', also include the file name (without directory)
1406 into the path. When `full-file-path', include the full file path."
1407 :group 'org-refile
1408 :type '(choice
1409 (const :tag "Not" nil)
1410 (const :tag "Yes" t)
1411 (const :tag "Start with file name" file)
1412 (const :tag "Start with full file path" full-file-path)))
1413
1414 (defcustom org-outline-path-complete-in-steps t
1415 "Non-nil means, complete the outline path in hierarchical steps.
1416 When Org-mode uses the refile interface to select an outline path
1417 \(see variable `org-refile-use-outline-path'), the completion of
1418 the path can be done is a single go, or if can be done in steps down
1419 the headline hierarchy. Going in steps is probably the best if you
1420 do not use a special completion package like `ido' or `icicles'.
1421 However, when using these packages, going in one step can be very
1422 fast, while still showing the whole path to the entry."
1423 :group 'org-refile
1424 :type 'boolean)
1425
1426 (defgroup org-todo nil
1427 "Options concerning TODO items in Org-mode."
1428 :tag "Org TODO"
1429 :group 'org)
1430
1431 (defgroup org-progress nil
1432 "Options concerning Progress logging in Org-mode."
1433 :tag "Org Progress"
1434 :group 'org-time)
1435
1436 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1437 "List of TODO entry keyword sequences and their interpretation.
1438 \\<org-mode-map>This is a list of sequences.
1439
1440 Each sequence starts with a symbol, either `sequence' or `type',
1441 indicating if the keywords should be interpreted as a sequence of
1442 action steps, or as different types of TODO items. The first
1443 keywords are states requiring action - these states will select a headline
1444 for inclusion into the global TODO list Org-mode produces. If one of
1445 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1446 signify that no further action is necessary. If \"|\" is not found,
1447 the last keyword is treated as the only DONE state of the sequence.
1448
1449 The command \\[org-todo] cycles an entry through these states, and one
1450 additional state where no keyword is present. For details about this
1451 cycling, see the manual.
1452
1453 TODO keywords and interpretation can also be set on a per-file basis with
1454 the special #+SEQ_TODO and #+TYP_TODO lines.
1455
1456 Each keyword can optionally specify a character for fast state selection
1457 \(in combination with the variable `org-use-fast-todo-selection')
1458 and specifiers for state change logging, using the same syntax
1459 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1460 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1461 indicates to record a time stamp each time this state is selected.
1462
1463 Each keyword may also specify if a timestamp or a note should be
1464 recorded when entering or leaving the state, by adding additional
1465 characters in the parenthesis after the keyword. This looks like this:
1466 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1467 record only the time of the state change. With X and Y being either
1468 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1469 Y when leaving the state if and only if the *target* state does not
1470 define X. You may omit any of the fast-selection key or X or /Y,
1471 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1472
1473 For backward compatibility, this variable may also be just a list
1474 of keywords - in this case the interpretation (sequence or type) will be
1475 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1476 :group 'org-todo
1477 :group 'org-keywords
1478 :type '(choice
1479 (repeat :tag "Old syntax, just keywords"
1480 (string :tag "Keyword"))
1481 (repeat :tag "New syntax"
1482 (cons
1483 (choice
1484 :tag "Interpretation"
1485 (const :tag "Sequence (cycling hits every state)" sequence)
1486 (const :tag "Type (cycling directly to DONE)" type))
1487 (repeat
1488 (string :tag "Keyword"))))))
1489
1490 (defvar org-todo-keywords-1 nil
1491 "All TODO and DONE keywords active in a buffer.")
1492 (make-variable-buffer-local 'org-todo-keywords-1)
1493 (defvar org-todo-keywords-for-agenda nil)
1494 (defvar org-done-keywords-for-agenda nil)
1495 (defvar org-todo-keyword-alist-for-agenda nil)
1496 (defvar org-tag-alist-for-agenda nil)
1497 (defvar org-agenda-contributing-files nil)
1498 (defvar org-not-done-keywords nil)
1499 (make-variable-buffer-local 'org-not-done-keywords)
1500 (defvar org-done-keywords nil)
1501 (make-variable-buffer-local 'org-done-keywords)
1502 (defvar org-todo-heads nil)
1503 (make-variable-buffer-local 'org-todo-heads)
1504 (defvar org-todo-sets nil)
1505 (make-variable-buffer-local 'org-todo-sets)
1506 (defvar org-todo-log-states nil)
1507 (make-variable-buffer-local 'org-todo-log-states)
1508 (defvar org-todo-kwd-alist nil)
1509 (make-variable-buffer-local 'org-todo-kwd-alist)
1510 (defvar org-todo-key-alist nil)
1511 (make-variable-buffer-local 'org-todo-key-alist)
1512 (defvar org-todo-key-trigger nil)
1513 (make-variable-buffer-local 'org-todo-key-trigger)
1514
1515 (defcustom org-todo-interpretation 'sequence
1516 "Controls how TODO keywords are interpreted.
1517 This variable is in principle obsolete and is only used for
1518 backward compatibility, if the interpretation of todo keywords is
1519 not given already in `org-todo-keywords'. See that variable for
1520 more information."
1521 :group 'org-todo
1522 :group 'org-keywords
1523 :type '(choice (const sequence)
1524 (const type)))
1525
1526 (defcustom org-use-fast-todo-selection 'prefix
1527 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1528 This variable describes if and under what circumstances the cycling
1529 mechanism for TODO keywords will be replaced by a single-key, direct
1530 selection scheme.
1531
1532 When nil, fast selection is never used.
1533
1534 When the symbol `prefix', it will be used when `org-todo' is called with
1535 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1536 in an agenda buffer.
1537
1538 When t, fast selection is used by default. In this case, the prefix
1539 argument forces cycling instead.
1540
1541 In all cases, the special interface is only used if access keys have actually
1542 been assigned by the user, i.e. if keywords in the configuration are followed
1543 by a letter in parenthesis, like TODO(t)."
1544 :group 'org-todo
1545 :type '(choice
1546 (const :tag "Never" nil)
1547 (const :tag "By default" t)
1548 (const :tag "Only with C-u C-c C-t" prefix)))
1549
1550 (defcustom org-provide-todo-statistics t
1551 "Non-nil means, update todo statistics after insert and toggle.
1552 When this is set, todo statistics is updated in the parent of the current
1553 entry each time a todo state is changed."
1554 :group 'org-todo
1555 :type 'boolean)
1556
1557 (defcustom org-after-todo-state-change-hook nil
1558 "Hook which is run after the state of a TODO item was changed.
1559 The new state (a string with a TODO keyword, or nil) is available in the
1560 Lisp variable `state'."
1561 :group 'org-todo
1562 :type 'hook)
1563
1564 (defcustom org-todo-state-tags-triggers nil
1565 "Tag changes that should be triggered by TODO state changes.
1566 This is a list. Each entry is
1567
1568 (state-change (tag . flag) .......)
1569
1570 State-change can be a string with a state, and empty string to indicate the
1571 state that has no TODO keyword, or it can be one of the symbols `todo'
1572 or `done', meaning any not-done or done state, respectively."
1573 :group 'org-todo
1574 :group 'org-tags
1575 :type '(repeat
1576 (cons (choice :tag "When changing to"
1577 (const :tag "Not-done state" todo)
1578 (const :tag "Done state" done)
1579 (string :tag "State"))
1580 (repeat
1581 (cons :tag "Tag action"
1582 (string :tag "Tag")
1583 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1584
1585 (defcustom org-log-done nil
1586 "Information to record when a task moves to the DONE state.
1587
1588 Possible values are:
1589
1590 nil Don't add anything, just change the keyword
1591 time Add a time stamp to the task
1592 note Prompt a closing note and add it with template `org-log-note-headings'
1593
1594 This option can also be set with on a per-file-basis with
1595
1596 #+STARTUP: nologdone
1597 #+STARTUP: logdone
1598 #+STARTUP: lognotedone
1599
1600 You can have local logging settings for a subtree by setting the LOGGING
1601 property to one or more of these keywords."
1602 :group 'org-todo
1603 :group 'org-progress
1604 :type '(choice
1605 (const :tag "No logging" nil)
1606 (const :tag "Record CLOSED timestamp" time)
1607 (const :tag "Record CLOSED timestamp with closing note." note)))
1608
1609 ;; Normalize old uses of org-log-done.
1610 (cond
1611 ((eq org-log-done t) (setq org-log-done 'time))
1612 ((and (listp org-log-done) (memq 'done org-log-done))
1613 (setq org-log-done 'note)))
1614
1615 (defcustom org-log-note-clock-out nil
1616 "Non-nil means, record a note when clocking out of an item.
1617 This can also be configured on a per-file basis by adding one of
1618 the following lines anywhere in the buffer:
1619
1620 #+STARTUP: lognoteclock-out
1621 #+STARTUP: nolognoteclock-out"
1622 :group 'org-todo
1623 :group 'org-progress
1624 :type 'boolean)
1625
1626 (defcustom org-log-done-with-time t
1627 "Non-nil means, the CLOSED time stamp will contain date and time.
1628 When nil, only the date will be recorded."
1629 :group 'org-progress
1630 :type 'boolean)
1631
1632 (defcustom org-log-note-headings
1633 '((done . "CLOSING NOTE %t")
1634 (state . "State %-12s %t")
1635 (note . "Note taken on %t")
1636 (clock-out . ""))
1637 "Headings for notes added to entries.
1638 The value is an alist, with the car being a symbol indicating the note
1639 context, and the cdr is the heading to be used. The heading may also be the
1640 empty string.
1641 %t in the heading will be replaced by a time stamp.
1642 %s will be replaced by the new TODO state, in double quotes.
1643 %u will be replaced by the user name.
1644 %U will be replaced by the full user name."
1645 :group 'org-todo
1646 :group 'org-progress
1647 :type '(list :greedy t
1648 (cons (const :tag "Heading when closing an item" done) string)
1649 (cons (const :tag
1650 "Heading when changing todo state (todo sequence only)"
1651 state) string)
1652 (cons (const :tag "Heading when just taking a note" note) string)
1653 (cons (const :tag "Heading when clocking out" clock-out) string)))
1654
1655 (unless (assq 'note org-log-note-headings)
1656 (push '(note . "%t") org-log-note-headings))
1657
1658 (defcustom org-log-state-notes-insert-after-drawers nil
1659 "Non-nil means, insert state change notes after any drawers in entry.
1660 Only the drawers that *immediately* follow the headline and the
1661 deadline/scheduled line are skipped.
1662 When nil, insert notes right after the heading and perhaps the line
1663 with deadline/scheduling if present."
1664 :group 'org-todo
1665 :group 'org-progress
1666 :type 'boolean)
1667
1668 (defcustom org-log-states-order-reversed t
1669 "Non-nil means, the latest state change note will be directly after heading.
1670 When nil, the notes will be orderer according to time."
1671 :group 'org-todo
1672 :group 'org-progress
1673 :type 'boolean)
1674
1675 (defcustom org-log-repeat 'time
1676 "Non-nil means, record moving through the DONE state when triggering repeat.
1677 An auto-repeating tasks is immediately switched back to TODO when marked
1678 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1679 the TODO keyword definition, or recording a closing note by setting
1680 `org-log-done', there will be no record of the task moving through DONE.
1681 This variable forces taking a note anyway. Possible values are:
1682
1683 nil Don't force a record
1684 time Record a time stamp
1685 note Record a note
1686
1687 This option can also be set with on a per-file-basis with
1688
1689 #+STARTUP: logrepeat
1690 #+STARTUP: lognoterepeat
1691 #+STARTUP: nologrepeat
1692
1693 You can have local logging settings for a subtree by setting the LOGGING
1694 property to one or more of these keywords."
1695 :group 'org-todo
1696 :group 'org-progress
1697 :type '(choice
1698 (const :tag "Don't force a record" nil)
1699 (const :tag "Force recording the DONE state" time)
1700 (const :tag "Force recording a note with the DONE state" note)))
1701
1702
1703 (defgroup org-priorities nil
1704 "Priorities in Org-mode."
1705 :tag "Org Priorities"
1706 :group 'org-todo)
1707
1708 (defcustom org-highest-priority ?A
1709 "The highest priority of TODO items. A character like ?A, ?B etc.
1710 Must have a smaller ASCII number than `org-lowest-priority'."
1711 :group 'org-priorities
1712 :type 'character)
1713
1714 (defcustom org-lowest-priority ?C
1715 "The lowest priority of TODO items. A character like ?A, ?B etc.
1716 Must have a larger ASCII number than `org-highest-priority'."
1717 :group 'org-priorities
1718 :type 'character)
1719
1720 (defcustom org-default-priority ?B
1721 "The default priority of TODO items.
1722 This is the priority an item get if no explicit priority is given."
1723 :group 'org-priorities
1724 :type 'character)
1725
1726 (defcustom org-priority-start-cycle-with-default t
1727 "Non-nil means, start with default priority when starting to cycle.
1728 When this is nil, the first step in the cycle will be (depending on the
1729 command used) one higher or lower that the default priority."
1730 :group 'org-priorities
1731 :type 'boolean)
1732
1733 (defgroup org-time nil
1734 "Options concerning time stamps and deadlines in Org-mode."
1735 :tag "Org Time"
1736 :group 'org)
1737
1738 (defcustom org-insert-labeled-timestamps-at-point nil
1739 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1740 When nil, these labeled time stamps are forces into the second line of an
1741 entry, just after the headline. When scheduling from the global TODO list,
1742 the time stamp will always be forced into the second line."
1743 :group 'org-time
1744 :type 'boolean)
1745
1746 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1747 "Formats for `format-time-string' which are used for time stamps.
1748 It is not recommended to change this constant.")
1749
1750 (defcustom org-time-stamp-rounding-minutes '(0 5)
1751 "Number of minutes to round time stamps to.
1752 These are two values, the first applies when first creating a time stamp.
1753 The second applies when changing it with the commands `S-up' and `S-down'.
1754 When changing the time stamp, this means that it will change in steps
1755 of N minutes, as given by the second value.
1756
1757 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1758 numbers should be factors of 60, so for example 5, 10, 15.
1759
1760 When this is larger than 1, you can still force an exact time-stamp by using
1761 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1762 and by using a prefix arg to `S-up/down' to specify the exact number
1763 of minutes to shift."
1764 :group 'org-time
1765 :get '(lambda (var) ; Make sure all entries have 5 elements
1766 (if (integerp (default-value var))
1767 (list (default-value var) 5)
1768 (default-value var)))
1769 :type '(list
1770 (integer :tag "when inserting times")
1771 (integer :tag "when modifying times")))
1772
1773 ;; Normalize old customizations of this variable.
1774 (when (integerp org-time-stamp-rounding-minutes)
1775 (setq org-time-stamp-rounding-minutes
1776 (list org-time-stamp-rounding-minutes
1777 org-time-stamp-rounding-minutes)))
1778
1779 (defcustom org-display-custom-times nil
1780 "Non-nil means, overlay custom formats over all time stamps.
1781 The formats are defined through the variable `org-time-stamp-custom-formats'.
1782 To turn this on on a per-file basis, insert anywhere in the file:
1783 #+STARTUP: customtime"
1784 :group 'org-time
1785 :set 'set-default
1786 :type 'sexp)
1787 (make-variable-buffer-local 'org-display-custom-times)
1788
1789 (defcustom org-time-stamp-custom-formats
1790 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1791 "Custom formats for time stamps. See `format-time-string' for the syntax.
1792 These are overlayed over the default ISO format if the variable
1793 `org-display-custom-times' is set. Time like %H:%M should be at the
1794 end of the second format."
1795 :group 'org-time
1796 :type 'sexp)
1797
1798 (defun org-time-stamp-format (&optional long inactive)
1799 "Get the right format for a time string."
1800 (let ((f (if long (cdr org-time-stamp-formats)
1801 (car org-time-stamp-formats))))
1802 (if inactive
1803 (concat "[" (substring f 1 -1) "]")
1804 f)))
1805
1806 (defcustom org-time-clocksum-format "%d:%02d"
1807 "The format string used when creating CLOCKSUM lines, or when
1808 org-mode generates a time duration."
1809 :group 'org-time
1810 :type 'string)
1811
1812 (defcustom org-deadline-warning-days 14
1813 "No. of days before expiration during which a deadline becomes active.
1814 This variable governs the display in sparse trees and in the agenda.
1815 When 0 or negative, it means use this number (the absolute value of it)
1816 even if a deadline has a different individual lead time specified."
1817 :group 'org-time
1818 :group 'org-agenda-daily/weekly
1819 :type 'number)
1820
1821 (defcustom org-read-date-prefer-future t
1822 "Non-nil means, assume future for incomplete date input from user.
1823 This affects the following situations:
1824 1. The user gives a day, but no month.
1825 For example, if today is the 15th, and you enter \"3\", Org-mode will
1826 read this as the third of *next* month. However, if you enter \"17\",
1827 it will be considered as *this* month.
1828 2. The user gives a month but not a year.
1829 For example, if it is april and you enter \"feb 2\", this will be read
1830 as feb 2, *next* year. \"May 5\", however, will be this year.
1831
1832 Currently this does not work for ISO week specifications.
1833
1834 When this option is nil, the current month and year will always be used
1835 as defaults."
1836 :group 'org-time
1837 :type 'boolean)
1838
1839 (defcustom org-read-date-display-live t
1840 "Non-nil means, display current interpretation of date prompt live.
1841 This display will be in an overlay, in the minibuffer."
1842 :group 'org-time
1843 :type 'boolean)
1844
1845 (defcustom org-read-date-popup-calendar t
1846 "Non-nil means, pop up a calendar when prompting for a date.
1847 In the calendar, the date can be selected with mouse-1. However, the
1848 minibuffer will also be active, and you can simply enter the date as well.
1849 When nil, only the minibuffer will be available."
1850 :group 'org-time
1851 :type 'boolean)
1852 (if (fboundp 'defvaralias)
1853 (defvaralias 'org-popup-calendar-for-date-prompt
1854 'org-read-date-popup-calendar))
1855
1856 (defcustom org-extend-today-until 0
1857 "The hour when your day really ends. Must be an integer.
1858 This has influence for the following applications:
1859 - When switching the agenda to \"today\". It it is still earlier than
1860 the time given here, the day recognized as TODAY is actually yesterday.
1861 - When a date is read from the user and it is still before the time given
1862 here, the current date and time will be assumed to be yesterday, 23:59.
1863 Also, timestamps inserted in remember templates follow this rule.
1864
1865 IMPORTANT: This is a feature whose implementation is and likely will
1866 remain incomplete. Really, it is only here because past midnight seems to
1867 be the favorite working time of John Wiegley :-)"
1868 :group 'org-time
1869 :type 'number)
1870
1871 (defcustom org-edit-timestamp-down-means-later nil
1872 "Non-nil means, S-down will increase the time in a time stamp.
1873 When nil, S-up will increase."
1874 :group 'org-time
1875 :type 'boolean)
1876
1877 (defcustom org-calendar-follow-timestamp-change t
1878 "Non-nil means, make the calendar window follow timestamp changes.
1879 When a timestamp is modified and the calendar window is visible, it will be
1880 moved to the new date."
1881 :group 'org-time
1882 :type 'boolean)
1883
1884 (defgroup org-tags nil
1885 "Options concerning tags in Org-mode."
1886 :tag "Org Tags"
1887 :group 'org)
1888
1889 (defcustom org-tag-alist nil
1890 "List of tags allowed in Org-mode files.
1891 When this list is nil, Org-mode will base TAG input on what is already in the
1892 buffer.
1893 The value of this variable is an alist, the car of each entry must be a
1894 keyword as a string, the cdr may be a character that is used to select
1895 that tag through the fast-tag-selection interface.
1896 See the manual for details."
1897 :group 'org-tags
1898 :type '(repeat
1899 (choice
1900 (cons (string :tag "Tag name")
1901 (character :tag "Access char"))
1902 (const :tag "Start radio group" (:startgroup))
1903 (const :tag "End radio group" (:endgroup)))))
1904
1905 (defvar org-file-tags nil
1906 "List of tags that can be inherited by all entries in the file.
1907 The tags will be inherited if the variable `org-use-tag-inheritance'
1908 says they should be.
1909 This variable is populated from #+TAG lines.")
1910
1911 (defcustom org-use-fast-tag-selection 'auto
1912 "Non-nil means, use fast tag selection scheme.
1913 This is a special interface to select and deselect tags with single keys.
1914 When nil, fast selection is never used.
1915 When the symbol `auto', fast selection is used if and only if selection
1916 characters for tags have been configured, either through the variable
1917 `org-tag-alist' or through a #+TAGS line in the buffer.
1918 When t, fast selection is always used and selection keys are assigned
1919 automatically if necessary."
1920 :group 'org-tags
1921 :type '(choice
1922 (const :tag "Always" t)
1923 (const :tag "Never" nil)
1924 (const :tag "When selection characters are configured" 'auto)))
1925
1926 (defcustom org-fast-tag-selection-single-key nil
1927 "Non-nil means, fast tag selection exits after first change.
1928 When nil, you have to press RET to exit it.
1929 During fast tag selection, you can toggle this flag with `C-c'.
1930 This variable can also have the value `expert'. In this case, the window
1931 displaying the tags menu is not even shown, until you press C-c again."
1932 :group 'org-tags
1933 :type '(choice
1934 (const :tag "No" nil)
1935 (const :tag "Yes" t)
1936 (const :tag "Expert" expert)))
1937
1938 (defvar org-fast-tag-selection-include-todo nil
1939 "Non-nil means, fast tags selection interface will also offer TODO states.
1940 This is an undocumented feature, you should not rely on it.")
1941
1942 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1943 "The column to which tags should be indented in a headline.
1944 If this number is positive, it specifies the column. If it is negative,
1945 it means that the tags should be flushright to that column. For example,
1946 -80 works well for a normal 80 character screen."
1947 :group 'org-tags
1948 :type 'integer)
1949
1950 (defcustom org-auto-align-tags t
1951 "Non-nil means, realign tags after pro/demotion of TODO state change.
1952 These operations change the length of a headline and therefore shift
1953 the tags around. With this options turned on, after each such operation
1954 the tags are again aligned to `org-tags-column'."
1955 :group 'org-tags
1956 :type 'boolean)
1957
1958 (defcustom org-use-tag-inheritance t
1959 "Non-nil means, tags in levels apply also for sublevels.
1960 When nil, only the tags directly given in a specific line apply there.
1961 This may also be a list of tags that should be inherited, or a regexp that
1962 matches tags that should be inherited. Additional control is possible
1963 with the variable `org-tags-exclude-from-inheritance' which gives an
1964 explicit list of tags to be excluded from inheritance., even if the value of
1965 `org-use-tag-inheritance' would select it for inheritance.
1966
1967 If this option is t, a match early-on in a tree can lead to a large
1968 number of matches in the subtree when constructing the agenda or creating
1969 a sparse tree. If you only want to see the first match in a tree during
1970 a search, check out the variable `org-tags-match-list-sublevels'."
1971 :group 'org-tags
1972 :type '(choice
1973 (const :tag "Not" nil)
1974 (const :tag "Always" t)
1975 (repeat :tag "Specific tags" (string :tag "Tag"))
1976 (regexp :tag "Tags matched by regexp")))
1977
1978 (defcustom org-tags-exclude-from-inheritance nil
1979 "List of tags that should never be inherited.
1980 This is a way to exclude a few tags from inheritance. For way to do
1981 the opposite, to actively allow inheritance for selected tags,
1982 see the variable `org-use-tag-inheritance'."
1983 :group 'org-tags
1984 :type '(repeat (string :tag "Tag")))
1985
1986 (defun org-tag-inherit-p (tag)
1987 "Check if TAG is one that should be inherited."
1988 (cond
1989 ((member tag org-tags-exclude-from-inheritance) nil)
1990 ((eq org-use-tag-inheritance t) t)
1991 ((not org-use-tag-inheritance) nil)
1992 ((stringp org-use-tag-inheritance)
1993 (string-match org-use-tag-inheritance tag))
1994 ((listp org-use-tag-inheritance)
1995 (member tag org-use-tag-inheritance))
1996 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1997
1998 (defcustom org-tags-match-list-sublevels t
1999 "Non-nil means list also sublevels of headlines matching tag search.
2000 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2001 the sublevels of a headline matching a tag search often also match
2002 the same search. Listing all of them can create very long lists.
2003 Setting this variable to nil causes subtrees of a match to be skipped.
2004 This option is off by default, because inheritance in on. If you turn
2005 inheritance off, you very likely want to turn this option on.
2006
2007 As a special case, if the tag search is restricted to TODO items, the
2008 value of this variable is ignored and sublevels are always checked, to
2009 make sure all corresponding TODO items find their way into the list.
2010
2011 This variable is semi-obsolete and probably should always be true. It
2012 is better to limit inheritance to certain tags using the variables
2013 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2014 :group 'org-tags
2015 :type 'boolean)
2016
2017 (defvar org-tags-history nil
2018 "History of minibuffer reads for tags.")
2019 (defvar org-last-tags-completion-table nil
2020 "The last used completion table for tags.")
2021 (defvar org-after-tags-change-hook nil
2022 "Hook that is run after the tags in a line have changed.")
2023
2024 (defgroup org-properties nil
2025 "Options concerning properties in Org-mode."
2026 :tag "Org Properties"
2027 :group 'org)
2028
2029 (defcustom org-property-format "%-10s %s"
2030 "How property key/value pairs should be formatted by `indent-line'.
2031 When `indent-line' hits a property definition, it will format the line
2032 according to this format, mainly to make sure that the values are
2033 lined-up with respect to each other."
2034 :group 'org-properties
2035 :type 'string)
2036
2037 (defcustom org-use-property-inheritance nil
2038 "Non-nil means, properties apply also for sublevels.
2039
2040 This setting is chiefly used during property searches. Turning it on can
2041 cause significant overhead when doing a search, which is why it is not
2042 on by default.
2043
2044 When nil, only the properties directly given in the current entry count.
2045 When t, every property is inherited. The value may also be a list of
2046 properties that should have inheritance, or a regular expression matching
2047 properties that should be inherited.
2048
2049 However, note that some special properties use inheritance under special
2050 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2051 and the properties ending in \"_ALL\" when they are used as descriptor
2052 for valid values of a property.
2053
2054 Note for programmers:
2055 When querying an entry with `org-entry-get', you can control if inheritance
2056 should be used. By default, `org-entry-get' looks only at the local
2057 properties. You can request inheritance by setting the inherit argument
2058 to t (to force inheritance) or to `selective' (to respect the setting
2059 in this variable)."
2060 :group 'org-properties
2061 :type '(choice
2062 (const :tag "Not" nil)
2063 (const :tag "Always" t)
2064 (repeat :tag "Specific properties" (string :tag "Property"))
2065 (regexp :tag "Properties matched by regexp")))
2066
2067 (defun org-property-inherit-p (property)
2068 "Check if PROPERTY is one that should be inherited."
2069 (cond
2070 ((eq org-use-property-inheritance t) t)
2071 ((not org-use-property-inheritance) nil)
2072 ((stringp org-use-property-inheritance)
2073 (string-match org-use-property-inheritance property))
2074 ((listp org-use-property-inheritance)
2075 (member property org-use-property-inheritance))
2076 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2077
2078 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2079 "The default column format, if no other format has been defined.
2080 This variable can be set on the per-file basis by inserting a line
2081
2082 #+COLUMNS: %25ITEM ....."
2083 :group 'org-properties
2084 :type 'string)
2085
2086 (defcustom org-columns-ellipses ".."
2087 "The ellipses to be used when a field in column view is truncated.
2088 When this is the empty string, as many characters as possible are shown,
2089 but then there will be no visual indication that the field has been truncated.
2090 When this is a string of length N, the last N characters of a truncated
2091 field are replaced by this string. If the column is narrower than the
2092 ellipses string, only part of the ellipses string will be shown."
2093 :group 'org-properties
2094 :type 'string)
2095
2096 (defcustom org-columns-modify-value-for-display-function nil
2097 "Function that modifies values for display in column view.
2098 For example, it can be used to cut out a certain part from a time stamp.
2099 The function must take 2 arguments:
2100
2101 column-title The title of the column (*not* the property name)
2102 value The value that should be modified.
2103
2104 The function should return the value that should be displayed,
2105 or nil if the normal value should be used."
2106 :group 'org-properties
2107 :type 'function)
2108
2109 (defcustom org-effort-property "Effort"
2110 "The property that is being used to keep track of effort estimates.
2111 Effort estimates given in this property need to have the format H:MM."
2112 :group 'org-properties
2113 :group 'org-progress
2114 :type '(string :tag "Property"))
2115
2116 (defconst org-global-properties-fixed
2117 '(("VISIBILITY_ALL" . "folded children content all"))
2118 "List of property/value pairs that can be inherited by any entry.
2119 These are fixed values, for the preset properties.")
2120
2121
2122 (defcustom org-global-properties nil
2123 "List of property/value pairs that can be inherited by any entry.
2124 You can set buffer-local values for the same purpose in the variable
2125 `org-file-properties' this by adding lines like
2126
2127 #+PROPERTY: NAME VALUE"
2128 :group 'org-properties
2129 :type '(repeat
2130 (cons (string :tag "Property")
2131 (string :tag "Value"))))
2132
2133 (defvar org-file-properties nil
2134 "List of property/value pairs that can be inherited by any entry.
2135 Valid for the current buffer.
2136 This variable is populated from #+PROPERTY lines.")
2137 (make-variable-buffer-local 'org-file-properties)
2138
2139 (defgroup org-agenda nil
2140 "Options concerning agenda views in Org-mode."
2141 :tag "Org Agenda"
2142 :group 'org)
2143
2144 (defvar org-category nil
2145 "Variable used by org files to set a category for agenda display.
2146 Such files should use a file variable to set it, for example
2147
2148 # -*- mode: org; org-category: \"ELisp\"
2149
2150 or contain a special line
2151
2152 #+CATEGORY: ELisp
2153
2154 If the file does not specify a category, then file's base name
2155 is used instead.")
2156 (make-variable-buffer-local 'org-category)
2157 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2158
2159 (defcustom org-agenda-files nil
2160 "The files to be used for agenda display.
2161 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2162 \\[org-remove-file]. You can also use customize to edit the list.
2163
2164 If an entry is a directory, all files in that directory that are matched by
2165 `org-agenda-file-regexp' will be part of the file list.
2166
2167 If the value of the variable is not a list but a single file name, then
2168 the list of agenda files is actually stored and maintained in that file, one
2169 agenda file per line."
2170 :group 'org-agenda
2171 :type '(choice
2172 (repeat :tag "List of files and directories" file)
2173 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2174
2175 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2176 "Regular expression to match files for `org-agenda-files'.
2177 If any element in the list in that variable contains a directory instead
2178 of a normal file, all files in that directory that are matched by this
2179 regular expression will be included."
2180 :group 'org-agenda
2181 :type 'regexp)
2182
2183 (defcustom org-agenda-text-search-extra-files nil
2184 "List of extra files to be searched by text search commands.
2185 These files will be search in addition to the agenda files by the
2186 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2187 Note that these files will only be searched for text search commands,
2188 not for the other agenda views like todo lists, tag searches or the weekly
2189 agenda. This variable is intended to list notes and possibly archive files
2190 that should also be searched by these two commands.
2191 In fact, if the first element in the list is the symbol `agenda-archives',
2192 than all archive files of all agenda files will be added to the search
2193 scope."
2194 :group 'org-agenda
2195 :type '(set :greedy t
2196 (const :tag "Agenda Archives" agenda-archives)
2197 (repeat :inline t (file))))
2198
2199 (if (fboundp 'defvaralias)
2200 (defvaralias 'org-agenda-multi-occur-extra-files
2201 'org-agenda-text-search-extra-files))
2202
2203 (defcustom org-agenda-skip-unavailable-files nil
2204 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2205 A nil value means to remove them, after a query, from the list."
2206 :group 'org-agenda
2207 :type 'boolean)
2208
2209 (defcustom org-calendar-to-agenda-key [?c]
2210 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2211 The command `org-calendar-goto-agenda' will be bound to this key. The
2212 default is the character `c' because then `c' can be used to switch back and
2213 forth between agenda and calendar."
2214 :group 'org-agenda
2215 :type 'sexp)
2216
2217 (defcustom org-calendar-agenda-action-key [?k]
2218 "The key to be installed in `calendar-mode-map' for agenda-action.
2219 The command `org-agenda-action' will be bound to this key. The
2220 default is the character `k' because we use the same key in the agenda."
2221 :group 'org-agenda
2222 :type 'sexp)
2223
2224 (eval-after-load "calendar"
2225 '(progn
2226 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2227 'org-calendar-goto-agenda)
2228 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2229 'org-agenda-action)))
2230
2231 (defgroup org-latex nil
2232 "Options for embedding LaTeX code into Org-mode."
2233 :tag "Org LaTeX"
2234 :group 'org)
2235
2236 (defcustom org-format-latex-options
2237 '(:foreground default :background default :scale 1.0
2238 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2239 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2240 "Options for creating images from LaTeX fragments.
2241 This is a property list with the following properties:
2242 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2243 `default' means use the foreground of the default face.
2244 :background the background color, or \"Transparent\".
2245 `default' means use the background of the default face.
2246 :scale a scaling factor for the size of the images.
2247 :html-foreground, :html-background, :html-scale
2248 the same numbers for HTML export.
2249 :matchers a list indicating which matchers should be used to
2250 find LaTeX fragments. Valid members of this list are:
2251 \"begin\" find environments
2252 \"$1\" find single characters surrounded by $.$
2253 \"$\" find math expressions surrounded by $...$
2254 \"$$\" find math expressions surrounded by $$....$$
2255 \"\\(\" find math expressions surrounded by \\(...\\)
2256 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2257 :group 'org-latex
2258 :type 'plist)
2259
2260 (defcustom org-format-latex-header "\\documentclass{article}
2261 \\usepackage{fullpage} % do not remove
2262 \\usepackage{amssymb}
2263 \\usepackage[usenames]{color}
2264 \\usepackage{amsmath}
2265 \\usepackage{latexsym}
2266 \\usepackage[mathscr]{eucal}
2267 \\pagestyle{empty} % do not remove"
2268 "The document header used for processing LaTeX fragments."
2269 :group 'org-latex
2270 :type 'string)
2271
2272
2273 (defgroup org-font-lock nil
2274 "Font-lock settings for highlighting in Org-mode."
2275 :tag "Org Font Lock"
2276 :group 'org)
2277
2278 (defcustom org-level-color-stars-only nil
2279 "Non-nil means fontify only the stars in each headline.
2280 When nil, the entire headline is fontified.
2281 Changing it requires restart of `font-lock-mode' to become effective
2282 also in regions already fontified."
2283 :group 'org-font-lock
2284 :type 'boolean)
2285
2286 (defcustom org-hide-leading-stars nil
2287 "Non-nil means, hide the first N-1 stars in a headline.
2288 This works by using the face `org-hide' for these stars. This
2289 face is white for a light background, and black for a dark
2290 background. You may have to customize the face `org-hide' to
2291 make this work.
2292 Changing it requires restart of `font-lock-mode' to become effective
2293 also in regions already fontified.
2294 You may also set this on a per-file basis by adding one of the following
2295 lines to the buffer:
2296
2297 #+STARTUP: hidestars
2298 #+STARTUP: showstars"
2299 :group 'org-font-lock
2300 :type 'boolean)
2301
2302 (defcustom org-fontify-done-headline nil
2303 "Non-nil means, change the face of a headline if it is marked DONE.
2304 Normally, only the TODO/DONE keyword indicates the state of a headline.
2305 When this is non-nil, the headline after the keyword is set to the
2306 `org-headline-done' as an additional indication."
2307 :group 'org-font-lock
2308 :type 'boolean)
2309
2310 (defcustom org-fontify-emphasized-text t
2311 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2312 Changing this variable requires a restart of Emacs to take effect."
2313 :group 'org-font-lock
2314 :type 'boolean)
2315
2316 (defcustom org-highlight-latex-fragments-and-specials nil
2317 "Non-nil means, fontify what is treated specially by the exporters."
2318 :group 'org-font-lock
2319 :type 'boolean)
2320
2321 (defcustom org-hide-emphasis-markers nil
2322 "Non-nil mean font-lock should hide the emphasis marker characters."
2323 :group 'org-font-lock
2324 :type 'boolean)
2325
2326 (defvar org-emph-re nil
2327 "Regular expression for matching emphasis.")
2328 (defvar org-verbatim-re nil
2329 "Regular expression for matching verbatim text.")
2330 (defvar org-emphasis-regexp-components) ; defined just below
2331 (defvar org-emphasis-alist) ; defined just below
2332 (defun org-set-emph-re (var val)
2333 "Set variable and compute the emphasis regular expression."
2334 (set var val)
2335 (when (and (boundp 'org-emphasis-alist)
2336 (boundp 'org-emphasis-regexp-components)
2337 org-emphasis-alist org-emphasis-regexp-components)
2338 (let* ((e org-emphasis-regexp-components)
2339 (pre (car e))
2340 (post (nth 1 e))
2341 (border (nth 2 e))
2342 (body (nth 3 e))
2343 (nl (nth 4 e))
2344 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2345 (body1 (concat body "*?"))
2346 (markers (mapconcat 'car org-emphasis-alist ""))
2347 (vmarkers (mapconcat
2348 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2349 org-emphasis-alist "")))
2350 ;; make sure special characters appear at the right position in the class
2351 (if (string-match "\\^" markers)
2352 (setq markers (concat (replace-match "" t t markers) "^")))
2353 (if (string-match "-" markers)
2354 (setq markers (concat (replace-match "" t t markers) "-")))
2355 (if (string-match "\\^" vmarkers)
2356 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2357 (if (string-match "-" vmarkers)
2358 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2359 (if (> nl 0)
2360 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2361 (int-to-string nl) "\\}")))
2362 ;; Make the regexp
2363 (setq org-emph-re
2364 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2365 "\\("
2366 "\\([" markers "]\\)"
2367 "\\("
2368 "[^" border "]\\|"
2369 "[^" border (if (and nil stacked) markers) "]"
2370 body1
2371 "[^" border (if (and nil stacked) markers) "]"
2372 "\\)"
2373 "\\3\\)"
2374 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2375 (setq org-verbatim-re
2376 (concat "\\([" pre "]\\|^\\)"
2377 "\\("
2378 "\\([" vmarkers "]\\)"
2379 "\\("
2380 "[^" border "]\\|"
2381 "[^" border "]"
2382 body1
2383 "[^" border "]"
2384 "\\)"
2385 "\\3\\)"
2386 "\\([" post "]\\|$\\)")))))
2387
2388 (defcustom org-emphasis-regexp-components
2389 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2390 "Components used to build the regular expression for emphasis.
2391 This is a list with 6 entries. Terminology: In an emphasis string
2392 like \" *strong word* \", we call the initial space PREMATCH, the final
2393 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2394 and \"trong wor\" is the body. The different components in this variable
2395 specify what is allowed/forbidden in each part:
2396
2397 pre Chars allowed as prematch. Beginning of line will be allowed too.
2398 post Chars allowed as postmatch. End of line will be allowed too.
2399 border The chars *forbidden* as border characters.
2400 body-regexp A regexp like \".\" to match a body character. Don't use
2401 non-shy groups here, and don't allow newline here.
2402 newline The maximum number of newlines allowed in an emphasis exp.
2403
2404 Use customize to modify this, or restart Emacs after changing it."
2405 :group 'org-font-lock
2406 :set 'org-set-emph-re
2407 :type '(list
2408 (sexp :tag "Allowed chars in pre ")
2409 (sexp :tag "Allowed chars in post ")
2410 (sexp :tag "Forbidden chars in border ")
2411 (sexp :tag "Regexp for body ")
2412 (integer :tag "number of newlines allowed")
2413 (option (boolean :tag "Please ignore this button"))))
2414
2415 (defcustom org-emphasis-alist
2416 `(("*" bold "<b>" "</b>")
2417 ("/" italic "<i>" "</i>")
2418 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2419 ("=" org-code "<code>" "</code>" verbatim)
2420 ("~" org-verbatim "<code>" "</code>" verbatim)
2421 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2422 "<del>" "</del>")
2423 )
2424 "Special syntax for emphasized text.
2425 Text starting and ending with a special character will be emphasized, for
2426 example *bold*, _underlined_ and /italic/. This variable sets the marker
2427 characters, the face to be used by font-lock for highlighting in Org-mode
2428 Emacs buffers, and the HTML tags to be used for this.
2429 Use customize to modify this, or restart Emacs after changing it."
2430 :group 'org-font-lock
2431 :set 'org-set-emph-re
2432 :type '(repeat
2433 (list
2434 (string :tag "Marker character")
2435 (choice
2436 (face :tag "Font-lock-face")
2437 (plist :tag "Face property list"))
2438 (string :tag "HTML start tag")
2439 (string :tag "HTML end tag")
2440 (option (const verbatim)))))
2441
2442 ;;; Miscellaneous options
2443
2444 (defgroup org-completion nil
2445 "Completion in Org-mode."
2446 :tag "Org Completion"
2447 :group 'org)
2448
2449 (defcustom org-completion-use-ido nil
2450 "Non-nil means, use ido completion wherever possible.
2451 Note that `ido-mode' must be active for this variable to be relevant.
2452 If you decide to turn this variable on, you might well want to turn off
2453 `org-outline-path-complete-in-steps'."
2454 :group 'org-completion
2455 :type 'boolean)
2456
2457 (defcustom org-completion-fallback-command 'hippie-expand
2458 "The expansion command called by \\[org-complete] in normal context.
2459 Normal means, no org-mode-specific context."
2460 :group 'org-completion
2461 :type 'function)
2462
2463 ;;; Functions and variables from ther packages
2464 ;; Declared here to avoid compiler warnings
2465
2466 ;; XEmacs only
2467 (defvar outline-mode-menu-heading)
2468 (defvar outline-mode-menu-show)
2469 (defvar outline-mode-menu-hide)
2470 (defvar zmacs-regions) ; XEmacs regions
2471
2472 ;; Emacs only
2473 (defvar mark-active)
2474
2475 ;; Various packages
2476 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2477 (declare-function calendar-forward-day "cal-move" (arg))
2478 (declare-function calendar-goto-date "cal-move" (date))
2479 (declare-function calendar-goto-today "cal-move" ())
2480 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2481 (defvar calc-embedded-close-formula)
2482 (defvar calc-embedded-open-formula)
2483 (declare-function cdlatex-tab "ext:cdlatex" ())
2484 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2485 (defvar font-lock-unfontify-region-function)
2486 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2487 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2488 (defvar iswitchb-temp-buflist)
2489 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2490 (defvar org-agenda-tags-todo-honor-ignore-options)
2491 (declare-function org-agenda-skip "org-agenda" ())
2492 (declare-function org-format-agenda-item "org-agenda"
2493 (extra txt &optional category tags dotime noprefix remove-re))
2494 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2495 (declare-function org-agenda-change-all-lines "org-agenda"
2496 (newhead hdmarker &optional fixface just-this))
2497 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2498 (declare-function org-agenda-maybe-redo "org-agenda" ())
2499 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2500 (beg end))
2501 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2502 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2503 "org-agenda" (&optional end))
2504
2505 (declare-function parse-time-string "parse-time" (string))
2506 (declare-function remember "remember" (&optional initial))
2507 (declare-function remember-buffer-desc "remember" ())
2508 (declare-function remember-finalize "remember" ())
2509 (defvar remember-save-after-remembering)
2510 (defvar remember-data-file)
2511 (defvar remember-register)
2512 (defvar remember-buffer)
2513 (defvar remember-handler-functions)
2514 (defvar remember-annotation-functions)
2515 (defvar texmathp-why)
2516 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2517 (declare-function table--at-cell-p "table" (position &optional object at-column))
2518
2519 (defvar w3m-current-url)
2520 (defvar w3m-current-title)
2521
2522 (defvar org-latex-regexps)
2523
2524 ;;; Autoload and prepare some org modules
2525
2526 ;; Some table stuff that needs to be defined here, because it is used
2527 ;; by the functions setting up org-mode or checking for table context.
2528
2529 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2530 "Detects an org-type or table-type table.")
2531 (defconst org-table-line-regexp "^[ \t]*|"
2532 "Detects an org-type table line.")
2533 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2534 "Detects an org-type table line.")
2535 (defconst org-table-hline-regexp "^[ \t]*|-"
2536 "Detects an org-type table hline.")
2537 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2538 "Detects a table-type table hline.")
2539 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2540 "Searching from within a table (any type) this finds the first line
2541 outside the table.")
2542
2543 ;; Autoload the functions in org-table.el that are needed by functions here.
2544
2545 (eval-and-compile
2546 (org-autoload "org-table"
2547 '(org-table-align org-table-begin org-table-blank-field
2548 org-table-convert org-table-convert-region org-table-copy-down
2549 org-table-copy-region org-table-create
2550 org-table-create-or-convert-from-region
2551 org-table-create-with-table.el org-table-current-dline
2552 org-table-cut-region org-table-delete-column org-table-edit-field
2553 org-table-edit-formulas org-table-end org-table-eval-formula
2554 org-table-export org-table-field-info
2555 org-table-get-stored-formulas org-table-goto-column
2556 org-table-hline-and-move org-table-import org-table-insert-column
2557 org-table-insert-hline org-table-insert-row org-table-iterate
2558 org-table-justify-field-maybe org-table-kill-row
2559 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2560 org-table-move-column org-table-move-column-left
2561 org-table-move-column-right org-table-move-row
2562 org-table-move-row-down org-table-move-row-up
2563 org-table-next-field org-table-next-row org-table-paste-rectangle
2564 org-table-previous-field org-table-recalculate
2565 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2566 org-table-toggle-coordinate-overlays
2567 org-table-toggle-formula-debugger org-table-wrap-region
2568 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2569
2570 (defun org-at-table-p (&optional table-type)
2571 "Return t if the cursor is inside an org-type table.
2572 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2573 (if org-enable-table-editor
2574 (save-excursion
2575 (beginning-of-line 1)
2576 (looking-at (if table-type org-table-any-line-regexp
2577 org-table-line-regexp)))
2578 nil))
2579 (defsubst org-table-p () (org-at-table-p))
2580
2581 (defun org-at-table.el-p ()
2582 "Return t if and only if we are at a table.el table."
2583 (and (org-at-table-p 'any)
2584 (save-excursion
2585 (goto-char (org-table-begin 'any))
2586 (looking-at org-table1-hline-regexp))))
2587 (defun org-table-recognize-table.el ()
2588 "If there is a table.el table nearby, recognize it and move into it."
2589 (if org-table-tab-recognizes-table.el
2590 (if (org-at-table.el-p)
2591 (progn
2592 (beginning-of-line 1)
2593 (if (looking-at org-table-dataline-regexp)
2594 nil
2595 (if (looking-at org-table1-hline-regexp)
2596 (progn
2597 (beginning-of-line 2)
2598 (if (looking-at org-table-any-border-regexp)
2599 (beginning-of-line -1)))))
2600 (if (re-search-forward "|" (org-table-end t) t)
2601 (progn
2602 (require 'table)
2603 (if (table--at-cell-p (point))
2604 t
2605 (message "recognizing table.el table...")
2606 (table-recognize-table)
2607 (message "recognizing table.el table...done")))
2608 (error "This should not happen..."))
2609 t)
2610 nil)
2611 nil))
2612
2613 (defun org-at-table-hline-p ()
2614 "Return t if the cursor is inside a hline in a table."
2615 (if org-enable-table-editor
2616 (save-excursion
2617 (beginning-of-line 1)
2618 (looking-at org-table-hline-regexp))
2619 nil))
2620
2621 (defvar org-table-clean-did-remove-column nil)
2622
2623 (defun org-table-map-tables (function)
2624 "Apply FUNCTION to the start of all tables in the buffer."
2625 (save-excursion
2626 (save-restriction
2627 (widen)
2628 (goto-char (point-min))
2629 (while (re-search-forward org-table-any-line-regexp nil t)
2630 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2631 (beginning-of-line 1)
2632 (if (looking-at org-table-line-regexp)
2633 (save-excursion (funcall function)))
2634 (re-search-forward org-table-any-border-regexp nil 1))))
2635 (message "Mapping tables: done"))
2636
2637 ;; Declare and autoload functions from org-exp.el
2638
2639 (declare-function org-default-export-plist "org-exp")
2640 (declare-function org-infile-export-plist "org-exp")
2641 (declare-function org-get-current-options "org-exp")
2642 (eval-and-compile
2643 (org-autoload "org-exp"
2644 '(org-export org-export-as-ascii org-export-visible
2645 org-insert-export-options-template org-export-as-html-and-open
2646 org-export-as-html-batch org-export-as-html-to-buffer
2647 org-replace-region-by-html org-export-region-as-html
2648 org-export-as-html org-export-icalendar-this-file
2649 org-export-icalendar-all-agenda-files
2650 org-table-clean-before-export
2651 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2652
2653 ;; Declare and autoload functions from org-agenda.el
2654
2655 (eval-and-compile
2656 (org-autoload "org-agenda"
2657 '(org-agenda org-agenda-list org-search-view
2658 org-todo-list org-tags-view org-agenda-list-stuck-projects
2659 org-diary org-agenda-to-appt
2660 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2661
2662 ;; Autoload org-remember
2663
2664 (eval-and-compile
2665 (org-autoload "org-remember"
2666 '(org-remember-insinuate org-remember-annotation
2667 org-remember-apply-template org-remember org-remember-handler)))
2668
2669 ;; Autoload org-clock.el
2670
2671
2672 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2673 (beg end))
2674 (declare-function org-clock-update-mode-line "org-clock" ())
2675 (defvar org-clock-start-time)
2676 (defvar org-clock-marker (make-marker)
2677 "Marker recording the last clock-in.")
2678
2679 (eval-and-compile
2680 (org-autoload
2681 "org-clock"
2682 '(org-clock-in org-clock-out org-clock-cancel
2683 org-clock-goto org-clock-sum org-clock-display
2684 org-clock-remove-overlays org-clock-report
2685 org-clocktable-shift org-dblock-write:clocktable
2686 org-get-clocktable)))
2687
2688 (defun org-clock-update-time-maybe ()
2689 "If this is a CLOCK line, update it and return t.
2690 Otherwise, return nil."
2691 (interactive)
2692 (save-excursion
2693 (beginning-of-line 1)
2694 (skip-chars-forward " \t")
2695 (when (looking-at org-clock-string)
2696 (let ((re (concat "[ \t]*" org-clock-string
2697 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2698 "\\([ \t]*=>.*\\)?\\)?"))
2699 ts te h m s neg)
2700 (cond
2701 ((not (looking-at re))
2702 nil)
2703 ((not (match-end 2))
2704 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2705 (> org-clock-marker (point))
2706 (<= org-clock-marker (point-at-eol)))
2707 ;; The clock is running here
2708 (setq org-clock-start-time
2709 (apply 'encode-time
2710 (org-parse-time-string (match-string 1))))
2711 (org-clock-update-mode-line)))
2712 (t
2713 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2714 (end-of-line 1)
2715 (setq ts (match-string 1)
2716 te (match-string 3))
2717 (setq s (- (time-to-seconds
2718 (apply 'encode-time (org-parse-time-string te)))
2719 (time-to-seconds
2720 (apply 'encode-time (org-parse-time-string ts))))
2721 neg (< s 0)
2722 s (abs s)
2723 h (floor (/ s 3600))
2724 s (- s (* 3600 h))
2725 m (floor (/ s 60))
2726 s (- s (* 60 s)))
2727 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2728 t))))))
2729
2730 (defun org-check-running-clock ()
2731 "Check if the current buffer contains the running clock.
2732 If yes, offer to stop it and to save the buffer with the changes."
2733 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2734 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2735 (buffer-name))))
2736 (org-clock-out)
2737 (when (y-or-n-p "Save changed buffer?")
2738 (save-buffer))))
2739
2740 (defun org-clocktable-try-shift (dir n)
2741 "Check if this line starts a clock table, if yes, shift the time block."
2742 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2743 (org-clocktable-shift dir n)))
2744
2745 ;; Autoload org-timer.el
2746
2747 ;(declare-function org-timer "org-timer")
2748
2749 (eval-and-compile
2750 (org-autoload
2751 "org-timer"
2752 '(org-timer-start org-timer org-timer-item
2753 org-timer-change-times-in-region)))
2754
2755
2756 ;; Autoload archiving code
2757 ;; The stuff that is needed for cycling and tags has to be defined here.
2758
2759 (defgroup org-archive nil
2760 "Options concerning archiving in Org-mode."
2761 :tag "Org Archive"
2762 :group 'org-structure)
2763
2764 (defcustom org-archive-location "%s_archive::"
2765 "The location where subtrees should be archived.
2766
2767 The value of this variable is a string, consisting of two parts,
2768 separated by a double-colon. The first part is a filename and
2769 the second part is a headline.
2770
2771 When the filename is omitted, archiving happens in the same file.
2772 %s in the filename will be replaced by the current file
2773 name (without the directory part). Archiving to a different file
2774 is useful to keep archived entries from contributing to the
2775 Org-mode Agenda.
2776
2777 The archived entries will be filed as subtrees of the specified
2778 headline. When the headline is omitted, the subtrees are simply
2779 filed away at the end of the file, as top-level entries. Also in
2780 the heading you can use %s to represent the file name, this can be
2781 useful when using the same archive for a number of different files.
2782
2783 Here are a few examples:
2784 \"%s_archive::\"
2785 If the current file is Projects.org, archive in file
2786 Projects.org_archive, as top-level trees. This is the default.
2787
2788 \"::* Archived Tasks\"
2789 Archive in the current file, under the top-level headline
2790 \"* Archived Tasks\".
2791
2792 \"~/org/archive.org::\"
2793 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2794
2795 \"~/org/archive.org::From %s\"
2796 Archive in file ~/org/archive.org (absolute path), und headlines
2797 \"From FILENAME\" where file name is the current file name.
2798
2799 \"basement::** Finished Tasks\"
2800 Archive in file ./basement (relative path), as level 3 trees
2801 below the level 2 heading \"** Finished Tasks\".
2802
2803 You may set this option on a per-file basis by adding to the buffer a
2804 line like
2805
2806 #+ARCHIVE: basement::** Finished Tasks
2807
2808 You may also define it locally for a subtree by setting an ARCHIVE property
2809 in the entry. If such a property is found in an entry, or anywhere up
2810 the hierarchy, it will be used."
2811 :group 'org-archive
2812 :type 'string)
2813
2814 (defcustom org-archive-tag "ARCHIVE"
2815 "The tag that marks a subtree as archived.
2816 An archived subtree does not open during visibility cycling, and does
2817 not contribute to the agenda listings.
2818 After changing this, font-lock must be restarted in the relevant buffers to
2819 get the proper fontification."
2820 :group 'org-archive
2821 :group 'org-keywords
2822 :type 'string)
2823
2824 (defcustom org-agenda-skip-archived-trees t
2825 "Non-nil means, the agenda will skip any items located in archived trees.
2826 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2827 variable is no longer recommended, you should leave it at the value t.
2828 Instead, use the key `v' to cycle the archives-mode in the agenda."
2829 :group 'org-archive
2830 :group 'org-agenda-skip
2831 :type 'boolean)
2832
2833 (defcustom org-cycle-open-archived-trees nil
2834 "Non-nil means, `org-cycle' will open archived trees.
2835 An archived tree is a tree marked with the tag ARCHIVE.
2836 When nil, archived trees will stay folded. You can still open them with
2837 normal outline commands like `show-all', but not with the cycling commands."
2838 :group 'org-archive
2839 :group 'org-cycle
2840 :type 'boolean)
2841
2842 (defcustom org-sparse-tree-open-archived-trees nil
2843 "Non-nil means sparse tree construction shows matches in archived trees.
2844 When nil, matches in these trees are highlighted, but the trees are kept in
2845 collapsed state."
2846 :group 'org-archive
2847 :group 'org-sparse-trees
2848 :type 'boolean)
2849
2850 (defun org-cycle-hide-archived-subtrees (state)
2851 "Re-hide all archived subtrees after a visibility state change."
2852 (when (and (not org-cycle-open-archived-trees)
2853 (not (memq state '(overview folded))))
2854 (save-excursion
2855 (let* ((globalp (memq state '(contents all)))
2856 (beg (if globalp (point-min) (point)))
2857 (end (if globalp (point-max) (org-end-of-subtree t))))
2858 (org-hide-archived-subtrees beg end)
2859 (goto-char beg)
2860 (if (looking-at (concat ".*:" org-archive-tag ":"))
2861 (message "%s" (substitute-command-keys
2862 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2863
2864 (defun org-force-cycle-archived ()
2865 "Cycle subtree even if it is archived."
2866 (interactive)
2867 (setq this-command 'org-cycle)
2868 (let ((org-cycle-open-archived-trees t))
2869 (call-interactively 'org-cycle)))
2870
2871 (defun org-hide-archived-subtrees (beg end)
2872 "Re-hide all archived subtrees after a visibility state change."
2873 (save-excursion
2874 (let* ((re (concat ":" org-archive-tag ":")))
2875 (goto-char beg)
2876 (while (re-search-forward re end t)
2877 (and (org-on-heading-p) (hide-subtree))
2878 (org-end-of-subtree t)))))
2879
2880 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2881
2882 (eval-and-compile
2883 (org-autoload "org-archive"
2884 '(org-add-archive-files org-archive-subtree
2885 org-archive-to-archive-sibling org-toggle-archive-tag)))
2886
2887 ;; Autoload Column View Code
2888
2889 (declare-function org-columns-number-to-string "org-colview")
2890 (declare-function org-columns-get-format-and-top-level "org-colview")
2891 (declare-function org-columns-compute "org-colview")
2892
2893 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2894 '(org-columns-number-to-string org-columns-get-format-and-top-level
2895 org-columns-compute org-agenda-columns org-columns-remove-overlays
2896 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2897
2898 ;; Autoload ID code
2899
2900 (declare-function org-id-store-link "org-id")
2901 (org-autoload "org-id"
2902 '(org-id-get-create org-id-new org-id-copy org-id-get
2903 org-id-get-with-outline-path-completion
2904 org-id-get-with-outline-drilling
2905 org-id-goto org-id-find org-id-store-link))
2906
2907 ;;; Variables for pre-computed regular expressions, all buffer local
2908
2909 (defvar org-drawer-regexp nil
2910 "Matches first line of a hidden block.")
2911 (make-variable-buffer-local 'org-drawer-regexp)
2912 (defvar org-todo-regexp nil
2913 "Matches any of the TODO state keywords.")
2914 (make-variable-buffer-local 'org-todo-regexp)
2915 (defvar org-not-done-regexp nil
2916 "Matches any of the TODO state keywords except the last one.")
2917 (make-variable-buffer-local 'org-not-done-regexp)
2918 (defvar org-todo-line-regexp nil
2919 "Matches a headline and puts TODO state into group 2 if present.")
2920 (make-variable-buffer-local 'org-todo-line-regexp)
2921 (defvar org-complex-heading-regexp nil
2922 "Matches a headline and puts everything into groups:
2923 group 1: the stars
2924 group 2: The todo keyword, maybe
2925 group 3: Priority cookie
2926 group 4: True headline
2927 group 5: Tags")
2928 (make-variable-buffer-local 'org-complex-heading-regexp)
2929 (defvar org-todo-line-tags-regexp nil
2930 "Matches a headline and puts TODO state into group 2 if present.
2931 Also put tags into group 4 if tags are present.")
2932 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2933 (defvar org-nl-done-regexp nil
2934 "Matches newline followed by a headline with the DONE keyword.")
2935 (make-variable-buffer-local 'org-nl-done-regexp)
2936 (defvar org-looking-at-done-regexp nil
2937 "Matches the DONE keyword a point.")
2938 (make-variable-buffer-local 'org-looking-at-done-regexp)
2939 (defvar org-ds-keyword-length 12
2940 "Maximum length of the Deadline and SCHEDULED keywords.")
2941 (make-variable-buffer-local 'org-ds-keyword-length)
2942 (defvar org-deadline-regexp nil
2943 "Matches the DEADLINE keyword.")
2944 (make-variable-buffer-local 'org-deadline-regexp)
2945 (defvar org-deadline-time-regexp nil
2946 "Matches the DEADLINE keyword together with a time stamp.")
2947 (make-variable-buffer-local 'org-deadline-time-regexp)
2948 (defvar org-deadline-line-regexp nil
2949 "Matches the DEADLINE keyword and the rest of the line.")
2950 (make-variable-buffer-local 'org-deadline-line-regexp)
2951 (defvar org-scheduled-regexp nil
2952 "Matches the SCHEDULED keyword.")
2953 (make-variable-buffer-local 'org-scheduled-regexp)
2954 (defvar org-scheduled-time-regexp nil
2955 "Matches the SCHEDULED keyword together with a time stamp.")
2956 (make-variable-buffer-local 'org-scheduled-time-regexp)
2957 (defvar org-closed-time-regexp nil
2958 "Matches the CLOSED keyword together with a time stamp.")
2959 (make-variable-buffer-local 'org-closed-time-regexp)
2960
2961 (defvar org-keyword-time-regexp nil
2962 "Matches any of the 4 keywords, together with the time stamp.")
2963 (make-variable-buffer-local 'org-keyword-time-regexp)
2964 (defvar org-keyword-time-not-clock-regexp nil
2965 "Matches any of the 3 keywords, together with the time stamp.")
2966 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2967 (defvar org-maybe-keyword-time-regexp nil
2968 "Matches a timestamp, possibly preceeded by a keyword.")
2969 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2970 (defvar org-planning-or-clock-line-re nil
2971 "Matches a line with planning or clock info.")
2972 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2973
2974 (defconst org-plain-time-of-day-regexp
2975 (concat
2976 "\\(\\<[012]?[0-9]"
2977 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2978 "\\(--?"
2979 "\\(\\<[012]?[0-9]"
2980 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2981 "\\)?")
2982 "Regular expression to match a plain time or time range.
2983 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2984 groups carry important information:
2985 0 the full match
2986 1 the first time, range or not
2987 8 the second time, if it is a range.")
2988
2989 (defconst org-plain-time-extension-regexp
2990 (concat
2991 "\\(\\<[012]?[0-9]"
2992 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2993 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2994 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2995 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2996 groups carry important information:
2997 0 the full match
2998 7 hours of duration
2999 9 minutes of duration")
3000
3001 (defconst org-stamp-time-of-day-regexp
3002 (concat
3003 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3004 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3005 "\\(--?"
3006 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3007 "Regular expression to match a timestamp time or time range.
3008 After a match, the following groups carry important information:
3009 0 the full match
3010 1 date plus weekday, for backreferencing to make sure both times on same day
3011 2 the first time, range or not
3012 4 the second time, if it is a range.")
3013
3014 (defconst org-startup-options
3015 '(("fold" org-startup-folded t)
3016 ("overview" org-startup-folded t)
3017 ("nofold" org-startup-folded nil)
3018 ("showall" org-startup-folded nil)
3019 ("content" org-startup-folded content)
3020 ("hidestars" org-hide-leading-stars t)
3021 ("showstars" org-hide-leading-stars nil)
3022 ("odd" org-odd-levels-only t)
3023 ("oddeven" org-odd-levels-only nil)
3024 ("align" org-startup-align-all-tables t)
3025 ("noalign" org-startup-align-all-tables nil)
3026 ("customtime" org-display-custom-times t)
3027 ("logdone" org-log-done time)
3028 ("lognotedone" org-log-done note)
3029 ("nologdone" org-log-done nil)
3030 ("lognoteclock-out" org-log-note-clock-out t)
3031 ("nolognoteclock-out" org-log-note-clock-out nil)
3032 ("logrepeat" org-log-repeat state)
3033 ("lognoterepeat" org-log-repeat note)
3034 ("nologrepeat" org-log-repeat nil)
3035 ("fninline" org-footnote-define-inline t)
3036 ("nofninline" org-footnote-define-inline nil)
3037 ("fnlocal" org-footnote-section nil)
3038 ("fnauto" org-footnote-auto-label t)
3039 ("fnprompt" org-footnote-auto-label nil)
3040 ("fnconfirm" org-footnote-auto-label confirm)
3041 ("fnplain" org-footnote-auto-label plain)
3042 ("constcgs" constants-unit-system cgs)
3043 ("constSI" constants-unit-system SI))
3044 "Variable associated with STARTUP options for org-mode.
3045 Each element is a list of three items: The startup options as written
3046 in the #+STARTUP line, the corresponding variable, and the value to
3047 set this variable to if the option is found. An optional forth element PUSH
3048 means to push this value onto the list in the variable.")
3049
3050 (defun org-set-regexps-and-options ()
3051 "Precompute regular expressions for current buffer."
3052 (when (org-mode-p)
3053 (org-set-local 'org-todo-kwd-alist nil)
3054 (org-set-local 'org-todo-key-alist nil)
3055 (org-set-local 'org-todo-key-trigger nil)
3056 (org-set-local 'org-todo-keywords-1 nil)
3057 (org-set-local 'org-done-keywords nil)
3058 (org-set-local 'org-todo-heads nil)
3059 (org-set-local 'org-todo-sets nil)
3060 (org-set-local 'org-todo-log-states nil)
3061 (org-set-local 'org-file-properties nil)
3062 (org-set-local 'org-file-tags nil)
3063 (let ((re (org-make-options-regexp
3064 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3065 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3066 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3067 (splitre "[ \t]+")
3068 kwds kws0 kwsa key log value cat arch tags const links hw dws
3069 tail sep kws1 prio props ftags drawers
3070 ext-setup-or-nil setup-contents (start 0))
3071 (save-excursion
3072 (save-restriction
3073 (widen)
3074 (goto-char (point-min))
3075 (while (or (and ext-setup-or-nil
3076 (string-match re ext-setup-or-nil start)
3077 (setq start (match-end 0)))
3078 (and (setq ext-setup-or-nil nil start 0)
3079 (re-search-forward re nil t)))
3080 (setq key (upcase (match-string 1 ext-setup-or-nil))
3081 value (org-match-string-no-properties 2 ext-setup-or-nil))
3082 (cond
3083 ((equal key "CATEGORY")
3084 (if (string-match "[ \t]+$" value)
3085 (setq value (replace-match "" t t value)))
3086 (setq cat value))
3087 ((member key '("SEQ_TODO" "TODO"))
3088 (push (cons 'sequence (org-split-string value splitre)) kwds))
3089 ((equal key "TYP_TODO")
3090 (push (cons 'type (org-split-string value splitre)) kwds))
3091 ((equal key "TAGS")
3092 (setq tags (append tags (org-split-string value splitre))))
3093 ((equal key "COLUMNS")
3094 (org-set-local 'org-columns-default-format value))
3095 ((equal key "LINK")
3096 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3097 (push (cons (match-string 1 value)
3098 (org-trim (match-string 2 value)))
3099 links)))
3100 ((equal key "PRIORITIES")
3101 (setq prio (org-split-string value " +")))
3102 ((equal key "PROPERTY")
3103 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3104 (push (cons (match-string 1 value) (match-string 2 value))
3105 props)))
3106 ((equal key "FILETAGS")
3107 (when (string-match "\\S-" value)
3108 (setq ftags
3109 (append
3110 ftags
3111 (apply 'append
3112 (mapcar (lambda (x) (org-split-string x ":"))
3113 (org-split-string value)))))))
3114 ((equal key "DRAWERS")
3115 (setq drawers (org-split-string value splitre)))
3116 ((equal key "CONSTANTS")
3117 (setq const (append const (org-split-string value splitre))))
3118 ((equal key "STARTUP")
3119 (let ((opts (org-split-string value splitre))
3120 l var val)
3121 (while (setq l (pop opts))
3122 (when (setq l (assoc l org-startup-options))
3123 (setq var (nth 1 l) val (nth 2 l))
3124 (if (not (nth 3 l))
3125 (set (make-local-variable var) val)
3126 (if (not (listp (symbol-value var)))
3127 (set (make-local-variable var) nil))
3128 (set (make-local-variable var) (symbol-value var))
3129 (add-to-list var val))))))
3130 ((equal key "ARCHIVE")
3131 (string-match " *$" value)
3132 (setq arch (replace-match "" t t value))
3133 (remove-text-properties 0 (length arch)
3134 '(face t fontified t) arch))
3135 ((equal key "SETUPFILE")
3136 (setq setup-contents (org-file-contents
3137 (expand-file-name
3138 (org-remove-double-quotes value))
3139 'noerror))
3140 (if (not ext-setup-or-nil)
3141 (setq ext-setup-or-nil setup-contents start 0)
3142 (setq ext-setup-or-nil
3143 (concat (substring ext-setup-or-nil 0 start)
3144 "\n" setup-contents "\n"
3145 (substring ext-setup-or-nil start)))))
3146 ))))
3147 (when cat
3148 (org-set-local 'org-category (intern cat))
3149 (push (cons "CATEGORY" cat) props))
3150 (when prio
3151 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3152 (setq prio (mapcar 'string-to-char prio))
3153 (org-set-local 'org-highest-priority (nth 0 prio))
3154 (org-set-local 'org-lowest-priority (nth 1 prio))
3155 (org-set-local 'org-default-priority (nth 2 prio)))
3156 (and props (org-set-local 'org-file-properties (nreverse props)))
3157 (and ftags (org-set-local 'org-file-tags ftags))
3158 (and drawers (org-set-local 'org-drawers drawers))
3159 (and arch (org-set-local 'org-archive-location arch))
3160 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3161 ;; Process the TODO keywords
3162 (unless kwds
3163 ;; Use the global values as if they had been given locally.
3164 (setq kwds (default-value 'org-todo-keywords))
3165 (if (stringp (car kwds))
3166 (setq kwds (list (cons org-todo-interpretation
3167 (default-value 'org-todo-keywords)))))
3168 (setq kwds (reverse kwds)))
3169 (setq kwds (nreverse kwds))
3170 (let (inter kws kw)
3171 (while (setq kws (pop kwds))
3172 (setq inter (pop kws) sep (member "|" kws)
3173 kws0 (delete "|" (copy-sequence kws))
3174 kwsa nil
3175 kws1 (mapcar
3176 (lambda (x)
3177 ;; 1 2
3178 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3179 (progn
3180 (setq kw (match-string 1 x)
3181 key (and (match-end 2) (match-string 2 x))
3182 log (org-extract-log-state-settings x))
3183 (push (cons kw (and key (string-to-char key))) kwsa)
3184 (and log (push log org-todo-log-states))
3185 kw)
3186 (error "Invalid TODO keyword %s" x)))
3187 kws0)
3188 kwsa (if kwsa (append '((:startgroup))
3189 (nreverse kwsa)
3190 '((:endgroup))))
3191 hw (car kws1)
3192 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3193 tail (list inter hw (car dws) (org-last dws)))
3194 (add-to-list 'org-todo-heads hw 'append)
3195 (push kws1 org-todo-sets)
3196 (setq org-done-keywords (append org-done-keywords dws nil))
3197 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3198 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3199 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3200 (setq org-todo-sets (nreverse org-todo-sets)
3201 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3202 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3203 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3204 ;; Process the constants
3205 (when const
3206 (let (e cst)
3207 (while (setq e (pop const))
3208 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3209 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3210 (setq org-table-formula-constants-local cst)))
3211
3212 ;; Process the tags.
3213 (when tags
3214 (let (e tgs)
3215 (while (setq e (pop tags))
3216 (cond
3217 ((equal e "{") (push '(:startgroup) tgs))
3218 ((equal e "}") (push '(:endgroup) tgs))
3219 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3220 (push (cons (match-string 1 e)
3221 (string-to-char (match-string 2 e)))
3222 tgs))
3223 (t (push (list e) tgs))))
3224 (org-set-local 'org-tag-alist nil)
3225 (while (setq e (pop tgs))
3226 (or (and (stringp (car e))
3227 (assoc (car e) org-tag-alist))
3228 (push e org-tag-alist)))))
3229
3230 ;; Compute the regular expressions and other local variables
3231 (if (not org-done-keywords)
3232 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3233 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3234 (length org-scheduled-string)
3235 (length org-clock-string)
3236 (length org-closed-string)))
3237 org-drawer-regexp
3238 (concat "^[ \t]*:\\("
3239 (mapconcat 'regexp-quote org-drawers "\\|")
3240 "\\):[ \t]*$")
3241 org-not-done-keywords
3242 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3243 org-todo-regexp
3244 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3245 "\\|") "\\)\\>")
3246 org-not-done-regexp
3247 (concat "\\<\\("
3248 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3249 "\\)\\>")
3250 org-todo-line-regexp
3251 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3252 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3253 "\\)\\>\\)?[ \t]*\\(.*\\)")
3254 org-complex-heading-regexp
3255 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3256 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3257 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3258 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3259 org-nl-done-regexp
3260 (concat "\n\\*+[ \t]+"
3261 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3262 "\\)" "\\>")
3263 org-todo-line-tags-regexp
3264 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3265 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3266 (org-re
3267 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3268 org-looking-at-done-regexp
3269 (concat "^" "\\(?:"
3270 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3271 "\\>")
3272 org-deadline-regexp (concat "\\<" org-deadline-string)
3273 org-deadline-time-regexp
3274 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3275 org-deadline-line-regexp
3276 (concat "\\<\\(" org-deadline-string "\\).*")
3277 org-scheduled-regexp
3278 (concat "\\<" org-scheduled-string)
3279 org-scheduled-time-regexp
3280 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3281 org-closed-time-regexp
3282 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3283 org-keyword-time-regexp
3284 (concat "\\<\\(" org-scheduled-string
3285 "\\|" org-deadline-string
3286 "\\|" org-closed-string
3287 "\\|" org-clock-string "\\)"
3288 " *[[<]\\([^]>]+\\)[]>]")
3289 org-keyword-time-not-clock-regexp
3290 (concat "\\<\\(" org-scheduled-string
3291 "\\|" org-deadline-string
3292 "\\|" org-closed-string
3293 "\\)"
3294 " *[[<]\\([^]>]+\\)[]>]")
3295 org-maybe-keyword-time-regexp
3296 (concat "\\(\\<\\(" org-scheduled-string
3297 "\\|" org-deadline-string
3298 "\\|" org-closed-string
3299 "\\|" org-clock-string "\\)\\)?"
3300 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3301 org-planning-or-clock-line-re
3302 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3303 "\\|" org-deadline-string
3304 "\\|" org-closed-string "\\|" org-clock-string
3305 "\\)\\>\\)")
3306 )
3307 (org-compute-latex-and-specials-regexp)
3308 (org-set-font-lock-defaults))))
3309
3310 (defun org-file-contents (file &optional noerror)
3311 "Return the contents of FILE, as a string."
3312 (if (or (not file)
3313 (not (file-readable-p file)))
3314 (if noerror
3315 (progn
3316 (message "Cannot read file %s" file)
3317 (ding) (sit-for 2)
3318 "")
3319 (error "Cannot read file %s" file))
3320 (with-temp-buffer
3321 (insert-file-contents file)
3322 (buffer-string))))
3323
3324 (defun org-extract-log-state-settings (x)
3325 "Extract the log state setting from a TODO keyword string.
3326 This will extract info from a string like \"WAIT(w@/!)\"."
3327 (let (kw key log1 log2)
3328 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3329 (setq kw (match-string 1 x)
3330 key (and (match-end 2) (match-string 2 x))
3331 log1 (and (match-end 3) (match-string 3 x))
3332 log2 (and (match-end 4) (match-string 4 x)))
3333 (and (or log1 log2)
3334 (list kw
3335 (and log1 (if (equal log1 "!") 'time 'note))
3336 (and log2 (if (equal log2 "!") 'time 'note)))))))
3337
3338 (defun org-remove-keyword-keys (list)
3339 "Remove a pair of parenthesis at the end of each string in LIST."
3340 (mapcar (lambda (x)
3341 (if (string-match "(.*)$" x)
3342 (substring x 0 (match-beginning 0))
3343 x))
3344 list))
3345
3346 ;; FIXME: this could be done much better, using second characters etc.
3347 (defun org-assign-fast-keys (alist)
3348 "Assign fast keys to a keyword-key alist.
3349 Respect keys that are already there."
3350 (let (new e k c c1 c2 (char ?a))
3351 (while (setq e (pop alist))
3352 (cond
3353 ((equal e '(:startgroup)) (push e new))
3354 ((equal e '(:endgroup)) (push e new))
3355 (t
3356 (setq k (car e) c2 nil)
3357 (if (cdr e)
3358 (setq c (cdr e))
3359 ;; automatically assign a character.
3360 (setq c1 (string-to-char
3361 (downcase (substring
3362 k (if (= (string-to-char k) ?@) 1 0)))))
3363 (if (or (rassoc c1 new) (rassoc c1 alist))
3364 (while (or (rassoc char new) (rassoc char alist))
3365 (setq char (1+ char)))
3366 (setq c2 c1))
3367 (setq c (or c2 char)))
3368 (push (cons k c) new))))
3369 (nreverse new)))
3370
3371 ;;; Some variables used in various places
3372
3373 (defvar org-window-configuration nil
3374 "Used in various places to store a window configuration.")
3375 (defvar org-finish-function nil
3376 "Function to be called when `C-c C-c' is used.
3377 This is for getting out of special buffers like remember.")
3378
3379
3380 ;; FIXME: Occasionally check by commenting these, to make sure
3381 ;; no other functions uses these, forgetting to let-bind them.
3382 (defvar entry)
3383 (defvar state)
3384 (defvar last-state)
3385 (defvar date)
3386 (defvar description)
3387
3388 ;; Defined somewhere in this file, but used before definition.
3389 (defvar org-html-entities)
3390 (defvar org-struct-menu)
3391 (defvar org-org-menu)
3392 (defvar org-tbl-menu)
3393 (defvar org-agenda-keymap)
3394
3395 ;;;; Define the Org-mode
3396
3397 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3398 (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."))
3399
3400
3401 ;; We use a before-change function to check if a table might need
3402 ;; an update.
3403 (defvar org-table-may-need-update t
3404 "Indicates that a table might need an update.
3405 This variable is set by `org-before-change-function'.
3406 `org-table-align' sets it back to nil.")
3407 (defun org-before-change-function (beg end)
3408 "Every change indicates that a table might need an update."
3409 (setq org-table-may-need-update t))
3410 (defvar org-mode-map)
3411 (defvar org-mode-hook nil
3412 "Mode hook for Org-mode, run after the mode was turned on.")
3413 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3414 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3415 (defvar org-table-buffer-is-an nil)
3416 (defconst org-outline-regexp "\\*+ ")
3417
3418 ;;;###autoload
3419 (define-derived-mode org-mode outline-mode "Org"
3420 "Outline-based notes management and organizer, alias
3421 \"Carsten's outline-mode for keeping track of everything.\"
3422
3423 Org-mode develops organizational tasks around a NOTES file which
3424 contains information about projects as plain text. Org-mode is
3425 implemented on top of outline-mode, which is ideal to keep the content
3426 of large files well structured. It supports ToDo items, deadlines and
3427 time stamps, which magically appear in the diary listing of the Emacs
3428 calendar. Tables are easily created with a built-in table editor.
3429 Plain text URL-like links connect to websites, emails (VM), Usenet
3430 messages (Gnus), BBDB entries, and any files related to the project.
3431 For printing and sharing of notes, an Org-mode file (or a part of it)
3432 can be exported as a structured ASCII or HTML file.
3433
3434 The following commands are available:
3435
3436 \\{org-mode-map}"
3437
3438 ;; Get rid of Outline menus, they are not needed
3439 ;; Need to do this here because define-derived-mode sets up
3440 ;; the keymap so late. Still, it is a waste to call this each time
3441 ;; we switch another buffer into org-mode.
3442 (if (featurep 'xemacs)
3443 (when (boundp 'outline-mode-menu-heading)
3444 ;; Assume this is Greg's port, it used easymenu
3445 (easy-menu-remove outline-mode-menu-heading)
3446 (easy-menu-remove outline-mode-menu-show)
3447 (easy-menu-remove outline-mode-menu-hide))
3448 (define-key org-mode-map [menu-bar headings] 'undefined)
3449 (define-key org-mode-map [menu-bar hide] 'undefined)
3450 (define-key org-mode-map [menu-bar show] 'undefined))
3451
3452 (org-load-modules-maybe)
3453 (easy-menu-add org-org-menu)
3454 (easy-menu-add org-tbl-menu)
3455 (org-install-agenda-files-menu)
3456 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3457 (org-add-to-invisibility-spec '(org-cwidth))
3458 (when (featurep 'xemacs)
3459 (org-set-local 'line-move-ignore-invisible t))
3460 (org-set-local 'outline-regexp org-outline-regexp)
3461 (org-set-local 'outline-level 'org-outline-level)
3462 (when (and org-ellipsis
3463 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3464 (fboundp 'make-glyph-code))
3465 (unless org-display-table
3466 (setq org-display-table (make-display-table)))
3467 (set-display-table-slot
3468 org-display-table 4
3469 (vconcat (mapcar
3470 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3471 org-ellipsis)))
3472 (if (stringp org-ellipsis) org-ellipsis "..."))))
3473 (setq buffer-display-table org-display-table))
3474 (org-set-regexps-and-options)
3475 (when (and org-tag-faces (not org-tags-special-faces-re))
3476 ;; tag faces set outside customize.... force initialization.
3477 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3478 ;; Calc embedded
3479 (org-set-local 'calc-embedded-open-mode "# ")
3480 (modify-syntax-entry ?# "<")
3481 (modify-syntax-entry ?@ "w")
3482 (if org-startup-truncated (setq truncate-lines t))
3483 (org-set-local 'font-lock-unfontify-region-function
3484 'org-unfontify-region)
3485 ;; Activate before-change-function
3486 (org-set-local 'org-table-may-need-update t)
3487 (org-add-hook 'before-change-functions 'org-before-change-function nil
3488 'local)
3489 ;; Check for running clock before killing a buffer
3490 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3491 ;; Paragraphs and auto-filling
3492 (org-set-autofill-regexps)
3493 (setq indent-line-function 'org-indent-line-function)
3494 (org-update-radio-target-regexp)
3495
3496 ;; Comment characters
3497 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3498 (org-set-local 'comment-padding " ")
3499
3500 ;; Align options lines
3501 (org-set-local
3502 'align-mode-rules-list
3503 '((org-in-buffer-settings
3504 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3505 (modes . '(org-mode)))))
3506
3507 ;; Imenu
3508 (org-set-local 'imenu-create-index-function
3509 'org-imenu-get-tree)
3510
3511 ;; Make isearch reveal context
3512 (if (or (featurep 'xemacs)
3513 (not (boundp 'outline-isearch-open-invisible-function)))
3514 ;; Emacs 21 and XEmacs make use of the hook
3515 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3516 ;; Emacs 22 deals with this through a special variable
3517 (org-set-local 'outline-isearch-open-invisible-function
3518 (lambda (&rest ignore) (org-show-context 'isearch))))
3519
3520 ;; If empty file that did not turn on org-mode automatically, make it to.
3521 (if (and org-insert-mode-line-in-empty-file
3522 (interactive-p)
3523 (= (point-min) (point-max)))
3524 (insert "# -*- mode: org -*-\n\n"))
3525
3526 (unless org-inhibit-startup
3527 (when org-startup-align-all-tables
3528 (let ((bmp (buffer-modified-p)))
3529 (org-table-map-tables 'org-table-align)
3530 (set-buffer-modified-p bmp)))
3531 (org-set-startup-visibility)))
3532
3533 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3534
3535 (defun org-current-time ()
3536 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3537 (if (> (car org-time-stamp-rounding-minutes) 1)
3538 (let ((r (car org-time-stamp-rounding-minutes))
3539 (time (decode-time)))
3540 (apply 'encode-time
3541 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3542 (nthcdr 2 time))))
3543 (current-time)))
3544
3545 ;;;; Font-Lock stuff, including the activators
3546
3547 (defvar org-mouse-map (make-sparse-keymap))
3548 (org-defkey org-mouse-map
3549 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3550 (org-defkey org-mouse-map
3551 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3552 (when org-mouse-1-follows-link
3553 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3554 (when org-tab-follows-link
3555 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3556 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3557 (when org-return-follows-link
3558 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3559 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3560
3561 (require 'font-lock)
3562
3563 (defconst org-non-link-chars "]\t\n\r<>")
3564 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3565 "shell" "elisp"))
3566 (defvar org-link-types-re nil
3567 "Matches a link that has a url-like prefix like \"http:\"")
3568 (defvar org-link-re-with-space nil
3569 "Matches a link with spaces, optional angular brackets around it.")
3570 (defvar org-link-re-with-space2 nil
3571 "Matches a link with spaces, optional angular brackets around it.")
3572 (defvar org-link-re-with-space3 nil
3573 "Matches a link with spaces, only for internal part in bracket links.")
3574 (defvar org-angle-link-re nil
3575 "Matches link with angular brackets, spaces are allowed.")
3576 (defvar org-plain-link-re nil
3577 "Matches plain link, without spaces.")
3578 (defvar org-bracket-link-regexp nil
3579 "Matches a link in double brackets.")
3580 (defvar org-bracket-link-analytic-regexp nil
3581 "Regular expression used to analyze links.
3582 Here is what the match groups contain after a match:
3583 1: http:
3584 2: http
3585 3: path
3586 4: [desc]
3587 5: desc")
3588 (defvar org-bracket-link-analytic-regexp++ nil
3589 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3590 (defvar org-any-link-re nil
3591 "Regular expression matching any link.")
3592
3593 (defun org-make-link-regexps ()
3594 "Update the link regular expressions.
3595 This should be called after the variable `org-link-types' has changed."
3596 (setq org-link-types-re
3597 (concat
3598 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3599 org-link-re-with-space
3600 (concat
3601 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3602 "\\([^" org-non-link-chars " ]"
3603 "[^" org-non-link-chars "]*"
3604 "[^" org-non-link-chars " ]\\)>?")
3605 org-link-re-with-space2
3606 (concat
3607 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3608 "\\([^" org-non-link-chars " ]"
3609 "[^\t\n\r]*"
3610 "[^" org-non-link-chars " ]\\)>?")
3611 org-link-re-with-space3
3612 (concat
3613 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3614 "\\([^" org-non-link-chars " ]"
3615 "[^\t\n\r]*\\)")
3616 org-angle-link-re
3617 (concat
3618 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3619 "\\([^" org-non-link-chars " ]"
3620 "[^" org-non-link-chars "]*"
3621 "\\)>")
3622 org-plain-link-re
3623 (concat
3624 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3625 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3626 org-bracket-link-regexp
3627 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3628 org-bracket-link-analytic-regexp
3629 (concat
3630 "\\[\\["
3631 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3632 "\\([^]]+\\)"
3633 "\\]"
3634 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3635 "\\]")
3636 org-bracket-link-analytic-regexp++
3637 (concat
3638 "\\[\\["
3639 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3640 "\\([^]]+\\)"
3641 "\\]"
3642 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3643 "\\]")
3644 org-any-link-re
3645 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3646 org-angle-link-re "\\)\\|\\("
3647 org-plain-link-re "\\)")))
3648
3649 (org-make-link-regexps)
3650
3651 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3652 "Regular expression for fast time stamp matching.")
3653 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3654 "Regular expression for fast time stamp matching.")
3655 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3656 "Regular expression matching time strings for analysis.
3657 This one does not require the space after the date, so it can be used
3658 on a string that terminates immediately after the date.")
3659 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3660 "Regular expression matching time strings for analysis.")
3661 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3662 "Regular expression matching time stamps, with groups.")
3663 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3664 "Regular expression matching time stamps (also [..]), with groups.")
3665 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3666 "Regular expression matching a time stamp range.")
3667 (defconst org-tr-regexp-both
3668 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3669 "Regular expression matching a time stamp range.")
3670 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3671 org-ts-regexp "\\)?")
3672 "Regular expression matching a time stamp or time stamp range.")
3673 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3674 org-ts-regexp-both "\\)?")
3675 "Regular expression matching a time stamp or time stamp range.
3676 The time stamps may be either active or inactive.")
3677
3678 (defvar org-emph-face nil)
3679
3680 (defun org-do-emphasis-faces (limit)
3681 "Run through the buffer and add overlays to links."
3682 (let (rtn)
3683 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3684 (if (not (= (char-after (match-beginning 3))
3685 (char-after (match-beginning 4))))
3686 (progn
3687 (setq rtn t)
3688 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3689 'face
3690 (nth 1 (assoc (match-string 3)
3691 org-emphasis-alist)))
3692 (add-text-properties (match-beginning 2) (match-end 2)
3693 '(font-lock-multiline t))
3694 (when org-hide-emphasis-markers
3695 (add-text-properties (match-end 4) (match-beginning 5)
3696 '(invisible org-link))
3697 (add-text-properties (match-beginning 3) (match-end 3)
3698 '(invisible org-link)))))
3699 (backward-char 1))
3700 rtn))
3701
3702 (defun org-emphasize (&optional char)
3703 "Insert or change an emphasis, i.e. a font like bold or italic.
3704 If there is an active region, change that region to a new emphasis.
3705 If there is no region, just insert the marker characters and position
3706 the cursor between them.
3707 CHAR should be either the marker character, or the first character of the
3708 HTML tag associated with that emphasis. If CHAR is a space, the means
3709 to remove the emphasis of the selected region.
3710 If char is not given (for example in an interactive call) it
3711 will be prompted for."
3712 (interactive)
3713 (let ((eal org-emphasis-alist) e det
3714 (erc org-emphasis-regexp-components)
3715 (prompt "")
3716 (string "") beg end move tag c s)
3717 (if (org-region-active-p)
3718 (setq beg (region-beginning) end (region-end)
3719 string (buffer-substring beg end))
3720 (setq move t))
3721
3722 (while (setq e (pop eal))
3723 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3724 c (aref tag 0))
3725 (push (cons c (string-to-char (car e))) det)
3726 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3727 (substring tag 1)))))
3728 (setq det (nreverse det))
3729 (unless char
3730 (message "%s" (concat "Emphasis marker or tag:" prompt))
3731 (setq char (read-char-exclusive)))
3732 (setq char (or (cdr (assoc char det)) char))
3733 (if (equal char ?\ )
3734 (setq s "" move nil)
3735 (unless (assoc (char-to-string char) org-emphasis-alist)
3736 (error "No such emphasis marker: \"%c\"" char))
3737 (setq s (char-to-string char)))
3738 (while (and (> (length string) 1)
3739 (equal (substring string 0 1) (substring string -1))
3740 (assoc (substring string 0 1) org-emphasis-alist))
3741 (setq string (substring string 1 -1)))
3742 (setq string (concat s string s))
3743 (if beg (delete-region beg end))
3744 (unless (or (bolp)
3745 (string-match (concat "[" (nth 0 erc) "\n]")
3746 (char-to-string (char-before (point)))))
3747 (insert " "))
3748 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3749 (char-to-string (char-after (point))))
3750 (insert " ") (backward-char 1))
3751 (insert string)
3752 (and move (backward-char 1))))
3753
3754 (defconst org-nonsticky-props
3755 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3756
3757
3758 (defun org-activate-plain-links (limit)
3759 "Run through the buffer and add overlays to links."
3760 (catch 'exit
3761 (let (f)
3762 (while (re-search-forward org-plain-link-re limit t)
3763 (setq f (get-text-property (match-beginning 0) 'face))
3764 (if (or (eq f 'org-tag)
3765 (and (listp f) (memq 'org-tag f)))
3766 nil
3767 (add-text-properties (match-beginning 0) (match-end 0)
3768 (list 'mouse-face 'highlight
3769 'rear-nonsticky org-nonsticky-props
3770 'keymap org-mouse-map
3771 ))
3772 (throw 'exit t))))))
3773
3774 (defun org-activate-code (limit)
3775 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3776 (progn
3777 (remove-text-properties (match-beginning 0) (match-end 0)
3778 '(display t invisible t intangible t))
3779 t)))
3780
3781 (defun org-activate-angle-links (limit)
3782 "Run through the buffer and add overlays to links."
3783 (if (re-search-forward org-angle-link-re limit t)
3784 (progn
3785 (add-text-properties (match-beginning 0) (match-end 0)
3786 (list 'mouse-face 'highlight
3787 'rear-nonsticky org-nonsticky-props
3788 'keymap org-mouse-map
3789 ))
3790 t)))
3791
3792 (defun org-activate-footnote-links (limit)
3793 "Run through the buffer and add overlays to links."
3794 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
3795 limit t)
3796 (progn
3797 (add-text-properties (match-beginning 2) (match-end 2)
3798 (list 'mouse-face 'highlight
3799 'rear-nonsticky org-nonsticky-props
3800 'keymap org-mouse-map
3801 'help-echo
3802 (if (= (point-at-bol) (match-beginning 2))
3803 "Footnote definition"
3804 "Footnote reference")
3805 ))
3806 t)))
3807
3808 (defun org-activate-bracket-links (limit)
3809 "Run through the buffer and add overlays to bracketed links."
3810 (if (re-search-forward org-bracket-link-regexp limit t)
3811 (let* ((help (concat "LINK: "
3812 (org-match-string-no-properties 1)))
3813 ;; FIXME: above we should remove the escapes.
3814 ;; but that requires another match, protecting match data,
3815 ;; a lot of overhead for font-lock.
3816 (ip (org-maybe-intangible
3817 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3818 'keymap org-mouse-map 'mouse-face 'highlight
3819 'font-lock-multiline t 'help-echo help)))
3820 (vp (list 'rear-nonsticky org-nonsticky-props
3821 'keymap org-mouse-map 'mouse-face 'highlight
3822 ' font-lock-multiline t 'help-echo help)))
3823 ;; We need to remove the invisible property here. Table narrowing
3824 ;; may have made some of this invisible.
3825 (remove-text-properties (match-beginning 0) (match-end 0)
3826 '(invisible nil))
3827 (if (match-end 3)
3828 (progn
3829 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3830 (add-text-properties (match-beginning 3) (match-end 3) vp)
3831 (add-text-properties (match-end 3) (match-end 0) ip))
3832 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3833 (add-text-properties (match-beginning 1) (match-end 1) vp)
3834 (add-text-properties (match-end 1) (match-end 0) ip))
3835 t)))
3836
3837 (defun org-activate-dates (limit)
3838 "Run through the buffer and add overlays to dates."
3839 (if (re-search-forward org-tsr-regexp-both limit t)
3840 (progn
3841 (add-text-properties (match-beginning 0) (match-end 0)
3842 (list 'mouse-face 'highlight
3843 'rear-nonsticky org-nonsticky-props
3844 'keymap org-mouse-map))
3845 (when org-display-custom-times
3846 (if (match-end 3)
3847 (org-display-custom-time (match-beginning 3) (match-end 3)))
3848 (org-display-custom-time (match-beginning 1) (match-end 1)))
3849 t)))
3850
3851 (defvar org-target-link-regexp nil
3852 "Regular expression matching radio targets in plain text.")
3853 (make-variable-buffer-local 'org-target-link-regexp)
3854 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3855 "Regular expression matching a link target.")
3856 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3857 "Regular expression matching a radio target.")
3858 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3859 "Regular expression matching any target.")
3860
3861 (defun org-activate-target-links (limit)
3862 "Run through the buffer and add overlays to target matches."
3863 (when org-target-link-regexp
3864 (let ((case-fold-search t))
3865 (if (re-search-forward org-target-link-regexp limit t)
3866 (progn
3867 (add-text-properties (match-beginning 0) (match-end 0)
3868 (list 'mouse-face 'highlight
3869 'rear-nonsticky org-nonsticky-props
3870 'keymap org-mouse-map
3871 'help-echo "Radio target link"
3872 'org-linked-text t))
3873 t)))))
3874
3875 (defun org-update-radio-target-regexp ()
3876 "Find all radio targets in this file and update the regular expression."
3877 (interactive)
3878 (when (memq 'radio org-activate-links)
3879 (setq org-target-link-regexp
3880 (org-make-target-link-regexp (org-all-targets 'radio)))
3881 (org-restart-font-lock)))
3882
3883 (defun org-hide-wide-columns (limit)
3884 (let (s e)
3885 (setq s (text-property-any (point) (or limit (point-max))
3886 'org-cwidth t))
3887 (when s
3888 (setq e (next-single-property-change s 'org-cwidth))
3889 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3890 (goto-char e)
3891 t)))
3892
3893 (defvar org-latex-and-specials-regexp nil
3894 "Regular expression for highlighting export special stuff.")
3895 (defvar org-match-substring-regexp)
3896 (defvar org-match-substring-with-braces-regexp)
3897 (defvar org-export-html-special-string-regexps)
3898
3899 (defun org-compute-latex-and-specials-regexp ()
3900 "Compute regular expression for stuff treated specially by exporters."
3901 (if (not org-highlight-latex-fragments-and-specials)
3902 (org-set-local 'org-latex-and-specials-regexp nil)
3903 (require 'org-exp)
3904 (let*
3905 ((matchers (plist-get org-format-latex-options :matchers))
3906 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3907 org-latex-regexps)))
3908 (options (org-combine-plists (org-default-export-plist)
3909 (org-infile-export-plist)))
3910 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3911 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3912 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3913 (org-export-html-expand (plist-get options :expand-quoted-html))
3914 (org-export-with-special-strings (plist-get options :special-strings))
3915 (re-sub
3916 (cond
3917 ((equal org-export-with-sub-superscripts '{})
3918 (list org-match-substring-with-braces-regexp))
3919 (org-export-with-sub-superscripts
3920 (list org-match-substring-regexp))
3921 (t nil)))
3922 (re-latex
3923 (if org-export-with-LaTeX-fragments
3924 (mapcar (lambda (x) (nth 1 x)) latexs)))
3925 (re-macros
3926 (if org-export-with-TeX-macros
3927 (list (concat "\\\\"
3928 (regexp-opt
3929 (append (mapcar 'car org-html-entities)
3930 (if (boundp 'org-latex-entities)
3931 org-latex-entities nil))
3932 'words))) ; FIXME
3933 ))
3934 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3935 (re-special (if org-export-with-special-strings
3936 (mapcar (lambda (x) (car x))
3937 org-export-html-special-string-regexps)))
3938 (re-rest
3939 (delq nil
3940 (list
3941 (if org-export-html-expand "@<[^>\n]+>")
3942 ))))
3943 (org-set-local
3944 'org-latex-and-specials-regexp
3945 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3946 re-rest) "\\|")))))
3947
3948 (defun org-do-latex-and-special-faces (limit)
3949 "Run through the buffer and add overlays to links."
3950 (when org-latex-and-specials-regexp
3951 (let (rtn d)
3952 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3953 limit t))
3954 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3955 'face))
3956 '(org-code org-verbatim underline)))
3957 (progn
3958 (setq rtn t
3959 d (cond ((member (char-after (1+ (match-beginning 0)))
3960 '(?_ ?^)) 1)
3961 (t 0)))
3962 (font-lock-prepend-text-property
3963 (+ d (match-beginning 0)) (match-end 0)
3964 'face 'org-latex-and-export-specials)
3965 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3966 '(font-lock-multiline t)))))
3967 rtn)))
3968
3969 (defun org-restart-font-lock ()
3970 "Restart font-lock-mode, to force refontification."
3971 (when (and (boundp 'font-lock-mode) font-lock-mode)
3972 (font-lock-mode -1)
3973 (font-lock-mode 1)))
3974
3975 (defun org-all-targets (&optional radio)
3976 "Return a list of all targets in this file.
3977 With optional argument RADIO, only find radio targets."
3978 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3979 rtn)
3980 (save-excursion
3981 (goto-char (point-min))
3982 (while (re-search-forward re nil t)
3983 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3984 rtn)))
3985
3986 (defun org-make-target-link-regexp (targets)
3987 "Make regular expression matching all strings in TARGETS.
3988 The regular expression finds the targets also if there is a line break
3989 between words."
3990 (and targets
3991 (concat
3992 "\\<\\("
3993 (mapconcat
3994 (lambda (x)
3995 (while (string-match " +" x)
3996 (setq x (replace-match "\\s-+" t t x)))
3997 x)
3998 targets
3999 "\\|")
4000 "\\)\\>")))
4001
4002 (defun org-activate-tags (limit)
4003 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4004 (progn
4005 (add-text-properties (match-beginning 1) (match-end 1)
4006 (list 'mouse-face 'highlight
4007 'rear-nonsticky org-nonsticky-props
4008 'keymap org-mouse-map))
4009 t)))
4010
4011 (defun org-outline-level ()
4012 (save-excursion
4013 (looking-at outline-regexp)
4014 (if (match-beginning 1)
4015 (+ (org-get-string-indentation (match-string 1)) 1000)
4016 (1- (- (match-end 0) (match-beginning 0))))))
4017
4018 (defvar org-font-lock-keywords nil)
4019
4020 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4021 "Regular expression matching a property line.")
4022
4023 (defvar org-font-lock-hook nil
4024 "Functions to be called for special font lock stuff.")
4025
4026 (defun org-font-lock-hook (limit)
4027 (run-hook-with-args 'org-font-lock-hook limit))
4028
4029 (defun org-set-font-lock-defaults ()
4030 (let* ((em org-fontify-emphasized-text)
4031 (lk org-activate-links)
4032 (org-font-lock-extra-keywords
4033 (list
4034 ;; Call the hook
4035 '(org-font-lock-hook)
4036 ;; Headlines
4037 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4038 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4039 ;; Table lines
4040 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4041 (1 'org-table t))
4042 ;; Table internals
4043 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4044 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4045 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4046 ;; Drawers
4047 (list org-drawer-regexp '(0 'org-special-keyword t))
4048 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4049 ;; Properties
4050 (list org-property-re
4051 '(1 'org-special-keyword t)
4052 '(3 'org-property-value t))
4053 (if org-format-transports-properties-p
4054 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4055 ;; Links
4056 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4057 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4058 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4059 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4060 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4061 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4062 (if (memq 'footnote lk) '(org-activate-footnote-links
4063 (2 'org-footnote t)))
4064 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4065 '(org-hide-wide-columns (0 nil append))
4066 ;; TODO lines
4067 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4068 '(1 (org-get-todo-face 1) t))
4069 ;; DONE
4070 (if org-fontify-done-headline
4071 (list (concat "^[*]+ +\\<\\("
4072 (mapconcat 'regexp-quote org-done-keywords "\\|")
4073 "\\)\\(.*\\)")
4074 '(2 'org-headline-done t))
4075 nil)
4076 ;; Priorities
4077 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4078 ;; Tags
4079 '(org-font-lock-add-tag-faces)
4080 ;; Special keywords
4081 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4082 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4083 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4084 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4085 ;; Emphasis
4086 (if em
4087 (if (featurep 'xemacs)
4088 '(org-do-emphasis-faces (0 nil append))
4089 '(org-do-emphasis-faces)))
4090 ;; Checkboxes
4091 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4092 2 'bold prepend)
4093 (if org-provide-checkbox-statistics
4094 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4095 (0 (org-get-checkbox-statistics-face) t)))
4096 ;; Description list items
4097 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4098 2 'bold prepend)
4099 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4100 '(1 'org-archived prepend))
4101 ;; Specials
4102 '(org-do-latex-and-special-faces)
4103 ;; Code
4104 '(org-activate-code (1 'org-code t))
4105 ;; COMMENT
4106 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4107 "\\|" org-quote-string "\\)\\>")
4108 '(1 'org-special-keyword t))
4109 '("^#.*" (0 'font-lock-comment-face t))
4110 )))
4111 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4112 ;; Now set the full font-lock-keywords
4113 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4114 (org-set-local 'font-lock-defaults
4115 '(org-font-lock-keywords t nil nil backward-paragraph))
4116 (kill-local-variable 'font-lock-keywords) nil))
4117
4118 (defvar org-m nil)
4119 (defvar org-l nil)
4120 (defvar org-f nil)
4121 (defun org-get-level-face (n)
4122 "Get the right face for match N in font-lock matching of headlines."
4123 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4124 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4125 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4126 (cond
4127 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4128 ((eq n 2) org-f)
4129 (t (if org-level-color-stars-only nil org-f))))
4130
4131 (defun org-get-todo-face (kwd)
4132 "Get the right face for a TODO keyword KWD.
4133 If KWD is a number, get the corresponding match group."
4134 (if (numberp kwd) (setq kwd (match-string kwd)))
4135 (or (cdr (assoc kwd org-todo-keyword-faces))
4136 (and (member kwd org-done-keywords) 'org-done)
4137 'org-todo))
4138
4139 (defun org-font-lock-add-tag-faces (limit)
4140 "Add the special tag faces."
4141 (when (and org-tag-faces org-tags-special-faces-re)
4142 (while (re-search-forward org-tags-special-faces-re limit t)
4143 (add-text-properties (match-beginning 1) (match-end 1)
4144 (list 'face (org-get-tag-face 1)
4145 'font-lock-fontified t))
4146 (backward-char 1))))
4147
4148 (defun org-get-tag-face (kwd)
4149 "Get the right face for a TODO keyword KWD.
4150 If KWD is a number, get the corresponding match group."
4151 (if (numberp kwd) (setq kwd (match-string kwd)))
4152 (or (cdr (assoc kwd org-tag-faces))
4153 'org-tag))
4154
4155 (defun org-unfontify-region (beg end &optional maybe_loudly)
4156 "Remove fontification and activation overlays from links."
4157 (font-lock-default-unfontify-region beg end)
4158 (let* ((buffer-undo-list t)
4159 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4160 (inhibit-modification-hooks t)
4161 deactivate-mark buffer-file-name buffer-file-truename)
4162 (remove-text-properties beg end
4163 '(mouse-face t keymap t org-linked-text t
4164 invisible t intangible t))))
4165
4166 ;;;; Visibility cycling, including org-goto and indirect buffer
4167
4168 ;;; Cycling
4169
4170 (defvar org-cycle-global-status nil)
4171 (make-variable-buffer-local 'org-cycle-global-status)
4172 (defvar org-cycle-subtree-status nil)
4173 (make-variable-buffer-local 'org-cycle-subtree-status)
4174
4175 ;;;###autoload
4176 (defun org-cycle (&optional arg)
4177 "Visibility cycling for Org-mode.
4178
4179 - When this function is called with a prefix argument, rotate the entire
4180 buffer through 3 states (global cycling)
4181 1. OVERVIEW: Show only top-level headlines.
4182 2. CONTENTS: Show all headlines of all levels, but no body text.
4183 3. SHOW ALL: Show everything.
4184 When called with two C-u C-u prefixes, switch to the startup visibility,
4185 determined by the variable `org-startup-folded', and by any VISIBILITY
4186 properties in the buffer.
4187 When called with three C-u C-u C-u prefixed, show the entire buffer,
4188 including drawers.
4189
4190 - When point is at the beginning of a headline, rotate the subtree started
4191 by this line through 3 different states (local cycling)
4192 1. FOLDED: Only the main headline is shown.
4193 2. CHILDREN: The main headline and the direct children are shown.
4194 From this state, you can move to one of the children
4195 and zoom in further.
4196 3. SUBTREE: Show the entire subtree, including body text.
4197
4198 - When there is a numeric prefix, go up to a heading with level ARG, do
4199 a `show-subtree' and return to the previous cursor position. If ARG
4200 is negative, go up that many levels.
4201
4202 - When point is not at the beginning of a headline, execute the global
4203 binding for TAB, which is re-indenting the line. See the option
4204 `org-cycle-emulate-tab' for details.
4205
4206 - Special case: if point is at the beginning of the buffer and there is
4207 no headline in line 1, this function will act as if called with prefix arg.
4208 But only if also the variable `org-cycle-global-at-bob' is t."
4209 (interactive "P")
4210 (org-load-modules-maybe)
4211 (let* ((outline-regexp
4212 (if (and (org-mode-p) org-cycle-include-plain-lists)
4213 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4214 outline-regexp))
4215 (bob-special (and org-cycle-global-at-bob (bobp)
4216 (not (looking-at outline-regexp))))
4217 (org-cycle-hook
4218 (if bob-special
4219 (delq 'org-optimize-window-after-visibility-change
4220 (copy-sequence org-cycle-hook))
4221 org-cycle-hook))
4222 (pos (point)))
4223
4224 (if (or bob-special (equal arg '(4)))
4225 ;; special case: use global cycling
4226 (setq arg t))
4227
4228 (cond
4229
4230 ((equal arg '(16))
4231 (org-set-startup-visibility)
4232 (message "Startup visibility, plus VISIBILITY properties"))
4233
4234 ((equal arg '(64))
4235 (show-all)
4236 (message "Entire buffer visible, including drawers"))
4237
4238 ((org-at-table-p 'any)
4239 ;; Enter the table or move to the next field in the table
4240 (or (org-table-recognize-table.el)
4241 (progn
4242 (if arg (org-table-edit-field t)
4243 (org-table-justify-field-maybe)
4244 (call-interactively 'org-table-next-field)))))
4245
4246 ((eq arg t) ;; Global cycling
4247
4248 (cond
4249 ((and (eq last-command this-command)
4250 (eq org-cycle-global-status 'overview))
4251 ;; We just created the overview - now do table of contents
4252 ;; This can be slow in very large buffers, so indicate action
4253 (message "CONTENTS...")
4254 (org-content)
4255 (message "CONTENTS...done")
4256 (setq org-cycle-global-status 'contents)
4257 (run-hook-with-args 'org-cycle-hook 'contents))
4258
4259 ((and (eq last-command this-command)
4260 (eq org-cycle-global-status 'contents))
4261 ;; We just showed the table of contents - now show everything
4262 (show-all)
4263 (message "SHOW ALL")
4264 (setq org-cycle-global-status 'all)
4265 (run-hook-with-args 'org-cycle-hook 'all))
4266
4267 (t
4268 ;; Default action: go to overview
4269 (org-overview)
4270 (message "OVERVIEW")
4271 (setq org-cycle-global-status 'overview)
4272 (run-hook-with-args 'org-cycle-hook 'overview))))
4273
4274 ((and org-drawers org-drawer-regexp
4275 (save-excursion
4276 (beginning-of-line 1)
4277 (looking-at org-drawer-regexp)))
4278 ;; Toggle block visibility
4279 (org-flag-drawer
4280 (not (get-char-property (match-end 0) 'invisible))))
4281
4282 ((integerp arg)
4283 ;; Show-subtree, ARG levels up from here.
4284 (save-excursion
4285 (org-back-to-heading)
4286 (outline-up-heading (if (< arg 0) (- arg)
4287 (- (funcall outline-level) arg)))
4288 (org-show-subtree)))
4289
4290 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4291 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4292 ;; At a heading: rotate between three different views
4293 (org-back-to-heading)
4294 (let ((goal-column 0) eoh eol eos)
4295 ;; First, some boundaries
4296 (save-excursion
4297 (org-back-to-heading)
4298 (save-excursion
4299 (beginning-of-line 2)
4300 (while (and (not (eobp)) ;; this is like `next-line'
4301 (get-char-property (1- (point)) 'invisible))
4302 (beginning-of-line 2)) (setq eol (point)))
4303 (outline-end-of-heading) (setq eoh (point))
4304 (org-end-of-subtree t)
4305 (unless (eobp)
4306 (skip-chars-forward " \t\n")
4307 (beginning-of-line 1) ; in case this is an item
4308 )
4309 (setq eos (1- (point))))
4310 ;; Find out what to do next and set `this-command'
4311 (cond
4312 ((= eos eoh)
4313 ;; Nothing is hidden behind this heading
4314 (message "EMPTY ENTRY")
4315 (setq org-cycle-subtree-status nil)
4316 (save-excursion
4317 (goto-char eos)
4318 (outline-next-heading)
4319 (if (org-invisible-p) (org-flag-heading nil))))
4320 ((or (>= eol eos)
4321 (not (string-match "\\S-" (buffer-substring eol eos))))
4322 ;; Entire subtree is hidden in one line: open it
4323 (org-show-entry)
4324 (show-children)
4325 (message "CHILDREN")
4326 (save-excursion
4327 (goto-char eos)
4328 (outline-next-heading)
4329 (if (org-invisible-p) (org-flag-heading nil)))
4330 (setq org-cycle-subtree-status 'children)
4331 (run-hook-with-args 'org-cycle-hook 'children))
4332 ((and (eq last-command this-command)
4333 (eq org-cycle-subtree-status 'children))
4334 ;; We just showed the children, now show everything.
4335 (org-show-subtree)
4336 (message "SUBTREE")
4337 (setq org-cycle-subtree-status 'subtree)
4338 (run-hook-with-args 'org-cycle-hook 'subtree))
4339 (t
4340 ;; Default action: hide the subtree.
4341 (hide-subtree)
4342 (message "FOLDED")
4343 (setq org-cycle-subtree-status 'folded)
4344 (run-hook-with-args 'org-cycle-hook 'folded)))))
4345
4346 ;; TAB emulation and template completion
4347 (buffer-read-only (org-back-to-heading))
4348
4349 ((org-try-structure-completion))
4350
4351 ((org-try-cdlatex-tab))
4352
4353 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4354 (or (not (bolp))
4355 (not (looking-at outline-regexp))))
4356 (call-interactively (global-key-binding "\t")))
4357
4358 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4359 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4360 (or (and (eq org-cycle-emulate-tab 'white)
4361 (= (match-end 0) (point-at-eol)))
4362 (and (eq org-cycle-emulate-tab 'whitestart)
4363 (>= (match-end 0) pos))))
4364 t
4365 (eq org-cycle-emulate-tab t))
4366 (call-interactively (global-key-binding "\t")))
4367
4368 (t (save-excursion
4369 (org-back-to-heading)
4370 (org-cycle))))))
4371
4372 ;;;###autoload
4373 (defun org-global-cycle (&optional arg)
4374 "Cycle the global visibility. For details see `org-cycle'.
4375 With C-u prefix arg, switch to startup visibility.
4376 With a numeric prefix, show all headlines up to that level."
4377 (interactive "P")
4378 (let ((org-cycle-include-plain-lists
4379 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4380 (cond
4381 ((integerp arg)
4382 (show-all)
4383 (hide-sublevels arg)
4384 (setq org-cycle-global-status 'contents))
4385 ((equal arg '(4))
4386 (org-set-startup-visibility)
4387 (message "Startup visibility, plus VISIBILITY properties."))
4388 (t
4389 (org-cycle '(4))))))
4390
4391 (defun org-set-startup-visibility ()
4392 "Set the visibility required by startup options and properties."
4393 (cond
4394 ((eq org-startup-folded t)
4395 (org-cycle '(4)))
4396 ((eq org-startup-folded 'content)
4397 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4398 (org-cycle '(4)) (org-cycle '(4)))))
4399 (org-set-visibility-according-to-property 'no-cleanup)
4400 (org-cycle-hide-archived-subtrees 'all)
4401 (org-cycle-hide-drawers 'all)
4402 (org-cycle-show-empty-lines 'all))
4403
4404 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4405 "Switch subtree visibilities according to :VISIBILITY: property."
4406 (interactive)
4407 (let (state)
4408 (save-excursion
4409 (goto-char (point-min))
4410 (while (re-search-forward
4411 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4412 nil t)
4413 (setq state (match-string 1))
4414 (save-excursion
4415 (org-back-to-heading t)
4416 (hide-subtree)
4417 (org-reveal)
4418 (cond
4419 ((equal state '("fold" "folded"))
4420 (hide-subtree))
4421 ((equal state "children")
4422 (org-show-hidden-entry)
4423 (show-children))
4424 ((equal state "content")
4425 (save-excursion
4426 (save-restriction
4427 (org-narrow-to-subtree)
4428 (org-content))))
4429 ((member state '("all" "showall"))
4430 (show-subtree)))))
4431 (unless no-cleanup
4432 (org-cycle-hide-archived-subtrees 'all)
4433 (org-cycle-hide-drawers 'all)
4434 (org-cycle-show-empty-lines 'all)))))
4435
4436 (defun org-overview ()
4437 "Switch to overview mode, showing only top-level headlines.
4438 Really, this shows all headlines with level equal or greater than the level
4439 of the first headline in the buffer. This is important, because if the
4440 first headline is not level one, then (hide-sublevels 1) gives confusing
4441 results."
4442 (interactive)
4443 (let ((level (save-excursion
4444 (goto-char (point-min))
4445 (if (re-search-forward (concat "^" outline-regexp) nil t)
4446 (progn
4447 (goto-char (match-beginning 0))
4448 (funcall outline-level))))))
4449 (and level (hide-sublevels level))))
4450
4451 (defun org-content (&optional arg)
4452 "Show all headlines in the buffer, like a table of contents.
4453 With numerical argument N, show content up to level N."
4454 (interactive "P")
4455 (save-excursion
4456 ;; Visit all headings and show their offspring
4457 (and (integerp arg) (org-overview))
4458 (goto-char (point-max))
4459 (catch 'exit
4460 (while (and (progn (condition-case nil
4461 (outline-previous-visible-heading 1)
4462 (error (goto-char (point-min))))
4463 t)
4464 (looking-at outline-regexp))
4465 (if (integerp arg)
4466 (show-children (1- arg))
4467 (show-branches))
4468 (if (bobp) (throw 'exit nil))))))
4469
4470
4471 (defun org-optimize-window-after-visibility-change (state)
4472 "Adjust the window after a change in outline visibility.
4473 This function is the default value of the hook `org-cycle-hook'."
4474 (when (get-buffer-window (current-buffer))
4475 (cond
4476 ; ((eq state 'overview) (org-first-headline-recenter 1))
4477 ; ((eq state 'overview) (org-beginning-of-line))
4478 ((eq state 'content) nil)
4479 ((eq state 'all) nil)
4480 ((eq state 'folded) nil)
4481 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4482 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4483
4484 (defun org-compact-display-after-subtree-move ()
4485 (let (beg end)
4486 (save-excursion
4487 (if (org-up-heading-safe)
4488 (progn
4489 (hide-subtree)
4490 (show-entry)
4491 (show-children)
4492 (org-cycle-show-empty-lines 'children)
4493 (org-cycle-hide-drawers 'children))
4494 (org-overview)))))
4495
4496 (defun org-cycle-show-empty-lines (state)
4497 "Show empty lines above all visible headlines.
4498 The region to be covered depends on STATE when called through
4499 `org-cycle-hook'. Lisp program can use t for STATE to get the
4500 entire buffer covered. Note that an empty line is only shown if there
4501 are at least `org-cycle-separator-lines' empty lines before the headline."
4502 (when (> org-cycle-separator-lines 0)
4503 (save-excursion
4504 (let* ((n org-cycle-separator-lines)
4505 (re (cond
4506 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4507 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4508 (t (let ((ns (number-to-string (- n 2))))
4509 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4510 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4511 beg end)
4512 (cond
4513 ((memq state '(overview contents t))
4514 (setq beg (point-min) end (point-max)))
4515 ((memq state '(children folded))
4516 (setq beg (point) end (progn (org-end-of-subtree t t)
4517 (beginning-of-line 2)
4518 (point)))))
4519 (when beg
4520 (goto-char beg)
4521 (while (re-search-forward re end t)
4522 (if (not (get-char-property (match-end 1) 'invisible))
4523 (outline-flag-region
4524 (match-beginning 1) (match-end 1) nil)))))))
4525 ;; Never hide empty lines at the end of the file.
4526 (save-excursion
4527 (goto-char (point-max))
4528 (outline-previous-heading)
4529 (outline-end-of-heading)
4530 (if (and (looking-at "[ \t\n]+")
4531 (= (match-end 0) (point-max)))
4532 (outline-flag-region (point) (match-end 0) nil))))
4533
4534 (defun org-show-empty-lines-in-parent ()
4535 "Move to the parent and re-show empty lines before visible headlines."
4536 (save-excursion
4537 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4538 (org-cycle-show-empty-lines context))))
4539
4540 (defun org-cycle-hide-drawers (state)
4541 "Re-hide all drawers after a visibility state change."
4542 (when (and (org-mode-p)
4543 (not (memq state '(overview folded))))
4544 (save-excursion
4545 (let* ((globalp (memq state '(contents all)))
4546 (beg (if globalp (point-min) (point)))
4547 (end (if globalp (point-max) (org-end-of-subtree t))))
4548 (goto-char beg)
4549 (while (re-search-forward org-drawer-regexp end t)
4550 (org-flag-drawer t))))))
4551
4552 (defun org-flag-drawer (flag)
4553 (save-excursion
4554 (beginning-of-line 1)
4555 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4556 (let ((b (match-end 0))
4557 (outline-regexp org-outline-regexp))
4558 (if (re-search-forward
4559 "^[ \t]*:END:"
4560 (save-excursion (outline-next-heading) (point)) t)
4561 (outline-flag-region b (point-at-eol) flag)
4562 (error ":END: line missing"))))))
4563
4564 (defun org-subtree-end-visible-p ()
4565 "Is the end of the current subtree visible?"
4566 (pos-visible-in-window-p
4567 (save-excursion (org-end-of-subtree t) (point))))
4568
4569 (defun org-first-headline-recenter (&optional N)
4570 "Move cursor to the first headline and recenter the headline.
4571 Optional argument N means, put the headline into the Nth line of the window."
4572 (goto-char (point-min))
4573 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4574 (beginning-of-line)
4575 (recenter (prefix-numeric-value N))))
4576
4577 ;;; Org-goto
4578
4579 (defvar org-goto-window-configuration nil)
4580 (defvar org-goto-marker nil)
4581 (defvar org-goto-map
4582 (let ((map (make-sparse-keymap)))
4583 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4584 (while (setq cmd (pop cmds))
4585 (substitute-key-definition cmd cmd map global-map)))
4586 (suppress-keymap map)
4587 (org-defkey map "\C-m" 'org-goto-ret)
4588 (org-defkey map [(return)] 'org-goto-ret)
4589 (org-defkey map [(left)] 'org-goto-left)
4590 (org-defkey map [(right)] 'org-goto-right)
4591 (org-defkey map [(control ?g)] 'org-goto-quit)
4592 (org-defkey map "\C-i" 'org-cycle)
4593 (org-defkey map [(tab)] 'org-cycle)
4594 (org-defkey map [(down)] 'outline-next-visible-heading)
4595 (org-defkey map [(up)] 'outline-previous-visible-heading)
4596 (if org-goto-auto-isearch
4597 (if (fboundp 'define-key-after)
4598 (define-key-after map [t] 'org-goto-local-auto-isearch)
4599 nil)
4600 (org-defkey map "q" 'org-goto-quit)
4601 (org-defkey map "n" 'outline-next-visible-heading)
4602 (org-defkey map "p" 'outline-previous-visible-heading)
4603 (org-defkey map "f" 'outline-forward-same-level)
4604 (org-defkey map "b" 'outline-backward-same-level)
4605 (org-defkey map "u" 'outline-up-heading))
4606 (org-defkey map "/" 'org-occur)
4607 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4608 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4609 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4610 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4611 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4612 map))
4613
4614 (defconst org-goto-help
4615 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4616 RET=jump to location [Q]uit and return to previous location
4617 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4618
4619 (defvar org-goto-start-pos) ; dynamically scoped parameter
4620
4621 ;; FIXME: Docstring doe not mention both interfaces
4622 (defun org-goto (&optional alternative-interface)
4623 "Look up a different location in the current file, keeping current visibility.
4624
4625 When you want look-up or go to a different location in a document, the
4626 fastest way is often to fold the entire buffer and then dive into the tree.
4627 This method has the disadvantage, that the previous location will be folded,
4628 which may not be what you want.
4629
4630 This command works around this by showing a copy of the current buffer
4631 in an indirect buffer, in overview mode. You can dive into the tree in
4632 that copy, use org-occur and incremental search to find a location.
4633 When pressing RET or `Q', the command returns to the original buffer in
4634 which the visibility is still unchanged. After RET is will also jump to
4635 the location selected in the indirect buffer and expose the
4636 the headline hierarchy above."
4637 (interactive "P")
4638 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4639 (org-refile-use-outline-path t)
4640 (interface
4641 (if (not alternative-interface)
4642 org-goto-interface
4643 (if (eq org-goto-interface 'outline)
4644 'outline-path-completion
4645 'outline)))
4646 (org-goto-start-pos (point))
4647 (selected-point
4648 (if (eq interface 'outline)
4649 (car (org-get-location (current-buffer) org-goto-help))
4650 (nth 3 (org-refile-get-location "Goto: ")))))
4651 (if selected-point
4652 (progn
4653 (org-mark-ring-push org-goto-start-pos)
4654 (goto-char selected-point)
4655 (if (or (org-invisible-p) (org-invisible-p2))
4656 (org-show-context 'org-goto)))
4657 (message "Quit"))))
4658
4659 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4660 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4661 (defvar org-goto-local-auto-isearch-map) ; defined below
4662
4663 (defun org-get-location (buf help)
4664 "Let the user select a location in the Org-mode buffer BUF.
4665 This function uses a recursive edit. It returns the selected position
4666 or nil."
4667 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4668 (isearch-hide-immediately nil)
4669 (isearch-search-fun-function
4670 (lambda () 'org-goto-local-search-headings))
4671 (org-goto-selected-point org-goto-exit-command))
4672 (save-excursion
4673 (save-window-excursion
4674 (delete-other-windows)
4675 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4676 (switch-to-buffer
4677 (condition-case nil
4678 (make-indirect-buffer (current-buffer) "*org-goto*")
4679 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4680 (with-output-to-temp-buffer "*Help*"
4681 (princ help))
4682 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4683 (setq buffer-read-only nil)
4684 (let ((org-startup-truncated t)
4685 (org-startup-folded nil)
4686 (org-startup-align-all-tables nil))
4687 (org-mode)
4688 (org-overview))
4689 (setq buffer-read-only t)
4690 (if (and (boundp 'org-goto-start-pos)
4691 (integer-or-marker-p org-goto-start-pos))
4692 (let ((org-show-hierarchy-above t)
4693 (org-show-siblings t)
4694 (org-show-following-heading t))
4695 (goto-char org-goto-start-pos)
4696 (and (org-invisible-p) (org-show-context)))
4697 (goto-char (point-min)))
4698 (org-beginning-of-line)
4699 (message "Select location and press RET")
4700 (use-local-map org-goto-map)
4701 (recursive-edit)
4702 ))
4703 (kill-buffer "*org-goto*")
4704 (cons org-goto-selected-point org-goto-exit-command)))
4705
4706 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4707 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4708 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4709 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4710
4711 (defun org-goto-local-search-headings (string bound noerror)
4712 "Search and make sure that any matches are in headlines."
4713 (catch 'return
4714 (while (if isearch-forward
4715 (search-forward string bound noerror)
4716 (search-backward string bound noerror))
4717 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4718 (and (member :headline context)
4719 (not (member :tags context))))
4720 (throw 'return (point))))))
4721
4722 (defun org-goto-local-auto-isearch ()
4723 "Start isearch."
4724 (interactive)
4725 (goto-char (point-min))
4726 (let ((keys (this-command-keys)))
4727 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4728 (isearch-mode t)
4729 (isearch-process-search-char (string-to-char keys)))))
4730
4731 (defun org-goto-ret (&optional arg)
4732 "Finish `org-goto' by going to the new location."
4733 (interactive "P")
4734 (setq org-goto-selected-point (point)
4735 org-goto-exit-command 'return)
4736 (throw 'exit nil))
4737
4738 (defun org-goto-left ()
4739 "Finish `org-goto' by going to the new location."
4740 (interactive)
4741 (if (org-on-heading-p)
4742 (progn
4743 (beginning-of-line 1)
4744 (setq org-goto-selected-point (point)
4745 org-goto-exit-command 'left)
4746 (throw 'exit nil))
4747 (error "Not on a heading")))
4748
4749 (defun org-goto-right ()
4750 "Finish `org-goto' by going to the new location."
4751 (interactive)
4752 (if (org-on-heading-p)
4753 (progn
4754 (setq org-goto-selected-point (point)
4755 org-goto-exit-command 'right)
4756 (throw 'exit nil))
4757 (error "Not on a heading")))
4758
4759 (defun org-goto-quit ()
4760 "Finish `org-goto' without cursor motion."
4761 (interactive)
4762 (setq org-goto-selected-point nil)
4763 (setq org-goto-exit-command 'quit)
4764 (throw 'exit nil))
4765
4766 ;;; Indirect buffer display of subtrees
4767
4768 (defvar org-indirect-dedicated-frame nil
4769 "This is the frame being used for indirect tree display.")
4770 (defvar org-last-indirect-buffer nil)
4771
4772 (defun org-tree-to-indirect-buffer (&optional arg)
4773 "Create indirect buffer and narrow it to current subtree.
4774 With numerical prefix ARG, go up to this level and then take that tree.
4775 If ARG is negative, go up that many levels.
4776 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4777 indirect buffer previously made with this command, to avoid proliferation of
4778 indirect buffers. However, when you call the command with a `C-u' prefix, or
4779 when `org-indirect-buffer-display' is `new-frame', the last buffer
4780 is kept so that you can work with several indirect buffers at the same time.
4781 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4782 requests that a new frame be made for the new buffer, so that the dedicated
4783 frame is not changed."
4784 (interactive "P")
4785 (let ((cbuf (current-buffer))
4786 (cwin (selected-window))
4787 (pos (point))
4788 beg end level heading ibuf)
4789 (save-excursion
4790 (org-back-to-heading t)
4791 (when (numberp arg)
4792 (setq level (org-outline-level))
4793 (if (< arg 0) (setq arg (+ level arg)))
4794 (while (> (setq level (org-outline-level)) arg)
4795 (outline-up-heading 1 t)))
4796 (setq beg (point)
4797 heading (org-get-heading))
4798 (org-end-of-subtree t) (setq end (point)))
4799 (if (and (buffer-live-p org-last-indirect-buffer)
4800 (not (eq org-indirect-buffer-display 'new-frame))
4801 (not arg))
4802 (kill-buffer org-last-indirect-buffer))
4803 (setq ibuf (org-get-indirect-buffer cbuf)
4804 org-last-indirect-buffer ibuf)
4805 (cond
4806 ((or (eq org-indirect-buffer-display 'new-frame)
4807 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4808 (select-frame (make-frame))
4809 (delete-other-windows)
4810 (switch-to-buffer ibuf)
4811 (org-set-frame-title heading))
4812 ((eq org-indirect-buffer-display 'dedicated-frame)
4813 (raise-frame
4814 (select-frame (or (and org-indirect-dedicated-frame
4815 (frame-live-p org-indirect-dedicated-frame)
4816 org-indirect-dedicated-frame)
4817 (setq org-indirect-dedicated-frame (make-frame)))))
4818 (delete-other-windows)
4819 (switch-to-buffer ibuf)
4820 (org-set-frame-title (concat "Indirect: " heading)))
4821 ((eq org-indirect-buffer-display 'current-window)
4822 (switch-to-buffer ibuf))
4823 ((eq org-indirect-buffer-display 'other-window)
4824 (pop-to-buffer ibuf))
4825 (t (error "Invalid value.")))
4826 (if (featurep 'xemacs)
4827 (save-excursion (org-mode) (turn-on-font-lock)))
4828 (narrow-to-region beg end)
4829 (show-all)
4830 (goto-char pos)
4831 (and (window-live-p cwin) (select-window cwin))))
4832
4833 (defun org-get-indirect-buffer (&optional buffer)
4834 (setq buffer (or buffer (current-buffer)))
4835 (let ((n 1) (base (buffer-name buffer)) bname)
4836 (while (buffer-live-p
4837 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4838 (setq n (1+ n)))
4839 (condition-case nil
4840 (make-indirect-buffer buffer bname 'clone)
4841 (error (make-indirect-buffer buffer bname)))))
4842
4843 (defun org-set-frame-title (title)
4844 "Set the title of the current frame to the string TITLE."
4845 ;; FIXME: how to name a single frame in XEmacs???
4846 (unless (featurep 'xemacs)
4847 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4848
4849 ;;;; Structure editing
4850
4851 ;;; Inserting headlines
4852
4853 (defun org-previous-line-empty-p ()
4854 (save-excursion
4855 (and (not (bobp))
4856 (or (beginning-of-line 0) t)
4857 (save-match-data
4858 (looking-at "[ \t]*$")))))
4859
4860 (defun org-insert-heading (&optional force-heading)
4861 "Insert a new heading or item with same depth at point.
4862 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4863 If point is at the beginning of a headline, insert a sibling before the
4864 current headline. If point is not at the beginning, do not split the line,
4865 but create the new headline after the current line."
4866 (interactive "P")
4867 (if (= (buffer-size) 0)
4868 (insert "\n* ")
4869 (when (or force-heading (not (org-insert-item)))
4870 (let* ((empty-line-p nil)
4871 (head (save-excursion
4872 (condition-case nil
4873 (progn
4874 (org-back-to-heading)
4875 (setq empty-line-p (org-previous-line-empty-p))
4876 (match-string 0))
4877 (error "*"))))
4878 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
4879 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
4880 pos hide-previous previous-pos)
4881 (cond
4882 ((and (org-on-heading-p) (bolp)
4883 (or (bobp)
4884 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4885 ;; insert before the current line
4886 (open-line (if blank 2 1)))
4887 ((and (bolp)
4888 (or (bobp)
4889 (save-excursion
4890 (backward-char 1) (not (org-invisible-p)))))
4891 ;; insert right here
4892 nil)
4893 (t
4894 ;; somewhere in the line
4895 (save-excursion
4896 (setq previous-pos (point-at-bol))
4897 (end-of-line)
4898 (setq hide-previous (org-invisible-p)))
4899 (and org-insert-heading-respect-content (org-show-subtree))
4900 (let ((split
4901 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4902 (save-excursion
4903 (let ((p (point)))
4904 (goto-char (point-at-bol))
4905 (and (looking-at org-complex-heading-regexp)
4906 (> p (match-beginning 4)))))))
4907 tags pos)
4908 (cond
4909 (org-insert-heading-respect-content
4910 (org-end-of-subtree nil t)
4911 (or (bolp) (newline))
4912 (or (org-previous-line-empty-p)
4913 (and blank (newline)))
4914 (open-line 1))
4915 ((org-on-heading-p)
4916 (when hide-previous
4917 (show-children)
4918 (org-show-entry))
4919 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4920 (setq tags (and (match-end 2) (match-string 2)))
4921 (and (match-end 1)
4922 (delete-region (match-beginning 1) (match-end 1)))
4923 (setq pos (point-at-bol))
4924 (or split (end-of-line 1))
4925 (delete-horizontal-space)
4926 (newline (if blank 2 1))
4927 (when tags
4928 (save-excursion
4929 (goto-char pos)
4930 (end-of-line 1)
4931 (insert " " tags)
4932 (org-set-tags nil 'align))))
4933 (t
4934 (or split (end-of-line 1))
4935 (newline (if blank 2 1)))))))
4936 (insert head) (just-one-space)
4937 (setq pos (point))
4938 (end-of-line 1)
4939 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4940 (when (and org-insert-heading-respect-content hide-previous)
4941 (save-excursion
4942 (goto-char previous-pos)
4943 (hide-subtree)))
4944 (run-hooks 'org-insert-heading-hook)))))
4945
4946 (defun org-get-heading (&optional no-tags)
4947 "Return the heading of the current entry, without the stars."
4948 (save-excursion
4949 (org-back-to-heading t)
4950 (if (looking-at
4951 (if no-tags
4952 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4953 "\\*+[ \t]+\\([^\r\n]*\\)"))
4954 (match-string 1) "")))
4955
4956 (defun org-heading-components ()
4957 "Return the components of the current heading.
4958 This is a list with the following elements:
4959 - the level as an integer
4960 - the reduced level, different if `org-odd-levels-only' is set.
4961 - the TODO keyword, or nil
4962 - the priority character, like ?A, or nil if no priority is given
4963 - the headline text itself, or the tags string if no headline text
4964 - the tags string, or nil."
4965 (save-excursion
4966 (org-back-to-heading t)
4967 (if (looking-at org-complex-heading-regexp)
4968 (list (length (match-string 1))
4969 (org-reduced-level (length (match-string 1)))
4970 (org-match-string-no-properties 2)
4971 (and (match-end 3) (aref (match-string 3) 2))
4972 (org-match-string-no-properties 4)
4973 (org-match-string-no-properties 5)))))
4974
4975 (defun org-insert-heading-after-current ()
4976 "Insert a new heading with same level as current, after current subtree."
4977 (interactive)
4978 (org-back-to-heading)
4979 (org-insert-heading)
4980 (org-move-subtree-down)
4981 (end-of-line 1))
4982
4983 (defun org-insert-heading-respect-content ()
4984 (interactive)
4985 (let ((org-insert-heading-respect-content t))
4986 (org-insert-heading t)))
4987
4988 (defun org-insert-todo-heading-respect-content (&optional force-state)
4989 (interactive "P")
4990 (let ((org-insert-heading-respect-content t))
4991 (org-insert-todo-heading force-state t)))
4992
4993 (defun org-insert-todo-heading (arg &optional force-heading)
4994 "Insert a new heading with the same level and TODO state as current heading.
4995 If the heading has no TODO state, or if the state is DONE, use the first
4996 state (TODO by default). Also with prefix arg, force first state."
4997 (interactive "P")
4998 (when (or force-heading (not (org-insert-item 'checkbox)))
4999 (org-insert-heading force-heading)
5000 (save-excursion
5001 (org-back-to-heading)
5002 (outline-previous-heading)
5003 (looking-at org-todo-line-regexp))
5004 (if (or arg
5005 (not (match-beginning 2))
5006 (member (match-string 2) org-done-keywords))
5007 (insert (car org-todo-keywords-1) " ")
5008 (insert (match-string 2) " "))
5009 (when org-provide-todo-statistics
5010 (org-update-parent-todo-statistics))))
5011
5012 (defun org-insert-subheading (arg)
5013 "Insert a new subheading and demote it.
5014 Works for outline headings and for plain lists alike."
5015 (interactive "P")
5016 (org-insert-heading arg)
5017 (cond
5018 ((org-on-heading-p) (org-do-demote))
5019 ((org-at-item-p) (org-indent-item 1))))
5020
5021 (defun org-insert-todo-subheading (arg)
5022 "Insert a new subheading with TODO keyword or checkbox and demote it.
5023 Works for outline headings and for plain lists alike."
5024 (interactive "P")
5025 (org-insert-todo-heading arg)
5026 (cond
5027 ((org-on-heading-p) (org-do-demote))
5028 ((org-at-item-p) (org-indent-item 1))))
5029
5030 ;;; Promotion and Demotion
5031
5032 (defun org-promote-subtree ()
5033 "Promote the entire subtree.
5034 See also `org-promote'."
5035 (interactive)
5036 (save-excursion
5037 (org-map-tree 'org-promote))
5038 (org-fix-position-after-promote))
5039
5040 (defun org-demote-subtree ()
5041 "Demote the entire subtree. See `org-demote'.
5042 See also `org-promote'."
5043 (interactive)
5044 (save-excursion
5045 (org-map-tree 'org-demote))
5046 (org-fix-position-after-promote))
5047
5048
5049 (defun org-do-promote ()
5050 "Promote the current heading higher up the tree.
5051 If the region is active in `transient-mark-mode', promote all headings
5052 in the region."
5053 (interactive)
5054 (save-excursion
5055 (if (org-region-active-p)
5056 (org-map-region 'org-promote (region-beginning) (region-end))
5057 (org-promote)))
5058 (org-fix-position-after-promote))
5059
5060 (defun org-do-demote ()
5061 "Demote the current heading lower down the tree.
5062 If the region is active in `transient-mark-mode', demote all headings
5063 in the region."
5064 (interactive)
5065 (save-excursion
5066 (if (org-region-active-p)
5067 (org-map-region 'org-demote (region-beginning) (region-end))
5068 (org-demote)))
5069 (org-fix-position-after-promote))
5070
5071 (defun org-fix-position-after-promote ()
5072 "Make sure that after pro/demotion cursor position is right."
5073 (let ((pos (point)))
5074 (when (save-excursion
5075 (beginning-of-line 1)
5076 (looking-at org-todo-line-regexp)
5077 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5078 (cond ((eobp) (insert " "))
5079 ((eolp) (insert " "))
5080 ((equal (char-after) ?\ ) (forward-char 1))))))
5081
5082 (defun org-reduced-level (l)
5083 "Compute the effective level of a heading.
5084 This takes into account the setting of `org-odd-levels-only'."
5085 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5086
5087 (defun org-get-valid-level (level &optional change)
5088 "Rectify a level change under the influence of `org-odd-levels-only'
5089 LEVEL is a current level, CHANGE is by how much the level should be
5090 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5091 even level numbers will become the next higher odd number."
5092 (if org-odd-levels-only
5093 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5094 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5095 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5096 (max 1 (+ level change))))
5097
5098 (if (boundp 'define-obsolete-function-alias)
5099 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5100 (define-obsolete-function-alias 'org-get-legal-level
5101 'org-get-valid-level)
5102 (define-obsolete-function-alias 'org-get-legal-level
5103 'org-get-valid-level "23.1")))
5104
5105 (defun org-promote ()
5106 "Promote the current heading higher up the tree.
5107 If the region is active in `transient-mark-mode', promote all headings
5108 in the region."
5109 (org-back-to-heading t)
5110 (let* ((level (save-match-data (funcall outline-level)))
5111 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5112 (diff (abs (- level (length up-head) -1))))
5113 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5114 (replace-match up-head nil t)
5115 ;; Fixup tag positioning
5116 (and org-auto-align-tags (org-set-tags nil t))
5117 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5118
5119 (defun org-demote ()
5120 "Demote the current heading lower down the tree.
5121 If the region is active in `transient-mark-mode', demote all headings
5122 in the region."
5123 (org-back-to-heading t)
5124 (let* ((level (save-match-data (funcall outline-level)))
5125 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5126 (diff (abs (- level (length down-head) -1))))
5127 (replace-match down-head nil t)
5128 ;; Fixup tag positioning
5129 (and org-auto-align-tags (org-set-tags nil t))
5130 (if org-adapt-indentation (org-fixup-indentation diff))))
5131
5132 (defun org-map-tree (fun)
5133 "Call FUN for every heading underneath the current one."
5134 (org-back-to-heading)
5135 (let ((level (funcall outline-level)))
5136 (save-excursion
5137 (funcall fun)
5138 (while (and (progn
5139 (outline-next-heading)
5140 (> (funcall outline-level) level))
5141 (not (eobp)))
5142 (funcall fun)))))
5143
5144 (defun org-map-region (fun beg end)
5145 "Call FUN for every heading between BEG and END."
5146 (let ((org-ignore-region t))
5147 (save-excursion
5148 (setq end (copy-marker end))
5149 (goto-char beg)
5150 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5151 (< (point) end))
5152 (funcall fun))
5153 (while (and (progn
5154 (outline-next-heading)
5155 (< (point) end))
5156 (not (eobp)))
5157 (funcall fun)))))
5158
5159 (defun org-fixup-indentation (diff)
5160 "Change the indentation in the current entry by DIFF
5161 However, if any line in the current entry has no indentation, or if it
5162 would end up with no indentation after the change, nothing at all is done."
5163 (save-excursion
5164 (let ((end (save-excursion (outline-next-heading)
5165 (point-marker)))
5166 (prohibit (if (> diff 0)
5167 "^\\S-"
5168 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5169 col)
5170 (unless (save-excursion (end-of-line 1)
5171 (re-search-forward prohibit end t))
5172 (while (and (< (point) end)
5173 (re-search-forward "^[ \t]+" end t))
5174 (goto-char (match-end 0))
5175 (setq col (current-column))
5176 (if (< diff 0) (replace-match ""))
5177 (org-indent-to-column (+ diff col))))
5178 (move-marker end nil))))
5179
5180 (defun org-convert-to-odd-levels ()
5181 "Convert an org-mode file with all levels allowed to one with odd levels.
5182 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5183 level 5 etc."
5184 (interactive)
5185 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5186 (let ((org-odd-levels-only nil) n)
5187 (save-excursion
5188 (goto-char (point-min))
5189 (while (re-search-forward "^\\*\\*+ " nil t)
5190 (setq n (- (length (match-string 0)) 2))
5191 (while (>= (setq n (1- n)) 0)
5192 (org-demote))
5193 (end-of-line 1))))))
5194
5195
5196 (defun org-convert-to-oddeven-levels ()
5197 "Convert an org-mode file with only odd levels to one with odd and even levels.
5198 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5199 section with an even level, conversion would destroy the structure of the file. An error
5200 is signaled in this case."
5201 (interactive)
5202 (goto-char (point-min))
5203 ;; First check if there are no even levels
5204 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5205 (org-show-context t)
5206 (error "Not all levels are odd in this file. Conversion not possible."))
5207 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5208 (let ((org-odd-levels-only nil) n)
5209 (save-excursion
5210 (goto-char (point-min))
5211 (while (re-search-forward "^\\*\\*+ " nil t)
5212 (setq n (/ (1- (length (match-string 0))) 2))
5213 (while (>= (setq n (1- n)) 0)
5214 (org-promote))
5215 (end-of-line 1))))))
5216
5217 (defun org-tr-level (n)
5218 "Make N odd if required."
5219 (if org-odd-levels-only (1+ (/ n 2)) n))
5220
5221 ;;; Vertical tree motion, cutting and pasting of subtrees
5222
5223 (defun org-move-subtree-up (&optional arg)
5224 "Move the current subtree up past ARG headlines of the same level."
5225 (interactive "p")
5226 (org-move-subtree-down (- (prefix-numeric-value arg))))
5227
5228 (defun org-move-subtree-down (&optional arg)
5229 "Move the current subtree down past ARG headlines of the same level."
5230 (interactive "p")
5231 (setq arg (prefix-numeric-value arg))
5232 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5233 'outline-get-last-sibling))
5234 (ins-point (make-marker))
5235 (cnt (abs arg))
5236 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5237 ;; Select the tree
5238 (org-back-to-heading)
5239 (setq beg0 (point))
5240 (save-excursion
5241 (setq ne-beg (org-back-over-empty-lines))
5242 (setq beg (point)))
5243 (save-match-data
5244 (save-excursion (outline-end-of-heading)
5245 (setq folded (org-invisible-p)))
5246 (outline-end-of-subtree))
5247 (outline-next-heading)
5248 (setq ne-end (org-back-over-empty-lines))
5249 (setq end (point))
5250 (goto-char beg0)
5251 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5252 ;; include less whitespace
5253 (save-excursion
5254 (goto-char beg)
5255 (forward-line (- ne-beg ne-end))
5256 (setq beg (point))))
5257 ;; Find insertion point, with error handling
5258 (while (> cnt 0)
5259 (or (and (funcall movfunc) (looking-at outline-regexp))
5260 (progn (goto-char beg0)
5261 (error "Cannot move past superior level or buffer limit")))
5262 (setq cnt (1- cnt)))
5263 (if (> arg 0)
5264 ;; Moving forward - still need to move over subtree
5265 (progn (org-end-of-subtree t t)
5266 (save-excursion
5267 (org-back-over-empty-lines)
5268 (or (bolp) (newline)))))
5269 (setq ne-ins (org-back-over-empty-lines))
5270 (move-marker ins-point (point))
5271 (setq txt (buffer-substring beg end))
5272 (org-save-markers-in-region beg end)
5273 (delete-region beg end)
5274 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5275 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5276 (let ((bbb (point)))
5277 (insert-before-markers txt)
5278 (org-reinstall-markers-in-region bbb)
5279 (move-marker ins-point bbb))
5280 (or (bolp) (insert "\n"))
5281 (setq ins-end (point))
5282 (goto-char ins-point)
5283 (org-skip-whitespace)
5284 (when (and (< arg 0)
5285 (org-first-sibling-p)
5286 (> ne-ins ne-beg))
5287 ;; Move whitespace back to beginning
5288 (save-excursion
5289 (goto-char ins-end)
5290 (let ((kill-whole-line t))
5291 (kill-line (- ne-ins ne-beg)) (point)))
5292 (insert (make-string (- ne-ins ne-beg) ?\n)))
5293 (move-marker ins-point nil)
5294 (org-compact-display-after-subtree-move)
5295 (org-show-empty-lines-in-parent)
5296 (unless folded
5297 (org-show-entry)
5298 (show-children)
5299 (org-cycle-hide-drawers 'children))))
5300
5301 (defvar org-subtree-clip ""
5302 "Clipboard for cut and paste of subtrees.
5303 This is actually only a copy of the kill, because we use the normal kill
5304 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5305
5306 (defvar org-subtree-clip-folded nil
5307 "Was the last copied subtree folded?
5308 This is used to fold the tree back after pasting.")
5309
5310 (defun org-cut-subtree (&optional n)
5311 "Cut the current subtree into the clipboard.
5312 With prefix arg N, cut this many sequential subtrees.
5313 This is a short-hand for marking the subtree and then cutting it."
5314 (interactive "p")
5315 (org-copy-subtree n 'cut))
5316
5317 (defun org-copy-subtree (&optional n cut force-store-markers)
5318 "Cut the current subtree into the clipboard.
5319 With prefix arg N, cut this many sequential subtrees.
5320 This is a short-hand for marking the subtree and then copying it.
5321 If CUT is non-nil, actually cut the subtree.
5322 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5323 of some markers in the region, even if CUT is non-nil. This is
5324 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5325 (interactive "p")
5326 (let (beg end folded (beg0 (point)))
5327 (if (interactive-p)
5328 (org-back-to-heading nil) ; take what looks like a subtree
5329 (org-back-to-heading t)) ; take what is really there
5330 (org-back-over-empty-lines)
5331 (setq beg (point))
5332 (skip-chars-forward " \t\r\n")
5333 (save-match-data
5334 (save-excursion (outline-end-of-heading)
5335 (setq folded (org-invisible-p)))
5336 (condition-case nil
5337 (outline-forward-same-level (1- n))
5338 (error nil))
5339 (org-end-of-subtree t t))
5340 (org-back-over-empty-lines)
5341 (setq end (point))
5342 (goto-char beg0)
5343 (when (> end beg)
5344 (setq org-subtree-clip-folded folded)
5345 (when (or cut force-store-markers)
5346 (org-save-markers-in-region beg end))
5347 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5348 (setq org-subtree-clip (current-kill 0))
5349 (message "%s: Subtree(s) with %d characters"
5350 (if cut "Cut" "Copied")
5351 (length org-subtree-clip)))))
5352
5353 (defun org-paste-subtree (&optional level tree for-yank)
5354 "Paste the clipboard as a subtree, with modification of headline level.
5355 The entire subtree is promoted or demoted in order to match a new headline
5356 level.
5357
5358 If the cursor is at the beginning of a headline, the same level as
5359 that headline is used to paste the tree
5360
5361 If not, the new level is derived from the *visible* headings
5362 before and after the insertion point, and taken to be the inferior headline
5363 level of the two. So if the previous visible heading is level 3 and the
5364 next is level 4 (or vice versa), level 4 will be used for insertion.
5365 This makes sure that the subtree remains an independent subtree and does
5366 not swallow low level entries.
5367
5368 You can also force a different level, either by using a numeric prefix
5369 argument, or by inserting the heading marker by hand. For example, if the
5370 cursor is after \"*****\", then the tree will be shifted to level 5.
5371
5372 If optional TREE is given, use this text instead of the kill ring.
5373
5374 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5375 move back over whitespace before inserting, and move point to the end of
5376 the inserted text when done."
5377 (interactive "P")
5378 (unless (org-kill-is-subtree-p tree)
5379 (error "%s"
5380 (substitute-command-keys
5381 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5382 (let* ((visp (not (org-invisible-p)))
5383 (txt (or tree (and kill-ring (current-kill 0))))
5384 (^re (concat "^\\(" outline-regexp "\\)"))
5385 (re (concat "\\(" outline-regexp "\\)"))
5386 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5387
5388 (old-level (if (string-match ^re txt)
5389 (- (match-end 0) (match-beginning 0) 1)
5390 -1))
5391 (force-level (cond (level (prefix-numeric-value level))
5392 ((and (looking-at "[ \t]*$")
5393 (string-match
5394 ^re_ (buffer-substring
5395 (point-at-bol) (point))))
5396 (- (match-end 1) (match-beginning 1)))
5397 ((and (bolp)
5398 (looking-at org-outline-regexp))
5399 (- (match-end 0) (point) 1))
5400 (t nil)))
5401 (previous-level (save-excursion
5402 (condition-case nil
5403 (progn
5404 (outline-previous-visible-heading 1)
5405 (if (looking-at re)
5406 (- (match-end 0) (match-beginning 0) 1)
5407 1))
5408 (error 1))))
5409 (next-level (save-excursion
5410 (condition-case nil
5411 (progn
5412 (or (looking-at outline-regexp)
5413 (outline-next-visible-heading 1))
5414 (if (looking-at re)
5415 (- (match-end 0) (match-beginning 0) 1)
5416 1))
5417 (error 1))))
5418 (new-level (or force-level (max previous-level next-level)))
5419 (shift (if (or (= old-level -1)
5420 (= new-level -1)
5421 (= old-level new-level))
5422 0
5423 (- new-level old-level)))
5424 (delta (if (> shift 0) -1 1))
5425 (func (if (> shift 0) 'org-demote 'org-promote))
5426 (org-odd-levels-only nil)
5427 beg end newend)
5428 ;; Remove the forced level indicator
5429 (if force-level
5430 (delete-region (point-at-bol) (point)))
5431 ;; Paste
5432 (beginning-of-line 1)
5433 (unless for-yank (org-back-over-empty-lines))
5434 (setq beg (point))
5435 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5436 (insert-before-markers txt)
5437 (unless (string-match "\n\\'" txt) (insert "\n"))
5438 (setq newend (point))
5439 (org-reinstall-markers-in-region beg)
5440 (setq end (point))
5441 (goto-char beg)
5442 (skip-chars-forward " \t\n\r")
5443 (setq beg (point))
5444 (if (and (org-invisible-p) visp)
5445 (save-excursion (outline-show-heading)))
5446 ;; Shift if necessary
5447 (unless (= shift 0)
5448 (save-restriction
5449 (narrow-to-region beg end)
5450 (while (not (= shift 0))
5451 (org-map-region func (point-min) (point-max))
5452 (setq shift (+ delta shift)))
5453 (goto-char (point-min))
5454 (setq newend (point-max))))
5455 (when (or (interactive-p) for-yank)
5456 (message "Clipboard pasted as level %d subtree" new-level))
5457 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5458 kill-ring
5459 (eq org-subtree-clip (current-kill 0))
5460 org-subtree-clip-folded)
5461 ;; The tree was folded before it was killed/copied
5462 (hide-subtree))
5463 (and for-yank (goto-char newend))))
5464
5465 (defun org-kill-is-subtree-p (&optional txt)
5466 "Check if the current kill is an outline subtree, or a set of trees.
5467 Returns nil if kill does not start with a headline, or if the first
5468 headline level is not the largest headline level in the tree.
5469 So this will actually accept several entries of equal levels as well,
5470 which is OK for `org-paste-subtree'.
5471 If optional TXT is given, check this string instead of the current kill."
5472 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5473 (start-level (and kill
5474 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5475 org-outline-regexp "\\)")
5476 kill)
5477 (- (match-end 2) (match-beginning 2) 1)))
5478 (re (concat "^" org-outline-regexp))
5479 (start (1+ (or (match-beginning 2) -1))))
5480 (if (not start-level)
5481 (progn
5482 nil) ;; does not even start with a heading
5483 (catch 'exit
5484 (while (setq start (string-match re kill (1+ start)))
5485 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5486 (throw 'exit nil)))
5487 t))))
5488
5489 (defvar org-markers-to-move nil
5490 "Markers that should be moved with a cut-and-paste operation.
5491 Those markers are stored together with their positions relative to
5492 the start of the region.")
5493
5494 (defun org-save-markers-in-region (beg end)
5495 "Check markers in region.
5496 If these markers are between BEG and END, record their position relative
5497 to BEG, so that after moving the block of text, we can put the markers back
5498 into place.
5499 This function gets called just before an entry or tree gets cut from the
5500 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5501 called immediately, to move the markers with the entries."
5502 (setq org-markers-to-move nil)
5503 (when (featurep 'org-clock)
5504 (org-clock-save-markers-for-cut-and-paste beg end))
5505 (when (featurep 'org-agenda)
5506 (org-agenda-save-markers-for-cut-and-paste beg end)))
5507
5508 (defun org-check-and-save-marker (marker beg end)
5509 "Check if MARKER is between BEG and END.
5510 If yes, remember the marker and the distance to BEG."
5511 (when (and (marker-buffer marker)
5512 (equal (marker-buffer marker) (current-buffer)))
5513 (if (and (>= marker beg) (< marker end))
5514 (push (cons marker (- marker beg)) org-markers-to-move))))
5515
5516 (defun org-reinstall-markers-in-region (beg)
5517 "Move all remembered markers to their position relative to BEG."
5518 (mapc (lambda (x)
5519 (move-marker (car x) (+ beg (cdr x))))
5520 org-markers-to-move)
5521 (setq org-markers-to-move nil))
5522
5523 (defun org-narrow-to-subtree ()
5524 "Narrow buffer to the current subtree."
5525 (interactive)
5526 (save-excursion
5527 (save-match-data
5528 (narrow-to-region
5529 (progn (org-back-to-heading) (point))
5530 (progn (org-end-of-subtree t) (point))))))
5531
5532
5533 ;;; Outline Sorting
5534
5535 (defun org-sort (with-case)
5536 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5537 Optional argument WITH-CASE means sort case-sensitively."
5538 (interactive "P")
5539 (if (org-at-table-p)
5540 (org-call-with-arg 'org-table-sort-lines with-case)
5541 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5542
5543 (defun org-sort-remove-invisible (s)
5544 (remove-text-properties 0 (length s) org-rm-props s)
5545 (while (string-match org-bracket-link-regexp s)
5546 (setq s (replace-match (if (match-end 2)
5547 (match-string 3 s)
5548 (match-string 1 s)) t t s)))
5549 s)
5550
5551 (defvar org-priority-regexp) ; defined later in the file
5552
5553 (defun org-sort-entries-or-items
5554 (&optional with-case sorting-type getkey-func compare-func property)
5555 "Sort entries on a certain level of an outline tree.
5556 If there is an active region, the entries in the region are sorted.
5557 Else, if the cursor is before the first entry, sort the top-level items.
5558 Else, the children of the entry at point are sorted.
5559
5560 Sorting can be alphabetically, numerically, and by date/time as given by
5561 the first time stamp in the entry. The command prompts for the sorting
5562 type unless it has been given to the function through the SORTING-TYPE
5563 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5564 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5565 called with point at the beginning of the record. It must return either
5566 a string or a number that should serve as the sorting key for that record.
5567
5568 Comparing entries ignores case by default. However, with an optional argument
5569 WITH-CASE, the sorting considers case as well."
5570 (interactive "P")
5571 (let ((case-func (if with-case 'identity 'downcase))
5572 start beg end stars re re2
5573 txt what tmp plain-list-p)
5574 ;; Find beginning and end of region to sort
5575 (cond
5576 ((org-region-active-p)
5577 ;; we will sort the region
5578 (setq end (region-end)
5579 what "region")
5580 (goto-char (region-beginning))
5581 (if (not (org-on-heading-p)) (outline-next-heading))
5582 (setq start (point)))
5583 ((org-at-item-p)
5584 ;; we will sort this plain list
5585 (org-beginning-of-item-list) (setq start (point))
5586 (org-end-of-item-list) (setq end (point))
5587 (goto-char start)
5588 (setq plain-list-p t
5589 what "plain list"))
5590 ((or (org-on-heading-p)
5591 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5592 ;; we will sort the children of the current headline
5593 (org-back-to-heading)
5594 (setq start (point)
5595 end (progn (org-end-of-subtree t t)
5596 (org-back-over-empty-lines)
5597 (point))
5598 what "children")
5599 (goto-char start)
5600 (show-subtree)
5601 (outline-next-heading))
5602 (t
5603 ;; we will sort the top-level entries in this file
5604 (goto-char (point-min))
5605 (or (org-on-heading-p) (outline-next-heading))
5606 (setq start (point) end (point-max) what "top-level")
5607 (goto-char start)
5608 (show-all)))
5609
5610 (setq beg (point))
5611 (if (>= beg end) (error "Nothing to sort"))
5612
5613 (unless plain-list-p
5614 (looking-at "\\(\\*+\\)")
5615 (setq stars (match-string 1)
5616 re (concat "^" (regexp-quote stars) " +")
5617 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5618 txt (buffer-substring beg end))
5619 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5620 (if (and (not (equal stars "*")) (string-match re2 txt))
5621 (error "Region to sort contains a level above the first entry")))
5622
5623 (unless sorting-type
5624 (message
5625 (if plain-list-p
5626 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5627 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty todo[o]rder [f]unc A/N/T/P/O/F means reversed:")
5628 what)
5629 (setq sorting-type (read-char-exclusive))
5630
5631 (and (= (downcase sorting-type) ?f)
5632 (setq getkey-func
5633 (org-ido-completing-read "Sort using function: "
5634 obarray 'fboundp t nil nil))
5635 (setq getkey-func (intern getkey-func)))
5636
5637 (and (= (downcase sorting-type) ?r)
5638 (setq property
5639 (org-ido-completing-read "Property: "
5640 (mapcar 'list (org-buffer-property-keys t))
5641 nil t))))
5642
5643 (message "Sorting entries...")
5644
5645 (save-restriction
5646 (narrow-to-region start end)
5647
5648 (let ((dcst (downcase sorting-type))
5649 (now (current-time)))
5650 (sort-subr
5651 (/= dcst sorting-type)
5652 ;; This function moves to the beginning character of the "record" to
5653 ;; be sorted.
5654 (if plain-list-p
5655 (lambda nil
5656 (if (org-at-item-p) t (goto-char (point-max))))
5657 (lambda nil
5658 (if (re-search-forward re nil t)
5659 (goto-char (match-beginning 0))
5660 (goto-char (point-max)))))
5661 ;; This function moves to the last character of the "record" being
5662 ;; sorted.
5663 (if plain-list-p
5664 'org-end-of-item
5665 (lambda nil
5666 (save-match-data
5667 (condition-case nil
5668 (outline-forward-same-level 1)
5669 (error
5670 (goto-char (point-max)))))))
5671
5672 ;; This function returns the value that gets sorted against.
5673 (if plain-list-p
5674 (lambda nil
5675 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5676 (cond
5677 ((= dcst ?n)
5678 (string-to-number (buffer-substring (match-end 0)
5679 (point-at-eol))))
5680 ((= dcst ?a)
5681 (buffer-substring (match-end 0) (point-at-eol)))
5682 ((= dcst ?t)
5683 (if (re-search-forward org-ts-regexp
5684 (point-at-eol) t)
5685 (org-time-string-to-time (match-string 0))
5686 now))
5687 ((= dcst ?f)
5688 (if getkey-func
5689 (progn
5690 (setq tmp (funcall getkey-func))
5691 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5692 tmp)
5693 (error "Invalid key function `%s'" getkey-func)))
5694 (t (error "Invalid sorting type `%c'" sorting-type)))))
5695 (lambda nil
5696 (cond
5697 ((= dcst ?n)
5698 (if (looking-at org-complex-heading-regexp)
5699 (string-to-number (match-string 4))
5700 nil))
5701 ((= dcst ?a)
5702 (if (looking-at org-complex-heading-regexp)
5703 (funcall case-func (match-string 4))
5704 nil))
5705 ((= dcst ?t)
5706 (if (re-search-forward org-ts-regexp
5707 (save-excursion
5708 (forward-line 2)
5709 (point)) t)
5710 (org-time-string-to-time (match-string 0))
5711 now))
5712 ((= dcst ?p)
5713 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5714 (string-to-char (match-string 2))
5715 org-default-priority))
5716 ((= dcst ?r)
5717 (or (org-entry-get nil property) ""))
5718 ((= dcst ?o)
5719 (if (looking-at org-complex-heading-regexp)
5720 (- 9999 (length (member (match-string 2)
5721 org-todo-keywords-1)))))
5722 ((= dcst ?f)
5723 (if getkey-func
5724 (progn
5725 (setq tmp (funcall getkey-func))
5726 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5727 tmp)
5728 (error "Invalid key function `%s'" getkey-func)))
5729 (t (error "Invalid sorting type `%c'" sorting-type)))))
5730 nil
5731 (cond
5732 ((= dcst ?a) 'string<)
5733 ((= dcst ?t) 'time-less-p)
5734 ((= dcst ?f) compare-func)
5735 (t nil)))))
5736 (message "Sorting entries...done")))
5737
5738 (defun org-do-sort (table what &optional with-case sorting-type)
5739 "Sort TABLE of WHAT according to SORTING-TYPE.
5740 The user will be prompted for the SORTING-TYPE if the call to this
5741 function does not specify it. WHAT is only for the prompt, to indicate
5742 what is being sorted. The sorting key will be extracted from
5743 the car of the elements of the table.
5744 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5745 (unless sorting-type
5746 (message
5747 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5748 what)
5749 (setq sorting-type (read-char-exclusive)))
5750 (let ((dcst (downcase sorting-type))
5751 extractfun comparefun)
5752 ;; Define the appropriate functions
5753 (cond
5754 ((= dcst ?n)
5755 (setq extractfun 'string-to-number
5756 comparefun (if (= dcst sorting-type) '< '>)))
5757 ((= dcst ?a)
5758 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5759 (lambda(x) (downcase (org-sort-remove-invisible x))))
5760 comparefun (if (= dcst sorting-type)
5761 'string<
5762 (lambda (a b) (and (not (string< a b))
5763 (not (string= a b)))))))
5764 ((= dcst ?t)
5765 (setq extractfun
5766 (lambda (x)
5767 (if (string-match org-ts-regexp x)
5768 (time-to-seconds
5769 (org-time-string-to-time (match-string 0 x)))
5770 0))
5771 comparefun (if (= dcst sorting-type) '< '>)))
5772 (t (error "Invalid sorting type `%c'" sorting-type)))
5773
5774 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5775 table)
5776 (lambda (a b) (funcall comparefun (car a) (car b))))))
5777
5778 ;;; Editing source examples
5779
5780 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5781 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5782 (defvar org-edit-src-force-single-line nil)
5783 (defvar org-edit-src-from-org-mode nil)
5784 (defvar org-edit-src-picture nil)
5785
5786 (define-minor-mode org-exit-edit-mode
5787 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5788
5789 (defun org-edit-src-code ()
5790 "Edit the source code example at point.
5791 An indirect buffer is created, and that buffer is then narrowed to the
5792 example at point and switched to the correct language mode. When done,
5793 exit by killing the buffer with \\[org-edit-src-exit]."
5794 (interactive)
5795 (let ((line (org-current-line))
5796 (case-fold-search t)
5797 (msg (substitute-command-keys
5798 "Edit, then exit with C-c ' (C-c and single quote)"))
5799 (info (org-edit-src-find-region-and-lang))
5800 (org-mode-p (eq major-mode 'org-mode))
5801 beg end lang lang-f single lfmt)
5802 (if (not info)
5803 nil
5804 (setq beg (nth 0 info)
5805 end (nth 1 info)
5806 lang (nth 2 info)
5807 single (nth 3 info)
5808 lfmt (nth 4 info)
5809 lang-f (intern (concat lang "-mode")))
5810 (unless (functionp lang-f)
5811 (error "No such language mode: %s" lang-f))
5812 (goto-line line)
5813 (if (get-buffer "*Org Edit Src Example*")
5814 (kill-buffer "*Org Edit Src Example*"))
5815 (switch-to-buffer (make-indirect-buffer (current-buffer)
5816 "*Org Edit Src Example*"))
5817 (narrow-to-region beg end)
5818 (remove-text-properties beg end '(display nil invisible nil
5819 intangible nil))
5820 (let ((org-inhibit-startup t))
5821 (funcall lang-f))
5822 (set (make-local-variable 'org-edit-src-force-single-line) single)
5823 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5824 (when lfmt
5825 (set (make-local-variable 'org-coderef-label-format) lfmt))
5826 (when org-mode-p
5827 (goto-char (point-min))
5828 (while (re-search-forward "^," nil t)
5829 (replace-match "")))
5830 (goto-line line)
5831 (org-exit-edit-mode)
5832 (org-set-local 'header-line-format msg)
5833 (message "%s" msg)
5834 t)))
5835
5836 (defun org-edit-fixed-width-region ()
5837 "Edit the fixed-width ascii drawing at point.
5838 This must be a region where each line starts with a colon followed by
5839 a space character.
5840 An indirect buffer is created, and that buffer is then narrowed to the
5841 example at point and switched to artist-mode. When done,
5842 exit by killing the buffer with \\[org-edit-src-exit]."
5843 (interactive)
5844 (let ((line (org-current-line))
5845 (case-fold-search t)
5846 (msg (substitute-command-keys
5847 "Edit, then exit with C-c ' (C-c and single quote)"))
5848 (org-mode-p (eq major-mode 'org-mode))
5849 beg end lang lang-f)
5850 (beginning-of-line 1)
5851 (if (looking-at "[ \t]*[^:\n \t]")
5852 nil
5853 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5854 (setq beg (point) end beg)
5855 (save-excursion
5856 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5857 (setq beg (point-at-bol 2))
5858 (setq beg (point))))
5859 (save-excursion
5860 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5861 (setq end (1- (match-beginning 0)))
5862 (setq end (point))))
5863 (goto-line line))
5864 (if (get-buffer "*Org Edit Picture*")
5865 (kill-buffer "*Org Edit Picture*"))
5866 (switch-to-buffer (make-indirect-buffer (current-buffer)
5867 "*Org Edit Picture*"))
5868 (narrow-to-region beg end)
5869 (remove-text-properties beg end '(display nil invisible nil
5870 intangible nil))
5871 (when (fboundp 'font-lock-unfontify-region)
5872 (font-lock-unfontify-region (point-min) (point-max)))
5873 (cond
5874 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5875 (fundamental-mode)
5876 (artist-mode 1))
5877 (t (funcall org-edit-fixed-width-region-mode)))
5878 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5879 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5880 (set (make-local-variable 'org-edit-src-picture) t)
5881 (goto-char (point-min))
5882 (while (re-search-forward "^[ \t]*: ?" nil t)
5883 (replace-match ""))
5884 (goto-line line)
5885 (org-exit-edit-mode)
5886 (org-set-local 'header-line-format msg)
5887 (message "%s" msg)
5888 t)))
5889
5890
5891 (defun org-edit-src-find-region-and-lang ()
5892 "Find the region and language for a local edit.
5893 Return a list with beginning and end of the region, a string representing
5894 the language, a switch telling of the content should be in a single line."
5895 (let ((re-list
5896 (append
5897 org-edit-src-region-extra
5898 '(
5899 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5900 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5901 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5902 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5903 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5904 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5905 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5906 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5907 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5908 ("^#\\+html:" "\n" "html" single-line)
5909 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5910 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5911 ("^#\\+latex:" "\n" "latex" single-line)
5912 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5913 ("^#\\+ascii:" "\n" "ascii" single-line)
5914 )))
5915 (pos (point))
5916 re re1 re2 single beg end lang lfmt match-re1)
5917 (catch 'exit
5918 (while (setq entry (pop re-list))
5919 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5920 single (nth 3 entry))
5921 (save-excursion
5922 (if (or (looking-at re1)
5923 (re-search-backward re1 nil t))
5924 (progn
5925 (setq match-re1 (match-string 0))
5926 (setq beg (match-end 0)
5927 lang (org-edit-src-get-lang lang)
5928 lfmt (org-edit-src-get-label-format match-re1))
5929 (if (and (re-search-forward re2 nil t)
5930 (>= (match-end 0) pos))
5931 (throw 'exit (list beg (match-beginning 0)
5932 lang single lfmt))))
5933 (if (or (looking-at re2)
5934 (re-search-forward re2 nil t))
5935 (progn
5936 (setq end (match-beginning 0))
5937 (if (and (re-search-backward re1 nil t)
5938 (<= (match-beginning 0) pos))
5939 (progn
5940 (setq lfmt (org-edit-src-get-label-format
5941 (match-string 0)))
5942 (throw 'exit
5943 (list (match-end 0) end
5944 (org-edit-src-get-lang lang)
5945 single lfmt))))))))))))
5946
5947 (defun org-edit-src-get-lang (lang)
5948 "Extract the src language."
5949 (let ((m (match-string 0)))
5950 (cond
5951 ((stringp lang) lang)
5952 ((integerp lang) (match-string lang))
5953 ((and (eq lang 'lang)
5954 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5955 (match-string 1 m))
5956 ((and (eq lang 'style)
5957 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5958 (match-string 1 m))
5959 (t "fundamental"))))
5960
5961 (defun org-edit-src-get-label-format (s)
5962 "Extract the label format."
5963 (save-match-data
5964 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
5965 (match-string 1 s))))
5966
5967 (defun org-edit-src-exit ()
5968 "Exit special edit and protect problematic lines."
5969 (interactive)
5970 (unless (buffer-base-buffer (current-buffer))
5971 (error "This is not an indirect buffer, something is wrong..."))
5972 (unless (> (point-min) 1)
5973 (error "This buffer is not narrowed, something is wrong..."))
5974 (goto-char (point-min))
5975 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5976 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5977 (when (org-bound-and-true-p org-edit-src-force-single-line)
5978 (goto-char (point-min))
5979 (while (re-search-forward "\n" nil t)
5980 (replace-match " "))
5981 (goto-char (point-min))
5982 (if (looking-at "\\s-*") (replace-match " "))
5983 (if (re-search-forward "\\s-+\\'" nil t)
5984 (replace-match "")))
5985 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5986 (goto-char (point-min))
5987 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5988 (replace-match ",\\1"))
5989 (when font-lock-mode
5990 (font-lock-unfontify-region (point-min) (point-max)))
5991 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5992 (when (org-bound-and-true-p org-edit-src-picture)
5993 (untabify (point-min) (point-max))
5994 (goto-char (point-min))
5995 (while (re-search-forward "^" nil t)
5996 (replace-match ": "))
5997 (when font-lock-mode
5998 (font-lock-unfontify-region (point-min) (point-max)))
5999 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6000 (kill-buffer (current-buffer))
6001 (and (org-mode-p) (org-restart-font-lock)))
6002
6003
6004 ;;; The orgstruct minor mode
6005
6006 ;; Define a minor mode which can be used in other modes in order to
6007 ;; integrate the org-mode structure editing commands.
6008
6009 ;; This is really a hack, because the org-mode structure commands use
6010 ;; keys which normally belong to the major mode. Here is how it
6011 ;; works: The minor mode defines all the keys necessary to operate the
6012 ;; structure commands, but wraps the commands into a function which
6013 ;; tests if the cursor is currently at a headline or a plain list
6014 ;; item. If that is the case, the structure command is used,
6015 ;; temporarily setting many Org-mode variables like regular
6016 ;; expressions for filling etc. However, when any of those keys is
6017 ;; used at a different location, function uses `key-binding' to look
6018 ;; up if the key has an associated command in another currently active
6019 ;; keymap (minor modes, major mode, global), and executes that
6020 ;; command. There might be problems if any of the keys is otherwise
6021 ;; used as a prefix key.
6022
6023 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6024 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6025 ;; addresses this by checking explicitly for both bindings.
6026
6027 (defvar orgstruct-mode-map (make-sparse-keymap)
6028 "Keymap for the minor `orgstruct-mode'.")
6029
6030 (defvar org-local-vars nil
6031 "List of local variables, for use by `orgstruct-mode'")
6032
6033 ;;;###autoload
6034 (define-minor-mode orgstruct-mode
6035 "Toggle the minor more `orgstruct-mode'.
6036 This mode is for using Org-mode structure commands in other modes.
6037 The following key behave as if Org-mode was active, if the cursor
6038 is on a headline, or on a plain list item (both in the definition
6039 of Org-mode).
6040
6041 M-up Move entry/item up
6042 M-down Move entry/item down
6043 M-left Promote
6044 M-right Demote
6045 M-S-up Move entry/item up
6046 M-S-down Move entry/item down
6047 M-S-left Promote subtree
6048 M-S-right Demote subtree
6049 M-q Fill paragraph and items like in Org-mode
6050 C-c ^ Sort entries
6051 C-c - Cycle list bullet
6052 TAB Cycle item visibility
6053 M-RET Insert new heading/item
6054 S-M-RET Insert new TODO heading / Checkbox item
6055 C-c C-c Set tags / toggle checkbox"
6056 nil " OrgStruct" nil
6057 (org-load-modules-maybe)
6058 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6059
6060 ;;;###autoload
6061 (defun turn-on-orgstruct ()
6062 "Unconditionally turn on `orgstruct-mode'."
6063 (orgstruct-mode 1))
6064
6065 ;;;###autoload
6066 (defun turn-on-orgstruct++ ()
6067 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6068 In addition to setting orgstruct-mode, this also exports all indentation and
6069 autofilling variables from org-mode into the buffer. Note that turning
6070 off orgstruct-mode will *not* remove these additional settings."
6071 (orgstruct-mode 1)
6072 (let (var val)
6073 (mapc
6074 (lambda (x)
6075 (when (string-match
6076 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6077 (symbol-name (car x)))
6078 (setq var (car x) val (nth 1 x))
6079 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6080 org-local-vars)))
6081
6082 (defun orgstruct-error ()
6083 "Error when there is no default binding for a structure key."
6084 (interactive)
6085 (error "This key has no function outside structure elements"))
6086
6087 (defun orgstruct-setup ()
6088 "Setup orgstruct keymaps."
6089 (let ((nfunc 0)
6090 (bindings
6091 (list
6092 '([(meta up)] org-metaup)
6093 '([(meta down)] org-metadown)
6094 '([(meta left)] org-metaleft)
6095 '([(meta right)] org-metaright)
6096 '([(meta shift up)] org-shiftmetaup)
6097 '([(meta shift down)] org-shiftmetadown)
6098 '([(meta shift left)] org-shiftmetaleft)
6099 '([(meta shift right)] org-shiftmetaright)
6100 '([(shift up)] org-shiftup)
6101 '([(shift down)] org-shiftdown)
6102 '([(shift left)] org-shiftleft)
6103 '([(shift right)] org-shiftright)
6104 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6105 '("\M-q" fill-paragraph)
6106 '("\C-c^" org-sort)
6107 '("\C-c-" org-cycle-list-bullet)))
6108 elt key fun cmd)
6109 (while (setq elt (pop bindings))
6110 (setq nfunc (1+ nfunc))
6111 (setq key (org-key (car elt))
6112 fun (nth 1 elt)
6113 cmd (orgstruct-make-binding fun nfunc key))
6114 (org-defkey orgstruct-mode-map key cmd))
6115
6116 ;; Special treatment needed for TAB and RET
6117 (org-defkey orgstruct-mode-map [(tab)]
6118 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6119 (org-defkey orgstruct-mode-map "\C-i"
6120 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6121
6122 (org-defkey orgstruct-mode-map "\M-\C-m"
6123 (orgstruct-make-binding 'org-insert-heading 105
6124 "\M-\C-m" [(meta return)]))
6125 (org-defkey orgstruct-mode-map [(meta return)]
6126 (orgstruct-make-binding 'org-insert-heading 106
6127 [(meta return)] "\M-\C-m"))
6128
6129 (org-defkey orgstruct-mode-map [(shift meta return)]
6130 (orgstruct-make-binding 'org-insert-todo-heading 107
6131 [(meta return)] "\M-\C-m"))
6132
6133 (unless org-local-vars
6134 (setq org-local-vars (org-get-local-variables)))
6135
6136 t))
6137
6138 (defun orgstruct-make-binding (fun n &rest keys)
6139 "Create a function for binding in the structure minor mode.
6140 FUN is the command to call inside a table. N is used to create a unique
6141 command name. KEYS are keys that should be checked in for a command
6142 to execute outside of tables."
6143 (eval
6144 (list 'defun
6145 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6146 '(arg)
6147 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6148 "Outside of structure, run the binding of `"
6149 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6150 "'.")
6151 '(interactive "p")
6152 (list 'if
6153 '(org-context-p 'headline 'item)
6154 (list 'org-run-like-in-org-mode (list 'quote fun))
6155 (list 'let '(orgstruct-mode)
6156 (list 'call-interactively
6157 (append '(or)
6158 (mapcar (lambda (k)
6159 (list 'key-binding k))
6160 keys)
6161 '('orgstruct-error))))))))
6162
6163 (defun org-context-p (&rest contexts)
6164 "Check if local context is any of CONTEXTS.
6165 Possible values in the list of contexts are `table', `headline', and `item'."
6166 (let ((pos (point)))
6167 (goto-char (point-at-bol))
6168 (prog1 (or (and (memq 'table contexts)
6169 (looking-at "[ \t]*|"))
6170 (and (memq 'headline contexts)
6171 ;;????????? (looking-at "\\*+"))
6172 (looking-at outline-regexp))
6173 (and (memq 'item contexts)
6174 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6175 (goto-char pos))))
6176
6177 (defun org-get-local-variables ()
6178 "Return a list of all local variables in an org-mode buffer."
6179 (let (varlist)
6180 (with-current-buffer (get-buffer-create "*Org tmp*")
6181 (erase-buffer)
6182 (org-mode)
6183 (setq varlist (buffer-local-variables)))
6184 (kill-buffer "*Org tmp*")
6185 (delq nil
6186 (mapcar
6187 (lambda (x)
6188 (setq x
6189 (if (symbolp x)
6190 (list x)
6191 (list (car x) (list 'quote (cdr x)))))
6192 (if (string-match
6193 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6194 (symbol-name (car x)))
6195 x nil))
6196 varlist))))
6197
6198 ;;;###autoload
6199 (defun org-run-like-in-org-mode (cmd)
6200 (org-load-modules-maybe)
6201 (unless org-local-vars
6202 (setq org-local-vars (org-get-local-variables)))
6203 (eval (list 'let org-local-vars
6204 (list 'call-interactively (list 'quote cmd)))))
6205
6206 ;;;; Archiving
6207
6208 (defun org-get-category (&optional pos)
6209 "Get the category applying to position POS."
6210 (get-text-property (or pos (point)) 'org-category))
6211
6212 (defun org-refresh-category-properties ()
6213 "Refresh category text properties in the buffer."
6214 (let ((def-cat (cond
6215 ((null org-category)
6216 (if buffer-file-name
6217 (file-name-sans-extension
6218 (file-name-nondirectory buffer-file-name))
6219 "???"))
6220 ((symbolp org-category) (symbol-name org-category))
6221 (t org-category)))
6222 beg end cat pos optionp)
6223 (org-unmodified
6224 (save-excursion
6225 (save-restriction
6226 (widen)
6227 (goto-char (point-min))
6228 (put-text-property (point) (point-max) 'org-category def-cat)
6229 (while (re-search-forward
6230 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6231 (setq pos (match-end 0)
6232 optionp (equal (char-after (match-beginning 0)) ?#)
6233 cat (org-trim (match-string 2)))
6234 (if optionp
6235 (setq beg (point-at-bol) end (point-max))
6236 (org-back-to-heading t)
6237 (setq beg (point) end (org-end-of-subtree t t)))
6238 (put-text-property beg end 'org-category cat)
6239 (goto-char pos)))))))
6240
6241
6242 ;;;; Link Stuff
6243
6244 ;;; Link abbreviations
6245
6246 (defun org-link-expand-abbrev (link)
6247 "Apply replacements as defined in `org-link-abbrev-alist."
6248 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6249 (let* ((key (match-string 1 link))
6250 (as (or (assoc key org-link-abbrev-alist-local)
6251 (assoc key org-link-abbrev-alist)))
6252 (tag (and (match-end 2) (match-string 3 link)))
6253 rpl)
6254 (if (not as)
6255 link
6256 (setq rpl (cdr as))
6257 (cond
6258 ((symbolp rpl) (funcall rpl tag))
6259 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6260 ((string-match "%h" rpl)
6261 (replace-match (url-hexify-string (or tag "")) t t rpl))
6262 (t (concat rpl tag)))))
6263 link))
6264
6265 ;;; Storing and inserting links
6266
6267 (defvar org-insert-link-history nil
6268 "Minibuffer history for links inserted with `org-insert-link'.")
6269
6270 (defvar org-stored-links nil
6271 "Contains the links stored with `org-store-link'.")
6272
6273 (defvar org-store-link-plist nil
6274 "Plist with info about the most recently link created with `org-store-link'.")
6275
6276 (defvar org-link-protocols nil
6277 "Link protocols added to Org-mode using `org-add-link-type'.")
6278
6279 (defvar org-store-link-functions nil
6280 "List of functions that are called to create and store a link.
6281 Each function will be called in turn until one returns a non-nil
6282 value. Each function should check if it is responsible for creating
6283 this link (for example by looking at the major mode).
6284 If not, it must exit and return nil.
6285 If yes, it should return a non-nil value after a calling
6286 `org-store-link-props' with a list of properties and values.
6287 Special properties are:
6288
6289 :type The link prefix. like \"http\". This must be given.
6290 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6291 This is obligatory as well.
6292 :description Optional default description for the second pair
6293 of brackets in an Org-mode link. The user can still change
6294 this when inserting this link into an Org-mode buffer.
6295
6296 In addition to these, any additional properties can be specified
6297 and then used in remember templates.")
6298
6299 (defun org-add-link-type (type &optional follow export)
6300 "Add TYPE to the list of `org-link-types'.
6301 Re-compute all regular expressions depending on `org-link-types'
6302
6303 FOLLOW and EXPORT are two functions.
6304
6305 FOLLOW should take the link path as the single argument and do whatever
6306 is necessary to follow the link, for example find a file or display
6307 a mail message.
6308
6309 EXPORT should format the link path for export to one of the export formats.
6310 It should be a function accepting three arguments:
6311
6312 path the path of the link, the text after the prefix (like \"http:\")
6313 desc the description of the link, if any, nil if there was no description
6314 format the export format, a symbol like `html' or `latex'.
6315
6316 The function may use the FORMAT information to return different values
6317 depending on the format. The return value will be put literally into
6318 the exported file.
6319 Org-mode has a built-in default for exporting links. If you are happy with
6320 this default, there is no need to define an export function for the link
6321 type. For a simple example of an export function, see `org-bbdb.el'."
6322 (add-to-list 'org-link-types type t)
6323 (org-make-link-regexps)
6324 (if (assoc type org-link-protocols)
6325 (setcdr (assoc type org-link-protocols) (list follow export))
6326 (push (list type follow export) org-link-protocols)))
6327
6328 ;;;###autoload
6329 (defun org-store-link (arg)
6330 "\\<org-mode-map>Store an org-link to the current location.
6331 This link is added to `org-stored-links' and can later be inserted
6332 into an org-buffer with \\[org-insert-link].
6333
6334 For some link types, a prefix arg is interpreted:
6335 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6336 For file links, arg negates `org-context-in-file-links'."
6337 (interactive "P")
6338 (org-load-modules-maybe)
6339 (setq org-store-link-plist nil) ; reset
6340 (let (link cpltxt desc description search txt)
6341 (cond
6342
6343 ((run-hook-with-args-until-success 'org-store-link-functions)
6344 (setq link (plist-get org-store-link-plist :link)
6345 desc (or (plist-get org-store-link-plist :description) link)))
6346
6347 ((equal (buffer-name) "*Org Edit Src Example*")
6348 (let (label gc)
6349 (while (or (not label)
6350 (save-excursion
6351 (save-restriction
6352 (widen)
6353 (goto-char (point-min))
6354 (re-search-forward
6355 (regexp-quote (format org-coderef-label-format label))
6356 nil t))))
6357 (when label (message "Label exists already") (sit-for 2))
6358 (setq label (read-string "Code line label: " label)))
6359 (end-of-line 1)
6360 (setq link (format org-coderef-label-format label))
6361 (setq gc (- 79 (length link)))
6362 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6363 (insert link)
6364 (setq link (concat "(" label ")") desc nil)))
6365
6366 ((eq major-mode 'calendar-mode)
6367 (let ((cd (calendar-cursor-to-date)))
6368 (setq link
6369 (format-time-string
6370 (car org-time-stamp-formats)
6371 (apply 'encode-time
6372 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6373 nil nil nil))))
6374 (org-store-link-props :type "calendar" :date cd)))
6375
6376 ((eq major-mode 'w3-mode)
6377 (setq cpltxt (url-view-url t)
6378 link (org-make-link cpltxt))
6379 (org-store-link-props :type "w3" :url (url-view-url t)))
6380
6381 ((eq major-mode 'w3m-mode)
6382 (setq cpltxt (or w3m-current-title w3m-current-url)
6383 link (org-make-link w3m-current-url))
6384 (org-store-link-props :type "w3m" :url (url-view-url t)))
6385
6386 ((setq search (run-hook-with-args-until-success
6387 'org-create-file-search-functions))
6388 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6389 "::" search))
6390 (setq cpltxt (or description link)))
6391
6392 ((eq major-mode 'image-mode)
6393 (setq cpltxt (concat "file:"
6394 (abbreviate-file-name buffer-file-name))
6395 link (org-make-link cpltxt))
6396 (org-store-link-props :type "image" :file buffer-file-name))
6397
6398 ((eq major-mode 'dired-mode)
6399 ;; link to the file in the current line
6400 (setq cpltxt (concat "file:"
6401 (abbreviate-file-name
6402 (expand-file-name
6403 (dired-get-filename nil t))))
6404 link (org-make-link cpltxt)))
6405
6406 ((and buffer-file-name (org-mode-p))
6407 (cond
6408 ((org-in-regexp "<<\\(.*?\\)>>")
6409 (setq cpltxt
6410 (concat "file:"
6411 (abbreviate-file-name buffer-file-name)
6412 "::" (match-string 1))
6413 link (org-make-link cpltxt)))
6414 ((and (featurep 'org-id)
6415 (or (eq org-link-to-org-use-id t)
6416 (and (eq org-link-to-org-use-id 'create-if-interactive)
6417 (interactive-p))
6418 (and org-link-to-org-use-id
6419 (condition-case nil
6420 (org-entry-get nil "ID")
6421 (error nil)))))
6422 ;; We can make a link using the ID.
6423 (setq link (condition-case nil
6424 (prog1 (org-id-store-link)
6425 (setq desc (plist-get org-store-link-plist
6426 :description)))
6427 (error
6428 ;; probably before first headline, link to file only
6429 (concat "file:"
6430 (abbreviate-file-name buffer-file-name))))))
6431 (t
6432 ;; Just link to current headline
6433 (setq cpltxt (concat "file:"
6434 (abbreviate-file-name buffer-file-name)))
6435 ;; Add a context search string
6436 (when (org-xor org-context-in-file-links arg)
6437 (setq txt (cond
6438 ((org-on-heading-p) nil)
6439 ((org-region-active-p)
6440 (buffer-substring (region-beginning) (region-end)))
6441 (t nil)))
6442 (when (or (null txt) (string-match "\\S-" txt))
6443 (setq cpltxt
6444 (concat cpltxt "::"
6445 (condition-case nil
6446 (org-make-org-heading-search-string txt)
6447 (error "")))
6448 desc "NONE")))
6449 (if (string-match "::\\'" cpltxt)
6450 (setq cpltxt (substring cpltxt 0 -2)))
6451 (setq link (org-make-link cpltxt)))))
6452
6453 ((buffer-file-name (buffer-base-buffer))
6454 ;; Just link to this file here.
6455 (setq cpltxt (concat "file:"
6456 (abbreviate-file-name
6457 (buffer-file-name (buffer-base-buffer)))))
6458 ;; Add a context string
6459 (when (org-xor org-context-in-file-links arg)
6460 (setq txt (if (org-region-active-p)
6461 (buffer-substring (region-beginning) (region-end))
6462 (buffer-substring (point-at-bol) (point-at-eol))))
6463 ;; Only use search option if there is some text.
6464 (when (string-match "\\S-" txt)
6465 (setq cpltxt
6466 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6467 desc "NONE")))
6468 (setq link (org-make-link cpltxt)))
6469
6470 ((interactive-p)
6471 (error "Cannot link to a buffer which is not visiting a file"))
6472
6473 (t (setq link nil)))
6474
6475 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6476 (setq link (or link cpltxt)
6477 desc (or desc cpltxt))
6478 (if (equal desc "NONE") (setq desc nil))
6479
6480 (if (and (interactive-p) link)
6481 (progn
6482 (setq org-stored-links
6483 (cons (list link desc) org-stored-links))
6484 (message "Stored: %s" (or desc link)))
6485 (and link (org-make-link-string link desc)))))
6486
6487 (defun org-store-link-props (&rest plist)
6488 "Store link properties, extract names and addresses."
6489 (let (x adr)
6490 (when (setq x (plist-get plist :from))
6491 (setq adr (mail-extract-address-components x))
6492 (setq plist (plist-put plist :fromname (car adr)))
6493 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6494 (when (setq x (plist-get plist :to))
6495 (setq adr (mail-extract-address-components x))
6496 (setq plist (plist-put plist :toname (car adr)))
6497 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6498 (let ((from (plist-get plist :from))
6499 (to (plist-get plist :to)))
6500 (when (and from to org-from-is-user-regexp)
6501 (setq plist
6502 (plist-put plist :fromto
6503 (if (string-match org-from-is-user-regexp from)
6504 (concat "to %t")
6505 (concat "from %f"))))))
6506 (setq org-store-link-plist plist))
6507
6508 (defun org-add-link-props (&rest plist)
6509 "Add these properties to the link property list."
6510 (let (key value)
6511 (while plist
6512 (setq key (pop plist) value (pop plist))
6513 (setq org-store-link-plist
6514 (plist-put org-store-link-plist key value)))))
6515
6516 (defun org-email-link-description (&optional fmt)
6517 "Return the description part of an email link.
6518 This takes information from `org-store-link-plist' and formats it
6519 according to FMT (default from `org-email-link-description-format')."
6520 (setq fmt (or fmt org-email-link-description-format))
6521 (let* ((p org-store-link-plist)
6522 (to (plist-get p :toaddress))
6523 (from (plist-get p :fromaddress))
6524 (table
6525 (list
6526 (cons "%c" (plist-get p :fromto))
6527 (cons "%F" (plist-get p :from))
6528 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6529 (cons "%T" (plist-get p :to))
6530 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6531 (cons "%s" (plist-get p :subject))
6532 (cons "%m" (plist-get p :message-id)))))
6533 (when (string-match "%c" fmt)
6534 ;; Check if the user wrote this message
6535 (if (and org-from-is-user-regexp from to
6536 (save-match-data (string-match org-from-is-user-regexp from)))
6537 (setq fmt (replace-match "to %t" t t fmt))
6538 (setq fmt (replace-match "from %f" t t fmt))))
6539 (org-replace-escapes fmt table)))
6540
6541 (defun org-make-org-heading-search-string (&optional string heading)
6542 "Make search string for STRING or current headline."
6543 (interactive)
6544 (let ((s (or string (org-get-heading))))
6545 (unless (and string (not heading))
6546 ;; We are using a headline, clean up garbage in there.
6547 (if (string-match org-todo-regexp s)
6548 (setq s (replace-match "" t t s)))
6549 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6550 (setq s (replace-match "" t t s)))
6551 (setq s (org-trim s))
6552 (if (string-match (concat "^\\(" org-quote-string "\\|"
6553 org-comment-string "\\)") s)
6554 (setq s (replace-match "" t t s)))
6555 (while (string-match org-ts-regexp s)
6556 (setq s (replace-match "" t t s))))
6557 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6558 (setq s (replace-match " " t t s)))
6559 (or string (setq s (concat "*" s))) ; Add * for headlines
6560 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6561
6562 (defun org-make-link (&rest strings)
6563 "Concatenate STRINGS."
6564 (apply 'concat strings))
6565
6566 (defun org-make-link-string (link &optional description)
6567 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6568 (unless (string-match "\\S-" link)
6569 (error "Empty link"))
6570 (when (stringp description)
6571 ;; Remove brackets from the description, they are fatal.
6572 (while (string-match "\\[" description)
6573 (setq description (replace-match "{" t t description)))
6574 (while (string-match "\\]" description)
6575 (setq description (replace-match "}" t t description))))
6576 (when (equal (org-link-escape link) description)
6577 ;; No description needed, it is identical
6578 (setq description nil))
6579 (when (and (not description)
6580 (not (equal link (org-link-escape link))))
6581 (setq description (org-extract-attributes link)))
6582 (concat "[[" (org-link-escape link) "]"
6583 (if description (concat "[" description "]") "")
6584 "]"))
6585
6586 (defconst org-link-escape-chars
6587 '((?\ . "%20")
6588 (?\[ . "%5B")
6589 (?\] . "%5D")
6590 (?\340 . "%E0") ; `a
6591 (?\342 . "%E2") ; ^a
6592 (?\347 . "%E7") ; ,c
6593 (?\350 . "%E8") ; `e
6594 (?\351 . "%E9") ; 'e
6595 (?\352 . "%EA") ; ^e
6596 (?\356 . "%EE") ; ^i
6597 (?\364 . "%F4") ; ^o
6598 (?\371 . "%F9") ; `u
6599 (?\373 . "%FB") ; ^u
6600 (?\; . "%3B")
6601 (?? . "%3F")
6602 (?= . "%3D")
6603 (?+ . "%2B")
6604 )
6605 "Association list of escapes for some characters problematic in links.
6606 This is the list that is used for internal purposes.")
6607
6608 (defconst org-link-escape-chars-browser
6609 '((?\ . "%20")) ; 32 for the SPC char
6610 "Association list of escapes for some characters problematic in links.
6611 This is the list that is used before handing over to the browser.")
6612
6613 (defun org-link-escape (text &optional table)
6614 "Escape characters in TEXT that are problematic for links."
6615 (setq table (or table org-link-escape-chars))
6616 (when text
6617 (let ((re (mapconcat (lambda (x) (regexp-quote
6618 (char-to-string (car x))))
6619 table "\\|")))
6620 (while (string-match re text)
6621 (setq text
6622 (replace-match
6623 (cdr (assoc (string-to-char (match-string 0 text))
6624 table))
6625 t t text)))
6626 text)))
6627
6628 (defun org-link-unescape (text &optional table)
6629 "Reverse the action of `org-link-escape'."
6630 (setq table (or table org-link-escape-chars))
6631 (when text
6632 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6633 table "\\|")))
6634 (while (string-match re text)
6635 (setq text
6636 (replace-match
6637 (char-to-string (car (rassoc (match-string 0 text) table)))
6638 t t text)))
6639 text)))
6640
6641 (defun org-xor (a b)
6642 "Exclusive or."
6643 (if a (not b) b))
6644
6645 (defun org-fixup-message-id-for-http (s)
6646 "Replace special characters in a message id, so it can be used in an http query."
6647 (while (string-match "<" s)
6648 (setq s (replace-match "%3C" t t s)))
6649 (while (string-match ">" s)
6650 (setq s (replace-match "%3E" t t s)))
6651 (while (string-match "@" s)
6652 (setq s (replace-match "%40" t t s)))
6653 s)
6654
6655 ;;;###autoload
6656 (defun org-insert-link-global ()
6657 "Insert a link like Org-mode does.
6658 This command can be called in any mode to insert a link in Org-mode syntax."
6659 (interactive)
6660 (org-load-modules-maybe)
6661 (org-run-like-in-org-mode 'org-insert-link))
6662
6663 (defun org-insert-link (&optional complete-file link-location)
6664 "Insert a link. At the prompt, enter the link.
6665
6666 Completion can be used to insert any of the link protocol prefixes like
6667 http or ftp in use.
6668
6669 The history can be used to select a link previously stored with
6670 `org-store-link'. When the empty string is entered (i.e. if you just
6671 press RET at the prompt), the link defaults to the most recently
6672 stored link. As SPC triggers completion in the minibuffer, you need to
6673 use M-SPC or C-q SPC to force the insertion of a space character.
6674
6675 You will also be prompted for a description, and if one is given, it will
6676 be displayed in the buffer instead of the link.
6677
6678 If there is already a link at point, this command will allow you to edit link
6679 and description parts.
6680
6681 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6682 be selected using completion. The path to the file will be relative to the
6683 current directory if the file is in the current directory or a subdirectory.
6684 Otherwise, the link will be the absolute path as completed in the minibuffer
6685 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6686 option `org-link-file-path-type'.
6687
6688 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6689 the current directory or below.
6690
6691 With three \\[universal-argument] prefixes, negate the meaning of
6692 `org-keep-stored-link-after-insertion'.
6693
6694 If `org-make-link-description-function' is non-nil, this function will be
6695 called with the link target, and the result will be the default
6696 link description.
6697
6698 If the LINK-LOCATION parameter is non-nil, this value will be
6699 used as the link location instead of reading one interactively."
6700 (interactive "P")
6701 (let* ((wcf (current-window-configuration))
6702 (region (if (org-region-active-p)
6703 (buffer-substring (region-beginning) (region-end))))
6704 (remove (and region (list (region-beginning) (region-end))))
6705 (desc region)
6706 tmphist ; byte-compile incorrectly complains about this
6707 (link link-location)
6708 entry file)
6709 (cond
6710 (link-location) ; specified by arg, just use it.
6711 ((org-in-regexp org-bracket-link-regexp 1)
6712 ;; We do have a link at point, and we are going to edit it.
6713 (setq remove (list (match-beginning 0) (match-end 0)))
6714 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6715 (setq link (read-string "Link: "
6716 (org-link-unescape
6717 (org-match-string-no-properties 1)))))
6718 ((or (org-in-regexp org-angle-link-re)
6719 (org-in-regexp org-plain-link-re))
6720 ;; Convert to bracket link
6721 (setq remove (list (match-beginning 0) (match-end 0))
6722 link (read-string "Link: "
6723 (org-remove-angle-brackets (match-string 0)))))
6724 ((member complete-file '((4) (16)))
6725 ;; Completing read for file names.
6726 (setq file (read-file-name "File: "))
6727 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6728 (pwd1 (file-name-as-directory (abbreviate-file-name
6729 (expand-file-name ".")))))
6730 (cond
6731 ((equal complete-file '(16))
6732 (setq link (org-make-link
6733 "file:"
6734 (abbreviate-file-name (expand-file-name file)))))
6735 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6736 (setq link (org-make-link "file:" (match-string 1 file))))
6737 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6738 (expand-file-name file))
6739 (setq link (org-make-link
6740 "file:" (match-string 1 (expand-file-name file)))))
6741 (t (setq link (org-make-link "file:" file))))))
6742 (t
6743 ;; Read link, with completion for stored links.
6744 (with-output-to-temp-buffer "*Org Links*"
6745 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6746 (when org-stored-links
6747 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6748 (princ (mapconcat
6749 (lambda (x)
6750 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6751 (reverse org-stored-links) "\n"))))
6752 (let ((cw (selected-window)))
6753 (select-window (get-buffer-window "*Org Links*"))
6754 (setq truncate-lines t)
6755 (org-fit-window-to-buffer)
6756 (select-window cw))
6757 ;; Fake a link history, containing the stored links.
6758 (setq tmphist (append (mapcar 'car org-stored-links)
6759 org-insert-link-history))
6760 (unwind-protect
6761 (setq link
6762 (let ((org-completion-use-ido nil))
6763 (org-completing-read
6764 "Link: "
6765 (append
6766 (mapcar (lambda (x) (list (concat (car x) ":")))
6767 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6768 (mapcar (lambda (x) (list (concat x ":")))
6769 org-link-types))
6770 nil nil nil
6771 'tmphist
6772 (or (car (car org-stored-links))))))
6773 (set-window-configuration wcf)
6774 (kill-buffer "*Org Links*"))
6775 (setq entry (assoc link org-stored-links))
6776 (or entry (push link org-insert-link-history))
6777 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6778 (not org-keep-stored-link-after-insertion))
6779 (setq org-stored-links (delq (assoc link org-stored-links)
6780 org-stored-links)))
6781 (setq desc (or desc (nth 1 entry)))))
6782
6783 (if (string-match org-plain-link-re link)
6784 ;; URL-like link, normalize the use of angular brackets.
6785 (setq link (org-make-link (org-remove-angle-brackets link))))
6786
6787 ;; Check if we are linking to the current file with a search option
6788 ;; If yes, simplify the link by using only the search option.
6789 (when (and buffer-file-name
6790 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6791 (let* ((path (match-string 1 link))
6792 (case-fold-search nil)
6793 (search (match-string 2 link)))
6794 (save-match-data
6795 (if (equal (file-truename buffer-file-name) (file-truename path))
6796 ;; We are linking to this same file, with a search option
6797 (setq link search)))))
6798
6799 ;; Check if we can/should use a relative path. If yes, simplify the link
6800 (when (string-match "^file:\\(.*\\)" link)
6801 (let* ((path (match-string 1 link))
6802 (origpath path)
6803 (case-fold-search nil))
6804 (cond
6805 ((or (eq org-link-file-path-type 'absolute)
6806 (equal complete-file '(16)))
6807 (setq path (abbreviate-file-name (expand-file-name path))))
6808 ((eq org-link-file-path-type 'noabbrev)
6809 (setq path (expand-file-name path)))
6810 ((eq org-link-file-path-type 'relative)
6811 (setq path (file-relative-name path)))
6812 (t
6813 (save-match-data
6814 (if (string-match (concat "^" (regexp-quote
6815 (file-name-as-directory
6816 (expand-file-name "."))))
6817 (expand-file-name path))
6818 ;; We are linking a file with relative path name.
6819 (setq path (substring (expand-file-name path)
6820 (match-end 0)))
6821 (setq path (abbreviate-file-name (expand-file-name path)))))))
6822 (setq link (concat "file:" path))
6823 (if (equal desc origpath)
6824 (setq desc path))))
6825
6826 (if org-make-link-description-function
6827 (setq desc (funcall org-make-link-description-function link desc)))
6828
6829 (setq desc (read-string "Description: " desc))
6830 (unless (string-match "\\S-" desc) (setq desc nil))
6831 (if remove (apply 'delete-region remove))
6832 (insert (org-make-link-string link desc))))
6833
6834 (defun org-completing-read (&rest args)
6835 "Completing-read with SPACE being a normal character."
6836 (let ((minibuffer-local-completion-map
6837 (copy-keymap minibuffer-local-completion-map)))
6838 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6839 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
6840 (apply 'org-ido-completing-read args)))
6841
6842 (defun org-ido-completing-read (&rest args)
6843 "Completing-read using `ido-mode' speedups if available"
6844 (if (and org-completion-use-ido
6845 (fboundp 'ido-completing-read)
6846 (boundp 'ido-mode) ido-mode
6847 (listp (second args)))
6848 (apply 'ido-completing-read (concat (car args)) (cdr args))
6849 (apply 'completing-read args)))
6850
6851 (defun org-extract-attributes (s)
6852 "Extract the attributes cookie from a string and set as text property."
6853 (let (a attr (start 0) key value)
6854 (save-match-data
6855 (when (string-match "{{\\([^}]+\\)}}$" s)
6856 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6857 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6858 (setq key (match-string 1 a) value (match-string 2 a)
6859 start (match-end 0)
6860 attr (plist-put attr (intern key) value))))
6861 (org-add-props s nil 'org-attr attr))
6862 s))
6863
6864 (defun org-attributes-to-string (plist)
6865 "Format a property list into an HTML attribute list."
6866 (let ((s "") key value)
6867 (while plist
6868 (setq key (pop plist) value (pop plist))
6869 (and value
6870 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6871 s))
6872
6873 ;;; Opening/following a link
6874
6875 (defvar org-link-search-failed nil)
6876
6877 (defun org-next-link ()
6878 "Move forward to the next link.
6879 If the link is in hidden text, expose it."
6880 (interactive)
6881 (when (and org-link-search-failed (eq this-command last-command))
6882 (goto-char (point-min))
6883 (message "Link search wrapped back to beginning of buffer"))
6884 (setq org-link-search-failed nil)
6885 (let* ((pos (point))
6886 (ct (org-context))
6887 (a (assoc :link ct)))
6888 (if a (goto-char (nth 2 a)))
6889 (if (re-search-forward org-any-link-re nil t)
6890 (progn
6891 (goto-char (match-beginning 0))
6892 (if (org-invisible-p) (org-show-context)))
6893 (goto-char pos)
6894 (setq org-link-search-failed t)
6895 (error "No further link found"))))
6896
6897 (defun org-previous-link ()
6898 "Move backward to the previous link.
6899 If the link is in hidden text, expose it."
6900 (interactive)
6901 (when (and org-link-search-failed (eq this-command last-command))
6902 (goto-char (point-max))
6903 (message "Link search wrapped back to end of buffer"))
6904 (setq org-link-search-failed nil)
6905 (let* ((pos (point))
6906 (ct (org-context))
6907 (a (assoc :link ct)))
6908 (if a (goto-char (nth 1 a)))
6909 (if (re-search-backward org-any-link-re nil t)
6910 (progn
6911 (goto-char (match-beginning 0))
6912 (if (org-invisible-p) (org-show-context)))
6913 (goto-char pos)
6914 (setq org-link-search-failed t)
6915 (error "No further link found"))))
6916
6917 (defun org-translate-link (s)
6918 "Translate a link string if a translation function has been defined."
6919 (if (and org-link-translation-function
6920 (fboundp org-link-translation-function)
6921 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6922 (progn
6923 (setq s (funcall org-link-translation-function
6924 (match-string 1) (match-string 2)))
6925 (concat (car s) ":" (cdr s)))
6926 s))
6927
6928 (defun org-translate-link-from-planner (type path)
6929 "Translate a link from Emacs Planner syntax so that Org can follow it.
6930 This is still an experimental function, your mileage may vary."
6931 (cond
6932 ((member type '("http" "https" "news" "ftp"))
6933 ;; standard Internet links are the same.
6934 nil)
6935 ((and (equal type "irc") (string-match "^//" path))
6936 ;; Planner has two / at the beginning of an irc link, we have 1.
6937 ;; We should have zero, actually....
6938 (setq path (substring path 1)))
6939 ((and (equal type "lisp") (string-match "^/" path))
6940 ;; Planner has a slash, we do not.
6941 (setq type "elisp" path (substring path 1)))
6942 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6943 ;; A typical message link. Planner has the id after the fina slash,
6944 ;; we separate it with a hash mark
6945 (setq path (concat (match-string 1 path) "#"
6946 (org-remove-angle-brackets (match-string 2 path)))))
6947 )
6948 (cons type path))
6949
6950 (defun org-find-file-at-mouse (ev)
6951 "Open file link or URL at mouse."
6952 (interactive "e")
6953 (mouse-set-point ev)
6954 (org-open-at-point 'in-emacs))
6955
6956 (defun org-open-at-mouse (ev)
6957 "Open file link or URL at mouse."
6958 (interactive "e")
6959 (mouse-set-point ev)
6960 (if (eq major-mode 'org-agenda-mode)
6961 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6962 (org-open-at-point))
6963
6964 (defvar org-window-config-before-follow-link nil
6965 "The window configuration before following a link.
6966 This is saved in case the need arises to restore it.")
6967
6968 (defvar org-open-link-marker (make-marker)
6969 "Marker pointing to the location where `org-open-at-point; was called.")
6970
6971 ;;;###autoload
6972 (defun org-open-at-point-global ()
6973 "Follow a link like Org-mode does.
6974 This command can be called in any mode to follow a link that has
6975 Org-mode syntax."
6976 (interactive)
6977 (org-run-like-in-org-mode 'org-open-at-point))
6978
6979 ;;;###autoload
6980 (defun org-open-link-from-string (s &optional arg)
6981 "Open a link in the string S, as if it was in Org-mode."
6982 (interactive "sLink: \nP")
6983 (with-temp-buffer
6984 (let ((org-inhibit-startup t))
6985 (org-mode)
6986 (insert s)
6987 (goto-char (point-min))
6988 (org-open-at-point arg))))
6989
6990 (defun org-open-at-point (&optional in-emacs)
6991 "Open link at or after point.
6992 If there is no link at point, this function will search forward up to
6993 the end of the current subtree.
6994 Normally, files will be opened by an appropriate application. If the
6995 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6996 With a double prefix argument, try to open outside of Emacs, in the
6997 application the system uses for this file type."
6998 (interactive "P")
6999 (org-load-modules-maybe)
7000 (move-marker org-open-link-marker (point))
7001 (setq org-window-config-before-follow-link (current-window-configuration))
7002 (org-remove-occur-highlights nil nil t)
7003 (cond
7004 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7005 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7006 (org-footnote-action))
7007 (t
7008 (let (type path link line search (pos (point)))
7009 (catch 'match
7010 (save-excursion
7011 (skip-chars-forward "^]\n\r")
7012 (when (org-in-regexp org-bracket-link-regexp)
7013 (setq link (org-extract-attributes
7014 (org-link-unescape (org-match-string-no-properties 1))))
7015 (while (string-match " *\n *" link)
7016 (setq link (replace-match " " t t link)))
7017 (setq link (org-link-expand-abbrev link))
7018 (cond
7019 ((or (file-name-absolute-p link)
7020 (string-match "^\\.\\.?/" link))
7021 (setq type "file" path link))
7022 ((string-match org-link-re-with-space3 link)
7023 (setq type (match-string 1 link) path (match-string 2 link)))
7024 (t (setq type "thisfile" path link)))
7025 (throw 'match t)))
7026
7027 (when (get-text-property (point) 'org-linked-text)
7028 (setq type "thisfile"
7029 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7030 (1+ (point)) (point))
7031 path (buffer-substring
7032 (previous-single-property-change pos 'org-linked-text)
7033 (next-single-property-change pos 'org-linked-text)))
7034 (throw 'match t))
7035
7036 (save-excursion
7037 (when (or (org-in-regexp org-angle-link-re)
7038 (org-in-regexp org-plain-link-re))
7039 (setq type (match-string 1) path (match-string 2))
7040 (throw 'match t)))
7041 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7042 (setq type "tree-match"
7043 path (match-string 1))
7044 (throw 'match t))
7045 (save-excursion
7046 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7047 (setq type "tags"
7048 path (match-string 1))
7049 (while (string-match ":" path)
7050 (setq path (replace-match "+" t t path)))
7051 (throw 'match t))))
7052 (unless path
7053 (error "No link found"))
7054 ;; Remove any trailing spaces in path
7055 (if (string-match " +\\'" path)
7056 (setq path (replace-match "" t t path)))
7057 (if (and org-link-translation-function
7058 (fboundp org-link-translation-function))
7059 ;; Check if we need to translate the link
7060 (let ((tmp (funcall org-link-translation-function type path)))
7061 (setq type (car tmp) path (cdr tmp))))
7062
7063 (cond
7064
7065 ((assoc type org-link-protocols)
7066 (funcall (nth 1 (assoc type org-link-protocols)) path))
7067
7068 ((equal type "mailto")
7069 (let ((cmd (car org-link-mailto-program))
7070 (args (cdr org-link-mailto-program)) args1
7071 (address path) (subject "") a)
7072 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7073 (setq address (match-string 1 path)
7074 subject (org-link-escape (match-string 2 path))))
7075 (while args
7076 (cond
7077 ((not (stringp (car args))) (push (pop args) args1))
7078 (t (setq a (pop args))
7079 (if (string-match "%a" a)
7080 (setq a (replace-match address t t a)))
7081 (if (string-match "%s" a)
7082 (setq a (replace-match subject t t a)))
7083 (push a args1))))
7084 (apply cmd (nreverse args1))))
7085
7086 ((member type '("http" "https" "ftp" "news"))
7087 (browse-url (concat type ":" (org-link-escape
7088 path org-link-escape-chars-browser))))
7089
7090 ((member type '("message"))
7091 (browse-url (concat type ":" path)))
7092
7093 ((string= type "tags")
7094 (org-tags-view in-emacs path))
7095 ((string= type "thisfile")
7096 (if in-emacs
7097 (switch-to-buffer-other-window
7098 (org-get-buffer-for-internal-link (current-buffer)))
7099 (org-mark-ring-push))
7100 (let ((cmd `(org-link-search
7101 ,path
7102 ,(cond ((equal in-emacs '(4)) 'occur)
7103 ((equal in-emacs '(16)) 'org-occur)
7104 (t nil))
7105 ,pos)))
7106 (condition-case nil (eval cmd)
7107 (error (progn (widen) (eval cmd))))))
7108
7109 ((string= type "tree-match")
7110 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7111
7112 ((string= type "file")
7113 (if (string-match "::\\([0-9]+\\)\\'" path)
7114 (setq line (string-to-number (match-string 1 path))
7115 path (substring path 0 (match-beginning 0)))
7116 (if (string-match "::\\(.+\\)\\'" path)
7117 (setq search (match-string 1 path)
7118 path (substring path 0 (match-beginning 0)))))
7119 (if (string-match "[*?{]" (file-name-nondirectory path))
7120 (dired path)
7121 (org-open-file path in-emacs line search)))
7122
7123 ((string= type "news")
7124 (require 'org-gnus)
7125 (org-gnus-follow-link path))
7126
7127 ((string= type "shell")
7128 (let ((cmd path))
7129 (if (or (not org-confirm-shell-link-function)
7130 (funcall org-confirm-shell-link-function
7131 (format "Execute \"%s\" in shell? "
7132 (org-add-props cmd nil
7133 'face 'org-warning))))
7134 (progn
7135 (message "Executing %s" cmd)
7136 (shell-command cmd))
7137 (error "Abort"))))
7138
7139 ((string= type "elisp")
7140 (let ((cmd path))
7141 (if (or (not org-confirm-elisp-link-function)
7142 (funcall org-confirm-elisp-link-function
7143 (format "Execute \"%s\" as elisp? "
7144 (org-add-props cmd nil
7145 'face 'org-warning))))
7146 (message "%s => %s" cmd
7147 (if (equal (string-to-char cmd) ?\()
7148 (eval (read cmd))
7149 (call-interactively (read cmd))))
7150 (error "Abort"))))
7151
7152 (t
7153 (browse-url-at-point))))))
7154 (move-marker org-open-link-marker nil)
7155 (run-hook-with-args 'org-follow-link-hook))
7156
7157 ;;;; Time estimates
7158
7159 (defun org-get-effort (&optional pom)
7160 "Get the effort estimate for the current entry."
7161 (org-entry-get pom org-effort-property))
7162
7163 ;;; File search
7164
7165 (defvar org-create-file-search-functions nil
7166 "List of functions to construct the right search string for a file link.
7167 These functions are called in turn with point at the location to
7168 which the link should point.
7169
7170 A function in the hook should first test if it would like to
7171 handle this file type, for example by checking the major-mode or
7172 the file extension. If it decides not to handle this file, it
7173 should just return nil to give other functions a chance. If it
7174 does handle the file, it must return the search string to be used
7175 when following the link. The search string will be part of the
7176 file link, given after a double colon, and `org-open-at-point'
7177 will automatically search for it. If special measures must be
7178 taken to make the search successful, another function should be
7179 added to the companion hook `org-execute-file-search-functions',
7180 which see.
7181
7182 A function in this hook may also use `setq' to set the variable
7183 `description' to provide a suggestion for the descriptive text to
7184 be used for this link when it gets inserted into an Org-mode
7185 buffer with \\[org-insert-link].")
7186
7187 (defvar org-execute-file-search-functions nil
7188 "List of functions to execute a file search triggered by a link.
7189
7190 Functions added to this hook must accept a single argument, the
7191 search string that was part of the file link, the part after the
7192 double colon. The function must first check if it would like to
7193 handle this search, for example by checking the major-mode or the
7194 file extension. If it decides not to handle this search, it
7195 should just return nil to give other functions a chance. If it
7196 does handle the search, it must return a non-nil value to keep
7197 other functions from trying.
7198
7199 Each function can access the current prefix argument through the
7200 variable `current-prefix-argument'. Note that a single prefix is
7201 used to force opening a link in Emacs, so it may be good to only
7202 use a numeric or double prefix to guide the search function.
7203
7204 In case this is needed, a function in this hook can also restore
7205 the window configuration before `org-open-at-point' was called using:
7206
7207 (set-window-configuration org-window-config-before-follow-link)")
7208
7209 (defun org-link-search (s &optional type avoid-pos)
7210 "Search for a link search option.
7211 If S is surrounded by forward slashes, it is interpreted as a
7212 regular expression. In org-mode files, this will create an `org-occur'
7213 sparse tree. In ordinary files, `occur' will be used to list matches.
7214 If the current buffer is in `dired-mode', grep will be used to search
7215 in all files. If AVOID-POS is given, ignore matches near that position."
7216 (let ((case-fold-search t)
7217 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7218 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7219 (append '(("") (" ") ("\t") ("\n"))
7220 org-emphasis-alist)
7221 "\\|") "\\)"))
7222 (pos (point))
7223 (pre nil) (post nil)
7224 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7225 (cond
7226 ;; First check if there are any special
7227 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7228 ;; Now try the builtin stuff
7229 ((save-excursion
7230 (goto-char (point-min))
7231 (and
7232 (re-search-forward
7233 (concat "<<" (regexp-quote s0) ">>") nil t)
7234 (setq type 'dedicated
7235 pos (match-beginning 0))))
7236 ;; There is an exact target for this
7237 (goto-char pos))
7238 ((and (string-match "^(\\(.*\\))$" s0)
7239 (save-excursion
7240 (goto-char (point-min))
7241 (and
7242 (re-search-forward
7243 (concat "[^[]" (regexp-quote
7244 (format org-coderef-label-format
7245 (match-string 1 s0))))
7246 nil t)
7247 (setq type 'dedicated
7248 pos (1+ (match-beginning 0))))))
7249 ;; There is a coderef target for this
7250 (goto-char pos))
7251 ((string-match "^/\\(.*\\)/$" s)
7252 ;; A regular expression
7253 (cond
7254 ((org-mode-p)
7255 (org-occur (match-string 1 s)))
7256 ;;((eq major-mode 'dired-mode)
7257 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7258 (t (org-do-occur (match-string 1 s)))))
7259 (t
7260 ;; A normal search strings
7261 (when (equal (string-to-char s) ?*)
7262 ;; Anchor on headlines, post may include tags.
7263 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7264 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7265 s (substring s 1)))
7266 (remove-text-properties
7267 0 (length s)
7268 '(face nil mouse-face nil keymap nil fontified nil) s)
7269 ;; Make a series of regular expressions to find a match
7270 (setq words (org-split-string s "[ \n\r\t]+")
7271
7272 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7273 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7274 "\\)" markers)
7275 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7276 re2a (concat "[ \t\r\n]" re2a_)
7277 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7278 re4 (concat "[^a-zA-Z_]" re4_)
7279
7280 re1 (concat pre re2 post)
7281 re3 (concat pre (if pre re4_ re4) post)
7282 re5 (concat pre ".*" re4)
7283 re2 (concat pre re2)
7284 re2a (concat pre (if pre re2a_ re2a))
7285 re4 (concat pre (if pre re4_ re4))
7286 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7287 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7288 re5 "\\)"
7289 ))
7290 (cond
7291 ((eq type 'org-occur) (org-occur reall))
7292 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7293 (t (goto-char (point-min))
7294 (setq type 'fuzzy)
7295 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7296 (org-search-not-self 1 re1 nil t)
7297 (org-search-not-self 1 re2 nil t)
7298 (org-search-not-self 1 re2a nil t)
7299 (org-search-not-self 1 re3 nil t)
7300 (org-search-not-self 1 re4 nil t)
7301 (org-search-not-self 1 re5 nil t)
7302 )
7303 (goto-char (match-beginning 1))
7304 (goto-char pos)
7305 (error "No match")))))
7306 (t
7307 ;; Normal string-search
7308 (goto-char (point-min))
7309 (if (search-forward s nil t)
7310 (goto-char (match-beginning 0))
7311 (error "No match"))))
7312 (and (org-mode-p) (org-show-context 'link-search))
7313 type))
7314
7315 (defun org-search-not-self (group &rest args)
7316 "Execute `re-search-forward', but only accept matches that do not
7317 enclose the position of `org-open-link-marker'."
7318 (let ((m org-open-link-marker))
7319 (catch 'exit
7320 (while (apply 're-search-forward args)
7321 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7322 (goto-char (match-end group))
7323 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7324 (> (match-beginning 0) (marker-position m))
7325 (< (match-end 0) (marker-position m)))
7326 (save-match-data
7327 (or (not (org-in-regexp
7328 org-bracket-link-analytic-regexp 1))
7329 (not (match-end 4)) ; no description
7330 (and (<= (match-beginning 4) (point))
7331 (>= (match-end 4) (point))))))
7332 (throw 'exit (point))))))))
7333
7334 (defun org-get-buffer-for-internal-link (buffer)
7335 "Return a buffer to be used for displaying the link target of internal links."
7336 (cond
7337 ((not org-display-internal-link-with-indirect-buffer)
7338 buffer)
7339 ((string-match "(Clone)$" (buffer-name buffer))
7340 (message "Buffer is already a clone, not making another one")
7341 ;; we also do not modify visibility in this case
7342 buffer)
7343 (t ; make a new indirect buffer for displaying the link
7344 (let* ((bn (buffer-name buffer))
7345 (ibn (concat bn "(Clone)"))
7346 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7347 (with-current-buffer ib (org-overview))
7348 ib))))
7349
7350 (defun org-do-occur (regexp &optional cleanup)
7351 "Call the Emacs command `occur'.
7352 If CLEANUP is non-nil, remove the printout of the regular expression
7353 in the *Occur* buffer. This is useful if the regex is long and not useful
7354 to read."
7355 (occur regexp)
7356 (when cleanup
7357 (let ((cwin (selected-window)) win beg end)
7358 (when (setq win (get-buffer-window "*Occur*"))
7359 (select-window win))
7360 (goto-char (point-min))
7361 (when (re-search-forward "match[a-z]+" nil t)
7362 (setq beg (match-end 0))
7363 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7364 (setq end (1- (match-beginning 0)))))
7365 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7366 (goto-char (point-min))
7367 (select-window cwin))))
7368
7369 ;;; The mark ring for links jumps
7370
7371 (defvar org-mark-ring nil
7372 "Mark ring for positions before jumps in Org-mode.")
7373 (defvar org-mark-ring-last-goto nil
7374 "Last position in the mark ring used to go back.")
7375 ;; Fill and close the ring
7376 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7377 (loop for i from 1 to org-mark-ring-length do
7378 (push (make-marker) org-mark-ring))
7379 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7380 org-mark-ring)
7381
7382 (defun org-mark-ring-push (&optional pos buffer)
7383 "Put the current position or POS into the mark ring and rotate it."
7384 (interactive)
7385 (setq pos (or pos (point)))
7386 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7387 (move-marker (car org-mark-ring)
7388 (or pos (point))
7389 (or buffer (current-buffer)))
7390 (message "%s"
7391 (substitute-command-keys
7392 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7393
7394 (defun org-mark-ring-goto (&optional n)
7395 "Jump to the previous position in the mark ring.
7396 With prefix arg N, jump back that many stored positions. When
7397 called several times in succession, walk through the entire ring.
7398 Org-mode commands jumping to a different position in the current file,
7399 or to another Org-mode file, automatically push the old position
7400 onto the ring."
7401 (interactive "p")
7402 (let (p m)
7403 (if (eq last-command this-command)
7404 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7405 (setq p org-mark-ring))
7406 (setq org-mark-ring-last-goto p)
7407 (setq m (car p))
7408 (switch-to-buffer (marker-buffer m))
7409 (goto-char m)
7410 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7411
7412 (defun org-remove-angle-brackets (s)
7413 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7414 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7415 s)
7416 (defun org-add-angle-brackets (s)
7417 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7418 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7419 s)
7420 (defun org-remove-double-quotes (s)
7421 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7422 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7423 s)
7424
7425 ;;; Following specific links
7426
7427 (defun org-follow-timestamp-link ()
7428 (cond
7429 ((org-at-date-range-p t)
7430 (let ((org-agenda-start-on-weekday)
7431 (t1 (match-string 1))
7432 (t2 (match-string 2)))
7433 (setq t1 (time-to-days (org-time-string-to-time t1))
7434 t2 (time-to-days (org-time-string-to-time t2)))
7435 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7436 ((org-at-timestamp-p t)
7437 (org-agenda-list nil (time-to-days (org-time-string-to-time
7438 (substring (match-string 1) 0 10)))
7439 1))
7440 (t (error "This should not happen"))))
7441
7442
7443 ;;; Following file links
7444 (defvar org-wait nil)
7445 (defun org-open-file (path &optional in-emacs line search)
7446 "Open the file at PATH.
7447 First, this expands any special file name abbreviations. Then the
7448 configuration variable `org-file-apps' is checked if it contains an
7449 entry for this file type, and if yes, the corresponding command is launched.
7450
7451 If no application is found, Emacs simply visits the file.
7452
7453 With optional prefix argument IN-EMACS, Emacs will visit the file.
7454 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7455 and o use an external application to visit the file.
7456
7457 Optional LINE specifies a line to go to, optional SEARCH a string to
7458 search for. If LINE or SEARCH is given, the file will always be
7459 opened in Emacs.
7460 If the file does not exist, an error is thrown."
7461 (setq in-emacs (or in-emacs line search))
7462 (let* ((file (if (equal path "")
7463 buffer-file-name
7464 (substitute-in-file-name (expand-file-name path))))
7465 (apps (append org-file-apps (org-default-apps)))
7466 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7467 (dirp (if remp nil (file-directory-p file)))
7468 (file (if (and dirp org-open-directory-means-index-dot-org)
7469 (concat (file-name-as-directory file) "index.org")
7470 file))
7471 (a-m-a-p (assq 'auto-mode apps))
7472 (dfile (downcase file))
7473 (old-buffer (current-buffer))
7474 (old-pos (point))
7475 (old-mode major-mode)
7476 ext cmd)
7477 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7478 (setq ext (match-string 1 dfile))
7479 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7480 (setq ext (match-string 1 dfile))))
7481 (cond
7482 ((equal in-emacs '(16))
7483 (setq cmd (cdr (assoc 'system apps))))
7484 (in-emacs (setq cmd 'emacs))
7485 (t
7486 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7487 (and dirp (cdr (assoc 'directory apps)))
7488 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7489 'string-match)
7490 (cdr (assoc ext apps))
7491 (cdr (assoc t apps))))))
7492 (when (eq cmd 'system)
7493 (setq cmd (cdr (assoc 'system apps))))
7494 (when (eq cmd 'default)
7495 (setq cmd (cdr (assoc t apps))))
7496 (when (eq cmd 'mailcap)
7497 (require 'mailcap)
7498 (mailcap-parse-mailcaps)
7499 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7500 (command (mailcap-mime-info mime-type)))
7501 (if (stringp command)
7502 (setq cmd command)
7503 (setq cmd 'emacs))))
7504 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7505 (not (file-exists-p file))
7506 (not org-open-non-existing-files))
7507 (error "No such file: %s" file))
7508 (cond
7509 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7510 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7511 (while (string-match "['\"]%s['\"]" cmd)
7512 (setq cmd (replace-match "%s" t t cmd)))
7513 (while (string-match "%s" cmd)
7514 (setq cmd (replace-match
7515 (save-match-data
7516 (shell-quote-argument
7517 (convert-standard-filename file)))
7518 t t cmd)))
7519 (save-window-excursion
7520 (start-process-shell-command cmd nil cmd)
7521 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7522 ))
7523 ((or (stringp cmd)
7524 (eq cmd 'emacs))
7525 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7526 (widen)
7527 (if line (goto-line line)
7528 (if search (org-link-search search))))
7529 ((consp cmd)
7530 (let ((file (convert-standard-filename file)))
7531 (eval cmd)))
7532 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7533 (and (org-mode-p) (eq old-mode 'org-mode)
7534 (or (not (equal old-buffer (current-buffer)))
7535 (not (equal old-pos (point))))
7536 (org-mark-ring-push old-pos old-buffer))))
7537
7538 (defun org-default-apps ()
7539 "Return the default applications for this operating system."
7540 (cond
7541 ((eq system-type 'darwin)
7542 org-file-apps-defaults-macosx)
7543 ((eq system-type 'windows-nt)
7544 org-file-apps-defaults-windowsnt)
7545 (t org-file-apps-defaults-gnu)))
7546
7547 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7548 "Convert extensions to regular expressions in the cars of LIST.
7549 Also, weed out any non-string entries, because the return value is used
7550 only for regexp matching.
7551 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7552 point to the symbol `emacs', indicating that the file should
7553 be opened in Emacs."
7554 (append
7555 (delq nil
7556 (mapcar (lambda (x)
7557 (if (not (stringp (car x)))
7558 nil
7559 (if (string-match "\\W" (car x))
7560 x
7561 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7562 list))
7563 (if add-auto-mode
7564 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7565
7566 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7567 (defun org-file-remote-p (file)
7568 "Test whether FILE specifies a location on a remote system.
7569 Return non-nil if the location is indeed remote.
7570
7571 For example, the filename \"/user@host:/foo\" specifies a location
7572 on the system \"/user@host:\"."
7573 (cond ((fboundp 'file-remote-p)
7574 (file-remote-p file))
7575 ((fboundp 'tramp-handle-file-remote-p)
7576 (tramp-handle-file-remote-p file))
7577 ((and (boundp 'ange-ftp-name-format)
7578 (string-match (car ange-ftp-name-format) file))
7579 t)
7580 (t nil)))
7581
7582
7583 ;;;; Refiling
7584
7585 (defun org-get-org-file ()
7586 "Read a filename, with default directory `org-directory'."
7587 (let ((default (or org-default-notes-file remember-data-file)))
7588 (read-file-name (format "File name [%s]: " default)
7589 (file-name-as-directory org-directory)
7590 default)))
7591
7592 (defun org-notes-order-reversed-p ()
7593 "Check if the current file should receive notes in reversed order."
7594 (cond
7595 ((not org-reverse-note-order) nil)
7596 ((eq t org-reverse-note-order) t)
7597 ((not (listp org-reverse-note-order)) nil)
7598 (t (catch 'exit
7599 (let ((all org-reverse-note-order)
7600 entry)
7601 (while (setq entry (pop all))
7602 (if (string-match (car entry) buffer-file-name)
7603 (throw 'exit (cdr entry))))
7604 nil)))))
7605
7606 (defvar org-refile-target-table nil
7607 "The list of refile targets, created by `org-refile'.")
7608
7609 (defvar org-agenda-new-buffers nil
7610 "Buffers created to visit agenda files.")
7611
7612 (defun org-get-refile-targets (&optional default-buffer)
7613 "Produce a table with refile targets."
7614 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7615 targets txt re files f desc descre fast-path-p level)
7616 (message "Getting targets...")
7617 (with-current-buffer (or default-buffer (current-buffer))
7618 (while (setq entry (pop entries))
7619 (setq files (car entry) desc (cdr entry))
7620 (setq fast-path-p nil)
7621 (cond
7622 ((null files) (setq files (list (current-buffer))))
7623 ((eq files 'org-agenda-files)
7624 (setq files (org-agenda-files 'unrestricted)))
7625 ((and (symbolp files) (fboundp files))
7626 (setq files (funcall files)))
7627 ((and (symbolp files) (boundp files))
7628 (setq files (symbol-value files))))
7629 (if (stringp files) (setq files (list files)))
7630 (cond
7631 ((eq (car desc) :tag)
7632 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7633 ((eq (car desc) :todo)
7634 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7635 ((eq (car desc) :regexp)
7636 (setq descre (cdr desc)))
7637 ((eq (car desc) :level)
7638 (setq descre (concat "^\\*\\{" (number-to-string
7639 (if org-odd-levels-only
7640 (1- (* 2 (cdr desc)))
7641 (cdr desc)))
7642 "\\}[ \t]")))
7643 ((eq (car desc) :maxlevel)
7644 (setq fast-path-p t)
7645 (setq descre (concat "^\\*\\{1," (number-to-string
7646 (if org-odd-levels-only
7647 (1- (* 2 (cdr desc)))
7648 (cdr desc)))
7649 "\\}[ \t]")))
7650 (t (error "Bad refiling target description %s" desc)))
7651 (while (setq f (pop files))
7652 (save-excursion
7653 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7654 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7655 (setq f (expand-file-name f))
7656 (save-excursion
7657 (save-restriction
7658 (widen)
7659 (goto-char (point-min))
7660 (while (re-search-forward descre nil t)
7661 (goto-char (point-at-bol))
7662 (when (looking-at org-complex-heading-regexp)
7663 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7664 txt (org-link-display-format (match-string 4))
7665 re (concat "^" (regexp-quote
7666 (buffer-substring (match-beginning 1)
7667 (match-end 4)))))
7668 (if (match-end 5) (setq re (concat re "[ \t]+"
7669 (regexp-quote
7670 (match-string 5)))))
7671 (setq re (concat re "[ \t]*$"))
7672 (when org-refile-use-outline-path
7673 (setq txt (mapconcat 'org-protect-slash
7674 (append
7675 (if (eq org-refile-use-outline-path 'file)
7676 (list (file-name-nondirectory
7677 (buffer-file-name (buffer-base-buffer))))
7678 (if (eq org-refile-use-outline-path 'full-file-path)
7679 (list (buffer-file-name (buffer-base-buffer)))))
7680 (org-get-outline-path fast-path-p level txt)
7681 (list txt))
7682 "/")))
7683 (push (list txt f re (point)) targets))
7684 (goto-char (point-at-eol))))))))
7685 (message "Getting targets...done")
7686 (nreverse targets))))
7687
7688 (defun org-protect-slash (s)
7689 (while (string-match "/" s)
7690 (setq s (replace-match "\\" t t s)))
7691 s)
7692
7693 (defvar org-olpa (make-vector 20 nil))
7694
7695 (defun org-get-outline-path (&optional fastp level heading)
7696 "Return the outline path to the current entry, as a list."
7697 (if fastp
7698 (progn
7699 (if (> level 19)
7700 (error "Outline path failure, more than 19 levels."))
7701 (loop for i from level upto 19 do
7702 (aset org-olpa i nil))
7703 (prog1
7704 (delq nil (append org-olpa nil))
7705 (aset org-olpa level heading)))
7706 (let (rtn)
7707 (save-excursion
7708 (while (org-up-heading-safe)
7709 (when (looking-at org-complex-heading-regexp)
7710 (push (org-match-string-no-properties 4) rtn)))
7711 rtn))))
7712
7713 (defvar org-refile-history nil
7714 "History for refiling operations.")
7715
7716 (defun org-refile (&optional goto default-buffer)
7717 "Move the entry at point to another heading.
7718 The list of target headings is compiled using the information in
7719 `org-refile-targets', which see. This list is created before each use
7720 and will therefore always be up-to-date.
7721
7722 At the target location, the entry is filed as a subitem of the target heading.
7723 Depending on `org-reverse-note-order', the new subitem will either be the
7724 first or the last subitem.
7725
7726 If there is an active region, all entries in that region will be moved.
7727 However, the region must fulfil the requirement that the first heading
7728 is the first one sets the top-level of the moved text - at most siblings
7729 below it are allowed.
7730
7731 With prefix arg GOTO, the command will only visit the target location,
7732 not actually move anything.
7733 With a double prefix `C-u C-u', go to the location where the last refiling
7734 operation has put the subtree."
7735 (interactive "P")
7736 (let* ((cbuf (current-buffer))
7737 (regionp (org-region-active-p))
7738 (region-start (and regionp (region-beginning)))
7739 (region-end (and regionp (region-end)))
7740 (region-length (and regionp (- region-end region-start)))
7741 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7742 pos it nbuf file re level reversed)
7743 (when regionp (goto-char region-start)
7744 (unless (org-kill-is-subtree-p
7745 (buffer-substring region-start region-end))
7746 (error "The region is not a (sequence of) subtree(s)")))
7747 (if (equal goto '(16))
7748 (org-refile-goto-last-stored)
7749 (when (setq it (org-refile-get-location
7750 (if goto "Goto: " "Refile to: ") default-buffer))
7751 (setq file (nth 1 it)
7752 re (nth 2 it)
7753 pos (nth 3 it))
7754 (if (and (equal (buffer-file-name) file)
7755 (if regionp
7756 (and (>= pos region-start)
7757 (<= pos region-end))
7758 (and (>= pos (point))
7759 (< pos (save-excursion
7760 (org-end-of-subtree t t))))))
7761 (error "Cannot refile to position inside the tree or region"))
7762
7763 (setq nbuf (or (find-buffer-visiting file)
7764 (find-file-noselect file)))
7765 (if goto
7766 (progn
7767 (switch-to-buffer nbuf)
7768 (goto-char pos)
7769 (org-show-context 'org-goto))
7770 (if regionp
7771 (progn
7772 (kill-new (buffer-substring region-start region-end))
7773 (org-save-markers-in-region region-start region-end))
7774 (org-copy-subtree 1 nil t))
7775 (save-excursion
7776 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7777 (find-file-noselect file))))
7778 (setq reversed (org-notes-order-reversed-p))
7779 (save-excursion
7780 (save-restriction
7781 (widen)
7782 (goto-char pos)
7783 (looking-at outline-regexp)
7784 (setq level (org-get-valid-level (funcall outline-level) 1))
7785 (goto-char
7786 (if reversed
7787 (or (outline-next-heading) (point-max))
7788 (or (save-excursion (outline-get-next-sibling))
7789 (org-end-of-subtree t t)
7790 (point-max))))
7791 (if (not (bolp)) (newline))
7792 (bookmark-set "org-refile-last-stored")
7793 (org-paste-subtree level))))
7794 (if regionp
7795 (delete-region (point) (+ (point) region-length))
7796 (org-cut-subtree))
7797 (setq org-markers-to-move nil)
7798 (message "Refiled to \"%s\"" (car it)))))))
7799
7800 (defun org-refile-goto-last-stored ()
7801 "Go to the location where the last refile was stored."
7802 (interactive)
7803 (bookmark-jump "org-refile-last-stored")
7804 (message "This is the location of the last refile"))
7805
7806 (defun org-refile-get-location (&optional prompt default-buffer)
7807 "Prompt the user for a refile location, using PROMPT."
7808 (let ((org-refile-targets org-refile-targets)
7809 (org-refile-use-outline-path org-refile-use-outline-path))
7810 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7811 (unless org-refile-target-table
7812 (error "No refile targets"))
7813 (let* ((cbuf (current-buffer))
7814 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7815 (cfunc (if (and org-refile-use-outline-path
7816 org-outline-path-complete-in-steps)
7817 'org-olpath-completing-read
7818 'org-ido-completing-read))
7819 (extra (if org-refile-use-outline-path "/" ""))
7820 (filename (and cfn (expand-file-name cfn)))
7821 (tbl (mapcar
7822 (lambda (x)
7823 (if (not (equal filename (nth 1 x)))
7824 (cons (concat (car x) extra " ("
7825 (file-name-nondirectory (nth 1 x)) ")")
7826 (cdr x))
7827 (cons (concat (car x) extra) (cdr x))))
7828 org-refile-target-table))
7829 (completion-ignore-case t))
7830 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7831 tbl)))
7832
7833 (defun org-olpath-completing-read (prompt collection &rest args)
7834 "Read an outline path like a file name."
7835 (let ((thetable collection))
7836 (apply
7837 'org-ido-completing-read prompt
7838 (lambda (string predicate &optional flag)
7839 (let (rtn r s f (l (length string)))
7840 (cond
7841 ((eq flag nil)
7842 ;; try completion
7843 (try-completion string thetable))
7844 ((eq flag t)
7845 ;; all-completions
7846 (setq rtn (all-completions string thetable predicate))
7847 (mapcar
7848 (lambda (x)
7849 (setq r (substring x l))
7850 (if (string-match " ([^)]*)$" x)
7851 (setq f (match-string 0 x))
7852 (setq f ""))
7853 (if (string-match "/" r)
7854 (concat string (substring r 0 (match-end 0)) f)
7855 x))
7856 rtn))
7857 ((eq flag 'lambda)
7858 ;; exact match?
7859 (assoc string thetable)))
7860 ))
7861 args)))
7862
7863 ;;;; Dynamic blocks
7864
7865 (defun org-find-dblock (name)
7866 "Find the first dynamic block with name NAME in the buffer.
7867 If not found, stay at current position and return nil."
7868 (let (pos)
7869 (save-excursion
7870 (goto-char (point-min))
7871 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7872 nil t)
7873 (match-beginning 0))))
7874 (if pos (goto-char pos))
7875 pos))
7876
7877 (defconst org-dblock-start-re
7878 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7879 "Matches the startline of a dynamic block, with parameters.")
7880
7881 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7882 "Matches the end of a dynamic block.")
7883
7884 (defun org-create-dblock (plist)
7885 "Create a dynamic block section, with parameters taken from PLIST.
7886 PLIST must contain a :name entry which is used as name of the block."
7887 (unless (bolp) (newline))
7888 (let ((name (plist-get plist :name)))
7889 (insert "#+BEGIN: " name)
7890 (while plist
7891 (if (eq (car plist) :name)
7892 (setq plist (cddr plist))
7893 (insert " " (prin1-to-string (pop plist)))))
7894 (insert "\n\n#+END:\n")
7895 (beginning-of-line -2)))
7896
7897 (defun org-prepare-dblock ()
7898 "Prepare dynamic block for refresh.
7899 This empties the block, puts the cursor at the insert position and returns
7900 the property list including an extra property :name with the block name."
7901 (unless (looking-at org-dblock-start-re)
7902 (error "Not at a dynamic block"))
7903 (let* ((begdel (1+ (match-end 0)))
7904 (name (org-no-properties (match-string 1)))
7905 (params (append (list :name name)
7906 (read (concat "(" (match-string 3) ")")))))
7907 (unless (re-search-forward org-dblock-end-re nil t)
7908 (error "Dynamic block not terminated"))
7909 (setq params
7910 (append params
7911 (list :content (buffer-substring
7912 begdel (match-beginning 0)))))
7913 (delete-region begdel (match-beginning 0))
7914 (goto-char begdel)
7915 (open-line 1)
7916 params))
7917
7918 (defun org-map-dblocks (&optional command)
7919 "Apply COMMAND to all dynamic blocks in the current buffer.
7920 If COMMAND is not given, use `org-update-dblock'."
7921 (let ((cmd (or command 'org-update-dblock))
7922 pos)
7923 (save-excursion
7924 (goto-char (point-min))
7925 (while (re-search-forward org-dblock-start-re nil t)
7926 (goto-char (setq pos (match-beginning 0)))
7927 (condition-case nil
7928 (funcall cmd)
7929 (error (message "Error during update of dynamic block")))
7930 (goto-char pos)
7931 (unless (re-search-forward org-dblock-end-re nil t)
7932 (error "Dynamic block not terminated"))))))
7933
7934 (defun org-dblock-update (&optional arg)
7935 "User command for updating dynamic blocks.
7936 Update the dynamic block at point. With prefix ARG, update all dynamic
7937 blocks in the buffer."
7938 (interactive "P")
7939 (if arg
7940 (org-update-all-dblocks)
7941 (or (looking-at org-dblock-start-re)
7942 (org-beginning-of-dblock))
7943 (org-update-dblock)))
7944
7945 (defun org-update-dblock ()
7946 "Update the dynamic block at point
7947 This means to empty the block, parse for parameters and then call
7948 the correct writing function."
7949 (save-window-excursion
7950 (let* ((pos (point))
7951 (line (org-current-line))
7952 (params (org-prepare-dblock))
7953 (name (plist-get params :name))
7954 (cmd (intern (concat "org-dblock-write:" name))))
7955 (message "Updating dynamic block `%s' at line %d..." name line)
7956 (funcall cmd params)
7957 (message "Updating dynamic block `%s' at line %d...done" name line)
7958 (goto-char pos))))
7959
7960 (defun org-beginning-of-dblock ()
7961 "Find the beginning of the dynamic block at point.
7962 Error if there is no such block at point."
7963 (let ((pos (point))
7964 beg)
7965 (end-of-line 1)
7966 (if (and (re-search-backward org-dblock-start-re nil t)
7967 (setq beg (match-beginning 0))
7968 (re-search-forward org-dblock-end-re nil t)
7969 (> (match-end 0) pos))
7970 (goto-char beg)
7971 (goto-char pos)
7972 (error "Not in a dynamic block"))))
7973
7974 (defun org-update-all-dblocks ()
7975 "Update all dynamic blocks in the buffer.
7976 This function can be used in a hook."
7977 (when (org-mode-p)
7978 (org-map-dblocks 'org-update-dblock)))
7979
7980
7981 ;;;; Completion
7982
7983 (defconst org-additional-option-like-keywords
7984 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7985 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7986 "BEGIN_EXAMPLE" "END_EXAMPLE"
7987 "BEGIN_QUOTE" "END_QUOTE"
7988 "BEGIN_VERSE" "END_VERSE"
7989 "BEGIN_SRC" "END_SRC"
7990 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
7991
7992 (defcustom org-structure-template-alist
7993 '(
7994 ("s" "#+begin_src ?\n\n#+end_src"
7995 "<src lang=\"?\">\n\n</src>")
7996 ("e" "#+begin_example\n?\n#+end_example"
7997 "<example>\n?\n</example>")
7998 ("q" "#+begin_quote\n?\n#+end_quote"
7999 "<quote>\n?\n</quote>")
8000 ("v" "#+begin_verse\n?\n#+end_verse"
8001 "<verse>\n?\n/verse>")
8002 ("l" "#+begin_latex\n?\n#+end_latex"
8003 "<literal style=\"latex\">\n?\n</literal>")
8004 ("L" "#+latex: "
8005 "<literal style=\"latex\">?</literal>")
8006 ("h" "#+begin_html\n?\n#+end_html"
8007 "<literal style=\"html\">\n?\n</literal>")
8008 ("H" "#+html: "
8009 "<literal style=\"html\">?</literal>")
8010 ("a" "#+begin_ascii\n?\n#+end_ascii")
8011 ("A" "#+ascii: ")
8012 ("i" "#+include %file ?"
8013 "<include file=%file markup=\"?\">")
8014 )
8015 "Structure completion elements.
8016 This is a list of abbreviation keys and values. The value gets inserted
8017 it you type @samp{.} followed by the key and then the completion key,
8018 usually `M-TAB'. %file will be replaced by a file name after prompting
8019 for the file using completion.
8020 There are two templates for each key, the first uses the original Org syntax,
8021 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8022 the default when the /org-mtags.el/ module has been loaded. See also the
8023 variable `org-mtags-prefer-muse-templates'.
8024 This is an experimental feature, it is undecided if it is going to stay in."
8025 :group 'org-completion
8026 :type '(repeat
8027 (string :tag "Key")
8028 (string :tag "Template")
8029 (string :tag "Muse Template")))
8030
8031 (defun org-try-structure-completion ()
8032 "Try to complete a structure template before point.
8033 This looks for strings like \"<e\" on an otherwise empty line and
8034 expands them."
8035 (let ((l (buffer-substring (point-at-bol) (point)))
8036 a)
8037 (when (and (looking-at "[ \t]*$")
8038 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8039 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8040 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8041 (match-beginning 1)) a)
8042 t)))
8043
8044 (defun org-complete-expand-structure-template (start cell)
8045 "Expand a structure template."
8046 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8047 (rpl (nth (if musep 2 1) cell)))
8048 (delete-region start (point))
8049 (when (string-match "\\`#\\+" rpl)
8050 (cond
8051 ((bolp))
8052 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8053 (delete-region (point-at-bol) (point)))
8054 (t (newline))))
8055 (setq start (point))
8056 (if (string-match "%file" rpl)
8057 (setq rpl (replace-match
8058 (concat
8059 "\""
8060 (save-match-data
8061 (abbreviate-file-name (read-file-name "Include file: ")))
8062 "\"")
8063 t t rpl)))
8064 (insert rpl)
8065 (if (re-search-backward "\\?" start t) (delete-char 1))))
8066
8067
8068 (defun org-complete (&optional arg)
8069 "Perform completion on word at point.
8070 At the beginning of a headline, this completes TODO keywords as given in
8071 `org-todo-keywords'.
8072 If the current word is preceded by a backslash, completes the TeX symbols
8073 that are supported for HTML support.
8074 If the current word is preceded by \"#+\", completes special words for
8075 setting file options.
8076 In the line after \"#+STARTUP:, complete valid keywords.\"
8077 At all other locations, this simply calls the value of
8078 `org-completion-fallback-command'."
8079 (interactive "P")
8080 (org-without-partial-completion
8081 (catch 'exit
8082 (let* ((a nil)
8083 (end (point))
8084 (beg1 (save-excursion
8085 (skip-chars-backward (org-re "[:alnum:]_@"))
8086 (point)))
8087 (beg (save-excursion
8088 (skip-chars-backward "a-zA-Z0-9_:$")
8089 (point)))
8090 (confirm (lambda (x) (stringp (car x))))
8091 (searchhead (equal (char-before beg) ?*))
8092 (struct
8093 (when (and (member (char-before beg1) '(?. ?<))
8094 (setq a (assoc (buffer-substring beg1 (point))
8095 org-structure-template-alist)))
8096 (org-complete-expand-structure-template (1- beg1) a)
8097 (throw 'exit t)))
8098 (tag (and (equal (char-before beg1) ?:)
8099 (equal (char-after (point-at-bol)) ?*)))
8100 (prop (and (equal (char-before beg1) ?:)
8101 (not (equal (char-after (point-at-bol)) ?*))))
8102 (texp (equal (char-before beg) ?\\))
8103 (link (equal (char-before beg) ?\[))
8104 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8105 beg)
8106 "#+"))
8107 (startup (string-match "^#\\+STARTUP:.*"
8108 (buffer-substring (point-at-bol) (point))))
8109 (completion-ignore-case opt)
8110 (type nil)
8111 (tbl nil)
8112 (table (cond
8113 (opt
8114 (setq type :opt)
8115 (require 'org-exp)
8116 (append
8117 (mapcar
8118 (lambda (x)
8119 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8120 (cons (match-string 2 x) (match-string 1 x)))
8121 (org-split-string (org-get-current-options) "\n"))
8122 (mapcar 'list org-additional-option-like-keywords)))
8123 (startup
8124 (setq type :startup)
8125 org-startup-options)
8126 (link (append org-link-abbrev-alist-local
8127 org-link-abbrev-alist))
8128 (texp
8129 (setq type :tex)
8130 org-html-entities)
8131 ((string-match "\\`\\*+[ \t]+\\'"
8132 (buffer-substring (point-at-bol) beg))
8133 (setq type :todo)
8134 (mapcar 'list org-todo-keywords-1))
8135 (searchhead
8136 (setq type :searchhead)
8137 (save-excursion
8138 (goto-char (point-min))
8139 (while (re-search-forward org-todo-line-regexp nil t)
8140 (push (list
8141 (org-make-org-heading-search-string
8142 (match-string 3) t))
8143 tbl)))
8144 tbl)
8145 (tag (setq type :tag beg beg1)
8146 (or org-tag-alist (org-get-buffer-tags)))
8147 (prop (setq type :prop beg beg1)
8148 (mapcar 'list (org-buffer-property-keys nil t t)))
8149 (t (progn
8150 (call-interactively org-completion-fallback-command)
8151 (throw 'exit nil)))))
8152 (pattern (buffer-substring-no-properties beg end))
8153 (completion (try-completion pattern table confirm)))
8154 (cond ((eq completion t)
8155 (if (not (assoc (upcase pattern) table))
8156 (message "Already complete")
8157 (if (and (equal type :opt)
8158 (not (member (car (assoc (upcase pattern) table))
8159 org-additional-option-like-keywords)))
8160 (insert (substring (cdr (assoc (upcase pattern) table))
8161 (length pattern)))
8162 (if (memq type '(:tag :prop)) (insert ":")))))
8163 ((null completion)
8164 (message "Can't find completion for \"%s\"" pattern)
8165 (ding))
8166 ((not (string= pattern completion))
8167 (delete-region beg end)
8168 (if (string-match " +$" completion)
8169 (setq completion (replace-match "" t t completion)))
8170 (insert completion)
8171 (if (get-buffer-window "*Completions*")
8172 (delete-window (get-buffer-window "*Completions*")))
8173 (if (assoc completion table)
8174 (if (eq type :todo) (insert " ")
8175 (if (memq type '(:tag :prop)) (insert ":"))))
8176 (if (and (equal type :opt) (assoc completion table))
8177 (message "%s" (substitute-command-keys
8178 "Press \\[org-complete] again to insert example settings"))))
8179 (t
8180 (message "Making completion list...")
8181 (let ((list (sort (all-completions pattern table confirm)
8182 'string<)))
8183 (with-output-to-temp-buffer "*Completions*"
8184 (condition-case nil
8185 ;; Protection needed for XEmacs and emacs 21
8186 (display-completion-list list pattern)
8187 (error (display-completion-list list)))))
8188 (message "Making completion list...%s" "done")))))))
8189
8190 ;;;; TODO, DEADLINE, Comments
8191
8192 (defun org-toggle-comment ()
8193 "Change the COMMENT state of an entry."
8194 (interactive)
8195 (save-excursion
8196 (org-back-to-heading)
8197 (let (case-fold-search)
8198 (if (looking-at (concat outline-regexp
8199 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8200 (replace-match "" t t nil 1)
8201 (if (looking-at outline-regexp)
8202 (progn
8203 (goto-char (match-end 0))
8204 (insert org-comment-string " ")))))))
8205
8206 (defvar org-last-todo-state-is-todo nil
8207 "This is non-nil when the last TODO state change led to a TODO state.
8208 If the last change removed the TODO tag or switched to DONE, then
8209 this is nil.")
8210
8211 (defvar org-setting-tags nil) ; dynamically skipped
8212
8213 (defun org-parse-local-options (string var)
8214 "Parse STRING for startup setting relevant for variable VAR."
8215 (let ((rtn (symbol-value var))
8216 e opts)
8217 (save-match-data
8218 (if (or (not string) (not (string-match "\\S-" string)))
8219 rtn
8220 (setq opts (delq nil (mapcar (lambda (x)
8221 (setq e (assoc x org-startup-options))
8222 (if (eq (nth 1 e) var) e nil))
8223 (org-split-string string "[ \t]+"))))
8224 (if (not opts)
8225 rtn
8226 (setq rtn nil)
8227 (while (setq e (pop opts))
8228 (if (not (nth 3 e))
8229 (setq rtn (nth 2 e))
8230 (if (not (listp rtn)) (setq rtn nil))
8231 (push (nth 2 e) rtn)))
8232 rtn)))))
8233
8234 (defvar org-blocker-hook nil
8235 "Hook for functions that are allowed to block a state change.
8236
8237 Each function gets as its single argument a property list, see
8238 `org-trigger-hook' for more information about this list.
8239
8240 If any of the functions in this hook returns nil, the state change
8241 is blocked.")
8242
8243 (defvar org-trigger-hook nil
8244 "Hook for functions that are triggered by a state change.
8245
8246 Each function gets as its single argument a property list with at least
8247 the following elements:
8248
8249 (:type type-of-change :position pos-at-entry-start
8250 :from old-state :to new-state)
8251
8252 Depending on the type, more properties may be present.
8253
8254 This mechanism is currently implemented for:
8255
8256 TODO state changes
8257 ------------------
8258 :type todo-state-change
8259 :from previous state (keyword as a string), or nil
8260 :to new state (keyword as a string), or nil")
8261
8262 (defvar org-agenda-headline-snapshot-before-repeat)
8263 (defun org-todo (&optional arg)
8264 "Change the TODO state of an item.
8265 The state of an item is given by a keyword at the start of the heading,
8266 like
8267 *** TODO Write paper
8268 *** DONE Call mom
8269
8270 The different keywords are specified in the variable `org-todo-keywords'.
8271 By default the available states are \"TODO\" and \"DONE\".
8272 So for this example: when the item starts with TODO, it is changed to DONE.
8273 When it starts with DONE, the DONE is removed. And when neither TODO nor
8274 DONE are present, add TODO at the beginning of the heading.
8275
8276 With C-u prefix arg, use completion to determine the new state.
8277 With numeric prefix arg, switch to that state.
8278
8279 For calling through lisp, arg is also interpreted in the following way:
8280 'none -> empty state
8281 \"\"(empty string) -> switch to empty state
8282 'done -> switch to DONE
8283 'nextset -> switch to the next set of keywords
8284 'previousset -> switch to the previous set of keywords
8285 \"WAITING\" -> switch to the specified keyword, but only if it
8286 really is a member of `org-todo-keywords'."
8287 (interactive "P")
8288 (save-excursion
8289 (catch 'exit
8290 (org-back-to-heading)
8291 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8292 (or (looking-at (concat " +" org-todo-regexp " *"))
8293 (looking-at " *"))
8294 (let* ((match-data (match-data))
8295 (startpos (point-at-bol))
8296 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8297 (org-log-done org-log-done)
8298 (org-log-repeat org-log-repeat)
8299 (org-todo-log-states org-todo-log-states)
8300 (this (match-string 1))
8301 (hl-pos (match-beginning 0))
8302 (head (org-get-todo-sequence-head this))
8303 (ass (assoc head org-todo-kwd-alist))
8304 (interpret (nth 1 ass))
8305 (done-word (nth 3 ass))
8306 (final-done-word (nth 4 ass))
8307 (last-state (or this ""))
8308 (completion-ignore-case t)
8309 (member (member this org-todo-keywords-1))
8310 (tail (cdr member))
8311 (state (cond
8312 ((and org-todo-key-trigger
8313 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8314 (and (not arg) org-use-fast-todo-selection
8315 (not (eq org-use-fast-todo-selection 'prefix)))))
8316 ;; Use fast selection
8317 (org-fast-todo-selection))
8318 ((and (equal arg '(4))
8319 (or (not org-use-fast-todo-selection)
8320 (not org-todo-key-trigger)))
8321 ;; Read a state with completion
8322 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8323 org-todo-keywords-1)
8324 nil t))
8325 ((eq arg 'right)
8326 (if this
8327 (if tail (car tail) nil)
8328 (car org-todo-keywords-1)))
8329 ((eq arg 'left)
8330 (if (equal member org-todo-keywords-1)
8331 nil
8332 (if this
8333 (nth (- (length org-todo-keywords-1) (length tail) 2)
8334 org-todo-keywords-1)
8335 (org-last org-todo-keywords-1))))
8336 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8337 (setq arg nil))) ; hack to fall back to cycling
8338 (arg
8339 ;; user or caller requests a specific state
8340 (cond
8341 ((equal arg "") nil)
8342 ((eq arg 'none) nil)
8343 ((eq arg 'done) (or done-word (car org-done-keywords)))
8344 ((eq arg 'nextset)
8345 (or (car (cdr (member head org-todo-heads)))
8346 (car org-todo-heads)))
8347 ((eq arg 'previousset)
8348 (let ((org-todo-heads (reverse org-todo-heads)))
8349 (or (car (cdr (member head org-todo-heads)))
8350 (car org-todo-heads))))
8351 ((car (member arg org-todo-keywords-1)))
8352 ((nth (1- (prefix-numeric-value arg))
8353 org-todo-keywords-1))))
8354 ((null member) (or head (car org-todo-keywords-1)))
8355 ((equal this final-done-word) nil) ;; -> make empty
8356 ((null tail) nil) ;; -> first entry
8357 ((eq interpret 'sequence)
8358 (car tail))
8359 ((memq interpret '(type priority))
8360 (if (eq this-command last-command)
8361 (car tail)
8362 (if (> (length tail) 0)
8363 (or done-word (car org-done-keywords))
8364 nil)))
8365 (t nil)))
8366 (next (if state (concat " " state " ") " "))
8367 (change-plist (list :type 'todo-state-change :from this :to state
8368 :position startpos))
8369 dolog now-done-p)
8370 (when org-blocker-hook
8371 (unless (save-excursion
8372 (save-match-data
8373 (run-hook-with-args-until-failure
8374 'org-blocker-hook change-plist)))
8375 (if (interactive-p)
8376 (error "TODO state change from %s to %s blocked" this state)
8377 ;; fail silently
8378 (message "TODO state change from %s to %s blocked" this state)
8379 (throw 'exit nil))))
8380 (store-match-data match-data)
8381 (replace-match next t t)
8382 (unless (pos-visible-in-window-p hl-pos)
8383 (message "TODO state changed to %s" (org-trim next)))
8384 (unless head
8385 (setq head (org-get-todo-sequence-head state)
8386 ass (assoc head org-todo-kwd-alist)
8387 interpret (nth 1 ass)
8388 done-word (nth 3 ass)
8389 final-done-word (nth 4 ass)))
8390 (when (memq arg '(nextset previousset))
8391 (message "Keyword-Set %d/%d: %s"
8392 (- (length org-todo-sets) -1
8393 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8394 (length org-todo-sets)
8395 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8396 (setq org-last-todo-state-is-todo
8397 (not (member state org-done-keywords)))
8398 (setq now-done-p (and (member state org-done-keywords)
8399 (not (member this org-done-keywords))))
8400 (and logging (org-local-logging logging))
8401 (when (and (or org-todo-log-states org-log-done)
8402 (not (memq arg '(nextset previousset))))
8403 ;; we need to look at recording a time and note
8404 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8405 (nth 2 (assoc this org-todo-log-states))))
8406 (when (and state
8407 (member state org-not-done-keywords)
8408 (not (member this org-not-done-keywords)))
8409 ;; This is now a todo state and was not one before
8410 ;; If there was a CLOSED time stamp, get rid of it.
8411 (org-add-planning-info nil nil 'closed))
8412 (when (and now-done-p org-log-done)
8413 ;; It is now done, and it was not done before
8414 (org-add-planning-info 'closed (org-current-time))
8415 (if (and (not dolog) (eq 'note org-log-done))
8416 (org-add-log-setup 'done state 'findpos 'note)))
8417 (when (and state dolog)
8418 ;; This is a non-nil state, and we need to log it
8419 (org-add-log-setup 'state state 'findpos dolog)))
8420 ;; Fixup tag positioning
8421 (org-todo-trigger-tag-changes state)
8422 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8423 (when org-provide-todo-statistics
8424 (org-update-parent-todo-statistics))
8425 (run-hooks 'org-after-todo-state-change-hook)
8426 (if (and arg (not (member state org-done-keywords)))
8427 (setq head (org-get-todo-sequence-head state)))
8428 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8429 ;; Do we need to trigger a repeat?
8430 (when now-done-p
8431 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8432 ;; This is for the agenda, take a snapshot of the headline.
8433 (save-match-data
8434 (setq org-agenda-headline-snapshot-before-repeat
8435 (org-get-heading))))
8436 (org-auto-repeat-maybe state))
8437 ;; Fixup cursor location if close to the keyword
8438 (if (and (outline-on-heading-p)
8439 (not (bolp))
8440 (save-excursion (beginning-of-line 1)
8441 (looking-at org-todo-line-regexp))
8442 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8443 (progn
8444 (goto-char (or (match-end 2) (match-end 1)))
8445 (just-one-space)))
8446 (when org-trigger-hook
8447 (save-excursion
8448 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8449
8450 (defun org-update-parent-todo-statistics ()
8451 "Update any statistics cookie in the parent of the current headline."
8452 (interactive)
8453 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8454 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8455 (catch 'exit
8456 (save-excursion
8457 (setq level (org-up-heading-safe))
8458 (unless (and level
8459 (re-search-forward box-re (point-at-eol) t))
8460 (throw 'exit nil))
8461 (setq is-percent (match-end 2))
8462 (save-match-data
8463 (unless (outline-next-heading) (throw 'exit nil))
8464 (while (looking-at org-todo-line-regexp)
8465 (setq kwd (match-string 2))
8466 (and kwd (setq cnt-all (1+ cnt-all)))
8467 (and (member kwd org-done-keywords)
8468 (setq cnt-done (1+ cnt-done)))
8469 (condition-case nil
8470 (org-forward-same-level 1)
8471 (error (end-of-line 1)))))
8472 (replace-match
8473 (if is-percent
8474 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8475 (format "[%d/%d]" cnt-done cnt-all)))
8476 (run-hook-with-args 'org-after-todo-statistics-hook
8477 cnt-done (- cnt-all cnt-done))))))
8478
8479 (defvar org-after-todo-statistics-hook nil
8480 "Hook that is called after a TODO statistics cookie has been updated.
8481 Each function is called with two arguments: the number of not-done entries
8482 and the number of done entries.
8483
8484 For example, the following function, when added to this hook, will switch
8485 an entry to DONE when all children are done, and back to TODO when new
8486 entries are set to a TODO status. Note that this hook is only called
8487 when there is a statistics cookie in the headline!
8488
8489 (defun org-summary-todo (n-done n-not-done)
8490 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8491 (let (org-log-done org-log-states) ; turn off logging
8492 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8493 ")
8494
8495 (defun org-todo-trigger-tag-changes (state)
8496 "Apply the changes defined in `org-todo-state-tags-triggers'."
8497 (let ((l org-todo-state-tags-triggers)
8498 changes)
8499 (when (or (not state) (equal state ""))
8500 (setq changes (append changes (cdr (assoc "" l)))))
8501 (when (and (stringp state) (> (length state) 0))
8502 (setq changes (append changes (cdr (assoc state l)))))
8503 (when (member state org-not-done-keywords)
8504 (setq changes (append changes (cdr (assoc 'todo l)))))
8505 (when (member state org-done-keywords)
8506 (setq changes (append changes (cdr (assoc 'done l)))))
8507 (dolist (c changes)
8508 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8509
8510 (defun org-local-logging (value)
8511 "Get logging settings from a property VALUE."
8512 (let* (words w a)
8513 ;; directly set the variables, they are already local.
8514 (setq org-log-done nil
8515 org-log-repeat nil
8516 org-todo-log-states nil)
8517 (setq words (org-split-string value))
8518 (while (setq w (pop words))
8519 (cond
8520 ((setq a (assoc w org-startup-options))
8521 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8522 (set (nth 1 a) (nth 2 a))))
8523 ((setq a (org-extract-log-state-settings w))
8524 (and (member (car a) org-todo-keywords-1)
8525 (push a org-todo-log-states)))))))
8526
8527 (defun org-get-todo-sequence-head (kwd)
8528 "Return the head of the TODO sequence to which KWD belongs.
8529 If KWD is not set, check if there is a text property remembering the
8530 right sequence."
8531 (let (p)
8532 (cond
8533 ((not kwd)
8534 (or (get-text-property (point-at-bol) 'org-todo-head)
8535 (progn
8536 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8537 nil (point-at-eol)))
8538 (get-text-property p 'org-todo-head))))
8539 ((not (member kwd org-todo-keywords-1))
8540 (car org-todo-keywords-1))
8541 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8542
8543 (defun org-fast-todo-selection ()
8544 "Fast TODO keyword selection with single keys.
8545 Returns the new TODO keyword, or nil if no state change should occur."
8546 (let* ((fulltable org-todo-key-alist)
8547 (done-keywords org-done-keywords) ;; needed for the faces.
8548 (maxlen (apply 'max (mapcar
8549 (lambda (x)
8550 (if (stringp (car x)) (string-width (car x)) 0))
8551 fulltable)))
8552 (expert nil)
8553 (fwidth (+ maxlen 3 1 3))
8554 (ncol (/ (- (window-width) 4) fwidth))
8555 tg cnt e c tbl
8556 groups ingroup)
8557 (save-window-excursion
8558 (if expert
8559 (set-buffer (get-buffer-create " *Org todo*"))
8560 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8561 (erase-buffer)
8562 (org-set-local 'org-done-keywords done-keywords)
8563 (setq tbl fulltable cnt 0)
8564 (while (setq e (pop tbl))
8565 (cond
8566 ((equal e '(:startgroup))
8567 (push '() groups) (setq ingroup t)
8568 (when (not (= cnt 0))
8569 (setq cnt 0)
8570 (insert "\n"))
8571 (insert "{ "))
8572 ((equal e '(:endgroup))
8573 (setq ingroup nil cnt 0)
8574 (insert "}\n"))
8575 (t
8576 (setq tg (car e) c (cdr e))
8577 (if ingroup (push tg (car groups)))
8578 (setq tg (org-add-props tg nil 'face
8579 (org-get-todo-face tg)))
8580 (if (and (= cnt 0) (not ingroup)) (insert " "))
8581 (insert "[" c "] " tg (make-string
8582 (- fwidth 4 (length tg)) ?\ ))
8583 (when (= (setq cnt (1+ cnt)) ncol)
8584 (insert "\n")
8585 (if ingroup (insert " "))
8586 (setq cnt 0)))))
8587 (insert "\n")
8588 (goto-char (point-min))
8589 (if (not expert) (org-fit-window-to-buffer))
8590 (message "[a-z..]:Set [SPC]:clear")
8591 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8592 (cond
8593 ((or (= c ?\C-g)
8594 (and (= c ?q) (not (rassoc c fulltable))))
8595 (setq quit-flag t))
8596 ((= c ?\ ) nil)
8597 ((setq e (rassoc c fulltable) tg (car e))
8598 tg)
8599 (t (setq quit-flag t))))))
8600
8601 (defun org-entry-is-todo-p ()
8602 (member (org-get-todo-state) org-not-done-keywords))
8603
8604 (defun org-entry-is-done-p ()
8605 (member (org-get-todo-state) org-done-keywords))
8606
8607 (defun org-get-todo-state ()
8608 (save-excursion
8609 (org-back-to-heading t)
8610 (and (looking-at org-todo-line-regexp)
8611 (match-end 2)
8612 (match-string 2))))
8613
8614 (defun org-at-date-range-p (&optional inactive-ok)
8615 "Is the cursor inside a date range?"
8616 (interactive)
8617 (save-excursion
8618 (catch 'exit
8619 (let ((pos (point)))
8620 (skip-chars-backward "^[<\r\n")
8621 (skip-chars-backward "<[")
8622 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8623 (>= (match-end 0) pos)
8624 (throw 'exit t))
8625 (skip-chars-backward "^<[\r\n")
8626 (skip-chars-backward "<[")
8627 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8628 (>= (match-end 0) pos)
8629 (throw 'exit t)))
8630 nil)))
8631
8632 (defun org-get-repeat ()
8633 "Check if there is a deadline/schedule with repeater in this entry."
8634 (save-match-data
8635 (save-excursion
8636 (org-back-to-heading t)
8637 (if (re-search-forward
8638 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8639 (match-string 1)))))
8640
8641 (defvar org-last-changed-timestamp)
8642 (defvar org-last-inserted-timestamp)
8643 (defvar org-log-post-message)
8644 (defvar org-log-note-purpose)
8645 (defvar org-log-note-how)
8646 (defvar org-log-note-extra)
8647 (defun org-auto-repeat-maybe (done-word)
8648 "Check if the current headline contains a repeated deadline/schedule.
8649 If yes, set TODO state back to what it was and change the base date
8650 of repeating deadline/scheduled time stamps to new date.
8651 This function is run automatically after each state change to a DONE state."
8652 ;; last-state is dynamically scoped into this function
8653 (let* ((repeat (org-get-repeat))
8654 (aa (assoc last-state org-todo-kwd-alist))
8655 (interpret (nth 1 aa))
8656 (head (nth 2 aa))
8657 (whata '(("d" . day) ("m" . month) ("y" . year)))
8658 (msg "Entry repeats: ")
8659 (org-log-done nil)
8660 (org-todo-log-states nil)
8661 (nshiftmax 10) (nshift 0)
8662 re type n what ts mb0 time)
8663 (when repeat
8664 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8665 (org-todo (if (eq interpret 'type) last-state head))
8666 (when org-log-repeat
8667 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8668 (memq 'org-add-log-note post-command-hook))
8669 ;; OK, we are already setup for some record
8670 (if (eq org-log-repeat 'note)
8671 ;; make sure we take a note, not only a time stamp
8672 (setq org-log-note-how 'note))
8673 ;; Set up for taking a record
8674 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8675 'findpos org-log-repeat)))
8676 (org-back-to-heading t)
8677 (org-add-planning-info nil nil 'closed)
8678 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8679 org-deadline-time-regexp "\\)\\|\\("
8680 org-ts-regexp "\\)"))
8681 (while (re-search-forward
8682 re (save-excursion (outline-next-heading) (point)) t)
8683 (setq type (if (match-end 1) org-scheduled-string
8684 (if (match-end 3) org-deadline-string "Plain:"))
8685 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8686 mb0 (match-beginning 0))
8687 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8688 (setq n (string-to-number (match-string 2 ts))
8689 what (match-string 3 ts))
8690 (if (equal what "w") (setq n (* n 7) what "d"))
8691 ;; Preparation, see if we need to modify the start date for the change
8692 (when (match-end 1)
8693 (setq time (save-match-data (org-time-string-to-time ts)))
8694 (cond
8695 ((equal (match-string 1 ts) ".")
8696 ;; Shift starting date to today
8697 (org-timestamp-change
8698 (- (time-to-days (current-time)) (time-to-days time))
8699 'day))
8700 ((equal (match-string 1 ts) "+")
8701 (while (or (= nshift 0)
8702 (<= (time-to-days time) (time-to-days (current-time))))
8703 (when (= (incf nshift) nshiftmax)
8704 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8705 (error "Abort")))
8706 (org-timestamp-change n (cdr (assoc what whata)))
8707 (org-at-timestamp-p t)
8708 (setq ts (match-string 1))
8709 (setq time (save-match-data (org-time-string-to-time ts))))
8710 (org-timestamp-change (- n) (cdr (assoc what whata)))
8711 ;; rematch, so that we have everything in place for the real shift
8712 (org-at-timestamp-p t)
8713 (setq ts (match-string 1))
8714 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8715 (org-timestamp-change n (cdr (assoc what whata)))
8716 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8717 (setq org-log-post-message msg)
8718 (message "%s" msg))))
8719
8720 (defun org-show-todo-tree (arg)
8721 "Make a compact tree which shows all headlines marked with TODO.
8722 The tree will show the lines where the regexp matches, and all higher
8723 headlines above the match.
8724 With a \\[universal-argument] prefix, also show the DONE entries.
8725 With a numeric prefix N, construct a sparse tree for the Nth element
8726 of `org-todo-keywords-1'."
8727 (interactive "P")
8728 (let ((case-fold-search nil)
8729 (kwd-re
8730 (cond ((null arg) org-not-done-regexp)
8731 ((equal arg '(4))
8732 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8733 (mapcar 'list org-todo-keywords-1))))
8734 (concat "\\("
8735 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8736 "\\)\\>")))
8737 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8738 (regexp-quote (nth (1- (prefix-numeric-value arg))
8739 org-todo-keywords-1)))
8740 (t (error "Invalid prefix argument: %s" arg)))))
8741 (message "%d TODO entries found"
8742 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8743
8744 (defun org-deadline (&optional remove time)
8745 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8746 With argument REMOVE, remove any deadline from the item.
8747 When TIME is set, it should be an internal time specification, and the
8748 scheduling will use the corresponding date."
8749 (interactive "P")
8750 (if remove
8751 (progn
8752 (org-remove-timestamp-with-keyword org-deadline-string)
8753 (message "Item no longer has a deadline."))
8754 (if (org-get-repeat)
8755 (error "Cannot change deadline on task with repeater, please do that by hand")
8756 (org-add-planning-info 'deadline time 'closed)
8757 (message "Deadline on %s" org-last-inserted-timestamp))))
8758
8759 (defun org-schedule (&optional remove time)
8760 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8761 With argument REMOVE, remove any scheduling date from the item.
8762 When TIME is set, it should be an internal time specification, and the
8763 scheduling will use the corresponding date."
8764 (interactive "P")
8765 (if remove
8766 (progn
8767 (org-remove-timestamp-with-keyword org-scheduled-string)
8768 (message "Item is no longer scheduled."))
8769 (if (org-get-repeat)
8770 (error "Cannot reschedule task with repeater, please do that by hand")
8771 (org-add-planning-info 'scheduled time 'closed)
8772 (message "Scheduled to %s" org-last-inserted-timestamp))))
8773
8774 (defun org-remove-timestamp-with-keyword (keyword)
8775 "Remove all time stamps with KEYWORD in the current entry."
8776 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8777 beg)
8778 (save-excursion
8779 (org-back-to-heading t)
8780 (setq beg (point))
8781 (org-end-of-subtree t t)
8782 (while (re-search-backward re beg t)
8783 (replace-match "")
8784 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8785 (equal (char-before) ?\ ))
8786 (backward-delete-char 1)
8787 (if (string-match "^[ \t]*$" (buffer-substring
8788 (point-at-bol) (point-at-eol)))
8789 (delete-region (point-at-bol)
8790 (min (point-max) (1+ (point-at-eol))))))))))
8791
8792 (defun org-add-planning-info (what &optional time &rest remove)
8793 "Insert new timestamp with keyword in the line directly after the headline.
8794 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8795 If non is given, the user is prompted for a date.
8796 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8797 be removed."
8798 (interactive)
8799 (let (org-time-was-given org-end-time-was-given ts
8800 end default-time default-input)
8801
8802 (when (and (not time) (memq what '(scheduled deadline)))
8803 ;; Try to get a default date/time from existing timestamp
8804 (save-excursion
8805 (org-back-to-heading t)
8806 (setq end (save-excursion (outline-next-heading) (point)))
8807 (when (re-search-forward (if (eq what 'scheduled)
8808 org-scheduled-time-regexp
8809 org-deadline-time-regexp)
8810 end t)
8811 (setq ts (match-string 1)
8812 default-time
8813 (apply 'encode-time (org-parse-time-string ts))
8814 default-input (and ts (org-get-compact-tod ts))))))
8815 (when what
8816 ;; If necessary, get the time from the user
8817 (setq time (or time (org-read-date nil 'to-time nil nil
8818 default-time default-input))))
8819
8820 (when (and org-insert-labeled-timestamps-at-point
8821 (member what '(scheduled deadline)))
8822 (insert
8823 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8824 (org-insert-time-stamp time org-time-was-given
8825 nil nil nil (list org-end-time-was-given))
8826 (setq what nil))
8827 (save-excursion
8828 (save-restriction
8829 (let (col list elt ts buffer-invisibility-spec)
8830 (org-back-to-heading t)
8831 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8832 (goto-char (match-end 1))
8833 (setq col (current-column))
8834 (goto-char (match-end 0))
8835 (if (eobp) (insert "\n") (forward-char 1))
8836 (if (and (not (looking-at outline-regexp))
8837 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8838 "[^\r\n]*"))
8839 (not (equal (match-string 1) org-clock-string)))
8840 (narrow-to-region (match-beginning 0) (match-end 0))
8841 (insert-before-markers "\n")
8842 (backward-char 1)
8843 (narrow-to-region (point) (point))
8844 (and org-adapt-indentation (org-indent-to-column col)))
8845 ;; Check if we have to remove something.
8846 (setq list (cons what remove))
8847 (while list
8848 (setq elt (pop list))
8849 (goto-char (point-min))
8850 (when (or (and (eq elt 'scheduled)
8851 (re-search-forward org-scheduled-time-regexp nil t))
8852 (and (eq elt 'deadline)
8853 (re-search-forward org-deadline-time-regexp nil t))
8854 (and (eq elt 'closed)
8855 (re-search-forward org-closed-time-regexp nil t)))
8856 (replace-match "")
8857 (if (looking-at "--+<[^>]+>") (replace-match ""))
8858 (if (looking-at " +") (replace-match ""))))
8859 (goto-char (point-max))
8860 (when what
8861 (insert
8862 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8863 (cond ((eq what 'scheduled) org-scheduled-string)
8864 ((eq what 'deadline) org-deadline-string)
8865 ((eq what 'closed) org-closed-string))
8866 " ")
8867 (setq ts (org-insert-time-stamp
8868 time
8869 (or org-time-was-given
8870 (and (eq what 'closed) org-log-done-with-time))
8871 (eq what 'closed)
8872 nil nil (list org-end-time-was-given)))
8873 (end-of-line 1))
8874 (goto-char (point-min))
8875 (widen)
8876 (if (and (looking-at "[ \t]+\n")
8877 (equal (char-before) ?\n))
8878 (delete-region (1- (point)) (point-at-eol)))
8879 ts)))))
8880
8881 (defvar org-log-note-marker (make-marker))
8882 (defvar org-log-note-purpose nil)
8883 (defvar org-log-note-state nil)
8884 (defvar org-log-note-how nil)
8885 (defvar org-log-note-extra nil)
8886 (defvar org-log-note-window-configuration nil)
8887 (defvar org-log-note-return-to (make-marker))
8888 (defvar org-log-post-message nil
8889 "Message to be displayed after a log note has been stored.
8890 The auto-repeater uses this.")
8891
8892 (defun org-add-note ()
8893 "Add a note to the current entry.
8894 This is done in the same way as adding a state change note."
8895 (interactive)
8896 (org-add-log-setup 'note nil 'findpos nil))
8897
8898 (defvar org-property-end-re)
8899 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8900 "Set up the post command hook to take a note.
8901 If this is about to TODO state change, the new state is expected in STATE.
8902 When FINDPOS is non-nil, find the correct position for the note in
8903 the current entry. If not, assume that it can be inserted at point.
8904 HOW is an indicator what kind of note should be created.
8905 EXTRA is additional text that will be inserted into the notes buffer."
8906 (save-restriction
8907 (save-excursion
8908 (when findpos
8909 (org-back-to-heading t)
8910 (narrow-to-region (point) (save-excursion
8911 (outline-next-heading) (point)))
8912 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8913 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8914 "[^\r\n]*\\)?"))
8915 (goto-char (match-end 0))
8916 (when (and org-log-state-notes-insert-after-drawers
8917 (save-excursion
8918 (forward-line) (looking-at org-drawer-regexp)))
8919 (progn (forward-line)
8920 (while (looking-at org-drawer-regexp)
8921 (goto-char (match-end 0))
8922 (re-search-forward org-property-end-re (point-max) t)
8923 (forward-line))
8924 (forward-line -1)))
8925 (unless org-log-states-order-reversed
8926 (and (= (char-after) ?\n) (forward-char 1))
8927 (org-skip-over-state-notes)
8928 (skip-chars-backward " \t\n\r")))
8929 (move-marker org-log-note-marker (point))
8930 (setq org-log-note-purpose purpose
8931 org-log-note-state state
8932 org-log-note-how how
8933 org-log-note-extra extra)
8934 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8935
8936 (defun org-skip-over-state-notes ()
8937 "Skip past the list of State notes in an entry."
8938 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8939 (while (looking-at "[ \t]*- State")
8940 (condition-case nil
8941 (org-next-item)
8942 (error (org-end-of-item)))))
8943
8944 (defun org-add-log-note (&optional purpose)
8945 "Pop up a window for taking a note, and add this note later at point."
8946 (remove-hook 'post-command-hook 'org-add-log-note)
8947 (setq org-log-note-window-configuration (current-window-configuration))
8948 (delete-other-windows)
8949 (move-marker org-log-note-return-to (point))
8950 (switch-to-buffer (marker-buffer org-log-note-marker))
8951 (goto-char org-log-note-marker)
8952 (org-switch-to-buffer-other-window "*Org Note*")
8953 (erase-buffer)
8954 (if (memq org-log-note-how '(time state))
8955 (let (current-prefix-arg) (org-store-log-note))
8956 (let ((org-inhibit-startup t)) (org-mode))
8957 (insert (format "# Insert note for %s.
8958 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8959 (cond
8960 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8961 ((eq org-log-note-purpose 'done) "closed todo item")
8962 ((eq org-log-note-purpose 'state)
8963 (format "state change to \"%s\"" org-log-note-state))
8964 ((eq org-log-note-purpose 'note)
8965 "this entry")
8966 (t (error "This should not happen")))))
8967 (if org-log-note-extra (insert org-log-note-extra))
8968 (org-set-local 'org-finish-function 'org-store-log-note)))
8969
8970 (defvar org-note-abort nil) ; dynamically scoped
8971 (defun org-store-log-note ()
8972 "Finish taking a log note, and insert it to where it belongs."
8973 (let ((txt (buffer-string))
8974 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8975 lines ind)
8976 (kill-buffer (current-buffer))
8977 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8978 (setq txt (replace-match "" t t txt)))
8979 (if (string-match "\\s-+\\'" txt)
8980 (setq txt (replace-match "" t t txt)))
8981 (setq lines (org-split-string txt "\n"))
8982 (when (and note (string-match "\\S-" note))
8983 (setq note
8984 (org-replace-escapes
8985 note
8986 (list (cons "%u" (user-login-name))
8987 (cons "%U" user-full-name)
8988 (cons "%t" (format-time-string
8989 (org-time-stamp-format 'long 'inactive)
8990 (current-time)))
8991 (cons "%s" (if org-log-note-state
8992 (concat "\"" org-log-note-state "\"")
8993 "")))))
8994 (if lines (setq note (concat note " \\\\")))
8995 (push note lines))
8996 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8997 (when lines
8998 (save-excursion
8999 (set-buffer (marker-buffer org-log-note-marker))
9000 (save-excursion
9001 (goto-char org-log-note-marker)
9002 (move-marker org-log-note-marker nil)
9003 (end-of-line 1)
9004 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9005 (indent-relative nil)
9006 (insert "- " (pop lines))
9007 (org-indent-line-function)
9008 (beginning-of-line 1)
9009 (looking-at "[ \t]*")
9010 (setq ind (concat (match-string 0) " "))
9011 (end-of-line 1)
9012 (while lines (insert "\n" ind (pop lines)))))))
9013 (set-window-configuration org-log-note-window-configuration)
9014 (with-current-buffer (marker-buffer org-log-note-return-to)
9015 (goto-char org-log-note-return-to))
9016 (move-marker org-log-note-return-to nil)
9017 (and org-log-post-message (message "%s" org-log-post-message)))
9018
9019 (defun org-sparse-tree (&optional arg)
9020 "Create a sparse tree, prompt for the details.
9021 This command can create sparse trees. You first need to select the type
9022 of match used to create the tree:
9023
9024 t Show entries with a specific TODO keyword.
9025 T Show entries selected by a tags match.
9026 p Enter a property name and its value (both with completion on existing
9027 names/values) and show entries with that property.
9028 r Show entries matching a regular expression
9029 d Show deadlines due within `org-deadline-warning-days'."
9030 (interactive "P")
9031 (let (ans kwd value)
9032 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9033 (setq ans (read-char-exclusive))
9034 (cond
9035 ((equal ans ?d)
9036 (call-interactively 'org-check-deadlines))
9037 ((equal ans ?b)
9038 (call-interactively 'org-check-before-date))
9039 ((equal ans ?t)
9040 (org-show-todo-tree '(4)))
9041 ((equal ans ?T)
9042 (call-interactively 'org-tags-sparse-tree))
9043 ((member ans '(?p ?P))
9044 (setq kwd (org-ido-completing-read "Property: "
9045 (mapcar 'list (org-buffer-property-keys))))
9046 (setq value (org-ido-completing-read "Value: "
9047 (mapcar 'list (org-property-values kwd))))
9048 (unless (string-match "\\`{.*}\\'" value)
9049 (setq value (concat "\"" value "\"")))
9050 (org-tags-sparse-tree arg (concat kwd "=" value)))
9051 ((member ans '(?r ?R ?/))
9052 (call-interactively 'org-occur))
9053 (t (error "No such sparse tree command \"%c\"" ans)))))
9054
9055 (defvar org-occur-highlights nil
9056 "List of overlays used for occur matches.")
9057 (make-variable-buffer-local 'org-occur-highlights)
9058 (defvar org-occur-parameters nil
9059 "Parameters of the active org-occur calls.
9060 This is a list, each call to org-occur pushes as cons cell,
9061 containing the regular expression and the callback, onto the list.
9062 The list can contain several entries if `org-occur' has been called
9063 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9064 will only contain one set of parameters. When the highlights are
9065 removed (for example with `C-c C-c', or with the next edit (depending
9066 on `org-remove-highlights-with-change'), this variable is emptied
9067 as well.")
9068 (make-variable-buffer-local 'org-occur-parameters)
9069
9070 (defun org-occur (regexp &optional keep-previous callback)
9071 "Make a compact tree which shows all matches of REGEXP.
9072 The tree will show the lines where the regexp matches, and all higher
9073 headlines above the match. It will also show the heading after the match,
9074 to make sure editing the matching entry is easy.
9075 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9076 call to `org-occur' will be kept, to allow stacking of calls to this
9077 command.
9078 If CALLBACK is non-nil, it is a function which is called to confirm
9079 that the match should indeed be shown."
9080 (interactive "sRegexp: \nP")
9081 (unless keep-previous
9082 (org-remove-occur-highlights nil nil t))
9083 (push (cons regexp callback) org-occur-parameters)
9084 (let ((cnt 0))
9085 (save-excursion
9086 (goto-char (point-min))
9087 (if (or (not keep-previous) ; do not want to keep
9088 (not org-occur-highlights)) ; no previous matches
9089 ;; hide everything
9090 (org-overview))
9091 (while (re-search-forward regexp nil t)
9092 (when (or (not callback)
9093 (save-match-data (funcall callback)))
9094 (setq cnt (1+ cnt))
9095 (when org-highlight-sparse-tree-matches
9096 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9097 (org-show-context 'occur-tree))))
9098 (when org-remove-highlights-with-change
9099 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9100 nil 'local))
9101 (unless org-sparse-tree-open-archived-trees
9102 (org-hide-archived-subtrees (point-min) (point-max)))
9103 (run-hooks 'org-occur-hook)
9104 (if (interactive-p)
9105 (message "%d match(es) for regexp %s" cnt regexp))
9106 cnt))
9107
9108 (defun org-show-context (&optional key)
9109 "Make sure point and context and visible.
9110 How much context is shown depends upon the variables
9111 `org-show-hierarchy-above', `org-show-following-heading'. and
9112 `org-show-siblings'."
9113 (let ((heading-p (org-on-heading-p t))
9114 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9115 (following-p (org-get-alist-option org-show-following-heading key))
9116 (entry-p (org-get-alist-option org-show-entry-below key))
9117 (siblings-p (org-get-alist-option org-show-siblings key)))
9118 (catch 'exit
9119 ;; Show heading or entry text
9120 (if (and heading-p (not entry-p))
9121 (org-flag-heading nil) ; only show the heading
9122 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9123 (org-show-hidden-entry))) ; show entire entry
9124 (when following-p
9125 ;; Show next sibling, or heading below text
9126 (save-excursion
9127 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9128 (org-flag-heading nil))))
9129 (when siblings-p (org-show-siblings))
9130 (when hierarchy-p
9131 ;; show all higher headings, possibly with siblings
9132 (save-excursion
9133 (while (and (condition-case nil
9134 (progn (org-up-heading-all 1) t)
9135 (error nil))
9136 (not (bobp)))
9137 (org-flag-heading nil)
9138 (when siblings-p (org-show-siblings))))))))
9139
9140 (defun org-reveal (&optional siblings)
9141 "Show current entry, hierarchy above it, and the following headline.
9142 This can be used to show a consistent set of context around locations
9143 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9144 not t for the search context.
9145
9146 With optional argument SIBLINGS, on each level of the hierarchy all
9147 siblings are shown. This repairs the tree structure to what it would
9148 look like when opened with hierarchical calls to `org-cycle'."
9149 (interactive "P")
9150 (let ((org-show-hierarchy-above t)
9151 (org-show-following-heading t)
9152 (org-show-siblings (if siblings t org-show-siblings)))
9153 (org-show-context nil)))
9154
9155 (defun org-highlight-new-match (beg end)
9156 "Highlight from BEG to END and mark the highlight is an occur headline."
9157 (let ((ov (org-make-overlay beg end)))
9158 (org-overlay-put ov 'face 'secondary-selection)
9159 (push ov org-occur-highlights)))
9160
9161 (defun org-remove-occur-highlights (&optional beg end noremove)
9162 "Remove the occur highlights from the buffer.
9163 BEG and END are ignored. If NOREMOVE is nil, remove this function
9164 from the `before-change-functions' in the current buffer."
9165 (interactive)
9166 (unless org-inhibit-highlight-removal
9167 (mapc 'org-delete-overlay org-occur-highlights)
9168 (setq org-occur-highlights nil)
9169 (setq org-occur-parameters nil)
9170 (unless noremove
9171 (remove-hook 'before-change-functions
9172 'org-remove-occur-highlights 'local))))
9173
9174 ;;;; Priorities
9175
9176 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9177 "Regular expression matching the priority indicator.")
9178
9179 (defvar org-remove-priority-next-time nil)
9180
9181 (defun org-priority-up ()
9182 "Increase the priority of the current item."
9183 (interactive)
9184 (org-priority 'up))
9185
9186 (defun org-priority-down ()
9187 "Decrease the priority of the current item."
9188 (interactive)
9189 (org-priority 'down))
9190
9191 (defun org-priority (&optional action)
9192 "Change the priority of an item by ARG.
9193 ACTION can be `set', `up', `down', or a character."
9194 (interactive)
9195 (setq action (or action 'set))
9196 (let (current new news have remove)
9197 (save-excursion
9198 (org-back-to-heading)
9199 (if (looking-at org-priority-regexp)
9200 (setq current (string-to-char (match-string 2))
9201 have t)
9202 (setq current org-default-priority))
9203 (cond
9204 ((or (eq action 'set)
9205 (if (featurep 'xemacs) (characterp action) (integerp action)))
9206 (if (not (eq action 'set))
9207 (setq new action)
9208 (message "Priority %c-%c, SPC to remove: "
9209 org-highest-priority org-lowest-priority)
9210 (setq new (read-char-exclusive)))
9211 (if (and (= (upcase org-highest-priority) org-highest-priority)
9212 (= (upcase org-lowest-priority) org-lowest-priority))
9213 (setq new (upcase new)))
9214 (cond ((equal new ?\ ) (setq remove t))
9215 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9216 (error "Priority must be between `%c' and `%c'"
9217 org-highest-priority org-lowest-priority))))
9218 ((eq action 'up)
9219 (if (and (not have) (eq last-command this-command))
9220 (setq new org-lowest-priority)
9221 (setq new (if (and org-priority-start-cycle-with-default (not have))
9222 org-default-priority (1- current)))))
9223 ((eq action 'down)
9224 (if (and (not have) (eq last-command this-command))
9225 (setq new org-highest-priority)
9226 (setq new (if (and org-priority-start-cycle-with-default (not have))
9227 org-default-priority (1+ current)))))
9228 (t (error "Invalid action")))
9229 (if (or (< (upcase new) org-highest-priority)
9230 (> (upcase new) org-lowest-priority))
9231 (setq remove t))
9232 (setq news (format "%c" new))
9233 (if have
9234 (if remove
9235 (replace-match "" t t nil 1)
9236 (replace-match news t t nil 2))
9237 (if remove
9238 (error "No priority cookie found in line")
9239 (looking-at org-todo-line-regexp)
9240 (if (match-end 2)
9241 (progn
9242 (goto-char (match-end 2))
9243 (insert " [#" news "]"))
9244 (goto-char (match-beginning 3))
9245 (insert "[#" news "] ")))))
9246 (org-preserve-lc (org-set-tags nil 'align))
9247 (if remove
9248 (message "Priority removed")
9249 (message "Priority of current item set to %s" news))))
9250
9251
9252 (defun org-get-priority (s)
9253 "Find priority cookie and return priority."
9254 (save-match-data
9255 (if (not (string-match org-priority-regexp s))
9256 (* 1000 (- org-lowest-priority org-default-priority))
9257 (* 1000 (- org-lowest-priority
9258 (string-to-char (match-string 2 s)))))))
9259
9260 ;;;; Tags
9261
9262 (defvar org-agenda-archives-mode)
9263 (defun org-scan-tags (action matcher &optional todo-only)
9264 "Scan headline tags with inheritance and produce output ACTION.
9265
9266 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9267 or `agenda' to produce an entry list for an agenda view. It can also be
9268 a Lisp form or a function that should be called at each matched headline, in
9269 this case the return value is a list of all return values from these calls.
9270
9271 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9272 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9273 only lines with a TODO keyword are included in the output."
9274 (require 'org-agenda)
9275 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9276 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9277 (org-re
9278 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9279 (props (list 'face 'default
9280 'done-face 'org-done
9281 'undone-face 'default
9282 'mouse-face 'highlight
9283 'org-not-done-regexp org-not-done-regexp
9284 'org-todo-regexp org-todo-regexp
9285 'keymap org-agenda-keymap
9286 'help-echo
9287 (format "mouse-2 or RET jump to org file %s"
9288 (abbreviate-file-name
9289 (or (buffer-file-name (buffer-base-buffer))
9290 (buffer-name (buffer-base-buffer)))))))
9291 (case-fold-search nil)
9292 lspos tags tags-list
9293 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9294 (llast 0) rtn rtn1 level category i txt
9295 todo marker entry priority)
9296 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9297 (setq action (list 'lambda nil action)))
9298 (save-excursion
9299 (goto-char (point-min))
9300 (when (eq action 'sparse-tree)
9301 (org-overview)
9302 (org-remove-occur-highlights))
9303 (while (re-search-forward re nil t)
9304 (catch :skip
9305 (setq todo (if (match-end 1) (match-string 2))
9306 tags (if (match-end 4) (match-string 4)))
9307 (goto-char (setq lspos (1+ (match-beginning 0))))
9308 (setq level (org-reduced-level (funcall outline-level))
9309 category (org-get-category))
9310 (setq i llast llast level)
9311 ;; remove tag lists from same and sublevels
9312 (while (>= i level)
9313 (when (setq entry (assoc i tags-alist))
9314 (setq tags-alist (delete entry tags-alist)))
9315 (setq i (1- i)))
9316 ;; add the next tags
9317 (when tags
9318 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9319 tags-alist
9320 (cons (cons level tags) tags-alist)))
9321 ;; compile tags for current headline
9322 (setq tags-list
9323 (if org-use-tag-inheritance
9324 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9325 tags))
9326 (when org-use-tag-inheritance
9327 (setcdr (car tags-alist)
9328 (mapcar (lambda (x)
9329 (setq x (copy-sequence x))
9330 (org-add-prop-inherited x))
9331 (cdar tags-alist))))
9332 (when (and tags org-use-tag-inheritance
9333 (not (eq t org-use-tag-inheritance)))
9334 ;; selective inheritance, remove uninherited ones
9335 (setcdr (car tags-alist)
9336 (org-remove-uniherited-tags (cdar tags-alist))))
9337 (when (and (or (not todo-only)
9338 (and (member todo org-not-done-keywords)
9339 (or (not org-agenda-tags-todo-honor-ignore-options)
9340 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9341 (let ((case-fold-search t)) (eval matcher))
9342 (or
9343 (not (member org-archive-tag tags-list))
9344 ;; we have an archive tag, should we use this anyway?
9345 (or (not org-agenda-skip-archived-trees)
9346 (and (eq action 'agenda) org-agenda-archives-mode))))
9347 (unless (eq action 'sparse-tree) (org-agenda-skip))
9348
9349 ;; select this headline
9350
9351 (cond
9352 ((eq action 'sparse-tree)
9353 (and org-highlight-sparse-tree-matches
9354 (org-get-heading) (match-end 0)
9355 (org-highlight-new-match
9356 (match-beginning 0) (match-beginning 1)))
9357 (org-show-context 'tags-tree))
9358 ((eq action 'agenda)
9359 (setq txt (org-format-agenda-item
9360 ""
9361 (concat
9362 (if org-tags-match-list-sublevels
9363 (make-string (1- level) ?.) "")
9364 (org-get-heading))
9365 category (org-get-tags-at))
9366 priority (org-get-priority txt))
9367 (goto-char lspos)
9368 (setq marker (org-agenda-new-marker))
9369 (org-add-props txt props
9370 'org-marker marker 'org-hd-marker marker 'org-category category
9371 'priority priority 'type "tagsmatch")
9372 (push txt rtn))
9373 ((functionp action)
9374 (save-excursion
9375 (setq rtn1 (funcall action))
9376 (push rtn1 rtn))
9377 (goto-char (point-at-eol)))
9378 (t (error "Invalid action")))
9379
9380 ;; if we are to skip sublevels, jump to end of subtree
9381 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9382 (when (and (eq action 'sparse-tree)
9383 (not org-sparse-tree-open-archived-trees))
9384 (org-hide-archived-subtrees (point-min) (point-max)))
9385 (nreverse rtn)))
9386
9387 (defun org-remove-uniherited-tags (tags)
9388 "Remove all tags that are not inherited from the list TAGS."
9389 (cond
9390 ((eq org-use-tag-inheritance t)
9391 (if org-tags-exclude-from-inheritance
9392 (org-delete-all org-tags-exclude-from-inheritance tags)
9393 tags))
9394 ((not org-use-tag-inheritance) nil)
9395 ((stringp org-use-tag-inheritance)
9396 (delq nil (mapcar
9397 (lambda (x)
9398 (if (and (string-match org-use-tag-inheritance x)
9399 (not (member x org-tags-exclude-from-inheritance)))
9400 x nil))
9401 tags)))
9402 ((listp org-use-tag-inheritance)
9403 (delq nil (mapcar
9404 (lambda (x)
9405 (if (member x org-use-tag-inheritance) x nil))
9406 tags)))))
9407
9408 (defvar todo-only) ;; dynamically scoped
9409
9410 (defun org-tags-sparse-tree (&optional todo-only match)
9411 "Create a sparse tree according to tags string MATCH.
9412 MATCH can contain positive and negative selection of tags, like
9413 \"+WORK+URGENT-WITHBOSS\".
9414 If optional argument TODO-ONLY is non-nil, only select lines that are
9415 also TODO lines."
9416 (interactive "P")
9417 (org-prepare-agenda-buffers (list (current-buffer)))
9418 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9419
9420 (defvar org-cached-props nil)
9421 (defun org-cached-entry-get (pom property)
9422 (if (or (eq t org-use-property-inheritance)
9423 (and (stringp org-use-property-inheritance)
9424 (string-match org-use-property-inheritance property))
9425 (and (listp org-use-property-inheritance)
9426 (member property org-use-property-inheritance)))
9427 ;; Caching is not possible, check it directly
9428 (org-entry-get pom property 'inherit)
9429 ;; Get all properties, so that we can do complicated checks easily
9430 (cdr (assoc property (or org-cached-props
9431 (setq org-cached-props
9432 (org-entry-properties pom)))))))
9433
9434 (defun org-global-tags-completion-table (&optional files)
9435 "Return the list of all tags in all agenda buffer/files."
9436 (save-excursion
9437 (org-uniquify
9438 (delq nil
9439 (apply 'append
9440 (mapcar
9441 (lambda (file)
9442 (set-buffer (find-file-noselect file))
9443 (append (org-get-buffer-tags)
9444 (mapcar (lambda (x) (if (stringp (car-safe x))
9445 (list (car-safe x)) nil))
9446 org-tag-alist)))
9447 (if (and files (car files))
9448 files
9449 (org-agenda-files))))))))
9450
9451 (defun org-make-tags-matcher (match)
9452 "Create the TAGS//TODO matcher form for the selection string MATCH."
9453 ;; todo-only is scoped dynamically into this function, and the function
9454 ;; may change it if the matcher asks for it.
9455 (unless match
9456 ;; Get a new match request, with completion
9457 (let ((org-last-tags-completion-table
9458 (org-global-tags-completion-table)))
9459 (setq match (org-completing-read
9460 "Match: " 'org-tags-completion-function nil nil nil
9461 'org-tags-history))))
9462
9463 ;; Parse the string and create a lisp form
9464 (let ((match0 match)
9465 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9466 minus tag mm
9467 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9468 orterms term orlist re-p str-p level-p level-op time-p
9469 prop-p pn pv po cat-p gv rest)
9470 (if (string-match "/+" match)
9471 ;; match contains also a todo-matching request
9472 (progn
9473 (setq tagsmatch (substring match 0 (match-beginning 0))
9474 todomatch (substring match (match-end 0)))
9475 (if (string-match "^!" todomatch)
9476 (setq todo-only t todomatch (substring todomatch 1)))
9477 (if (string-match "^\\s-*$" todomatch)
9478 (setq todomatch nil)))
9479 ;; only matching tags
9480 (setq tagsmatch match todomatch nil))
9481
9482 ;; Make the tags matcher
9483 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9484 (setq tagsmatcher t)
9485 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9486 (while (setq term (pop orterms))
9487 (while (and (equal (substring term -1) "\\") orterms)
9488 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9489 (while (string-match re term)
9490 (setq rest (substring term (match-end 0))
9491 minus (and (match-end 1)
9492 (equal (match-string 1 term) "-"))
9493 tag (match-string 2 term)
9494 re-p (equal (string-to-char tag) ?{)
9495 level-p (match-end 4)
9496 prop-p (match-end 5)
9497 mm (cond
9498 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9499 (level-p
9500 (setq level-op (org-op-to-function (match-string 3 term)))
9501 `(,level-op level ,(string-to-number
9502 (match-string 4 term))))
9503 (prop-p
9504 (setq pn (match-string 5 term)
9505 po (match-string 6 term)
9506 pv (match-string 7 term)
9507 cat-p (equal pn "CATEGORY")
9508 re-p (equal (string-to-char pv) ?{)
9509 str-p (equal (string-to-char pv) ?\")
9510 time-p (save-match-data
9511 (string-match "^\"[[<].*[]>]\"$" pv))
9512 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9513 (if time-p (setq pv (org-matcher-time pv)))
9514 (setq po (org-op-to-function po (if time-p 'time str-p)))
9515 (cond
9516 ((equal pn "CATEGORY")
9517 (setq gv '(get-text-property (point) 'org-category)))
9518 ((equal pn "TODO")
9519 (setq gv 'todo))
9520 (t
9521 (setq gv `(org-cached-entry-get nil ,pn))))
9522 (if re-p
9523 (if (eq po 'org<>)
9524 `(not (string-match ,pv (or ,gv "")))
9525 `(string-match ,pv (or ,gv "")))
9526 (if str-p
9527 `(,po (or ,gv "") ,pv)
9528 `(,po (string-to-number (or ,gv ""))
9529 ,(string-to-number pv) ))))
9530 (t `(member ,(downcase tag) tags-list)))
9531 mm (if minus (list 'not mm) mm)
9532 term rest)
9533 (push mm tagsmatcher))
9534 (push (if (> (length tagsmatcher) 1)
9535 (cons 'and tagsmatcher)
9536 (car tagsmatcher))
9537 orlist)
9538 (setq tagsmatcher nil))
9539 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9540 (setq tagsmatcher
9541 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9542 ;; Make the todo matcher
9543 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9544 (setq todomatcher t)
9545 (setq orterms (org-split-string todomatch "|") orlist nil)
9546 (while (setq term (pop orterms))
9547 (while (string-match re term)
9548 (setq minus (and (match-end 1)
9549 (equal (match-string 1 term) "-"))
9550 kwd (match-string 2 term)
9551 re-p (equal (string-to-char kwd) ?{)
9552 term (substring term (match-end 0))
9553 mm (if re-p
9554 `(string-match ,(substring kwd 1 -1) todo)
9555 (list 'equal 'todo kwd))
9556 mm (if minus (list 'not mm) mm))
9557 (push mm todomatcher))
9558 (push (if (> (length todomatcher) 1)
9559 (cons 'and todomatcher)
9560 (car todomatcher))
9561 orlist)
9562 (setq todomatcher nil))
9563 (setq todomatcher (if (> (length orlist) 1)
9564 (cons 'or orlist) (car orlist))))
9565
9566 ;; Return the string and lisp forms of the matcher
9567 (setq matcher (if todomatcher
9568 (list 'and tagsmatcher todomatcher)
9569 tagsmatcher))
9570 (cons match0 matcher)))
9571
9572 (defun org-op-to-function (op &optional stringp)
9573 "Turn an operator into the appropriate function."
9574 (setq op
9575 (cond
9576 ((equal op "<" ) '(< string< org-time<))
9577 ((equal op ">" ) '(> org-string> org-time>))
9578 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9579 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9580 ((member op '("=" "==")) '(= string= org-time=))
9581 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9582 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9583
9584 (defun org<> (a b) (not (= a b)))
9585 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9586 (defun org-string>= (a b) (not (string< a b)))
9587 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9588 (defun org-string<> (a b) (not (string= a b)))
9589 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
9590 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
9591 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
9592 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
9593 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
9594 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
9595 (defun org-2ft (s)
9596 "Convert S to a floating point time.
9597 If S is already a number, just return it. If it is a string, parse
9598 it as a time string and apply `float-time' to it. If S is nil, just return 0."
9599 (cond
9600 ((numberp s) s)
9601 ((stringp s)
9602 (condition-case nil
9603 (float-time (apply 'encode-time (org-parse-time-string s)))
9604 (error 0.)))
9605 (t 0.)))
9606
9607 (defun org-time-today ()
9608 "Time in seconds today at 0:00.
9609 Returns the float number of seconds since the beginning of the
9610 epoch to the beginning of today (00:00)."
9611 (float-time (apply 'encode-time
9612 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9613
9614 (defun org-matcher-time (s)
9615 "Interpret a time comparison value."
9616 (save-match-data
9617 (cond
9618 ((string= s "<now>") (float-time))
9619 ((string= s "<today>") (org-time-today))
9620 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9621 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9622 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9623 (+ (org-time-today)
9624 (* (string-to-number (match-string 1 s))
9625 (cdr (assoc (match-string 2 s)
9626 '(("d" . 86400.0) ("w" . 604800.0)
9627 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9628 (t (org-2ft s)))))
9629
9630 (defun org-match-any-p (re list)
9631 "Does re match any element of list?"
9632 (setq list (mapcar (lambda (x) (string-match re x)) list))
9633 (delq nil list))
9634
9635 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9636 (defvar org-tags-overlay (org-make-overlay 1 1))
9637 (org-detach-overlay org-tags-overlay)
9638
9639 (defun org-get-local-tags-at (&optional pos)
9640 "Get a list of tags defined in the current headline."
9641 (org-get-tags-at pos 'local))
9642
9643 (defun org-get-local-tags ()
9644 "Get a list of tags defined in the current headline."
9645 (org-get-tags-at nil 'local))
9646
9647 (defun org-get-tags-at (&optional pos local)
9648 "Get a list of all headline tags applicable at POS.
9649 POS defaults to point. If tags are inherited, the list contains
9650 the targets in the same sequence as the headlines appear, i.e.
9651 the tags of the current headline come last.
9652 When LOCAL is non-nil, only return tags from the current headline,
9653 ignore inherited ones."
9654 (interactive)
9655 (let (tags ltags lastpos parent)
9656 (save-excursion
9657 (save-restriction
9658 (widen)
9659 (goto-char (or pos (point)))
9660 (save-match-data
9661 (catch 'done
9662 (condition-case nil
9663 (progn
9664 (org-back-to-heading t)
9665 (while (not (equal lastpos (point)))
9666 (setq lastpos (point))
9667 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9668 (setq ltags (org-split-string
9669 (org-match-string-no-properties 1) ":"))
9670 (when parent
9671 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9672 (setq tags (append
9673 (if parent
9674 (org-remove-uniherited-tags ltags)
9675 ltags)
9676 tags)))
9677 (or org-use-tag-inheritance (throw 'done t))
9678 (if local (throw 'done t))
9679 (org-up-heading-all 1)
9680 (setq parent t)))
9681 (error nil)))))
9682 (append (org-remove-uniherited-tags org-file-tags) tags))))
9683
9684 (defun org-add-prop-inherited (s)
9685 (add-text-properties 0 (length s) '(inherited t) s)
9686 s)
9687
9688 (defun org-toggle-tag (tag &optional onoff)
9689 "Toggle the tag TAG for the current line.
9690 If ONOFF is `on' or `off', don't toggle but set to this state."
9691 (let (res current)
9692 (save-excursion
9693 (org-back-to-heading t)
9694 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9695 (point-at-eol) t)
9696 (progn
9697 (setq current (match-string 1))
9698 (replace-match ""))
9699 (setq current ""))
9700 (setq current (nreverse (org-split-string current ":")))
9701 (cond
9702 ((eq onoff 'on)
9703 (setq res t)
9704 (or (member tag current) (push tag current)))
9705 ((eq onoff 'off)
9706 (or (not (member tag current)) (setq current (delete tag current))))
9707 (t (if (member tag current)
9708 (setq current (delete tag current))
9709 (setq res t)
9710 (push tag current))))
9711 (end-of-line 1)
9712 (if current
9713 (progn
9714 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9715 (org-set-tags nil t))
9716 (delete-horizontal-space))
9717 (run-hooks 'org-after-tags-change-hook))
9718 res))
9719
9720 (defun org-align-tags-here (to-col)
9721 ;; Assumes that this is a headline
9722 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9723 (beginning-of-line 1)
9724 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9725 (< pos (match-beginning 2)))
9726 (progn
9727 (setq tags-l (- (match-end 2) (match-beginning 2)))
9728 (goto-char (match-beginning 1))
9729 (insert " ")
9730 (delete-region (point) (1+ (match-beginning 2)))
9731 (setq ncol (max (1+ (current-column))
9732 (1+ col)
9733 (if (> to-col 0)
9734 to-col
9735 (- (abs to-col) tags-l))))
9736 (setq p (point))
9737 (insert (make-string (- ncol (current-column)) ?\ ))
9738 (setq ncol (current-column))
9739 (when indent-tabs-mode (tabify p (point-at-eol)))
9740 (org-move-to-column (min ncol col) t))
9741 (goto-char pos))))
9742
9743 (defun org-set-tags-command (&optional arg just-align)
9744 "Call the set-tags command for the current entry."
9745 (interactive "P")
9746 (if (org-on-heading-p)
9747 (org-set-tags arg just-align)
9748 (save-excursion
9749 (org-back-to-heading t)
9750 (org-set-tags arg just-align))))
9751
9752 (defun org-set-tags (&optional arg just-align)
9753 "Set the tags for the current headline.
9754 With prefix ARG, realign all tags in headings in the current buffer."
9755 (interactive "P")
9756 (let* ((re (concat "^" outline-regexp))
9757 (current (org-get-tags-string))
9758 (col (current-column))
9759 (org-setting-tags t)
9760 table current-tags inherited-tags ; computed below when needed
9761 tags p0 c0 c1 rpl)
9762 (if arg
9763 (save-excursion
9764 (goto-char (point-min))
9765 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9766 (while (re-search-forward re nil t)
9767 (org-set-tags nil t)
9768 (end-of-line 1)))
9769 (message "All tags realigned to column %d" org-tags-column))
9770 (if just-align
9771 (setq tags current)
9772 ;; Get a new set of tags from the user
9773 (save-excursion
9774 (setq table (or org-tag-alist (org-get-buffer-tags))
9775 org-last-tags-completion-table table
9776 current-tags (org-split-string current ":")
9777 inherited-tags (nreverse
9778 (nthcdr (length current-tags)
9779 (nreverse (org-get-tags-at))))
9780 tags
9781 (if (or (eq t org-use-fast-tag-selection)
9782 (and org-use-fast-tag-selection
9783 (delq nil (mapcar 'cdr table))))
9784 (org-fast-tag-selection
9785 current-tags inherited-tags table
9786 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9787 (let ((org-add-colon-after-tag-completion t))
9788 (org-trim
9789 (org-without-partial-completion
9790 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9791 nil nil current 'org-tags-history)))))))
9792 (while (string-match "[-+&]+" tags)
9793 ;; No boolean logic, just a list
9794 (setq tags (replace-match ":" t t tags))))
9795
9796 (if (string-match "\\`[\t ]*\\'" tags)
9797 (setq tags "")
9798 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9799 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9800
9801 ;; Insert new tags at the correct column
9802 (beginning-of-line 1)
9803 (cond
9804 ((and (equal current "") (equal tags "")))
9805 ((re-search-forward
9806 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9807 (point-at-eol) t)
9808 (if (equal tags "")
9809 (setq rpl "")
9810 (goto-char (match-beginning 0))
9811 (setq c0 (current-column) p0 (point)
9812 c1 (max (1+ c0) (if (> org-tags-column 0)
9813 org-tags-column
9814 (- (- org-tags-column) (length tags))))
9815 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9816 (replace-match rpl t t)
9817 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9818 tags)
9819 (t (error "Tags alignment failed")))
9820 (org-move-to-column col)
9821 (unless just-align
9822 (run-hooks 'org-after-tags-change-hook)))))
9823
9824 (defun org-change-tag-in-region (beg end tag off)
9825 "Add or remove TAG for each entry in the region.
9826 This works in the agenda, and also in an org-mode buffer."
9827 (interactive
9828 (list (region-beginning) (region-end)
9829 (let ((org-last-tags-completion-table
9830 (if (org-mode-p)
9831 (org-get-buffer-tags)
9832 (org-global-tags-completion-table))))
9833 (org-ido-completing-read
9834 "Tag: " 'org-tags-completion-function nil nil nil
9835 'org-tags-history))
9836 (progn
9837 (message "[s]et or [r]emove? ")
9838 (equal (read-char-exclusive) ?r))))
9839 (if (fboundp 'deactivate-mark) (deactivate-mark))
9840 (let ((agendap (equal major-mode 'org-agenda-mode))
9841 l1 l2 m buf pos newhead (cnt 0))
9842 (goto-char end)
9843 (setq l2 (1- (org-current-line)))
9844 (goto-char beg)
9845 (setq l1 (org-current-line))
9846 (loop for l from l1 to l2 do
9847 (goto-line l)
9848 (setq m (get-text-property (point) 'org-hd-marker))
9849 (when (or (and (org-mode-p) (org-on-heading-p))
9850 (and agendap m))
9851 (setq buf (if agendap (marker-buffer m) (current-buffer))
9852 pos (if agendap m (point)))
9853 (with-current-buffer buf
9854 (save-excursion
9855 (save-restriction
9856 (goto-char pos)
9857 (setq cnt (1+ cnt))
9858 (org-toggle-tag tag (if off 'off 'on))
9859 (setq newhead (org-get-heading)))))
9860 (and agendap (org-agenda-change-all-lines newhead m))))
9861 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9862
9863 (defun org-tags-completion-function (string predicate &optional flag)
9864 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9865 (confirm (lambda (x) (stringp (car x)))))
9866 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9867 (setq s1 (match-string 1 string)
9868 s2 (match-string 2 string))
9869 (setq s1 "" s2 string))
9870 (cond
9871 ((eq flag nil)
9872 ;; try completion
9873 (setq rtn (try-completion s2 ctable confirm))
9874 (if (stringp rtn)
9875 (setq rtn
9876 (concat s1 s2 (substring rtn (length s2))
9877 (if (and org-add-colon-after-tag-completion
9878 (assoc rtn ctable))
9879 ":" ""))))
9880 rtn)
9881 ((eq flag t)
9882 ;; all-completions
9883 (all-completions s2 ctable confirm)
9884 )
9885 ((eq flag 'lambda)
9886 ;; exact match?
9887 (assoc s2 ctable)))
9888 ))
9889
9890 (defun org-fast-tag-insert (kwd tags face &optional end)
9891 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
9892 (insert (format "%-12s" (concat kwd ":"))
9893 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9894 (or end "")))
9895
9896 (defun org-fast-tag-show-exit (flag)
9897 (save-excursion
9898 (goto-line 3)
9899 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9900 (replace-match ""))
9901 (when flag
9902 (end-of-line 1)
9903 (org-move-to-column (- (window-width) 19) t)
9904 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9905
9906 (defun org-set-current-tags-overlay (current prefix)
9907 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9908 (if (featurep 'xemacs)
9909 (org-overlay-display org-tags-overlay (concat prefix s)
9910 'secondary-selection)
9911 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9912 (org-overlay-display org-tags-overlay (concat prefix s)))))
9913
9914 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9915 "Fast tag selection with single keys.
9916 CURRENT is the current list of tags in the headline, INHERITED is the
9917 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9918 possibly with grouping information. TODO-TABLE is a similar table with
9919 TODO keywords, should these have keys assigned to them.
9920 If the keys are nil, a-z are automatically assigned.
9921 Returns the new tags string, or nil to not change the current settings."
9922 (let* ((fulltable (append table todo-table))
9923 (maxlen (apply 'max (mapcar
9924 (lambda (x)
9925 (if (stringp (car x)) (string-width (car x)) 0))
9926 fulltable)))
9927 (buf (current-buffer))
9928 (expert (eq org-fast-tag-selection-single-key 'expert))
9929 (buffer-tags nil)
9930 (fwidth (+ maxlen 3 1 3))
9931 (ncol (/ (- (window-width) 4) fwidth))
9932 (i-face 'org-done)
9933 (c-face 'org-todo)
9934 tg cnt e c char c1 c2 ntable tbl rtn
9935 ov-start ov-end ov-prefix
9936 (exit-after-next org-fast-tag-selection-single-key)
9937 (done-keywords org-done-keywords)
9938 groups ingroup)
9939 (save-excursion
9940 (beginning-of-line 1)
9941 (if (looking-at
9942 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9943 (setq ov-start (match-beginning 1)
9944 ov-end (match-end 1)
9945 ov-prefix "")
9946 (setq ov-start (1- (point-at-eol))
9947 ov-end (1+ ov-start))
9948 (skip-chars-forward "^\n\r")
9949 (setq ov-prefix
9950 (concat
9951 (buffer-substring (1- (point)) (point))
9952 (if (> (current-column) org-tags-column)
9953 " "
9954 (make-string (- org-tags-column (current-column)) ?\ ))))))
9955 (org-move-overlay org-tags-overlay ov-start ov-end)
9956 (save-window-excursion
9957 (if expert
9958 (set-buffer (get-buffer-create " *Org tags*"))
9959 (delete-other-windows)
9960 (split-window-vertically)
9961 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9962 (erase-buffer)
9963 (org-set-local 'org-done-keywords done-keywords)
9964 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9965 (org-fast-tag-insert "Current" current c-face "\n\n")
9966 (org-fast-tag-show-exit exit-after-next)
9967 (org-set-current-tags-overlay current ov-prefix)
9968 (setq tbl fulltable char ?a cnt 0)
9969 (while (setq e (pop tbl))
9970 (cond
9971 ((equal e '(:startgroup))
9972 (push '() groups) (setq ingroup t)
9973 (when (not (= cnt 0))
9974 (setq cnt 0)
9975 (insert "\n"))
9976 (insert "{ "))
9977 ((equal e '(:endgroup))
9978 (setq ingroup nil cnt 0)
9979 (insert "}\n"))
9980 (t
9981 (setq tg (car e) c2 nil)
9982 (if (cdr e)
9983 (setq c (cdr e))
9984 ;; automatically assign a character.
9985 (setq c1 (string-to-char
9986 (downcase (substring
9987 tg (if (= (string-to-char tg) ?@) 1 0)))))
9988 (if (or (rassoc c1 ntable) (rassoc c1 table))
9989 (while (or (rassoc char ntable) (rassoc char table))
9990 (setq char (1+ char)))
9991 (setq c2 c1))
9992 (setq c (or c2 char)))
9993 (if ingroup (push tg (car groups)))
9994 (setq tg (org-add-props tg nil 'face
9995 (cond
9996 ((not (assoc tg table))
9997 (org-get-todo-face tg))
9998 ((member tg current) c-face)
9999 ((member tg inherited) i-face)
10000 (t nil))))
10001 (if (and (= cnt 0) (not ingroup)) (insert " "))
10002 (insert "[" c "] " tg (make-string
10003 (- fwidth 4 (length tg)) ?\ ))
10004 (push (cons tg c) ntable)
10005 (when (= (setq cnt (1+ cnt)) ncol)
10006 (insert "\n")
10007 (if ingroup (insert " "))
10008 (setq cnt 0)))))
10009 (setq ntable (nreverse ntable))
10010 (insert "\n")
10011 (goto-char (point-min))
10012 (if (not expert) (org-fit-window-to-buffer))
10013 (setq rtn
10014 (catch 'exit
10015 (while t
10016 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10017 (if groups " [!] no groups" " [!]groups")
10018 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10019 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10020 (cond
10021 ((= c ?\r) (throw 'exit t))
10022 ((= c ?!)
10023 (setq groups (not groups))
10024 (goto-char (point-min))
10025 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10026 ((= c ?\C-c)
10027 (if (not expert)
10028 (org-fast-tag-show-exit
10029 (setq exit-after-next (not exit-after-next)))
10030 (setq expert nil)
10031 (delete-other-windows)
10032 (split-window-vertically)
10033 (org-switch-to-buffer-other-window " *Org tags*")
10034 (org-fit-window-to-buffer)))
10035 ((or (= c ?\C-g)
10036 (and (= c ?q) (not (rassoc c ntable))))
10037 (org-detach-overlay org-tags-overlay)
10038 (setq quit-flag t))
10039 ((= c ?\ )
10040 (setq current nil)
10041 (if exit-after-next (setq exit-after-next 'now)))
10042 ((= c ?\t)
10043 (condition-case nil
10044 (setq tg (org-ido-completing-read
10045 "Tag: "
10046 (or buffer-tags
10047 (with-current-buffer buf
10048 (org-get-buffer-tags)))))
10049 (quit (setq tg "")))
10050 (when (string-match "\\S-" tg)
10051 (add-to-list 'buffer-tags (list tg))
10052 (if (member tg current)
10053 (setq current (delete tg current))
10054 (push tg current)))
10055 (if exit-after-next (setq exit-after-next 'now)))
10056 ((setq e (rassoc c todo-table) tg (car e))
10057 (with-current-buffer buf
10058 (save-excursion (org-todo tg)))
10059 (if exit-after-next (setq exit-after-next 'now)))
10060 ((setq e (rassoc c ntable) tg (car e))
10061 (if (member tg current)
10062 (setq current (delete tg current))
10063 (loop for g in groups do
10064 (if (member tg g)
10065 (mapc (lambda (x)
10066 (setq current (delete x current)))
10067 g)))
10068 (push tg current))
10069 (if exit-after-next (setq exit-after-next 'now))))
10070
10071 ;; Create a sorted list
10072 (setq current
10073 (sort current
10074 (lambda (a b)
10075 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10076 (if (eq exit-after-next 'now) (throw 'exit t))
10077 (goto-char (point-min))
10078 (beginning-of-line 2)
10079 (delete-region (point) (point-at-eol))
10080 (org-fast-tag-insert "Current" current c-face)
10081 (org-set-current-tags-overlay current ov-prefix)
10082 (while (re-search-forward
10083 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10084 (setq tg (match-string 1))
10085 (add-text-properties
10086 (match-beginning 1) (match-end 1)
10087 (list 'face
10088 (cond
10089 ((member tg current) c-face)
10090 ((member tg inherited) i-face)
10091 (t (get-text-property (match-beginning 1) 'face))))))
10092 (goto-char (point-min)))))
10093 (org-detach-overlay org-tags-overlay)
10094 (if rtn
10095 (mapconcat 'identity current ":")
10096 nil))))
10097
10098 (defun org-get-tags-string ()
10099 "Get the TAGS string in the current headline."
10100 (unless (org-on-heading-p t)
10101 (error "Not on a heading"))
10102 (save-excursion
10103 (beginning-of-line 1)
10104 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10105 (org-match-string-no-properties 1)
10106 "")))
10107
10108 (defun org-get-tags ()
10109 "Get the list of tags specified in the current headline."
10110 (org-split-string (org-get-tags-string) ":"))
10111
10112 (defun org-get-buffer-tags ()
10113 "Get a table of all tags used in the buffer, for completion."
10114 (let (tags)
10115 (save-excursion
10116 (goto-char (point-min))
10117 (while (re-search-forward
10118 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10119 (when (equal (char-after (point-at-bol 0)) ?*)
10120 (mapc (lambda (x) (add-to-list 'tags x))
10121 (org-split-string (org-match-string-no-properties 1) ":")))))
10122 (mapcar 'list tags)))
10123
10124 ;;;; The mapping API
10125
10126 ;;;###autoload
10127 (defun org-map-entries (func &optional match scope &rest skip)
10128 "Call FUNC at each headline selected by MATCH in SCOPE.
10129
10130 FUNC is a function or a lisp form. The function will be called without
10131 arguments, with the cursor positioned at the beginning of the headline.
10132 The return values of all calls to the function will be collected and
10133 returned as a list.
10134
10135 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10136 Only headlines that are matched by this query will be considered during
10137 the iteration. When MATCH is nil or t, all headlines will be
10138 visited by the iteration.
10139
10140 SCOPE determines the scope of this command. It can be any of:
10141
10142 nil The current buffer, respecting the restriction if any
10143 tree The subtree started with the entry at point
10144 file The current buffer, without restriction
10145 file-with-archives
10146 The current buffer, and any archives associated with it
10147 agenda All agenda files
10148 agenda-with-archives
10149 All agenda files with any archive files associated with them
10150 \(file1 file2 ...)
10151 If this is a list, all files in the list will be scanned
10152
10153 The remaining args are treated as settings for the skipping facilities of
10154 the scanner. The following items can be given here:
10155
10156 archive skip trees with the archive tag.
10157 comment skip trees with the COMMENT keyword
10158 function or Emacs Lisp form:
10159 will be used as value for `org-agenda-skip-function', so whenever
10160 the the function returns t, FUNC will not be called for that
10161 entry and search will continue from the point where the
10162 function leaves it."
10163 (let* ((org-agenda-archives-mode nil) ; just to make sure
10164 (org-agenda-skip-archived-trees (memq 'archive skip))
10165 (org-agenda-skip-comment-trees (memq 'comment skip))
10166 (org-agenda-skip-function
10167 (car (org-delete-all '(comment archive) skip)))
10168 (org-tags-match-list-sublevels t)
10169 matcher pos file res
10170 org-todo-keywords-for-agenda
10171 org-done-keywords-for-agenda
10172 org-todo-keyword-alist-for-agenda
10173 org-tag-alist-for-agenda)
10174
10175 (cond
10176 ((eq match t) (setq matcher t))
10177 ((eq match nil) (setq matcher t))
10178 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10179
10180 (save-excursion
10181 (save-restriction
10182 (when (eq scope 'tree)
10183 (org-back-to-heading t)
10184 (org-narrow-to-subtree)
10185 (setq scope nil))
10186
10187 (if (not scope)
10188 (progn
10189 (org-prepare-agenda-buffers
10190 (list (buffer-file-name (current-buffer))))
10191 (setq res (org-scan-tags func matcher)))
10192 ;; Get the right scope
10193 (setq pos (point))
10194 (cond
10195 ((and scope (listp scope) (symbolp (car scope)))
10196 (setq scope (eval scope)))
10197 ((eq scope 'agenda)
10198 (setq scope (org-agenda-files t)))
10199 ((eq scope 'agenda-with-archives)
10200 (setq scope (org-agenda-files t))
10201 (setq scope (org-add-archive-files scope)))
10202 ((eq scope 'file)
10203 (setq scope (list (buffer-file-name))))
10204 ((eq scope 'file-with-archives)
10205 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10206 (org-prepare-agenda-buffers scope)
10207 (while (setq file (pop scope))
10208 (with-current-buffer (org-find-base-buffer-visiting file)
10209 (save-excursion
10210 (save-restriction
10211 (widen)
10212 (goto-char (point-min))
10213 (setq res (append res (org-scan-tags func matcher))))))))))
10214 res))
10215
10216 ;;;; Properties
10217
10218 ;;; Setting and retrieving properties
10219
10220 (defconst org-special-properties
10221 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10222 "TIMESTAMP" "TIMESTAMP_IA")
10223 "The special properties valid in Org-mode.
10224
10225 These are properties that are not defined in the property drawer,
10226 but in some other way.")
10227
10228 (defconst org-default-properties
10229 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10230 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10231 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10232 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10233 "Some properties that are used by Org-mode for various purposes.
10234 Being in this list makes sure that they are offered for completion.")
10235
10236 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10237 "Regular expression matching the first line of a property drawer.")
10238
10239 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10240 "Regular expression matching the first line of a property drawer.")
10241
10242 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10243 "Regular expression matching the first line of a property drawer.")
10244
10245 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10246 "Regular expression matching the first line of a property drawer.")
10247
10248 (defconst org-property-drawer-re
10249 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10250 org-property-end-re "\\)\n?")
10251 "Matches an entire property drawer.")
10252
10253 (defconst org-clock-drawer-re
10254 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10255 org-property-end-re "\\)\n?")
10256 "Matches an entire clock drawer.")
10257
10258 (defun org-property-action ()
10259 "Do an action on properties."
10260 (interactive)
10261 (let (c)
10262 (org-at-property-p)
10263 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10264 (setq c (read-char-exclusive))
10265 (cond
10266 ((equal c ?s)
10267 (call-interactively 'org-set-property))
10268 ((equal c ?d)
10269 (call-interactively 'org-delete-property))
10270 ((equal c ?D)
10271 (call-interactively 'org-delete-property-globally))
10272 ((equal c ?c)
10273 (call-interactively 'org-compute-property-at-point))
10274 (t (error "No such property action %c" c)))))
10275
10276 (defun org-at-property-p ()
10277 "Is the cursor in a property line?"
10278 ;; FIXME: Does not check if we are actually in the drawer.
10279 ;; FIXME: also returns true on any drawers.....
10280 ;; This is used by C-c C-c for property action.
10281 (save-excursion
10282 (beginning-of-line 1)
10283 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10284
10285 (defun org-get-property-block (&optional beg end force)
10286 "Return the (beg . end) range of the body of the property drawer.
10287 BEG and END can be beginning and end of subtree, if not given
10288 they will be found.
10289 If the drawer does not exist and FORCE is non-nil, create the drawer."
10290 (catch 'exit
10291 (save-excursion
10292 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10293 (end (or end (progn (outline-next-heading) (point)))))
10294 (goto-char beg)
10295 (if (re-search-forward org-property-start-re end t)
10296 (setq beg (1+ (match-end 0)))
10297 (if force
10298 (save-excursion
10299 (org-insert-property-drawer)
10300 (setq end (progn (outline-next-heading) (point))))
10301 (throw 'exit nil))
10302 (goto-char beg)
10303 (if (re-search-forward org-property-start-re end t)
10304 (setq beg (1+ (match-end 0)))))
10305 (if (re-search-forward org-property-end-re end t)
10306 (setq end (match-beginning 0))
10307 (or force (throw 'exit nil))
10308 (goto-char beg)
10309 (setq end beg)
10310 (org-indent-line-function)
10311 (insert ":END:\n"))
10312 (cons beg end)))))
10313
10314 (defun org-entry-properties (&optional pom which)
10315 "Get all properties of the entry at point-or-marker POM.
10316 This includes the TODO keyword, the tags, time strings for deadline,
10317 scheduled, and clocking, and any additional properties defined in the
10318 entry. The return value is an alist, keys may occur multiple times
10319 if the property key was used several times.
10320 POM may also be nil, in which case the current entry is used.
10321 If WHICH is nil or `all', get all properties. If WHICH is
10322 `special' or `standard', only get that subclass."
10323 (setq which (or which 'all))
10324 (org-with-point-at pom
10325 (let ((clockstr (substring org-clock-string 0 -1))
10326 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10327 beg end range props sum-props key value string clocksum)
10328 (save-excursion
10329 (when (condition-case nil
10330 (and (org-mode-p) (org-back-to-heading t))
10331 (error nil))
10332 (setq beg (point))
10333 (setq sum-props (get-text-property (point) 'org-summaries))
10334 (setq clocksum (get-text-property (point) :org-clock-minutes))
10335 (outline-next-heading)
10336 (setq end (point))
10337 (when (memq which '(all special))
10338 ;; Get the special properties, like TODO and tags
10339 (goto-char beg)
10340 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10341 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10342 (when (looking-at org-priority-regexp)
10343 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10344 (when (and (setq value (org-get-tags-string))
10345 (string-match "\\S-" value))
10346 (push (cons "TAGS" value) props))
10347 (when (setq value (org-get-tags-at))
10348 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10349 props))
10350 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10351 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10352 string (if (equal key clockstr)
10353 (org-no-properties
10354 (org-trim
10355 (buffer-substring
10356 (match-beginning 3) (goto-char (point-at-eol)))))
10357 (substring (org-match-string-no-properties 3) 1 -1)))
10358 (unless key
10359 (if (= (char-after (match-beginning 3)) ?\[)
10360 (setq key "TIMESTAMP_IA")
10361 (setq key "TIMESTAMP")))
10362 (when (or (equal key clockstr) (not (assoc key props)))
10363 (push (cons key string) props)))
10364
10365 )
10366
10367 (when (memq which '(all standard))
10368 ;; Get the standard properties, like :PORP: ...
10369 (setq range (org-get-property-block beg end))
10370 (when range
10371 (goto-char (car range))
10372 (while (re-search-forward
10373 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10374 (cdr range) t)
10375 (setq key (org-match-string-no-properties 1)
10376 value (org-trim (or (org-match-string-no-properties 2) "")))
10377 (unless (member key excluded)
10378 (push (cons key (or value "")) props)))))
10379 (if clocksum
10380 (push (cons "CLOCKSUM"
10381 (org-columns-number-to-string (/ (float clocksum) 60.)
10382 'add_times))
10383 props))
10384 (unless (assoc "CATEGORY" props)
10385 (setq value (or (org-get-category)
10386 (progn (org-refresh-category-properties)
10387 (org-get-category))))
10388 (push (cons "CATEGORY" value) props))
10389 (append sum-props (nreverse props)))))))
10390
10391 (defun org-entry-get (pom property &optional inherit)
10392 "Get value of PROPERTY for entry at point-or-marker POM.
10393 If INHERIT is non-nil and the entry does not have the property,
10394 then also check higher levels of the hierarchy.
10395 If INHERIT is the symbol `selective', use inheritance only if the setting
10396 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10397 If the property is present but empty, the return value is the empty string.
10398 If the property is not present at all, nil is returned."
10399 (org-with-point-at pom
10400 (if (and inherit (if (eq inherit 'selective)
10401 (org-property-inherit-p property)
10402 t))
10403 (org-entry-get-with-inheritance property)
10404 (if (member property org-special-properties)
10405 ;; We need a special property. Use brute force, get all properties.
10406 (cdr (assoc property (org-entry-properties nil 'special)))
10407 (let ((range (org-get-property-block)))
10408 (if (and range
10409 (goto-char (car range))
10410 (re-search-forward
10411 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10412 (cdr range) t))
10413 ;; Found the property, return it.
10414 (if (match-end 1)
10415 (org-match-string-no-properties 1)
10416 "")))))))
10417
10418 (defun org-property-or-variable-value (var &optional inherit)
10419 "Check if there is a property fixing the value of VAR.
10420 If yes, return this value. If not, return the current value of the variable."
10421 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10422 (if (and prop (stringp prop) (string-match "\\S-" prop))
10423 (read prop)
10424 (symbol-value var))))
10425
10426 (defun org-entry-delete (pom property)
10427 "Delete the property PROPERTY from entry at point-or-marker POM."
10428 (org-with-point-at pom
10429 (if (member property org-special-properties)
10430 nil ; cannot delete these properties.
10431 (let ((range (org-get-property-block)))
10432 (if (and range
10433 (goto-char (car range))
10434 (re-search-forward
10435 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10436 (cdr range) t))
10437 (progn
10438 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10439 t)
10440 nil)))))
10441
10442 ;; Multi-values properties are properties that contain multiple values
10443 ;; These values are assumed to be single words, separated by whitespace.
10444 (defun org-entry-add-to-multivalued-property (pom property value)
10445 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10446 (let* ((old (org-entry-get pom property))
10447 (values (and old (org-split-string old "[ \t]"))))
10448 (setq value (org-entry-protect-space value))
10449 (unless (member value values)
10450 (setq values (cons value values))
10451 (org-entry-put pom property
10452 (mapconcat 'identity values " ")))))
10453
10454 (defun org-entry-remove-from-multivalued-property (pom property value)
10455 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10456 (let* ((old (org-entry-get pom property))
10457 (values (and old (org-split-string old "[ \t]"))))
10458 (setq value (org-entry-protect-space value))
10459 (when (member value values)
10460 (setq values (delete value values))
10461 (org-entry-put pom property
10462 (mapconcat 'identity values " ")))))
10463
10464 (defun org-entry-member-in-multivalued-property (pom property value)
10465 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10466 (let* ((old (org-entry-get pom property))
10467 (values (and old (org-split-string old "[ \t]"))))
10468 (setq value (org-entry-protect-space value))
10469 (member value values)))
10470
10471 (defun org-entry-get-multivalued-property (pom property)
10472 "Return a list of values in a multivalued property."
10473 (let* ((value (org-entry-get pom property))
10474 (values (and value (org-split-string value "[ \t]"))))
10475 (mapcar 'org-entry-restore-space values)))
10476
10477 (defun org-entry-put-multivalued-property (pom property &rest values)
10478 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10479 VALUES should be a list of strings. Spaces will be protected."
10480 (org-entry-put pom property
10481 (mapconcat 'org-entry-protect-space values " "))
10482 (let* ((value (org-entry-get pom property))
10483 (values (and value (org-split-string value "[ \t]"))))
10484 (mapcar 'org-entry-restore-space values)))
10485
10486 (defun org-entry-protect-space (s)
10487 "Protect spaces and newline in string S."
10488 (while (string-match " " s)
10489 (setq s (replace-match "%20" t t s)))
10490 (while (string-match "\n" s)
10491 (setq s (replace-match "%0A" t t s)))
10492 s)
10493
10494 (defun org-entry-restore-space (s)
10495 "Restore spaces and newline in string S."
10496 (while (string-match "%20" s)
10497 (setq s (replace-match " " t t s)))
10498 (while (string-match "%0A" s)
10499 (setq s (replace-match "\n" t t s)))
10500 s)
10501
10502 (defvar org-entry-property-inherited-from (make-marker)
10503 "Marker pointing to the entry from where a property was inherited.
10504 Each call to `org-entry-get-with-inheritance' will set this marker to the
10505 location of the entry where the inheritance search matched. If there was
10506 no match, the marker will point nowhere.
10507 Note that also `org-entry-get' calls this function, if the INHERIT flag
10508 is set.")
10509
10510 (defun org-entry-get-with-inheritance (property)
10511 "Get entry property, and search higher levels if not present."
10512 (move-marker org-entry-property-inherited-from nil)
10513 (let (tmp)
10514 (save-excursion
10515 (save-restriction
10516 (widen)
10517 (catch 'ex
10518 (while t
10519 (when (setq tmp (org-entry-get nil property))
10520 (org-back-to-heading t)
10521 (move-marker org-entry-property-inherited-from (point))
10522 (throw 'ex tmp))
10523 (or (org-up-heading-safe) (throw 'ex nil)))))
10524 (or tmp
10525 (cdr (assoc property org-file-properties))
10526 (cdr (assoc property org-global-properties))
10527 (cdr (assoc property org-global-properties-fixed))))))
10528
10529 (defun org-entry-put (pom property value)
10530 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10531 (org-with-point-at pom
10532 (org-back-to-heading t)
10533 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10534 range)
10535 (cond
10536 ((equal property "TODO")
10537 (when (and (stringp value) (string-match "\\S-" value)
10538 (not (member value org-todo-keywords-1)))
10539 (error "\"%s\" is not a valid TODO state" value))
10540 (if (or (not value)
10541 (not (string-match "\\S-" value)))
10542 (setq value 'none))
10543 (org-todo value)
10544 (org-set-tags nil 'align))
10545 ((equal property "PRIORITY")
10546 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10547 (string-to-char value) ?\ ))
10548 (org-set-tags nil 'align))
10549 ((equal property "SCHEDULED")
10550 (if (re-search-forward org-scheduled-time-regexp end t)
10551 (cond
10552 ((eq value 'earlier) (org-timestamp-change -1 'day))
10553 ((eq value 'later) (org-timestamp-change 1 'day))
10554 (t (call-interactively 'org-schedule)))
10555 (call-interactively 'org-schedule)))
10556 ((equal property "DEADLINE")
10557 (if (re-search-forward org-deadline-time-regexp end t)
10558 (cond
10559 ((eq value 'earlier) (org-timestamp-change -1 'day))
10560 ((eq value 'later) (org-timestamp-change 1 'day))
10561 (t (call-interactively 'org-deadline)))
10562 (call-interactively 'org-deadline)))
10563 ((member property org-special-properties)
10564 (error "The %s property can not yet be set with `org-entry-put'"
10565 property))
10566 (t ; a non-special property
10567 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10568 (setq range (org-get-property-block beg end 'force))
10569 (goto-char (car range))
10570 (if (re-search-forward
10571 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10572 (progn
10573 (delete-region (match-beginning 1) (match-end 1))
10574 (goto-char (match-beginning 1)))
10575 (goto-char (cdr range))
10576 (insert "\n")
10577 (backward-char 1)
10578 (org-indent-line-function)
10579 (insert ":" property ":"))
10580 (and value (insert " " value))
10581 (org-indent-line-function)))))))
10582
10583 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10584 "Get all property keys in the current buffer.
10585 With INCLUDE-SPECIALS, also list the special properties that reflect things
10586 like tags and TODO state.
10587 With INCLUDE-DEFAULTS, also include properties that has special meaning
10588 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10589 With INCLUDE-COLUMNS, also include property names given in COLUMN
10590 formats in the current buffer."
10591 (let (rtn range cfmt cols s p)
10592 (save-excursion
10593 (save-restriction
10594 (widen)
10595 (goto-char (point-min))
10596 (while (re-search-forward org-property-start-re nil t)
10597 (setq range (org-get-property-block))
10598 (goto-char (car range))
10599 (while (re-search-forward
10600 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10601 (cdr range) t)
10602 (add-to-list 'rtn (org-match-string-no-properties 1)))
10603 (outline-next-heading))))
10604
10605 (when include-specials
10606 (setq rtn (append org-special-properties rtn)))
10607
10608 (when include-defaults
10609 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10610
10611 (when include-columns
10612 (save-excursion
10613 (save-restriction
10614 (widen)
10615 (goto-char (point-min))
10616 (while (re-search-forward
10617 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10618 nil t)
10619 (setq cfmt (match-string 2) s 0)
10620 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10621 cfmt s)
10622 (setq s (match-end 0)
10623 p (match-string 1 cfmt))
10624 (unless (or (equal p "ITEM")
10625 (member p org-special-properties))
10626 (add-to-list 'rtn (match-string 1 cfmt))))))))
10627
10628 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10629
10630 (defun org-property-values (key)
10631 "Return a list of all values of property KEY."
10632 (save-excursion
10633 (save-restriction
10634 (widen)
10635 (goto-char (point-min))
10636 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10637 values)
10638 (while (re-search-forward re nil t)
10639 (add-to-list 'values (org-trim (match-string 1))))
10640 (delete "" values)))))
10641
10642 (defun org-insert-property-drawer ()
10643 "Insert a property drawer into the current entry."
10644 (interactive)
10645 (org-back-to-heading t)
10646 (looking-at outline-regexp)
10647 (let ((indent (- (match-end 0)(match-beginning 0)))
10648 (beg (point))
10649 (re (concat "^[ \t]*" org-keyword-time-regexp))
10650 end hiddenp)
10651 (outline-next-heading)
10652 (setq end (point))
10653 (goto-char beg)
10654 (while (re-search-forward re end t))
10655 (setq hiddenp (org-invisible-p))
10656 (end-of-line 1)
10657 (and (equal (char-after) ?\n) (forward-char 1))
10658 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10659 (beginning-of-line 2))
10660 (org-skip-over-state-notes)
10661 (skip-chars-backward " \t\n\r")
10662 (if (eq (char-before) ?*) (forward-char 1))
10663 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10664 (beginning-of-line 0)
10665 (org-indent-to-column indent)
10666 (beginning-of-line 2)
10667 (org-indent-to-column indent)
10668 (beginning-of-line 0)
10669 (if hiddenp
10670 (save-excursion
10671 (org-back-to-heading t)
10672 (hide-entry))
10673 (org-flag-drawer t))))
10674
10675 (defun org-set-property (property value)
10676 "In the current entry, set PROPERTY to VALUE.
10677 When called interactively, this will prompt for a property name, offering
10678 completion on existing and default properties. And then it will prompt
10679 for a value, offering completion either on allowed values (via an inherited
10680 xxx_ALL property) or on existing values in other instances of this property
10681 in the current file."
10682 (interactive
10683 (let* ((completion-ignore-case t)
10684 (keys (org-buffer-property-keys nil t t))
10685 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10686 (prop (if (member prop0 keys)
10687 prop0
10688 (or (cdr (assoc (downcase prop0)
10689 (mapcar (lambda (x) (cons (downcase x) x))
10690 keys)))
10691 prop0)))
10692 (cur (org-entry-get nil prop))
10693 (allowed (org-property-get-allowed-values nil prop 'table))
10694 (existing (mapcar 'list (org-property-values prop)))
10695 (val (if allowed
10696 (org-completing-read "Value: " allowed nil 'req-match)
10697 (org-completing-read
10698 (concat "Value" (if (and cur (string-match "\\S-" cur))
10699 (concat "[" cur "]") "")
10700 ": ")
10701 existing nil nil "" nil cur))))
10702 (list prop (if (equal val "") cur val))))
10703 (unless (equal (org-entry-get nil property) value)
10704 (org-entry-put nil property value)))
10705
10706 (defun org-delete-property (property)
10707 "In the current entry, delete PROPERTY."
10708 (interactive
10709 (let* ((completion-ignore-case t)
10710 (prop (org-ido-completing-read
10711 "Property: " (org-entry-properties nil 'standard))))
10712 (list prop)))
10713 (message "Property %s %s" property
10714 (if (org-entry-delete nil property)
10715 "deleted"
10716 "was not present in the entry")))
10717
10718 (defun org-delete-property-globally (property)
10719 "Remove PROPERTY globally, from all entries."
10720 (interactive
10721 (let* ((completion-ignore-case t)
10722 (prop (org-ido-completing-read
10723 "Globally remove property: "
10724 (mapcar 'list (org-buffer-property-keys)))))
10725 (list prop)))
10726 (save-excursion
10727 (save-restriction
10728 (widen)
10729 (goto-char (point-min))
10730 (let ((cnt 0))
10731 (while (re-search-forward
10732 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10733 nil t)
10734 (setq cnt (1+ cnt))
10735 (replace-match ""))
10736 (message "Property \"%s\" removed from %d entries" property cnt)))))
10737
10738 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10739
10740 (defun org-compute-property-at-point ()
10741 "Compute the property at point.
10742 This looks for an enclosing column format, extracts the operator and
10743 then applies it to the property in the column format's scope."
10744 (interactive)
10745 (unless (org-at-property-p)
10746 (error "Not at a property"))
10747 (let ((prop (org-match-string-no-properties 2)))
10748 (org-columns-get-format-and-top-level)
10749 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10750 (error "No operator defined for property %s" prop))
10751 (org-columns-compute prop)))
10752
10753 (defun org-property-get-allowed-values (pom property &optional table)
10754 "Get allowed values for the property PROPERTY.
10755 When TABLE is non-nil, return an alist that can directly be used for
10756 completion."
10757 (let (vals)
10758 (cond
10759 ((equal property "TODO")
10760 (setq vals (org-with-point-at pom
10761 (append org-todo-keywords-1 '("")))))
10762 ((equal property "PRIORITY")
10763 (let ((n org-lowest-priority))
10764 (while (>= n org-highest-priority)
10765 (push (char-to-string n) vals)
10766 (setq n (1- n)))))
10767 ((member property org-special-properties))
10768 (t
10769 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10770
10771 (when (and vals (string-match "\\S-" vals))
10772 (setq vals (car (read-from-string (concat "(" vals ")"))))
10773 (setq vals (mapcar (lambda (x)
10774 (cond ((stringp x) x)
10775 ((numberp x) (number-to-string x))
10776 ((symbolp x) (symbol-name x))
10777 (t "???")))
10778 vals)))))
10779 (if table (mapcar 'list vals) vals)))
10780
10781 (defun org-property-previous-allowed-value (&optional previous)
10782 "Switch to the next allowed value for this property."
10783 (interactive)
10784 (org-property-next-allowed-value t))
10785
10786 (defun org-property-next-allowed-value (&optional previous)
10787 "Switch to the next allowed value for this property."
10788 (interactive)
10789 (unless (org-at-property-p)
10790 (error "Not at a property"))
10791 (let* ((key (match-string 2))
10792 (value (match-string 3))
10793 (allowed (or (org-property-get-allowed-values (point) key)
10794 (and (member value '("[ ]" "[-]" "[X]"))
10795 '("[ ]" "[X]"))))
10796 nval)
10797 (unless allowed
10798 (error "Allowed values for this property have not been defined"))
10799 (if previous (setq allowed (reverse allowed)))
10800 (if (member value allowed)
10801 (setq nval (car (cdr (member value allowed)))))
10802 (setq nval (or nval (car allowed)))
10803 (if (equal nval value)
10804 (error "Only one allowed value for this property"))
10805 (org-at-property-p)
10806 (replace-match (concat " :" key ": " nval) t t)
10807 (org-indent-line-function)
10808 (beginning-of-line 1)
10809 (skip-chars-forward " \t")))
10810
10811 (defun org-find-entry-with-id (ident)
10812 "Locate the entry that contains the ID property with exact value IDENT.
10813 IDENT can be a string, a symbol or a number, this function will search for
10814 the string representation of it.
10815 Return the position where this entry starts, or nil if there is no such entry."
10816 (interactive "sID: ")
10817 (let ((id (cond
10818 ((stringp ident) ident)
10819 ((symbol-name ident) (symbol-name ident))
10820 ((numberp ident) (number-to-string ident))
10821 (t (error "IDENT %s must be a string, symbol or number" ident))))
10822 (case-fold-search nil))
10823 (save-excursion
10824 (save-restriction
10825 (widen)
10826 (goto-char (point-min))
10827 (when (re-search-forward
10828 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10829 nil t)
10830 (org-back-to-heading)
10831 (point))))))
10832
10833 ;;;; Timestamps
10834
10835 (defvar org-last-changed-timestamp nil)
10836 (defvar org-last-inserted-timestamp nil
10837 "The last time stamp inserted with `org-insert-time-stamp'.")
10838 (defvar org-time-was-given) ; dynamically scoped parameter
10839 (defvar org-end-time-was-given) ; dynamically scoped parameter
10840 (defvar org-ts-what) ; dynamically scoped parameter
10841
10842 (defun org-time-stamp (arg &optional inactive)
10843 "Prompt for a date/time and insert a time stamp.
10844 If the user specifies a time like HH:MM, or if this command is called
10845 with a prefix argument, the time stamp will contain date and time.
10846 Otherwise, only the date will be included. All parts of a date not
10847 specified by the user will be filled in from the current date/time.
10848 So if you press just return without typing anything, the time stamp
10849 will represent the current date/time. If there is already a timestamp
10850 at the cursor, it will be modified."
10851 (interactive "P")
10852 (let* ((ts nil)
10853 (default-time
10854 ;; Default time is either today, or, when entering a range,
10855 ;; the range start.
10856 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10857 (save-excursion
10858 (re-search-backward
10859 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10860 (- (point) 20) t)))
10861 (apply 'encode-time (org-parse-time-string (match-string 1)))
10862 (current-time)))
10863 (default-input (and ts (org-get-compact-tod ts)))
10864 org-time-was-given org-end-time-was-given time)
10865 (cond
10866 ((and (org-at-timestamp-p t)
10867 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10868 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10869 (insert "--")
10870 (setq time (let ((this-command this-command))
10871 (org-read-date arg 'totime nil nil
10872 default-time default-input)))
10873 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10874 ((org-at-timestamp-p t)
10875 (setq time (let ((this-command this-command))
10876 (org-read-date arg 'totime nil nil default-time default-input)))
10877 (when (org-at-timestamp-p t) ; just to get the match data
10878 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10879 (replace-match "")
10880 (setq org-last-changed-timestamp
10881 (org-insert-time-stamp
10882 time (or org-time-was-given arg)
10883 inactive nil nil (list org-end-time-was-given))))
10884 (message "Timestamp updated"))
10885 (t
10886 (setq time (let ((this-command this-command))
10887 (org-read-date arg 'totime nil nil default-time default-input)))
10888 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10889 nil nil (list org-end-time-was-given))))))
10890
10891 ;; FIXME: can we use this for something else, like computing time differences?
10892 (defun org-get-compact-tod (s)
10893 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10894 (let* ((t1 (match-string 1 s))
10895 (h1 (string-to-number (match-string 2 s)))
10896 (m1 (string-to-number (match-string 3 s)))
10897 (t2 (and (match-end 4) (match-string 5 s)))
10898 (h2 (and t2 (string-to-number (match-string 6 s))))
10899 (m2 (and t2 (string-to-number (match-string 7 s))))
10900 dh dm)
10901 (if (not t2)
10902 t1
10903 (setq dh (- h2 h1) dm (- m2 m1))
10904 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10905 (concat t1 "+" (number-to-string dh)
10906 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10907
10908 (defun org-time-stamp-inactive (&optional arg)
10909 "Insert an inactive time stamp.
10910 An inactive time stamp is enclosed in square brackets instead of angle
10911 brackets. It is inactive in the sense that it does not trigger agenda entries,
10912 does not link to the calendar and cannot be changed with the S-cursor keys.
10913 So these are more for recording a certain time/date."
10914 (interactive "P")
10915 (org-time-stamp arg 'inactive))
10916
10917 (defvar org-date-ovl (org-make-overlay 1 1))
10918 (org-overlay-put org-date-ovl 'face 'org-warning)
10919 (org-detach-overlay org-date-ovl)
10920
10921 (defvar org-ans1) ; dynamically scoped parameter
10922 (defvar org-ans2) ; dynamically scoped parameter
10923
10924 (defvar org-plain-time-of-day-regexp) ; defined below
10925
10926 (defvar org-overriding-default-time nil) ; dynamically scoped
10927 (defvar org-read-date-overlay nil)
10928 (defvar org-dcst nil) ; dynamically scoped
10929
10930 (defun org-read-date (&optional with-time to-time from-string prompt
10931 default-time default-input)
10932 "Read a date, possibly a time, and make things smooth for the user.
10933 The prompt will suggest to enter an ISO date, but you can also enter anything
10934 which will at least partially be understood by `parse-time-string'.
10935 Unrecognized parts of the date will default to the current day, month, year,
10936 hour and minute. If this command is called to replace a timestamp at point,
10937 of to enter the second timestamp of a range, the default time is taken from the
10938 existing stamp. For example,
10939 3-2-5 --> 2003-02-05
10940 feb 15 --> currentyear-02-15
10941 sep 12 9 --> 2009-09-12
10942 12:45 --> today 12:45
10943 22 sept 0:34 --> currentyear-09-22 0:34
10944 12 --> currentyear-currentmonth-12
10945 Fri --> nearest Friday (today or later)
10946 etc.
10947
10948 Furthermore you can specify a relative date by giving, as the *first* thing
10949 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10950 change in days weeks, months, years.
10951 With a single plus or minus, the date is relative to today. With a double
10952 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10953 +4d --> four days from today
10954 +4 --> same as above
10955 +2w --> two weeks from today
10956 ++5 --> five days from default date
10957
10958 The function understands only English month and weekday abbreviations,
10959 but this can be configured with the variables `parse-time-months' and
10960 `parse-time-weekdays'.
10961
10962 While prompting, a calendar is popped up - you can also select the
10963 date with the mouse (button 1). The calendar shows a period of three
10964 months. To scroll it to other months, use the keys `>' and `<'.
10965 If you don't like the calendar, turn it off with
10966 \(setq org-read-date-popup-calendar nil)
10967
10968 With optional argument TO-TIME, the date will immediately be converted
10969 to an internal time.
10970 With an optional argument WITH-TIME, the prompt will suggest to also
10971 insert a time. Note that when WITH-TIME is not set, you can still
10972 enter a time, and this function will inform the calling routine about
10973 this change. The calling routine may then choose to change the format
10974 used to insert the time stamp into the buffer to include the time.
10975 With optional argument FROM-STRING, read from this string instead from
10976 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10977 the time/date that is used for everything that is not specified by the
10978 user."
10979 (require 'parse-time)
10980 (let* ((org-time-stamp-rounding-minutes
10981 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10982 (org-dcst org-display-custom-times)
10983 (ct (org-current-time))
10984 (def (or org-overriding-default-time default-time ct))
10985 (defdecode (decode-time def))
10986 (dummy (progn
10987 (when (< (nth 2 defdecode) org-extend-today-until)
10988 (setcar (nthcdr 2 defdecode) -1)
10989 (setcar (nthcdr 1 defdecode) 59)
10990 (setq def (apply 'encode-time defdecode)
10991 defdecode (decode-time def)))))
10992 (calendar-move-hook nil)
10993 (calendar-view-diary-initially-flag nil)
10994 (view-diary-entries-initially nil)
10995 (calendar-view-holidays-initially-flag nil)
10996 (view-calendar-holidays-initially nil)
10997 (timestr (format-time-string
10998 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10999 (prompt (concat (if prompt (concat prompt " ") "")
11000 (format "Date+time [%s]: " timestr)))
11001 ans (org-ans0 "") org-ans1 org-ans2 final)
11002
11003 (cond
11004 (from-string (setq ans from-string))
11005 (org-read-date-popup-calendar
11006 (save-excursion
11007 (save-window-excursion
11008 (calendar)
11009 (calendar-forward-day (- (time-to-days def)
11010 (calendar-absolute-from-gregorian
11011 (calendar-current-date))))
11012 (org-eval-in-calendar nil t)
11013 (let* ((old-map (current-local-map))
11014 (map (copy-keymap calendar-mode-map))
11015 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11016 (org-defkey map (kbd "RET") 'org-calendar-select)
11017 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11018 'org-calendar-select-mouse)
11019 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11020 'org-calendar-select-mouse)
11021 (org-defkey minibuffer-local-map [(meta shift left)]
11022 (lambda () (interactive)
11023 (org-eval-in-calendar '(calendar-backward-month 1))))
11024 (org-defkey minibuffer-local-map [(meta shift right)]
11025 (lambda () (interactive)
11026 (org-eval-in-calendar '(calendar-forward-month 1))))
11027 (org-defkey minibuffer-local-map [(meta shift up)]
11028 (lambda () (interactive)
11029 (org-eval-in-calendar '(calendar-backward-year 1))))
11030 (org-defkey minibuffer-local-map [(meta shift down)]
11031 (lambda () (interactive)
11032 (org-eval-in-calendar '(calendar-forward-year 1))))
11033 (org-defkey minibuffer-local-map [(shift up)]
11034 (lambda () (interactive)
11035 (org-eval-in-calendar '(calendar-backward-week 1))))
11036 (org-defkey minibuffer-local-map [(shift down)]
11037 (lambda () (interactive)
11038 (org-eval-in-calendar '(calendar-forward-week 1))))
11039 (org-defkey minibuffer-local-map [(shift left)]
11040 (lambda () (interactive)
11041 (org-eval-in-calendar '(calendar-backward-day 1))))
11042 (org-defkey minibuffer-local-map [(shift right)]
11043 (lambda () (interactive)
11044 (org-eval-in-calendar '(calendar-forward-day 1))))
11045 (org-defkey minibuffer-local-map ">"
11046 (lambda () (interactive)
11047 (org-eval-in-calendar '(scroll-calendar-left 1))))
11048 (org-defkey minibuffer-local-map "<"
11049 (lambda () (interactive)
11050 (org-eval-in-calendar '(scroll-calendar-right 1))))
11051 (unwind-protect
11052 (progn
11053 (use-local-map map)
11054 (add-hook 'post-command-hook 'org-read-date-display)
11055 (setq org-ans0 (read-string prompt default-input nil nil))
11056 ;; org-ans0: from prompt
11057 ;; org-ans1: from mouse click
11058 ;; org-ans2: from calendar motion
11059 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11060 (remove-hook 'post-command-hook 'org-read-date-display)
11061 (use-local-map old-map)
11062 (when org-read-date-overlay
11063 (org-delete-overlay org-read-date-overlay)
11064 (setq org-read-date-overlay nil)))))))
11065
11066 (t ; Naked prompt only
11067 (unwind-protect
11068 (setq ans (read-string prompt default-input nil timestr))
11069 (when org-read-date-overlay
11070 (org-delete-overlay org-read-date-overlay)
11071 (setq org-read-date-overlay nil)))))
11072
11073 (setq final (org-read-date-analyze ans def defdecode))
11074
11075 (if to-time
11076 (apply 'encode-time final)
11077 (if (and (boundp 'org-time-was-given) org-time-was-given)
11078 (format "%04d-%02d-%02d %02d:%02d"
11079 (nth 5 final) (nth 4 final) (nth 3 final)
11080 (nth 2 final) (nth 1 final))
11081 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11082 (defvar def)
11083 (defvar defdecode)
11084 (defvar with-time)
11085 (defun org-read-date-display ()
11086 "Display the current date prompt interpretation in the minibuffer."
11087 (when org-read-date-display-live
11088 (when org-read-date-overlay
11089 (org-delete-overlay org-read-date-overlay))
11090 (let ((p (point)))
11091 (end-of-line 1)
11092 (while (not (equal (buffer-substring
11093 (max (point-min) (- (point) 4)) (point))
11094 " "))
11095 (insert " "))
11096 (goto-char p))
11097 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11098 " " (or org-ans1 org-ans2)))
11099 (org-end-time-was-given nil)
11100 (f (org-read-date-analyze ans def defdecode))
11101 (fmts (if org-dcst
11102 org-time-stamp-custom-formats
11103 org-time-stamp-formats))
11104 (fmt (if (or with-time
11105 (and (boundp 'org-time-was-given) org-time-was-given))
11106 (cdr fmts)
11107 (car fmts)))
11108 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11109 (when (and org-end-time-was-given
11110 (string-match org-plain-time-of-day-regexp txt))
11111 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11112 org-end-time-was-given
11113 (substring txt (match-end 0)))))
11114 (setq org-read-date-overlay
11115 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11116 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11117
11118 (defun org-read-date-analyze (ans def defdecode)
11119 "Analyse the combined answer of the date prompt."
11120 ;; FIXME: cleanup and comment
11121 (let (delta deltan deltaw deltadef year month day
11122 hour minute second wday pm h2 m2 tl wday1
11123 iso-year iso-weekday iso-week iso-year iso-date)
11124
11125 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11126 (setq ans "+0"))
11127
11128 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11129 (setq ans (replace-match "" t t ans)
11130 deltan (car delta)
11131 deltaw (nth 1 delta)
11132 deltadef (nth 2 delta)))
11133
11134 ;; Check if there is an iso week date in there
11135 ;; If yes, sore the info and postpone interpreting it until the rest
11136 ;; of the parsing is done
11137 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11138 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11139 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11140 iso-week (string-to-number (match-string 2 ans)))
11141 (setq ans (replace-match "" t t ans)))
11142
11143 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11144 (when (string-match
11145 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11146 (setq year (if (match-end 2)
11147 (string-to-number (match-string 2 ans))
11148 (string-to-number (format-time-string "%Y")))
11149 month (string-to-number (match-string 3 ans))
11150 day (string-to-number (match-string 4 ans)))
11151 (if (< year 100) (setq year (+ 2000 year)))
11152 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11153 t nil ans)))
11154 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11155 ;; If there is a time with am/pm, and *no* time without it, we convert
11156 ;; so that matching will be successful.
11157 (loop for i from 1 to 2 do ; twice, for end time as well
11158 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11159 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11160 (setq hour (string-to-number (match-string 1 ans))
11161 minute (if (match-end 3)
11162 (string-to-number (match-string 3 ans))
11163 0)
11164 pm (equal ?p
11165 (string-to-char (downcase (match-string 4 ans)))))
11166 (if (and (= hour 12) (not pm))
11167 (setq hour 0)
11168 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11169 (setq ans (replace-match (format "%02d:%02d" hour minute)
11170 t t ans))))
11171
11172 ;; Check if a time range is given as a duration
11173 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11174 (setq hour (string-to-number (match-string 1 ans))
11175 h2 (+ hour (string-to-number (match-string 3 ans)))
11176 minute (string-to-number (match-string 2 ans))
11177 m2 (+ minute (if (match-end 5) (string-to-number
11178 (match-string 5 ans))0)))
11179 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11180 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11181 t t ans)))
11182
11183 ;; Check if there is a time range
11184 (when (boundp 'org-end-time-was-given)
11185 (setq org-time-was-given nil)
11186 (when (and (string-match org-plain-time-of-day-regexp ans)
11187 (match-end 8))
11188 (setq org-end-time-was-given (match-string 8 ans))
11189 (setq ans (concat (substring ans 0 (match-beginning 7))
11190 (substring ans (match-end 7))))))
11191
11192 (setq tl (parse-time-string ans)
11193 day (or (nth 3 tl) (nth 3 defdecode))
11194 month (or (nth 4 tl)
11195 (if (and org-read-date-prefer-future
11196 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11197 (1+ (nth 4 defdecode))
11198 (nth 4 defdecode)))
11199 year (or (nth 5 tl)
11200 (if (and org-read-date-prefer-future
11201 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11202 (1+ (nth 5 defdecode))
11203 (nth 5 defdecode)))
11204 hour (or (nth 2 tl) (nth 2 defdecode))
11205 minute (or (nth 1 tl) (nth 1 defdecode))
11206 second (or (nth 0 tl) 0)
11207 wday (nth 6 tl))
11208
11209 ;; Special date definitions below
11210 (cond
11211 (iso-week
11212 ;; There was an iso week
11213 (setq year (or iso-year year)
11214 day (or iso-weekday wday 1)
11215 wday nil ; to make sure that the trigger below does not match
11216 iso-date (calendar-gregorian-from-absolute
11217 (calendar-absolute-from-iso
11218 (list iso-week day year))))
11219 ; FIXME: Should we also push ISO weeks into the future?
11220 ; (when (and org-read-date-prefer-future
11221 ; (not iso-year)
11222 ; (< (calendar-absolute-from-gregorian iso-date)
11223 ; (time-to-days (current-time))))
11224 ; (setq year (1+ year)
11225 ; iso-date (calendar-gregorian-from-absolute
11226 ; (calendar-absolute-from-iso
11227 ; (list iso-week day year)))))
11228 (setq month (car iso-date)
11229 year (nth 2 iso-date)
11230 day (nth 1 iso-date)))
11231 (deltan
11232 (unless deltadef
11233 (let ((now (decode-time (current-time))))
11234 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11235 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11236 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11237 ((equal deltaw "m") (setq month (+ month deltan)))
11238 ((equal deltaw "y") (setq year (+ year deltan)))))
11239 ((and wday (not (nth 3 tl)))
11240 ;; Weekday was given, but no day, so pick that day in the week
11241 ;; on or after the derived date.
11242 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11243 (unless (equal wday wday1)
11244 (setq day (+ day (% (- wday wday1 -7) 7))))))
11245 (if (and (boundp 'org-time-was-given)
11246 (nth 2 tl))
11247 (setq org-time-was-given t))
11248 (if (< year 100) (setq year (+ 2000 year)))
11249 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11250 (list second minute hour day month year)))
11251
11252 (defvar parse-time-weekdays)
11253
11254 (defun org-read-date-get-relative (s today default)
11255 "Check string S for special relative date string.
11256 TODAY and DEFAULT are internal times, for today and for a default.
11257 Return shift list (N what def-flag)
11258 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11259 N is the number of WHATs to shift.
11260 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11261 the DEFAULT date rather than TODAY."
11262 (when (and
11263 (string-match
11264 (concat
11265 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11266 "\\([0-9]+\\)?"
11267 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11268 "\\([ \t]\\|$\\)") s)
11269 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11270 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11271 (string-to-char (substring (match-string 1 s) -1))
11272 ?+))
11273 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11274 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11275 (what (if (match-end 3) (match-string 3 s) "d"))
11276 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11277 (date (if rel default today))
11278 (wday (nth 6 (decode-time date)))
11279 delta)
11280 (if wday1
11281 (progn
11282 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11283 (if (= dir ?-) (setq delta (- delta 7)))
11284 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11285 (list delta "d" rel))
11286 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11287
11288 (defun org-eval-in-calendar (form &optional keepdate)
11289 "Eval FORM in the calendar window and return to current window.
11290 Also, store the cursor date in variable org-ans2."
11291 (let ((sw (selected-window)))
11292 (select-window (get-buffer-window "*Calendar*"))
11293 (eval form)
11294 (when (and (not keepdate) (calendar-cursor-to-date))
11295 (let* ((date (calendar-cursor-to-date))
11296 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11297 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11298 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11299 (select-window sw)))
11300
11301 (defun org-calendar-select ()
11302 "Return to `org-read-date' with the date currently selected.
11303 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11304 (interactive)
11305 (when (calendar-cursor-to-date)
11306 (let* ((date (calendar-cursor-to-date))
11307 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11308 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11309 (if (active-minibuffer-window) (exit-minibuffer))))
11310
11311 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11312 "Insert a date stamp for the date given by the internal TIME.
11313 WITH-HM means, use the stamp format that includes the time of the day.
11314 INACTIVE means use square brackets instead of angular ones, so that the
11315 stamp will not contribute to the agenda.
11316 PRE and POST are optional strings to be inserted before and after the
11317 stamp.
11318 The command returns the inserted time stamp."
11319 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11320 stamp)
11321 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11322 (insert-before-markers (or pre ""))
11323 (insert-before-markers (setq stamp (format-time-string fmt time)))
11324 (when (listp extra)
11325 (setq extra (car extra))
11326 (if (and (stringp extra)
11327 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11328 (setq extra (format "-%02d:%02d"
11329 (string-to-number (match-string 1 extra))
11330 (string-to-number (match-string 2 extra))))
11331 (setq extra nil)))
11332 (when extra
11333 (backward-char 1)
11334 (insert-before-markers extra)
11335 (forward-char 1))
11336 (insert-before-markers (or post ""))
11337 (setq org-last-inserted-timestamp stamp)))
11338
11339 (defun org-toggle-time-stamp-overlays ()
11340 "Toggle the use of custom time stamp formats."
11341 (interactive)
11342 (setq org-display-custom-times (not org-display-custom-times))
11343 (unless org-display-custom-times
11344 (let ((p (point-min)) (bmp (buffer-modified-p)))
11345 (while (setq p (next-single-property-change p 'display))
11346 (if (and (get-text-property p 'display)
11347 (eq (get-text-property p 'face) 'org-date))
11348 (remove-text-properties
11349 p (setq p (next-single-property-change p 'display))
11350 '(display t))))
11351 (set-buffer-modified-p bmp)))
11352 (if (featurep 'xemacs)
11353 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11354 (org-restart-font-lock)
11355 (setq org-table-may-need-update t)
11356 (if org-display-custom-times
11357 (message "Time stamps are overlayed with custom format")
11358 (message "Time stamp overlays removed")))
11359
11360 (defun org-display-custom-time (beg end)
11361 "Overlay modified time stamp format over timestamp between BEG and END."
11362 (let* ((ts (buffer-substring beg end))
11363 t1 w1 with-hm tf time str w2 (off 0))
11364 (save-match-data
11365 (setq t1 (org-parse-time-string ts t))
11366 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11367 (setq off (- (match-end 0) (match-beginning 0)))))
11368 (setq end (- end off))
11369 (setq w1 (- end beg)
11370 with-hm (and (nth 1 t1) (nth 2 t1))
11371 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11372 time (org-fix-decoded-time t1)
11373 str (org-add-props
11374 (format-time-string
11375 (substring tf 1 -1) (apply 'encode-time time))
11376 nil 'mouse-face 'highlight)
11377 w2 (length str))
11378 (if (not (= w2 w1))
11379 (add-text-properties (1+ beg) (+ 2 beg)
11380 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11381 (if (featurep 'xemacs)
11382 (progn
11383 (put-text-property beg end 'invisible t)
11384 (put-text-property beg end 'end-glyph (make-glyph str)))
11385 (put-text-property beg end 'display str))))
11386
11387 (defun org-translate-time (string)
11388 "Translate all timestamps in STRING to custom format.
11389 But do this only if the variable `org-display-custom-times' is set."
11390 (when org-display-custom-times
11391 (save-match-data
11392 (let* ((start 0)
11393 (re org-ts-regexp-both)
11394 t1 with-hm inactive tf time str beg end)
11395 (while (setq start (string-match re string start))
11396 (setq beg (match-beginning 0)
11397 end (match-end 0)
11398 t1 (save-match-data
11399 (org-parse-time-string (substring string beg end) t))
11400 with-hm (and (nth 1 t1) (nth 2 t1))
11401 inactive (equal (substring string beg (1+ beg)) "[")
11402 tf (funcall (if with-hm 'cdr 'car)
11403 org-time-stamp-custom-formats)
11404 time (org-fix-decoded-time t1)
11405 str (format-time-string
11406 (concat
11407 (if inactive "[" "<") (substring tf 1 -1)
11408 (if inactive "]" ">"))
11409 (apply 'encode-time time))
11410 string (replace-match str t t string)
11411 start (+ start (length str)))))))
11412 string)
11413
11414 (defun org-fix-decoded-time (time)
11415 "Set 0 instead of nil for the first 6 elements of time.
11416 Don't touch the rest."
11417 (let ((n 0))
11418 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11419
11420 (defun org-days-to-time (timestamp-string)
11421 "Difference between TIMESTAMP-STRING and now in days."
11422 (- (time-to-days (org-time-string-to-time timestamp-string))
11423 (time-to-days (current-time))))
11424
11425 (defun org-deadline-close (timestamp-string &optional ndays)
11426 "Is the time in TIMESTAMP-STRING close to the current date?"
11427 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11428 (and (< (org-days-to-time timestamp-string) ndays)
11429 (not (org-entry-is-done-p))))
11430
11431 (defun org-get-wdays (ts)
11432 "Get the deadline lead time appropriate for timestring TS."
11433 (cond
11434 ((<= org-deadline-warning-days 0)
11435 ;; 0 or negative, enforce this value no matter what
11436 (- org-deadline-warning-days))
11437 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11438 ;; lead time is specified.
11439 (floor (* (string-to-number (match-string 1 ts))
11440 (cdr (assoc (match-string 2 ts)
11441 '(("d" . 1) ("w" . 7)
11442 ("m" . 30.4) ("y" . 365.25)))))))
11443 ;; go for the default.
11444 (t org-deadline-warning-days)))
11445
11446 (defun org-calendar-select-mouse (ev)
11447 "Return to `org-read-date' with the date currently selected.
11448 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11449 (interactive "e")
11450 (mouse-set-point ev)
11451 (when (calendar-cursor-to-date)
11452 (let* ((date (calendar-cursor-to-date))
11453 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11454 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11455 (if (active-minibuffer-window) (exit-minibuffer))))
11456
11457 (defun org-check-deadlines (ndays)
11458 "Check if there are any deadlines due or past due.
11459 A deadline is considered due if it happens within `org-deadline-warning-days'
11460 days from today's date. If the deadline appears in an entry marked DONE,
11461 it is not shown. The prefix arg NDAYS can be used to test that many
11462 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11463 (interactive "P")
11464 (let* ((org-warn-days
11465 (cond
11466 ((equal ndays '(4)) 100000)
11467 (ndays (prefix-numeric-value ndays))
11468 (t (abs org-deadline-warning-days))))
11469 (case-fold-search nil)
11470 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11471 (callback
11472 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11473
11474 (message "%d deadlines past-due or due within %d days"
11475 (org-occur regexp nil callback)
11476 org-warn-days)))
11477
11478 (defun org-check-before-date (date)
11479 "Check if there are deadlines or scheduled entries before DATE."
11480 (interactive (list (org-read-date)))
11481 (let ((case-fold-search nil)
11482 (regexp (concat "\\<\\(" org-deadline-string
11483 "\\|" org-scheduled-string
11484 "\\) *<\\([^>]+\\)>"))
11485 (callback
11486 (lambda () (time-less-p
11487 (org-time-string-to-time (match-string 2))
11488 (org-time-string-to-time date)))))
11489 (message "%d entries before %s"
11490 (org-occur regexp nil callback) date)))
11491
11492 (defun org-evaluate-time-range (&optional to-buffer)
11493 "Evaluate a time range by computing the difference between start and end.
11494 Normally the result is just printed in the echo area, but with prefix arg
11495 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11496 If the time range is actually in a table, the result is inserted into the
11497 next column.
11498 For time difference computation, a year is assumed to be exactly 365
11499 days in order to avoid rounding problems."
11500 (interactive "P")
11501 (or
11502 (org-clock-update-time-maybe)
11503 (save-excursion
11504 (unless (org-at-date-range-p t)
11505 (goto-char (point-at-bol))
11506 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11507 (if (not (org-at-date-range-p t))
11508 (error "Not at a time-stamp range, and none found in current line")))
11509 (let* ((ts1 (match-string 1))
11510 (ts2 (match-string 2))
11511 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11512 (match-end (match-end 0))
11513 (time1 (org-time-string-to-time ts1))
11514 (time2 (org-time-string-to-time ts2))
11515 (t1 (time-to-seconds time1))
11516 (t2 (time-to-seconds time2))
11517 (diff (abs (- t2 t1)))
11518 (negative (< (- t2 t1) 0))
11519 ;; (ys (floor (* 365 24 60 60)))
11520 (ds (* 24 60 60))
11521 (hs (* 60 60))
11522 (fy "%dy %dd %02d:%02d")
11523 (fy1 "%dy %dd")
11524 (fd "%dd %02d:%02d")
11525 (fd1 "%dd")
11526 (fh "%02d:%02d")
11527 y d h m align)
11528 (if havetime
11529 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11530 y 0
11531 d (floor (/ diff ds)) diff (mod diff ds)
11532 h (floor (/ diff hs)) diff (mod diff hs)
11533 m (floor (/ diff 60)))
11534 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11535 y 0
11536 d (floor (+ (/ diff ds) 0.5))
11537 h 0 m 0))
11538 (if (not to-buffer)
11539 (message "%s" (org-make-tdiff-string y d h m))
11540 (if (org-at-table-p)
11541 (progn
11542 (goto-char match-end)
11543 (setq align t)
11544 (and (looking-at " *|") (goto-char (match-end 0))))
11545 (goto-char match-end))
11546 (if (looking-at
11547 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11548 (replace-match ""))
11549 (if negative (insert " -"))
11550 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11551 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11552 (insert " " (format fh h m))))
11553 (if align (org-table-align))
11554 (message "Time difference inserted")))))
11555
11556 (defun org-make-tdiff-string (y d h m)
11557 (let ((fmt "")
11558 (l nil))
11559 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11560 l (push y l)))
11561 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11562 l (push d l)))
11563 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11564 l (push h l)))
11565 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11566 l (push m l)))
11567 (apply 'format fmt (nreverse l))))
11568
11569 (defun org-time-string-to-time (s)
11570 (apply 'encode-time (org-parse-time-string s)))
11571
11572 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11573 "Convert a time stamp to an absolute day number.
11574 If there is a specifyer for a cyclic time stamp, get the closest date to
11575 DAYNR.
11576 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11577 (cond
11578 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11579 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11580 daynr
11581 (+ daynr 1000)))
11582 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11583 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11584 (time-to-days (current-time))) (match-string 0 s)
11585 prefer show-all))
11586 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11587
11588 (defun org-days-to-iso-week (days)
11589 "Return the iso week number."
11590 (require 'cal-iso)
11591 (car (calendar-iso-from-absolute days)))
11592
11593 (defun org-small-year-to-year (year)
11594 "Convert 2-digit years into 4-digit years.
11595 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11596 The year 2000 cannot be abbreviated. Any year larger than 99
11597 is returned unchanged."
11598 (if (< year 38)
11599 (setq year (+ 2000 year))
11600 (if (< year 100)
11601 (setq year (+ 1900 year))))
11602 year)
11603
11604 (defun org-time-from-absolute (d)
11605 "Return the time corresponding to date D.
11606 D may be an absolute day number, or a calendar-type list (month day year)."
11607 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11608 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11609
11610 (defun org-calendar-holiday ()
11611 "List of holidays, for Diary display in Org-mode."
11612 (require 'holidays)
11613 (let ((hl (funcall
11614 (if (fboundp 'calendar-check-holidays)
11615 'calendar-check-holidays 'check-calendar-holidays) date)))
11616 (if hl (mapconcat 'identity hl "; "))))
11617
11618 (defun org-diary-sexp-entry (sexp entry date)
11619 "Process a SEXP diary ENTRY for DATE."
11620 (require 'diary-lib)
11621 (let ((result (if calendar-debug-sexp
11622 (let ((stack-trace-on-error t))
11623 (eval (car (read-from-string sexp))))
11624 (condition-case nil
11625 (eval (car (read-from-string sexp)))
11626 (error
11627 (beep)
11628 (message "Bad sexp at line %d in %s: %s"
11629 (org-current-line)
11630 (buffer-file-name) sexp)
11631 (sleep-for 2))))))
11632 (cond ((stringp result) result)
11633 ((and (consp result)
11634 (stringp (cdr result))) (cdr result))
11635 (result entry)
11636 (t nil))))
11637
11638 (defun org-diary-to-ical-string (frombuf)
11639 "Get iCalendar entries from diary entries in buffer FROMBUF.
11640 This uses the icalendar.el library."
11641 (let* ((tmpdir (if (featurep 'xemacs)
11642 (temp-directory)
11643 temporary-file-directory))
11644 (tmpfile (make-temp-name
11645 (expand-file-name "orgics" tmpdir)))
11646 buf rtn b e)
11647 (save-excursion
11648 (set-buffer frombuf)
11649 (icalendar-export-region (point-min) (point-max) tmpfile)
11650 (setq buf (find-buffer-visiting tmpfile))
11651 (set-buffer buf)
11652 (goto-char (point-min))
11653 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11654 (setq b (match-beginning 0)))
11655 (goto-char (point-max))
11656 (if (re-search-backward "^END:VEVENT" nil t)
11657 (setq e (match-end 0)))
11658 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11659 (kill-buffer buf)
11660 (delete-file tmpfile)
11661 rtn))
11662
11663 (defun org-closest-date (start current change prefer show-all)
11664 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11665 When PREFER is `past' return a date that is either CURRENT or past.
11666 When PREFER is `future', return a date that is either CURRENT or future.
11667 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11668 ;; Make the proper lists from the dates
11669 (catch 'exit
11670 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11671 dn dw sday cday n1 n2 n0
11672 d m y y1 y2 date1 date2 nmonths nm ny m2)
11673
11674 (setq start (org-date-to-gregorian start)
11675 current (org-date-to-gregorian
11676 (if show-all
11677 current
11678 (time-to-days (current-time))))
11679 sday (calendar-absolute-from-gregorian start)
11680 cday (calendar-absolute-from-gregorian current))
11681
11682 (if (<= cday sday) (throw 'exit sday))
11683
11684 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11685 (setq dn (string-to-number (match-string 1 change))
11686 dw (cdr (assoc (match-string 2 change) a1)))
11687 (error "Invalid change specifyer: %s" change))
11688 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11689 (cond
11690 ((eq dw 'day)
11691 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11692 n2 (+ n1 dn)))
11693 ((eq dw 'year)
11694 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11695 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11696 (setq date1 (list m d y1)
11697 n1 (calendar-absolute-from-gregorian date1)
11698 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11699 n2 (calendar-absolute-from-gregorian date2)))
11700 ((eq dw 'month)
11701 ;; approx number of month between the two dates
11702 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11703 ;; How often does dn fit in there?
11704 (setq d (nth 1 start) m (car start) y (nth 2 start)
11705 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11706 m (+ m nm)
11707 ny (floor (/ m 12))
11708 y (+ y ny)
11709 m (- m (* ny 12)))
11710 (while (> m 12) (setq m (- m 12) y (1+ y)))
11711 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11712 (setq m2 (+ m dn) y2 y)
11713 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11714 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11715 (while (<= n2 cday)
11716 (setq n1 n2 m m2 y y2)
11717 (setq m2 (+ m dn) y2 y)
11718 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11719 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11720 ;; Make sure n1 is the earlier date
11721 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
11722 (if show-all
11723 (cond
11724 ((eq prefer 'past) n1)
11725 ((eq prefer 'future) (if (= cday n1) n1 n2))
11726 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11727 (cond
11728 ((eq prefer 'past) n1)
11729 ((eq prefer 'future) (if (= cday n1) n1 n2))
11730 (t (if (= cday n1) n1 n2)))))))
11731
11732 (defun org-date-to-gregorian (date)
11733 "Turn any specification of DATE into a gregorian date for the calendar."
11734 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11735 ((and (listp date) (= (length date) 3)) date)
11736 ((stringp date)
11737 (setq date (org-parse-time-string date))
11738 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11739 ((listp date)
11740 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11741
11742 (defun org-parse-time-string (s &optional nodefault)
11743 "Parse the standard Org-mode time string.
11744 This should be a lot faster than the normal `parse-time-string'.
11745 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11746 hour and minute fields will be nil if not given."
11747 (if (string-match org-ts-regexp0 s)
11748 (list 0
11749 (if (or (match-beginning 8) (not nodefault))
11750 (string-to-number (or (match-string 8 s) "0")))
11751 (if (or (match-beginning 7) (not nodefault))
11752 (string-to-number (or (match-string 7 s) "0")))
11753 (string-to-number (match-string 4 s))
11754 (string-to-number (match-string 3 s))
11755 (string-to-number (match-string 2 s))
11756 nil nil nil)
11757 (make-list 9 0)))
11758
11759 (defun org-timestamp-up (&optional arg)
11760 "Increase the date item at the cursor by one.
11761 If the cursor is on the year, change the year. If it is on the month or
11762 the day, change that.
11763 With prefix ARG, change by that many units."
11764 (interactive "p")
11765 (org-timestamp-change (prefix-numeric-value arg)))
11766
11767 (defun org-timestamp-down (&optional arg)
11768 "Decrease the date item at the cursor by one.
11769 If the cursor is on the year, change the year. If it is on the month or
11770 the day, change that.
11771 With prefix ARG, change by that many units."
11772 (interactive "p")
11773 (org-timestamp-change (- (prefix-numeric-value arg))))
11774
11775 (defun org-timestamp-up-day (&optional arg)
11776 "Increase the date in the time stamp by one day.
11777 With prefix ARG, change that many days."
11778 (interactive "p")
11779 (if (and (not (org-at-timestamp-p t))
11780 (org-on-heading-p))
11781 (org-todo 'up)
11782 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11783
11784 (defun org-timestamp-down-day (&optional arg)
11785 "Decrease the date in the time stamp by one day.
11786 With prefix ARG, change that many days."
11787 (interactive "p")
11788 (if (and (not (org-at-timestamp-p t))
11789 (org-on-heading-p))
11790 (org-todo 'down)
11791 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11792
11793 (defun org-at-timestamp-p (&optional inactive-ok)
11794 "Determine if the cursor is in or at a timestamp."
11795 (interactive)
11796 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11797 (pos (point))
11798 (ans (or (looking-at tsr)
11799 (save-excursion
11800 (skip-chars-backward "^[<\n\r\t")
11801 (if (> (point) (point-min)) (backward-char 1))
11802 (and (looking-at tsr)
11803 (> (- (match-end 0) pos) -1))))))
11804 (and ans
11805 (boundp 'org-ts-what)
11806 (setq org-ts-what
11807 (cond
11808 ((= pos (match-beginning 0)) 'bracket)
11809 ((= pos (1- (match-end 0))) 'bracket)
11810 ((org-pos-in-match-range pos 2) 'year)
11811 ((org-pos-in-match-range pos 3) 'month)
11812 ((org-pos-in-match-range pos 7) 'hour)
11813 ((org-pos-in-match-range pos 8) 'minute)
11814 ((or (org-pos-in-match-range pos 4)
11815 (org-pos-in-match-range pos 5)) 'day)
11816 ((and (> pos (or (match-end 8) (match-end 5)))
11817 (< pos (match-end 0)))
11818 (- pos (or (match-end 8) (match-end 5))))
11819 (t 'day))))
11820 ans))
11821
11822 (defun org-toggle-timestamp-type ()
11823 "Toggle the type (<active> or [inactive]) of a time stamp."
11824 (interactive)
11825 (when (org-at-timestamp-p t)
11826 (let ((beg (match-beginning 0)) (end (match-end 0))
11827 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11828 (save-excursion
11829 (goto-char beg)
11830 (while (re-search-forward "[][<>]" end t)
11831 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11832 t t)))
11833 (message "Timestamp is now %sactive"
11834 (if (equal (char-after beg) ?<) "" "in")))))
11835
11836 (defun org-timestamp-change (n &optional what)
11837 "Change the date in the time stamp at point.
11838 The date will be changed by N times WHAT. WHAT can be `day', `month',
11839 `year', `minute', `second'. If WHAT is not given, the cursor position
11840 in the timestamp determines what will be changed."
11841 (let ((pos (point))
11842 with-hm inactive
11843 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11844 org-ts-what
11845 extra rem
11846 ts time time0)
11847 (if (not (org-at-timestamp-p t))
11848 (error "Not at a timestamp"))
11849 (if (and (not what) (eq org-ts-what 'bracket))
11850 (org-toggle-timestamp-type)
11851 (if (and (not what) (not (eq org-ts-what 'day))
11852 org-display-custom-times
11853 (get-text-property (point) 'display)
11854 (not (get-text-property (1- (point)) 'display)))
11855 (setq org-ts-what 'day))
11856 (setq org-ts-what (or what org-ts-what)
11857 inactive (= (char-after (match-beginning 0)) ?\[)
11858 ts (match-string 0))
11859 (replace-match "")
11860 (if (string-match
11861 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11862 ts)
11863 (setq extra (match-string 1 ts)))
11864 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11865 (setq with-hm t))
11866 (setq time0 (org-parse-time-string ts))
11867 (when (and (eq org-ts-what 'minute)
11868 (eq current-prefix-arg nil))
11869 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11870 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11871 (setcar (cdr time0) (+ (nth 1 time0)
11872 (if (> n 0) (- rem) (- dm rem))))))
11873 (setq time
11874 (encode-time (or (car time0) 0)
11875 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11876 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11877 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11878 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11879 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11880 (nthcdr 6 time0)))
11881 (when (integerp org-ts-what)
11882 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11883 (if (eq what 'calendar)
11884 (let ((cal-date (org-get-date-from-calendar)))
11885 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11886 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11887 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11888 (setcar time0 (or (car time0) 0))
11889 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11890 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11891 (setq time (apply 'encode-time time0))))
11892 (setq org-last-changed-timestamp
11893 (org-insert-time-stamp time with-hm inactive nil nil extra))
11894 (org-clock-update-time-maybe)
11895 (goto-char pos)
11896 ;; Try to recenter the calendar window, if any
11897 (if (and org-calendar-follow-timestamp-change
11898 (get-buffer-window "*Calendar*" t)
11899 (memq org-ts-what '(day month year)))
11900 (org-recenter-calendar (time-to-days time))))))
11901
11902 (defun org-modify-ts-extra (s pos n dm)
11903 "Change the different parts of the lead-time and repeat fields in timestamp."
11904 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11905 ng h m new rem)
11906 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11907 (cond
11908 ((or (org-pos-in-match-range pos 2)
11909 (org-pos-in-match-range pos 3))
11910 (setq m (string-to-number (match-string 3 s))
11911 h (string-to-number (match-string 2 s)))
11912 (if (org-pos-in-match-range pos 2)
11913 (setq h (+ h n))
11914 (setq n (* dm (org-no-warnings (signum n))))
11915 (when (not (= 0 (setq rem (% m dm))))
11916 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11917 (setq m (+ m n)))
11918 (if (< m 0) (setq m (+ m 60) h (1- h)))
11919 (if (> m 59) (setq m (- m 60) h (1+ h)))
11920 (setq h (min 24 (max 0 h)))
11921 (setq ng 1 new (format "-%02d:%02d" h m)))
11922 ((org-pos-in-match-range pos 6)
11923 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11924 ((org-pos-in-match-range pos 5)
11925 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11926
11927 ((org-pos-in-match-range pos 9)
11928 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11929 ((org-pos-in-match-range pos 8)
11930 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11931
11932 (when ng
11933 (setq s (concat
11934 (substring s 0 (match-beginning ng))
11935 new
11936 (substring s (match-end ng))))))
11937 s))
11938
11939 (defun org-recenter-calendar (date)
11940 "If the calendar is visible, recenter it to DATE."
11941 (let* ((win (selected-window))
11942 (cwin (get-buffer-window "*Calendar*" t))
11943 (calendar-move-hook nil))
11944 (when cwin
11945 (select-window cwin)
11946 (calendar-goto-date (if (listp date) date
11947 (calendar-gregorian-from-absolute date)))
11948 (select-window win))))
11949
11950 (defun org-goto-calendar (&optional arg)
11951 "Go to the Emacs calendar at the current date.
11952 If there is a time stamp in the current line, go to that date.
11953 A prefix ARG can be used to force the current date."
11954 (interactive "P")
11955 (let ((tsr org-ts-regexp) diff
11956 (calendar-move-hook nil)
11957 (calendar-view-holidays-initially-flag nil)
11958 (view-calendar-holidays-initially nil)
11959 (calendar-view-diary-initially-flag nil)
11960 (view-diary-entries-initially nil))
11961 (if (or (org-at-timestamp-p)
11962 (save-excursion
11963 (beginning-of-line 1)
11964 (looking-at (concat ".*" tsr))))
11965 (let ((d1 (time-to-days (current-time)))
11966 (d2 (time-to-days
11967 (org-time-string-to-time (match-string 1)))))
11968 (setq diff (- d2 d1))))
11969 (calendar)
11970 (calendar-goto-today)
11971 (if (and diff (not arg)) (calendar-forward-day diff))))
11972
11973 (defun org-get-date-from-calendar ()
11974 "Return a list (month day year) of date at point in calendar."
11975 (with-current-buffer "*Calendar*"
11976 (save-match-data
11977 (calendar-cursor-to-date))))
11978
11979 (defun org-date-from-calendar ()
11980 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11981 If there is already a time stamp at the cursor position, update it."
11982 (interactive)
11983 (if (org-at-timestamp-p t)
11984 (org-timestamp-change 0 'calendar)
11985 (let ((cal-date (org-get-date-from-calendar)))
11986 (org-insert-time-stamp
11987 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11988
11989 (defun org-minutes-to-hh:mm-string (m)
11990 "Compute H:MM from a number of minutes."
11991 (let ((h (/ m 60)))
11992 (setq m (- m (* 60 h)))
11993 (format org-time-clocksum-format h m)))
11994
11995 (defun org-hh:mm-string-to-minutes (s)
11996 "Convert a string H:MM to a number of minutes."
11997 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11998 (+ (* (string-to-number (match-string 1 s)) 60)
11999 (string-to-number (match-string 2 s)))
12000 0))
12001
12002 ;;;; Agenda files
12003
12004 ;;;###autoload
12005 (defun org-iswitchb (&optional arg)
12006 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12007 With a prefix argument, restrict available to files.
12008 With two prefix arguments, restrict available buffers to agenda files.
12009
12010 Due to some yet unresolved reason, the global function
12011 `iswitchb-mode' needs to be active for this function to work."
12012 (interactive "P")
12013 (require 'iswitchb)
12014 (let ((enabled iswitchb-mode) blist)
12015 (or enabled (iswitchb-mode 1))
12016 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12017 ((equal arg '(16)) (org-buffer-list 'agenda))
12018 (t (org-buffer-list))))
12019 (unwind-protect
12020 (let ((iswitchb-make-buflist-hook
12021 (lambda ()
12022 (setq iswitchb-temp-buflist
12023 (mapcar 'buffer-name blist)))))
12024 (switch-to-buffer
12025 (iswitchb-read-buffer
12026 "Switch-to: " nil t))
12027 (or enabled (iswitchb-mode -1))))))
12028
12029 ;;;###autoload
12030 (defun org-ido-switchb (&optional arg)
12031 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12032 With a prefix argument, restrict available to files.
12033 With two prefix arguments, restrict available buffers to agenda files."
12034 (interactive "P")
12035 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12036 ((equal arg '(16)) (org-buffer-list 'agenda))
12037 (t (org-buffer-list)))))
12038 (switch-to-buffer
12039 (org-ido-completing-read "Org buffer: "
12040 (mapcar 'buffer-name blist)
12041 nil t))))
12042
12043 (defun org-buffer-list (&optional predicate exclude-tmp)
12044 "Return a list of Org buffers.
12045 PREDICATE can be `export', `files' or `agenda'.
12046
12047 export restrict the list to Export buffers.
12048 files restrict the list to buffers visiting Org files.
12049 agenda restrict the list to buffers visiting agenda files.
12050
12051 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12052 (let* ((bfn nil)
12053 (agenda-files (and (eq predicate 'agenda)
12054 (mapcar 'file-truename (org-agenda-files t))))
12055 (filter
12056 (cond
12057 ((eq predicate 'files)
12058 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12059 ((eq predicate 'export)
12060 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12061 ((eq predicate 'agenda)
12062 (lambda (b)
12063 (with-current-buffer b
12064 (and (eq major-mode 'org-mode)
12065 (setq bfn (buffer-file-name b))
12066 (member (file-truename bfn) agenda-files)))))
12067 (t (lambda (b) (with-current-buffer b
12068 (or (eq major-mode 'org-mode)
12069 (string-match "\*Org .*Export"
12070 (buffer-name b)))))))))
12071 (delq nil
12072 (mapcar
12073 (lambda(b)
12074 (if (and (funcall filter b)
12075 (or (not exclude-tmp)
12076 (not (string-match "tmp" (buffer-name b)))))
12077 b
12078 nil))
12079 (buffer-list)))))
12080
12081 (defun org-agenda-files (&optional unrestricted archives)
12082 "Get the list of agenda files.
12083 Optional UNRESTRICTED means return the full list even if a restriction
12084 is currently in place.
12085 When ARCHIVES is t, include all archive files hat are really being
12086 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12087 `org-agenda-archives-mode' is t."
12088 (let ((files
12089 (cond
12090 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12091 ((stringp org-agenda-files) (org-read-agenda-file-list))
12092 ((listp org-agenda-files) org-agenda-files)
12093 (t (error "Invalid value of `org-agenda-files'")))))
12094 (setq files (apply 'append
12095 (mapcar (lambda (f)
12096 (if (file-directory-p f)
12097 (directory-files
12098 f t org-agenda-file-regexp)
12099 (list f)))
12100 files)))
12101 (when org-agenda-skip-unavailable-files
12102 (setq files (delq nil
12103 (mapcar (function
12104 (lambda (file)
12105 (and (file-readable-p file) file)))
12106 files))))
12107 (when (or (eq archives t)
12108 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12109 (setq files (org-add-archive-files files)))
12110 files))
12111
12112 (defun org-edit-agenda-file-list ()
12113 "Edit the list of agenda files.
12114 Depending on setup, this either uses customize to edit the variable
12115 `org-agenda-files', or it visits the file that is holding the list. In the
12116 latter case, the buffer is set up in a way that saving it automatically kills
12117 the buffer and restores the previous window configuration."
12118 (interactive)
12119 (if (stringp org-agenda-files)
12120 (let ((cw (current-window-configuration)))
12121 (find-file org-agenda-files)
12122 (org-set-local 'org-window-configuration cw)
12123 (org-add-hook 'after-save-hook
12124 (lambda ()
12125 (set-window-configuration
12126 (prog1 org-window-configuration
12127 (kill-buffer (current-buffer))))
12128 (org-install-agenda-files-menu)
12129 (message "New agenda file list installed"))
12130 nil 'local)
12131 (message "%s" (substitute-command-keys
12132 "Edit list and finish with \\[save-buffer]")))
12133 (customize-variable 'org-agenda-files)))
12134
12135 (defun org-store-new-agenda-file-list (list)
12136 "Set new value for the agenda file list and save it correctly."
12137 (if (stringp org-agenda-files)
12138 (let ((f org-agenda-files) b)
12139 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12140 (with-temp-file f
12141 (insert (mapconcat 'identity list "\n") "\n")))
12142 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12143 (setq org-agenda-files list)
12144 (customize-save-variable 'org-agenda-files org-agenda-files))))
12145
12146 (defun org-read-agenda-file-list ()
12147 "Read the list of agenda files from a file."
12148 (when (file-directory-p org-agenda-files)
12149 (error "`org-agenda-files' cannot be a single directory"))
12150 (when (stringp org-agenda-files)
12151 (with-temp-buffer
12152 (insert-file-contents org-agenda-files)
12153 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12154
12155
12156 ;;;###autoload
12157 (defun org-cycle-agenda-files ()
12158 "Cycle through the files in `org-agenda-files'.
12159 If the current buffer visits an agenda file, find the next one in the list.
12160 If the current buffer does not, find the first agenda file."
12161 (interactive)
12162 (let* ((fs (org-agenda-files t))
12163 (files (append fs (list (car fs))))
12164 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12165 file)
12166 (unless files (error "No agenda files"))
12167 (catch 'exit
12168 (while (setq file (pop files))
12169 (if (equal (file-truename file) tcf)
12170 (when (car files)
12171 (find-file (car files))
12172 (throw 'exit t))))
12173 (find-file (car fs)))
12174 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12175
12176 (defun org-agenda-file-to-front (&optional to-end)
12177 "Move/add the current file to the top of the agenda file list.
12178 If the file is not present in the list, it is added to the front. If it is
12179 present, it is moved there. With optional argument TO-END, add/move to the
12180 end of the list."
12181 (interactive "P")
12182 (let ((org-agenda-skip-unavailable-files nil)
12183 (file-alist (mapcar (lambda (x)
12184 (cons (file-truename x) x))
12185 (org-agenda-files t)))
12186 (ctf (file-truename buffer-file-name))
12187 x had)
12188 (setq x (assoc ctf file-alist) had x)
12189
12190 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12191 (if to-end
12192 (setq file-alist (append (delq x file-alist) (list x)))
12193 (setq file-alist (cons x (delq x file-alist))))
12194 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12195 (org-install-agenda-files-menu)
12196 (message "File %s to %s of agenda file list"
12197 (if had "moved" "added") (if to-end "end" "front"))))
12198
12199 (defun org-remove-file (&optional file)
12200 "Remove current file from the list of files in variable `org-agenda-files'.
12201 These are the files which are being checked for agenda entries.
12202 Optional argument FILE means, use this file instead of the current."
12203 (interactive)
12204 (let* ((org-agenda-skip-unavailable-files nil)
12205 (file (or file buffer-file-name))
12206 (true-file (file-truename file))
12207 (afile (abbreviate-file-name file))
12208 (files (delq nil (mapcar
12209 (lambda (x)
12210 (if (equal true-file
12211 (file-truename x))
12212 nil x))
12213 (org-agenda-files t)))))
12214 (if (not (= (length files) (length (org-agenda-files t))))
12215 (progn
12216 (org-store-new-agenda-file-list files)
12217 (org-install-agenda-files-menu)
12218 (message "Removed file: %s" afile))
12219 (message "File was not in list: %s (not removed)" afile))))
12220
12221 (defun org-file-menu-entry (file)
12222 (vector file (list 'find-file file) t))
12223
12224 (defun org-check-agenda-file (file)
12225 "Make sure FILE exists. If not, ask user what to do."
12226 (when (not (file-exists-p file))
12227 (message "non-existent file %s. [R]emove from list or [A]bort?"
12228 (abbreviate-file-name file))
12229 (let ((r (downcase (read-char-exclusive))))
12230 (cond
12231 ((equal r ?r)
12232 (org-remove-file file)
12233 (throw 'nextfile t))
12234 (t (error "Abort"))))))
12235
12236 (defun org-get-agenda-file-buffer (file)
12237 "Get a buffer visiting FILE. If the buffer needs to be created, add
12238 it to the list of buffers which might be released later."
12239 (let ((buf (org-find-base-buffer-visiting file)))
12240 (if buf
12241 buf ; just return it
12242 ;; Make a new buffer and remember it
12243 (setq buf (find-file-noselect file))
12244 (if buf (push buf org-agenda-new-buffers))
12245 buf)))
12246
12247 (defun org-release-buffers (blist)
12248 "Release all buffers in list, asking the user for confirmation when needed.
12249 When a buffer is unmodified, it is just killed. When modified, it is saved
12250 \(if the user agrees) and then killed."
12251 (let (buf file)
12252 (while (setq buf (pop blist))
12253 (setq file (buffer-file-name buf))
12254 (when (and (buffer-modified-p buf)
12255 file
12256 (y-or-n-p (format "Save file %s? " file)))
12257 (with-current-buffer buf (save-buffer)))
12258 (kill-buffer buf))))
12259
12260 (defun org-prepare-agenda-buffers (files)
12261 "Create buffers for all agenda files, protect archived trees and comments."
12262 (interactive)
12263 (let ((pa '(:org-archived t))
12264 (pc '(:org-comment t))
12265 (pall '(:org-archived t :org-comment t))
12266 (inhibit-read-only t)
12267 (rea (concat ":" org-archive-tag ":"))
12268 bmp file re)
12269 (save-excursion
12270 (save-restriction
12271 (while (setq file (pop files))
12272 (if (bufferp file)
12273 (set-buffer file)
12274 (org-check-agenda-file file)
12275 (set-buffer (org-get-agenda-file-buffer file)))
12276 (widen)
12277 (setq bmp (buffer-modified-p))
12278 (org-refresh-category-properties)
12279 (setq org-todo-keywords-for-agenda
12280 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12281 (setq org-done-keywords-for-agenda
12282 (append org-done-keywords-for-agenda org-done-keywords))
12283 (setq org-todo-keyword-alist-for-agenda
12284 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12285 (setq org-tag-alist-for-agenda
12286 (append org-tag-alist-for-agenda org-tag-alist))
12287
12288 (save-excursion
12289 (remove-text-properties (point-min) (point-max) pall)
12290 (when org-agenda-skip-archived-trees
12291 (goto-char (point-min))
12292 (while (re-search-forward rea nil t)
12293 (if (org-on-heading-p t)
12294 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12295 (goto-char (point-min))
12296 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12297 (while (re-search-forward re nil t)
12298 (add-text-properties
12299 (match-beginning 0) (org-end-of-subtree t) pc)))
12300 (set-buffer-modified-p bmp))))
12301 (setq org-todo-keyword-alist-for-agenda
12302 (org-uniquify org-todo-keyword-alist-for-agenda)
12303 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12304
12305 ;;;; Embedded LaTeX
12306
12307 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12308 "Keymap for the minor `org-cdlatex-mode'.")
12309
12310 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12311 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12312 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12313 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12314 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12315
12316 (defvar org-cdlatex-texmathp-advice-is-done nil
12317 "Flag remembering if we have applied the advice to texmathp already.")
12318
12319 (define-minor-mode org-cdlatex-mode
12320 "Toggle the minor `org-cdlatex-mode'.
12321 This mode supports entering LaTeX environment and math in LaTeX fragments
12322 in Org-mode.
12323 \\{org-cdlatex-mode-map}"
12324 nil " OCDL" nil
12325 (when org-cdlatex-mode (require 'cdlatex))
12326 (unless org-cdlatex-texmathp-advice-is-done
12327 (setq org-cdlatex-texmathp-advice-is-done t)
12328 (defadvice texmathp (around org-math-always-on activate)
12329 "Always return t in org-mode buffers.
12330 This is because we want to insert math symbols without dollars even outside
12331 the LaTeX math segments. If Orgmode thinks that point is actually inside
12332 an embedded LaTeX fragment, let texmathp do its job.
12333 \\[org-cdlatex-mode-map]"
12334 (interactive)
12335 (let (p)
12336 (cond
12337 ((not (org-mode-p)) ad-do-it)
12338 ((eq this-command 'cdlatex-math-symbol)
12339 (setq ad-return-value t
12340 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12341 (t
12342 (let ((p (org-inside-LaTeX-fragment-p)))
12343 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12344 (setq ad-return-value t
12345 texmathp-why '("Org-mode embedded math" . 0))
12346 (if p ad-do-it)))))))))
12347
12348 (defun turn-on-org-cdlatex ()
12349 "Unconditionally turn on `org-cdlatex-mode'."
12350 (org-cdlatex-mode 1))
12351
12352 (defun org-inside-LaTeX-fragment-p ()
12353 "Test if point is inside a LaTeX fragment.
12354 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12355 sequence appearing also before point.
12356 Even though the matchers for math are configurable, this function assumes
12357 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12358 delimiters are skipped when they have been removed by customization.
12359 The return value is nil, or a cons cell with the delimiter and
12360 and the position of this delimiter.
12361
12362 This function does a reasonably good job, but can locally be fooled by
12363 for example currency specifications. For example it will assume being in
12364 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12365 fragments that are properly closed, but during editing, we have to live
12366 with the uncertainty caused by missing closing delimiters. This function
12367 looks only before point, not after."
12368 (catch 'exit
12369 (let ((pos (point))
12370 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12371 (lim (progn
12372 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12373 (point)))
12374 dd-on str (start 0) m re)
12375 (goto-char pos)
12376 (when dodollar
12377 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12378 re (nth 1 (assoc "$" org-latex-regexps)))
12379 (while (string-match re str start)
12380 (cond
12381 ((= (match-end 0) (length str))
12382 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12383 ((= (match-end 0) (- (length str) 5))
12384 (throw 'exit nil))
12385 (t (setq start (match-end 0))))))
12386 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12387 (goto-char pos)
12388 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12389 (and (match-beginning 2) (throw 'exit nil))
12390 ;; count $$
12391 (while (re-search-backward "\\$\\$" lim t)
12392 (setq dd-on (not dd-on)))
12393 (goto-char pos)
12394 (if dd-on (cons "$$" m))))))
12395
12396
12397 (defun org-try-cdlatex-tab ()
12398 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12399 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12400 - inside a LaTeX fragment, or
12401 - after the first word in a line, where an abbreviation expansion could
12402 insert a LaTeX environment."
12403 (when org-cdlatex-mode
12404 (cond
12405 ((save-excursion
12406 (skip-chars-backward "a-zA-Z0-9*")
12407 (skip-chars-backward " \t")
12408 (bolp))
12409 (cdlatex-tab) t)
12410 ((org-inside-LaTeX-fragment-p)
12411 (cdlatex-tab) t)
12412 (t nil))))
12413
12414 (defun org-cdlatex-underscore-caret (&optional arg)
12415 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12416 Revert to the normal definition outside of these fragments."
12417 (interactive "P")
12418 (if (org-inside-LaTeX-fragment-p)
12419 (call-interactively 'cdlatex-sub-superscript)
12420 (let (org-cdlatex-mode)
12421 (call-interactively (key-binding (vector last-input-event))))))
12422
12423 (defun org-cdlatex-math-modify (&optional arg)
12424 "Execute `cdlatex-math-modify' in LaTeX fragments.
12425 Revert to the normal definition outside of these fragments."
12426 (interactive "P")
12427 (if (org-inside-LaTeX-fragment-p)
12428 (call-interactively 'cdlatex-math-modify)
12429 (let (org-cdlatex-mode)
12430 (call-interactively (key-binding (vector last-input-event))))))
12431
12432 (defvar org-latex-fragment-image-overlays nil
12433 "List of overlays carrying the images of latex fragments.")
12434 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12435
12436 (defun org-remove-latex-fragment-image-overlays ()
12437 "Remove all overlays with LaTeX fragment images in current buffer."
12438 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12439 (setq org-latex-fragment-image-overlays nil))
12440
12441 (defun org-preview-latex-fragment (&optional subtree)
12442 "Preview the LaTeX fragment at point, or all locally or globally.
12443 If the cursor is in a LaTeX fragment, create the image and overlay
12444 it over the source code. If there is no fragment at point, display
12445 all fragments in the current text, from one headline to the next. With
12446 prefix SUBTREE, display all fragments in the current subtree. With a
12447 double prefix `C-u C-u', or when the cursor is before the first headline,
12448 display all fragments in the buffer.
12449 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12450 (interactive "P")
12451 (org-remove-latex-fragment-image-overlays)
12452 (save-excursion
12453 (save-restriction
12454 (let (beg end at msg)
12455 (cond
12456 ((or (equal subtree '(16))
12457 (not (save-excursion
12458 (re-search-backward (concat "^" outline-regexp) nil t))))
12459 (setq beg (point-min) end (point-max)
12460 msg "Creating images for buffer...%s"))
12461 ((equal subtree '(4))
12462 (org-back-to-heading)
12463 (setq beg (point) end (org-end-of-subtree t)
12464 msg "Creating images for subtree...%s"))
12465 (t
12466 (if (setq at (org-inside-LaTeX-fragment-p))
12467 (goto-char (max (point-min) (- (cdr at) 2)))
12468 (org-back-to-heading))
12469 (setq beg (point) end (progn (outline-next-heading) (point))
12470 msg (if at "Creating image...%s"
12471 "Creating images for entry...%s"))))
12472 (message msg "")
12473 (narrow-to-region beg end)
12474 (goto-char beg)
12475 (org-format-latex
12476 (concat "ltxpng/" (file-name-sans-extension
12477 (file-name-nondirectory
12478 buffer-file-name)))
12479 default-directory 'overlays msg at 'forbuffer)
12480 (message msg "done. Use `C-c C-c' to remove images.")))))
12481
12482 (defvar org-latex-regexps
12483 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12484 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12485 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12486 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12487 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12488 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12489 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12490 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12491 "Regular expressions for matching embedded LaTeX.")
12492
12493 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12494 "Replace LaTeX fragments with links to an image, and produce images."
12495 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12496 (let* ((prefixnodir (file-name-nondirectory prefix))
12497 (absprefix (expand-file-name prefix dir))
12498 (todir (file-name-directory absprefix))
12499 (opt org-format-latex-options)
12500 (matchers (plist-get opt :matchers))
12501 (re-list org-latex-regexps)
12502 (cnt 0) txt link beg end re e checkdir
12503 m n block linkfile movefile ov)
12504 ;; Check if there are old images files with this prefix, and remove them
12505 (when (file-directory-p todir)
12506 (mapc 'delete-file
12507 (directory-files
12508 todir 'full
12509 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12510 ;; Check the different regular expressions
12511 (while (setq e (pop re-list))
12512 (setq m (car e) re (nth 1 e) n (nth 2 e)
12513 block (if (nth 3 e) "\n\n" ""))
12514 (when (member m matchers)
12515 (goto-char (point-min))
12516 (while (re-search-forward re nil t)
12517 (when (or (not at) (equal (cdr at) (match-beginning n)))
12518 (setq txt (match-string n)
12519 beg (match-beginning n) end (match-end n)
12520 cnt (1+ cnt)
12521 linkfile (format "%s_%04d.png" prefix cnt)
12522 movefile (format "%s_%04d.png" absprefix cnt)
12523 link (concat block "[[file:" linkfile "]]" block))
12524 (if msg (message msg cnt))
12525 (goto-char beg)
12526 (unless checkdir ; make sure the directory exists
12527 (setq checkdir t)
12528 (or (file-directory-p todir) (make-directory todir)))
12529 (org-create-formula-image
12530 txt movefile opt forbuffer)
12531 (if overlays
12532 (progn
12533 (setq ov (org-make-overlay beg end))
12534 (if (featurep 'xemacs)
12535 (progn
12536 (org-overlay-put ov 'invisible t)
12537 (org-overlay-put
12538 ov 'end-glyph
12539 (make-glyph (vector 'png :file movefile))))
12540 (org-overlay-put
12541 ov 'display
12542 (list 'image :type 'png :file movefile :ascent 'center)))
12543 (push ov org-latex-fragment-image-overlays)
12544 (goto-char end))
12545 (delete-region beg end)
12546 (insert link))))))))
12547
12548 ;; This function borrows from Ganesh Swami's latex2png.el
12549 (defun org-create-formula-image (string tofile options buffer)
12550 (let* ((tmpdir (if (featurep 'xemacs)
12551 (temp-directory)
12552 temporary-file-directory))
12553 (texfilebase (make-temp-name
12554 (expand-file-name "orgtex" tmpdir)))
12555 (texfile (concat texfilebase ".tex"))
12556 (dvifile (concat texfilebase ".dvi"))
12557 (pngfile (concat texfilebase ".png"))
12558 (fnh (if (featurep 'xemacs)
12559 (font-height (get-face-font 'default))
12560 (face-attribute 'default :height nil)))
12561 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12562 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12563 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12564 "Black"))
12565 (bg (or (plist-get options (if buffer :background :html-background))
12566 "Transparent")))
12567 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12568 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12569 (with-temp-file texfile
12570 (insert org-format-latex-header
12571 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12572 (let ((dir default-directory))
12573 (condition-case nil
12574 (progn
12575 (cd tmpdir)
12576 (call-process "latex" nil nil nil texfile))
12577 (error nil))
12578 (cd dir))
12579 (if (not (file-exists-p dvifile))
12580 (progn (message "Failed to create dvi file from %s" texfile) nil)
12581 (condition-case nil
12582 (call-process "dvipng" nil nil nil
12583 "-E" "-fg" fg "-bg" bg
12584 "-D" dpi
12585 ;;"-x" scale "-y" scale
12586 "-T" "tight"
12587 "-o" pngfile
12588 dvifile)
12589 (error nil))
12590 (if (not (file-exists-p pngfile))
12591 (progn (message "Failed to create png file from %s" texfile) nil)
12592 ;; Use the requested file name and clean up
12593 (copy-file pngfile tofile 'replace)
12594 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12595 (delete-file (concat texfilebase e)))
12596 pngfile))))
12597
12598 (defun org-dvipng-color (attr)
12599 "Return an rgb color specification for dvipng."
12600 (apply 'format "rgb %s %s %s"
12601 (mapcar 'org-normalize-color
12602 (color-values (face-attribute 'default attr nil)))))
12603
12604 (defun org-normalize-color (value)
12605 "Return string to be used as color value for an RGB component."
12606 (format "%g" (/ value 65535.0)))
12607
12608 ;;;; Key bindings
12609
12610 ;; Make `C-c C-x' a prefix key
12611 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12612
12613 ;; TAB key with modifiers
12614 (org-defkey org-mode-map "\C-i" 'org-cycle)
12615 (org-defkey org-mode-map [(tab)] 'org-cycle)
12616 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12617 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12618 (org-defkey org-mode-map "\M-\t" 'org-complete)
12619 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12620 ;; The following line is necessary under Suse GNU/Linux
12621 (unless (featurep 'xemacs)
12622 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12623 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12624 (define-key org-mode-map [backtab] 'org-shifttab)
12625
12626 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12627 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12628 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12629
12630 ;; Cursor keys with modifiers
12631 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12632 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12633 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12634 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12635
12636 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12637 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12638 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12639 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12640
12641 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12642 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12643 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12644 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12645
12646 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12647 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12648
12649 ;;; Extra keys for tty access.
12650 ;; We only set them when really needed because otherwise the
12651 ;; menus don't show the simple keys
12652
12653 (when (or org-use-extra-keys
12654 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12655 (not window-system))
12656 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12657 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12658 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12659 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12660 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12661 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12662 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12663 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12664 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12665 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12666 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12667 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12668 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12669 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12670 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12671 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12672 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12673 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12674 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12675 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12676 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12677 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12678
12679 ;; All the other keys
12680
12681 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12682 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12683 (if (boundp 'narrow-map)
12684 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12685 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12686 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12687 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12688 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12689 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12690 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12691 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12692 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12693 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12694 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12695 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12696 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12697 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12698 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12699 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12700 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12701 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12702 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12703 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12704 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12705 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12706 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12707 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12708 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12709 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12710 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12711 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12712 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12713 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12714 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12715 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12716 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12717 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12718 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12719 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12720 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12721 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12722 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12723 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12724 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12725 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12726 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12727 (org-defkey org-mode-map "\C-c^" 'org-sort)
12728 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12729 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12730 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12731 (org-defkey org-mode-map "\C-m" 'org-return)
12732 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12733 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12734 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12735 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12736 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12737 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12738 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12739 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12740 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12741 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12742 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12743 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12744 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12745 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12746 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12747 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12748 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
12749
12750 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12751 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12752 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12753 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12754
12755 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12756 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12757 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12758 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12759 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12760 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12761 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12762 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12763 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12764 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12765 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12766 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12767
12768 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12769 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12770 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12771 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
12772
12773 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12774
12775 (when (featurep 'xemacs)
12776 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12777
12778 (defvar org-table-auto-blank-field) ; defined in org-table.el
12779 (defun org-self-insert-command (N)
12780 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12781 If the cursor is in a table looking at whitespace, the whitespace is
12782 overwritten, and the table is not marked as requiring realignment."
12783 (interactive "p")
12784 (if (and (org-table-p)
12785 (progn
12786 ;; check if we blank the field, and if that triggers align
12787 (and (featurep 'org-table) org-table-auto-blank-field
12788 (member last-command
12789 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12790 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12791 ;; got extra space, this field does not determine column width
12792 (let (org-table-may-need-update) (org-table-blank-field))
12793 ;; no extra space, this field may determine column width
12794 (org-table-blank-field)))
12795 t)
12796 (eq N 1)
12797 (looking-at "[^|\n]* |"))
12798 (let (org-table-may-need-update)
12799 (goto-char (1- (match-end 0)))
12800 (delete-backward-char 1)
12801 (goto-char (match-beginning 0))
12802 (self-insert-command N))
12803 (setq org-table-may-need-update t)
12804 (self-insert-command N)
12805 (org-fix-tags-on-the-fly)))
12806
12807 (defun org-fix-tags-on-the-fly ()
12808 (when (and (equal (char-after (point-at-bol)) ?*)
12809 (org-on-heading-p))
12810 (org-align-tags-here org-tags-column)))
12811
12812 (defun org-delete-backward-char (N)
12813 "Like `delete-backward-char', insert whitespace at field end in tables.
12814 When deleting backwards, in tables this function will insert whitespace in
12815 front of the next \"|\" separator, to keep the table aligned. The table will
12816 still be marked for re-alignment if the field did fill the entire column,
12817 because, in this case the deletion might narrow the column."
12818 (interactive "p")
12819 (if (and (org-table-p)
12820 (eq N 1)
12821 (string-match "|" (buffer-substring (point-at-bol) (point)))
12822 (looking-at ".*?|"))
12823 (let ((pos (point))
12824 (noalign (looking-at "[^|\n\r]* |"))
12825 (c org-table-may-need-update))
12826 (backward-delete-char N)
12827 (skip-chars-forward "^|")
12828 (insert " ")
12829 (goto-char (1- pos))
12830 ;; noalign: if there were two spaces at the end, this field
12831 ;; does not determine the width of the column.
12832 (if noalign (setq org-table-may-need-update c)))
12833 (backward-delete-char N)
12834 (org-fix-tags-on-the-fly)))
12835
12836 (defun org-delete-char (N)
12837 "Like `delete-char', but insert whitespace at field end in tables.
12838 When deleting characters, in tables this function will insert whitespace in
12839 front of the next \"|\" separator, to keep the table aligned. The table will
12840 still be marked for re-alignment if the field did fill the entire column,
12841 because, in this case the deletion might narrow the column."
12842 (interactive "p")
12843 (if (and (org-table-p)
12844 (not (bolp))
12845 (not (= (char-after) ?|))
12846 (eq N 1))
12847 (if (looking-at ".*?|")
12848 (let ((pos (point))
12849 (noalign (looking-at "[^|\n\r]* |"))
12850 (c org-table-may-need-update))
12851 (replace-match (concat
12852 (substring (match-string 0) 1 -1)
12853 " |"))
12854 (goto-char pos)
12855 ;; noalign: if there were two spaces at the end, this field
12856 ;; does not determine the width of the column.
12857 (if noalign (setq org-table-may-need-update c)))
12858 (delete-char N))
12859 (delete-char N)
12860 (org-fix-tags-on-the-fly)))
12861
12862 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12863 (put 'org-self-insert-command 'delete-selection t)
12864 (put 'orgtbl-self-insert-command 'delete-selection t)
12865 (put 'org-delete-char 'delete-selection 'supersede)
12866 (put 'org-delete-backward-char 'delete-selection 'supersede)
12867 (put 'org-yank 'delete-selection 'yank)
12868
12869 ;; Make `flyspell-mode' delay after some commands
12870 (put 'org-self-insert-command 'flyspell-delayed t)
12871 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12872 (put 'org-delete-char 'flyspell-delayed t)
12873 (put 'org-delete-backward-char 'flyspell-delayed t)
12874
12875 ;; Make pabbrev-mode expand after org-mode commands
12876 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12877 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
12878
12879 ;; How to do this: Measure non-white length of current string
12880 ;; If equal to column width, we should realign.
12881
12882 (defun org-remap (map &rest commands)
12883 "In MAP, remap the functions given in COMMANDS.
12884 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12885 (let (new old)
12886 (while commands
12887 (setq old (pop commands) new (pop commands))
12888 (if (fboundp 'command-remapping)
12889 (org-defkey map (vector 'remap old) new)
12890 (substitute-key-definition old new map global-map)))))
12891
12892 (when (eq org-enable-table-editor 'optimized)
12893 ;; If the user wants maximum table support, we need to hijack
12894 ;; some standard editing functions
12895 (org-remap org-mode-map
12896 'self-insert-command 'org-self-insert-command
12897 'delete-char 'org-delete-char
12898 'delete-backward-char 'org-delete-backward-char)
12899 (org-defkey org-mode-map "|" 'org-force-self-insert))
12900
12901 (defun org-shiftcursor-error ()
12902 "Throw an error because Shift-Cursor command was applied in wrong context."
12903 (error "This command is active in special context like tables, headlines or timestamps"))
12904
12905 (defun org-shifttab (&optional arg)
12906 "Global visibility cycling or move to previous table field.
12907 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12908 on context.
12909 See the individual commands for more information."
12910 (interactive "P")
12911 (cond
12912 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12913 ((integerp arg)
12914 (message "Content view to level: %d" arg)
12915 (org-content (prefix-numeric-value arg))
12916 (setq org-cycle-global-status 'overview))
12917 (t (call-interactively 'org-global-cycle))))
12918
12919 (defun org-shiftmetaleft ()
12920 "Promote subtree or delete table column.
12921 Calls `org-promote-subtree', `org-outdent-item',
12922 or `org-table-delete-column', depending on context.
12923 See the individual commands for more information."
12924 (interactive)
12925 (cond
12926 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12927 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12928 ((org-at-item-p) (call-interactively 'org-outdent-item))
12929 (t (org-shiftcursor-error))))
12930
12931 (defun org-shiftmetaright ()
12932 "Demote subtree or insert table column.
12933 Calls `org-demote-subtree', `org-indent-item',
12934 or `org-table-insert-column', depending on context.
12935 See the individual commands for more information."
12936 (interactive)
12937 (cond
12938 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12939 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12940 ((org-at-item-p) (call-interactively 'org-indent-item))
12941 (t (org-shiftcursor-error))))
12942
12943 (defun org-shiftmetaup (&optional arg)
12944 "Move subtree up or kill table row.
12945 Calls `org-move-subtree-up' or `org-table-kill-row' or
12946 `org-move-item-up' depending on context. See the individual commands
12947 for more information."
12948 (interactive "P")
12949 (cond
12950 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12951 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12952 ((org-at-item-p) (call-interactively 'org-move-item-up))
12953 (t (org-shiftcursor-error))))
12954 (defun org-shiftmetadown (&optional arg)
12955 "Move subtree down or insert table row.
12956 Calls `org-move-subtree-down' or `org-table-insert-row' or
12957 `org-move-item-down', depending on context. See the individual
12958 commands for more information."
12959 (interactive "P")
12960 (cond
12961 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12962 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12963 ((org-at-item-p) (call-interactively 'org-move-item-down))
12964 (t (org-shiftcursor-error))))
12965
12966 (defun org-metaleft (&optional arg)
12967 "Promote heading or move table column to left.
12968 Calls `org-do-promote' or `org-table-move-column', depending on context.
12969 With no specific context, calls the Emacs default `backward-word'.
12970 See the individual commands for more information."
12971 (interactive "P")
12972 (cond
12973 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12974 ((or (org-on-heading-p) (org-region-active-p))
12975 (call-interactively 'org-do-promote))
12976 ((org-at-item-p) (call-interactively 'org-outdent-item))
12977 (t (call-interactively 'backward-word))))
12978
12979 (defun org-metaright (&optional arg)
12980 "Demote subtree or move table column to right.
12981 Calls `org-do-demote' or `org-table-move-column', depending on context.
12982 With no specific context, calls the Emacs default `forward-word'.
12983 See the individual commands for more information."
12984 (interactive "P")
12985 (cond
12986 ((org-at-table-p) (call-interactively 'org-table-move-column))
12987 ((or (org-on-heading-p) (org-region-active-p))
12988 (call-interactively 'org-do-demote))
12989 ((org-at-item-p) (call-interactively 'org-indent-item))
12990 (t (call-interactively 'forward-word))))
12991
12992 (defun org-metaup (&optional arg)
12993 "Move subtree up or move table row up.
12994 Calls `org-move-subtree-up' or `org-table-move-row' or
12995 `org-move-item-up', depending on context. See the individual commands
12996 for more information."
12997 (interactive "P")
12998 (cond
12999 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13000 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13001 ((org-at-item-p) (call-interactively 'org-move-item-up))
13002 (t (transpose-lines 1) (beginning-of-line -1))))
13003
13004 (defun org-metadown (&optional arg)
13005 "Move subtree down or move table row down.
13006 Calls `org-move-subtree-down' or `org-table-move-row' or
13007 `org-move-item-down', depending on context. See the individual
13008 commands for more information."
13009 (interactive "P")
13010 (cond
13011 ((org-at-table-p) (call-interactively 'org-table-move-row))
13012 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13013 ((org-at-item-p) (call-interactively 'org-move-item-down))
13014 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13015
13016 (defun org-shiftup (&optional arg)
13017 "Increase item in timestamp or increase priority of current headline.
13018 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13019 depending on context. See the individual commands for more information."
13020 (interactive "P")
13021 (cond
13022 ((org-at-timestamp-p t)
13023 (call-interactively (if org-edit-timestamp-down-means-later
13024 'org-timestamp-down 'org-timestamp-up)))
13025 ((org-on-heading-p) (call-interactively 'org-priority-up))
13026 ((org-at-item-p) (call-interactively 'org-previous-item))
13027 ((org-clocktable-try-shift 'up arg))
13028 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
13029
13030 (defun org-shiftdown (&optional arg)
13031 "Decrease item in timestamp or decrease priority of current headline.
13032 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13033 depending on context. See the individual commands for more information."
13034 (interactive "P")
13035 (cond
13036 ((org-at-timestamp-p t)
13037 (call-interactively (if org-edit-timestamp-down-means-later
13038 'org-timestamp-up 'org-timestamp-down)))
13039 ((org-on-heading-p) (call-interactively 'org-priority-down))
13040 ((org-clocktable-try-shift 'down arg))
13041 (t (call-interactively 'org-next-item))))
13042
13043 (defun org-shiftright (&optional arg)
13044 "Cycle the thing at point or in the current line, depending on context.
13045 Depending on context, this does one of the following:
13046
13047 - switch a timestamp at point one day into the future
13048 - on a headline, switch to the next TODO keyword.
13049 - on an item, switch entire list to the next bullet type
13050 - on a property line, switch to the next allowed value
13051 - on a clocktable definition line, move time block into the future"
13052 (interactive "P")
13053 (cond
13054 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13055 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
13056 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
13057 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
13058 ((org-clocktable-try-shift 'right arg))
13059 (t (org-shiftcursor-error))))
13060
13061 (defun org-shiftleft (&optional arg)
13062 "Cycle the thing at point or in the current line, depending on context.
13063 Depending on context, this does one of the following:
13064
13065 - switch a timestamp at point one day into the past
13066 - on a headline, switch to the previous TODO keyword.
13067 - on an item, switch entire list to the previous bullet type
13068 - on a property line, switch to the previous allowed value
13069 - on a clocktable definition line, move time block into the past"
13070 (interactive "P")
13071 (cond
13072 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13073 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
13074 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
13075 ((org-at-property-p)
13076 (call-interactively 'org-property-previous-allowed-value))
13077 ((org-clocktable-try-shift 'left arg))
13078 (t (org-shiftcursor-error))))
13079
13080 (defun org-shiftcontrolright ()
13081 "Switch to next TODO set."
13082 (interactive)
13083 (cond
13084 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
13085 (t (org-shiftcursor-error))))
13086
13087 (defun org-shiftcontrolleft ()
13088 "Switch to previous TODO set."
13089 (interactive)
13090 (cond
13091 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
13092 (t (org-shiftcursor-error))))
13093
13094 (defun org-ctrl-c-ret ()
13095 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13096 (interactive)
13097 (cond
13098 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13099 (t (call-interactively 'org-insert-heading))))
13100
13101 (defun org-copy-special ()
13102 "Copy region in table or copy current subtree.
13103 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13104 See the individual commands for more information."
13105 (interactive)
13106 (call-interactively
13107 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13108
13109 (defun org-cut-special ()
13110 "Cut region in table or cut current subtree.
13111 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13112 See the individual commands for more information."
13113 (interactive)
13114 (call-interactively
13115 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13116
13117 (defun org-paste-special (arg)
13118 "Paste rectangular region into table, or past subtree relative to level.
13119 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13120 See the individual commands for more information."
13121 (interactive "P")
13122 (if (org-at-table-p)
13123 (org-table-paste-rectangle)
13124 (org-paste-subtree arg)))
13125
13126 (defun org-edit-special ()
13127 "Call a special editor for the stuff at point.
13128 When at a table, call the formula editor with `org-table-edit-formulas'.
13129 When at the first line of an src example, call `org-edit-src-code'.
13130 When in an #+include line, visit the include file. Otherwise call
13131 `ffap' to visit the file at point."
13132 (interactive)
13133 (cond
13134 ((org-at-table-p)
13135 (call-interactively 'org-table-edit-formulas))
13136 ((save-excursion
13137 (beginning-of-line 1)
13138 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13139 (find-file (org-trim (match-string 1))))
13140 ((org-edit-src-code))
13141 ((org-edit-fixed-width-region))
13142 (t (call-interactively 'ffap))))
13143
13144 (defun org-ctrl-c-ctrl-c (&optional arg)
13145 "Set tags in headline, or update according to changed information at point.
13146
13147 This command does many different things, depending on context:
13148
13149 - If the cursor is in a headline, prompt for tags and insert them
13150 into the current line, aligned to `org-tags-column'. When called
13151 with prefix arg, realign all tags in the current buffer.
13152
13153 - If the cursor is in one of the special #+KEYWORD lines, this
13154 triggers scanning the buffer for these lines and updating the
13155 information.
13156
13157 - If the cursor is inside a table, realign the table. This command
13158 works even if the automatic table editor has been turned off.
13159
13160 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13161 the entire table.
13162
13163 - If the cursor is at a footnote reference or definition, jump to
13164 the corresponding definition or references, respectively.
13165
13166 - If the cursor is a the beginning of a dynamic block, update it.
13167
13168 - If the cursor is inside a table created by the table.el package,
13169 activate that table.
13170
13171 - If the current buffer is a remember buffer, close note and file
13172 it. A prefix argument of 1 files to the default location
13173 without further interaction. A prefix argument of 2 files to
13174 the currently clocking task.
13175
13176 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13177 links in this buffer.
13178
13179 - If the cursor is on a numbered item in a plain list, renumber the
13180 ordered list.
13181
13182 - If the cursor is on a checkbox, toggle it."
13183 (interactive "P")
13184 (let ((org-enable-table-editor t))
13185 (cond
13186 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13187 org-occur-highlights
13188 org-latex-fragment-image-overlays)
13189 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13190 (org-remove-occur-highlights)
13191 (org-remove-latex-fragment-image-overlays)
13192 (message "Temporary highlights/overlays removed from current buffer"))
13193 ((and (local-variable-p 'org-finish-function (current-buffer))
13194 (fboundp org-finish-function))
13195 (funcall org-finish-function))
13196 ((org-at-property-p)
13197 (call-interactively 'org-property-action))
13198 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13199 ((org-on-heading-p) (call-interactively 'org-set-tags))
13200 ((org-at-table.el-p)
13201 (require 'table)
13202 (beginning-of-line 1)
13203 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13204 (call-interactively 'table-recognize-table))
13205 ((org-at-table-p)
13206 (org-table-maybe-eval-formula)
13207 (if arg
13208 (call-interactively 'org-table-recalculate)
13209 (org-table-maybe-recalculate-line))
13210 (call-interactively 'org-table-align))
13211 ((or (org-footnote-at-reference-p)
13212 (org-footnote-at-definition-p))
13213 (call-interactively 'org-footnote-action))
13214 ((org-at-item-checkbox-p)
13215 (call-interactively 'org-toggle-checkbox))
13216 ((org-at-item-p)
13217 (call-interactively 'org-maybe-renumber-ordered-list))
13218 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13219 ;; Dynamic block
13220 (beginning-of-line 1)
13221 (save-excursion (org-update-dblock)))
13222 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13223 (cond
13224 ((equal (match-string 1) "TBLFM")
13225 ;; Recalculate the table before this line
13226 (save-excursion
13227 (beginning-of-line 1)
13228 (skip-chars-backward " \r\n\t")
13229 (if (org-at-table-p)
13230 (org-call-with-arg 'org-table-recalculate t))))
13231 (t
13232 ; (org-set-regexps-and-options)
13233 ; (org-restart-font-lock)
13234 (let ((org-inhibit-startup t)) (org-mode-restart))
13235 (message "Local setup has been refreshed"))))
13236 (t (error "C-c C-c can do nothing useful at this location.")))))
13237
13238 (defun org-mode-restart ()
13239 "Restart Org-mode, to scan again for special lines.
13240 Also updates the keyword regular expressions."
13241 (interactive)
13242 (org-mode)
13243 (message "Org-mode restarted"))
13244
13245 (defun org-kill-note-or-show-branches ()
13246 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13247 (interactive)
13248 (if (not org-finish-function)
13249 (call-interactively 'show-branches)
13250 (let ((org-note-abort t))
13251 (funcall org-finish-function))))
13252
13253 (defun org-return (&optional indent)
13254 "Goto next table row or insert a newline.
13255 Calls `org-table-next-row' or `newline', depending on context.
13256 See the individual commands for more information."
13257 (interactive)
13258 (cond
13259 ((bobp) (if indent (newline-and-indent) (newline)))
13260 ((and (org-at-heading-p)
13261 (looking-at
13262 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13263 (org-show-entry)
13264 (end-of-line 1)
13265 (newline))
13266 ((org-at-table-p)
13267 (org-table-justify-field-maybe)
13268 (call-interactively 'org-table-next-row))
13269 (t (if indent (newline-and-indent) (newline)))))
13270
13271 (defun org-return-indent ()
13272 "Goto next table row or insert a newline and indent.
13273 Calls `org-table-next-row' or `newline-and-indent', depending on
13274 context. See the individual commands for more information."
13275 (interactive)
13276 (org-return t))
13277
13278 (defun org-ctrl-c-star ()
13279 "Compute table, or change heading status of lines.
13280 Calls `org-table-recalculate' or `org-toggle-heading',
13281 depending on context."
13282 (interactive)
13283 (cond
13284 ((org-at-table-p)
13285 (call-interactively 'org-table-recalculate))
13286 (t
13287 ;; Convert all lines in region to list items
13288 (call-interactively 'org-toggle-heading))))
13289
13290 (defun org-ctrl-c-minus ()
13291 "Insert separator line in table or modify bullet status of line.
13292 Also turns a plain line or a region of lines into list items.
13293 Calls `org-table-insert-hline', `org-toggle-item', or
13294 `org-cycle-list-bullet', depending on context."
13295 (interactive)
13296 (cond
13297 ((org-at-table-p)
13298 (call-interactively 'org-table-insert-hline))
13299 ((org-region-active-p)
13300 (call-interactively 'org-toggle-item))
13301 ((org-in-item-p)
13302 (call-interactively 'org-cycle-list-bullet))
13303 (t
13304 (call-interactively 'org-toggle-item))))
13305
13306 (defun org-toggle-item ()
13307 "Convert headings or normal lines to items, items to normal lines.
13308 If there is no active region, only the current line is considered.
13309
13310 If the first line in the region is a headline, convert all headlines to items.
13311
13312 If the first line in the region is an item, convert all items to normal lines.
13313
13314 If the first line is normal text, add an item bullet to each line."
13315 (interactive)
13316 (let (l2 l beg end)
13317 (if (org-region-active-p)
13318 (setq beg (region-beginning) end (region-end))
13319 (setq beg (point-at-bol)
13320 end (min (1+ (point-at-eol)) (point-max))))
13321 (save-excursion
13322 (goto-char end)
13323 (setq l2 (org-current-line))
13324 (goto-char beg)
13325 (beginning-of-line 1)
13326 (setq l (1- (org-current-line)))
13327 (if (org-at-item-p)
13328 ;; We already have items, de-itemize
13329 (while (< (setq l (1+ l)) l2)
13330 (when (org-at-item-p)
13331 (goto-char (match-beginning 2))
13332 (delete-region (match-beginning 2) (match-end 2))
13333 (and (looking-at "[ \t]+") (replace-match "")))
13334 (beginning-of-line 2))
13335 (if (org-on-heading-p)
13336 ;; Headings, convert to items
13337 (while (< (setq l (1+ l)) l2)
13338 (if (looking-at org-outline-regexp)
13339 (replace-match "- " t t))
13340 (beginning-of-line 2))
13341 ;; normal lines, turn them into items
13342 (while (< (setq l (1+ l)) l2)
13343 (unless (org-at-item-p)
13344 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13345 (replace-match "\\1- \\2")))
13346 (beginning-of-line 2)))))))
13347
13348 (defun org-toggle-heading (&optional nstars)
13349 "Convert headings to normal text, or items or text to headings.
13350 If there is no active region, only the current line is considered.
13351
13352 If the first line is a heading, remove the stars from all headlines
13353 in the region.
13354
13355 If the first line is a plain list item, turn all plain list items into
13356 headings.
13357
13358 If the first line is a normal line, turn each and every line in the region
13359 into a heading.
13360
13361 When converting a line into a heading, the number of stars is chosen
13362 such that the lines become children of the current entry. However, when
13363 a prefix argument is given, its value determines the number of stars to add."
13364 (interactive "P")
13365 (let (l2 l itemp beg end)
13366 (if (org-region-active-p)
13367 (setq beg (region-beginning) end (region-end))
13368 (setq beg (point-at-bol)
13369 end (min (1+ (point-at-eol)) (point-max))))
13370 (save-excursion
13371 (goto-char end)
13372 (setq l2 (org-current-line))
13373 (goto-char beg)
13374 (beginning-of-line 1)
13375 (setq l (1- (org-current-line)))
13376 (if (org-on-heading-p)
13377 ;; We already have headlines, de-star them
13378 (while (< (setq l (1+ l)) l2)
13379 (when (org-on-heading-p t)
13380 (and (looking-at outline-regexp) (replace-match "")))
13381 (beginning-of-line 2))
13382 (setq itemp (org-at-item-p))
13383 (let* ((stars
13384 (if nstars
13385 (make-string (prefix-numeric-value current-prefix-arg)
13386 ?*)
13387 (save-excursion
13388 (re-search-backward org-complex-heading-regexp nil t)
13389 (or (match-string 1) "*"))))
13390 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
13391 (rpl (concat stars add-stars " ")))
13392 (while (< (setq l (1+ l)) l2)
13393 (if itemp
13394 (and (org-at-item-p) (replace-match rpl t t))
13395 (unless (org-on-heading-p)
13396 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13397 (replace-match (concat rpl (match-string 2))))))
13398 (beginning-of-line 2)))))))
13399
13400 (defun org-meta-return (&optional arg)
13401 "Insert a new heading or wrap a region in a table.
13402 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13403 See the individual commands for more information."
13404 (interactive "P")
13405 (cond
13406 ((org-at-table-p)
13407 (call-interactively 'org-table-wrap-region))
13408 (t (call-interactively 'org-insert-heading))))
13409
13410 ;;; Menu entries
13411
13412 ;; Define the Org-mode menus
13413 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13414 '("Tbl"
13415 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13416 ["Next Field" org-cycle (org-at-table-p)]
13417 ["Previous Field" org-shifttab (org-at-table-p)]
13418 ["Next Row" org-return (org-at-table-p)]
13419 "--"
13420 ["Blank Field" org-table-blank-field (org-at-table-p)]
13421 ["Edit Field" org-table-edit-field (org-at-table-p)]
13422 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13423 "--"
13424 ("Column"
13425 ["Move Column Left" org-metaleft (org-at-table-p)]
13426 ["Move Column Right" org-metaright (org-at-table-p)]
13427 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13428 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13429 ("Row"
13430 ["Move Row Up" org-metaup (org-at-table-p)]
13431 ["Move Row Down" org-metadown (org-at-table-p)]
13432 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13433 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13434 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13435 "--"
13436 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13437 ("Rectangle"
13438 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13439 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13440 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13441 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13442 "--"
13443 ("Calculate"
13444 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13445 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13446 ["Edit Formulas" org-edit-special (org-at-table-p)]
13447 "--"
13448 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13449 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13450 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13451 "--"
13452 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13453 "--"
13454 ["Sum Column/Rectangle" org-table-sum
13455 (or (org-at-table-p) (org-region-active-p))]
13456 ["Which Column?" org-table-current-column (org-at-table-p)])
13457 ["Debug Formulas"
13458 org-table-toggle-formula-debugger
13459 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13460 ["Show Col/Row Numbers"
13461 org-table-toggle-coordinate-overlays
13462 :style toggle
13463 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13464 "--"
13465 ["Create" org-table-create (and (not (org-at-table-p))
13466 org-enable-table-editor)]
13467 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13468 ["Import from File" org-table-import (not (org-at-table-p))]
13469 ["Export to File" org-table-export (org-at-table-p)]
13470 "--"
13471 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13472
13473 (easy-menu-define org-org-menu org-mode-map "Org menu"
13474 '("Org"
13475 ("Show/Hide"
13476 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13477 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13478 ["Sparse Tree..." org-sparse-tree t]
13479 ["Reveal Context" org-reveal t]
13480 ["Show All" show-all t]
13481 "--"
13482 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13483 "--"
13484 ["New Heading" org-insert-heading t]
13485 ("Navigate Headings"
13486 ["Up" outline-up-heading t]
13487 ["Next" outline-next-visible-heading t]
13488 ["Previous" outline-previous-visible-heading t]
13489 ["Next Same Level" outline-forward-same-level t]
13490 ["Previous Same Level" outline-backward-same-level t]
13491 "--"
13492 ["Jump" org-goto t])
13493 ("Edit Structure"
13494 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13495 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13496 "--"
13497 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13498 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13499 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13500 "--"
13501 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13502 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13503 ["Demote Heading" org-metaright (not (org-at-table-p))]
13504 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13505 "--"
13506 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13507 "--"
13508 ["Convert to odd levels" org-convert-to-odd-levels t]
13509 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13510 ("Editing"
13511 ["Emphasis..." org-emphasize t]
13512 ["Edit Source Example" org-edit-special t]
13513 "--"
13514 ["Footnote new/jump" org-footnote-action t]
13515 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13516 ("Archive"
13517 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13518 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13519 ; :active t :keys "C-u C-c C-x C-a"]
13520 ["Sparse trees open ARCHIVE trees"
13521 (setq org-sparse-tree-open-archived-trees
13522 (not org-sparse-tree-open-archived-trees))
13523 :style toggle :selected org-sparse-tree-open-archived-trees]
13524 ["Cycling opens ARCHIVE trees"
13525 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13526 :style toggle :selected org-cycle-open-archived-trees]
13527 "--"
13528 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13529 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13530 ; ["Check and Move Children" (org-archive-subtree '(4))
13531 ; :active t :keys "C-u C-c C-x C-s"]
13532 )
13533 "--"
13534 ("TODO Lists"
13535 ["TODO/DONE/-" org-todo t]
13536 ("Select keyword"
13537 ["Next keyword" org-shiftright (org-on-heading-p)]
13538 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13539 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13540 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13541 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13542 ["Show TODO Tree" org-show-todo-tree t]
13543 ["Global TODO list" org-todo-list t]
13544 "--"
13545 ["Set Priority" org-priority t]
13546 ["Priority Up" org-shiftup t]
13547 ["Priority Down" org-shiftdown t])
13548 ("TAGS and Properties"
13549 ["Set Tags" org-set-tags-command t]
13550 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13551 "--"
13552 ["Set property" org-set-property t]
13553 ["Column view of properties" org-columns t]
13554 ["Insert Column View DBlock" org-insert-columns-dblock t])
13555 ("Dates and Scheduling"
13556 ["Timestamp" org-time-stamp t]
13557 ["Timestamp (inactive)" org-time-stamp-inactive t]
13558 ("Change Date"
13559 ["1 Day Later" org-shiftright t]
13560 ["1 Day Earlier" org-shiftleft t]
13561 ["1 ... Later" org-shiftup t]
13562 ["1 ... Earlier" org-shiftdown t])
13563 ["Compute Time Range" org-evaluate-time-range t]
13564 ["Schedule Item" org-schedule t]
13565 ["Deadline" org-deadline t]
13566 "--"
13567 ["Custom time format" org-toggle-time-stamp-overlays
13568 :style radio :selected org-display-custom-times]
13569 "--"
13570 ["Goto Calendar" org-goto-calendar t]
13571 ["Date from Calendar" org-date-from-calendar t]
13572 "--"
13573 ["Start/Restart Timer" org-timer-start t]
13574 ["Pause/Continue Timer" org-timer-pause-or-continue t]
13575 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
13576 ["Insert Timer String" org-timer t]
13577 ["Insert Timer Item" org-timer-item t])
13578 ("Logging work"
13579 ["Clock in" org-clock-in t]
13580 ["Clock out" org-clock-out t]
13581 ["Clock cancel" org-clock-cancel t]
13582 ["Goto running clock" org-clock-goto t]
13583 ["Display times" org-clock-display t]
13584 ["Create clock table" org-clock-report t]
13585 "--"
13586 ["Record DONE time"
13587 (progn (setq org-log-done (not org-log-done))
13588 (message "Switching to %s will %s record a timestamp"
13589 (car org-done-keywords)
13590 (if org-log-done "automatically" "not")))
13591 :style toggle :selected org-log-done])
13592 "--"
13593 ["Agenda Command..." org-agenda t]
13594 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13595 ("File List for Agenda")
13596 ("Special views current file"
13597 ["TODO Tree" org-show-todo-tree t]
13598 ["Check Deadlines" org-check-deadlines t]
13599 ["Timeline" org-timeline t]
13600 ["Tags Tree" org-tags-sparse-tree t])
13601 "--"
13602 ("Hyperlinks"
13603 ["Store Link (Global)" org-store-link t]
13604 ["Insert Link" org-insert-link t]
13605 ["Follow Link" org-open-at-point t]
13606 "--"
13607 ["Next link" org-next-link t]
13608 ["Previous link" org-previous-link t]
13609 "--"
13610 ["Descriptive Links"
13611 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13612 :style radio
13613 :selected (member '(org-link) buffer-invisibility-spec)]
13614 ["Literal Links"
13615 (progn
13616 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13617 :style radio
13618 :selected (not (member '(org-link) buffer-invisibility-spec))])
13619 "--"
13620 ["Export/Publish..." org-export t]
13621 ("LaTeX"
13622 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13623 :selected org-cdlatex-mode]
13624 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13625 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13626 ["Modify math symbol" org-cdlatex-math-modify
13627 (org-inside-LaTeX-fragment-p)]
13628 ["Export LaTeX fragments as images"
13629 (if (featurep 'org-exp)
13630 (setq org-export-with-LaTeX-fragments
13631 (not org-export-with-LaTeX-fragments))
13632 (require 'org-exp))
13633 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13634 org-export-with-LaTeX-fragments)])
13635 "--"
13636 ("Documentation"
13637 ["Show Version" org-version t]
13638 ["Info Documentation" org-info t])
13639 ("Customize"
13640 ["Browse Org Group" org-customize t]
13641 "--"
13642 ["Expand This Menu" org-create-customize-menu
13643 (fboundp 'customize-menu-create)])
13644 "--"
13645 ["Refresh setup" org-mode-restart t]
13646 ))
13647
13648 (defun org-info (&optional node)
13649 "Read documentation for Org-mode in the info system.
13650 With optional NODE, go directly to that node."
13651 (interactive)
13652 (info (format "(org)%s" (or node ""))))
13653
13654 (defun org-install-agenda-files-menu ()
13655 (let ((bl (buffer-list)))
13656 (save-excursion
13657 (while bl
13658 (set-buffer (pop bl))
13659 (if (org-mode-p) (setq bl nil)))
13660 (when (org-mode-p)
13661 (easy-menu-change
13662 '("Org") "File List for Agenda"
13663 (append
13664 (list
13665 ["Edit File List" (org-edit-agenda-file-list) t]
13666 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13667 ["Remove Current File from List" org-remove-file t]
13668 ["Cycle through agenda files" org-cycle-agenda-files t]
13669 ["Occur in all agenda files" org-occur-in-agenda-files t]
13670 "--")
13671 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13672
13673 ;;;; Documentation
13674
13675 ;;;###autoload
13676 (defun org-require-autoloaded-modules ()
13677 (interactive)
13678 (mapc 'require
13679 '(org-agenda org-archive org-clock org-colview
13680 org-exp org-id org-export-latex org-publish
13681 org-remember org-table)))
13682
13683 ;;;###autoload
13684 (defun org-customize ()
13685 "Call the customize function with org as argument."
13686 (interactive)
13687 (org-load-modules-maybe)
13688 (org-require-autoloaded-modules)
13689 (customize-browse 'org))
13690
13691 (defun org-create-customize-menu ()
13692 "Create a full customization menu for Org-mode, insert it into the menu."
13693 (interactive)
13694 (org-load-modules-maybe)
13695 (org-require-autoloaded-modules)
13696 (if (fboundp 'customize-menu-create)
13697 (progn
13698 (easy-menu-change
13699 '("Org") "Customize"
13700 `(["Browse Org group" org-customize t]
13701 "--"
13702 ,(customize-menu-create 'org)
13703 ["Set" Custom-set t]
13704 ["Save" Custom-save t]
13705 ["Reset to Current" Custom-reset-current t]
13706 ["Reset to Saved" Custom-reset-saved t]
13707 ["Reset to Standard Settings" Custom-reset-standard t]))
13708 (message "\"Org\"-menu now contains full customization menu"))
13709 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13710
13711 ;;;; Miscellaneous stuff
13712
13713 ;;; Generally useful functions
13714
13715 (defun org-find-text-property-in-string (prop s)
13716 "Return the first non-nil value of property PROP in string S."
13717 (or (get-text-property 0 prop s)
13718 (get-text-property (or (next-single-property-change 0 prop s) 0)
13719 prop s)))
13720
13721 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13722 "Display the given MESSAGE as a warning."
13723 (if (fboundp 'display-warning)
13724 (display-warning 'org message
13725 (if (featurep 'xemacs)
13726 'warning
13727 :warning))
13728 (let ((buf (get-buffer-create "*Org warnings*")))
13729 (with-current-buffer buf
13730 (goto-char (point-max))
13731 (insert "Warning (Org): " message)
13732 (unless (bolp)
13733 (newline)))
13734 (display-buffer buf)
13735 (sit-for 0))))
13736
13737 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13738 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13739 (if (and marker (marker-buffer marker)
13740 (buffer-live-p (marker-buffer marker)))
13741 (progn
13742 (switch-to-buffer (marker-buffer marker))
13743 (if (or (> marker (point-max)) (< marker (point-min)))
13744 (widen))
13745 (goto-char marker)
13746 (org-show-context 'org-goto))
13747 (if bookmark
13748 (bookmark-jump bookmark)
13749 (error "Cannot find location"))))
13750
13751 (defun org-quote-csv-field (s)
13752 "Quote field for inclusion in CSV material."
13753 (if (string-match "[\",]" s)
13754 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13755 s))
13756
13757 (defun org-plist-delete (plist property)
13758 "Delete PROPERTY from PLIST.
13759 This is in contrast to merely setting it to 0."
13760 (let (p)
13761 (while plist
13762 (if (not (eq property (car plist)))
13763 (setq p (plist-put p (car plist) (nth 1 plist))))
13764 (setq plist (cddr plist)))
13765 p))
13766
13767 (defun org-force-self-insert (N)
13768 "Needed to enforce self-insert under remapping."
13769 (interactive "p")
13770 (self-insert-command N))
13771
13772 (defun org-string-width (s)
13773 "Compute width of string, ignoring invisible characters.
13774 This ignores character with invisibility property `org-link', and also
13775 characters with property `org-cwidth', because these will become invisible
13776 upon the next fontification round."
13777 (let (b l)
13778 (when (or (eq t buffer-invisibility-spec)
13779 (assq 'org-link buffer-invisibility-spec))
13780 (while (setq b (text-property-any 0 (length s)
13781 'invisible 'org-link s))
13782 (setq s (concat (substring s 0 b)
13783 (substring s (or (next-single-property-change
13784 b 'invisible s) (length s)))))))
13785 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13786 (setq s (concat (substring s 0 b)
13787 (substring s (or (next-single-property-change
13788 b 'org-cwidth s) (length s))))))
13789 (setq l (string-width s) b -1)
13790 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13791 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13792 l))
13793
13794 (defun org-get-indentation (&optional line)
13795 "Get the indentation of the current line, interpreting tabs.
13796 When LINE is given, assume it represents a line and compute its indentation."
13797 (if line
13798 (if (string-match "^ *" (org-remove-tabs line))
13799 (match-end 0))
13800 (save-excursion
13801 (beginning-of-line 1)
13802 (skip-chars-forward " \t")
13803 (current-column))))
13804
13805 (defun org-remove-tabs (s &optional width)
13806 "Replace tabulators in S with spaces.
13807 Assumes that s is a single line, starting in column 0."
13808 (setq width (or width tab-width))
13809 (while (string-match "\t" s)
13810 (setq s (replace-match
13811 (make-string
13812 (- (* width (/ (+ (match-beginning 0) width) width))
13813 (match-beginning 0)) ?\ )
13814 t t s)))
13815 s)
13816
13817 (defun org-fix-indentation (line ind)
13818 "Fix indentation in LINE.
13819 IND is a cons cell with target and minimum indentation.
13820 If the current indentation in LINE is smaller than the minimum,
13821 leave it alone. If it is larger than ind, set it to the target."
13822 (let* ((l (org-remove-tabs line))
13823 (i (org-get-indentation l))
13824 (i1 (car ind)) (i2 (cdr ind)))
13825 (if (>= i i2) (setq l (substring line i2)))
13826 (if (> i1 0)
13827 (concat (make-string i1 ?\ ) l)
13828 l)))
13829
13830 (defun org-base-buffer (buffer)
13831 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13832 (if (not buffer)
13833 buffer
13834 (or (buffer-base-buffer buffer)
13835 buffer)))
13836
13837 (defun org-trim (s)
13838 "Remove whitespace at beginning and end of string."
13839 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13840 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13841 s)
13842
13843 (defun org-wrap (string &optional width lines)
13844 "Wrap string to either a number of lines, or a width in characters.
13845 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13846 that costs. If there is a word longer than WIDTH, the text is actually
13847 wrapped to the length of that word.
13848 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13849 many lines, whatever width that takes.
13850 The return value is a list of lines, without newlines at the end."
13851 (let* ((words (org-split-string string "[ \t\n]+"))
13852 (maxword (apply 'max (mapcar 'org-string-width words)))
13853 w ll)
13854 (cond (width
13855 (org-do-wrap words (max maxword width)))
13856 (lines
13857 (setq w maxword)
13858 (setq ll (org-do-wrap words maxword))
13859 (if (<= (length ll) lines)
13860 ll
13861 (setq ll words)
13862 (while (> (length ll) lines)
13863 (setq w (1+ w))
13864 (setq ll (org-do-wrap words w)))
13865 ll))
13866 (t (error "Cannot wrap this")))))
13867
13868 (defun org-do-wrap (words width)
13869 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13870 (let (lines line)
13871 (while words
13872 (setq line (pop words))
13873 (while (and words (< (+ (length line) (length (car words))) width))
13874 (setq line (concat line " " (pop words))))
13875 (setq lines (push line lines)))
13876 (nreverse lines)))
13877
13878 (defun org-split-string (string &optional separators)
13879 "Splits STRING into substrings at SEPARATORS.
13880 No empty strings are returned if there are matches at the beginning
13881 and end of string."
13882 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13883 (start 0)
13884 notfirst
13885 (list nil))
13886 (while (and (string-match rexp string
13887 (if (and notfirst
13888 (= start (match-beginning 0))
13889 (< start (length string)))
13890 (1+ start) start))
13891 (< (match-beginning 0) (length string)))
13892 (setq notfirst t)
13893 (or (eq (match-beginning 0) 0)
13894 (and (eq (match-beginning 0) (match-end 0))
13895 (eq (match-beginning 0) start))
13896 (setq list
13897 (cons (substring string start (match-beginning 0))
13898 list)))
13899 (setq start (match-end 0)))
13900 (or (eq start (length string))
13901 (setq list
13902 (cons (substring string start)
13903 list)))
13904 (nreverse list)))
13905
13906 (defun org-context ()
13907 "Return a list of contexts of the current cursor position.
13908 If several contexts apply, all are returned.
13909 Each context entry is a list with a symbol naming the context, and
13910 two positions indicating start and end of the context. Possible
13911 contexts are:
13912
13913 :headline anywhere in a headline
13914 :headline-stars on the leading stars in a headline
13915 :todo-keyword on a TODO keyword (including DONE) in a headline
13916 :tags on the TAGS in a headline
13917 :priority on the priority cookie in a headline
13918 :item on the first line of a plain list item
13919 :item-bullet on the bullet/number of a plain list item
13920 :checkbox on the checkbox in a plain list item
13921 :table in an org-mode table
13922 :table-special on a special filed in a table
13923 :table-table in a table.el table
13924 :link on a hyperlink
13925 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13926 :target on a <<target>>
13927 :radio-target on a <<<radio-target>>>
13928 :latex-fragment on a LaTeX fragment
13929 :latex-preview on a LaTeX fragment with overlayed preview image
13930
13931 This function expects the position to be visible because it uses font-lock
13932 faces as a help to recognize the following contexts: :table-special, :link,
13933 and :keyword."
13934 (let* ((f (get-text-property (point) 'face))
13935 (faces (if (listp f) f (list f)))
13936 (p (point)) clist o)
13937 ;; First the large context
13938 (cond
13939 ((org-on-heading-p t)
13940 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13941 (when (progn
13942 (beginning-of-line 1)
13943 (looking-at org-todo-line-tags-regexp))
13944 (push (org-point-in-group p 1 :headline-stars) clist)
13945 (push (org-point-in-group p 2 :todo-keyword) clist)
13946 (push (org-point-in-group p 4 :tags) clist))
13947 (goto-char p)
13948 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13949 (if (looking-at "\\[#[A-Z0-9]\\]")
13950 (push (org-point-in-group p 0 :priority) clist)))
13951
13952 ((org-at-item-p)
13953 (push (org-point-in-group p 2 :item-bullet) clist)
13954 (push (list :item (point-at-bol)
13955 (save-excursion (org-end-of-item) (point)))
13956 clist)
13957 (and (org-at-item-checkbox-p)
13958 (push (org-point-in-group p 0 :checkbox) clist)))
13959
13960 ((org-at-table-p)
13961 (push (list :table (org-table-begin) (org-table-end)) clist)
13962 (if (memq 'org-formula faces)
13963 (push (list :table-special
13964 (previous-single-property-change p 'face)
13965 (next-single-property-change p 'face)) clist)))
13966 ((org-at-table-p 'any)
13967 (push (list :table-table) clist)))
13968 (goto-char p)
13969
13970 ;; Now the small context
13971 (cond
13972 ((org-at-timestamp-p)
13973 (push (org-point-in-group p 0 :timestamp) clist))
13974 ((memq 'org-link faces)
13975 (push (list :link
13976 (previous-single-property-change p 'face)
13977 (next-single-property-change p 'face)) clist))
13978 ((memq 'org-special-keyword faces)
13979 (push (list :keyword
13980 (previous-single-property-change p 'face)
13981 (next-single-property-change p 'face)) clist))
13982 ((org-on-target-p)
13983 (push (org-point-in-group p 0 :target) clist)
13984 (goto-char (1- (match-beginning 0)))
13985 (if (looking-at org-radio-target-regexp)
13986 (push (org-point-in-group p 0 :radio-target) clist))
13987 (goto-char p))
13988 ((setq o (car (delq nil
13989 (mapcar
13990 (lambda (x)
13991 (if (memq x org-latex-fragment-image-overlays) x))
13992 (org-overlays-at (point))))))
13993 (push (list :latex-fragment
13994 (org-overlay-start o) (org-overlay-end o)) clist)
13995 (push (list :latex-preview
13996 (org-overlay-start o) (org-overlay-end o)) clist))
13997 ((org-inside-LaTeX-fragment-p)
13998 ;; FIXME: positions wrong.
13999 (push (list :latex-fragment (point) (point)) clist)))
14000
14001 (setq clist (nreverse (delq nil clist)))
14002 clist))
14003
14004 ;; FIXME: Compare with at-regexp-p Do we need both?
14005 (defun org-in-regexp (re &optional nlines visually)
14006 "Check if point is inside a match of regexp.
14007 Normally only the current line is checked, but you can include NLINES extra
14008 lines both before and after point into the search.
14009 If VISUALLY is set, require that the cursor is not after the match but
14010 really on, so that the block visually is on the match."
14011 (catch 'exit
14012 (let ((pos (point))
14013 (eol (point-at-eol (+ 1 (or nlines 0))))
14014 (inc (if visually 1 0)))
14015 (save-excursion
14016 (beginning-of-line (- 1 (or nlines 0)))
14017 (while (re-search-forward re eol t)
14018 (if (and (<= (match-beginning 0) pos)
14019 (>= (+ inc (match-end 0)) pos))
14020 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14021
14022 (defun org-at-regexp-p (regexp)
14023 "Is point inside a match of REGEXP in the current line?"
14024 (catch 'exit
14025 (save-excursion
14026 (let ((pos (point)) (end (point-at-eol)))
14027 (beginning-of-line 1)
14028 (while (re-search-forward regexp end t)
14029 (if (and (<= (match-beginning 0) pos)
14030 (>= (match-end 0) pos))
14031 (throw 'exit t)))
14032 nil))))
14033
14034 (defun org-occur-in-agenda-files (regexp &optional nlines)
14035 "Call `multi-occur' with buffers for all agenda files."
14036 (interactive "sOrg-files matching: \np")
14037 (let* ((files (org-agenda-files))
14038 (tnames (mapcar 'file-truename files))
14039 (extra org-agenda-text-search-extra-files)
14040 f)
14041 (when (eq (car extra) 'agenda-archives)
14042 (setq extra (cdr extra))
14043 (setq files (org-add-archive-files files)))
14044 (while (setq f (pop extra))
14045 (unless (member (file-truename f) tnames)
14046 (add-to-list 'files f 'append)
14047 (add-to-list 'tnames (file-truename f) 'append)))
14048 (multi-occur
14049 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14050 regexp)))
14051
14052 (if (boundp 'occur-mode-find-occurrence-hook)
14053 ;; Emacs 23
14054 (add-hook 'occur-mode-find-occurrence-hook
14055 (lambda ()
14056 (when (org-mode-p)
14057 (org-reveal))))
14058 ;; Emacs 22
14059 (defadvice occur-mode-goto-occurrence
14060 (after org-occur-reveal activate)
14061 (and (org-mode-p) (org-reveal)))
14062 (defadvice occur-mode-goto-occurrence-other-window
14063 (after org-occur-reveal activate)
14064 (and (org-mode-p) (org-reveal)))
14065 (defadvice occur-mode-display-occurrence
14066 (after org-occur-reveal activate)
14067 (when (org-mode-p)
14068 (let ((pos (occur-mode-find-occurrence)))
14069 (with-current-buffer (marker-buffer pos)
14070 (save-excursion
14071 (goto-char pos)
14072 (org-reveal)))))))
14073
14074 (defun org-uniquify (list)
14075 "Remove duplicate elements from LIST."
14076 (let (res)
14077 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14078 res))
14079
14080 (defun org-delete-all (elts list)
14081 "Remove all elements in ELTS from LIST."
14082 (while elts
14083 (setq list (delete (pop elts) list)))
14084 list)
14085
14086 (defun org-back-over-empty-lines ()
14087 "Move backwards over whitespace, to the beginning of the first empty line.
14088 Returns the number of empty lines passed."
14089 (let ((pos (point)))
14090 (skip-chars-backward " \t\n\r")
14091 (beginning-of-line 2)
14092 (goto-char (min (point) pos))
14093 (count-lines (point) pos)))
14094
14095 (defun org-skip-whitespace ()
14096 (skip-chars-forward " \t\n\r"))
14097
14098 (defun org-point-in-group (point group &optional context)
14099 "Check if POINT is in match-group GROUP.
14100 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14101 match. If the match group does ot exist or point is not inside it,
14102 return nil."
14103 (and (match-beginning group)
14104 (>= point (match-beginning group))
14105 (<= point (match-end group))
14106 (if context
14107 (list context (match-beginning group) (match-end group))
14108 t)))
14109
14110 (defun org-switch-to-buffer-other-window (&rest args)
14111 "Switch to buffer in a second window on the current frame.
14112 In particular, do not allow pop-up frames."
14113 (let (pop-up-frames special-display-buffer-names special-display-regexps
14114 special-display-function)
14115 (apply 'switch-to-buffer-other-window args)))
14116
14117 (defun org-combine-plists (&rest plists)
14118 "Create a single property list from all plists in PLISTS.
14119 The process starts by copying the first list, and then setting properties
14120 from the other lists. Settings in the last list are the most significant
14121 ones and overrule settings in the other lists."
14122 (let ((rtn (copy-sequence (pop plists)))
14123 p v ls)
14124 (while plists
14125 (setq ls (pop plists))
14126 (while ls
14127 (setq p (pop ls) v (pop ls))
14128 (setq rtn (plist-put rtn p v))))
14129 rtn))
14130
14131 (defun org-move-line-down (arg)
14132 "Move the current line down. With prefix argument, move it past ARG lines."
14133 (interactive "p")
14134 (let ((col (current-column))
14135 beg end pos)
14136 (beginning-of-line 1) (setq beg (point))
14137 (beginning-of-line 2) (setq end (point))
14138 (beginning-of-line (+ 1 arg))
14139 (setq pos (move-marker (make-marker) (point)))
14140 (insert (delete-and-extract-region beg end))
14141 (goto-char pos)
14142 (org-move-to-column col)))
14143
14144 (defun org-move-line-up (arg)
14145 "Move the current line up. With prefix argument, move it past ARG lines."
14146 (interactive "p")
14147 (let ((col (current-column))
14148 beg end pos)
14149 (beginning-of-line 1) (setq beg (point))
14150 (beginning-of-line 2) (setq end (point))
14151 (beginning-of-line (- arg))
14152 (setq pos (move-marker (make-marker) (point)))
14153 (insert (delete-and-extract-region beg end))
14154 (goto-char pos)
14155 (org-move-to-column col)))
14156
14157 (defun org-replace-escapes (string table)
14158 "Replace %-escapes in STRING with values in TABLE.
14159 TABLE is an association list with keys like \"%a\" and string values.
14160 The sequences in STRING may contain normal field width and padding information,
14161 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14162 so values can contain further %-escapes if they are define later in TABLE."
14163 (let ((case-fold-search nil)
14164 e re rpl)
14165 (while (setq e (pop table))
14166 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14167 (while (string-match re string)
14168 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14169 (cdr e)))
14170 (setq string (replace-match rpl t t string))))
14171 string))
14172
14173
14174 (defun org-sublist (list start end)
14175 "Return a section of LIST, from START to END.
14176 Counting starts at 1."
14177 (let (rtn (c start))
14178 (setq list (nthcdr (1- start) list))
14179 (while (and list (<= c end))
14180 (push (pop list) rtn)
14181 (setq c (1+ c)))
14182 (nreverse rtn)))
14183
14184 (defun org-find-base-buffer-visiting (file)
14185 "Like `find-buffer-visiting' but alway return the base buffer and
14186 not an indirect buffer."
14187 (let ((buf (find-buffer-visiting file)))
14188 (if buf
14189 (or (buffer-base-buffer buf) buf)
14190 nil)))
14191
14192 (defun org-image-file-name-regexp (&optional extensions)
14193 "Return regexp matching the file names of images.
14194 If EXTENSIONS is given, only match these."
14195 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14196 (image-file-name-regexp)
14197 (let ((image-file-name-extensions
14198 (or extensions
14199 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14200 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14201 (concat "\\."
14202 (regexp-opt (nconc (mapcar 'upcase
14203 image-file-name-extensions)
14204 image-file-name-extensions)
14205 t)
14206 "\\'"))))
14207
14208 (defun org-file-image-p (file &optional extensions)
14209 "Return non-nil if FILE is an image."
14210 (save-match-data
14211 (string-match (org-image-file-name-regexp extensions) file)))
14212
14213 (defun org-get-cursor-date ()
14214 "Return the date at cursor in as a time.
14215 This works in the calendar and in the agenda, anywhere else it just
14216 returns the current time."
14217 (let (date day defd)
14218 (cond
14219 ((eq major-mode 'calendar-mode)
14220 (setq date (calendar-cursor-to-date)
14221 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14222 ((eq major-mode 'org-agenda-mode)
14223 (setq day (get-text-property (point) 'day))
14224 (if day
14225 (setq date (calendar-gregorian-from-absolute day)
14226 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14227 (nth 2 date))))))
14228 (or defd (current-time))))
14229
14230 (defvar org-agenda-action-marker (make-marker)
14231 "Marker pointing to the entry for the next agenda action.")
14232
14233 (defun org-mark-entry-for-agenda-action ()
14234 "Mark the current entry as target of an agenda action.
14235 Agenda actions are actions executed from the agenda with the key `k',
14236 which make use of the date at the cursor."
14237 (interactive)
14238 (move-marker org-agenda-action-marker
14239 (save-excursion (org-back-to-heading t) (point))
14240 (current-buffer))
14241 (message
14242 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14243
14244 ;;; Paragraph filling stuff.
14245 ;; We want this to be just right, so use the full arsenal.
14246
14247 (defun org-indent-line-function ()
14248 "Indent line like previous, but further if previous was headline or item."
14249 (interactive)
14250 (let* ((pos (point))
14251 (itemp (org-at-item-p))
14252 column bpos bcol tpos tcol bullet btype bullet-type)
14253 ;; Find the previous relevant line
14254 (beginning-of-line 1)
14255 (cond
14256 ((looking-at "#") (setq column 0))
14257 ((looking-at "\\*+ ") (setq column 0))
14258 (t
14259 (beginning-of-line 0)
14260 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14261 (beginning-of-line 0))
14262 (cond
14263 ((looking-at "\\*+[ \t]+")
14264 (if (not org-adapt-indentation)
14265 (setq column 0)
14266 (goto-char (match-end 0))
14267 (setq column (current-column))))
14268 ((org-in-item-p)
14269 (org-beginning-of-item)
14270 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14271 (setq bpos (match-beginning 1) tpos (match-end 0)
14272 bcol (progn (goto-char bpos) (current-column))
14273 tcol (progn (goto-char tpos) (current-column))
14274 bullet (match-string 1)
14275 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14276 (if (> tcol (+ bcol org-description-max-indent))
14277 (setq tcol (+ bcol 5)))
14278 (if (not itemp)
14279 (setq column tcol)
14280 (goto-char pos)
14281 (beginning-of-line 1)
14282 (if (looking-at "\\S-")
14283 (progn
14284 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14285 (setq bullet (match-string 1)
14286 btype (if (string-match "[0-9]" bullet) "n" bullet))
14287 (setq column (if (equal btype bullet-type) bcol tcol)))
14288 (setq column (org-get-indentation)))))
14289 (t (setq column (org-get-indentation))))))
14290 (goto-char pos)
14291 (if (<= (current-column) (current-indentation))
14292 (org-indent-line-to column)
14293 (save-excursion (org-indent-line-to column)))
14294 (setq column (current-column))
14295 (beginning-of-line 1)
14296 (if (looking-at
14297 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14298 (replace-match (concat "\\1" (format org-property-format
14299 (match-string 2) (match-string 3)))
14300 t nil))
14301 (org-move-to-column column)))
14302
14303 (defun org-set-autofill-regexps ()
14304 (interactive)
14305 ;; In the paragraph separator we include headlines, because filling
14306 ;; text in a line directly attached to a headline would otherwise
14307 ;; fill the headline as well.
14308 (org-set-local 'comment-start-skip "^#+[ \t]*")
14309 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14310 ;; The paragraph starter includes hand-formatted lists.
14311 (org-set-local 'paragraph-start
14312 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14313 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14314 ;; But only if the user has not turned off tables or fixed-width regions
14315 (org-set-local
14316 'auto-fill-inhibit-regexp
14317 (concat "\\*+ \\|#\\+"
14318 "\\|[ \t]*" org-keyword-time-regexp
14319 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14320 (concat
14321 "\\|[ \t]*["
14322 (if org-enable-table-editor "|" "")
14323 (if org-enable-fixed-width-editor ":" "")
14324 "]"))))
14325 ;; We use our own fill-paragraph function, to make sure that tables
14326 ;; and fixed-width regions are not wrapped. That function will pass
14327 ;; through to `fill-paragraph' when appropriate.
14328 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14329 ; Adaptive filling: To get full control, first make sure that
14330 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14331 (org-set-local 'adaptive-fill-regexp "\000")
14332 (org-set-local 'adaptive-fill-function
14333 'org-adaptive-fill-function)
14334 (org-set-local
14335 'align-mode-rules-list
14336 '((org-in-buffer-settings
14337 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14338 (modes . '(org-mode))))))
14339
14340 (defun org-fill-paragraph (&optional justify)
14341 "Re-align a table, pass through to fill-paragraph if no table."
14342 (let ((table-p (org-at-table-p))
14343 (table.el-p (org-at-table.el-p)))
14344 (cond ((and (equal (char-after (point-at-bol)) ?*)
14345 (save-excursion (goto-char (point-at-bol))
14346 (looking-at outline-regexp)))
14347 t) ; skip headlines
14348 (table.el-p t) ; skip table.el tables
14349 (table-p (org-table-align) t) ; align org-mode tables
14350 (t nil)))) ; call paragraph-fill
14351
14352 ;; For reference, this is the default value of adaptive-fill-regexp
14353 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14354
14355 (defun org-adaptive-fill-function ()
14356 "Return a fill prefix for org-mode files.
14357 In particular, this makes sure hanging paragraphs for hand-formatted lists
14358 work correctly."
14359 (cond ((looking-at "#[ \t]+")
14360 (match-string 0))
14361 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14362 (save-excursion
14363 (if (> (match-end 1) (+ (match-beginning 1)
14364 org-description-max-indent))
14365 (goto-char (+ (match-beginning 1) 5))
14366 (goto-char (match-end 0)))
14367 (make-string (current-column) ?\ )))
14368 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14369 (save-excursion
14370 (goto-char (match-end 0))
14371 (make-string (current-column) ?\ )))
14372 (t nil)))
14373
14374 ;;; Other stuff.
14375
14376 (defun org-toggle-fixed-width-section (arg)
14377 "Toggle the fixed-width export.
14378 If there is no active region, the QUOTE keyword at the current headline is
14379 inserted or removed. When present, it causes the text between this headline
14380 and the next to be exported as fixed-width text, and unmodified.
14381 If there is an active region, this command adds or removes a colon as the
14382 first character of this line. If the first character of a line is a colon,
14383 this line is also exported in fixed-width font."
14384 (interactive "P")
14385 (let* ((cc 0)
14386 (regionp (org-region-active-p))
14387 (beg (if regionp (region-beginning) (point)))
14388 (end (if regionp (region-end)))
14389 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14390 (case-fold-search nil)
14391 (re "[ \t]*\\(:\\)")
14392 off)
14393 (if regionp
14394 (save-excursion
14395 (goto-char beg)
14396 (setq cc (current-column))
14397 (beginning-of-line 1)
14398 (setq off (looking-at re))
14399 (while (> nlines 0)
14400 (setq nlines (1- nlines))
14401 (beginning-of-line 1)
14402 (cond
14403 (arg
14404 (org-move-to-column cc t)
14405 (insert ":\n")
14406 (forward-line -1))
14407 ((and off (looking-at re))
14408 (replace-match "" t t nil 1))
14409 ((not off) (org-move-to-column cc t) (insert ":")))
14410 (forward-line 1)))
14411 (save-excursion
14412 (org-back-to-heading)
14413 (if (looking-at (concat outline-regexp
14414 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14415 (replace-match "" t t nil 1)
14416 (if (looking-at outline-regexp)
14417 (progn
14418 (goto-char (match-end 0))
14419 (insert org-quote-string " "))))))))
14420
14421 ;;;; Functions extending outline functionality
14422
14423 (defun org-beginning-of-line (&optional arg)
14424 "Go to the beginning of the current line. If that is invisible, continue
14425 to a visible line beginning. This makes the function of C-a more intuitive.
14426 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14427 first attempt, and only move to after the tags when the cursor is already
14428 beyond the end of the headline."
14429 (interactive "P")
14430 (let ((pos (point)) refpos)
14431 (beginning-of-line 1)
14432 (if (bobp)
14433 nil
14434 (backward-char 1)
14435 (if (org-invisible-p)
14436 (while (and (not (bobp)) (org-invisible-p))
14437 (backward-char 1)
14438 (beginning-of-line 1))
14439 (forward-char 1)))
14440 (when org-special-ctrl-a/e
14441 (cond
14442 ((and (looking-at org-complex-heading-regexp)
14443 (= (char-after (match-end 1)) ?\ ))
14444 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14445 (point-at-eol)))
14446 (goto-char
14447 (if (eq org-special-ctrl-a/e t)
14448 (cond ((> pos refpos) refpos)
14449 ((= pos (point)) refpos)
14450 (t (point)))
14451 (cond ((> pos (point)) (point))
14452 ((not (eq last-command this-command)) (point))
14453 (t refpos)))))
14454 ((org-at-item-p)
14455 (goto-char
14456 (if (eq org-special-ctrl-a/e t)
14457 (cond ((> pos (match-end 4)) (match-end 4))
14458 ((= pos (point)) (match-end 4))
14459 (t (point)))
14460 (cond ((> pos (point)) (point))
14461 ((not (eq last-command this-command)) (point))
14462 (t (match-end 4))))))))
14463 (org-no-warnings
14464 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14465
14466 (defun org-end-of-line (&optional arg)
14467 "Go to the end of the line.
14468 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14469 first attempt, and only move to after the tags when the cursor is already
14470 beyond the end of the headline."
14471 (interactive "P")
14472 (if (or (not org-special-ctrl-a/e)
14473 (not (org-on-heading-p)))
14474 (end-of-line arg)
14475 (let ((pos (point)))
14476 (beginning-of-line 1)
14477 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14478 (if (eq org-special-ctrl-a/e t)
14479 (if (or (< pos (match-beginning 1))
14480 (= pos (match-end 0)))
14481 (goto-char (match-beginning 1))
14482 (goto-char (match-end 0)))
14483 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14484 (goto-char (match-end 0))
14485 (goto-char (match-beginning 1))))
14486 (end-of-line arg))))
14487 (org-no-warnings
14488 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14489
14490
14491 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14492 (define-key org-mode-map "\C-e" 'org-end-of-line)
14493
14494 (defun org-kill-line (&optional arg)
14495 "Kill line, to tags or end of line."
14496 (interactive "P")
14497 (cond
14498 ((or (not org-special-ctrl-k)
14499 (bolp)
14500 (not (org-on-heading-p)))
14501 (call-interactively 'kill-line))
14502 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14503 (kill-region (point) (match-beginning 1))
14504 (org-set-tags nil t))
14505 (t (kill-region (point) (point-at-eol)))))
14506
14507 (define-key org-mode-map "\C-k" 'org-kill-line)
14508
14509 (defun org-yank (&optional arg)
14510 "Yank. If the kill is a subtree, treat it specially.
14511 This command will look at the current kill and check if is a single
14512 subtree, or a series of subtrees[1]. If it passes the test, and if the
14513 cursor is at the beginning of a line or after the stars of a currently
14514 empty headline, then the yank is handled specially. How exactly depends
14515 on the value of the following variables, both set by default.
14516
14517 org-yank-folded-subtrees
14518 When set, the subtree(s) will be folded after insertion, but only
14519 if doing so would now swallow text after the yanked text.
14520
14521 org-yank-adjusted-subtrees
14522 When set, the subtree will be promoted or demoted in order to
14523 fit into the local outline tree structure, which means that the level
14524 will be adjusted so that it becomes the smaller one of the two
14525 *visible* surrounding headings.
14526
14527 Any prefix to this command will cause `yank' to be called directly with
14528 no special treatment. In particular, a simple `C-u' prefix will just
14529 plainly yank the text as it is.
14530
14531 \[1] Basically, the test checks if the first non-white line is a heading
14532 and if there are no other headings with fewer stars."
14533 (interactive "P")
14534 (setq this-command 'yank)
14535 (if arg
14536 (call-interactively 'yank)
14537 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14538 (and (org-kill-is-subtree-p)
14539 (or (bolp)
14540 (and (looking-at "[ \t]*$")
14541 (string-match
14542 "\\`\\*+\\'"
14543 (buffer-substring (point-at-bol) (point)))))))
14544 swallowp)
14545 (cond
14546 ((and subtreep org-yank-folded-subtrees)
14547 (let ((beg (point))
14548 end)
14549 (if (and subtreep org-yank-adjusted-subtrees)
14550 (org-paste-subtree nil nil 'for-yank)
14551 (call-interactively 'yank))
14552 (setq end (point))
14553 (goto-char beg)
14554 (when (and (bolp) subtreep
14555 (not (setq swallowp
14556 (org-yank-folding-would-swallow-text beg end))))
14557 (or (looking-at outline-regexp)
14558 (re-search-forward (concat "^" outline-regexp) end t))
14559 (while (and (< (point) end) (looking-at outline-regexp))
14560 (hide-subtree)
14561 (org-cycle-show-empty-lines 'folded)
14562 (condition-case nil
14563 (outline-forward-same-level 1)
14564 (error (goto-char end)))))
14565 (when swallowp
14566 (message
14567 "Yanked text not folded because that would swallow text"))
14568 (goto-char end)
14569 (skip-chars-forward " \t\n\r")
14570 (beginning-of-line 1)
14571 (push-mark beg 'nomsg)))
14572 ((and subtreep org-yank-adjusted-subtrees)
14573 (let ((beg (point-at-bol)))
14574 (org-paste-subtree nil nil 'for-yank)
14575 (push-mark beg 'nomsg)))
14576 (t
14577 (call-interactively 'yank))))))
14578
14579 (defun org-yank-folding-would-swallow-text (beg end)
14580 "Would hide-subtree at BEG swallow any text after END?"
14581 (let (level)
14582 (save-excursion
14583 (goto-char beg)
14584 (when (or (looking-at outline-regexp)
14585 (re-search-forward (concat "^" outline-regexp) end t))
14586 (setq level (org-outline-level)))
14587 (goto-char end)
14588 (skip-chars-forward " \t\r\n\v\f")
14589 (if (or (eobp)
14590 (and (bolp) (looking-at org-outline-regexp)
14591 (<= (org-outline-level) level)))
14592 nil ; Nothing would be swallowed
14593 t)))) ; something would swallow
14594
14595 (define-key org-mode-map "\C-y" 'org-yank)
14596
14597 (defun org-invisible-p ()
14598 "Check if point is at a character currently not visible."
14599 ;; Early versions of noutline don't have `outline-invisible-p'.
14600 (if (fboundp 'outline-invisible-p)
14601 (outline-invisible-p)
14602 (get-char-property (point) 'invisible)))
14603
14604 (defun org-invisible-p2 ()
14605 "Check if point is at a character currently not visible."
14606 (save-excursion
14607 (if (and (eolp) (not (bobp))) (backward-char 1))
14608 ;; Early versions of noutline don't have `outline-invisible-p'.
14609 (if (fboundp 'outline-invisible-p)
14610 (outline-invisible-p)
14611 (get-char-property (point) 'invisible))))
14612
14613 (defun org-back-to-heading (&optional invisible-ok)
14614 "Call `outline-back-to-heading', but provide a better error message."
14615 (condition-case nil
14616 (outline-back-to-heading invisible-ok)
14617 (error (error "Before first headline at position %d in buffer %s"
14618 (point) (current-buffer)))))
14619
14620 (defun org-before-first-heading-p ()
14621 "Before first heading?"
14622 (save-excursion
14623 (null (re-search-backward "^\\*+ " nil t))))
14624
14625 (defalias 'org-on-heading-p 'outline-on-heading-p)
14626 (defalias 'org-at-heading-p 'outline-on-heading-p)
14627 (defun org-at-heading-or-item-p ()
14628 (or (org-on-heading-p) (org-at-item-p)))
14629
14630 (defun org-on-target-p ()
14631 (or (org-in-regexp org-radio-target-regexp)
14632 (org-in-regexp org-target-regexp)))
14633
14634 (defun org-up-heading-all (arg)
14635 "Move to the heading line of which the present line is a subheading.
14636 This function considers both visible and invisible heading lines.
14637 With argument, move up ARG levels."
14638 (if (fboundp 'outline-up-heading-all)
14639 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14640 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14641
14642 (defun org-up-heading-safe ()
14643 "Move to the heading line of which the present line is a subheading.
14644 This version will not throw an error. It will return the level of the
14645 headline found, or nil if no higher level is found."
14646 (let (start-level re)
14647 (org-back-to-heading t)
14648 (setq start-level (funcall outline-level))
14649 (if (equal start-level 1)
14650 nil
14651 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14652 (if (re-search-backward re nil t)
14653 (funcall outline-level)))))
14654
14655 (defun org-first-sibling-p ()
14656 "Is this heading the first child of its parents?"
14657 (interactive)
14658 (let ((re (concat "^" outline-regexp))
14659 level l)
14660 (unless (org-at-heading-p t)
14661 (error "Not at a heading"))
14662 (setq level (funcall outline-level))
14663 (save-excursion
14664 (if (not (re-search-backward re nil t))
14665 t
14666 (setq l (funcall outline-level))
14667 (< l level)))))
14668
14669 (defun org-goto-sibling (&optional previous)
14670 "Goto the next sibling, even if it is invisible.
14671 When PREVIOUS is set, go to the previous sibling instead. Returns t
14672 when a sibling was found. When none is found, return nil and don't
14673 move point."
14674 (let ((fun (if previous 're-search-backward 're-search-forward))
14675 (pos (point))
14676 (re (concat "^" outline-regexp))
14677 level l)
14678 (when (condition-case nil (org-back-to-heading t) (error nil))
14679 (setq level (funcall outline-level))
14680 (catch 'exit
14681 (or previous (forward-char 1))
14682 (while (funcall fun re nil t)
14683 (setq l (funcall outline-level))
14684 (when (< l level) (goto-char pos) (throw 'exit nil))
14685 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14686 (goto-char pos)
14687 nil))))
14688
14689 (defun org-show-siblings ()
14690 "Show all siblings of the current headline."
14691 (save-excursion
14692 (while (org-goto-sibling) (org-flag-heading nil)))
14693 (save-excursion
14694 (while (org-goto-sibling 'previous)
14695 (org-flag-heading nil))))
14696
14697 (defun org-show-hidden-entry ()
14698 "Show an entry where even the heading is hidden."
14699 (save-excursion
14700 (org-show-entry)))
14701
14702 (defun org-flag-heading (flag &optional entry)
14703 "Flag the current heading. FLAG non-nil means make invisible.
14704 When ENTRY is non-nil, show the entire entry."
14705 (save-excursion
14706 (org-back-to-heading t)
14707 ;; Check if we should show the entire entry
14708 (if entry
14709 (progn
14710 (org-show-entry)
14711 (save-excursion
14712 (and (outline-next-heading)
14713 (org-flag-heading nil))))
14714 (outline-flag-region (max (point-min) (1- (point)))
14715 (save-excursion (outline-end-of-heading) (point))
14716 flag))))
14717
14718 (defun org-forward-same-level (arg)
14719 "Move forward to the ARG'th subheading at same level as this one.
14720 Stop at the first and last subheadings of a superior heading.
14721 This is like outline-forward-same-level, but invisible headings are ok."
14722 (interactive "p")
14723 (org-back-to-heading t)
14724 (while (> arg 0)
14725 (let ((point-to-move-to (save-excursion
14726 (org-get-next-sibling))))
14727 (if point-to-move-to
14728 (progn
14729 (goto-char point-to-move-to)
14730 (setq arg (1- arg)))
14731 (progn
14732 (setq arg 0)
14733 (error "No following same-level heading"))))))
14734
14735 (defun org-get-next-sibling ()
14736 "Move to next heading of the same level, and return point.
14737 If there is no such heading, return nil.
14738 This is like outline-next-sibling, but invisible headings are ok."
14739 (let ((level (funcall outline-level)))
14740 (outline-next-heading)
14741 (while (and (not (eobp)) (> (funcall outline-level) level))
14742 (outline-next-heading))
14743 (if (or (eobp) (< (funcall outline-level) level))
14744 nil
14745 (point))))
14746
14747 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14748 ;; This is an exact copy of the original function, but it uses
14749 ;; `org-back-to-heading', to make it work also in invisible
14750 ;; trees. And is uses an invisible-OK argument.
14751 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14752 (org-back-to-heading invisible-OK)
14753 (let ((first t)
14754 (level (funcall outline-level)))
14755 (while (and (not (eobp))
14756 (or first (> (funcall outline-level) level)))
14757 (setq first nil)
14758 (outline-next-heading))
14759 (unless to-heading
14760 (if (memq (preceding-char) '(?\n ?\^M))
14761 (progn
14762 ;; Go to end of line before heading
14763 (forward-char -1)
14764 (if (memq (preceding-char) '(?\n ?\^M))
14765 ;; leave blank line before heading
14766 (forward-char -1))))))
14767 (point))
14768
14769 (defun org-show-subtree ()
14770 "Show everything after this heading at deeper levels."
14771 (outline-flag-region
14772 (point)
14773 (save-excursion
14774 (outline-end-of-subtree) (outline-next-heading) (point))
14775 nil))
14776
14777 (defun org-show-entry ()
14778 "Show the body directly following this heading.
14779 Show the heading too, if it is currently invisible."
14780 (interactive)
14781 (save-excursion
14782 (condition-case nil
14783 (progn
14784 (org-back-to-heading t)
14785 (outline-flag-region
14786 (max (point-min) (1- (point)))
14787 (save-excursion
14788 (re-search-forward
14789 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14790 (or (match-beginning 1) (point-max)))
14791 nil))
14792 (error nil))))
14793
14794 (defun org-make-options-regexp (kwds)
14795 "Make a regular expression for keyword lines."
14796 (concat
14797 "^"
14798 "#?[ \t]*\\+\\("
14799 (mapconcat 'regexp-quote kwds "\\|")
14800 "\\):[ \t]*"
14801 "\\(.+\\)"))
14802
14803 ;; Make isearch reveal the necessary context
14804 (defun org-isearch-end ()
14805 "Reveal context after isearch exits."
14806 (when isearch-success ; only if search was successful
14807 (if (featurep 'xemacs)
14808 ;; Under XEmacs, the hook is run in the correct place,
14809 ;; we directly show the context.
14810 (org-show-context 'isearch)
14811 ;; In Emacs the hook runs *before* restoring the overlays.
14812 ;; So we have to use a one-time post-command-hook to do this.
14813 ;; (Emacs 22 has a special variable, see function `org-mode')
14814 (unless (and (boundp 'isearch-mode-end-hook-quit)
14815 isearch-mode-end-hook-quit)
14816 ;; Only when the isearch was not quitted.
14817 (org-add-hook 'post-command-hook 'org-isearch-post-command
14818 'append 'local)))))
14819
14820 (defun org-isearch-post-command ()
14821 "Remove self from hook, and show context."
14822 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14823 (org-show-context 'isearch))
14824
14825
14826 ;;;; Integration with and fixes for other packages
14827
14828 ;;; Imenu support
14829
14830 (defvar org-imenu-markers nil
14831 "All markers currently used by Imenu.")
14832 (make-variable-buffer-local 'org-imenu-markers)
14833
14834 (defun org-imenu-new-marker (&optional pos)
14835 "Return a new marker for use by Imenu, and remember the marker."
14836 (let ((m (make-marker)))
14837 (move-marker m (or pos (point)))
14838 (push m org-imenu-markers)
14839 m))
14840
14841 (defun org-imenu-get-tree ()
14842 "Produce the index for Imenu."
14843 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14844 (setq org-imenu-markers nil)
14845 (let* ((n org-imenu-depth)
14846 (re (concat "^" outline-regexp))
14847 (subs (make-vector (1+ n) nil))
14848 (last-level 0)
14849 m tree level head)
14850 (save-excursion
14851 (save-restriction
14852 (widen)
14853 (goto-char (point-max))
14854 (while (re-search-backward re nil t)
14855 (setq level (org-reduced-level (funcall outline-level)))
14856 (when (<= level n)
14857 (looking-at org-complex-heading-regexp)
14858 (setq head (org-link-display-format
14859 (org-match-string-no-properties 4))
14860 m (org-imenu-new-marker))
14861 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14862 (if (>= level last-level)
14863 (push (cons head m) (aref subs level))
14864 (push (cons head (aref subs (1+ level))) (aref subs level))
14865 (loop for i from (1+ level) to n do (aset subs i nil)))
14866 (setq last-level level)))))
14867 (aref subs 1)))
14868
14869 (eval-after-load "imenu"
14870 '(progn
14871 (add-hook 'imenu-after-jump-hook
14872 (lambda ()
14873 (if (eq major-mode 'org-mode)
14874 (org-show-context 'org-goto))))))
14875
14876 (defun org-link-display-format (link)
14877 "Replace a link with either the description, or the link target
14878 if no description is present"
14879 (save-match-data
14880 (if (string-match org-bracket-link-analytic-regexp link)
14881 (replace-match (or (match-string 5 link)
14882 (concat (match-string 1 link)
14883 (match-string 3 link)))
14884 nil nil link)
14885 link)))
14886
14887 ;; Speedbar support
14888
14889 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14890 "Overlay marking the agenda restriction line in speedbar.")
14891 (org-overlay-put org-speedbar-restriction-lock-overlay
14892 'face 'org-agenda-restriction-lock)
14893 (org-overlay-put org-speedbar-restriction-lock-overlay
14894 'help-echo "Agendas are currently limited to this item.")
14895 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14896
14897 (defun org-speedbar-set-agenda-restriction ()
14898 "Restrict future agenda commands to the location at point in speedbar.
14899 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14900 (interactive)
14901 (require 'org-agenda)
14902 (let (p m tp np dir txt w)
14903 (cond
14904 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14905 'org-imenu t))
14906 (setq m (get-text-property p 'org-imenu-marker))
14907 (save-excursion
14908 (save-restriction
14909 (set-buffer (marker-buffer m))
14910 (goto-char m)
14911 (org-agenda-set-restriction-lock 'subtree))))
14912 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14913 'speedbar-function 'speedbar-find-file))
14914 (setq tp (previous-single-property-change
14915 (1+ p) 'speedbar-function)
14916 np (next-single-property-change
14917 tp 'speedbar-function)
14918 dir (speedbar-line-directory)
14919 txt (buffer-substring-no-properties (or tp (point-min))
14920 (or np (point-max))))
14921 (save-excursion
14922 (save-restriction
14923 (set-buffer (find-file-noselect
14924 (let ((default-directory dir))
14925 (expand-file-name txt))))
14926 (unless (org-mode-p)
14927 (error "Cannot restrict to non-Org-mode file"))
14928 (org-agenda-set-restriction-lock 'file))))
14929 (t (error "Don't know how to restrict Org-mode's agenda")))
14930 (org-move-overlay org-speedbar-restriction-lock-overlay
14931 (point-at-bol) (point-at-eol))
14932 (setq current-prefix-arg nil)
14933 (org-agenda-maybe-redo)))
14934
14935 (eval-after-load "speedbar"
14936 '(progn
14937 (speedbar-add-supported-extension ".org")
14938 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14939 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14940 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14941 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14942 (add-hook 'speedbar-visiting-tag-hook
14943 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
14944
14945
14946 ;;; Fixes and Hacks for problems with other packages
14947
14948 ;; Make flyspell not check words in links, to not mess up our keymap
14949 (defun org-mode-flyspell-verify ()
14950 "Don't let flyspell put overlays at active buttons."
14951 (not (get-text-property (point) 'keymap)))
14952
14953 ;; Make `bookmark-jump' show the jump location if it was hidden.
14954 (eval-after-load "bookmark"
14955 '(if (boundp 'bookmark-after-jump-hook)
14956 ;; We can use the hook
14957 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14958 ;; Hook not available, use advice
14959 (defadvice bookmark-jump (after org-make-visible activate)
14960 "Make the position visible."
14961 (org-bookmark-jump-unhide))))
14962
14963 ;; Make sure saveplace show the location if it was hidden
14964 (eval-after-load "saveplace"
14965 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14966 "Make the position visible."
14967 (org-bookmark-jump-unhide)))
14968
14969 (defun org-bookmark-jump-unhide ()
14970 "Unhide the current position, to show the bookmark location."
14971 (and (org-mode-p)
14972 (or (org-invisible-p)
14973 (save-excursion (goto-char (max (point-min) (1- (point))))
14974 (org-invisible-p)))
14975 (org-show-context 'bookmark-jump)))
14976
14977 ;; Make session.el ignore our circular variable
14978 (eval-after-load "session"
14979 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14980
14981 ;;;; Experimental code
14982
14983 (defun org-closed-in-range ()
14984 "Sparse tree of items closed in a certain time range.
14985 Still experimental, may disappear in the future."
14986 (interactive)
14987 ;; Get the time interval from the user.
14988 (let* ((time1 (time-to-seconds
14989 (org-read-date nil 'to-time nil "Starting date: ")))
14990 (time2 (time-to-seconds
14991 (org-read-date nil 'to-time nil "End date:")))
14992 ;; callback function
14993 (callback (lambda ()
14994 (let ((time
14995 (time-to-seconds
14996 (apply 'encode-time
14997 (org-parse-time-string
14998 (match-string 1))))))
14999 ;; check if time in interval
15000 (and (>= time time1) (<= time time2))))))
15001 ;; make tree, check each match with the callback
15002 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15003
15004
15005 ;;;; Finish up
15006
15007 (provide 'org)
15008
15009 (run-hooks 'org-load-hook)
15010
15011 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15012
15013 ;;; org.el ends here