]> code.delx.au - gnu-emacs/blob - lisp/org/org.el
2008-10-26 Carsten Dominik <dominik@science.uva.nl>
[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 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 6.10c
9 ;;
10 ;; This file is part of GNU Emacs.
11 ;;
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
16
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
21
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
25 ;;
26 ;;; Commentary:
27 ;;
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
30 ;;
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
45 ;;
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
49 ;;
50 ;; http://orgmode.org/org.html#Installation
51 ;;
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
59 ;;
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
62 ;;
63 ;;; Code:
64
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
69
70 ;;;; Require other packages
71
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum)
75 (require 'calendar))
76 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
77 ;; the file noutline.el being loaded.
78 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
79 ;; We require noutline, which might be provided in outline.el
80 (require 'outline) (require 'noutline)
81 ;; Other stuff we need.
82 (require 'time-date)
83 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
84 (require 'easymenu)
85
86 (require 'org-macs)
87 (require 'org-compat)
88 (require 'org-faces)
89 (require 'org-list)
90
91 ;;;; Customization variables
92
93 ;;; Version
94
95 (defconst org-version "6.10c"
96 "The version number of the file org.el.")
97
98 (defun org-version (&optional here)
99 "Show the org-mode version in the echo area.
100 With prefix arg HERE, insert it at point."
101 (interactive "P")
102 (let ((version (format "Org-mode version %s" org-version)))
103 (message version)
104 (if here
105 (insert version))))
106
107 ;;; Compatibility constants
108
109 ;;; The custom variables
110
111 (defgroup org nil
112 "Outline-based notes management and organizer."
113 :tag "Org"
114 :group 'outlines
115 :group 'hypermedia
116 :group 'calendar)
117
118 (defcustom org-load-hook nil
119 "Hook that is run after org.el has been loaded."
120 :group 'org
121 :type 'hook)
122
123 (defvar org-modules) ; defined below
124 (defvar org-modules-loaded nil
125 "Have the modules been loaded already?")
126
127 (defun org-load-modules-maybe (&optional force)
128 "Load all extensions listed in `org-default-extensions'."
129 (when (or force (not org-modules-loaded))
130 (mapc (lambda (ext)
131 (condition-case nil (require ext)
132 (error (message "Problems while trying to load feature `%s'" ext))))
133 org-modules)
134 (setq org-modules-loaded t)))
135
136 (defun org-set-modules (var value)
137 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
138 (set var value)
139 (when (featurep 'org)
140 (org-load-modules-maybe 'force)))
141
142 (when (org-bound-and-true-p org-modules)
143 (let ((a (member 'org-infojs org-modules)))
144 (and a (setcar a 'org-jsinfo))))
145
146 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-wl)
147 "Modules that should always be loaded together with org.el.
148 If a description starts with <C>, the file is not part of Emacs
149 and loading it will require that you have downloaded and properly installed
150 the org-mode distribution.
151
152 You can also use this system to load external packages (i.e. neither Org
153 core modules, not modules from the CONTRIB directory). Just add symbols
154 to the end of the list. If the package is called org-xyz.el, then you need
155 to add the symbol `xyz', and the package must have a call to
156
157 (provide 'org-xyz)"
158 :group 'org
159 :set 'org-set-modules
160 :type
161 '(set :greedy t
162 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
163 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
164 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
165 (const :tag " id: Global id's for identifying entries" org-id)
166 (const :tag " info: Links to Info nodes" org-info)
167 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
168 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
169 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
170 (const :tag " mew Links to Mew folders/messages" org-mew)
171 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
172 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
173 (const :tag " vm: Links to VM folders/messages" org-vm)
174 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
175 (const :tag " mouse: Additional mouse support" org-mouse)
176
177 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
178 (const :tag "C annotation-helper: Call Remeber directly from Browser" org-annotation-helper)
179 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
180 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
181 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
182 (const :tag "C eval: Include command output as text" org-eval)
183 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
184 (const :tag "C id: Global id's for identifying entries" org-id)
185 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
186 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
187 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
188 (const :tag "C mtags: Support for muse-like tags" org-mtags)
189 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
190 (const :tag "C registry: A registry for Org links" org-registry)
191 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
192 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
193 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
194 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
195 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
196
197
198 (defgroup org-startup nil
199 "Options concerning startup of Org-mode."
200 :tag "Org Startup"
201 :group 'org)
202
203 (defcustom org-startup-folded t
204 "Non-nil means, entering Org-mode will switch to OVERVIEW.
205 This can also be configured on a per-file basis by adding one of
206 the following lines anywhere in the buffer:
207
208 #+STARTUP: fold
209 #+STARTUP: nofold
210 #+STARTUP: content"
211 :group 'org-startup
212 :type '(choice
213 (const :tag "nofold: show all" nil)
214 (const :tag "fold: overview" t)
215 (const :tag "content: all headlines" content)))
216
217 (defcustom org-startup-truncated t
218 "Non-nil means, entering Org-mode will set `truncate-lines'.
219 This is useful since some lines containing links can be very long and
220 uninteresting. Also tables look terrible when wrapped."
221 :group 'org-startup
222 :type 'boolean)
223
224 (defcustom org-startup-align-all-tables nil
225 "Non-nil means, align all tables when visiting a file.
226 This is useful when the column width in tables is forced with <N> cookies
227 in table fields. Such tables will look correct only after the first re-align.
228 This can also be configured on a per-file basis by adding one of
229 the following lines anywhere in the buffer:
230 #+STARTUP: align
231 #+STARTUP: noalign"
232 :group 'org-startup
233 :type 'boolean)
234
235 (defcustom org-insert-mode-line-in-empty-file nil
236 "Non-nil means insert the first line setting Org-mode in empty files.
237 When the function `org-mode' is called interactively in an empty file, this
238 normally means that the file name does not automatically trigger Org-mode.
239 To ensure that the file will always be in Org-mode in the future, a
240 line enforcing Org-mode will be inserted into the buffer, if this option
241 has been set."
242 :group 'org-startup
243 :type 'boolean)
244
245 (defcustom org-replace-disputed-keys nil
246 "Non-nil means use alternative key bindings for some keys.
247 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
248 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
249 If you want to use Org-mode together with one of these other modes,
250 or more generally if you would like to move some Org-mode commands to
251 other keys, set this variable and configure the keys with the variable
252 `org-disputed-keys'.
253
254 This option is only relevant at load-time of Org-mode, and must be set
255 *before* org.el is loaded. Changing it requires a restart of Emacs to
256 become effective."
257 :group 'org-startup
258 :type 'boolean)
259
260 (defcustom org-use-extra-keys nil
261 "Non-nil means use extra key sequence definitions for certain
262 commands. This happens automatically if you run XEmacs or if
263 window-system is nil. This variable lets you do the same
264 manually. You must set it before loading org.
265
266 Example: on Carbon Emacs 22 running graphically, with an external
267 keyboard on a Powerbook, the default way of setting M-left might
268 not work for either Alt or ESC. Setting this variable will make
269 it work for ESC."
270 :group 'org-startup
271 :type 'boolean)
272
273 (if (fboundp 'defvaralias)
274 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
275
276 (defcustom org-disputed-keys
277 '(([(shift up)] . [(meta p)])
278 ([(shift down)] . [(meta n)])
279 ([(shift left)] . [(meta -)])
280 ([(shift right)] . [(meta +)])
281 ([(control shift right)] . [(meta shift +)])
282 ([(control shift left)] . [(meta shift -)]))
283 "Keys for which Org-mode and other modes compete.
284 This is an alist, cars are the default keys, second element specifies
285 the alternative to use when `org-replace-disputed-keys' is t.
286
287 Keys can be specified in any syntax supported by `define-key'.
288 The value of this option takes effect only at Org-mode's startup,
289 therefore you'll have to restart Emacs to apply it after changing."
290 :group 'org-startup
291 :type 'alist)
292
293 (defun org-key (key)
294 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
295 Or return the original if not disputed."
296 (if org-replace-disputed-keys
297 (let* ((nkey (key-description key))
298 (x (org-find-if (lambda (x)
299 (equal (key-description (car x)) nkey))
300 org-disputed-keys)))
301 (if x (cdr x) key))
302 key))
303
304 (defun org-find-if (predicate seq)
305 (catch 'exit
306 (while seq
307 (if (funcall predicate (car seq))
308 (throw 'exit (car seq))
309 (pop seq)))))
310
311 (defun org-defkey (keymap key def)
312 "Define a key, possibly translated, as returned by `org-key'."
313 (define-key keymap (org-key key) def))
314
315 (defcustom org-ellipsis nil
316 "The ellipsis to use in the Org-mode outline.
317 When nil, just use the standard three dots. When a string, use that instead,
318 When a face, use the standart 3 dots, but with the specified face.
319 The change affects only Org-mode (which will then use its own display table).
320 Changing this requires executing `M-x org-mode' in a buffer to become
321 effective."
322 :group 'org-startup
323 :type '(choice (const :tag "Default" nil)
324 (face :tag "Face" :value org-warning)
325 (string :tag "String" :value "...#")))
326
327 (defvar org-display-table nil
328 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
329
330 (defgroup org-keywords nil
331 "Keywords in Org-mode."
332 :tag "Org Keywords"
333 :group 'org)
334
335 (defcustom org-deadline-string "DEADLINE:"
336 "String to mark deadline entries.
337 A deadline is this string, followed by a time stamp. Should be a word,
338 terminated by a colon. You can insert a schedule keyword and
339 a timestamp with \\[org-deadline].
340 Changes become only effective after restarting Emacs."
341 :group 'org-keywords
342 :type 'string)
343
344 (defcustom org-scheduled-string "SCHEDULED:"
345 "String to mark scheduled TODO entries.
346 A schedule is this string, followed by a time stamp. Should be a word,
347 terminated by a colon. You can insert a schedule keyword and
348 a timestamp with \\[org-schedule].
349 Changes become only effective after restarting Emacs."
350 :group 'org-keywords
351 :type 'string)
352
353 (defcustom org-closed-string "CLOSED:"
354 "String used as the prefix for timestamps logging closing a TODO entry."
355 :group 'org-keywords
356 :type 'string)
357
358 (defcustom org-clock-string "CLOCK:"
359 "String used as prefix for timestamps clocking work hours on an item."
360 :group 'org-keywords
361 :type 'string)
362
363 (defcustom org-comment-string "COMMENT"
364 "Entries starting with this keyword will never be exported.
365 An entry can be toggled between COMMENT and normal with
366 \\[org-toggle-comment].
367 Changes become only effective after restarting Emacs."
368 :group 'org-keywords
369 :type 'string)
370
371 (defcustom org-quote-string "QUOTE"
372 "Entries starting with this keyword will be exported in fixed-width font.
373 Quoting applies only to the text in the entry following the headline, and does
374 not extend beyond the next headline, even if that is lower level.
375 An entry can be toggled between QUOTE and normal with
376 \\[org-toggle-fixed-width-section]."
377 :group 'org-keywords
378 :type 'string)
379
380 (defconst org-repeat-re
381 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
382 "Regular expression for specifying repeated events.
383 After a match, group 1 contains the repeat expression.")
384
385 (defgroup org-structure nil
386 "Options concerning the general structure of Org-mode files."
387 :tag "Org Structure"
388 :group 'org)
389
390 (defgroup org-reveal-location nil
391 "Options about how to make context of a location visible."
392 :tag "Org Reveal Location"
393 :group 'org-structure)
394
395 (defconst org-context-choice
396 '(choice
397 (const :tag "Always" t)
398 (const :tag "Never" nil)
399 (repeat :greedy t :tag "Individual contexts"
400 (cons
401 (choice :tag "Context"
402 (const agenda)
403 (const org-goto)
404 (const occur-tree)
405 (const tags-tree)
406 (const link-search)
407 (const mark-goto)
408 (const bookmark-jump)
409 (const isearch)
410 (const default))
411 (boolean))))
412 "Contexts for the reveal options.")
413
414 (defcustom org-show-hierarchy-above '((default . t))
415 "Non-nil means, show full hierarchy when revealing a location.
416 Org-mode often shows locations in an org-mode file which might have
417 been invisible before. When this is set, the hierarchy of headings
418 above the exposed location is shown.
419 Turning this off for example for sparse trees makes them very compact.
420 Instead of t, this can also be an alist specifying this option for different
421 contexts. Valid contexts are
422 agenda when exposing an entry from the agenda
423 org-goto when using the command `org-goto' on key C-c C-j
424 occur-tree when using the command `org-occur' on key C-c /
425 tags-tree when constructing a sparse tree based on tags matches
426 link-search when exposing search matches associated with a link
427 mark-goto when exposing the jump goal of a mark
428 bookmark-jump when exposing a bookmark location
429 isearch when exiting from an incremental search
430 default default for all contexts not set explicitly"
431 :group 'org-reveal-location
432 :type org-context-choice)
433
434 (defcustom org-show-following-heading '((default . nil))
435 "Non-nil means, show following heading when revealing a location.
436 Org-mode often shows locations in an org-mode file which might have
437 been invisible before. When this is set, the heading following the
438 match is shown.
439 Turning this off for example for sparse trees makes them very compact,
440 but makes it harder to edit the location of the match. In such a case,
441 use the command \\[org-reveal] to show more context.
442 Instead of t, this can also be an alist specifying this option for different
443 contexts. See `org-show-hierarchy-above' for valid contexts."
444 :group 'org-reveal-location
445 :type org-context-choice)
446
447 (defcustom org-show-siblings '((default . nil) (isearch t))
448 "Non-nil means, show all sibling heading when revealing a location.
449 Org-mode often shows locations in an org-mode file which might have
450 been invisible before. When this is set, the sibling of the current entry
451 heading are all made visible. If `org-show-hierarchy-above' is t,
452 the same happens on each level of the hierarchy above the current entry.
453
454 By default this is on for the isearch context, off for all other contexts.
455 Turning this off for example for sparse trees makes them very compact,
456 but makes it harder to edit the location of the match. In such a case,
457 use the command \\[org-reveal] to show more context.
458 Instead of t, this can also be an alist specifying this option for different
459 contexts. See `org-show-hierarchy-above' for valid contexts."
460 :group 'org-reveal-location
461 :type org-context-choice)
462
463 (defcustom org-show-entry-below '((default . nil))
464 "Non-nil means, show the entry below a headline when revealing a location.
465 Org-mode often shows locations in an org-mode file which might have
466 been invisible before. When this is set, the text below the headline that is
467 exposed is also shown.
468
469 By default this is off for all contexts.
470 Instead of t, this can also be an alist specifying this option for different
471 contexts. See `org-show-hierarchy-above' for valid contexts."
472 :group 'org-reveal-location
473 :type org-context-choice)
474
475 (defcustom org-indirect-buffer-display 'other-window
476 "How should indirect tree buffers be displayed?
477 This applies to indirect buffers created with the commands
478 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
479 Valid values are:
480 current-window Display in the current window
481 other-window Just display in another window.
482 dedicated-frame Create one new frame, and re-use it each time.
483 new-frame Make a new frame each time. Note that in this case
484 previously-made indirect buffers are kept, and you need to
485 kill these buffers yourself."
486 :group 'org-structure
487 :group 'org-agenda-windows
488 :type '(choice
489 (const :tag "In current window" current-window)
490 (const :tag "In current frame, other window" other-window)
491 (const :tag "Each time a new frame" new-frame)
492 (const :tag "One dedicated frame" dedicated-frame)))
493
494 (defgroup org-cycle nil
495 "Options concerning visibility cycling in Org-mode."
496 :tag "Org Cycle"
497 :group 'org-structure)
498
499 (defcustom org-drawers '("PROPERTIES" "CLOCK")
500 "Names of drawers. Drawers are not opened by cycling on the headline above.
501 Drawers only open with a TAB on the drawer line itself. A drawer looks like
502 this:
503 :DRAWERNAME:
504 .....
505 :END:
506 The drawer \"PROPERTIES\" is special for capturing properties through
507 the property API.
508
509 Drawers can be defined on the per-file basis with a line like:
510
511 #+DRAWERS: HIDDEN STATE PROPERTIES"
512 :group 'org-structure
513 :type '(repeat (string :tag "Drawer Name")))
514
515 (defcustom org-cycle-global-at-bob nil
516 "Cycle globally if cursor is at beginning of buffer and not at a headline.
517 This makes it possible to do global cycling without having to use S-TAB or
518 C-u TAB. For this special case to work, the first line of the buffer
519 must not be a headline - it may be empty ot some other text. When used in
520 this way, `org-cycle-hook' is disables temporarily, to make sure the
521 cursor stays at the beginning of the buffer.
522 When this option is nil, don't do anything special at the beginning
523 of the buffer."
524 :group 'org-cycle
525 :type 'boolean)
526
527 (defcustom org-cycle-emulate-tab t
528 "Where should `org-cycle' emulate TAB.
529 nil Never
530 white Only in completely white lines
531 whitestart Only at the beginning of lines, before the first non-white char
532 t Everywhere except in headlines
533 exc-hl-bol Everywhere except at the start of a headline
534 If TAB is used in a place where it does not emulate TAB, the current subtree
535 visibility is cycled."
536 :group 'org-cycle
537 :type '(choice (const :tag "Never" nil)
538 (const :tag "Only in completely white lines" white)
539 (const :tag "Before first char in a line" whitestart)
540 (const :tag "Everywhere except in headlines" t)
541 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
542 ))
543
544 (defcustom org-cycle-separator-lines 2
545 "Number of empty lines needed to keep an empty line between collapsed trees.
546 If you leave an empty line between the end of a subtree and the following
547 headline, this empty line is hidden when the subtree is folded.
548 Org-mode will leave (exactly) one empty line visible if the number of
549 empty lines is equal or larger to the number given in this variable.
550 So the default 2 means, at least 2 empty lines after the end of a subtree
551 are needed to produce free space between a collapsed subtree and the
552 following headline.
553
554 Special case: when 0, never leave empty lines in collapsed view."
555 :group 'org-cycle
556 :type 'integer)
557 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
558
559 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
560 org-cycle-hide-drawers
561 org-cycle-show-empty-lines
562 org-optimize-window-after-visibility-change)
563 "Hook that is run after `org-cycle' has changed the buffer visibility.
564 The function(s) in this hook must accept a single argument which indicates
565 the new state that was set by the most recent `org-cycle' command. The
566 argument is a symbol. After a global state change, it can have the values
567 `overview', `content', or `all'. After a local state change, it can have
568 the values `folded', `children', or `subtree'."
569 :group 'org-cycle
570 :type 'hook)
571
572 (defgroup org-edit-structure nil
573 "Options concerning structure editing in Org-mode."
574 :tag "Org Edit Structure"
575 :group 'org-structure)
576
577 (defcustom org-odd-levels-only nil
578 "Non-nil means, skip even levels and only use odd levels for the outline.
579 This has the effect that two stars are being added/taken away in
580 promotion/demotion commands. It also influences how levels are
581 handled by the exporters.
582 Changing it requires restart of `font-lock-mode' to become effective
583 for fontification also in regions already fontified.
584 You may also set this on a per-file basis by adding one of the following
585 lines to the buffer:
586
587 #+STARTUP: odd
588 #+STARTUP: oddeven"
589 :group 'org-edit-structure
590 :group 'org-font-lock
591 :type 'boolean)
592
593 (defcustom org-adapt-indentation t
594 "Non-nil means, adapt indentation when promoting and demoting.
595 When this is set and the *entire* text in an entry is indented, the
596 indentation is increased by one space in a demotion command, and
597 decreased by one in a promotion command. If any line in the entry
598 body starts at column 0, indentation is not changed at all."
599 :group 'org-edit-structure
600 :type 'boolean)
601
602 (defcustom org-special-ctrl-a/e nil
603 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
604 When t, `C-a' will bring back the cursor to the beginning of the
605 headline text, i.e. after the stars and after a possible TODO keyword.
606 In an item, this will be the position after the bullet.
607 When the cursor is already at that position, another `C-a' will bring
608 it to the beginning of the line.
609 `C-e' will jump to the end of the headline, ignoring the presence of tags
610 in the headline. A second `C-e' will then jump to the true end of the
611 line, after any tags.
612 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
613 and only a directly following, identical keypress will bring the cursor
614 to the special positions."
615 :group 'org-edit-structure
616 :type '(choice
617 (const :tag "off" nil)
618 (const :tag "after bullet first" t)
619 (const :tag "border first" reversed)))
620
621 (if (fboundp 'defvaralias)
622 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
623
624 (defcustom org-special-ctrl-k nil
625 "Non-nil means `C-k' will behave specially in headlines.
626 When nil, `C-k' will call the default `kill-line' command.
627 When t, the following will happen while the cursor is in the headline:
628
629 - When the cursor is at the beginning of a headline, kill the entire
630 line and possible the folded subtree below the line.
631 - When in the middle of the headline text, kill the headline up to the tags.
632 - When after the headline text, kill the tags."
633 :group 'org-edit-structure
634 :type 'boolean)
635
636 (defcustom org-yank-folded-subtrees t
637 "Non-nil means, when yanking subtrees, fold them.
638 If the kill is a single subtree, or a sequence of subtrees, i.e. if
639 it starts with a heading and all other headings in it are either children
640 or siblings, then fold all the subtrees."
641 :group 'org-edit-structure
642 :type 'boolean)
643
644 (defcustom org-M-RET-may-split-line '((default . t))
645 "Non-nil means, M-RET will split the line at the cursor position.
646 When nil, it will go to the end of the line before making a
647 new line.
648 You may also set this option in a different way for different
649 contexts. Valid contexts are:
650
651 headline when creating a new headline
652 item when creating a new item
653 table in a table field
654 default the value to be used for all contexts not explicitly
655 customized"
656 :group 'org-structure
657 :group 'org-table
658 :type '(choice
659 (const :tag "Always" t)
660 (const :tag "Never" nil)
661 (repeat :greedy t :tag "Individual contexts"
662 (cons
663 (choice :tag "Context"
664 (const headline)
665 (const item)
666 (const table)
667 (const default))
668 (boolean)))))
669
670
671 (defcustom org-insert-heading-respect-content nil
672 "Non-nil means, insert new headings after the current subtree.
673 When nil, the new heading is created directly after the current line.
674 The commands \\[org-insert-heading-respect-content] and
675 \\[org-insert-todo-heading-respect-content] turn this variable on
676 for the duration of the command."
677 :group 'org-structure
678 :type 'boolean)
679
680 (defcustom org-blank-before-new-entry '((heading . nil)
681 (plain-list-item . nil))
682 "Should `org-insert-heading' leave a blank line before new heading/item?
683 The value is an alist, with `heading' and `plain-list-item' as car,
684 and a boolean flag as cdr."
685 :group 'org-edit-structure
686 :type '(list
687 (cons (const heading) (boolean))
688 (cons (const plain-list-item) (boolean))))
689
690 (defcustom org-insert-heading-hook nil
691 "Hook being run after inserting a new heading."
692 :group 'org-edit-structure
693 :type 'hook)
694
695 (defcustom org-enable-fixed-width-editor t
696 "Non-nil means, lines starting with \":\" are treated as fixed-width.
697 This currently only means, they are never auto-wrapped.
698 When nil, such lines will be treated like ordinary lines.
699 See also the QUOTE keyword."
700 :group 'org-edit-structure
701 :type 'boolean)
702
703 (defcustom org-edit-src-region-extra nil
704 "Additional regexps to identify regions for editing with `org-edit-src-code'.
705 For examples see the function `org-edit-src-find-region-and-lang'.
706 The regular expression identifying the begin marker should end with a newline,
707 and the regexp marking the end line should start with a newline, to make sure
708 there are kept outside the narrowed region."
709 :group 'org-edit-structure
710 :type '(repeat
711 (list
712 (regexp :tag "begin regexp")
713 (regexp :tag "end regexp")
714 (choice :tag "language"
715 (string :tag "specify")
716 (integer :tag "from match group")
717 (const :tag "from `lang' element")
718 (const :tag "from `style' element")))))
719
720 (defcustom org-edit-fixed-width-region-mode 'artist-mode
721 "The mode that should be used to edit fixed-width regions.
722 These are the regions where each line starts with a colon."
723 :group 'org-edit-structure
724 :type '(choice
725 (const artist-mode)
726 (const picture-mode)
727 (const fundamental-mode)
728 (function :tag "Other (specify)")))
729
730 (defcustom org-goto-auto-isearch t
731 "Non-nil means, typing characters in org-goto starts incremental search."
732 :group 'org-edit-structure
733 :type 'boolean)
734
735 (defgroup org-sparse-trees nil
736 "Options concerning sparse trees in Org-mode."
737 :tag "Org Sparse Trees"
738 :group 'org-structure)
739
740 (defcustom org-highlight-sparse-tree-matches t
741 "Non-nil means, highlight all matches that define a sparse tree.
742 The highlights will automatically disappear the next time the buffer is
743 changed by an edit command."
744 :group 'org-sparse-trees
745 :type 'boolean)
746
747 (defcustom org-remove-highlights-with-change t
748 "Non-nil means, any change to the buffer will remove temporary highlights.
749 Such highlights are created by `org-occur' and `org-clock-display'.
750 When nil, `C-c C-c needs to be used to get rid of the highlights.
751 The highlights created by `org-preview-latex-fragment' always need
752 `C-c C-c' to be removed."
753 :group 'org-sparse-trees
754 :group 'org-time
755 :type 'boolean)
756
757
758 (defcustom org-occur-hook '(org-first-headline-recenter)
759 "Hook that is run after `org-occur' has constructed a sparse tree.
760 This can be used to recenter the window to show as much of the structure
761 as possible."
762 :group 'org-sparse-trees
763 :type 'hook)
764
765 (defgroup org-imenu-and-speedbar nil
766 "Options concerning imenu and speedbar in Org-mode."
767 :tag "Org Imenu and Speedbar"
768 :group 'org-structure)
769
770 (defcustom org-imenu-depth 2
771 "The maximum level for Imenu access to Org-mode headlines.
772 This also applied for speedbar access."
773 :group 'org-imenu-and-speedbar
774 :type 'number)
775
776 (defgroup org-table nil
777 "Options concerning tables in Org-mode."
778 :tag "Org Table"
779 :group 'org)
780
781 (defcustom org-enable-table-editor 'optimized
782 "Non-nil means, lines starting with \"|\" are handled by the table editor.
783 When nil, such lines will be treated like ordinary lines.
784
785 When equal to the symbol `optimized', the table editor will be optimized to
786 do the following:
787 - Automatic overwrite mode in front of whitespace in table fields.
788 This makes the structure of the table stay in tact as long as the edited
789 field does not exceed the column width.
790 - Minimize the number of realigns. Normally, the table is aligned each time
791 TAB or RET are pressed to move to another field. With optimization this
792 happens only if changes to a field might have changed the column width.
793 Optimization requires replacing the functions `self-insert-command',
794 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
795 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
796 very good at guessing when a re-align will be necessary, but you can always
797 force one with \\[org-ctrl-c-ctrl-c].
798
799 If you would like to use the optimized version in Org-mode, but the
800 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
801
802 This variable can be used to turn on and off the table editor during a session,
803 but in order to toggle optimization, a restart is required.
804
805 See also the variable `org-table-auto-blank-field'."
806 :group 'org-table
807 :type '(choice
808 (const :tag "off" nil)
809 (const :tag "on" t)
810 (const :tag "on, optimized" optimized)))
811
812 (defcustom org-table-tab-recognizes-table.el t
813 "Non-nil means, TAB will automatically notice a table.el table.
814 When it sees such a table, it moves point into it and - if necessary -
815 calls `table-recognize-table'."
816 :group 'org-table-editing
817 :type 'boolean)
818
819 (defgroup org-link nil
820 "Options concerning links in Org-mode."
821 :tag "Org Link"
822 :group 'org)
823
824 (defvar org-link-abbrev-alist-local nil
825 "Buffer-local version of `org-link-abbrev-alist', which see.
826 The value of this is taken from the #+LINK lines.")
827 (make-variable-buffer-local 'org-link-abbrev-alist-local)
828
829 (defcustom org-link-abbrev-alist nil
830 "Alist of link abbreviations.
831 The car of each element is a string, to be replaced at the start of a link.
832 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
833 links in Org-mode buffers can have an optional tag after a double colon, e.g.
834
835 [[linkkey:tag][description]]
836
837 If REPLACE is a string, the tag will simply be appended to create the link.
838 If the string contains \"%s\", the tag will be inserted there.
839
840 REPLACE may also be a function that will be called with the tag as the
841 only argument to create the link, which should be returned as a string.
842
843 See the manual for examples."
844 :group 'org-link
845 :type 'alist)
846
847 (defcustom org-descriptive-links t
848 "Non-nil means, hide link part and only show description of bracket links.
849 Bracket links are like [[link][descritpion]]. This variable sets the initial
850 state in new org-mode buffers. The setting can then be toggled on a
851 per-buffer basis from the Org->Hyperlinks menu."
852 :group 'org-link
853 :type 'boolean)
854
855 (defcustom org-link-file-path-type 'adaptive
856 "How the path name in file links should be stored.
857 Valid values are:
858
859 relative Relative to the current directory, i.e. the directory of the file
860 into which the link is being inserted.
861 absolute Absolute path, if possible with ~ for home directory.
862 noabbrev Absolute path, no abbreviation of home directory.
863 adaptive Use relative path for files in the current directory and sub-
864 directories of it. For other files, use an absolute path."
865 :group 'org-link
866 :type '(choice
867 (const relative)
868 (const absolute)
869 (const noabbrev)
870 (const adaptive)))
871
872 (defcustom org-activate-links '(bracket angle plain radio tag date)
873 "Types of links that should be activated in Org-mode files.
874 This is a list of symbols, each leading to the activation of a certain link
875 type. In principle, it does not hurt to turn on most link types - there may
876 be a small gain when turning off unused link types. The types are:
877
878 bracket The recommended [[link][description]] or [[link]] links with hiding.
879 angular Links in angular brackes that may contain whitespace like
880 <bbdb:Carsten Dominik>.
881 plain Plain links in normal text, no whitespace, like http://google.com.
882 radio Text that is matched by a radio target, see manual for details.
883 tag Tag settings in a headline (link to tag search).
884 date Time stamps (link to calendar).
885
886 Changing this variable requires a restart of Emacs to become effective."
887 :group 'org-link
888 :type '(set (const :tag "Double bracket links (new style)" bracket)
889 (const :tag "Angular bracket links (old style)" angular)
890 (const :tag "Plain text links" plain)
891 (const :tag "Radio target matches" radio)
892 (const :tag "Tags" tag)
893 (const :tag "Timestamps" date)))
894
895 (defcustom org-make-link-description-function nil
896 "Function to use to generate link descriptions from links. If
897 nil the link location will be used. This function must take two
898 parameters; the first is the link and the second the description
899 org-insert-link has generated, and should return the description
900 to use."
901 :group 'org-link
902 :type 'function)
903
904 (defgroup org-link-store nil
905 "Options concerning storing links in Org-mode."
906 :tag "Org Store Link"
907 :group 'org-link)
908
909 (defcustom org-email-link-description-format "Email %c: %.30s"
910 "Format of the description part of a link to an email or usenet message.
911 The following %-excapes will be replaced by corresponding information:
912
913 %F full \"From\" field
914 %f name, taken from \"From\" field, address if no name
915 %T full \"To\" field
916 %t first name in \"To\" field, address if no name
917 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
918 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
919 %s subject
920 %m message-id.
921
922 You may use normal field width specification between the % and the letter.
923 This is for example useful to limit the length of the subject.
924
925 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
926 :group 'org-link-store
927 :type 'string)
928
929 (defcustom org-from-is-user-regexp
930 (let (r1 r2)
931 (when (and user-mail-address (not (string= user-mail-address "")))
932 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
933 (when (and user-full-name (not (string= user-full-name "")))
934 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
935 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
936 "Regexp mached against the \"From:\" header of an email or usenet message.
937 It should match if the message is from the user him/herself."
938 :group 'org-link-store
939 :type 'regexp)
940
941 (defcustom org-context-in-file-links t
942 "Non-nil means, file links from `org-store-link' contain context.
943 A search string will be added to the file name with :: as separator and
944 used to find the context when the link is activated by the command
945 `org-open-at-point'.
946 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
947 negates this setting for the duration of the command."
948 :group 'org-link-store
949 :type 'boolean)
950
951 (defcustom org-keep-stored-link-after-insertion nil
952 "Non-nil means, keep link in list for entire session.
953
954 The command `org-store-link' adds a link pointing to the current
955 location to an internal list. These links accumulate during a session.
956 The command `org-insert-link' can be used to insert links into any
957 Org-mode file (offering completion for all stored links). When this
958 option is nil, every link which has been inserted once using \\[org-insert-link]
959 will be removed from the list, to make completing the unused links
960 more efficient."
961 :group 'org-link-store
962 :type 'boolean)
963
964 (defgroup org-link-follow nil
965 "Options concerning following links in Org-mode."
966 :tag "Org Follow Link"
967 :group 'org-link)
968
969 (defcustom org-follow-link-hook nil
970 "Hook that is run after a link has been followed."
971 :group 'org-link-follow
972 :type 'hook)
973
974 (defcustom org-tab-follows-link nil
975 "Non-nil means, on links TAB will follow the link.
976 Needs to be set before org.el is loaded."
977 :group 'org-link-follow
978 :type 'boolean)
979
980 (defcustom org-return-follows-link nil
981 "Non-nil means, on links RET will follow the link.
982 Needs to be set before org.el is loaded."
983 :group 'org-link-follow
984 :type 'boolean)
985
986 (defcustom org-mouse-1-follows-link
987 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
988 "Non-nil means, mouse-1 on a link will follow the link.
989 A longer mouse click will still set point. Does not work on XEmacs.
990 Needs to be set before org.el is loaded."
991 :group 'org-link-follow
992 :type 'boolean)
993
994 (defcustom org-mark-ring-length 4
995 "Number of different positions to be recorded in the ring
996 Changing this requires a restart of Emacs to work correctly."
997 :group 'org-link-follow
998 :type 'interger)
999
1000 (defcustom org-link-frame-setup
1001 '((vm . vm-visit-folder-other-frame)
1002 (gnus . gnus-other-frame)
1003 (file . find-file-other-window))
1004 "Setup the frame configuration for following links.
1005 When following a link with Emacs, it may often be useful to display
1006 this link in another window or frame. This variable can be used to
1007 set this up for the different types of links.
1008 For VM, use any of
1009 `vm-visit-folder'
1010 `vm-visit-folder-other-frame'
1011 For Gnus, use any of
1012 `gnus'
1013 `gnus-other-frame'
1014 For FILE, use any of
1015 `find-file'
1016 `find-file-other-window'
1017 `find-file-other-frame'
1018 For the calendar, use the variable `calendar-setup'.
1019 For BBDB, it is currently only possible to display the matches in
1020 another window."
1021 :group 'org-link-follow
1022 :type '(list
1023 (cons (const vm)
1024 (choice
1025 (const vm-visit-folder)
1026 (const vm-visit-folder-other-window)
1027 (const vm-visit-folder-other-frame)))
1028 (cons (const gnus)
1029 (choice
1030 (const gnus)
1031 (const gnus-other-frame)))
1032 (cons (const file)
1033 (choice
1034 (const find-file)
1035 (const find-file-other-window)
1036 (const find-file-other-frame)))))
1037
1038 (defcustom org-display-internal-link-with-indirect-buffer nil
1039 "Non-nil means, use indirect buffer to display infile links.
1040 Activating internal links (from one location in a file to another location
1041 in the same file) normally just jumps to the location. When the link is
1042 activated with a C-u prefix (or with mouse-3), the link is displayed in
1043 another window. When this option is set, the other window actually displays
1044 an indirect buffer clone of the current buffer, to avoid any visibility
1045 changes to the current buffer."
1046 :group 'org-link-follow
1047 :type 'boolean)
1048
1049 (defcustom org-open-non-existing-files nil
1050 "Non-nil means, `org-open-file' will open non-existing files.
1051 When nil, an error will be generated."
1052 :group 'org-link-follow
1053 :type 'boolean)
1054
1055 (defcustom org-open-directory-means-index-dot-org nil
1056 "Non-nil means, a link to a directory really means to index.org.
1057 When nil, following a directory link will run dired or open a finder/explorer
1058 window on that directory."
1059 :group 'org-link-follow
1060 :type 'boolean)
1061
1062 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1063 "Function and arguments to call for following mailto links.
1064 This is a list with the first element being a lisp function, and the
1065 remaining elements being arguments to the function. In string arguments,
1066 %a will be replaced by the address, and %s will be replaced by the subject
1067 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1068 :group 'org-link-follow
1069 :type '(choice
1070 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1071 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1072 (const :tag "message-mail" (message-mail "%a" "%s"))
1073 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1074
1075 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1076 "Non-nil means, ask for confirmation before executing shell links.
1077 Shell links can be dangerous: just think about a link
1078
1079 [[shell:rm -rf ~/*][Google Search]]
1080
1081 This link would show up in your Org-mode document as \"Google Search\",
1082 but really it would remove your entire home directory.
1083 Therefore we advise against setting this variable to nil.
1084 Just change it to `y-or-n-p' of you want to confirm with a
1085 single keystroke rather than having to type \"yes\"."
1086 :group 'org-link-follow
1087 :type '(choice
1088 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1089 (const :tag "with y-or-n (faster)" y-or-n-p)
1090 (const :tag "no confirmation (dangerous)" nil)))
1091
1092 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1093 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1094 Elisp links can be dangerous: just think about a link
1095
1096 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1097
1098 This link would show up in your Org-mode document as \"Google Search\",
1099 but really it would remove your entire home directory.
1100 Therefore we advise against setting this variable to nil.
1101 Just change it to `y-or-n-p' of you want to confirm with a
1102 single keystroke rather than having to type \"yes\"."
1103 :group 'org-link-follow
1104 :type '(choice
1105 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1106 (const :tag "with y-or-n (faster)" y-or-n-p)
1107 (const :tag "no confirmation (dangerous)" nil)))
1108
1109 (defconst org-file-apps-defaults-gnu
1110 '((remote . emacs)
1111 (t . mailcap))
1112 "Default file applications on a UNIX or GNU/Linux system.
1113 See `org-file-apps'.")
1114
1115 (defconst org-file-apps-defaults-macosx
1116 '((remote . emacs)
1117 (t . "open %s")
1118 ("ps.gz" . "gv %s")
1119 ("eps.gz" . "gv %s")
1120 ("dvi" . "xdvi %s")
1121 ("fig" . "xfig %s"))
1122 "Default file applications on a MacOS X system.
1123 The system \"open\" is known as a default, but we use X11 applications
1124 for some files for which the OS does not have a good default.
1125 See `org-file-apps'.")
1126
1127 (defconst org-file-apps-defaults-windowsnt
1128 (list
1129 '(remote . emacs)
1130 (cons t
1131 (list (if (featurep 'xemacs)
1132 'mswindows-shell-execute
1133 'w32-shell-execute)
1134 "open" 'file)))
1135 "Default file applications on a Windows NT system.
1136 The system \"open\" is used for most files.
1137 See `org-file-apps'.")
1138
1139 (defcustom org-file-apps
1140 '(
1141 (auto-mode . emacs)
1142 ("\\.x?html?\\'" . default)
1143 ("\\.pdf\\'" . default)
1144 )
1145 "External applications for opening `file:path' items in a document.
1146 Org-mode uses system defaults for different file types, but
1147 you can use this variable to set the application for a given file
1148 extension. The entries in this list are cons cells where the car identifies
1149 files and the cdr the corresponding command. Possible values for the
1150 file identifier are
1151 \"regex\" Regular expression matched against the file name. For backward
1152 compatibility, this can also be a string with only alphanumeric
1153 characters, which is then interpreted as an extension.
1154 `directory' Matches a directory
1155 `remote' Matches a remote file, accessible through tramp or efs.
1156 Remote files most likely should be visited through Emacs
1157 because external applications cannot handle such paths.
1158 `auto-mode' Matches files that are mached by any entry in `auto-mode-alist',
1159 so all files Emacs knows how to handle. Useing this with
1160 command `emacs' will open most files in Emacs. Beware that this
1161 will also open html files insite Emacs, unless you add
1162 (\"html\" . default) to the list as well.
1163 t Default for files not matched by any of the other options.
1164
1165 Possible values for the command are:
1166 `emacs' The file will be visited by the current Emacs process.
1167 `default' Use the default application for this file type, which is the
1168 association for t in the list, most likely in the system-specific
1169 part.
1170 This can be used to overrule an unwanted seting in the
1171 system-specific variable.
1172 string A command to be executed by a shell; %s will be replaced
1173 by the path to the file.
1174 sexp A Lisp form which will be evaluated. The file path will
1175 be available in the Lisp variable `file'.
1176 For more examples, see the system specific constants
1177 `org-file-apps-defaults-macosx'
1178 `org-file-apps-defaults-windowsnt'
1179 `org-file-apps-defaults-gnu'."
1180 :group 'org-link-follow
1181 :type '(repeat
1182 (cons (choice :value ""
1183 (string :tag "Extension")
1184 (const :tag "Default for unrecognized files" t)
1185 (const :tag "Remote file" remote)
1186 (const :tag "Links to a directory" directory)
1187 (const :tag "Any files that have Emacs modes"
1188 auto-mode))
1189 (choice :value ""
1190 (const :tag "Visit with Emacs" emacs)
1191 (const :tag "Use system default" default)
1192 (string :tag "Command")
1193 (sexp :tag "Lisp form")))))
1194
1195 (defgroup org-refile nil
1196 "Options concerning refiling entries in Org-mode."
1197 :tag "Org Remember"
1198 :group 'org)
1199
1200 (defcustom org-directory "~/org"
1201 "Directory with org files.
1202 This directory will be used as default to prompt for org files.
1203 Used by the hooks for remember.el."
1204 :group 'org-refile
1205 :group 'org-remember
1206 :type 'directory)
1207
1208 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1209 "Default target for storing notes.
1210 Used by the hooks for remember.el. This can be a string, or nil to mean
1211 the value of `remember-data-file'.
1212 You can set this on a per-template basis with the variable
1213 `org-remember-templates'."
1214 :group 'org-refile
1215 :group 'org-remember
1216 :type '(choice
1217 (const :tag "Default from remember-data-file" nil)
1218 file))
1219
1220 (defcustom org-goto-interface 'outline
1221 "The default interface to be used for `org-goto'.
1222 Allowed vaues are:
1223 outline The interface shows an outline of the relevant file
1224 and the correct heading is found by moving through
1225 the outline or by searching with incremental search.
1226 outline-path-completion Headlines in the current buffer are offered via
1227 completion."
1228 :group 'org-refile
1229 :type '(choice
1230 (const :tag "Outline" outline)
1231 (const :tag "Outline-path-completion" outline-path-completion)))
1232
1233 (defcustom org-reverse-note-order nil
1234 "Non-nil means, store new notes at the beginning of a file or entry.
1235 When nil, new notes will be filed to the end of a file or entry.
1236 This can also be a list with cons cells of regular expressions that
1237 are matched against file names, and values."
1238 :group 'org-remember
1239 :type '(choice
1240 (const :tag "Reverse always" t)
1241 (const :tag "Reverse never" nil)
1242 (repeat :tag "By file name regexp"
1243 (cons regexp boolean))))
1244
1245 (defcustom org-refile-targets nil
1246 "Targets for refiling entries with \\[org-refile].
1247 This is list of cons cells. Each cell contains:
1248 - a specification of the files to be considered, either a list of files,
1249 or a symbol whose function or variable value will be used to retrieve
1250 a file name or a list of file names. Nil means, refile to a different
1251 heading in the current buffer.
1252 - A specification of how to find candidate refile targets. This may be
1253 any of
1254 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1255 This tag has to be present in all target headlines, inheritance will
1256 not be considered.
1257 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1258 todo keyword.
1259 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1260 headlines that are refiling targets.
1261 - a cons cell (:level . N). Any headline of level N is considered a target.
1262 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1263
1264 When this variable is nil, all top-level headlines in the current buffer
1265 are used, equivalent to the vlaue `((nil . (:level . 1))'."
1266 :group 'org-remember
1267 :type '(repeat
1268 (cons
1269 (choice :value org-agenda-files
1270 (const :tag "All agenda files" org-agenda-files)
1271 (const :tag "Current buffer" nil)
1272 (function) (variable) (file))
1273 (choice :tag "Identify target headline by"
1274 (cons :tag "Specific tag" (const :tag) (string))
1275 (cons :tag "TODO keyword" (const :todo) (string))
1276 (cons :tag "Regular expression" (const :regexp) (regexp))
1277 (cons :tag "Level number" (const :level) (integer))
1278 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1279
1280 (defcustom org-refile-use-outline-path nil
1281 "Non-nil means, provide refile targets as paths.
1282 So a level 3 headline will be available as level1/level2/level3.
1283 When the value is `file', also include the file name (without directory)
1284 into the path. When `full-file-path', include the full file path."
1285 :group 'org-remember
1286 :type '(choice
1287 (const :tag "Not" nil)
1288 (const :tag "Yes" t)
1289 (const :tag "Start with file name" file)
1290 (const :tag "Start with full file path" full-file-path)))
1291
1292 (defgroup org-todo nil
1293 "Options concerning TODO items in Org-mode."
1294 :tag "Org TODO"
1295 :group 'org)
1296
1297 (defgroup org-progress nil
1298 "Options concerning Progress logging in Org-mode."
1299 :tag "Org Progress"
1300 :group 'org-time)
1301
1302 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1303 "List of TODO entry keyword sequences and their interpretation.
1304 \\<org-mode-map>This is a list of sequences.
1305
1306 Each sequence starts with a symbol, either `sequence' or `type',
1307 indicating if the keywords should be interpreted as a sequence of
1308 action steps, or as different types of TODO items. The first
1309 keywords are states requiring action - these states will select a headline
1310 for inclusion into the global TODO list Org-mode produces. If one of
1311 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1312 signify that no further action is necessary. If \"|\" is not found,
1313 the last keyword is treated as the only DONE state of the sequence.
1314
1315 The command \\[org-todo] cycles an entry through these states, and one
1316 additional state where no keyword is present. For details about this
1317 cycling, see the manual.
1318
1319 TODO keywords and interpretation can also be set on a per-file basis with
1320 the special #+SEQ_TODO and #+TYP_TODO lines.
1321
1322 Each keyword can optionally specify a character for fast state selection
1323 \(in combination with the variable `org-use-fast-todo-selection')
1324 and specifiers for state change logging, using the same syntax
1325 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1326 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1327 indicates to record a time stamp each time this state is selected.
1328
1329 Each keyword may also specify if a timestamp or a note should be
1330 recorded when entering or leaving the state, by adding additional
1331 characters in the parenthesis after the keyword. This looks like this:
1332 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1333 record only the time of the state change. With X and Y being either
1334 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1335 Y when leaving the state if and only if the *target* state does not
1336 define X. You may omit any of the fast-selection key or X or /Y,
1337 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1338
1339 For backward compatibility, this variable may also be just a list
1340 of keywords - in this case the interptetation (sequence or type) will be
1341 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1342 :group 'org-todo
1343 :group 'org-keywords
1344 :type '(choice
1345 (repeat :tag "Old syntax, just keywords"
1346 (string :tag "Keyword"))
1347 (repeat :tag "New syntax"
1348 (cons
1349 (choice
1350 :tag "Interpretation"
1351 (const :tag "Sequence (cycling hits every state)" sequence)
1352 (const :tag "Type (cycling directly to DONE)" type))
1353 (repeat
1354 (string :tag "Keyword"))))))
1355
1356 (defvar org-todo-keywords-1 nil
1357 "All TODO and DONE keywords active in a buffer.")
1358 (make-variable-buffer-local 'org-todo-keywords-1)
1359 (defvar org-todo-keywords-for-agenda nil)
1360 (defvar org-done-keywords-for-agenda nil)
1361 (defvar org-todo-keyword-alist-for-agenda nil)
1362 (defvar org-tag-alist-for-agenda nil)
1363 (defvar org-agenda-contributing-files nil)
1364 (defvar org-not-done-keywords nil)
1365 (make-variable-buffer-local 'org-not-done-keywords)
1366 (defvar org-done-keywords nil)
1367 (make-variable-buffer-local 'org-done-keywords)
1368 (defvar org-todo-heads nil)
1369 (make-variable-buffer-local 'org-todo-heads)
1370 (defvar org-todo-sets nil)
1371 (make-variable-buffer-local 'org-todo-sets)
1372 (defvar org-todo-log-states nil)
1373 (make-variable-buffer-local 'org-todo-log-states)
1374 (defvar org-todo-kwd-alist nil)
1375 (make-variable-buffer-local 'org-todo-kwd-alist)
1376 (defvar org-todo-key-alist nil)
1377 (make-variable-buffer-local 'org-todo-key-alist)
1378 (defvar org-todo-key-trigger nil)
1379 (make-variable-buffer-local 'org-todo-key-trigger)
1380
1381 (defcustom org-todo-interpretation 'sequence
1382 "Controls how TODO keywords are interpreted.
1383 This variable is in principle obsolete and is only used for
1384 backward compatibility, if the interpretation of todo keywords is
1385 not given already in `org-todo-keywords'. See that variable for
1386 more information."
1387 :group 'org-todo
1388 :group 'org-keywords
1389 :type '(choice (const sequence)
1390 (const type)))
1391
1392 (defcustom org-use-fast-todo-selection 'prefix
1393 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1394 This variable describes if and under what circumstances the cycling
1395 mechanism for TODO keywords will be replaced by a single-key, direct
1396 selection scheme.
1397
1398 When nil, fast selection is never used.
1399
1400 When the symbol `prefix', it will be used when `org-todo' is called with
1401 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1402 in an agenda buffer.
1403
1404 When t, fast selection is used by default. In this case, the prefix
1405 argument forces cycling instead.
1406
1407 In all cases, the special interface is only used if access keys have actually
1408 been assigned by the user, i.e. if keywords in the configuration are followed
1409 by a letter in parenthesis, like TODO(t)."
1410 :group 'org-todo
1411 :type '(choice
1412 (const :tag "Never" nil)
1413 (const :tag "By default" t)
1414 (const :tag "Only with C-u C-c C-t" prefix)))
1415
1416 (defcustom org-provide-todo-statistics t
1417 "Non-nil means, update todo statistics after insert and toggle.
1418 When this is set, todo statistics is updated in the parent of the current
1419 entry each time a todo state is changed."
1420 :group 'org-todo
1421 :type 'boolean)
1422
1423 (defcustom org-after-todo-state-change-hook nil
1424 "Hook which is run after the state of a TODO item was changed.
1425 The new state (a string with a TODO keyword, or nil) is available in the
1426 Lisp variable `state'."
1427 :group 'org-todo
1428 :type 'hook)
1429
1430 (defcustom org-todo-state-tags-triggers nil
1431 "Tag changes that should be triggered by TODO state changes.
1432 This is a list. Each entry is
1433
1434 (state-change (tag . flag) .......)
1435
1436 State-change can be a string with a state, and empty string to indicate the
1437 state that has no TODO keyword, or it can be one of the symbols `todo'
1438 or `done', meaning any not-done or done state, respectively."
1439 :group 'org-todo
1440 :group 'org-tags
1441 :type '(repeat
1442 (cons (choice :tag "When changing to"
1443 (const :tag "Not-done state" todo)
1444 (const :tag "Done state" done)
1445 (string :tag "State"))
1446 (repeat
1447 (cons :tag "Tag action"
1448 (string :tag "Tag")
1449 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1450
1451 (defcustom org-log-done nil
1452 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1453 When equal to the list (done), also prompt for a closing note.
1454 This can also be configured on a per-file basis by adding one of
1455 the following lines anywhere in the buffer:
1456
1457 #+STARTUP: logdone
1458 #+STARTUP: lognotedone
1459 #+STARTUP: nologdone"
1460 :group 'org-todo
1461 :group 'org-progress
1462 :type '(choice
1463 (const :tag "No logging" nil)
1464 (const :tag "Record CLOSED timestamp" time)
1465 (const :tag "Record CLOSED timestamp with closing note." note)))
1466
1467 ;; Normalize old uses of org-log-done.
1468 (cond
1469 ((eq org-log-done t) (setq org-log-done 'time))
1470 ((and (listp org-log-done) (memq 'done org-log-done))
1471 (setq org-log-done 'note)))
1472
1473 (defcustom org-log-note-clock-out nil
1474 "Non-nil means, record a note when clocking out of an item.
1475 This can also be configured on a per-file basis by adding one of
1476 the following lines anywhere in the buffer:
1477
1478 #+STARTUP: lognoteclock-out
1479 #+STARTUP: nolognoteclock-out"
1480 :group 'org-todo
1481 :group 'org-progress
1482 :type 'boolean)
1483
1484 (defcustom org-log-done-with-time t
1485 "Non-nil means, the CLOSED time stamp will contain date and time.
1486 When nil, only the date will be recorded."
1487 :group 'org-progress
1488 :type 'boolean)
1489
1490 (defcustom org-log-note-headings
1491 '((done . "CLOSING NOTE %t")
1492 (state . "State %-12s %t")
1493 (note . "Note taken on %t")
1494 (clock-out . ""))
1495 "Headings for notes added to entries.
1496 The value is an alist, with the car being a symbol indicating the note
1497 context, and the cdr is the heading to be used. The heading may also be the
1498 empty string.
1499 %t in the heading will be replaced by a time stamp.
1500 %s will be replaced by the new TODO state, in double quotes.
1501 %u will be replaced by the user name.
1502 %U will be replaced by the full user name."
1503 :group 'org-todo
1504 :group 'org-progress
1505 :type '(list :greedy t
1506 (cons (const :tag "Heading when closing an item" done) string)
1507 (cons (const :tag
1508 "Heading when changing todo state (todo sequence only)"
1509 state) string)
1510 (cons (const :tag "Heading when just taking a note" note) string)
1511 (cons (const :tag "Heading when clocking out" clock-out) string)))
1512
1513 (unless (assq 'note org-log-note-headings)
1514 (push '(note . "%t") org-log-note-headings))
1515
1516 (defcustom org-log-state-notes-insert-after-drawers nil
1517 "Non-nil means, insert state change notes after any drawers in entry.
1518 Only the drawers that *immediately* follow the headline and the
1519 deadline/scheduled line are skipped.
1520 When nil, insert notes right after the heading and perhaps the line
1521 with deadline/scheduling if present."
1522 :group 'org-todo
1523 :group 'org-progress
1524 :type 'boolean)
1525
1526 (defcustom org-log-states-order-reversed t
1527 "Non-nil means, the latest state change note will be directly after heading.
1528 When nil, the notes will be orderer according to time."
1529 :group 'org-todo
1530 :group 'org-progress
1531 :type 'boolean)
1532
1533 (defcustom org-log-repeat 'time
1534 "Non-nil means, record moving through the DONE state when triggering repeat.
1535 An auto-repeating tasks is immediately switched back to TODO when marked
1536 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1537 the TODO keyword definition, or recording a closing note by setting
1538 `org-log-done', there will be no record of the task moving through DONE.
1539 This variable forces taking a note anyway. Possible values are:
1540
1541 nil Don't force a record
1542 time Record a time stamp
1543 note Record a note
1544
1545 This option can also be set with on a per-file-basis with
1546
1547 #+STARTUP: logrepeat
1548 #+STARTUP: lognoterepeat
1549 #+STARTUP: nologrepeat
1550
1551 You can have local logging settings for a subtree by setting the LOGGING
1552 property to one or more of these keywords."
1553 :group 'org-todo
1554 :group 'org-progress
1555 :type '(choice
1556 (const :tag "Don't force a record" nil)
1557 (const :tag "Force recording the DONE state" time)
1558 (const :tag "Force recording a note with the DONE state" note)))
1559
1560
1561 (defgroup org-priorities nil
1562 "Priorities in Org-mode."
1563 :tag "Org Priorities"
1564 :group 'org-todo)
1565
1566 (defcustom org-highest-priority ?A
1567 "The highest priority of TODO items. A character like ?A, ?B etc.
1568 Must have a smaller ASCII number than `org-lowest-priority'."
1569 :group 'org-priorities
1570 :type 'character)
1571
1572 (defcustom org-lowest-priority ?C
1573 "The lowest priority of TODO items. A character like ?A, ?B etc.
1574 Must have a larger ASCII number than `org-highest-priority'."
1575 :group 'org-priorities
1576 :type 'character)
1577
1578 (defcustom org-default-priority ?B
1579 "The default priority of TODO items.
1580 This is the priority an item get if no explicit priority is given."
1581 :group 'org-priorities
1582 :type 'character)
1583
1584 (defcustom org-priority-start-cycle-with-default t
1585 "Non-nil means, start with default priority when starting to cycle.
1586 When this is nil, the first step in the cycle will be (depending on the
1587 command used) one higher or lower that the default priority."
1588 :group 'org-priorities
1589 :type 'boolean)
1590
1591 (defgroup org-time nil
1592 "Options concerning time stamps and deadlines in Org-mode."
1593 :tag "Org Time"
1594 :group 'org)
1595
1596 (defcustom org-insert-labeled-timestamps-at-point nil
1597 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1598 When nil, these labeled time stamps are forces into the second line of an
1599 entry, just after the headline. When scheduling from the global TODO list,
1600 the time stamp will always be forced into the second line."
1601 :group 'org-time
1602 :type 'boolean)
1603
1604 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1605 "Formats for `format-time-string' which are used for time stamps.
1606 It is not recommended to change this constant.")
1607
1608 (defcustom org-time-stamp-rounding-minutes '(0 5)
1609 "Number of minutes to round time stamps to.
1610 These are two values, the first applies when first creating a time stamp.
1611 The second applies when changing it with the commands `S-up' and `S-down'.
1612 When changing the time stamp, this means that it will change in steps
1613 of N minutes, as given by the second value.
1614
1615 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1616 numbers should be factors of 60, so for example 5, 10, 15.
1617
1618 When this is larger than 1, you can still force an exact time-stamp by using
1619 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1620 and by using a prefix arg to `S-up/down' to specify the exact number
1621 of minutes to shift."
1622 :group 'org-time
1623 :get '(lambda (var) ; Make sure all entries have 5 elements
1624 (if (integerp (default-value var))
1625 (list (default-value var) 5)
1626 (default-value var)))
1627 :type '(list
1628 (integer :tag "when inserting times")
1629 (integer :tag "when modifying times")))
1630
1631 ;; Normalize old customizations of this variable.
1632 (when (integerp org-time-stamp-rounding-minutes)
1633 (setq org-time-stamp-rounding-minutes
1634 (list org-time-stamp-rounding-minutes
1635 org-time-stamp-rounding-minutes)))
1636
1637 (defcustom org-display-custom-times nil
1638 "Non-nil means, overlay custom formats over all time stamps.
1639 The formats are defined through the variable `org-time-stamp-custom-formats'.
1640 To turn this on on a per-file basis, insert anywhere in the file:
1641 #+STARTUP: customtime"
1642 :group 'org-time
1643 :set 'set-default
1644 :type 'sexp)
1645 (make-variable-buffer-local 'org-display-custom-times)
1646
1647 (defcustom org-time-stamp-custom-formats
1648 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1649 "Custom formats for time stamps. See `format-time-string' for the syntax.
1650 These are overlayed over the default ISO format if the variable
1651 `org-display-custom-times' is set. Time like %H:%M should be at the
1652 end of the second format."
1653 :group 'org-time
1654 :type 'sexp)
1655
1656 (defun org-time-stamp-format (&optional long inactive)
1657 "Get the right format for a time string."
1658 (let ((f (if long (cdr org-time-stamp-formats)
1659 (car org-time-stamp-formats))))
1660 (if inactive
1661 (concat "[" (substring f 1 -1) "]")
1662 f)))
1663
1664 (defcustom org-time-clocksum-format "%d:%02d"
1665 "The format string used when creating CLOCKSUM lines, or when
1666 org-mode generates a time duration."
1667 :group 'org-time
1668 :type 'string)
1669
1670 (defcustom org-deadline-warning-days 14
1671 "No. of days before expiration during which a deadline becomes active.
1672 This variable governs the display in sparse trees and in the agenda.
1673 When 0 or negative, it means use this number (the absolute value of it)
1674 even if a deadline has a different individual lead time specified."
1675 :group 'org-time
1676 :group 'org-agenda-daily/weekly
1677 :type 'number)
1678
1679 (defcustom org-read-date-prefer-future t
1680 "Non-nil means, assume future for incomplete date input from user.
1681 This affects the following situations:
1682 1. The user gives a day, but no month.
1683 For example, if today is the 15th, and you enter \"3\", Org-mode will
1684 read this as the third of *next* month. However, if you enter \"17\",
1685 it will be considered as *this* month.
1686 2. The user gives a month but not a year.
1687 For example, if it is april and you enter \"feb 2\", this will be read
1688 as feb 2, *next* year. \"May 5\", however, will be this year.
1689
1690 Currently this does not work for ISO week specifications.
1691
1692 When this option is nil, the current month and year will always be used
1693 as defaults."
1694 :group 'org-time
1695 :type 'boolean)
1696
1697 (defcustom org-read-date-display-live t
1698 "Non-nil means, display current interpretation of date prompt live.
1699 This display will be in an overlay, in the minibuffer."
1700 :group 'org-time
1701 :type 'boolean)
1702
1703 (defcustom org-read-date-popup-calendar t
1704 "Non-nil means, pop up a calendar when prompting for a date.
1705 In the calendar, the date can be selected with mouse-1. However, the
1706 minibuffer will also be active, and you can simply enter the date as well.
1707 When nil, only the minibuffer will be available."
1708 :group 'org-time
1709 :type 'boolean)
1710 (if (fboundp 'defvaralias)
1711 (defvaralias 'org-popup-calendar-for-date-prompt
1712 'org-read-date-popup-calendar))
1713
1714 (defcustom org-extend-today-until 0
1715 "The hour when your day really ends. Must be an integer.
1716 This has influence for the following applications:
1717 - When switching the agenda to \"today\". It it is still earlier than
1718 the time given here, the day recognized as TODAY is actually yesterday.
1719 - When a date is read from the user and it is still before the time given
1720 here, the current date and time will be assumed to be yesterday, 23:59.
1721 Also, timestamps inserted in remember templates follow this rule.
1722
1723 IMPORTANT: This is a feature whose implementation is and likely will
1724 remain incomplete. Really, it is only here because past midnight seems to
1725 be the favorite working time of John Wiegley :-)"
1726 :group 'org-time
1727 :type 'number)
1728
1729 (defcustom org-edit-timestamp-down-means-later nil
1730 "Non-nil means, S-down will increase the time in a time stamp.
1731 When nil, S-up will increase."
1732 :group 'org-time
1733 :type 'boolean)
1734
1735 (defcustom org-calendar-follow-timestamp-change t
1736 "Non-nil means, make the calendar window follow timestamp changes.
1737 When a timestamp is modified and the calendar window is visible, it will be
1738 moved to the new date."
1739 :group 'org-time
1740 :type 'boolean)
1741
1742 (defgroup org-tags nil
1743 "Options concerning tags in Org-mode."
1744 :tag "Org Tags"
1745 :group 'org)
1746
1747 (defcustom org-tag-alist nil
1748 "List of tags allowed in Org-mode files.
1749 When this list is nil, Org-mode will base TAG input on what is already in the
1750 buffer.
1751 The value of this variable is an alist, the car of each entry must be a
1752 keyword as a string, the cdr may be a character that is used to select
1753 that tag through the fast-tag-selection interface.
1754 See the manual for details."
1755 :group 'org-tags
1756 :type '(repeat
1757 (choice
1758 (cons (string :tag "Tag name")
1759 (character :tag "Access char"))
1760 (const :tag "Start radio group" (:startgroup))
1761 (const :tag "End radio group" (:endgroup)))))
1762
1763 (defvar org-file-tags nil
1764 "List of tags that can be inherited by all entries in the file.
1765 The tags will be inherited if the variable `org-use-tag-inheritance'
1766 says they should be.
1767 This variable is populated from #+TAG lines.")
1768
1769 (defcustom org-use-fast-tag-selection 'auto
1770 "Non-nil means, use fast tag selection scheme.
1771 This is a special interface to select and deselect tags with single keys.
1772 When nil, fast selection is never used.
1773 When the symbol `auto', fast selection is used if and only if selection
1774 characters for tags have been configured, either through the variable
1775 `org-tag-alist' or through a #+TAGS line in the buffer.
1776 When t, fast selection is always used and selection keys are assigned
1777 automatically if necessary."
1778 :group 'org-tags
1779 :type '(choice
1780 (const :tag "Always" t)
1781 (const :tag "Never" nil)
1782 (const :tag "When selection characters are configured" 'auto)))
1783
1784 (defcustom org-fast-tag-selection-single-key nil
1785 "Non-nil means, fast tag selection exits after first change.
1786 When nil, you have to press RET to exit it.
1787 During fast tag selection, you can toggle this flag with `C-c'.
1788 This variable can also have the value `expert'. In this case, the window
1789 displaying the tags menu is not even shown, until you press C-c again."
1790 :group 'org-tags
1791 :type '(choice
1792 (const :tag "No" nil)
1793 (const :tag "Yes" t)
1794 (const :tag "Expert" expert)))
1795
1796 (defvar org-fast-tag-selection-include-todo nil
1797 "Non-nil means, fast tags selection interface will also offer TODO states.
1798 This is an undocumented feature, you should not rely on it.")
1799
1800 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1801 "The column to which tags should be indented in a headline.
1802 If this number is positive, it specifies the column. If it is negative,
1803 it means that the tags should be flushright to that column. For example,
1804 -80 works well for a normal 80 character screen."
1805 :group 'org-tags
1806 :type 'integer)
1807
1808 (defcustom org-auto-align-tags t
1809 "Non-nil means, realign tags after pro/demotion of TODO state change.
1810 These operations change the length of a headline and therefore shift
1811 the tags around. With this options turned on, after each such operation
1812 the tags are again aligned to `org-tags-column'."
1813 :group 'org-tags
1814 :type 'boolean)
1815
1816 (defcustom org-use-tag-inheritance t
1817 "Non-nil means, tags in levels apply also for sublevels.
1818 When nil, only the tags directly given in a specific line apply there.
1819 If this option is t, a match early-on in a tree can lead to a large
1820 number of matches in the subtree. If you only want to see the first
1821 match in a tree during a search, check out the variable
1822 `org-tags-match-list-sublevels'.
1823
1824 This may also be a list of tags that should be inherited, or a regexp that
1825 matches tags that should be inherited."
1826 :group 'org-tags
1827 :type '(choice
1828 (const :tag "Not" nil)
1829 (const :tag "Always" t)
1830 (repeat :tag "Specific tags" (string :tag "Tag"))
1831 (regexp :tag "Tags matched by regexp")))
1832
1833 (defun org-tag-inherit-p (tag)
1834 "Check if TAG is one that should be inherited."
1835 (cond
1836 ((eq org-use-tag-inheritance t) t)
1837 ((not org-use-tag-inheritance) nil)
1838 ((stringp org-use-tag-inheritance)
1839 (string-match org-use-tag-inheritance tag))
1840 ((listp org-use-tag-inheritance)
1841 (member tag org-use-tag-inheritance))
1842 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1843
1844 (defcustom org-tags-match-list-sublevels t
1845 "Non-nil means list also sublevels of headlines matching tag search.
1846 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1847 the sublevels of a headline matching a tag search often also match
1848 the same search. Listing all of them can create very long lists.
1849 Setting this variable to nil causes subtrees of a match to be skipped.
1850 This option is off by default, because inheritance in on. If you turn
1851 inheritance off, you very likely want to turn this option on.
1852
1853 As a special case, if the tag search is restricted to TODO items, the
1854 value of this variable is ignored and sublevels are always checked, to
1855 make sure all corresponding TODO items find their way into the list."
1856 :group 'org-tags
1857 :type 'boolean)
1858
1859 (defvar org-tags-history nil
1860 "History of minibuffer reads for tags.")
1861 (defvar org-last-tags-completion-table nil
1862 "The last used completion table for tags.")
1863 (defvar org-after-tags-change-hook nil
1864 "Hook that is run after the tags in a line have changed.")
1865
1866 (defgroup org-properties nil
1867 "Options concerning properties in Org-mode."
1868 :tag "Org Properties"
1869 :group 'org)
1870
1871 (defcustom org-property-format "%-10s %s"
1872 "How property key/value pairs should be formatted by `indent-line'.
1873 When `indent-line' hits a property definition, it will format the line
1874 according to this format, mainly to make sure that the values are
1875 lined-up with respect to each other."
1876 :group 'org-properties
1877 :type 'string)
1878
1879 (defcustom org-use-property-inheritance nil
1880 "Non-nil means, properties apply also for sublevels.
1881
1882 This setting is chiefly used during property searches. Turning it on can
1883 cause significant overhead when doing a search, which is why it is not
1884 on by default.
1885
1886 When nil, only the properties directly given in the current entry count.
1887 When t, every property is inherited. The value may also be a list of
1888 properties that should have inheritance, or a regular expression matching
1889 properties that should be inherited.
1890
1891 However, note that some special properties use inheritance under special
1892 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1893 and the properties ending in \"_ALL\" when they are used as descriptor
1894 for valid values of a property.
1895
1896 Note for programmers:
1897 When querying an entry with `org-entry-get', you can control if inheritance
1898 should be used. By default, `org-entry-get' looks only at the local
1899 properties. You can request inheritance by setting the inherit argument
1900 to t (to force inheritance) or to `selective' (to respect the setting
1901 in this variable)."
1902 :group 'org-properties
1903 :type '(choice
1904 (const :tag "Not" nil)
1905 (const :tag "Always" t)
1906 (repeat :tag "Specific properties" (string :tag "Property"))
1907 (regexp :tag "Properties matched by regexp")))
1908
1909 (defun org-property-inherit-p (property)
1910 "Check if PROPERTY is one that should be inherited."
1911 (cond
1912 ((eq org-use-property-inheritance t) t)
1913 ((not org-use-property-inheritance) nil)
1914 ((stringp org-use-property-inheritance)
1915 (string-match org-use-property-inheritance property))
1916 ((listp org-use-property-inheritance)
1917 (member property org-use-property-inheritance))
1918 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1919
1920 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1921 "The default column format, if no other format has been defined.
1922 This variable can be set on the per-file basis by inserting a line
1923
1924 #+COLUMNS: %25ITEM ....."
1925 :group 'org-properties
1926 :type 'string)
1927
1928 (defcustom org-columns-ellipses ".."
1929 "The ellipses to be used when a field in column view is truncated.
1930 When this is the empty string, as many characters as possible are shown,
1931 but then there will be no visual indication that the field has been truncated.
1932 When this is a string of length N, the last N characters of a truncated
1933 field are replaced by this string. If the column is narrower than the
1934 ellipses string, only part of the ellipses string will be shown."
1935 :group 'org-properties
1936 :type 'string)
1937
1938 (defcustom org-columns-modify-value-for-display-function nil
1939 "Function that modifies values for display in column view.
1940 For example, it can be used to cut out a certain part from a time stamp.
1941 The function must take 2 argments:
1942
1943 column-title The tite of the column (*not* the property name)
1944 value The value that should be modified.
1945
1946 The function should return the value that should be displayed,
1947 or nil if the normal value should be used."
1948 :group 'org-properties
1949 :type 'function)
1950
1951 (defcustom org-effort-property "Effort"
1952 "The property that is being used to keep track of effort estimates.
1953 Effort estimates given in this property need to have the format H:MM."
1954 :group 'org-properties
1955 :group 'org-progress
1956 :type '(string :tag "Property"))
1957
1958 (defconst org-global-properties-fixed
1959 '(("VISIBILITY_ALL" . "folded children content all"))
1960 "List of property/value pairs that can be inherited by any entry.
1961 These are fixed values, for the preset properties.")
1962
1963
1964 (defcustom org-global-properties nil
1965 "List of property/value pairs that can be inherited by any entry.
1966 You can set buffer-local values for this by adding lines like
1967
1968 #+PROPERTY: NAME VALUE"
1969 :group 'org-properties
1970 :type '(repeat
1971 (cons (string :tag "Property")
1972 (string :tag "Value"))))
1973
1974 (defvar org-file-properties nil
1975 "List of property/value pairs that can be inherited by any entry.
1976 Valid for the current buffer.
1977 This variable is populated from #+PROPERTY lines.")
1978 (make-variable-buffer-local 'org-file-properties)
1979
1980 (defgroup org-agenda nil
1981 "Options concerning agenda views in Org-mode."
1982 :tag "Org Agenda"
1983 :group 'org)
1984
1985 (defvar org-category nil
1986 "Variable used by org files to set a category for agenda display.
1987 Such files should use a file variable to set it, for example
1988
1989 # -*- mode: org; org-category: \"ELisp\"
1990
1991 or contain a special line
1992
1993 #+CATEGORY: ELisp
1994
1995 If the file does not specify a category, then file's base name
1996 is used instead.")
1997 (make-variable-buffer-local 'org-category)
1998 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
1999
2000 (defcustom org-agenda-files nil
2001 "The files to be used for agenda display.
2002 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2003 \\[org-remove-file]. You can also use customize to edit the list.
2004
2005 If an entry is a directory, all files in that directory that are matched by
2006 `org-agenda-file-regexp' will be part of the file list.
2007
2008 If the value of the variable is not a list but a single file name, then
2009 the list of agenda files is actually stored and maintained in that file, one
2010 agenda file per line."
2011 :group 'org-agenda
2012 :type '(choice
2013 (repeat :tag "List of files and directories" file)
2014 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2015
2016 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2017 "Regular expression to match files for `org-agenda-files'.
2018 If any element in the list in that variable contains a directory instead
2019 of a normal file, all files in that directory that are matched by this
2020 regular expression will be included."
2021 :group 'org-agenda
2022 :type 'regexp)
2023
2024 (defcustom org-agenda-text-search-extra-files nil
2025 "List of extra files to be searched by text search commands.
2026 These files will be search in addition to the agenda files by the
2027 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2028 Note that these files will only be searched for text search commands,
2029 not for the other agenda views like todo lists, tag searches or the weekly
2030 agenda. This variable is intended to list notes and possibly archive files
2031 that should also be searched by these two commands.
2032 In fact, if the first element in the list is the symbol `agenda-archives',
2033 than all archive files of all agenda files will be added to the search
2034 scope."
2035 :group 'org-agenda
2036 :type '(set :greedy t
2037 (const :tag "Agenda Archives" agenda-archives)
2038 (repeat :inline t (file))))
2039
2040 (if (fboundp 'defvaralias)
2041 (defvaralias 'org-agenda-multi-occur-extra-files
2042 'org-agenda-text-search-extra-files))
2043
2044 (defcustom org-agenda-skip-unavailable-files nil
2045 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2046 A nil value means to remove them, after a query, from the list."
2047 :group 'org-agenda
2048 :type 'boolean)
2049
2050 (defcustom org-calendar-to-agenda-key [?c]
2051 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2052 The command `org-calendar-goto-agenda' will be bound to this key. The
2053 default is the character `c' because then `c' can be used to switch back and
2054 forth between agenda and calendar."
2055 :group 'org-agenda
2056 :type 'sexp)
2057
2058 (defcustom org-calendar-agenda-action-key [?k]
2059 "The key to be installed in `calendar-mode-map' for agenda-action.
2060 The command `org-agenda-action' will be bound to this key. The
2061 default is the character `k' because we use the same key in the agenda."
2062 :group 'org-agenda
2063 :type 'sexp)
2064
2065 (eval-after-load "calendar"
2066 '(progn
2067 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2068 'org-calendar-goto-agenda)
2069 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2070 'org-agenda-action)))
2071
2072 (defgroup org-latex nil
2073 "Options for embedding LaTeX code into Org-mode."
2074 :tag "Org LaTeX"
2075 :group 'org)
2076
2077 (defcustom org-format-latex-options
2078 '(:foreground default :background default :scale 1.0
2079 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2080 :matchers ("begin" "$" "$$" "\\(" "\\["))
2081 "Options for creating images from LaTeX fragments.
2082 This is a property list with the following properties:
2083 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2084 `default' means use the foreground of the default face.
2085 :background the background color, or \"Transparent\".
2086 `default' means use the background of the default face.
2087 :scale a scaling factor for the size of the images.
2088 :html-foreground, :html-background, :html-scale
2089 the same numbers for HTML export.
2090 :matchers a list indicating which matchers should be used to
2091 find LaTeX fragments. Valid members of this list are:
2092 \"begin\" find environments
2093 \"$\" find math expressions surrounded by $...$
2094 \"$$\" find math expressions surrounded by $$....$$
2095 \"\\(\" find math expressions surrounded by \\(...\\)
2096 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2097 :group 'org-latex
2098 :type 'plist)
2099
2100 (defcustom org-format-latex-header "\\documentclass{article}
2101 \\usepackage{fullpage} % do not remove
2102 \\usepackage{amssymb}
2103 \\usepackage[usenames]{color}
2104 \\usepackage{amsmath}
2105 \\usepackage{latexsym}
2106 \\usepackage[mathscr]{eucal}
2107 \\pagestyle{empty} % do not remove"
2108 "The document header used for processing LaTeX fragments."
2109 :group 'org-latex
2110 :type 'string)
2111
2112
2113 (defgroup org-font-lock nil
2114 "Font-lock settings for highlighting in Org-mode."
2115 :tag "Org Font Lock"
2116 :group 'org)
2117
2118 (defcustom org-level-color-stars-only nil
2119 "Non-nil means fontify only the stars in each headline.
2120 When nil, the entire headline is fontified.
2121 Changing it requires restart of `font-lock-mode' to become effective
2122 also in regions already fontified."
2123 :group 'org-font-lock
2124 :type 'boolean)
2125
2126 (defcustom org-hide-leading-stars nil
2127 "Non-nil means, hide the first N-1 stars in a headline.
2128 This works by using the face `org-hide' for these stars. This
2129 face is white for a light background, and black for a dark
2130 background. You may have to customize the face `org-hide' to
2131 make this work.
2132 Changing it requires restart of `font-lock-mode' to become effective
2133 also in regions already fontified.
2134 You may also set this on a per-file basis by adding one of the following
2135 lines to the buffer:
2136
2137 #+STARTUP: hidestars
2138 #+STARTUP: showstars"
2139 :group 'org-font-lock
2140 :type 'boolean)
2141
2142 (defcustom org-fontify-done-headline nil
2143 "Non-nil means, change the face of a headline if it is marked DONE.
2144 Normally, only the TODO/DONE keyword indicates the state of a headline.
2145 When this is non-nil, the headline after the keyword is set to the
2146 `org-headline-done' as an additional indication."
2147 :group 'org-font-lock
2148 :type 'boolean)
2149
2150 (defcustom org-fontify-emphasized-text t
2151 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2152 Changing this variable requires a restart of Emacs to take effect."
2153 :group 'org-font-lock
2154 :type 'boolean)
2155
2156 (defcustom org-highlight-latex-fragments-and-specials nil
2157 "Non-nil means, fontify what is treated specially by the exporters."
2158 :group 'org-font-lock
2159 :type 'boolean)
2160
2161 (defcustom org-hide-emphasis-markers nil
2162 "Non-nil mean font-lock should hide the emphasis marker characters."
2163 :group 'org-font-lock
2164 :type 'boolean)
2165
2166 (defvar org-emph-re nil
2167 "Regular expression for matching emphasis.")
2168 (defvar org-verbatim-re nil
2169 "Regular expression for matching verbatim text.")
2170 (defvar org-emphasis-regexp-components) ; defined just below
2171 (defvar org-emphasis-alist) ; defined just below
2172 (defun org-set-emph-re (var val)
2173 "Set variable and compute the emphasis regular expression."
2174 (set var val)
2175 (when (and (boundp 'org-emphasis-alist)
2176 (boundp 'org-emphasis-regexp-components)
2177 org-emphasis-alist org-emphasis-regexp-components)
2178 (let* ((e org-emphasis-regexp-components)
2179 (pre (car e))
2180 (post (nth 1 e))
2181 (border (nth 2 e))
2182 (body (nth 3 e))
2183 (nl (nth 4 e))
2184 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2185 (body1 (concat body "*?"))
2186 (markers (mapconcat 'car org-emphasis-alist ""))
2187 (vmarkers (mapconcat
2188 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2189 org-emphasis-alist "")))
2190 ;; make sure special characters appear at the right position in the class
2191 (if (string-match "\\^" markers)
2192 (setq markers (concat (replace-match "" t t markers) "^")))
2193 (if (string-match "-" markers)
2194 (setq markers (concat (replace-match "" t t markers) "-")))
2195 (if (string-match "\\^" vmarkers)
2196 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2197 (if (string-match "-" vmarkers)
2198 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2199 (if (> nl 0)
2200 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2201 (int-to-string nl) "\\}")))
2202 ;; Make the regexp
2203 (setq org-emph-re
2204 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2205 "\\("
2206 "\\([" markers "]\\)"
2207 "\\("
2208 "[^" border "]\\|"
2209 "[^" border (if (and nil stacked) markers) "]"
2210 body1
2211 "[^" border (if (and nil stacked) markers) "]"
2212 "\\)"
2213 "\\3\\)"
2214 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2215 (setq org-verbatim-re
2216 (concat "\\([" pre "]\\|^\\)"
2217 "\\("
2218 "\\([" vmarkers "]\\)"
2219 "\\("
2220 "[^" border "]\\|"
2221 "[^" border "]"
2222 body1
2223 "[^" border "]"
2224 "\\)"
2225 "\\3\\)"
2226 "\\([" post "]\\|$\\)")))))
2227
2228 (defcustom org-emphasis-regexp-components
2229 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2230 "Components used to build the regular expression for emphasis.
2231 This is a list with 6 entries. Terminology: In an emphasis string
2232 like \" *strong word* \", we call the initial space PREMATCH, the final
2233 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2234 and \"trong wor\" is the body. The different components in this variable
2235 specify what is allowed/forbidden in each part:
2236
2237 pre Chars allowed as prematch. Beginning of line will be allowed too.
2238 post Chars allowed as postmatch. End of line will be allowed too.
2239 border The chars *forbidden* as border characters.
2240 body-regexp A regexp like \".\" to match a body character. Don't use
2241 non-shy groups here, and don't allow newline here.
2242 newline The maximum number of newlines allowed in an emphasis exp.
2243
2244 Use customize to modify this, or restart Emacs after changing it."
2245 :group 'org-font-lock
2246 :set 'org-set-emph-re
2247 :type '(list
2248 (sexp :tag "Allowed chars in pre ")
2249 (sexp :tag "Allowed chars in post ")
2250 (sexp :tag "Forbidden chars in border ")
2251 (sexp :tag "Regexp for body ")
2252 (integer :tag "number of newlines allowed")
2253 (option (boolean :tag "Please ignore this button"))))
2254
2255 (defcustom org-emphasis-alist
2256 `(("*" bold "<b>" "</b>")
2257 ("/" italic "<i>" "</i>")
2258 ("_" underline "<u>" "</u>")
2259 ("=" org-code "<code>" "</code>" verbatim)
2260 ("~" org-verbatim "" "" verbatim)
2261 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2262 "<del>" "</del>")
2263 )
2264 "Special syntax for emphasized text.
2265 Text starting and ending with a special character will be emphasized, for
2266 example *bold*, _underlined_ and /italic/. This variable sets the marker
2267 characters, the face to be used by font-lock for highlighting in Org-mode
2268 Emacs buffers, and the HTML tags to be used for this.
2269 Use customize to modify this, or restart Emacs after changing it."
2270 :group 'org-font-lock
2271 :set 'org-set-emph-re
2272 :type '(repeat
2273 (list
2274 (string :tag "Marker character")
2275 (choice
2276 (face :tag "Font-lock-face")
2277 (plist :tag "Face property list"))
2278 (string :tag "HTML start tag")
2279 (string :tag "HTML end tag")
2280 (option (const verbatim)))))
2281
2282 ;;; Miscellaneous options
2283
2284 (defgroup org-completion nil
2285 "Completion in Org-mode."
2286 :tag "Org Completion"
2287 :group 'org)
2288
2289 (defcustom org-completion-fallback-command 'hippie-expand
2290 "The expansion command called by \\[org-complete] in normal context.
2291 Normal means, no org-mode-specific context."
2292 :group 'org-completion
2293 :type 'function)
2294
2295 ;;; Functions and variables from ther packages
2296 ;; Declared here to avoid compiler warnings
2297
2298 ;; XEmacs only
2299 (defvar outline-mode-menu-heading)
2300 (defvar outline-mode-menu-show)
2301 (defvar outline-mode-menu-hide)
2302 (defvar zmacs-regions) ; XEmacs regions
2303
2304 ;; Emacs only
2305 (defvar mark-active)
2306
2307 ;; Various packages
2308 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2309 (declare-function calendar-forward-day "cal-move" (arg))
2310 (declare-function calendar-goto-date "cal-move" (date))
2311 (declare-function calendar-goto-today "cal-move" ())
2312 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2313 (defvar calc-embedded-close-formula)
2314 (defvar calc-embedded-open-formula)
2315 (declare-function cdlatex-tab "ext:cdlatex" ())
2316 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2317 (defvar font-lock-unfontify-region-function)
2318 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2319 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2320 (defvar iswitchb-temp-buflist)
2321 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2322 (declare-function org-agenda-skip "org-agenda" ())
2323 (declare-function org-format-agenda-item "org-agenda"
2324 (extra txt &optional category tags dotime noprefix remove-re))
2325 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2326 (declare-function org-agenda-change-all-lines "org-agenda"
2327 (newhead hdmarker &optional fixface))
2328 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2329 (declare-function org-agenda-maybe-redo "org-agenda" ())
2330 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2331 (beg end))
2332 (declare-function parse-time-string "parse-time" (string))
2333 (declare-function remember "remember" (&optional initial))
2334 (declare-function remember-buffer-desc "remember" ())
2335 (declare-function remember-finalize "remember" ())
2336 (defvar remember-save-after-remembering)
2337 (defvar remember-data-file)
2338 (defvar remember-register)
2339 (defvar remember-buffer)
2340 (defvar remember-handler-functions)
2341 (defvar remember-annotation-functions)
2342 (defvar texmathp-why)
2343 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2344 (declare-function table--at-cell-p "table" (position &optional object at-column))
2345
2346 (defvar w3m-current-url)
2347 (defvar w3m-current-title)
2348
2349 (defvar org-latex-regexps)
2350
2351 ;;; Autoload and prepare some org modules
2352
2353 ;; Some table stuff that needs to be defined here, because it is used
2354 ;; by the functions setting up org-mode or checking for table context.
2355
2356 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2357 "Detects an org-type or table-type table.")
2358 (defconst org-table-line-regexp "^[ \t]*|"
2359 "Detects an org-type table line.")
2360 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2361 "Detects an org-type table line.")
2362 (defconst org-table-hline-regexp "^[ \t]*|-"
2363 "Detects an org-type table hline.")
2364 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2365 "Detects a table-type table hline.")
2366 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2367 "Searching from within a table (any type) this finds the first line
2368 outside the table.")
2369
2370 ;; Autoload the functions in org-table.el that are needed by functions here.
2371
2372 (eval-and-compile
2373 (org-autoload "org-table"
2374 '(org-table-align org-table-begin org-table-blank-field
2375 org-table-convert org-table-convert-region org-table-copy-down
2376 org-table-copy-region org-table-create
2377 org-table-create-or-convert-from-region
2378 org-table-create-with-table.el org-table-current-dline
2379 org-table-cut-region org-table-delete-column org-table-edit-field
2380 org-table-edit-formulas org-table-end org-table-eval-formula
2381 org-table-export org-table-field-info
2382 org-table-get-stored-formulas org-table-goto-column
2383 org-table-hline-and-move org-table-import org-table-insert-column
2384 org-table-insert-hline org-table-insert-row org-table-iterate
2385 org-table-justify-field-maybe org-table-kill-row
2386 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2387 org-table-move-column org-table-move-column-left
2388 org-table-move-column-right org-table-move-row
2389 org-table-move-row-down org-table-move-row-up
2390 org-table-next-field org-table-next-row org-table-paste-rectangle
2391 org-table-previous-field org-table-recalculate
2392 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2393 org-table-toggle-coordinate-overlays
2394 org-table-toggle-formula-debugger org-table-wrap-region
2395 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2396
2397 (defun org-at-table-p (&optional table-type)
2398 "Return t if the cursor is inside an org-type table.
2399 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2400 (if org-enable-table-editor
2401 (save-excursion
2402 (beginning-of-line 1)
2403 (looking-at (if table-type org-table-any-line-regexp
2404 org-table-line-regexp)))
2405 nil))
2406 (defsubst org-table-p () (org-at-table-p))
2407
2408 (defun org-at-table.el-p ()
2409 "Return t if and only if we are at a table.el table."
2410 (and (org-at-table-p 'any)
2411 (save-excursion
2412 (goto-char (org-table-begin 'any))
2413 (looking-at org-table1-hline-regexp))))
2414 (defun org-table-recognize-table.el ()
2415 "If there is a table.el table nearby, recognize it and move into it."
2416 (if org-table-tab-recognizes-table.el
2417 (if (org-at-table.el-p)
2418 (progn
2419 (beginning-of-line 1)
2420 (if (looking-at org-table-dataline-regexp)
2421 nil
2422 (if (looking-at org-table1-hline-regexp)
2423 (progn
2424 (beginning-of-line 2)
2425 (if (looking-at org-table-any-border-regexp)
2426 (beginning-of-line -1)))))
2427 (if (re-search-forward "|" (org-table-end t) t)
2428 (progn
2429 (require 'table)
2430 (if (table--at-cell-p (point))
2431 t
2432 (message "recognizing table.el table...")
2433 (table-recognize-table)
2434 (message "recognizing table.el table...done")))
2435 (error "This should not happen..."))
2436 t)
2437 nil)
2438 nil))
2439
2440 (defun org-at-table-hline-p ()
2441 "Return t if the cursor is inside a hline in a table."
2442 (if org-enable-table-editor
2443 (save-excursion
2444 (beginning-of-line 1)
2445 (looking-at org-table-hline-regexp))
2446 nil))
2447
2448 (defvar org-table-clean-did-remove-column nil)
2449
2450 (defun org-table-map-tables (function)
2451 "Apply FUNCTION to the start of all tables in the buffer."
2452 (save-excursion
2453 (save-restriction
2454 (widen)
2455 (goto-char (point-min))
2456 (while (re-search-forward org-table-any-line-regexp nil t)
2457 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2458 (beginning-of-line 1)
2459 (if (looking-at org-table-line-regexp)
2460 (save-excursion (funcall function)))
2461 (re-search-forward org-table-any-border-regexp nil 1))))
2462 (message "Mapping tables: done"))
2463
2464 ;; Declare and autoload functions from org-exp.el
2465
2466 (declare-function org-default-export-plist "org-exp")
2467 (declare-function org-infile-export-plist "org-exp")
2468 (declare-function org-get-current-options "org-exp")
2469 (eval-and-compile
2470 (org-autoload "org-exp"
2471 '(org-export org-export-as-ascii org-export-visible
2472 org-insert-export-options-template org-export-as-html-and-open
2473 org-export-as-html-batch org-export-as-html-to-buffer
2474 org-replace-region-by-html org-export-region-as-html
2475 org-export-as-html org-export-icalendar-this-file
2476 org-export-icalendar-all-agenda-files
2477 org-table-clean-before-export
2478 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2479
2480 ;; Declare and autoload functions from org-agenda.el
2481
2482 (eval-and-compile
2483 (org-autoload "org-agenda"
2484 '(org-agenda org-agenda-list org-search-view
2485 org-todo-list org-tags-view org-agenda-list-stuck-projects
2486 org-diary org-agenda-to-appt)))
2487
2488 ;; Autoload org-remember
2489
2490 (eval-and-compile
2491 (org-autoload "org-remember"
2492 '(org-remember-insinuate org-remember-annotation
2493 org-remember-apply-template org-remember org-remember-handler)))
2494
2495 ;; Autoload org-clock.el
2496
2497
2498 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2499 (beg end))
2500 (declare-function org-update-mode-line "org-clock" ())
2501 (defvar org-clock-start-time)
2502 (defvar org-clock-marker (make-marker)
2503 "Marker recording the last clock-in.")
2504
2505 (eval-and-compile
2506 (org-autoload
2507 "org-clock"
2508 '(org-clock-in org-clock-out org-clock-cancel
2509 org-clock-goto org-clock-sum org-clock-display
2510 org-remove-clock-overlays org-clock-report
2511 org-clocktable-shift org-dblock-write:clocktable
2512 org-get-clocktable)))
2513
2514 (defun org-clock-update-time-maybe ()
2515 "If this is a CLOCK line, update it and return t.
2516 Otherwise, return nil."
2517 (interactive)
2518 (save-excursion
2519 (beginning-of-line 1)
2520 (skip-chars-forward " \t")
2521 (when (looking-at org-clock-string)
2522 (let ((re (concat "[ \t]*" org-clock-string
2523 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2524 "\\([ \t]*=>.*\\)?\\)?"))
2525 ts te h m s neg)
2526 (cond
2527 ((not (looking-at re))
2528 nil)
2529 ((not (match-end 2))
2530 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2531 (> org-clock-marker (point))
2532 (<= org-clock-marker (point-at-eol)))
2533 ;; The clock is running here
2534 (setq org-clock-start-time
2535 (apply 'encode-time
2536 (org-parse-time-string (match-string 1))))
2537 (org-update-mode-line)))
2538 (t
2539 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2540 (end-of-line 1)
2541 (setq ts (match-string 1)
2542 te (match-string 3))
2543 (setq s (- (time-to-seconds
2544 (apply 'encode-time (org-parse-time-string te)))
2545 (time-to-seconds
2546 (apply 'encode-time (org-parse-time-string ts))))
2547 neg (< s 0)
2548 s (abs s)
2549 h (floor (/ s 3600))
2550 s (- s (* 3600 h))
2551 m (floor (/ s 60))
2552 s (- s (* 60 s)))
2553 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2554 t))))))
2555
2556 (defun org-check-running-clock ()
2557 "Check if the current buffer contains the running clock.
2558 If yes, offer to stop it and to save the buffer with the changes."
2559 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2560 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2561 (buffer-name))))
2562 (org-clock-out)
2563 (when (y-or-n-p "Save changed buffer?")
2564 (save-buffer))))
2565
2566 (defun org-clocktable-try-shift (dir n)
2567 "Check if this line starts a clock table, if yes, shift the time block."
2568 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2569 (org-clocktable-shift dir n)))
2570
2571 ;; Autoload archiving code
2572 ;; The stuff that is needed for cycling and tags has to be defined here.
2573
2574 (defgroup org-archive nil
2575 "Options concerning archiving in Org-mode."
2576 :tag "Org Archive"
2577 :group 'org-structure)
2578
2579 (defcustom org-archive-location "%s_archive::"
2580 "The location where subtrees should be archived.
2581
2582 Otherwise, the value of this variable is a string, consisting of two
2583 parts, separated by a double-colon.
2584
2585 The first part is a file name - when omitted, archiving happens in the same
2586 file. %s will be replaced by the current file name (without directory part).
2587 Archiving to a different file is useful to keep archived entries from
2588 contributing to the Org-mode Agenda.
2589
2590 The part after the double colon is a headline. The archived entries will be
2591 filed under that headline. When omitted, the subtrees are simply filed away
2592 at the end of the file, as top-level entries.
2593
2594 Here are a few examples:
2595 \"%s_archive::\"
2596 If the current file is Projects.org, archive in file
2597 Projects.org_archive, as top-level trees. This is the default.
2598
2599 \"::* Archived Tasks\"
2600 Archive in the current file, under the top-level headline
2601 \"* Archived Tasks\".
2602
2603 \"~/org/archive.org::\"
2604 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2605
2606 \"basement::** Finished Tasks\"
2607 Archive in file ./basement (relative path), as level 3 trees
2608 below the level 2 heading \"** Finished Tasks\".
2609
2610 You may set this option on a per-file basis by adding to the buffer a
2611 line like
2612
2613 #+ARCHIVE: basement::** Finished Tasks
2614
2615 You may also define it locally for a subtree by setting an ARCHIVE property
2616 in the entry. If such a property is found in an entry, or anywhere up
2617 the hierarchy, it will be used."
2618 :group 'org-archive
2619 :type 'string)
2620
2621 (defcustom org-archive-tag "ARCHIVE"
2622 "The tag that marks a subtree as archived.
2623 An archived subtree does not open during visibility cycling, and does
2624 not contribute to the agenda listings.
2625 After changing this, font-lock must be restarted in the relevant buffers to
2626 get the proper fontification."
2627 :group 'org-archive
2628 :group 'org-keywords
2629 :type 'string)
2630
2631 (defcustom org-agenda-skip-archived-trees t
2632 "Non-nil means, the agenda will skip any items located in archived trees.
2633 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2634 variable is no longer recommended, you should leave it at the value t.
2635 Instead, use the key `v' to cycle the archives-mode in the agenda."
2636 :group 'org-archive
2637 :group 'org-agenda-skip
2638 :type 'boolean)
2639
2640 (defcustom org-cycle-open-archived-trees nil
2641 "Non-nil means, `org-cycle' will open archived trees.
2642 An archived tree is a tree marked with the tag ARCHIVE.
2643 When nil, archived trees will stay folded. You can still open them with
2644 normal outline commands like `show-all', but not with the cycling commands."
2645 :group 'org-archive
2646 :group 'org-cycle
2647 :type 'boolean)
2648
2649 (defcustom org-sparse-tree-open-archived-trees nil
2650 "Non-nil means sparse tree construction shows matches in archived trees.
2651 When nil, matches in these trees are highlighted, but the trees are kept in
2652 collapsed state."
2653 :group 'org-archive
2654 :group 'org-sparse-trees
2655 :type 'boolean)
2656
2657 (defun org-cycle-hide-archived-subtrees (state)
2658 "Re-hide all archived subtrees after a visibility state change."
2659 (when (and (not org-cycle-open-archived-trees)
2660 (not (memq state '(overview folded))))
2661 (save-excursion
2662 (let* ((globalp (memq state '(contents all)))
2663 (beg (if globalp (point-min) (point)))
2664 (end (if globalp (point-max) (org-end-of-subtree t))))
2665 (org-hide-archived-subtrees beg end)
2666 (goto-char beg)
2667 (if (looking-at (concat ".*:" org-archive-tag ":"))
2668 (message "%s" (substitute-command-keys
2669 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2670
2671 (defun org-force-cycle-archived ()
2672 "Cycle subtree even if it is archived."
2673 (interactive)
2674 (setq this-command 'org-cycle)
2675 (let ((org-cycle-open-archived-trees t))
2676 (call-interactively 'org-cycle)))
2677
2678 (defun org-hide-archived-subtrees (beg end)
2679 "Re-hide all archived subtrees after a visibility state change."
2680 (save-excursion
2681 (let* ((re (concat ":" org-archive-tag ":")))
2682 (goto-char beg)
2683 (while (re-search-forward re end t)
2684 (and (org-on-heading-p) (hide-subtree))
2685 (org-end-of-subtree t)))))
2686
2687 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2688
2689 (eval-and-compile
2690 (org-autoload "org-archive"
2691 '(org-add-archive-files org-archive-subtree
2692 org-archive-to-archive-sibling org-toggle-archive-tag)))
2693
2694 ;; Autoload Column View Code
2695
2696 (declare-function org-columns-number-to-string "org-colview")
2697 (declare-function org-columns-get-format-and-top-level "org-colview")
2698 (declare-function org-columns-compute "org-colview")
2699
2700 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2701 '(org-columns-number-to-string org-columns-get-format-and-top-level
2702 org-columns-compute org-agenda-columns org-columns-remove-overlays
2703 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2704
2705 ;; Autoload ID code
2706
2707 (org-autoload "org-id"
2708 '(org-id-get-create org-id-new org-id-copy org-id-get
2709 org-id-get-with-outline-path-completion
2710 org-id-get-with-outline-drilling
2711 org-id-goto org-id-find))
2712
2713 ;;; Variables for pre-computed regular expressions, all buffer local
2714
2715 (defvar org-drawer-regexp nil
2716 "Matches first line of a hidden block.")
2717 (make-variable-buffer-local 'org-drawer-regexp)
2718 (defvar org-todo-regexp nil
2719 "Matches any of the TODO state keywords.")
2720 (make-variable-buffer-local 'org-todo-regexp)
2721 (defvar org-not-done-regexp nil
2722 "Matches any of the TODO state keywords except the last one.")
2723 (make-variable-buffer-local 'org-not-done-regexp)
2724 (defvar org-todo-line-regexp nil
2725 "Matches a headline and puts TODO state into group 2 if present.")
2726 (make-variable-buffer-local 'org-todo-line-regexp)
2727 (defvar org-complex-heading-regexp nil
2728 "Matches a headline and puts everything into groups:
2729 group 1: the stars
2730 group 2: The todo keyword, maybe
2731 group 3: Priority cookie
2732 group 4: True headline
2733 group 5: Tags")
2734 (make-variable-buffer-local 'org-complex-heading-regexp)
2735 (defvar org-todo-line-tags-regexp nil
2736 "Matches a headline and puts TODO state into group 2 if present.
2737 Also put tags into group 4 if tags are present.")
2738 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2739 (defvar org-nl-done-regexp nil
2740 "Matches newline followed by a headline with the DONE keyword.")
2741 (make-variable-buffer-local 'org-nl-done-regexp)
2742 (defvar org-looking-at-done-regexp nil
2743 "Matches the DONE keyword a point.")
2744 (make-variable-buffer-local 'org-looking-at-done-regexp)
2745 (defvar org-ds-keyword-length 12
2746 "Maximum length of the Deadline and SCHEDULED keywords.")
2747 (make-variable-buffer-local 'org-ds-keyword-length)
2748 (defvar org-deadline-regexp nil
2749 "Matches the DEADLINE keyword.")
2750 (make-variable-buffer-local 'org-deadline-regexp)
2751 (defvar org-deadline-time-regexp nil
2752 "Matches the DEADLINE keyword together with a time stamp.")
2753 (make-variable-buffer-local 'org-deadline-time-regexp)
2754 (defvar org-deadline-line-regexp nil
2755 "Matches the DEADLINE keyword and the rest of the line.")
2756 (make-variable-buffer-local 'org-deadline-line-regexp)
2757 (defvar org-scheduled-regexp nil
2758 "Matches the SCHEDULED keyword.")
2759 (make-variable-buffer-local 'org-scheduled-regexp)
2760 (defvar org-scheduled-time-regexp nil
2761 "Matches the SCHEDULED keyword together with a time stamp.")
2762 (make-variable-buffer-local 'org-scheduled-time-regexp)
2763 (defvar org-closed-time-regexp nil
2764 "Matches the CLOSED keyword together with a time stamp.")
2765 (make-variable-buffer-local 'org-closed-time-regexp)
2766
2767 (defvar org-keyword-time-regexp nil
2768 "Matches any of the 4 keywords, together with the time stamp.")
2769 (make-variable-buffer-local 'org-keyword-time-regexp)
2770 (defvar org-keyword-time-not-clock-regexp nil
2771 "Matches any of the 3 keywords, together with the time stamp.")
2772 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2773 (defvar org-maybe-keyword-time-regexp nil
2774 "Matches a timestamp, possibly preceeded by a keyword.")
2775 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2776 (defvar org-planning-or-clock-line-re nil
2777 "Matches a line with planning or clock info.")
2778 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2779
2780 (defconst org-plain-time-of-day-regexp
2781 (concat
2782 "\\(\\<[012]?[0-9]"
2783 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2784 "\\(--?"
2785 "\\(\\<[012]?[0-9]"
2786 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2787 "\\)?")
2788 "Regular expression to match a plain time or time range.
2789 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2790 groups carry important information:
2791 0 the full match
2792 1 the first time, range or not
2793 8 the second time, if it is a range.")
2794
2795 (defconst org-plain-time-extension-regexp
2796 (concat
2797 "\\(\\<[012]?[0-9]"
2798 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2799 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2800 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2801 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2802 groups carry important information:
2803 0 the full match
2804 7 hours of duration
2805 9 minutes of duration")
2806
2807 (defconst org-stamp-time-of-day-regexp
2808 (concat
2809 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2810 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2811 "\\(--?"
2812 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2813 "Regular expression to match a timestamp time or time range.
2814 After a match, the following groups carry important information:
2815 0 the full match
2816 1 date plus weekday, for backreferencing to make sure both times on same day
2817 2 the first time, range or not
2818 4 the second time, if it is a range.")
2819
2820 (defconst org-startup-options
2821 '(("fold" org-startup-folded t)
2822 ("overview" org-startup-folded t)
2823 ("nofold" org-startup-folded nil)
2824 ("showall" org-startup-folded nil)
2825 ("content" org-startup-folded content)
2826 ("hidestars" org-hide-leading-stars t)
2827 ("showstars" org-hide-leading-stars nil)
2828 ("odd" org-odd-levels-only t)
2829 ("oddeven" org-odd-levels-only nil)
2830 ("align" org-startup-align-all-tables t)
2831 ("noalign" org-startup-align-all-tables nil)
2832 ("customtime" org-display-custom-times t)
2833 ("logdone" org-log-done time)
2834 ("lognotedone" org-log-done note)
2835 ("nologdone" org-log-done nil)
2836 ("lognoteclock-out" org-log-note-clock-out t)
2837 ("nolognoteclock-out" org-log-note-clock-out nil)
2838 ("logrepeat" org-log-repeat state)
2839 ("lognoterepeat" org-log-repeat note)
2840 ("nologrepeat" org-log-repeat nil)
2841 ("constcgs" constants-unit-system cgs)
2842 ("constSI" constants-unit-system SI))
2843 "Variable associated with STARTUP options for org-mode.
2844 Each element is a list of three items: The startup options as written
2845 in the #+STARTUP line, the corresponding variable, and the value to
2846 set this variable to if the option is found. An optional forth element PUSH
2847 means to push this value onto the list in the variable.")
2848
2849 (defun org-set-regexps-and-options ()
2850 "Precompute regular expressions for current buffer."
2851 (when (org-mode-p)
2852 (org-set-local 'org-todo-kwd-alist nil)
2853 (org-set-local 'org-todo-key-alist nil)
2854 (org-set-local 'org-todo-key-trigger nil)
2855 (org-set-local 'org-todo-keywords-1 nil)
2856 (org-set-local 'org-done-keywords nil)
2857 (org-set-local 'org-todo-heads nil)
2858 (org-set-local 'org-todo-sets nil)
2859 (org-set-local 'org-todo-log-states nil)
2860 (org-set-local 'org-file-properties nil)
2861 (org-set-local 'org-file-tags nil)
2862 (let ((re (org-make-options-regexp
2863 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2864 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2865 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2866 (splitre "[ \t]+")
2867 kwds kws0 kwsa key log value cat arch tags const links hw dws
2868 tail sep kws1 prio props ftags drawers
2869 ext-setup-or-nil setup-contents (start 0))
2870 (save-excursion
2871 (save-restriction
2872 (widen)
2873 (goto-char (point-min))
2874 (while (or (and ext-setup-or-nil
2875 (string-match re ext-setup-or-nil start)
2876 (setq start (match-end 0)))
2877 (and (setq ext-setup-or-nil nil start 0)
2878 (re-search-forward re nil t)))
2879 (setq key (upcase (match-string 1 ext-setup-or-nil))
2880 value (org-match-string-no-properties 2 ext-setup-or-nil))
2881 (cond
2882 ((equal key "CATEGORY")
2883 (if (string-match "[ \t]+$" value)
2884 (setq value (replace-match "" t t value)))
2885 (setq cat value))
2886 ((member key '("SEQ_TODO" "TODO"))
2887 (push (cons 'sequence (org-split-string value splitre)) kwds))
2888 ((equal key "TYP_TODO")
2889 (push (cons 'type (org-split-string value splitre)) kwds))
2890 ((equal key "TAGS")
2891 (setq tags (append tags (org-split-string value splitre))))
2892 ((equal key "COLUMNS")
2893 (org-set-local 'org-columns-default-format value))
2894 ((equal key "LINK")
2895 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2896 (push (cons (match-string 1 value)
2897 (org-trim (match-string 2 value)))
2898 links)))
2899 ((equal key "PRIORITIES")
2900 (setq prio (org-split-string value " +")))
2901 ((equal key "PROPERTY")
2902 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2903 (push (cons (match-string 1 value) (match-string 2 value))
2904 props)))
2905 ((equal key "FILETAGS")
2906 (when (string-match "\\S-" value)
2907 (setq ftags
2908 (append
2909 ftags
2910 (apply 'append
2911 (mapcar (lambda (x) (org-split-string x ":"))
2912 (org-split-string value)))))))
2913 ((equal key "DRAWERS")
2914 (setq drawers (org-split-string value splitre)))
2915 ((equal key "CONSTANTS")
2916 (setq const (append const (org-split-string value splitre))))
2917 ((equal key "STARTUP")
2918 (let ((opts (org-split-string value splitre))
2919 l var val)
2920 (while (setq l (pop opts))
2921 (when (setq l (assoc l org-startup-options))
2922 (setq var (nth 1 l) val (nth 2 l))
2923 (if (not (nth 3 l))
2924 (set (make-local-variable var) val)
2925 (if (not (listp (symbol-value var)))
2926 (set (make-local-variable var) nil))
2927 (set (make-local-variable var) (symbol-value var))
2928 (add-to-list var val))))))
2929 ((equal key "ARCHIVE")
2930 (string-match " *$" value)
2931 (setq arch (replace-match "" t t value))
2932 (remove-text-properties 0 (length arch)
2933 '(face t fontified t) arch))
2934 ((equal key "SETUPFILE")
2935 (setq setup-contents (org-file-contents
2936 (expand-file-name
2937 (org-remove-double-quotes value))
2938 'noerror))
2939 (if (not ext-setup-or-nil)
2940 (setq ext-setup-or-nil setup-contents start 0)
2941 (setq ext-setup-or-nil
2942 (concat (substring ext-setup-or-nil 0 start)
2943 "\n" setup-contents "\n"
2944 (substring ext-setup-or-nil start)))))
2945 ))))
2946 (when cat
2947 (org-set-local 'org-category (intern cat))
2948 (push (cons "CATEGORY" cat) props))
2949 (when prio
2950 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2951 (setq prio (mapcar 'string-to-char prio))
2952 (org-set-local 'org-highest-priority (nth 0 prio))
2953 (org-set-local 'org-lowest-priority (nth 1 prio))
2954 (org-set-local 'org-default-priority (nth 2 prio)))
2955 (and props (org-set-local 'org-file-properties (nreverse props)))
2956 (and ftags (org-set-local 'org-file-tags ftags))
2957 (and drawers (org-set-local 'org-drawers drawers))
2958 (and arch (org-set-local 'org-archive-location arch))
2959 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2960 ;; Process the TODO keywords
2961 (unless kwds
2962 ;; Use the global values as if they had been given locally.
2963 (setq kwds (default-value 'org-todo-keywords))
2964 (if (stringp (car kwds))
2965 (setq kwds (list (cons org-todo-interpretation
2966 (default-value 'org-todo-keywords)))))
2967 (setq kwds (reverse kwds)))
2968 (setq kwds (nreverse kwds))
2969 (let (inter kws kw)
2970 (while (setq kws (pop kwds))
2971 (setq inter (pop kws) sep (member "|" kws)
2972 kws0 (delete "|" (copy-sequence kws))
2973 kwsa nil
2974 kws1 (mapcar
2975 (lambda (x)
2976 ;; 1 2
2977 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2978 (progn
2979 (setq kw (match-string 1 x)
2980 key (and (match-end 2) (match-string 2 x))
2981 log (org-extract-log-state-settings x))
2982 (push (cons kw (and key (string-to-char key))) kwsa)
2983 (and log (push log org-todo-log-states))
2984 kw)
2985 (error "Invalid TODO keyword %s" x)))
2986 kws0)
2987 kwsa (if kwsa (append '((:startgroup))
2988 (nreverse kwsa)
2989 '((:endgroup))))
2990 hw (car kws1)
2991 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2992 tail (list inter hw (car dws) (org-last dws)))
2993 (add-to-list 'org-todo-heads hw 'append)
2994 (push kws1 org-todo-sets)
2995 (setq org-done-keywords (append org-done-keywords dws nil))
2996 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2997 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2998 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2999 (setq org-todo-sets (nreverse org-todo-sets)
3000 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3001 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3002 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3003 ;; Process the constants
3004 (when const
3005 (let (e cst)
3006 (while (setq e (pop const))
3007 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3008 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3009 (setq org-table-formula-constants-local cst)))
3010
3011 ;; Process the tags.
3012 (when tags
3013 (let (e tgs)
3014 (while (setq e (pop tags))
3015 (cond
3016 ((equal e "{") (push '(:startgroup) tgs))
3017 ((equal e "}") (push '(:endgroup) tgs))
3018 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3019 (push (cons (match-string 1 e)
3020 (string-to-char (match-string 2 e)))
3021 tgs))
3022 (t (push (list e) tgs))))
3023 (org-set-local 'org-tag-alist nil)
3024 (while (setq e (pop tgs))
3025 (or (and (stringp (car e))
3026 (assoc (car e) org-tag-alist))
3027 (push e org-tag-alist)))))
3028
3029 ;; Compute the regular expressions and other local variables
3030 (if (not org-done-keywords)
3031 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3032 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3033 (length org-scheduled-string)
3034 (length org-clock-string)
3035 (length org-closed-string)))
3036 org-drawer-regexp
3037 (concat "^[ \t]*:\\("
3038 (mapconcat 'regexp-quote org-drawers "\\|")
3039 "\\):[ \t]*$")
3040 org-not-done-keywords
3041 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3042 org-todo-regexp
3043 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3044 "\\|") "\\)\\>")
3045 org-not-done-regexp
3046 (concat "\\<\\("
3047 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3048 "\\)\\>")
3049 org-todo-line-regexp
3050 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3051 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3052 "\\)\\>\\)?[ \t]*\\(.*\\)")
3053 org-complex-heading-regexp
3054 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3055 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3056 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3057 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3058 org-nl-done-regexp
3059 (concat "\n\\*+[ \t]+"
3060 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3061 "\\)" "\\>")
3062 org-todo-line-tags-regexp
3063 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3064 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3065 (org-re
3066 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3067 org-looking-at-done-regexp
3068 (concat "^" "\\(?:"
3069 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3070 "\\>")
3071 org-deadline-regexp (concat "\\<" org-deadline-string)
3072 org-deadline-time-regexp
3073 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3074 org-deadline-line-regexp
3075 (concat "\\<\\(" org-deadline-string "\\).*")
3076 org-scheduled-regexp
3077 (concat "\\<" org-scheduled-string)
3078 org-scheduled-time-regexp
3079 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3080 org-closed-time-regexp
3081 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3082 org-keyword-time-regexp
3083 (concat "\\<\\(" org-scheduled-string
3084 "\\|" org-deadline-string
3085 "\\|" org-closed-string
3086 "\\|" org-clock-string "\\)"
3087 " *[[<]\\([^]>]+\\)[]>]")
3088 org-keyword-time-not-clock-regexp
3089 (concat "\\<\\(" org-scheduled-string
3090 "\\|" org-deadline-string
3091 "\\|" org-closed-string
3092 "\\)"
3093 " *[[<]\\([^]>]+\\)[]>]")
3094 org-maybe-keyword-time-regexp
3095 (concat "\\(\\<\\(" org-scheduled-string
3096 "\\|" org-deadline-string
3097 "\\|" org-closed-string
3098 "\\|" org-clock-string "\\)\\)?"
3099 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3100 org-planning-or-clock-line-re
3101 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3102 "\\|" org-deadline-string
3103 "\\|" org-closed-string "\\|" org-clock-string
3104 "\\)\\>\\)")
3105 )
3106 (org-compute-latex-and-specials-regexp)
3107 (org-set-font-lock-defaults))))
3108
3109 (defun org-file-contents (file &optional noerror)
3110 "Return the contents of FILE, as a string."
3111 (if (or (not file)
3112 (not (file-readable-p file)))
3113 (if noerror
3114 (progn
3115 (message "Cannot read file %s" file)
3116 (ding) (sit-for 2)
3117 "")
3118 (error "Cannot read file %s" file))
3119 (with-temp-buffer
3120 (insert-file-contents file)
3121 (buffer-string))))
3122
3123 (defun org-extract-log-state-settings (x)
3124 "Extract the log state setting from a TODO keyword string.
3125 This will extract info from a string like \"WAIT(w@/!)\"."
3126 (let (kw key log1 log2)
3127 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3128 (setq kw (match-string 1 x)
3129 key (and (match-end 2) (match-string 2 x))
3130 log1 (and (match-end 3) (match-string 3 x))
3131 log2 (and (match-end 4) (match-string 4 x)))
3132 (and (or log1 log2)
3133 (list kw
3134 (and log1 (if (equal log1 "!") 'time 'note))
3135 (and log2 (if (equal log2 "!") 'time 'note)))))))
3136
3137 (defun org-remove-keyword-keys (list)
3138 "Remove a pair of parenthesis at the end of each string in LIST."
3139 (mapcar (lambda (x)
3140 (if (string-match "(.*)$" x)
3141 (substring x 0 (match-beginning 0))
3142 x))
3143 list))
3144
3145 ;; FIXME: this could be done much better, using second characters etc.
3146 (defun org-assign-fast-keys (alist)
3147 "Assign fast keys to a keyword-key alist.
3148 Respect keys that are already there."
3149 (let (new e k c c1 c2 (char ?a))
3150 (while (setq e (pop alist))
3151 (cond
3152 ((equal e '(:startgroup)) (push e new))
3153 ((equal e '(:endgroup)) (push e new))
3154 (t
3155 (setq k (car e) c2 nil)
3156 (if (cdr e)
3157 (setq c (cdr e))
3158 ;; automatically assign a character.
3159 (setq c1 (string-to-char
3160 (downcase (substring
3161 k (if (= (string-to-char k) ?@) 1 0)))))
3162 (if (or (rassoc c1 new) (rassoc c1 alist))
3163 (while (or (rassoc char new) (rassoc char alist))
3164 (setq char (1+ char)))
3165 (setq c2 c1))
3166 (setq c (or c2 char)))
3167 (push (cons k c) new))))
3168 (nreverse new)))
3169
3170 ;;; Some variables used in various places
3171
3172 (defvar org-window-configuration nil
3173 "Used in various places to store a window configuration.")
3174 (defvar org-finish-function nil
3175 "Function to be called when `C-c C-c' is used.
3176 This is for getting out of special buffers like remember.")
3177
3178
3179 ;; FIXME: Occasionally check by commenting these, to make sure
3180 ;; no other functions uses these, forgetting to let-bind them.
3181 (defvar entry)
3182 (defvar state)
3183 (defvar last-state)
3184 (defvar date)
3185 (defvar description)
3186
3187 ;; Defined somewhere in this file, but used before definition.
3188 (defvar org-html-entities)
3189 (defvar org-struct-menu)
3190 (defvar org-org-menu)
3191 (defvar org-tbl-menu)
3192 (defvar org-agenda-keymap)
3193
3194 ;;;; Define the Org-mode
3195
3196 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3197 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or ugrade to newer allout, for example by switching to Emacs 22."))
3198
3199
3200 ;; We use a before-change function to check if a table might need
3201 ;; an update.
3202 (defvar org-table-may-need-update t
3203 "Indicates that a table might need an update.
3204 This variable is set by `org-before-change-function'.
3205 `org-table-align' sets it back to nil.")
3206 (defun org-before-change-function (beg end)
3207 "Every change indicates that a table might need an update."
3208 (setq org-table-may-need-update t))
3209 (defvar org-mode-map)
3210 (defvar org-mode-hook nil)
3211 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3212 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3213 (defvar org-table-buffer-is-an nil)
3214 (defconst org-outline-regexp "\\*+ ")
3215
3216 ;;;###autoload
3217 (define-derived-mode org-mode outline-mode "Org"
3218 "Outline-based notes management and organizer, alias
3219 \"Carsten's outline-mode for keeping track of everything.\"
3220
3221 Org-mode develops organizational tasks around a NOTES file which
3222 contains information about projects as plain text. Org-mode is
3223 implemented on top of outline-mode, which is ideal to keep the content
3224 of large files well structured. It supports ToDo items, deadlines and
3225 time stamps, which magically appear in the diary listing of the Emacs
3226 calendar. Tables are easily created with a built-in table editor.
3227 Plain text URL-like links connect to websites, emails (VM), Usenet
3228 messages (Gnus), BBDB entries, and any files related to the project.
3229 For printing and sharing of notes, an Org-mode file (or a part of it)
3230 can be exported as a structured ASCII or HTML file.
3231
3232 The following commands are available:
3233
3234 \\{org-mode-map}"
3235
3236 ;; Get rid of Outline menus, they are not needed
3237 ;; Need to do this here because define-derived-mode sets up
3238 ;; the keymap so late. Still, it is a waste to call this each time
3239 ;; we switch another buffer into org-mode.
3240 (if (featurep 'xemacs)
3241 (when (boundp 'outline-mode-menu-heading)
3242 ;; Assume this is Greg's port, it used easymenu
3243 (easy-menu-remove outline-mode-menu-heading)
3244 (easy-menu-remove outline-mode-menu-show)
3245 (easy-menu-remove outline-mode-menu-hide))
3246 (define-key org-mode-map [menu-bar headings] 'undefined)
3247 (define-key org-mode-map [menu-bar hide] 'undefined)
3248 (define-key org-mode-map [menu-bar show] 'undefined))
3249
3250 (org-load-modules-maybe)
3251 (easy-menu-add org-org-menu)
3252 (easy-menu-add org-tbl-menu)
3253 (org-install-agenda-files-menu)
3254 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3255 (org-add-to-invisibility-spec '(org-cwidth))
3256 (when (featurep 'xemacs)
3257 (org-set-local 'line-move-ignore-invisible t))
3258 (org-set-local 'outline-regexp org-outline-regexp)
3259 (org-set-local 'outline-level 'org-outline-level)
3260 (when (and org-ellipsis
3261 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3262 (fboundp 'make-glyph-code))
3263 (unless org-display-table
3264 (setq org-display-table (make-display-table)))
3265 (set-display-table-slot
3266 org-display-table 4
3267 (vconcat (mapcar
3268 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3269 org-ellipsis)))
3270 (if (stringp org-ellipsis) org-ellipsis "..."))))
3271 (setq buffer-display-table org-display-table))
3272 (org-set-regexps-and-options)
3273 ;; Calc embedded
3274 (org-set-local 'calc-embedded-open-mode "# ")
3275 (modify-syntax-entry ?# "<")
3276 (modify-syntax-entry ?@ "w")
3277 (if org-startup-truncated (setq truncate-lines t))
3278 (org-set-local 'font-lock-unfontify-region-function
3279 'org-unfontify-region)
3280 ;; Activate before-change-function
3281 (org-set-local 'org-table-may-need-update t)
3282 (org-add-hook 'before-change-functions 'org-before-change-function nil
3283 'local)
3284 ;; Check for running clock before killing a buffer
3285 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3286 ;; Paragraphs and auto-filling
3287 (org-set-autofill-regexps)
3288 (setq indent-line-function 'org-indent-line-function)
3289 (org-update-radio-target-regexp)
3290
3291 ;; Comment characters
3292 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3293 (org-set-local 'comment-padding " ")
3294
3295 ;; Align options lines
3296 (org-set-local
3297 'align-mode-rules-list
3298 '((org-in-buffer-settings
3299 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3300 (modes . '(org-mode)))))
3301
3302 ;; Imenu
3303 (org-set-local 'imenu-create-index-function
3304 'org-imenu-get-tree)
3305
3306 ;; Make isearch reveal context
3307 (if (or (featurep 'xemacs)
3308 (not (boundp 'outline-isearch-open-invisible-function)))
3309 ;; Emacs 21 and XEmacs make use of the hook
3310 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3311 ;; Emacs 22 deals with this through a special variable
3312 (org-set-local 'outline-isearch-open-invisible-function
3313 (lambda (&rest ignore) (org-show-context 'isearch))))
3314
3315 ;; If empty file that did not turn on org-mode automatically, make it to.
3316 (if (and org-insert-mode-line-in-empty-file
3317 (interactive-p)
3318 (= (point-min) (point-max)))
3319 (insert "# -*- mode: org -*-\n\n"))
3320
3321 (unless org-inhibit-startup
3322 (when org-startup-align-all-tables
3323 (let ((bmp (buffer-modified-p)))
3324 (org-table-map-tables 'org-table-align)
3325 (set-buffer-modified-p bmp)))
3326 (org-set-startup-visibility)))
3327
3328 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3329
3330 (defun org-current-time ()
3331 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3332 (if (> (car org-time-stamp-rounding-minutes) 1)
3333 (let ((r (car org-time-stamp-rounding-minutes))
3334 (time (decode-time)))
3335 (apply 'encode-time
3336 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3337 (nthcdr 2 time))))
3338 (current-time)))
3339
3340 ;;;; Font-Lock stuff, including the activators
3341
3342 (defvar org-mouse-map (make-sparse-keymap))
3343 (org-defkey org-mouse-map
3344 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3345 (org-defkey org-mouse-map
3346 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3347 (when org-mouse-1-follows-link
3348 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3349 (when org-tab-follows-link
3350 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3351 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3352 (when org-return-follows-link
3353 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3354 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3355
3356 (require 'font-lock)
3357
3358 (defconst org-non-link-chars "]\t\n\r<>")
3359 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3360 "shell" "elisp"))
3361 (defvar org-link-types-re nil
3362 "Matches a link that has a url-like prefix like \"http:\"")
3363 (defvar org-link-re-with-space nil
3364 "Matches a link with spaces, optional angular brackets around it.")
3365 (defvar org-link-re-with-space2 nil
3366 "Matches a link with spaces, optional angular brackets around it.")
3367 (defvar org-angle-link-re nil
3368 "Matches link with angular brackets, spaces are allowed.")
3369 (defvar org-plain-link-re nil
3370 "Matches plain link, without spaces.")
3371 (defvar org-bracket-link-regexp nil
3372 "Matches a link in double brackets.")
3373 (defvar org-bracket-link-analytic-regexp nil
3374 "Regular expression used to analyze links.
3375 Here is what the match groups contain after a match:
3376 1: http:
3377 2: http
3378 3: path
3379 4: [desc]
3380 5: desc")
3381 (defvar org-any-link-re nil
3382 "Regular expression matching any link.")
3383
3384 (defun org-make-link-regexps ()
3385 "Update the link regular expressions.
3386 This should be called after the variable `org-link-types' has changed."
3387 (setq org-link-types-re
3388 (concat
3389 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3390 org-link-re-with-space
3391 (concat
3392 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3393 "\\([^" org-non-link-chars " ]"
3394 "[^" org-non-link-chars "]*"
3395 "[^" org-non-link-chars " ]\\)>?")
3396 org-link-re-with-space2
3397 (concat
3398 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3399 "\\([^" org-non-link-chars " ]"
3400 "[^]\t\n\r]*"
3401 "[^" org-non-link-chars " ]\\)>?")
3402 org-angle-link-re
3403 (concat
3404 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3405 "\\([^" org-non-link-chars " ]"
3406 "[^" org-non-link-chars "]*"
3407 "\\)>")
3408 org-plain-link-re
3409 (concat
3410 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3411 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3412 org-bracket-link-regexp
3413 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3414 org-bracket-link-analytic-regexp
3415 (concat
3416 "\\[\\["
3417 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3418 "\\([^]]+\\)"
3419 "\\]"
3420 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3421 "\\]")
3422 org-any-link-re
3423 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3424 org-angle-link-re "\\)\\|\\("
3425 org-plain-link-re "\\)")))
3426
3427 (org-make-link-regexps)
3428
3429 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3430 "Regular expression for fast time stamp matching.")
3431 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3432 "Regular expression for fast time stamp matching.")
3433 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3434 "Regular expression matching time strings for analysis.
3435 This one does not require the space after the date, so it can be used
3436 on a string that terminates immediately after the date.")
3437 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3438 "Regular expression matching time strings for analysis.")
3439 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3440 "Regular expression matching time stamps, with groups.")
3441 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3442 "Regular expression matching time stamps (also [..]), with groups.")
3443 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3444 "Regular expression matching a time stamp range.")
3445 (defconst org-tr-regexp-both
3446 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3447 "Regular expression matching a time stamp range.")
3448 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3449 org-ts-regexp "\\)?")
3450 "Regular expression matching a time stamp or time stamp range.")
3451 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3452 org-ts-regexp-both "\\)?")
3453 "Regular expression matching a time stamp or time stamp range.
3454 The time stamps may be either active or inactive.")
3455
3456 (defvar org-emph-face nil)
3457
3458 (defun org-do-emphasis-faces (limit)
3459 "Run through the buffer and add overlays to links."
3460 (let (rtn)
3461 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3462 (if (not (= (char-after (match-beginning 3))
3463 (char-after (match-beginning 4))))
3464 (progn
3465 (setq rtn t)
3466 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3467 'face
3468 (nth 1 (assoc (match-string 3)
3469 org-emphasis-alist)))
3470 (add-text-properties (match-beginning 2) (match-end 2)
3471 '(font-lock-multiline t))
3472 (when org-hide-emphasis-markers
3473 (add-text-properties (match-end 4) (match-beginning 5)
3474 '(invisible org-link))
3475 (add-text-properties (match-beginning 3) (match-end 3)
3476 '(invisible org-link)))))
3477 (backward-char 1))
3478 rtn))
3479
3480 (defun org-emphasize (&optional char)
3481 "Insert or change an emphasis, i.e. a font like bold or italic.
3482 If there is an active region, change that region to a new emphasis.
3483 If there is no region, just insert the marker characters and position
3484 the cursor between them.
3485 CHAR should be either the marker character, or the first character of the
3486 HTML tag associated with that emphasis. If CHAR is a space, the means
3487 to remove the emphasis of the selected region.
3488 If char is not given (for example in an interactive call) it
3489 will be prompted for."
3490 (interactive)
3491 (let ((eal org-emphasis-alist) e det
3492 (erc org-emphasis-regexp-components)
3493 (prompt "")
3494 (string "") beg end move tag c s)
3495 (if (org-region-active-p)
3496 (setq beg (region-beginning) end (region-end)
3497 string (buffer-substring beg end))
3498 (setq move t))
3499
3500 (while (setq e (pop eal))
3501 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3502 c (aref tag 0))
3503 (push (cons c (string-to-char (car e))) det)
3504 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3505 (substring tag 1)))))
3506 (unless char
3507 (message "%s" (concat "Emphasis marker or tag:" prompt))
3508 (setq char (read-char-exclusive)))
3509 (setq char (or (cdr (assoc char det)) char))
3510 (if (equal char ?\ )
3511 (setq s "" move nil)
3512 (unless (assoc (char-to-string char) org-emphasis-alist)
3513 (error "No such emphasis marker: \"%c\"" char))
3514 (setq s (char-to-string char)))
3515 (while (and (> (length string) 1)
3516 (equal (substring string 0 1) (substring string -1))
3517 (assoc (substring string 0 1) org-emphasis-alist))
3518 (setq string (substring string 1 -1)))
3519 (setq string (concat s string s))
3520 (if beg (delete-region beg end))
3521 (unless (or (bolp)
3522 (string-match (concat "[" (nth 0 erc) "\n]")
3523 (char-to-string (char-before (point)))))
3524 (insert " "))
3525 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3526 (char-to-string (char-after (point))))
3527 (insert " ") (backward-char 1))
3528 (insert string)
3529 (and move (backward-char 1))))
3530
3531 (defconst org-nonsticky-props
3532 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3533
3534
3535 (defun org-activate-plain-links (limit)
3536 "Run through the buffer and add overlays to links."
3537 (catch 'exit
3538 (let (f)
3539 (while (re-search-forward org-plain-link-re limit t)
3540 (setq f (get-text-property (match-beginning 0) 'face))
3541 (if (or (eq f 'org-tag)
3542 (and (listp f) (memq 'org-tag f)))
3543 nil
3544 (add-text-properties (match-beginning 0) (match-end 0)
3545 (list 'mouse-face 'highlight
3546 'rear-nonsticky org-nonsticky-props
3547 'keymap org-mouse-map
3548 ))
3549 (throw 'exit t))))))
3550
3551 (defun org-activate-code (limit)
3552 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3553 (progn
3554 (remove-text-properties (match-beginning 0) (match-end 0)
3555 '(display t invisible t intangible t))
3556 t)))
3557
3558 (defun org-activate-angle-links (limit)
3559 "Run through the buffer and add overlays to links."
3560 (if (re-search-forward org-angle-link-re limit t)
3561 (progn
3562 (add-text-properties (match-beginning 0) (match-end 0)
3563 (list 'mouse-face 'highlight
3564 'rear-nonsticky org-nonsticky-props
3565 'keymap org-mouse-map
3566 ))
3567 t)))
3568
3569 (defun org-activate-bracket-links (limit)
3570 "Run through the buffer and add overlays to bracketed links."
3571 (if (re-search-forward org-bracket-link-regexp limit t)
3572 (let* ((help (concat "LINK: "
3573 (org-match-string-no-properties 1)))
3574 ;; FIXME: above we should remove the escapes.
3575 ;; but that requires another match, protecting match data,
3576 ;; a lot of overhead for font-lock.
3577 (ip (org-maybe-intangible
3578 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3579 'keymap org-mouse-map 'mouse-face 'highlight
3580 'font-lock-multiline t 'help-echo help)))
3581 (vp (list 'rear-nonsticky org-nonsticky-props
3582 'keymap org-mouse-map 'mouse-face 'highlight
3583 ' font-lock-multiline t 'help-echo help)))
3584 ;; We need to remove the invisible property here. Table narrowing
3585 ;; may have made some of this invisible.
3586 (remove-text-properties (match-beginning 0) (match-end 0)
3587 '(invisible nil))
3588 (if (match-end 3)
3589 (progn
3590 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3591 (add-text-properties (match-beginning 3) (match-end 3) vp)
3592 (add-text-properties (match-end 3) (match-end 0) ip))
3593 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3594 (add-text-properties (match-beginning 1) (match-end 1) vp)
3595 (add-text-properties (match-end 1) (match-end 0) ip))
3596 t)))
3597
3598 (defun org-activate-dates (limit)
3599 "Run through the buffer and add overlays to dates."
3600 (if (re-search-forward org-tsr-regexp-both limit t)
3601 (progn
3602 (add-text-properties (match-beginning 0) (match-end 0)
3603 (list 'mouse-face 'highlight
3604 'rear-nonsticky org-nonsticky-props
3605 'keymap org-mouse-map))
3606 (when org-display-custom-times
3607 (if (match-end 3)
3608 (org-display-custom-time (match-beginning 3) (match-end 3)))
3609 (org-display-custom-time (match-beginning 1) (match-end 1)))
3610 t)))
3611
3612 (defvar org-target-link-regexp nil
3613 "Regular expression matching radio targets in plain text.")
3614 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3615 "Regular expression matching a link target.")
3616 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3617 "Regular expression matching a radio target.")
3618 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3619 "Regular expression matching any target.")
3620
3621 (defun org-activate-target-links (limit)
3622 "Run through the buffer and add overlays to target matches."
3623 (when org-target-link-regexp
3624 (let ((case-fold-search t))
3625 (if (re-search-forward org-target-link-regexp limit t)
3626 (progn
3627 (add-text-properties (match-beginning 0) (match-end 0)
3628 (list 'mouse-face 'highlight
3629 'rear-nonsticky org-nonsticky-props
3630 'keymap org-mouse-map
3631 'help-echo "Radio target link"
3632 'org-linked-text t))
3633 t)))))
3634
3635 (defun org-update-radio-target-regexp ()
3636 "Find all radio targets in this file and update the regular expression."
3637 (interactive)
3638 (when (memq 'radio org-activate-links)
3639 (setq org-target-link-regexp
3640 (org-make-target-link-regexp (org-all-targets 'radio)))
3641 (org-restart-font-lock)))
3642
3643 (defun org-hide-wide-columns (limit)
3644 (let (s e)
3645 (setq s (text-property-any (point) (or limit (point-max))
3646 'org-cwidth t))
3647 (when s
3648 (setq e (next-single-property-change s 'org-cwidth))
3649 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3650 (goto-char e)
3651 t)))
3652
3653 (defvar org-latex-and-specials-regexp nil
3654 "Regular expression for highlighting export special stuff.")
3655 (defvar org-match-substring-regexp)
3656 (defvar org-match-substring-with-braces-regexp)
3657 (defvar org-export-html-special-string-regexps)
3658
3659 (defun org-compute-latex-and-specials-regexp ()
3660 "Compute regular expression for stuff treated specially by exporters."
3661 (if (not org-highlight-latex-fragments-and-specials)
3662 (org-set-local 'org-latex-and-specials-regexp nil)
3663 (require 'org-exp)
3664 (let*
3665 ((matchers (plist-get org-format-latex-options :matchers))
3666 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3667 org-latex-regexps)))
3668 (options (org-combine-plists (org-default-export-plist)
3669 (org-infile-export-plist)))
3670 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3671 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3672 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3673 (org-export-html-expand (plist-get options :expand-quoted-html))
3674 (org-export-with-special-strings (plist-get options :special-strings))
3675 (re-sub
3676 (cond
3677 ((equal org-export-with-sub-superscripts '{})
3678 (list org-match-substring-with-braces-regexp))
3679 (org-export-with-sub-superscripts
3680 (list org-match-substring-regexp))
3681 (t nil)))
3682 (re-latex
3683 (if org-export-with-LaTeX-fragments
3684 (mapcar (lambda (x) (nth 1 x)) latexs)))
3685 (re-macros
3686 (if org-export-with-TeX-macros
3687 (list (concat "\\\\"
3688 (regexp-opt
3689 (append (mapcar 'car org-html-entities)
3690 (if (boundp 'org-latex-entities)
3691 org-latex-entities nil))
3692 'words))) ; FIXME
3693 ))
3694 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3695 (re-special (if org-export-with-special-strings
3696 (mapcar (lambda (x) (car x))
3697 org-export-html-special-string-regexps)))
3698 (re-rest
3699 (delq nil
3700 (list
3701 (if org-export-html-expand "@<[^>\n]+>")
3702 ))))
3703 (org-set-local
3704 'org-latex-and-specials-regexp
3705 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3706 re-rest) "\\|")))))
3707
3708 (defun org-do-latex-and-special-faces (limit)
3709 "Run through the buffer and add overlays to links."
3710 (when org-latex-and-specials-regexp
3711 (let (rtn d)
3712 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3713 limit t))
3714 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3715 'face))
3716 '(org-code org-verbatim underline)))
3717 (progn
3718 (setq rtn t
3719 d (cond ((member (char-after (1+ (match-beginning 0)))
3720 '(?_ ?^)) 1)
3721 (t 0)))
3722 (font-lock-prepend-text-property
3723 (+ d (match-beginning 0)) (match-end 0)
3724 'face 'org-latex-and-export-specials)
3725 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3726 '(font-lock-multiline t)))))
3727 rtn)))
3728
3729 (defun org-restart-font-lock ()
3730 "Restart font-lock-mode, to force refontification."
3731 (when (and (boundp 'font-lock-mode) font-lock-mode)
3732 (font-lock-mode -1)
3733 (font-lock-mode 1)))
3734
3735 (defun org-all-targets (&optional radio)
3736 "Return a list of all targets in this file.
3737 With optional argument RADIO, only find radio targets."
3738 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3739 rtn)
3740 (save-excursion
3741 (goto-char (point-min))
3742 (while (re-search-forward re nil t)
3743 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3744 rtn)))
3745
3746 (defun org-make-target-link-regexp (targets)
3747 "Make regular expression matching all strings in TARGETS.
3748 The regular expression finds the targets also if there is a line break
3749 between words."
3750 (and targets
3751 (concat
3752 "\\<\\("
3753 (mapconcat
3754 (lambda (x)
3755 (while (string-match " +" x)
3756 (setq x (replace-match "\\s-+" t t x)))
3757 x)
3758 targets
3759 "\\|")
3760 "\\)\\>")))
3761
3762 (defun org-activate-tags (limit)
3763 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3764 (progn
3765 (add-text-properties (match-beginning 1) (match-end 1)
3766 (list 'mouse-face 'highlight
3767 'rear-nonsticky org-nonsticky-props
3768 'keymap org-mouse-map))
3769 t)))
3770
3771 (defun org-outline-level ()
3772 (save-excursion
3773 (looking-at outline-regexp)
3774 (if (match-beginning 1)
3775 (+ (org-get-string-indentation (match-string 1)) 1000)
3776 (1- (- (match-end 0) (match-beginning 0))))))
3777
3778 (defvar org-font-lock-keywords nil)
3779
3780 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3781 "Regular expression matching a property line.")
3782
3783 (defvar org-font-lock-hook nil
3784 "Functions to be called for special font lock stuff.")
3785
3786 (defun org-font-lock-hook (limit)
3787 (run-hook-with-args 'org-font-lock-hook limit))
3788
3789 (defun org-set-font-lock-defaults ()
3790 (let* ((em org-fontify-emphasized-text)
3791 (lk org-activate-links)
3792 (org-font-lock-extra-keywords
3793 (list
3794 ;; Call the hook
3795 '(org-font-lock-hook)
3796 ;; Headlines
3797 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3798 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3799 ;; Table lines
3800 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3801 (1 'org-table t))
3802 ;; Table internals
3803 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3804 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3805 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3806 ;; Drawers
3807 (list org-drawer-regexp '(0 'org-special-keyword t))
3808 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3809 ;; Properties
3810 (list org-property-re
3811 '(1 'org-special-keyword t)
3812 '(3 'org-property-value t))
3813 (if org-format-transports-properties-p
3814 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3815 ;; Links
3816 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3817 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3818 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3819 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3820 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3821 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3822 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3823 '(org-hide-wide-columns (0 nil append))
3824 ;; TODO lines
3825 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3826 '(1 (org-get-todo-face 1) t))
3827 ;; DONE
3828 (if org-fontify-done-headline
3829 (list (concat "^[*]+ +\\<\\("
3830 (mapconcat 'regexp-quote org-done-keywords "\\|")
3831 "\\)\\(.*\\)")
3832 '(2 'org-headline-done t))
3833 nil)
3834 ;; Priorities
3835 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3836 ;; Special keywords
3837 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3838 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3839 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3840 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3841 ;; Emphasis
3842 (if em
3843 (if (featurep 'xemacs)
3844 '(org-do-emphasis-faces (0 nil append))
3845 '(org-do-emphasis-faces)))
3846 ;; Checkboxes
3847 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3848 2 'bold prepend)
3849 (if org-provide-checkbox-statistics
3850 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3851 (0 (org-get-checkbox-statistics-face) t)))
3852 ;; Description list items
3853 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3854 2 'bold prepend)
3855 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3856 '(1 'org-archived prepend))
3857 ;; Specials
3858 '(org-do-latex-and-special-faces)
3859 ;; Code
3860 '(org-activate-code (1 'org-code t))
3861 ;; COMMENT
3862 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3863 "\\|" org-quote-string "\\)\\>")
3864 '(1 'org-special-keyword t))
3865 '("^#.*" (0 'font-lock-comment-face t))
3866 )))
3867 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3868 ;; Now set the full font-lock-keywords
3869 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3870 (org-set-local 'font-lock-defaults
3871 '(org-font-lock-keywords t nil nil backward-paragraph))
3872 (kill-local-variable 'font-lock-keywords) nil))
3873
3874 (defvar org-m nil)
3875 (defvar org-l nil)
3876 (defvar org-f nil)
3877 (defun org-get-level-face (n)
3878 "Get the right face for match N in font-lock matching of healdines."
3879 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3880 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3881 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3882 (cond
3883 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3884 ((eq n 2) org-f)
3885 (t (if org-level-color-stars-only nil org-f))))
3886
3887 (defun org-get-todo-face (kwd)
3888 "Get the right face for a TODO keyword KWD.
3889 If KWD is a number, get the corresponding match group."
3890 (if (numberp kwd) (setq kwd (match-string kwd)))
3891 (or (cdr (assoc kwd org-todo-keyword-faces))
3892 (and (member kwd org-done-keywords) 'org-done)
3893 'org-todo))
3894
3895 (defun org-unfontify-region (beg end &optional maybe_loudly)
3896 "Remove fontification and activation overlays from links."
3897 (font-lock-default-unfontify-region beg end)
3898 (let* ((buffer-undo-list t)
3899 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3900 (inhibit-modification-hooks t)
3901 deactivate-mark buffer-file-name buffer-file-truename)
3902 (remove-text-properties beg end
3903 '(mouse-face t keymap t org-linked-text t
3904 invisible t intangible t))))
3905
3906 ;;;; Visibility cycling, including org-goto and indirect buffer
3907
3908 ;;; Cycling
3909
3910 (defvar org-cycle-global-status nil)
3911 (make-variable-buffer-local 'org-cycle-global-status)
3912 (defvar org-cycle-subtree-status nil)
3913 (make-variable-buffer-local 'org-cycle-subtree-status)
3914
3915 ;;;###autoload
3916 (defun org-cycle (&optional arg)
3917 "Visibility cycling for Org-mode.
3918
3919 - When this function is called with a prefix argument, rotate the entire
3920 buffer through 3 states (global cycling)
3921 1. OVERVIEW: Show only top-level headlines.
3922 2. CONTENTS: Show all headlines of all levels, but no body text.
3923 3. SHOW ALL: Show everything.
3924 When called with two C-u C-u prefixes, switch to the startup visibility,
3925 determined by the variable `org-startup-folded', and by any VISIBILITY
3926 properties in the buffer.
3927 When called with three C-u C-u C-u prefixed, show the entire buffer,
3928 including drawers.
3929
3930 - When point is at the beginning of a headline, rotate the subtree started
3931 by this line through 3 different states (local cycling)
3932 1. FOLDED: Only the main headline is shown.
3933 2. CHILDREN: The main headline and the direct children are shown.
3934 From this state, you can move to one of the children
3935 and zoom in further.
3936 3. SUBTREE: Show the entire subtree, including body text.
3937
3938 - When there is a numeric prefix, go up to a heading with level ARG, do
3939 a `show-subtree' and return to the previous cursor position. If ARG
3940 is negative, go up that many levels.
3941
3942 - When point is not at the beginning of a headline, execute the global
3943 binding for TAB, which is re-indenting the line. See the option
3944 `org-cycle-emulate-tab' for details.
3945
3946 - Special case: if point is at the beginning of the buffer and there is
3947 no headline in line 1, this function will act as if called with prefix arg.
3948 But only if also the variable `org-cycle-global-at-bob' is t."
3949 (interactive "P")
3950 (org-load-modules-maybe)
3951 (let* ((outline-regexp
3952 (if (and (org-mode-p) org-cycle-include-plain-lists)
3953 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3954 outline-regexp))
3955 (bob-special (and org-cycle-global-at-bob (bobp)
3956 (not (looking-at outline-regexp))))
3957 (org-cycle-hook
3958 (if bob-special
3959 (delq 'org-optimize-window-after-visibility-change
3960 (copy-sequence org-cycle-hook))
3961 org-cycle-hook))
3962 (pos (point)))
3963
3964 (if (or bob-special (equal arg '(4)))
3965 ;; special case: use global cycling
3966 (setq arg t))
3967
3968 (cond
3969
3970 ((equal arg '(16))
3971 (org-set-startup-visibility)
3972 (message "Startup visibility, plus VISIBILITY properties"))
3973
3974 ((equal arg '(64))
3975 (show-all)
3976 (message "Entire buffer visible, including drawers"))
3977
3978 ((org-at-table-p 'any)
3979 ;; Enter the table or move to the next field in the table
3980 (or (org-table-recognize-table.el)
3981 (progn
3982 (if arg (org-table-edit-field t)
3983 (org-table-justify-field-maybe)
3984 (call-interactively 'org-table-next-field)))))
3985
3986 ((eq arg t) ;; Global cycling
3987
3988 (cond
3989 ((and (eq last-command this-command)
3990 (eq org-cycle-global-status 'overview))
3991 ;; We just created the overview - now do table of contents
3992 ;; This can be slow in very large buffers, so indicate action
3993 (message "CONTENTS...")
3994 (org-content)
3995 (message "CONTENTS...done")
3996 (setq org-cycle-global-status 'contents)
3997 (run-hook-with-args 'org-cycle-hook 'contents))
3998
3999 ((and (eq last-command this-command)
4000 (eq org-cycle-global-status 'contents))
4001 ;; We just showed the table of contents - now show everything
4002 (show-all)
4003 (message "SHOW ALL")
4004 (setq org-cycle-global-status 'all)
4005 (run-hook-with-args 'org-cycle-hook 'all))
4006
4007 (t
4008 ;; Default action: go to overview
4009 (org-overview)
4010 (message "OVERVIEW")
4011 (setq org-cycle-global-status 'overview)
4012 (run-hook-with-args 'org-cycle-hook 'overview))))
4013
4014 ((and org-drawers org-drawer-regexp
4015 (save-excursion
4016 (beginning-of-line 1)
4017 (looking-at org-drawer-regexp)))
4018 ;; Toggle block visibility
4019 (org-flag-drawer
4020 (not (get-char-property (match-end 0) 'invisible))))
4021
4022 ((integerp arg)
4023 ;; Show-subtree, ARG levels up from here.
4024 (save-excursion
4025 (org-back-to-heading)
4026 (outline-up-heading (if (< arg 0) (- arg)
4027 (- (funcall outline-level) arg)))
4028 (org-show-subtree)))
4029
4030 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4031 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4032 ;; At a heading: rotate between three different views
4033 (org-back-to-heading)
4034 (let ((goal-column 0) eoh eol eos)
4035 ;; First, some boundaries
4036 (save-excursion
4037 (org-back-to-heading)
4038 (save-excursion
4039 (beginning-of-line 2)
4040 (while (and (not (eobp)) ;; this is like `next-line'
4041 (get-char-property (1- (point)) 'invisible))
4042 (beginning-of-line 2)) (setq eol (point)))
4043 (outline-end-of-heading) (setq eoh (point))
4044 (org-end-of-subtree t)
4045 (unless (eobp)
4046 (skip-chars-forward " \t\n")
4047 (beginning-of-line 1) ; in case this is an item
4048 )
4049 (setq eos (1- (point))))
4050 ;; Find out what to do next and set `this-command'
4051 (cond
4052 ((= eos eoh)
4053 ;; Nothing is hidden behind this heading
4054 (message "EMPTY ENTRY")
4055 (setq org-cycle-subtree-status nil)
4056 (save-excursion
4057 (goto-char eos)
4058 (outline-next-heading)
4059 (if (org-invisible-p) (org-flag-heading nil))))
4060 ((or (>= eol eos)
4061 (not (string-match "\\S-" (buffer-substring eol eos))))
4062 ;; Entire subtree is hidden in one line: open it
4063 (org-show-entry)
4064 (show-children)
4065 (message "CHILDREN")
4066 (save-excursion
4067 (goto-char eos)
4068 (outline-next-heading)
4069 (if (org-invisible-p) (org-flag-heading nil)))
4070 (setq org-cycle-subtree-status 'children)
4071 (run-hook-with-args 'org-cycle-hook 'children))
4072 ((and (eq last-command this-command)
4073 (eq org-cycle-subtree-status 'children))
4074 ;; We just showed the children, now show everything.
4075 (org-show-subtree)
4076 (message "SUBTREE")
4077 (setq org-cycle-subtree-status 'subtree)
4078 (run-hook-with-args 'org-cycle-hook 'subtree))
4079 (t
4080 ;; Default action: hide the subtree.
4081 (hide-subtree)
4082 (message "FOLDED")
4083 (setq org-cycle-subtree-status 'folded)
4084 (run-hook-with-args 'org-cycle-hook 'folded)))))
4085
4086 ;; TAB emulation and template completion
4087 (buffer-read-only (org-back-to-heading))
4088
4089 ((org-try-structure-completion))
4090
4091 ((org-try-cdlatex-tab))
4092
4093 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4094 (or (not (bolp))
4095 (not (looking-at outline-regexp))))
4096 (call-interactively (global-key-binding "\t")))
4097
4098 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4099 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4100 (or (and (eq org-cycle-emulate-tab 'white)
4101 (= (match-end 0) (point-at-eol)))
4102 (and (eq org-cycle-emulate-tab 'whitestart)
4103 (>= (match-end 0) pos))))
4104 t
4105 (eq org-cycle-emulate-tab t))
4106 (call-interactively (global-key-binding "\t")))
4107
4108 (t (save-excursion
4109 (org-back-to-heading)
4110 (org-cycle))))))
4111
4112 ;;;###autoload
4113 (defun org-global-cycle (&optional arg)
4114 "Cycle the global visibility. For details see `org-cycle'.
4115 With C-u prefix arg, switch to startup visibility.
4116 With a numeric prefix, show all headlines up to that level."
4117 (interactive "P")
4118 (let ((org-cycle-include-plain-lists
4119 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4120 (cond
4121 ((integerp arg)
4122 (show-all)
4123 (hide-sublevels arg)
4124 (setq org-cycle-global-status 'contents))
4125 ((equal arg '(4))
4126 (org-set-startup-visibility)
4127 (message "Startup visibility, plus VISIBILITY properties."))
4128 (t
4129 (org-cycle '(4))))))
4130
4131 (defun org-set-startup-visibility ()
4132 "Set the visibility required by startup options and properties."
4133 (cond
4134 ((eq org-startup-folded t)
4135 (org-cycle '(4)))
4136 ((eq org-startup-folded 'content)
4137 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4138 (org-cycle '(4)) (org-cycle '(4)))))
4139 (org-set-visibility-according-to-property 'no-cleanup)
4140 (org-cycle-hide-archived-subtrees 'all)
4141 (org-cycle-hide-drawers 'all)
4142 (org-cycle-show-empty-lines 'all))
4143
4144 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4145 "Switch subtree visibilities according to :VISIBILITY: property."
4146 (interactive)
4147 (let (state)
4148 (save-excursion
4149 (goto-char (point-min))
4150 (while (re-search-forward
4151 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4152 nil t)
4153 (setq state (match-string 1))
4154 (save-excursion
4155 (org-back-to-heading t)
4156 (hide-subtree)
4157 (org-reveal)
4158 (cond
4159 ((equal state '("fold" "folded"))
4160 (hide-subtree))
4161 ((equal state "children")
4162 (org-show-hidden-entry)
4163 (show-children))
4164 ((equal state "content")
4165 (save-excursion
4166 (save-restriction
4167 (org-narrow-to-subtree)
4168 (org-content))))
4169 ((member state '("all" "showall"))
4170 (show-subtree)))))
4171 (unless no-cleanup
4172 (org-cycle-hide-archived-subtrees 'all)
4173 (org-cycle-hide-drawers 'all)
4174 (org-cycle-show-empty-lines 'all)))))
4175
4176 (defun org-overview ()
4177 "Switch to overview mode, shoing only top-level headlines.
4178 Really, this shows all headlines with level equal or greater than the level
4179 of the first headline in the buffer. This is important, because if the
4180 first headline is not level one, then (hide-sublevels 1) gives confusing
4181 results."
4182 (interactive)
4183 (let ((level (save-excursion
4184 (goto-char (point-min))
4185 (if (re-search-forward (concat "^" outline-regexp) nil t)
4186 (progn
4187 (goto-char (match-beginning 0))
4188 (funcall outline-level))))))
4189 (and level (hide-sublevels level))))
4190
4191 (defun org-content (&optional arg)
4192 "Show all headlines in the buffer, like a table of contents.
4193 With numerical argument N, show content up to level N."
4194 (interactive "P")
4195 (save-excursion
4196 ;; Visit all headings and show their offspring
4197 (and (integerp arg) (org-overview))
4198 (goto-char (point-max))
4199 (catch 'exit
4200 (while (and (progn (condition-case nil
4201 (outline-previous-visible-heading 1)
4202 (error (goto-char (point-min))))
4203 t)
4204 (looking-at outline-regexp))
4205 (if (integerp arg)
4206 (show-children (1- arg))
4207 (show-branches))
4208 (if (bobp) (throw 'exit nil))))))
4209
4210
4211 (defun org-optimize-window-after-visibility-change (state)
4212 "Adjust the window after a change in outline visibility.
4213 This function is the default value of the hook `org-cycle-hook'."
4214 (when (get-buffer-window (current-buffer))
4215 (cond
4216 ; ((eq state 'overview) (org-first-headline-recenter 1))
4217 ; ((eq state 'overview) (org-beginning-of-line))
4218 ((eq state 'content) nil)
4219 ((eq state 'all) nil)
4220 ((eq state 'folded) nil)
4221 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4222 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4223
4224 (defun org-compact-display-after-subtree-move ()
4225 (let (beg end)
4226 (save-excursion
4227 (if (org-up-heading-safe)
4228 (progn
4229 (hide-subtree)
4230 (show-entry)
4231 (show-children)
4232 (org-cycle-show-empty-lines 'children)
4233 (org-cycle-hide-drawers 'children))
4234 (org-overview)))))
4235
4236 (defun org-cycle-show-empty-lines (state)
4237 "Show empty lines above all visible headlines.
4238 The region to be covered depends on STATE when called through
4239 `org-cycle-hook'. Lisp program can use t for STATE to get the
4240 entire buffer covered. Note that an empty line is only shown if there
4241 are at least `org-cycle-separator-lines' empty lines before the headeline."
4242 (when (> org-cycle-separator-lines 0)
4243 (save-excursion
4244 (let* ((n org-cycle-separator-lines)
4245 (re (cond
4246 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4247 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4248 (t (let ((ns (number-to-string (- n 2))))
4249 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4250 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4251 beg end)
4252 (cond
4253 ((memq state '(overview contents t))
4254 (setq beg (point-min) end (point-max)))
4255 ((memq state '(children folded))
4256 (setq beg (point) end (progn (org-end-of-subtree t t)
4257 (beginning-of-line 2)
4258 (point)))))
4259 (when beg
4260 (goto-char beg)
4261 (while (re-search-forward re end t)
4262 (if (not (get-char-property (match-end 1) 'invisible))
4263 (outline-flag-region
4264 (match-beginning 1) (match-end 1) nil)))))))
4265 ;; Never hide empty lines at the end of the file.
4266 (save-excursion
4267 (goto-char (point-max))
4268 (outline-previous-heading)
4269 (outline-end-of-heading)
4270 (if (and (looking-at "[ \t\n]+")
4271 (= (match-end 0) (point-max)))
4272 (outline-flag-region (point) (match-end 0) nil))))
4273
4274 (defun org-show-empty-lines-in-parent ()
4275 "Move to the parent and re-show empty lines before visible headlines."
4276 (save-excursion
4277 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4278 (org-cycle-show-empty-lines context))))
4279
4280 (defun org-cycle-hide-drawers (state)
4281 "Re-hide all drawers after a visibility state change."
4282 (when (and (org-mode-p)
4283 (not (memq state '(overview folded))))
4284 (save-excursion
4285 (let* ((globalp (memq state '(contents all)))
4286 (beg (if globalp (point-min) (point)))
4287 (end (if globalp (point-max) (org-end-of-subtree t))))
4288 (goto-char beg)
4289 (while (re-search-forward org-drawer-regexp end t)
4290 (org-flag-drawer t))))))
4291
4292 (defun org-flag-drawer (flag)
4293 (save-excursion
4294 (beginning-of-line 1)
4295 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4296 (let ((b (match-end 0))
4297 (outline-regexp org-outline-regexp))
4298 (if (re-search-forward
4299 "^[ \t]*:END:"
4300 (save-excursion (outline-next-heading) (point)) t)
4301 (outline-flag-region b (point-at-eol) flag)
4302 (error ":END: line missing"))))))
4303
4304 (defun org-subtree-end-visible-p ()
4305 "Is the end of the current subtree visible?"
4306 (pos-visible-in-window-p
4307 (save-excursion (org-end-of-subtree t) (point))))
4308
4309 (defun org-first-headline-recenter (&optional N)
4310 "Move cursor to the first headline and recenter the headline.
4311 Optional argument N means, put the headline into the Nth line of the window."
4312 (goto-char (point-min))
4313 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4314 (beginning-of-line)
4315 (recenter (prefix-numeric-value N))))
4316
4317 ;;; Org-goto
4318
4319 (defvar org-goto-window-configuration nil)
4320 (defvar org-goto-marker nil)
4321 (defvar org-goto-map
4322 (let ((map (make-sparse-keymap)))
4323 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4324 (while (setq cmd (pop cmds))
4325 (substitute-key-definition cmd cmd map global-map)))
4326 (suppress-keymap map)
4327 (org-defkey map "\C-m" 'org-goto-ret)
4328 (org-defkey map [(return)] 'org-goto-ret)
4329 (org-defkey map [(left)] 'org-goto-left)
4330 (org-defkey map [(right)] 'org-goto-right)
4331 (org-defkey map [(control ?g)] 'org-goto-quit)
4332 (org-defkey map "\C-i" 'org-cycle)
4333 (org-defkey map [(tab)] 'org-cycle)
4334 (org-defkey map [(down)] 'outline-next-visible-heading)
4335 (org-defkey map [(up)] 'outline-previous-visible-heading)
4336 (if org-goto-auto-isearch
4337 (if (fboundp 'define-key-after)
4338 (define-key-after map [t] 'org-goto-local-auto-isearch)
4339 nil)
4340 (org-defkey map "q" 'org-goto-quit)
4341 (org-defkey map "n" 'outline-next-visible-heading)
4342 (org-defkey map "p" 'outline-previous-visible-heading)
4343 (org-defkey map "f" 'outline-forward-same-level)
4344 (org-defkey map "b" 'outline-backward-same-level)
4345 (org-defkey map "u" 'outline-up-heading))
4346 (org-defkey map "/" 'org-occur)
4347 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4348 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4349 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4350 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4351 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4352 map))
4353
4354 (defconst org-goto-help
4355 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4356 RET=jump to location [Q]uit and return to previous location
4357 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4358
4359 (defvar org-goto-start-pos) ; dynamically scoped parameter
4360
4361 ;; FIXME: Docstring doe not mention both interfaces
4362 (defun org-goto (&optional alternative-interface)
4363 "Look up a different location in the current file, keeping current visibility.
4364
4365 When you want look-up or go to a different location in a document, the
4366 fastest way is often to fold the entire buffer and then dive into the tree.
4367 This method has the disadvantage, that the previous location will be folded,
4368 which may not be what you want.
4369
4370 This command works around this by showing a copy of the current buffer
4371 in an indirect buffer, in overview mode. You can dive into the tree in
4372 that copy, use org-occur and incremental search to find a location.
4373 When pressing RET or `Q', the command returns to the original buffer in
4374 which the visibility is still unchanged. After RET is will also jump to
4375 the location selected in the indirect buffer and expose the
4376 the headline hierarchy above."
4377 (interactive "P")
4378 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4379 (org-refile-use-outline-path t)
4380 (interface
4381 (if (not alternative-interface)
4382 org-goto-interface
4383 (if (eq org-goto-interface 'outline)
4384 'outline-path-completion
4385 'outline)))
4386 (org-goto-start-pos (point))
4387 (selected-point
4388 (if (eq interface 'outline)
4389 (car (org-get-location (current-buffer) org-goto-help))
4390 (nth 3 (org-refile-get-location "Goto: ")))))
4391 (if selected-point
4392 (progn
4393 (org-mark-ring-push org-goto-start-pos)
4394 (goto-char selected-point)
4395 (if (or (org-invisible-p) (org-invisible-p2))
4396 (org-show-context 'org-goto)))
4397 (message "Quit"))))
4398
4399 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4400 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4401 (defvar org-goto-local-auto-isearch-map) ; defined below
4402
4403 (defun org-get-location (buf help)
4404 "Let the user select a location in the Org-mode buffer BUF.
4405 This function uses a recursive edit. It returns the selected position
4406 or nil."
4407 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4408 (isearch-hide-immediately nil)
4409 (isearch-search-fun-function
4410 (lambda () 'org-goto-local-search-headings))
4411 (org-goto-selected-point org-goto-exit-command))
4412 (save-excursion
4413 (save-window-excursion
4414 (delete-other-windows)
4415 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4416 (switch-to-buffer
4417 (condition-case nil
4418 (make-indirect-buffer (current-buffer) "*org-goto*")
4419 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4420 (with-output-to-temp-buffer "*Help*"
4421 (princ help))
4422 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4423 (setq buffer-read-only nil)
4424 (let ((org-startup-truncated t)
4425 (org-startup-folded nil)
4426 (org-startup-align-all-tables nil))
4427 (org-mode)
4428 (org-overview))
4429 (setq buffer-read-only t)
4430 (if (and (boundp 'org-goto-start-pos)
4431 (integer-or-marker-p org-goto-start-pos))
4432 (let ((org-show-hierarchy-above t)
4433 (org-show-siblings t)
4434 (org-show-following-heading t))
4435 (goto-char org-goto-start-pos)
4436 (and (org-invisible-p) (org-show-context)))
4437 (goto-char (point-min)))
4438 (org-beginning-of-line)
4439 (message "Select location and press RET")
4440 (use-local-map org-goto-map)
4441 (recursive-edit)
4442 ))
4443 (kill-buffer "*org-goto*")
4444 (cons org-goto-selected-point org-goto-exit-command)))
4445
4446 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4447 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4448 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4449 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4450
4451 (defun org-goto-local-search-headings (string bound noerror)
4452 "Search and make sure that any matches are in headlines."
4453 (catch 'return
4454 (while (if isearch-forward
4455 (search-forward string bound noerror)
4456 (search-backward string bound noerror))
4457 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4458 (and (member :headline context)
4459 (not (member :tags context))))
4460 (throw 'return (point))))))
4461
4462 (defun org-goto-local-auto-isearch ()
4463 "Start isearch."
4464 (interactive)
4465 (goto-char (point-min))
4466 (let ((keys (this-command-keys)))
4467 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4468 (isearch-mode t)
4469 (isearch-process-search-char (string-to-char keys)))))
4470
4471 (defun org-goto-ret (&optional arg)
4472 "Finish `org-goto' by going to the new location."
4473 (interactive "P")
4474 (setq org-goto-selected-point (point)
4475 org-goto-exit-command 'return)
4476 (throw 'exit nil))
4477
4478 (defun org-goto-left ()
4479 "Finish `org-goto' by going to the new location."
4480 (interactive)
4481 (if (org-on-heading-p)
4482 (progn
4483 (beginning-of-line 1)
4484 (setq org-goto-selected-point (point)
4485 org-goto-exit-command 'left)
4486 (throw 'exit nil))
4487 (error "Not on a heading")))
4488
4489 (defun org-goto-right ()
4490 "Finish `org-goto' by going to the new location."
4491 (interactive)
4492 (if (org-on-heading-p)
4493 (progn
4494 (setq org-goto-selected-point (point)
4495 org-goto-exit-command 'right)
4496 (throw 'exit nil))
4497 (error "Not on a heading")))
4498
4499 (defun org-goto-quit ()
4500 "Finish `org-goto' without cursor motion."
4501 (interactive)
4502 (setq org-goto-selected-point nil)
4503 (setq org-goto-exit-command 'quit)
4504 (throw 'exit nil))
4505
4506 ;;; Indirect buffer display of subtrees
4507
4508 (defvar org-indirect-dedicated-frame nil
4509 "This is the frame being used for indirect tree display.")
4510 (defvar org-last-indirect-buffer nil)
4511
4512 (defun org-tree-to-indirect-buffer (&optional arg)
4513 "Create indirect buffer and narrow it to current subtree.
4514 With numerical prefix ARG, go up to this level and then take that tree.
4515 If ARG is negative, go up that many levels.
4516 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4517 indirect buffer previously made with this command, to avoid proliferation of
4518 indirect buffers. However, when you call the command with a `C-u' prefix, or
4519 when `org-indirect-buffer-display' is `new-frame', the last buffer
4520 is kept so that you can work with several indirect buffers at the same time.
4521 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4522 requests that a new frame be made for the new buffer, so that the dedicated
4523 frame is not changed."
4524 (interactive "P")
4525 (let ((cbuf (current-buffer))
4526 (cwin (selected-window))
4527 (pos (point))
4528 beg end level heading ibuf)
4529 (save-excursion
4530 (org-back-to-heading t)
4531 (when (numberp arg)
4532 (setq level (org-outline-level))
4533 (if (< arg 0) (setq arg (+ level arg)))
4534 (while (> (setq level (org-outline-level)) arg)
4535 (outline-up-heading 1 t)))
4536 (setq beg (point)
4537 heading (org-get-heading))
4538 (org-end-of-subtree t) (setq end (point)))
4539 (if (and (buffer-live-p org-last-indirect-buffer)
4540 (not (eq org-indirect-buffer-display 'new-frame))
4541 (not arg))
4542 (kill-buffer org-last-indirect-buffer))
4543 (setq ibuf (org-get-indirect-buffer cbuf)
4544 org-last-indirect-buffer ibuf)
4545 (cond
4546 ((or (eq org-indirect-buffer-display 'new-frame)
4547 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4548 (select-frame (make-frame))
4549 (delete-other-windows)
4550 (switch-to-buffer ibuf)
4551 (org-set-frame-title heading))
4552 ((eq org-indirect-buffer-display 'dedicated-frame)
4553 (raise-frame
4554 (select-frame (or (and org-indirect-dedicated-frame
4555 (frame-live-p org-indirect-dedicated-frame)
4556 org-indirect-dedicated-frame)
4557 (setq org-indirect-dedicated-frame (make-frame)))))
4558 (delete-other-windows)
4559 (switch-to-buffer ibuf)
4560 (org-set-frame-title (concat "Indirect: " heading)))
4561 ((eq org-indirect-buffer-display 'current-window)
4562 (switch-to-buffer ibuf))
4563 ((eq org-indirect-buffer-display 'other-window)
4564 (pop-to-buffer ibuf))
4565 (t (error "Invalid value.")))
4566 (if (featurep 'xemacs)
4567 (save-excursion (org-mode) (turn-on-font-lock)))
4568 (narrow-to-region beg end)
4569 (show-all)
4570 (goto-char pos)
4571 (and (window-live-p cwin) (select-window cwin))))
4572
4573 (defun org-get-indirect-buffer (&optional buffer)
4574 (setq buffer (or buffer (current-buffer)))
4575 (let ((n 1) (base (buffer-name buffer)) bname)
4576 (while (buffer-live-p
4577 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4578 (setq n (1+ n)))
4579 (condition-case nil
4580 (make-indirect-buffer buffer bname 'clone)
4581 (error (make-indirect-buffer buffer bname)))))
4582
4583 (defun org-set-frame-title (title)
4584 "Set the title of the current frame to the string TITLE."
4585 ;; FIXME: how to name a single frame in XEmacs???
4586 (unless (featurep 'xemacs)
4587 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4588
4589 ;;;; Structure editing
4590
4591 ;;; Inserting headlines
4592
4593 (defun org-insert-heading (&optional force-heading)
4594 "Insert a new heading or item with same depth at point.
4595 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4596 If point is at the beginning of a headline, insert a sibling before the
4597 current headline. If point is not at the beginning, do not split the line,
4598 but create the new hedline after the current line."
4599 (interactive "P")
4600 (if (= (buffer-size) 0)
4601 (insert "\n* ")
4602 (when (or force-heading (not (org-insert-item)))
4603 (let* ((head (save-excursion
4604 (condition-case nil
4605 (progn
4606 (org-back-to-heading)
4607 (match-string 0))
4608 (error "*"))))
4609 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4610 pos hide-previous)
4611 (cond
4612 ((and (org-on-heading-p) (bolp)
4613 (or (bobp)
4614 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4615 ;; insert before the current line
4616 (open-line (if blank 2 1)))
4617 ((and (bolp)
4618 (or (bobp)
4619 (save-excursion
4620 (backward-char 1) (not (org-invisible-p)))))
4621 ;; insert right here
4622 nil)
4623 (t
4624 ;; in the middle of the line
4625 (save-excursion
4626 (end-of-line)
4627 (setq hide-previous (org-invisible-p)))
4628 (org-show-entry)
4629 (let ((split
4630 (org-get-alist-option org-M-RET-may-split-line 'headline))
4631 tags pos)
4632 (cond
4633 (org-insert-heading-respect-content
4634 (org-end-of-subtree nil t)
4635 (open-line 1))
4636 ((org-on-heading-p)
4637 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4638 (setq tags (and (match-end 2) (match-string 2)))
4639 (and (match-end 1)
4640 (delete-region (match-beginning 1) (match-end 1)))
4641 (setq pos (point-at-bol))
4642 (or split (end-of-line 1))
4643 (delete-horizontal-space)
4644 (newline (if blank 2 1))
4645 (when tags
4646 (save-excursion
4647 (goto-char pos)
4648 (end-of-line 1)
4649 (insert " " tags)
4650 (org-set-tags nil 'align))))
4651 (t
4652 (or split (end-of-line 1))
4653 (newline (if blank 2 1)))))))
4654 (insert head) (just-one-space)
4655 (setq pos (point))
4656 (end-of-line 1)
4657 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4658 (when (and org-insert-heading-respect-content hide-previous)
4659 (save-excursion
4660 (outline-previous-visible-heading 1)
4661 (hide-entry)))
4662 (run-hooks 'org-insert-heading-hook)))))
4663
4664 (defun org-get-heading (&optional no-tags)
4665 "Return the heading of the current entry, without the stars."
4666 (save-excursion
4667 (org-back-to-heading t)
4668 (if (looking-at
4669 (if no-tags
4670 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4671 "\\*+[ \t]+\\([^\r\n]*\\)"))
4672 (match-string 1) "")))
4673
4674 (defun org-insert-heading-after-current ()
4675 "Insert a new heading with same level as current, after current subtree."
4676 (interactive)
4677 (org-back-to-heading)
4678 (org-insert-heading)
4679 (org-move-subtree-down)
4680 (end-of-line 1))
4681
4682 (defun org-insert-heading-respect-content ()
4683 (interactive)
4684 (let ((org-insert-heading-respect-content t))
4685 (org-insert-heading t)))
4686
4687 (defun org-insert-todo-heading-respect-content (&optional force-state)
4688 (interactive "P")
4689 (let ((org-insert-heading-respect-content t))
4690 (org-insert-todo-heading force-state t)))
4691
4692 (defun org-insert-todo-heading (arg &optional force-heading)
4693 "Insert a new heading with the same level and TODO state as current heading.
4694 If the heading has no TODO state, or if the state is DONE, use the first
4695 state (TODO by default). Also with prefix arg, force first state."
4696 (interactive "P")
4697 (when (or force-heading (not (org-insert-item 'checkbox)))
4698 (org-insert-heading force-heading)
4699 (save-excursion
4700 (org-back-to-heading)
4701 (outline-previous-heading)
4702 (looking-at org-todo-line-regexp))
4703 (if (or arg
4704 (not (match-beginning 2))
4705 (member (match-string 2) org-done-keywords))
4706 (insert (car org-todo-keywords-1) " ")
4707 (insert (match-string 2) " "))
4708 (when org-provide-todo-statistics
4709 (org-update-parent-todo-statistics))))
4710
4711 (defun org-insert-subheading (arg)
4712 "Insert a new subheading and demote it.
4713 Works for outline headings and for plain lists alike."
4714 (interactive "P")
4715 (org-insert-heading arg)
4716 (cond
4717 ((org-on-heading-p) (org-do-demote))
4718 ((org-at-item-p) (org-indent-item 1))))
4719
4720 (defun org-insert-todo-subheading (arg)
4721 "Insert a new subheading with TODO keyword or checkbox and demote it.
4722 Works for outline headings and for plain lists alike."
4723 (interactive "P")
4724 (org-insert-todo-heading arg)
4725 (cond
4726 ((org-on-heading-p) (org-do-demote))
4727 ((org-at-item-p) (org-indent-item 1))))
4728
4729 ;;; Promotion and Demotion
4730
4731 (defun org-promote-subtree ()
4732 "Promote the entire subtree.
4733 See also `org-promote'."
4734 (interactive)
4735 (save-excursion
4736 (org-map-tree 'org-promote))
4737 (org-fix-position-after-promote))
4738
4739 (defun org-demote-subtree ()
4740 "Demote the entire subtree. See `org-demote'.
4741 See also `org-promote'."
4742 (interactive)
4743 (save-excursion
4744 (org-map-tree 'org-demote))
4745 (org-fix-position-after-promote))
4746
4747
4748 (defun org-do-promote ()
4749 "Promote the current heading higher up the tree.
4750 If the region is active in `transient-mark-mode', promote all headings
4751 in the region."
4752 (interactive)
4753 (save-excursion
4754 (if (org-region-active-p)
4755 (org-map-region 'org-promote (region-beginning) (region-end))
4756 (org-promote)))
4757 (org-fix-position-after-promote))
4758
4759 (defun org-do-demote ()
4760 "Demote the current heading lower down the tree.
4761 If the region is active in `transient-mark-mode', demote all headings
4762 in the region."
4763 (interactive)
4764 (save-excursion
4765 (if (org-region-active-p)
4766 (org-map-region 'org-demote (region-beginning) (region-end))
4767 (org-demote)))
4768 (org-fix-position-after-promote))
4769
4770 (defun org-fix-position-after-promote ()
4771 "Make sure that after pro/demotion cursor position is right."
4772 (let ((pos (point)))
4773 (when (save-excursion
4774 (beginning-of-line 1)
4775 (looking-at org-todo-line-regexp)
4776 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4777 (cond ((eobp) (insert " "))
4778 ((eolp) (insert " "))
4779 ((equal (char-after) ?\ ) (forward-char 1))))))
4780
4781 (defun org-reduced-level (l)
4782 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4783
4784 (defun org-get-valid-level (level &optional change)
4785 "Rectify a level change under the influence of `org-odd-levels-only'
4786 LEVEL is a current level, CHANGE is by how much the level should be
4787 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4788 even level numbers will become the next higher odd number."
4789 (if org-odd-levels-only
4790 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4791 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4792 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4793 (max 1 (+ level change))))
4794
4795 (if (boundp 'define-obsolete-function-alias)
4796 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4797 (define-obsolete-function-alias 'org-get-legal-level
4798 'org-get-valid-level)
4799 (define-obsolete-function-alias 'org-get-legal-level
4800 'org-get-valid-level "23.1")))
4801
4802 (defun org-promote ()
4803 "Promote the current heading higher up the tree.
4804 If the region is active in `transient-mark-mode', promote all headings
4805 in the region."
4806 (org-back-to-heading t)
4807 (let* ((level (save-match-data (funcall outline-level)))
4808 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4809 (diff (abs (- level (length up-head) -1))))
4810 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4811 (replace-match up-head nil t)
4812 ;; Fixup tag positioning
4813 (and org-auto-align-tags (org-set-tags nil t))
4814 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4815
4816 (defun org-demote ()
4817 "Demote the current heading lower down the tree.
4818 If the region is active in `transient-mark-mode', demote all headings
4819 in the region."
4820 (org-back-to-heading t)
4821 (let* ((level (save-match-data (funcall outline-level)))
4822 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4823 (diff (abs (- level (length down-head) -1))))
4824 (replace-match down-head nil t)
4825 ;; Fixup tag positioning
4826 (and org-auto-align-tags (org-set-tags nil t))
4827 (if org-adapt-indentation (org-fixup-indentation diff))))
4828
4829 (defun org-map-tree (fun)
4830 "Call FUN for every heading underneath the current one."
4831 (org-back-to-heading)
4832 (let ((level (funcall outline-level)))
4833 (save-excursion
4834 (funcall fun)
4835 (while (and (progn
4836 (outline-next-heading)
4837 (> (funcall outline-level) level))
4838 (not (eobp)))
4839 (funcall fun)))))
4840
4841 (defun org-map-region (fun beg end)
4842 "Call FUN for every heading between BEG and END."
4843 (let ((org-ignore-region t))
4844 (save-excursion
4845 (setq end (copy-marker end))
4846 (goto-char beg)
4847 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4848 (< (point) end))
4849 (funcall fun))
4850 (while (and (progn
4851 (outline-next-heading)
4852 (< (point) end))
4853 (not (eobp)))
4854 (funcall fun)))))
4855
4856 (defun org-fixup-indentation (diff)
4857 "Change the indentation in the current entry by DIFF
4858 However, if any line in the current entry has no indentation, or if it
4859 would end up with no indentation after the change, nothing at all is done."
4860 (save-excursion
4861 (let ((end (save-excursion (outline-next-heading)
4862 (point-marker)))
4863 (prohibit (if (> diff 0)
4864 "^\\S-"
4865 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4866 col)
4867 (unless (save-excursion (end-of-line 1)
4868 (re-search-forward prohibit end t))
4869 (while (and (< (point) end)
4870 (re-search-forward "^[ \t]+" end t))
4871 (goto-char (match-end 0))
4872 (setq col (current-column))
4873 (if (< diff 0) (replace-match ""))
4874 (indent-to (+ diff col))))
4875 (move-marker end nil))))
4876
4877 (defun org-convert-to-odd-levels ()
4878 "Convert an org-mode file with all levels allowed to one with odd levels.
4879 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4880 level 5 etc."
4881 (interactive)
4882 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4883 (let ((org-odd-levels-only nil) n)
4884 (save-excursion
4885 (goto-char (point-min))
4886 (while (re-search-forward "^\\*\\*+ " nil t)
4887 (setq n (- (length (match-string 0)) 2))
4888 (while (>= (setq n (1- n)) 0)
4889 (org-demote))
4890 (end-of-line 1))))))
4891
4892
4893 (defun org-convert-to-oddeven-levels ()
4894 "Convert an org-mode file with only odd levels to one with odd and even levels.
4895 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4896 section with an even level, conversion would destroy the structure of the file. An error
4897 is signaled in this case."
4898 (interactive)
4899 (goto-char (point-min))
4900 ;; First check if there are no even levels
4901 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4902 (org-show-context t)
4903 (error "Not all levels are odd in this file. Conversion not possible."))
4904 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4905 (let ((org-odd-levels-only nil) n)
4906 (save-excursion
4907 (goto-char (point-min))
4908 (while (re-search-forward "^\\*\\*+ " nil t)
4909 (setq n (/ (1- (length (match-string 0))) 2))
4910 (while (>= (setq n (1- n)) 0)
4911 (org-promote))
4912 (end-of-line 1))))))
4913
4914 (defun org-tr-level (n)
4915 "Make N odd if required."
4916 (if org-odd-levels-only (1+ (/ n 2)) n))
4917
4918 ;;; Vertical tree motion, cutting and pasting of subtrees
4919
4920 (defun org-move-subtree-up (&optional arg)
4921 "Move the current subtree up past ARG headlines of the same level."
4922 (interactive "p")
4923 (org-move-subtree-down (- (prefix-numeric-value arg))))
4924
4925 (defun org-move-subtree-down (&optional arg)
4926 "Move the current subtree down past ARG headlines of the same level."
4927 (interactive "p")
4928 (setq arg (prefix-numeric-value arg))
4929 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4930 'outline-get-last-sibling))
4931 (ins-point (make-marker))
4932 (cnt (abs arg))
4933 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4934 ;; Select the tree
4935 (org-back-to-heading)
4936 (setq beg0 (point))
4937 (save-excursion
4938 (setq ne-beg (org-back-over-empty-lines))
4939 (setq beg (point)))
4940 (save-match-data
4941 (save-excursion (outline-end-of-heading)
4942 (setq folded (org-invisible-p)))
4943 (outline-end-of-subtree))
4944 (outline-next-heading)
4945 (setq ne-end (org-back-over-empty-lines))
4946 (setq end (point))
4947 (goto-char beg0)
4948 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4949 ;; include less whitespace
4950 (save-excursion
4951 (goto-char beg)
4952 (forward-line (- ne-beg ne-end))
4953 (setq beg (point))))
4954 ;; Find insertion point, with error handling
4955 (while (> cnt 0)
4956 (or (and (funcall movfunc) (looking-at outline-regexp))
4957 (progn (goto-char beg0)
4958 (error "Cannot move past superior level or buffer limit")))
4959 (setq cnt (1- cnt)))
4960 (if (> arg 0)
4961 ;; Moving forward - still need to move over subtree
4962 (progn (org-end-of-subtree t t)
4963 (save-excursion
4964 (org-back-over-empty-lines)
4965 (or (bolp) (newline)))))
4966 (setq ne-ins (org-back-over-empty-lines))
4967 (move-marker ins-point (point))
4968 (setq txt (buffer-substring beg end))
4969 (org-save-markers-in-region beg end)
4970 (delete-region beg end)
4971 (outline-flag-region (1- beg) beg nil)
4972 (outline-flag-region (1- (point)) (point) nil)
4973 (let ((bbb (point)))
4974 (insert-before-markers txt)
4975 (org-reinstall-markers-in-region bbb)
4976 (move-marker ins-point bbb))
4977 (or (bolp) (insert "\n"))
4978 (setq ins-end (point))
4979 (goto-char ins-point)
4980 (org-skip-whitespace)
4981 (when (and (< arg 0)
4982 (org-first-sibling-p)
4983 (> ne-ins ne-beg))
4984 ;; Move whitespace back to beginning
4985 (save-excursion
4986 (goto-char ins-end)
4987 (let ((kill-whole-line t))
4988 (kill-line (- ne-ins ne-beg)) (point)))
4989 (insert (make-string (- ne-ins ne-beg) ?\n)))
4990 (move-marker ins-point nil)
4991 (org-compact-display-after-subtree-move)
4992 (org-show-empty-lines-in-parent)
4993 (unless folded
4994 (org-show-entry)
4995 (show-children)
4996 (org-cycle-hide-drawers 'children))))
4997
4998 (defvar org-subtree-clip ""
4999 "Clipboard for cut and paste of subtrees.
5000 This is actually only a copy of the kill, because we use the normal kill
5001 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5002
5003 (defvar org-subtree-clip-folded nil
5004 "Was the last copied subtree folded?
5005 This is used to fold the tree back after pasting.")
5006
5007 (defun org-cut-subtree (&optional n)
5008 "Cut the current subtree into the clipboard.
5009 With prefix arg N, cut this many sequential subtrees.
5010 This is a short-hand for marking the subtree and then cutting it."
5011 (interactive "p")
5012 (org-copy-subtree n 'cut))
5013
5014 (defun org-copy-subtree (&optional n cut force-store-markers)
5015 "Cut the current subtree into the clipboard.
5016 With prefix arg N, cut this many sequential subtrees.
5017 This is a short-hand for marking the subtree and then copying it.
5018 If CUT is non-nil, actually cut the subtree.
5019 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5020 of some markers in the region, even if CUT is non-nil. This is
5021 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5022 (interactive "p")
5023 (let (beg end folded (beg0 (point)))
5024 (if (interactive-p)
5025 (org-back-to-heading nil) ; take what looks like a subtree
5026 (org-back-to-heading t)) ; take what is really there
5027 (org-back-over-empty-lines)
5028 (setq beg (point))
5029 (skip-chars-forward " \t\r\n")
5030 (save-match-data
5031 (save-excursion (outline-end-of-heading)
5032 (setq folded (org-invisible-p)))
5033 (condition-case nil
5034 (outline-forward-same-level (1- n))
5035 (error nil))
5036 (org-end-of-subtree t t))
5037 (org-back-over-empty-lines)
5038 (setq end (point))
5039 (goto-char beg0)
5040 (when (> end beg)
5041 (setq org-subtree-clip-folded folded)
5042 (when (or cut force-store-markers)
5043 (org-save-markers-in-region beg end))
5044 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5045 (setq org-subtree-clip (current-kill 0))
5046 (message "%s: Subtree(s) with %d characters"
5047 (if cut "Cut" "Copied")
5048 (length org-subtree-clip)))))
5049
5050 (defun org-paste-subtree (&optional level tree)
5051 "Paste the clipboard as a subtree, with modification of headline level.
5052 The entire subtree is promoted or demoted in order to match a new headline
5053 level. By default, the new level is derived from the visible headings
5054 before and after the insertion point, and taken to be the inferior headline
5055 level of the two. So if the previous visible heading is level 3 and the
5056 next is level 4 (or vice versa), level 4 will be used for insertion.
5057 This makes sure that the subtree remains an independent subtree and does
5058 not swallow low level entries.
5059
5060 You can also force a different level, either by using a numeric prefix
5061 argument, or by inserting the heading marker by hand. For example, if the
5062 cursor is after \"*****\", then the tree will be shifted to level 5.
5063
5064 If you want to insert the tree as is, just use \\[yank].
5065
5066 If optional TREE is given, use this text instead of the kill ring."
5067 (interactive "P")
5068 (unless (org-kill-is-subtree-p tree)
5069 (error "%s"
5070 (substitute-command-keys
5071 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5072 (let* ((visp (not (org-invisible-p)))
5073 (txt (or tree (and kill-ring (current-kill 0))))
5074 (^re (concat "^\\(" outline-regexp "\\)"))
5075 (re (concat "\\(" outline-regexp "\\)"))
5076 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5077
5078 (old-level (if (string-match ^re txt)
5079 (- (match-end 0) (match-beginning 0) 1)
5080 -1))
5081 (force-level (cond (level (prefix-numeric-value level))
5082 ((string-match
5083 ^re_ (buffer-substring (point-at-bol) (point)))
5084 (- (match-end 1) (match-beginning 1)))
5085 (t nil)))
5086 (previous-level (save-excursion
5087 (condition-case nil
5088 (progn
5089 (outline-previous-visible-heading 1)
5090 (if (looking-at re)
5091 (- (match-end 0) (match-beginning 0) 1)
5092 1))
5093 (error 1))))
5094 (next-level (save-excursion
5095 (condition-case nil
5096 (progn
5097 (or (looking-at outline-regexp)
5098 (outline-next-visible-heading 1))
5099 (if (looking-at re)
5100 (- (match-end 0) (match-beginning 0) 1)
5101 1))
5102 (error 1))))
5103 (new-level (or force-level (max previous-level next-level)))
5104 (shift (if (or (= old-level -1)
5105 (= new-level -1)
5106 (= old-level new-level))
5107 0
5108 (- new-level old-level)))
5109 (delta (if (> shift 0) -1 1))
5110 (func (if (> shift 0) 'org-demote 'org-promote))
5111 (org-odd-levels-only nil)
5112 beg end)
5113 ;; Remove the forced level indicator
5114 (if force-level
5115 (delete-region (point-at-bol) (point)))
5116 ;; Paste
5117 (beginning-of-line 1)
5118 (org-back-over-empty-lines)
5119 (setq beg (point))
5120 (insert-before-markers txt)
5121 (unless (string-match "\n\\'" txt) (insert "\n"))
5122 (org-reinstall-markers-in-region beg)
5123 (setq end (point))
5124 (goto-char beg)
5125 (skip-chars-forward " \t\n\r")
5126 (setq beg (point))
5127 (if (and (org-invisible-p) visp)
5128 (save-excursion (outline-show-heading)))
5129 ;; Shift if necessary
5130 (unless (= shift 0)
5131 (save-restriction
5132 (narrow-to-region beg end)
5133 (while (not (= shift 0))
5134 (org-map-region func (point-min) (point-max))
5135 (setq shift (+ delta shift)))
5136 (goto-char (point-min))))
5137 (when (interactive-p)
5138 (message "Clipboard pasted as level %d subtree" new-level))
5139 (if (and kill-ring
5140 (eq org-subtree-clip (current-kill 0))
5141 org-subtree-clip-folded)
5142 ;; The tree was folded before it was killed/copied
5143 (hide-subtree))))
5144
5145 (defun org-kill-is-subtree-p (&optional txt)
5146 "Check if the current kill is an outline subtree, or a set of trees.
5147 Returns nil if kill does not start with a headline, or if the first
5148 headline level is not the largest headline level in the tree.
5149 So this will actually accept several entries of equal levels as well,
5150 which is OK for `org-paste-subtree'.
5151 If optional TXT is given, check this string instead of the current kill."
5152 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5153 (start-level (and kill
5154 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5155 org-outline-regexp "\\)")
5156 kill)
5157 (- (match-end 2) (match-beginning 2) 1)))
5158 (re (concat "^" org-outline-regexp))
5159 (start (1+ (or (match-beginning 2) -1))))
5160 (if (not start-level)
5161 (progn
5162 nil) ;; does not even start with a heading
5163 (catch 'exit
5164 (while (setq start (string-match re kill (1+ start)))
5165 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5166 (throw 'exit nil)))
5167 t))))
5168
5169 (defvar org-markers-to-move nil
5170 "Markers that should be moved with a cut-and-paste operation.
5171 Those markers are stored together with their positions relative to
5172 the start of the region.")
5173
5174 (defun org-save-markers-in-region (beg end)
5175 "Check markers in region.
5176 If these markers are between BEG and END, record their position relative
5177 to BEG, so that after moving the block of text, we can put the markers back
5178 into place.
5179 This function gets called just before an entry or tree gets cut from the
5180 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5181 called immediately, to move the markers with the entries."
5182 (setq org-markers-to-move nil)
5183 (when (featurep 'org-clock)
5184 (org-clock-save-markers-for-cut-and-paste beg end))
5185 (when (featurep 'org-agenda)
5186 (org-agenda-save-markers-for-cut-and-paste beg end)))
5187
5188 (defun org-check-and-save-marker (marker beg end)
5189 "Check if MARKER is between BEG and END.
5190 If yes, remember the marker and the distance to BEG."
5191 (when (and (marker-buffer marker)
5192 (equal (marker-buffer marker) (current-buffer)))
5193 (if (and (>= marker beg) (< marker end))
5194 (push (cons marker (- marker beg)) org-markers-to-move))))
5195
5196 (defun org-reinstall-markers-in-region (beg)
5197 "Move all remembered markers to their position relative to BEG."
5198 (mapc (lambda (x)
5199 (move-marker (car x) (+ beg (cdr x))))
5200 org-markers-to-move)
5201 (setq org-markers-to-move nil))
5202
5203 (defun org-narrow-to-subtree ()
5204 "Narrow buffer to the current subtree."
5205 (interactive)
5206 (save-excursion
5207 (save-match-data
5208 (narrow-to-region
5209 (progn (org-back-to-heading) (point))
5210 (progn (org-end-of-subtree t) (point))))))
5211
5212
5213 ;;; Outline Sorting
5214
5215 (defun org-sort (with-case)
5216 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5217 Optional argument WITH-CASE means sort case-sensitively."
5218 (interactive "P")
5219 (if (org-at-table-p)
5220 (org-call-with-arg 'org-table-sort-lines with-case)
5221 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5222
5223 (defun org-sort-remove-invisible (s)
5224 (remove-text-properties 0 (length s) org-rm-props s)
5225 (while (string-match org-bracket-link-regexp s)
5226 (setq s (replace-match (if (match-end 2)
5227 (match-string 3 s)
5228 (match-string 1 s)) t t s)))
5229 s)
5230
5231 (defvar org-priority-regexp) ; defined later in the file
5232
5233 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5234 "Sort entries on a certain level of an outline tree.
5235 If there is an active region, the entries in the region are sorted.
5236 Else, if the cursor is before the first entry, sort the top-level items.
5237 Else, the children of the entry at point are sorted.
5238
5239 Sorting can be alphabetically, numerically, and by date/time as given by
5240 the first time stamp in the entry. The command prompts for the sorting
5241 type unless it has been given to the function through the SORTING-TYPE
5242 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5243 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5244 called with point at the beginning of the record. It must return either
5245 a string or a number that should serve as the sorting key for that record.
5246
5247 Comparing entries ignores case by default. However, with an optional argument
5248 WITH-CASE, the sorting considers case as well."
5249 (interactive "P")
5250 (let ((case-func (if with-case 'identity 'downcase))
5251 start beg end stars re re2
5252 txt what tmp plain-list-p)
5253 ;; Find beginning and end of region to sort
5254 (cond
5255 ((org-region-active-p)
5256 ;; we will sort the region
5257 (setq end (region-end)
5258 what "region")
5259 (goto-char (region-beginning))
5260 (if (not (org-on-heading-p)) (outline-next-heading))
5261 (setq start (point)))
5262 ((org-at-item-p)
5263 ;; we will sort this plain list
5264 (org-beginning-of-item-list) (setq start (point))
5265 (org-end-of-item-list) (setq end (point))
5266 (goto-char start)
5267 (setq plain-list-p t
5268 what "plain list"))
5269 ((or (org-on-heading-p)
5270 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5271 ;; we will sort the children of the current headline
5272 (org-back-to-heading)
5273 (setq start (point)
5274 end (progn (org-end-of-subtree t t)
5275 (org-back-over-empty-lines)
5276 (point))
5277 what "children")
5278 (goto-char start)
5279 (show-subtree)
5280 (outline-next-heading))
5281 (t
5282 ;; we will sort the top-level entries in this file
5283 (goto-char (point-min))
5284 (or (org-on-heading-p) (outline-next-heading))
5285 (setq start (point) end (point-max) what "top-level")
5286 (goto-char start)
5287 (show-all)))
5288
5289 (setq beg (point))
5290 (if (>= beg end) (error "Nothing to sort"))
5291
5292 (unless plain-list-p
5293 (looking-at "\\(\\*+\\)")
5294 (setq stars (match-string 1)
5295 re (concat "^" (regexp-quote stars) " +")
5296 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5297 txt (buffer-substring beg end))
5298 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5299 (if (and (not (equal stars "*")) (string-match re2 txt))
5300 (error "Region to sort contains a level above the first entry")))
5301
5302 (unless sorting-type
5303 (message
5304 (if plain-list-p
5305 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5306 "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:")
5307 what)
5308 (setq sorting-type (read-char-exclusive))
5309
5310 (and (= (downcase sorting-type) ?f)
5311 (setq getkey-func
5312 (completing-read "Sort using function: "
5313 obarray 'fboundp t nil nil))
5314 (setq getkey-func (intern getkey-func)))
5315
5316 (and (= (downcase sorting-type) ?r)
5317 (setq property
5318 (completing-read "Property: "
5319 (mapcar 'list (org-buffer-property-keys t))
5320 nil t))))
5321
5322 (message "Sorting entries...")
5323
5324 (save-restriction
5325 (narrow-to-region start end)
5326
5327 (let ((dcst (downcase sorting-type))
5328 (now (current-time)))
5329 (sort-subr
5330 (/= dcst sorting-type)
5331 ;; This function moves to the beginning character of the "record" to
5332 ;; be sorted.
5333 (if plain-list-p
5334 (lambda nil
5335 (if (org-at-item-p) t (goto-char (point-max))))
5336 (lambda nil
5337 (if (re-search-forward re nil t)
5338 (goto-char (match-beginning 0))
5339 (goto-char (point-max)))))
5340 ;; This function moves to the last character of the "record" being
5341 ;; sorted.
5342 (if plain-list-p
5343 'org-end-of-item
5344 (lambda nil
5345 (save-match-data
5346 (condition-case nil
5347 (outline-forward-same-level 1)
5348 (error
5349 (goto-char (point-max)))))))
5350
5351 ;; This function returns the value that gets sorted against.
5352 (if plain-list-p
5353 (lambda nil
5354 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5355 (cond
5356 ((= dcst ?n)
5357 (string-to-number (buffer-substring (match-end 0)
5358 (point-at-eol))))
5359 ((= dcst ?a)
5360 (buffer-substring (match-end 0) (point-at-eol)))
5361 ((= dcst ?t)
5362 (if (re-search-forward org-ts-regexp
5363 (point-at-eol) t)
5364 (org-time-string-to-time (match-string 0))
5365 now))
5366 ((= dcst ?f)
5367 (if getkey-func
5368 (progn
5369 (setq tmp (funcall getkey-func))
5370 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5371 tmp)
5372 (error "Invalid key function `%s'" getkey-func)))
5373 (t (error "Invalid sorting type `%c'" sorting-type)))))
5374 (lambda nil
5375 (cond
5376 ((= dcst ?n)
5377 (if (looking-at org-complex-heading-regexp)
5378 (string-to-number (match-string 4))
5379 nil))
5380 ((= dcst ?a)
5381 (if (looking-at org-complex-heading-regexp)
5382 (funcall case-func (match-string 4))
5383 nil))
5384 ((= dcst ?t)
5385 (if (re-search-forward org-ts-regexp
5386 (save-excursion
5387 (forward-line 2)
5388 (point)) t)
5389 (org-time-string-to-time (match-string 0))
5390 now))
5391 ((= dcst ?p)
5392 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5393 (string-to-char (match-string 2))
5394 org-default-priority))
5395 ((= dcst ?r)
5396 (or (org-entry-get nil property) ""))
5397 ((= dcst ?o)
5398 (if (looking-at org-complex-heading-regexp)
5399 (- 9999 (length (member (match-string 2)
5400 org-todo-keywords-1)))))
5401 ((= dcst ?f)
5402 (if getkey-func
5403 (progn
5404 (setq tmp (funcall getkey-func))
5405 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5406 tmp)
5407 (error "Invalid key function `%s'" getkey-func)))
5408 (t (error "Invalid sorting type `%c'" sorting-type)))))
5409 nil
5410 (cond
5411 ((= dcst ?a) 'string<)
5412 ((= dcst ?t) 'time-less-p)
5413 (t nil)))))
5414 (message "Sorting entries...done")))
5415
5416 (defun org-do-sort (table what &optional with-case sorting-type)
5417 "Sort TABLE of WHAT according to SORTING-TYPE.
5418 The user will be prompted for the SORTING-TYPE if the call to this
5419 function does not specify it. WHAT is only for the prompt, to indicate
5420 what is being sorted. The sorting key will be extracted from
5421 the car of the elements of the table.
5422 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5423 (unless sorting-type
5424 (message
5425 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5426 what)
5427 (setq sorting-type (read-char-exclusive)))
5428 (let ((dcst (downcase sorting-type))
5429 extractfun comparefun)
5430 ;; Define the appropriate functions
5431 (cond
5432 ((= dcst ?n)
5433 (setq extractfun 'string-to-number
5434 comparefun (if (= dcst sorting-type) '< '>)))
5435 ((= dcst ?a)
5436 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5437 (lambda(x) (downcase (org-sort-remove-invisible x))))
5438 comparefun (if (= dcst sorting-type)
5439 'string<
5440 (lambda (a b) (and (not (string< a b))
5441 (not (string= a b)))))))
5442 ((= dcst ?t)
5443 (setq extractfun
5444 (lambda (x)
5445 (if (string-match org-ts-regexp x)
5446 (time-to-seconds
5447 (org-time-string-to-time (match-string 0 x)))
5448 0))
5449 comparefun (if (= dcst sorting-type) '< '>)))
5450 (t (error "Invalid sorting type `%c'" sorting-type)))
5451
5452 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5453 table)
5454 (lambda (a b) (funcall comparefun (car a) (car b))))))
5455
5456 ;;; Editing source examples
5457
5458 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5459 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5460 (defvar org-edit-src-force-single-line nil)
5461 (defvar org-edit-src-from-org-mode nil)
5462 (defvar org-edit-src-picture nil)
5463
5464 (define-minor-mode org-exit-edit-mode
5465 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5466
5467 (defun org-edit-src-code ()
5468 "Edit the source code example at point.
5469 An indirect buffer is created, and that buffer is then narrowed to the
5470 example at point and switched to the correct language mode. When done,
5471 exit by killing the buffer with \\[org-edit-src-exit]."
5472 (interactive)
5473 (let ((line (org-current-line))
5474 (case-fold-search t)
5475 (msg (substitute-command-keys
5476 "Edit, then exit with C-c ' (C-c and single quote)"))
5477 (info (org-edit-src-find-region-and-lang))
5478 (org-mode-p (eq major-mode 'org-mode))
5479 beg end lang lang-f single)
5480 (if (not info)
5481 nil
5482 (setq beg (nth 0 info)
5483 end (nth 1 info)
5484 lang (nth 2 info)
5485 single (nth 3 info)
5486 lang-f (intern (concat lang "-mode")))
5487 (unless (functionp lang-f)
5488 (error "No such language mode: %s" lang-f))
5489 (goto-line line)
5490 (if (get-buffer "*Org Edit Src Example*")
5491 (kill-buffer "*Org Edit Src Example*"))
5492 (switch-to-buffer (make-indirect-buffer (current-buffer)
5493 "*Org Edit Src Example*"))
5494 (narrow-to-region beg end)
5495 (remove-text-properties beg end '(display nil invisible nil
5496 intangible nil))
5497 (let ((org-inhibit-startup t))
5498 (funcall lang-f))
5499 (set (make-local-variable 'org-edit-src-force-single-line) single)
5500 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5501 (when org-mode-p
5502 (goto-char (point-min))
5503 (while (re-search-forward "^," nil t)
5504 (replace-match "")))
5505 (goto-line line)
5506 (org-exit-edit-mode)
5507 (org-set-local 'header-line-format msg)
5508 (message "%s" msg)
5509 t)))
5510
5511 (defun org-edit-fixed-width-region ()
5512 "Edit the fixed-width ascii drawing at point.
5513 This must be a region where each line starts with ca colon followed by
5514 a space character.
5515 An indirect buffer is created, and that buffer is then narrowed to the
5516 example at point and switched to artist-mode. When done,
5517 exit by killing the buffer with \\[org-edit-src-exit]."
5518 (interactive)
5519 (let ((line (org-current-line))
5520 (case-fold-search t)
5521 (msg (substitute-command-keys
5522 "Edit, then exit with C-c ' (C-c and single quote)"))
5523 (org-mode-p (eq major-mode 'org-mode))
5524 beg end lang lang-f)
5525 (beginning-of-line 1)
5526 (if (looking-at "[ \t]*[^:\n \t]")
5527 nil
5528 (if (looking-at "[ \t]*\\(\n\\|\\'\\)]")
5529 (setq beg (point) end (match-end 0))
5530 (save-excursion
5531 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5532 (setq beg (point-at-bol 2))
5533 (setq beg (point))))
5534 (save-excursion
5535 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5536 (setq end (1- (match-beginning 0)))
5537 (setq end (point))))
5538 (goto-line line)
5539 (if (get-buffer "*Org Edit Picture*")
5540 (kill-buffer "*Org Edit Picture*"))
5541 (switch-to-buffer (make-indirect-buffer (current-buffer)
5542 "*Org Edit Picture*"))
5543 (narrow-to-region beg end)
5544 (remove-text-properties beg end '(display nil invisible nil
5545 intangible nil))
5546 (when (fboundp 'font-lock-unfontify-region)
5547 (font-lock-unfontify-region (point-min) (point-max)))
5548 (cond
5549 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5550 (fundamental-mode)
5551 (artist-mode 1))
5552 (t (funcall org-edit-fixed-width-region-mode)))
5553 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5554 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5555 (set (make-local-variable 'org-edit-src-picture) t)
5556 (goto-char (point-min))
5557 (while (re-search-forward "^[ \t]*: " nil t)
5558 (replace-match ""))
5559 (goto-line line)
5560 (org-exit-edit-mode)
5561 (org-set-local 'header-line-format msg)
5562 (message "%s" msg)
5563 t))))
5564
5565
5566 (defun org-edit-src-find-region-and-lang ()
5567 "Find the region and language for a local edit.
5568 Return a list with beginning and end of the region, a string representing
5569 the language, a switch telling of the content should be in a single line."
5570 (let ((re-list
5571 (append
5572 org-edit-src-region-extra
5573 '(
5574 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5575 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5576 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5577 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5578 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5579 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5580 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5581 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5582 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5583 ("^#\\+html:" "\n" "html" single-line)
5584 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5585 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5586 ("^#\\+latex:" "\n" "latex" single-line)
5587 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5588 ("^#\\+ascii:" "\n" "ascii" single-line)
5589 )))
5590 (pos (point))
5591 re re1 re2 single beg end lang)
5592 (catch 'exit
5593 (while (setq entry (pop re-list))
5594 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5595 single (nth 3 entry))
5596 (save-excursion
5597 (if (or (looking-at re1)
5598 (re-search-backward re1 nil t))
5599 (progn
5600 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5601 (if (and (re-search-forward re2 nil t)
5602 (>= (match-end 0) pos))
5603 (throw 'exit (list beg (match-beginning 0) lang single))))
5604 (if (or (looking-at re2)
5605 (re-search-forward re2 nil t))
5606 (progn
5607 (setq end (match-beginning 0))
5608 (if (and (re-search-backward re1 nil t)
5609 (<= (match-beginning 0) pos))
5610 (throw 'exit
5611 (list (match-end 0) end
5612 (org-edit-src-get-lang lang) single)))))))))))
5613
5614 (defun org-edit-src-get-lang (lang)
5615 "Extract the src language."
5616 (let ((m (match-string 0)))
5617 (cond
5618 ((stringp lang) lang)
5619 ((integerp lang) (match-string lang))
5620 ((and (eq lang 'lang)
5621 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5622 (match-string 1 m))
5623 ((and (eq lang 'style)
5624 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5625 (match-string 1 m))
5626 (t "fundamental"))))
5627
5628 (defun org-edit-src-exit ()
5629 "Exit special edit and protect problematic lines."
5630 (interactive)
5631 (unless (buffer-base-buffer (current-buffer))
5632 (error "This is not an indirect buffer, something is wrong..."))
5633 (unless (> (point-min) 1)
5634 (error "This buffer is not narrowed, something is wrong..."))
5635 (goto-char (point-min))
5636 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5637 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5638 (when (org-bound-and-true-p org-edit-src-force-single-line)
5639 (goto-char (point-min))
5640 (while (re-search-forward "\n" nil t)
5641 (replace-match " "))
5642 (goto-char (point-min))
5643 (if (looking-at "\\s-*") (replace-match " "))
5644 (if (re-search-forward "\\s-+\\'" nil t)
5645 (replace-match "")))
5646 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5647 (goto-char (point-min))
5648 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5649 (replace-match ",\\1"))
5650 (when font-lock-mode
5651 (font-lock-unfontify-region (point-min) (point-max)))
5652 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5653 (when (org-bound-and-true-p org-edit-src-picture)
5654 (goto-char (point-min))
5655 (while (re-search-forward "^" nil t)
5656 (replace-match ": "))
5657 (when font-lock-mode
5658 (font-lock-unfontify-region (point-min) (point-max)))
5659 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5660 (kill-buffer (current-buffer))
5661 (and (org-mode-p) (org-restart-font-lock)))
5662
5663
5664 ;;; The orgstruct minor mode
5665
5666 ;; Define a minor mode which can be used in other modes in order to
5667 ;; integrate the org-mode structure editing commands.
5668
5669 ;; This is really a hack, because the org-mode structure commands use
5670 ;; keys which normally belong to the major mode. Here is how it
5671 ;; works: The minor mode defines all the keys necessary to operate the
5672 ;; structure commands, but wraps the commands into a function which
5673 ;; tests if the cursor is currently at a headline or a plain list
5674 ;; item. If that is the case, the structure command is used,
5675 ;; temporarily setting many Org-mode variables like regular
5676 ;; expressions for filling etc. However, when any of those keys is
5677 ;; used at a different location, function uses `key-binding' to look
5678 ;; up if the key has an associated command in another currently active
5679 ;; keymap (minor modes, major mode, global), and executes that
5680 ;; command. There might be problems if any of the keys is otherwise
5681 ;; used as a prefix key.
5682
5683 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5684 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5685 ;; addresses this by checking explicitly for both bindings.
5686
5687 (defvar orgstruct-mode-map (make-sparse-keymap)
5688 "Keymap for the minor `orgstruct-mode'.")
5689
5690 (defvar org-local-vars nil
5691 "List of local variables, for use by `orgstruct-mode'")
5692
5693 ;;;###autoload
5694 (define-minor-mode orgstruct-mode
5695 "Toggle the minor more `orgstruct-mode'.
5696 This mode is for using Org-mode structure commands in other modes.
5697 The following key behave as if Org-mode was active, if the cursor
5698 is on a headline, or on a plain list item (both in the definition
5699 of Org-mode).
5700
5701 M-up Move entry/item up
5702 M-down Move entry/item down
5703 M-left Promote
5704 M-right Demote
5705 M-S-up Move entry/item up
5706 M-S-down Move entry/item down
5707 M-S-left Promote subtree
5708 M-S-right Demote subtree
5709 M-q Fill paragraph and items like in Org-mode
5710 C-c ^ Sort entries
5711 C-c - Cycle list bullet
5712 TAB Cycle item visibility
5713 M-RET Insert new heading/item
5714 S-M-RET Insert new TODO heading / Chekbox item
5715 C-c C-c Set tags / toggle checkbox"
5716 nil " OrgStruct" nil
5717 (org-load-modules-maybe)
5718 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5719
5720 ;;;###autoload
5721 (defun turn-on-orgstruct ()
5722 "Unconditionally turn on `orgstruct-mode'."
5723 (orgstruct-mode 1))
5724
5725 ;;;###autoload
5726 (defun turn-on-orgstruct++ ()
5727 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5728 In addition to setting orgstruct-mode, this also exports all indentation and
5729 autofilling variables from org-mode into the buffer. Note that turning
5730 off orgstruct-mode will *not* remove these additional settings."
5731 (orgstruct-mode 1)
5732 (let (var val)
5733 (mapc
5734 (lambda (x)
5735 (when (string-match
5736 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5737 (symbol-name (car x)))
5738 (setq var (car x) val (nth 1 x))
5739 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5740 org-local-vars)))
5741
5742 (defun orgstruct-error ()
5743 "Error when there is no default binding for a structure key."
5744 (interactive)
5745 (error "This key has no function outside structure elements"))
5746
5747 (defun orgstruct-setup ()
5748 "Setup orgstruct keymaps."
5749 (let ((nfunc 0)
5750 (bindings
5751 (list
5752 '([(meta up)] org-metaup)
5753 '([(meta down)] org-metadown)
5754 '([(meta left)] org-metaleft)
5755 '([(meta right)] org-metaright)
5756 '([(meta shift up)] org-shiftmetaup)
5757 '([(meta shift down)] org-shiftmetadown)
5758 '([(meta shift left)] org-shiftmetaleft)
5759 '([(meta shift right)] org-shiftmetaright)
5760 '([(shift up)] org-shiftup)
5761 '([(shift down)] org-shiftdown)
5762 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5763 '("\M-q" fill-paragraph)
5764 '("\C-c^" org-sort)
5765 '("\C-c-" org-cycle-list-bullet)))
5766 elt key fun cmd)
5767 (while (setq elt (pop bindings))
5768 (setq nfunc (1+ nfunc))
5769 (setq key (org-key (car elt))
5770 fun (nth 1 elt)
5771 cmd (orgstruct-make-binding fun nfunc key))
5772 (org-defkey orgstruct-mode-map key cmd))
5773
5774 ;; Special treatment needed for TAB and RET
5775 (org-defkey orgstruct-mode-map [(tab)]
5776 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5777 (org-defkey orgstruct-mode-map "\C-i"
5778 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5779
5780 (org-defkey orgstruct-mode-map "\M-\C-m"
5781 (orgstruct-make-binding 'org-insert-heading 105
5782 "\M-\C-m" [(meta return)]))
5783 (org-defkey orgstruct-mode-map [(meta return)]
5784 (orgstruct-make-binding 'org-insert-heading 106
5785 [(meta return)] "\M-\C-m"))
5786
5787 (org-defkey orgstruct-mode-map [(shift meta return)]
5788 (orgstruct-make-binding 'org-insert-todo-heading 107
5789 [(meta return)] "\M-\C-m"))
5790
5791 (unless org-local-vars
5792 (setq org-local-vars (org-get-local-variables)))
5793
5794 t))
5795
5796 (defun orgstruct-make-binding (fun n &rest keys)
5797 "Create a function for binding in the structure minor mode.
5798 FUN is the command to call inside a table. N is used to create a unique
5799 command name. KEYS are keys that should be checked in for a command
5800 to execute outside of tables."
5801 (eval
5802 (list 'defun
5803 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5804 '(arg)
5805 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5806 "Outside of structure, run the binding of `"
5807 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5808 "'.")
5809 '(interactive "p")
5810 (list 'if
5811 '(org-context-p 'headline 'item)
5812 (list 'org-run-like-in-org-mode (list 'quote fun))
5813 (list 'let '(orgstruct-mode)
5814 (list 'call-interactively
5815 (append '(or)
5816 (mapcar (lambda (k)
5817 (list 'key-binding k))
5818 keys)
5819 '('orgstruct-error))))))))
5820
5821 (defun org-context-p (&rest contexts)
5822 "Check if local context is any of CONTEXTS.
5823 Possible values in the list of contexts are `table', `headline', and `item'."
5824 (let ((pos (point)))
5825 (goto-char (point-at-bol))
5826 (prog1 (or (and (memq 'table contexts)
5827 (looking-at "[ \t]*|"))
5828 (and (memq 'headline contexts)
5829 ;;????????? (looking-at "\\*+"))
5830 (looking-at outline-regexp))
5831 (and (memq 'item contexts)
5832 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5833 (goto-char pos))))
5834
5835 (defun org-get-local-variables ()
5836 "Return a list of all local variables in an org-mode buffer."
5837 (let (varlist)
5838 (with-current-buffer (get-buffer-create "*Org tmp*")
5839 (erase-buffer)
5840 (org-mode)
5841 (setq varlist (buffer-local-variables)))
5842 (kill-buffer "*Org tmp*")
5843 (delq nil
5844 (mapcar
5845 (lambda (x)
5846 (setq x
5847 (if (symbolp x)
5848 (list x)
5849 (list (car x) (list 'quote (cdr x)))))
5850 (if (string-match
5851 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5852 (symbol-name (car x)))
5853 x nil))
5854 varlist))))
5855
5856 ;;;###autoload
5857 (defun org-run-like-in-org-mode (cmd)
5858 (org-load-modules-maybe)
5859 (unless org-local-vars
5860 (setq org-local-vars (org-get-local-variables)))
5861 (eval (list 'let org-local-vars
5862 (list 'call-interactively (list 'quote cmd)))))
5863
5864 ;;;; Archiving
5865
5866 (defun org-get-category (&optional pos)
5867 "Get the category applying to position POS."
5868 (get-text-property (or pos (point)) 'org-category))
5869
5870 (defun org-refresh-category-properties ()
5871 "Refresh category text properties in the buffer."
5872 (let ((def-cat (cond
5873 ((null org-category)
5874 (if buffer-file-name
5875 (file-name-sans-extension
5876 (file-name-nondirectory buffer-file-name))
5877 "???"))
5878 ((symbolp org-category) (symbol-name org-category))
5879 (t org-category)))
5880 beg end cat pos optionp)
5881 (org-unmodified
5882 (save-excursion
5883 (save-restriction
5884 (widen)
5885 (goto-char (point-min))
5886 (put-text-property (point) (point-max) 'org-category def-cat)
5887 (while (re-search-forward
5888 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
5889 (setq pos (match-end 0)
5890 optionp (equal (char-after (match-beginning 0)) ?#)
5891 cat (org-trim (match-string 2)))
5892 (if optionp
5893 (setq beg (point-at-bol) end (point-max))
5894 (org-back-to-heading t)
5895 (setq beg (point) end (org-end-of-subtree t t)))
5896 (put-text-property beg end 'org-category cat)
5897 (goto-char pos)))))))
5898
5899
5900 ;;;; Link Stuff
5901
5902 ;;; Link abbreviations
5903
5904 (defun org-link-expand-abbrev (link)
5905 "Apply replacements as defined in `org-link-abbrev-alist."
5906 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
5907 (let* ((key (match-string 1 link))
5908 (as (or (assoc key org-link-abbrev-alist-local)
5909 (assoc key org-link-abbrev-alist)))
5910 (tag (and (match-end 2) (match-string 3 link)))
5911 rpl)
5912 (if (not as)
5913 link
5914 (setq rpl (cdr as))
5915 (cond
5916 ((symbolp rpl) (funcall rpl tag))
5917 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
5918 (t (concat rpl tag)))))
5919 link))
5920
5921 ;;; Storing and inserting links
5922
5923 (defvar org-insert-link-history nil
5924 "Minibuffer history for links inserted with `org-insert-link'.")
5925
5926 (defvar org-stored-links nil
5927 "Contains the links stored with `org-store-link'.")
5928
5929 (defvar org-store-link-plist nil
5930 "Plist with info about the most recently link created with `org-store-link'.")
5931
5932 (defvar org-link-protocols nil
5933 "Link protocols added to Org-mode using `org-add-link-type'.")
5934
5935 (defvar org-store-link-functions nil
5936 "List of functions that are called to create and store a link.
5937 Each function will be called in turn until one returns a non-nil
5938 value. Each function should check if it is responsible for creating
5939 this link (for example by looking at the major mode).
5940 If not, it must exit and return nil.
5941 If yes, it should return a non-nil value after a calling
5942 `org-store-link-props' with a list of properties and values.
5943 Special properties are:
5944
5945 :type The link prefix. like \"http\". This must be given.
5946 :link The link, like \"http://www.astro.uva.nl/~dominik\".
5947 This is obligatory as well.
5948 :description Optional default description for the second pair
5949 of brackets in an Org-mode link. The user can still change
5950 this when inserting this link into an Org-mode buffer.
5951
5952 In addition to these, any additional properties can be specified
5953 and then used in remember templates.")
5954
5955 (defun org-add-link-type (type &optional follow export)
5956 "Add TYPE to the list of `org-link-types'.
5957 Re-compute all regular expressions depending on `org-link-types'
5958
5959 FOLLOW and EXPORT are two functions.
5960
5961 FOLLOW should take the link path as the single argument and do whatever
5962 is necessary to follow the link, for example find a file or display
5963 a mail message.
5964
5965 EXPORT should format the link path for export to one of the export formats.
5966 It should be a function accepting three arguments:
5967
5968 path the path of the link, the text after the prefix (like \"http:\")
5969 desc the description of the link, if any, nil if there was no descripton
5970 format the export format, a symbol like `html' or `latex'.
5971
5972 The function may use the FORMAT information to return different values
5973 depending on the format. The return value will be put literally into
5974 the exported file.
5975 Org-mode has a built-in default for exporting links. If you are happy with
5976 this default, there is no need to define an export function for the link
5977 type. For a simple example of an export function, see `org-bbdb.el'."
5978 (add-to-list 'org-link-types type t)
5979 (org-make-link-regexps)
5980 (if (assoc type org-link-protocols)
5981 (setcdr (assoc type org-link-protocols) (list follow export))
5982 (push (list type follow export) org-link-protocols)))
5983
5984
5985 ;;;###autoload
5986 (defun org-store-link (arg)
5987 "\\<org-mode-map>Store an org-link to the current location.
5988 This link is added to `org-stored-links' and can later be inserted
5989 into an org-buffer with \\[org-insert-link].
5990
5991 For some link types, a prefix arg is interpreted:
5992 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
5993 For file links, arg negates `org-context-in-file-links'."
5994 (interactive "P")
5995 (org-load-modules-maybe)
5996 (setq org-store-link-plist nil) ; reset
5997 (let (link cpltxt desc description search txt)
5998 (cond
5999
6000 ((run-hook-with-args-until-success 'org-store-link-functions)
6001 (setq link (plist-get org-store-link-plist :link)
6002 desc (or (plist-get org-store-link-plist :description) link)))
6003
6004 ((eq major-mode 'calendar-mode)
6005 (let ((cd (calendar-cursor-to-date)))
6006 (setq link
6007 (format-time-string
6008 (car org-time-stamp-formats)
6009 (apply 'encode-time
6010 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6011 nil nil nil))))
6012 (org-store-link-props :type "calendar" :date cd)))
6013
6014 ((eq major-mode 'w3-mode)
6015 (setq cpltxt (url-view-url t)
6016 link (org-make-link cpltxt))
6017 (org-store-link-props :type "w3" :url (url-view-url t)))
6018
6019 ((eq major-mode 'w3m-mode)
6020 (setq cpltxt (or w3m-current-title w3m-current-url)
6021 link (org-make-link w3m-current-url))
6022 (org-store-link-props :type "w3m" :url (url-view-url t)))
6023
6024 ((setq search (run-hook-with-args-until-success
6025 'org-create-file-search-functions))
6026 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6027 "::" search))
6028 (setq cpltxt (or description link)))
6029
6030 ((eq major-mode 'image-mode)
6031 (setq cpltxt (concat "file:"
6032 (abbreviate-file-name buffer-file-name))
6033 link (org-make-link cpltxt))
6034 (org-store-link-props :type "image" :file buffer-file-name))
6035
6036 ((eq major-mode 'dired-mode)
6037 ;; link to the file in the current line
6038 (setq cpltxt (concat "file:"
6039 (abbreviate-file-name
6040 (expand-file-name
6041 (dired-get-filename nil t))))
6042 link (org-make-link cpltxt)))
6043
6044 ((and buffer-file-name (org-mode-p))
6045 ;; Just link to current headline
6046 (setq cpltxt (concat "file:"
6047 (abbreviate-file-name buffer-file-name)))
6048 ;; Add a context search string
6049 (when (org-xor org-context-in-file-links arg)
6050 ;; Check if we are on a target
6051 (if (org-in-regexp "<<\\(.*?\\)>>")
6052 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6053 (setq txt (cond
6054 ((org-on-heading-p) nil)
6055 ((org-region-active-p)
6056 (buffer-substring (region-beginning) (region-end)))
6057 (t nil)))
6058 (when (or (null txt) (string-match "\\S-" txt))
6059 (setq cpltxt
6060 (concat cpltxt "::"
6061 (condition-case nil
6062 (org-make-org-heading-search-string txt)
6063 (error "")))
6064 desc "NONE"))))
6065 (if (string-match "::\\'" cpltxt)
6066 (setq cpltxt (substring cpltxt 0 -2)))
6067 (setq link (org-make-link cpltxt)))
6068
6069 ((buffer-file-name (buffer-base-buffer))
6070 ;; Just link to this file here.
6071 (setq cpltxt (concat "file:"
6072 (abbreviate-file-name
6073 (buffer-file-name (buffer-base-buffer)))))
6074 ;; Add a context string
6075 (when (org-xor org-context-in-file-links arg)
6076 (setq txt (if (org-region-active-p)
6077 (buffer-substring (region-beginning) (region-end))
6078 (buffer-substring (point-at-bol) (point-at-eol))))
6079 ;; Only use search option if there is some text.
6080 (when (string-match "\\S-" txt)
6081 (setq cpltxt
6082 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6083 desc "NONE")))
6084 (setq link (org-make-link cpltxt)))
6085
6086 ((interactive-p)
6087 (error "Cannot link to a buffer which is not visiting a file"))
6088
6089 (t (setq link nil)))
6090
6091 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6092 (setq link (or link cpltxt)
6093 desc (or desc cpltxt))
6094 (if (equal desc "NONE") (setq desc nil))
6095
6096 (if (and (interactive-p) link)
6097 (progn
6098 (setq org-stored-links
6099 (cons (list link desc) org-stored-links))
6100 (message "Stored: %s" (or desc link)))
6101 (and link (org-make-link-string link desc)))))
6102
6103 (defun org-store-link-props (&rest plist)
6104 "Store link properties, extract names and addresses."
6105 (let (x adr)
6106 (when (setq x (plist-get plist :from))
6107 (setq adr (mail-extract-address-components x))
6108 (plist-put plist :fromname (car adr))
6109 (plist-put plist :fromaddress (nth 1 adr)))
6110 (when (setq x (plist-get plist :to))
6111 (setq adr (mail-extract-address-components x))
6112 (plist-put plist :toname (car adr))
6113 (plist-put plist :toaddress (nth 1 adr))))
6114 (let ((from (plist-get plist :from))
6115 (to (plist-get plist :to)))
6116 (when (and from to org-from-is-user-regexp)
6117 (plist-put plist :fromto
6118 (if (string-match org-from-is-user-regexp from)
6119 (concat "to %t")
6120 (concat "from %f")))))
6121 (setq org-store-link-plist plist))
6122
6123 (defun org-add-link-props (&rest plist)
6124 "Add these properties to the link property list."
6125 (let (key value)
6126 (while plist
6127 (setq key (pop plist) value (pop plist))
6128 (setq org-store-link-plist
6129 (plist-put org-store-link-plist key value)))))
6130
6131 (defun org-email-link-description (&optional fmt)
6132 "Return the description part of an email link.
6133 This takes information from `org-store-link-plist' and formats it
6134 according to FMT (default from `org-email-link-description-format')."
6135 (setq fmt (or fmt org-email-link-description-format))
6136 (let* ((p org-store-link-plist)
6137 (to (plist-get p :toaddress))
6138 (from (plist-get p :fromaddress))
6139 (table
6140 (list
6141 (cons "%c" (plist-get p :fromto))
6142 (cons "%F" (plist-get p :from))
6143 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6144 (cons "%T" (plist-get p :to))
6145 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6146 (cons "%s" (plist-get p :subject))
6147 (cons "%m" (plist-get p :message-id)))))
6148 (when (string-match "%c" fmt)
6149 ;; Check if the user wrote this message
6150 (if (and org-from-is-user-regexp from to
6151 (save-match-data (string-match org-from-is-user-regexp from)))
6152 (setq fmt (replace-match "to %t" t t fmt))
6153 (setq fmt (replace-match "from %f" t t fmt))))
6154 (org-replace-escapes fmt table)))
6155
6156 (defun org-make-org-heading-search-string (&optional string heading)
6157 "Make search string for STRING or current headline."
6158 (interactive)
6159 (let ((s (or string (org-get-heading))))
6160 (unless (and string (not heading))
6161 ;; We are using a headline, clean up garbage in there.
6162 (if (string-match org-todo-regexp s)
6163 (setq s (replace-match "" t t s)))
6164 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6165 (setq s (replace-match "" t t s)))
6166 (setq s (org-trim s))
6167 (if (string-match (concat "^\\(" org-quote-string "\\|"
6168 org-comment-string "\\)") s)
6169 (setq s (replace-match "" t t s)))
6170 (while (string-match org-ts-regexp s)
6171 (setq s (replace-match "" t t s))))
6172 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6173 (setq s (replace-match " " t t s)))
6174 (or string (setq s (concat "*" s))) ; Add * for headlines
6175 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6176
6177 (defun org-make-link (&rest strings)
6178 "Concatenate STRINGS."
6179 (apply 'concat strings))
6180
6181 (defun org-make-link-string (link &optional description)
6182 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6183 (unless (string-match "\\S-" link)
6184 (error "Empty link"))
6185 (when (stringp description)
6186 ;; Remove brackets from the description, they are fatal.
6187 (while (string-match "\\[" description)
6188 (setq description (replace-match "{" t t description)))
6189 (while (string-match "\\]" description)
6190 (setq description (replace-match "}" t t description))))
6191 (when (equal (org-link-escape link) description)
6192 ;; No description needed, it is identical
6193 (setq description nil))
6194 (when (and (not description)
6195 (not (equal link (org-link-escape link))))
6196 (setq description (org-extract-attributes link)))
6197 (concat "[[" (org-link-escape link) "]"
6198 (if description (concat "[" description "]") "")
6199 "]"))
6200
6201 (defconst org-link-escape-chars
6202 '((?\ . "%20")
6203 (?\[ . "%5B")
6204 (?\] . "%5D")
6205 (?\340 . "%E0") ; `a
6206 (?\342 . "%E2") ; ^a
6207 (?\347 . "%E7") ; ,c
6208 (?\350 . "%E8") ; `e
6209 (?\351 . "%E9") ; 'e
6210 (?\352 . "%EA") ; ^e
6211 (?\356 . "%EE") ; ^i
6212 (?\364 . "%F4") ; ^o
6213 (?\371 . "%F9") ; `u
6214 (?\373 . "%FB") ; ^u
6215 (?\; . "%3B")
6216 (?? . "%3F")
6217 (?= . "%3D")
6218 (?+ . "%2B")
6219 )
6220 "Association list of escapes for some characters problematic in links.
6221 This is the list that is used for internal purposes.")
6222
6223 (defconst org-link-escape-chars-browser
6224 '((?\ . "%20")) ; 32 for the SPC char
6225 "Association list of escapes for some characters problematic in links.
6226 This is the list that is used before handing over to the browser.")
6227
6228 (defun org-link-escape (text &optional table)
6229 "Escape charaters in TEXT that are problematic for links."
6230 (setq table (or table org-link-escape-chars))
6231 (when text
6232 (let ((re (mapconcat (lambda (x) (regexp-quote
6233 (char-to-string (car x))))
6234 table "\\|")))
6235 (while (string-match re text)
6236 (setq text
6237 (replace-match
6238 (cdr (assoc (string-to-char (match-string 0 text))
6239 table))
6240 t t text)))
6241 text)))
6242
6243 (defun org-link-unescape (text &optional table)
6244 "Reverse the action of `org-link-escape'."
6245 (setq table (or table org-link-escape-chars))
6246 (when text
6247 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6248 table "\\|")))
6249 (while (string-match re text)
6250 (setq text
6251 (replace-match
6252 (char-to-string (car (rassoc (match-string 0 text) table)))
6253 t t text)))
6254 text)))
6255
6256 (defun org-xor (a b)
6257 "Exclusive or."
6258 (if a (not b) b))
6259
6260 (defun org-get-header (header)
6261 "Find a header field in the current buffer."
6262 (save-excursion
6263 (goto-char (point-min))
6264 (let ((case-fold-search t) s)
6265 (cond
6266 ((eq header 'from)
6267 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6268 (setq s (match-string 1)))
6269 (while (string-match "\"" s)
6270 (setq s (replace-match "" t t s)))
6271 (if (string-match "[<(].*" s)
6272 (setq s (replace-match "" t t s))))
6273 ((eq header 'message-id)
6274 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6275 (setq s (match-string 1))))
6276 ((eq header 'subject)
6277 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6278 (setq s (match-string 1)))))
6279 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6280 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6281 s)))
6282
6283
6284 (defun org-fixup-message-id-for-http (s)
6285 "Replace special characters in a message id, so it can be used in an http query."
6286 (while (string-match "<" s)
6287 (setq s (replace-match "%3C" t t s)))
6288 (while (string-match ">" s)
6289 (setq s (replace-match "%3E" t t s)))
6290 (while (string-match "@" s)
6291 (setq s (replace-match "%40" t t s)))
6292 s)
6293
6294 ;;;###autoload
6295 (defun org-insert-link-global ()
6296 "Insert a link like Org-mode does.
6297 This command can be called in any mode to insert a link in Org-mode syntax."
6298 (interactive)
6299 (org-load-modules-maybe)
6300 (org-run-like-in-org-mode 'org-insert-link))
6301
6302 (defun org-insert-link (&optional complete-file link-location)
6303 "Insert a link. At the prompt, enter the link.
6304
6305 Completion can be used to select a link previously stored with
6306 `org-store-link'. When the empty string is entered (i.e. if you just
6307 press RET at the prompt), the link defaults to the most recently
6308 stored link. As SPC triggers completion in the minibuffer, you need to
6309 use M-SPC or C-q SPC to force the insertion of a space character.
6310
6311 You will also be prompted for a description, and if one is given, it will
6312 be displayed in the buffer instead of the link.
6313
6314 If there is already a link at point, this command will allow you to edit link
6315 and description parts.
6316
6317 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6318 be selected using completion. The path to the file will be relative to the
6319 current directory if the file is in the current directory or a subdirectory.
6320 Otherwise, the link will be the absolute path as completed in the minibuffer
6321 \(i.e. normally ~/path/to/file).
6322
6323 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6324 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6325 of `org-keep-stored-link-after-insertion'.
6326
6327 If `org-make-link-description-function' is non-nil, this function will be
6328 called with the link target, and the result will be the default
6329 link description.
6330
6331 If the LINK-LOCATION parameter is non-nil, this value will be
6332 used as the link location instead of reading one interactively."
6333 (interactive "P")
6334 (let* ((wcf (current-window-configuration))
6335 (region (if (org-region-active-p)
6336 (buffer-substring (region-beginning) (region-end))))
6337 (remove (and region (list (region-beginning) (region-end))))
6338 (desc region)
6339 tmphist ; byte-compile incorrectly complains about this
6340 (link link-location)
6341 entry file)
6342 (cond
6343 (link-location) ; specified by arg, just use it.
6344 ((org-in-regexp org-bracket-link-regexp 1)
6345 ;; We do have a link at point, and we are going to edit it.
6346 (setq remove (list (match-beginning 0) (match-end 0)))
6347 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6348 (setq link (read-string "Link: "
6349 (org-link-unescape
6350 (org-match-string-no-properties 1)))))
6351 ((or (org-in-regexp org-angle-link-re)
6352 (org-in-regexp org-plain-link-re))
6353 ;; Convert to bracket link
6354 (setq remove (list (match-beginning 0) (match-end 0))
6355 link (read-string "Link: "
6356 (org-remove-angle-brackets (match-string 0)))))
6357 ((equal complete-file '(4))
6358 ;; Completing read for file names.
6359 (setq file (read-file-name "File: "))
6360 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6361 (pwd1 (file-name-as-directory (abbreviate-file-name
6362 (expand-file-name ".")))))
6363 (cond
6364 ((equal complete-file '(16))
6365 (setq link (org-make-link
6366 "file:"
6367 (abbreviate-file-name (expand-file-name file)))))
6368 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6369 (setq link (org-make-link "file:" (match-string 1 file))))
6370 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6371 (expand-file-name file))
6372 (setq link (org-make-link
6373 "file:" (match-string 1 (expand-file-name file)))))
6374 (t (setq link (org-make-link "file:" file))))))
6375 (t
6376 ;; Read link, with completion for stored links.
6377 (with-output-to-temp-buffer "*Org Links*"
6378 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6379 (when org-stored-links
6380 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6381 (princ (mapconcat
6382 (lambda (x)
6383 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6384 (reverse org-stored-links) "\n"))))
6385 (let ((cw (selected-window)))
6386 (select-window (get-buffer-window "*Org Links*"))
6387 (shrink-window-if-larger-than-buffer)
6388 (setq truncate-lines t)
6389 (select-window cw))
6390 ;; Fake a link history, containing the stored links.
6391 (setq tmphist (append (mapcar 'car org-stored-links)
6392 org-insert-link-history))
6393 (unwind-protect
6394 (setq link (org-completing-read
6395 "Link: "
6396 (append
6397 (mapcar (lambda (x) (list (concat (car x) ":")))
6398 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6399 (mapcar (lambda (x) (list (concat x ":")))
6400 org-link-types))
6401 nil nil nil
6402 'tmphist
6403 (or (car (car org-stored-links)))))
6404 (set-window-configuration wcf)
6405 (kill-buffer "*Org Links*"))
6406 (setq entry (assoc link org-stored-links))
6407 (or entry (push link org-insert-link-history))
6408 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6409 (not org-keep-stored-link-after-insertion))
6410 (setq org-stored-links (delq (assoc link org-stored-links)
6411 org-stored-links)))
6412 (setq desc (or desc (nth 1 entry)))))
6413
6414 (if (string-match org-plain-link-re link)
6415 ;; URL-like link, normalize the use of angular brackets.
6416 (setq link (org-make-link (org-remove-angle-brackets link))))
6417
6418 ;; Check if we are linking to the current file with a search option
6419 ;; If yes, simplify the link by using only the search option.
6420 (when (and buffer-file-name
6421 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6422 (let* ((path (match-string 1 link))
6423 (case-fold-search nil)
6424 (search (match-string 2 link)))
6425 (save-match-data
6426 (if (equal (file-truename buffer-file-name) (file-truename path))
6427 ;; We are linking to this same file, with a search option
6428 (setq link search)))))
6429
6430 ;; Check if we can/should use a relative path. If yes, simplify the link
6431 (when (string-match "\\<file:\\(.*\\)" link)
6432 (let* ((path (match-string 1 link))
6433 (origpath path)
6434 (case-fold-search nil))
6435 (cond
6436 ((eq org-link-file-path-type 'absolute)
6437 (setq path (abbreviate-file-name (expand-file-name path))))
6438 ((eq org-link-file-path-type 'noabbrev)
6439 (setq path (expand-file-name path)))
6440 ((eq org-link-file-path-type 'relative)
6441 (setq path (file-relative-name path)))
6442 (t
6443 (save-match-data
6444 (if (string-match (concat "^" (regexp-quote
6445 (file-name-as-directory
6446 (expand-file-name "."))))
6447 (expand-file-name path))
6448 ;; We are linking a file with relative path name.
6449 (setq path (substring (expand-file-name path)
6450 (match-end 0)))))))
6451 (setq link (concat "file:" path))
6452 (if (equal desc origpath)
6453 (setq desc path))))
6454
6455 (if org-make-link-description-function
6456 (setq desc (funcall org-make-link-description-function link desc)))
6457
6458 (setq desc (read-string "Description: " desc))
6459 (unless (string-match "\\S-" desc) (setq desc nil))
6460 (if remove (apply 'delete-region remove))
6461 (insert (org-make-link-string link desc))))
6462
6463 (defun org-completing-read (&rest args)
6464 (let ((minibuffer-local-completion-map
6465 (copy-keymap minibuffer-local-completion-map)))
6466 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6467 (apply 'completing-read args)))
6468
6469 (defun org-extract-attributes (s)
6470 "Extract the attributes cookie from a string and set as text property."
6471 (let (a attr (start 0) key value)
6472 (save-match-data
6473 (when (string-match "{{\\([^}]+\\)}}$" s)
6474 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6475 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6476 (setq key (match-string 1 a) value (match-string 2 a)
6477 start (match-end 0)
6478 attr (plist-put attr (intern key) value))))
6479 (org-add-props s nil 'org-attributes attr))
6480 s))
6481
6482 (defun org-attributes-to-string (plist)
6483 "Format a property list into an HTML attribute list."
6484 (let ((s "") key value)
6485 (while plist
6486 (setq key (pop plist) value (pop plist))
6487 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
6488 s))
6489
6490 ;;; Opening/following a link
6491
6492 (defvar org-link-search-failed nil)
6493
6494 (defun org-next-link ()
6495 "Move forward to the next link.
6496 If the link is in hidden text, expose it."
6497 (interactive)
6498 (when (and org-link-search-failed (eq this-command last-command))
6499 (goto-char (point-min))
6500 (message "Link search wrapped back to beginning of buffer"))
6501 (setq org-link-search-failed nil)
6502 (let* ((pos (point))
6503 (ct (org-context))
6504 (a (assoc :link ct)))
6505 (if a (goto-char (nth 2 a)))
6506 (if (re-search-forward org-any-link-re nil t)
6507 (progn
6508 (goto-char (match-beginning 0))
6509 (if (org-invisible-p) (org-show-context)))
6510 (goto-char pos)
6511 (setq org-link-search-failed t)
6512 (error "No further link found"))))
6513
6514 (defun org-previous-link ()
6515 "Move backward to the previous link.
6516 If the link is in hidden text, expose it."
6517 (interactive)
6518 (when (and org-link-search-failed (eq this-command last-command))
6519 (goto-char (point-max))
6520 (message "Link search wrapped back to end of buffer"))
6521 (setq org-link-search-failed nil)
6522 (let* ((pos (point))
6523 (ct (org-context))
6524 (a (assoc :link ct)))
6525 (if a (goto-char (nth 1 a)))
6526 (if (re-search-backward org-any-link-re nil t)
6527 (progn
6528 (goto-char (match-beginning 0))
6529 (if (org-invisible-p) (org-show-context)))
6530 (goto-char pos)
6531 (setq org-link-search-failed t)
6532 (error "No further link found"))))
6533
6534 (defun org-find-file-at-mouse (ev)
6535 "Open file link or URL at mouse."
6536 (interactive "e")
6537 (mouse-set-point ev)
6538 (org-open-at-point 'in-emacs))
6539
6540 (defun org-open-at-mouse (ev)
6541 "Open file link or URL at mouse."
6542 (interactive "e")
6543 (mouse-set-point ev)
6544 (org-open-at-point))
6545
6546 (defvar org-window-config-before-follow-link nil
6547 "The window configuration before following a link.
6548 This is saved in case the need arises to restore it.")
6549
6550 (defvar org-open-link-marker (make-marker)
6551 "Marker pointing to the location where `org-open-at-point; was called.")
6552
6553 ;;;###autoload
6554 (defun org-open-at-point-global ()
6555 "Follow a link like Org-mode does.
6556 This command can be called in any mode to follow a link that has
6557 Org-mode syntax."
6558 (interactive)
6559 (org-run-like-in-org-mode 'org-open-at-point))
6560
6561 ;;;###autoload
6562 (defun org-open-link-from-string (s &optional arg)
6563 "Open a link in the string S, as if it was in Org-mode."
6564 (interactive "sLink: \nP")
6565 (with-temp-buffer
6566 (let ((org-inhibit-startup t))
6567 (org-mode)
6568 (insert s)
6569 (goto-char (point-min))
6570 (org-open-at-point arg))))
6571
6572 (defun org-open-at-point (&optional in-emacs)
6573 "Open link at or after point.
6574 If there is no link at point, this function will search forward up to
6575 the end of the current subtree.
6576 Normally, files will be opened by an appropriate application. If the
6577 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6578 (interactive "P")
6579 (org-load-modules-maybe)
6580 (move-marker org-open-link-marker (point))
6581 (setq org-window-config-before-follow-link (current-window-configuration))
6582 (org-remove-occur-highlights nil nil t)
6583 (if (org-at-timestamp-p t)
6584 (org-follow-timestamp-link)
6585 (let (type path link line search (pos (point)))
6586 (catch 'match
6587 (save-excursion
6588 (skip-chars-forward "^]\n\r")
6589 (when (org-in-regexp org-bracket-link-regexp)
6590 (setq link (org-extract-attributes
6591 (org-link-unescape (org-match-string-no-properties 1))))
6592 (while (string-match " *\n *" link)
6593 (setq link (replace-match " " t t link)))
6594 (setq link (org-link-expand-abbrev link))
6595 (cond
6596 ((or (file-name-absolute-p link)
6597 (string-match "^\\.\\.?/" link))
6598 (setq type "file" path link))
6599 ((string-match org-link-re-with-space2 link)
6600 (setq type (match-string 1 link) path (match-string 2 link)))
6601 (t (setq type "thisfile" path link)))
6602 (throw 'match t)))
6603
6604 (when (get-text-property (point) 'org-linked-text)
6605 (setq type "thisfile"
6606 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6607 (1+ (point)) (point))
6608 path (buffer-substring
6609 (previous-single-property-change pos 'org-linked-text)
6610 (next-single-property-change pos 'org-linked-text)))
6611 (throw 'match t))
6612
6613 (save-excursion
6614 (when (or (org-in-regexp org-angle-link-re)
6615 (org-in-regexp org-plain-link-re))
6616 (setq type (match-string 1) path (match-string 2))
6617 (throw 'match t)))
6618 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6619 (setq type "tree-match"
6620 path (match-string 1))
6621 (throw 'match t))
6622 (save-excursion
6623 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6624 (setq type "tags"
6625 path (match-string 1))
6626 (while (string-match ":" path)
6627 (setq path (replace-match "+" t t path)))
6628 (throw 'match t))))
6629 (unless path
6630 (error "No link found"))
6631 ;; Remove any trailing spaces in path
6632 (if (string-match " +\\'" path)
6633 (setq path (replace-match "" t t path)))
6634
6635 (cond
6636
6637 ((assoc type org-link-protocols)
6638 (funcall (nth 1 (assoc type org-link-protocols)) path))
6639
6640 ((equal type "mailto")
6641 (let ((cmd (car org-link-mailto-program))
6642 (args (cdr org-link-mailto-program)) args1
6643 (address path) (subject "") a)
6644 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6645 (setq address (match-string 1 path)
6646 subject (org-link-escape (match-string 2 path))))
6647 (while args
6648 (cond
6649 ((not (stringp (car args))) (push (pop args) args1))
6650 (t (setq a (pop args))
6651 (if (string-match "%a" a)
6652 (setq a (replace-match address t t a)))
6653 (if (string-match "%s" a)
6654 (setq a (replace-match subject t t a)))
6655 (push a args1))))
6656 (apply cmd (nreverse args1))))
6657
6658 ((member type '("http" "https" "ftp" "news"))
6659 (browse-url (concat type ":" (org-link-escape
6660 path org-link-escape-chars-browser))))
6661
6662 ((member type '("message"))
6663 (browse-url (concat type ":" path)))
6664
6665 ((string= type "tags")
6666 (org-tags-view in-emacs path))
6667 ((string= type "thisfile")
6668 (if in-emacs
6669 (switch-to-buffer-other-window
6670 (org-get-buffer-for-internal-link (current-buffer)))
6671 (org-mark-ring-push))
6672 (let ((cmd `(org-link-search
6673 ,path
6674 ,(cond ((equal in-emacs '(4)) 'occur)
6675 ((equal in-emacs '(16)) 'org-occur)
6676 (t nil))
6677 ,pos)))
6678 (condition-case nil (eval cmd)
6679 (error (progn (widen) (eval cmd))))))
6680
6681 ((string= type "tree-match")
6682 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6683
6684 ((string= type "file")
6685 (if (string-match "::\\([0-9]+\\)\\'" path)
6686 (setq line (string-to-number (match-string 1 path))
6687 path (substring path 0 (match-beginning 0)))
6688 (if (string-match "::\\(.+\\)\\'" path)
6689 (setq search (match-string 1 path)
6690 path (substring path 0 (match-beginning 0)))))
6691 (if (string-match "[*?{]" (file-name-nondirectory path))
6692 (dired path)
6693 (org-open-file path in-emacs line search)))
6694
6695 ((string= type "news")
6696 (require 'org-gnus)
6697 (org-gnus-follow-link path))
6698
6699 ((string= type "shell")
6700 (let ((cmd path))
6701 (if (or (not org-confirm-shell-link-function)
6702 (funcall org-confirm-shell-link-function
6703 (format "Execute \"%s\" in shell? "
6704 (org-add-props cmd nil
6705 'face 'org-warning))))
6706 (progn
6707 (message "Executing %s" cmd)
6708 (shell-command cmd))
6709 (error "Abort"))))
6710
6711 ((string= type "elisp")
6712 (let ((cmd path))
6713 (if (or (not org-confirm-elisp-link-function)
6714 (funcall org-confirm-elisp-link-function
6715 (format "Execute \"%s\" as elisp? "
6716 (org-add-props cmd nil
6717 'face 'org-warning))))
6718 (message "%s => %s" cmd (eval (read cmd)))
6719 (error "Abort"))))
6720
6721 (t
6722 (browse-url-at-point)))))
6723 (move-marker org-open-link-marker nil)
6724 (run-hook-with-args 'org-follow-link-hook))
6725
6726 ;;;; Time estimates
6727
6728 (defun org-get-effort (&optional pom)
6729 "Get the effort estimate for the current entry."
6730 (org-entry-get pom org-effort-property))
6731
6732 ;;; File search
6733
6734 (defvar org-create-file-search-functions nil
6735 "List of functions to construct the right search string for a file link.
6736 These functions are called in turn with point at the location to
6737 which the link should point.
6738
6739 A function in the hook should first test if it would like to
6740 handle this file type, for example by checking the major-mode or
6741 the file extension. If it decides not to handle this file, it
6742 should just return nil to give other functions a chance. If it
6743 does handle the file, it must return the search string to be used
6744 when following the link. The search string will be part of the
6745 file link, given after a double colon, and `org-open-at-point'
6746 will automatically search for it. If special measures must be
6747 taken to make the search successful, another function should be
6748 added to the companion hook `org-execute-file-search-functions',
6749 which see.
6750
6751 A function in this hook may also use `setq' to set the variable
6752 `description' to provide a suggestion for the descriptive text to
6753 be used for this link when it gets inserted into an Org-mode
6754 buffer with \\[org-insert-link].")
6755
6756 (defvar org-execute-file-search-functions nil
6757 "List of functions to execute a file search triggered by a link.
6758
6759 Functions added to this hook must accept a single argument, the
6760 search string that was part of the file link, the part after the
6761 double colon. The function must first check if it would like to
6762 handle this search, for example by checking the major-mode or the
6763 file extension. If it decides not to handle this search, it
6764 should just return nil to give other functions a chance. If it
6765 does handle the search, it must return a non-nil value to keep
6766 other functions from trying.
6767
6768 Each function can access the current prefix argument through the
6769 variable `current-prefix-argument'. Note that a single prefix is
6770 used to force opening a link in Emacs, so it may be good to only
6771 use a numeric or double prefix to guide the search function.
6772
6773 In case this is needed, a function in this hook can also restore
6774 the window configuration before `org-open-at-point' was called using:
6775
6776 (set-window-configuration org-window-config-before-follow-link)")
6777
6778 (defun org-link-search (s &optional type avoid-pos)
6779 "Search for a link search option.
6780 If S is surrounded by forward slashes, it is interpreted as a
6781 regular expression. In org-mode files, this will create an `org-occur'
6782 sparse tree. In ordinary files, `occur' will be used to list matches.
6783 If the current buffer is in `dired-mode', grep will be used to search
6784 in all files. If AVOID-POS is given, ignore matches near that position."
6785 (let ((case-fold-search t)
6786 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6787 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6788 (append '(("") (" ") ("\t") ("\n"))
6789 org-emphasis-alist)
6790 "\\|") "\\)"))
6791 (pos (point))
6792 (pre nil) (post nil)
6793 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6794 (cond
6795 ;; First check if there are any special
6796 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6797 ;; Now try the builtin stuff
6798 ((save-excursion
6799 (goto-char (point-min))
6800 (and
6801 (re-search-forward
6802 (concat "<<" (regexp-quote s0) ">>") nil t)
6803 (setq type 'dedicated
6804 pos (match-beginning 0))))
6805 ;; There is an exact target for this
6806 (goto-char pos))
6807 ((string-match "^/\\(.*\\)/$" s)
6808 ;; A regular expression
6809 (cond
6810 ((org-mode-p)
6811 (org-occur (match-string 1 s)))
6812 ;;((eq major-mode 'dired-mode)
6813 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6814 (t (org-do-occur (match-string 1 s)))))
6815 (t
6816 ;; A normal search strings
6817 (when (equal (string-to-char s) ?*)
6818 ;; Anchor on headlines, post may include tags.
6819 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6820 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6821 s (substring s 1)))
6822 (remove-text-properties
6823 0 (length s)
6824 '(face nil mouse-face nil keymap nil fontified nil) s)
6825 ;; Make a series of regular expressions to find a match
6826 (setq words (org-split-string s "[ \n\r\t]+")
6827
6828 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6829 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6830 "\\)" markers)
6831 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6832 re2a (concat "[ \t\r\n]" re2a_)
6833 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6834 re4 (concat "[^a-zA-Z_]" re4_)
6835
6836 re1 (concat pre re2 post)
6837 re3 (concat pre (if pre re4_ re4) post)
6838 re5 (concat pre ".*" re4)
6839 re2 (concat pre re2)
6840 re2a (concat pre (if pre re2a_ re2a))
6841 re4 (concat pre (if pre re4_ re4))
6842 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6843 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6844 re5 "\\)"
6845 ))
6846 (cond
6847 ((eq type 'org-occur) (org-occur reall))
6848 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6849 (t (goto-char (point-min))
6850 (setq type 'fuzzy)
6851 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
6852 (org-search-not-self 1 re1 nil t)
6853 (org-search-not-self 1 re2 nil t)
6854 (org-search-not-self 1 re2a nil t)
6855 (org-search-not-self 1 re3 nil t)
6856 (org-search-not-self 1 re4 nil t)
6857 (org-search-not-self 1 re5 nil t)
6858 )
6859 (goto-char (match-beginning 1))
6860 (goto-char pos)
6861 (error "No match")))))
6862 (t
6863 ;; Normal string-search
6864 (goto-char (point-min))
6865 (if (search-forward s nil t)
6866 (goto-char (match-beginning 0))
6867 (error "No match"))))
6868 (and (org-mode-p) (org-show-context 'link-search))
6869 type))
6870
6871 (defun org-search-not-self (group &rest args)
6872 "Execute `re-search-forward', but only accept matches that do not
6873 enclose the position of `org-open-link-marker'."
6874 (let ((m org-open-link-marker))
6875 (catch 'exit
6876 (while (apply 're-search-forward args)
6877 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
6878 (goto-char (match-end group))
6879 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
6880 (> (match-beginning 0) (marker-position m))
6881 (< (match-end 0) (marker-position m)))
6882 (save-match-data
6883 (or (not (org-in-regexp
6884 org-bracket-link-analytic-regexp 1))
6885 (not (match-end 4)) ; no description
6886 (and (<= (match-beginning 4) (point))
6887 (>= (match-end 4) (point))))))
6888 (throw 'exit (point))))))))
6889
6890 (defun org-get-buffer-for-internal-link (buffer)
6891 "Return a buffer to be used for displaying the link target of internal links."
6892 (cond
6893 ((not org-display-internal-link-with-indirect-buffer)
6894 buffer)
6895 ((string-match "(Clone)$" (buffer-name buffer))
6896 (message "Buffer is already a clone, not making another one")
6897 ;; we also do not modify visibility in this case
6898 buffer)
6899 (t ; make a new indirect buffer for displaying the link
6900 (let* ((bn (buffer-name buffer))
6901 (ibn (concat bn "(Clone)"))
6902 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
6903 (with-current-buffer ib (org-overview))
6904 ib))))
6905
6906 (defun org-do-occur (regexp &optional cleanup)
6907 "Call the Emacs command `occur'.
6908 If CLEANUP is non-nil, remove the printout of the regular expression
6909 in the *Occur* buffer. This is useful if the regex is long and not useful
6910 to read."
6911 (occur regexp)
6912 (when cleanup
6913 (let ((cwin (selected-window)) win beg end)
6914 (when (setq win (get-buffer-window "*Occur*"))
6915 (select-window win))
6916 (goto-char (point-min))
6917 (when (re-search-forward "match[a-z]+" nil t)
6918 (setq beg (match-end 0))
6919 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
6920 (setq end (1- (match-beginning 0)))))
6921 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
6922 (goto-char (point-min))
6923 (select-window cwin))))
6924
6925 ;;; The mark ring for links jumps
6926
6927 (defvar org-mark-ring nil
6928 "Mark ring for positions before jumps in Org-mode.")
6929 (defvar org-mark-ring-last-goto nil
6930 "Last position in the mark ring used to go back.")
6931 ;; Fill and close the ring
6932 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
6933 (loop for i from 1 to org-mark-ring-length do
6934 (push (make-marker) org-mark-ring))
6935 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
6936 org-mark-ring)
6937
6938 (defun org-mark-ring-push (&optional pos buffer)
6939 "Put the current position or POS into the mark ring and rotate it."
6940 (interactive)
6941 (setq pos (or pos (point)))
6942 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
6943 (move-marker (car org-mark-ring)
6944 (or pos (point))
6945 (or buffer (current-buffer)))
6946 (message "%s"
6947 (substitute-command-keys
6948 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
6949
6950 (defun org-mark-ring-goto (&optional n)
6951 "Jump to the previous position in the mark ring.
6952 With prefix arg N, jump back that many stored positions. When
6953 called several times in succession, walk through the entire ring.
6954 Org-mode commands jumping to a different position in the current file,
6955 or to another Org-mode file, automatically push the old position
6956 onto the ring."
6957 (interactive "p")
6958 (let (p m)
6959 (if (eq last-command this-command)
6960 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
6961 (setq p org-mark-ring))
6962 (setq org-mark-ring-last-goto p)
6963 (setq m (car p))
6964 (switch-to-buffer (marker-buffer m))
6965 (goto-char m)
6966 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
6967
6968 (defun org-remove-angle-brackets (s)
6969 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
6970 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
6971 s)
6972 (defun org-add-angle-brackets (s)
6973 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
6974 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
6975 s)
6976 (defun org-remove-double-quotes (s)
6977 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
6978 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
6979 s)
6980
6981 ;;; Following specific links
6982
6983 (defun org-follow-timestamp-link ()
6984 (cond
6985 ((org-at-date-range-p t)
6986 (let ((org-agenda-start-on-weekday)
6987 (t1 (match-string 1))
6988 (t2 (match-string 2)))
6989 (setq t1 (time-to-days (org-time-string-to-time t1))
6990 t2 (time-to-days (org-time-string-to-time t2)))
6991 (org-agenda-list nil t1 (1+ (- t2 t1)))))
6992 ((org-at-timestamp-p t)
6993 (org-agenda-list nil (time-to-days (org-time-string-to-time
6994 (substring (match-string 1) 0 10)))
6995 1))
6996 (t (error "This should not happen"))))
6997
6998
6999 ;;; Following file links
7000 (defvar org-wait nil)
7001 (defun org-open-file (path &optional in-emacs line search)
7002 "Open the file at PATH.
7003 First, this expands any special file name abbreviations. Then the
7004 configuration variable `org-file-apps' is checked if it contains an
7005 entry for this file type, and if yes, the corresponding command is launched.
7006 If no application is found, Emacs simply visits the file.
7007 With optional argument IN-EMACS, Emacs will visit the file.
7008 Optional LINE specifies a line to go to, optional SEARCH a string to
7009 search for. If LINE or SEARCH is given, the file will always be
7010 opened in Emacs.
7011 If the file does not exist, an error is thrown."
7012 (setq in-emacs (or in-emacs line search))
7013 (let* ((file (if (equal path "")
7014 buffer-file-name
7015 (substitute-in-file-name (expand-file-name path))))
7016 (apps (append org-file-apps (org-default-apps)))
7017 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7018 (dirp (if remp nil (file-directory-p file)))
7019 (file (if (and dirp org-open-directory-means-index-dot-org)
7020 (concat (file-name-as-directory file) "index.org")
7021 file))
7022 (a-m-a-p (assq 'auto-mode apps))
7023 (dfile (downcase file))
7024 (old-buffer (current-buffer))
7025 (old-pos (point))
7026 (old-mode major-mode)
7027 ext cmd)
7028 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7029 (setq ext (match-string 1 dfile))
7030 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7031 (setq ext (match-string 1 dfile))))
7032 (if in-emacs
7033 (setq cmd 'emacs)
7034 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7035 (and dirp (cdr (assoc 'directory apps)))
7036 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7037 'string-match)
7038 (cdr (assoc ext apps))
7039 (cdr (assoc t apps)))))
7040 (when (eq cmd 'default)
7041 (setq cmd (cdr (assoc t apps))))
7042 (when (eq cmd 'mailcap)
7043 (require 'mailcap)
7044 (mailcap-parse-mailcaps)
7045 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7046 (command (mailcap-mime-info mime-type)))
7047 (if (stringp command)
7048 (setq cmd command)
7049 (setq cmd 'emacs))))
7050 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7051 (not (file-exists-p file))
7052 (not org-open-non-existing-files))
7053 (error "No such file: %s" file))
7054 (cond
7055 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7056 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7057 (while (string-match "['\"]%s['\"]" cmd)
7058 (setq cmd (replace-match "%s" t t cmd)))
7059 (while (string-match "%s" cmd)
7060 (setq cmd (replace-match
7061 (save-match-data
7062 (shell-quote-argument
7063 (convert-standard-filename file)))
7064 t t cmd)))
7065 (save-window-excursion
7066 (start-process-shell-command cmd nil cmd)
7067 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7068 ))
7069 ((or (stringp cmd)
7070 (eq cmd 'emacs))
7071 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7072 (widen)
7073 (if line (goto-line line)
7074 (if search (org-link-search search))))
7075 ((consp cmd)
7076 (let ((file (convert-standard-filename file)))
7077 (eval cmd)))
7078 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7079 (and (org-mode-p) (eq old-mode 'org-mode)
7080 (or (not (equal old-buffer (current-buffer)))
7081 (not (equal old-pos (point))))
7082 (org-mark-ring-push old-pos old-buffer))))
7083
7084 (defun org-default-apps ()
7085 "Return the default applications for this operating system."
7086 (cond
7087 ((eq system-type 'darwin)
7088 org-file-apps-defaults-macosx)
7089 ((eq system-type 'windows-nt)
7090 org-file-apps-defaults-windowsnt)
7091 (t org-file-apps-defaults-gnu)))
7092
7093 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7094 "Convert extensions to regular expressions in the cars of LIST.
7095 Also, weed out any non-string entries, because the return value is used
7096 only for regexp matching.
7097 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7098 point to the symbol `emacs', indicating that the file should
7099 be opened in Emacs."
7100 (append
7101 (delq nil
7102 (mapcar (lambda (x)
7103 (if (not (stringp (car x)))
7104 nil
7105 (if (string-match "\\W" (car x))
7106 x
7107 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7108 list))
7109 (if add-auto-mode
7110 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7111
7112 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7113 (defun org-file-remote-p (file)
7114 "Test whether FILE specifies a location on a remote system.
7115 Return non-nil if the location is indeed remote.
7116
7117 For example, the filename \"/user@host:/foo\" specifies a location
7118 on the system \"/user@host:\"."
7119 (cond ((fboundp 'file-remote-p)
7120 (file-remote-p file))
7121 ((fboundp 'tramp-handle-file-remote-p)
7122 (tramp-handle-file-remote-p file))
7123 ((and (boundp 'ange-ftp-name-format)
7124 (string-match (car ange-ftp-name-format) file))
7125 t)
7126 (t nil)))
7127
7128
7129 ;;;; Refiling
7130
7131 (defun org-get-org-file ()
7132 "Read a filename, with default directory `org-directory'."
7133 (let ((default (or org-default-notes-file remember-data-file)))
7134 (read-file-name (format "File name [%s]: " default)
7135 (file-name-as-directory org-directory)
7136 default)))
7137
7138 (defun org-notes-order-reversed-p ()
7139 "Check if the current file should receive notes in reversed order."
7140 (cond
7141 ((not org-reverse-note-order) nil)
7142 ((eq t org-reverse-note-order) t)
7143 ((not (listp org-reverse-note-order)) nil)
7144 (t (catch 'exit
7145 (let ((all org-reverse-note-order)
7146 entry)
7147 (while (setq entry (pop all))
7148 (if (string-match (car entry) buffer-file-name)
7149 (throw 'exit (cdr entry))))
7150 nil)))))
7151
7152 (defvar org-refile-target-table nil
7153 "The list of refile targets, created by `org-refile'.")
7154
7155 (defvar org-agenda-new-buffers nil
7156 "Buffers created to visit agenda files.")
7157
7158 (defun org-get-refile-targets (&optional default-buffer)
7159 "Produce a table with refile targets."
7160 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7161 targets txt re files f desc descre)
7162 (with-current-buffer (or default-buffer (current-buffer))
7163 (while (setq entry (pop entries))
7164 (setq files (car entry) desc (cdr entry))
7165 (cond
7166 ((null files) (setq files (list (current-buffer))))
7167 ((eq files 'org-agenda-files)
7168 (setq files (org-agenda-files 'unrestricted)))
7169 ((and (symbolp files) (fboundp files))
7170 (setq files (funcall files)))
7171 ((and (symbolp files) (boundp files))
7172 (setq files (symbol-value files))))
7173 (if (stringp files) (setq files (list files)))
7174 (cond
7175 ((eq (car desc) :tag)
7176 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7177 ((eq (car desc) :todo)
7178 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7179 ((eq (car desc) :regexp)
7180 (setq descre (cdr desc)))
7181 ((eq (car desc) :level)
7182 (setq descre (concat "^\\*\\{" (number-to-string
7183 (if org-odd-levels-only
7184 (1- (* 2 (cdr desc)))
7185 (cdr desc)))
7186 "\\}[ \t]")))
7187 ((eq (car desc) :maxlevel)
7188 (setq descre (concat "^\\*\\{1," (number-to-string
7189 (if org-odd-levels-only
7190 (1- (* 2 (cdr desc)))
7191 (cdr desc)))
7192 "\\}[ \t]")))
7193 (t (error "Bad refiling target description %s" desc)))
7194 (while (setq f (pop files))
7195 (save-excursion
7196 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7197 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7198 (save-excursion
7199 (save-restriction
7200 (widen)
7201 (goto-char (point-min))
7202 (while (re-search-forward descre nil t)
7203 (goto-char (point-at-bol))
7204 (when (looking-at org-complex-heading-regexp)
7205 (setq txt (org-link-display-format (match-string 4))
7206 re (concat "^" (regexp-quote
7207 (buffer-substring (match-beginning 1)
7208 (match-end 4)))))
7209 (if (match-end 5) (setq re (concat re "[ \t]+"
7210 (regexp-quote
7211 (match-string 5)))))
7212 (setq re (concat re "[ \t]*$"))
7213 (when org-refile-use-outline-path
7214 (setq txt (mapconcat 'org-protect-slash
7215 (append
7216 (if (eq org-refile-use-outline-path 'file)
7217 (list (file-name-nondirectory
7218 (buffer-file-name (buffer-base-buffer))))
7219 (if (eq org-refile-use-outline-path 'full-file-path)
7220 (list (buffer-file-name (buffer-base-buffer)))))
7221 (org-get-outline-path)
7222 (list txt))
7223 "/")))
7224 (push (list txt f re (point)) targets))
7225 (goto-char (point-at-eol))))))))
7226 (nreverse targets))))
7227
7228 (defun org-protect-slash (s)
7229 (while (string-match "/" s)
7230 (setq s (replace-match "\\" t t s)))
7231 s)
7232
7233 (defun org-get-outline-path ()
7234 "Return the outline path to the current entry, as a list."
7235 (let (rtn)
7236 (save-excursion
7237 (while (org-up-heading-safe)
7238 (when (looking-at org-complex-heading-regexp)
7239 (push (org-match-string-no-properties 4) rtn)))
7240 rtn)))
7241
7242 (defvar org-refile-history nil
7243 "History for refiling operations.")
7244
7245 (defun org-refile (&optional goto default-buffer)
7246 "Move the entry at point to another heading.
7247 The list of target headings is compiled using the information in
7248 `org-refile-targets', which see. This list is created before each use
7249 and will therefore always be up-to-date.
7250
7251 At the target location, the entry is filed as a subitem of the target heading.
7252 Depending on `org-reverse-note-order', the new subitem will either be the
7253 first or the last subitem.
7254
7255 With prefix arg GOTO, the command will only visit the target location,
7256 not actually move anything.
7257 With a double prefix `C-u C-u', go to the location where the last refiling
7258 operation has put the subtree."
7259 (interactive "P")
7260 (let* ((cbuf (current-buffer))
7261 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7262 pos it nbuf file re level reversed)
7263 (if (equal goto '(16))
7264 (org-refile-goto-last-stored)
7265 (when (setq it (org-refile-get-location
7266 (if goto "Goto: " "Refile to: ") default-buffer))
7267 (setq file (nth 1 it)
7268 re (nth 2 it)
7269 pos (nth 3 it))
7270 (setq nbuf (or (find-buffer-visiting file)
7271 (find-file-noselect file)))
7272 (if goto
7273 (progn
7274 (switch-to-buffer nbuf)
7275 (goto-char pos)
7276 (org-show-context 'org-goto))
7277 (org-copy-subtree 1 nil t)
7278 (save-excursion
7279 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7280 (find-file-noselect file))))
7281 (setq reversed (org-notes-order-reversed-p))
7282 (save-excursion
7283 (save-restriction
7284 (widen)
7285 (goto-char pos)
7286 (looking-at outline-regexp)
7287 (setq level (org-get-valid-level (funcall outline-level) 1))
7288 (goto-char
7289 (if reversed
7290 (or (outline-next-heading) (point-max))
7291 (or (save-excursion (outline-get-next-sibling))
7292 (org-end-of-subtree t t)
7293 (point-max))))
7294 (if (not (bolp)) (newline))
7295 (bookmark-set "org-refile-last-stored")
7296 (org-paste-subtree level))))
7297 (org-cut-subtree)
7298 (setq org-markers-to-move nil)
7299 (message "Entry refiled to \"%s\"" (car it)))))))
7300
7301 (defun org-refile-goto-last-stored ()
7302 "Go to the location where the last refile was stored."
7303 (interactive)
7304 (bookmark-jump "org-refile-last-stored")
7305 (message "This is the location of the last refile"))
7306
7307 (defun org-refile-get-location (&optional prompt default-buffer)
7308 "Prompt the user for a refile location, using PROMPT."
7309 (let ((org-refile-targets org-refile-targets)
7310 (org-refile-use-outline-path org-refile-use-outline-path))
7311 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7312 (unless org-refile-target-table
7313 (error "No refile targets"))
7314 (let* ((cbuf (current-buffer))
7315 (cfunc (if org-refile-use-outline-path
7316 'org-olpath-completing-read
7317 'completing-read))
7318 (extra (if org-refile-use-outline-path "/" ""))
7319 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7320 (fname (and filename (file-truename filename)))
7321 (tbl (mapcar
7322 (lambda (x)
7323 (if (not (equal fname (file-truename (nth 1 x))))
7324 (cons (concat (car x) extra " ("
7325 (file-name-nondirectory (nth 1 x)) ")")
7326 (cdr x))
7327 (cons (concat (car x) extra) (cdr x))))
7328 org-refile-target-table))
7329 (completion-ignore-case t))
7330 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7331 tbl)))
7332
7333 (defun org-olpath-completing-read (prompt collection &rest args)
7334 "Read an outline path like a file name."
7335 (let ((thetable collection))
7336 (apply
7337 'completing-read prompt
7338 (lambda (string predicate &optional flag)
7339 (let (rtn r s f (l (length string)))
7340 (cond
7341 ((eq flag nil)
7342 ;; try completion
7343 (try-completion string thetable))
7344 ((eq flag t)
7345 ;; all-completions
7346 (setq rtn (all-completions string thetable predicate))
7347 (mapcar
7348 (lambda (x)
7349 (setq r (substring x l))
7350 (if (string-match " ([^)]*)$" x)
7351 (setq f (match-string 0 x))
7352 (setq f ""))
7353 (if (string-match "/" r)
7354 (concat string (substring r 0 (match-end 0)) f)
7355 x))
7356 rtn))
7357 ((eq flag 'lambda)
7358 ;; exact match?
7359 (assoc string thetable)))
7360 ))
7361 args)))
7362
7363 ;;;; Dynamic blocks
7364
7365 (defun org-find-dblock (name)
7366 "Find the first dynamic block with name NAME in the buffer.
7367 If not found, stay at current position and return nil."
7368 (let (pos)
7369 (save-excursion
7370 (goto-char (point-min))
7371 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7372 nil t)
7373 (match-beginning 0))))
7374 (if pos (goto-char pos))
7375 pos))
7376
7377 (defconst org-dblock-start-re
7378 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7379 "Matches the startline of a dynamic block, with parameters.")
7380
7381 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7382 "Matches the end of a dyhamic block.")
7383
7384 (defun org-create-dblock (plist)
7385 "Create a dynamic block section, with parameters taken from PLIST.
7386 PLIST must containe a :name entry which is used as name of the block."
7387 (unless (bolp) (newline))
7388 (let ((name (plist-get plist :name)))
7389 (insert "#+BEGIN: " name)
7390 (while plist
7391 (if (eq (car plist) :name)
7392 (setq plist (cddr plist))
7393 (insert " " (prin1-to-string (pop plist)))))
7394 (insert "\n\n#+END:\n")
7395 (beginning-of-line -2)))
7396
7397 (defun org-prepare-dblock ()
7398 "Prepare dynamic block for refresh.
7399 This empties the block, puts the cursor at the insert position and returns
7400 the property list including an extra property :name with the block name."
7401 (unless (looking-at org-dblock-start-re)
7402 (error "Not at a dynamic block"))
7403 (let* ((begdel (1+ (match-end 0)))
7404 (name (org-no-properties (match-string 1)))
7405 (params (append (list :name name)
7406 (read (concat "(" (match-string 3) ")")))))
7407 (unless (re-search-forward org-dblock-end-re nil t)
7408 (error "Dynamic block not terminated"))
7409 (setq params
7410 (append params
7411 (list :content (buffer-substring
7412 begdel (match-beginning 0)))))
7413 (delete-region begdel (match-beginning 0))
7414 (goto-char begdel)
7415 (open-line 1)
7416 params))
7417
7418 (defun org-map-dblocks (&optional command)
7419 "Apply COMMAND to all dynamic blocks in the current buffer.
7420 If COMMAND is not given, use `org-update-dblock'."
7421 (let ((cmd (or command 'org-update-dblock))
7422 pos)
7423 (save-excursion
7424 (goto-char (point-min))
7425 (while (re-search-forward org-dblock-start-re nil t)
7426 (goto-char (setq pos (match-beginning 0)))
7427 (condition-case nil
7428 (funcall cmd)
7429 (error (message "Error during update of dynamic block")))
7430 (goto-char pos)
7431 (unless (re-search-forward org-dblock-end-re nil t)
7432 (error "Dynamic block not terminated"))))))
7433
7434 (defun org-dblock-update (&optional arg)
7435 "User command for updating dynamic blocks.
7436 Update the dynamic block at point. With prefix ARG, update all dynamic
7437 blocks in the buffer."
7438 (interactive "P")
7439 (if arg
7440 (org-update-all-dblocks)
7441 (or (looking-at org-dblock-start-re)
7442 (org-beginning-of-dblock))
7443 (org-update-dblock)))
7444
7445 (defun org-update-dblock ()
7446 "Update the dynamic block at point
7447 This means to empty the block, parse for parameters and then call
7448 the correct writing function."
7449 (save-window-excursion
7450 (let* ((pos (point))
7451 (line (org-current-line))
7452 (params (org-prepare-dblock))
7453 (name (plist-get params :name))
7454 (cmd (intern (concat "org-dblock-write:" name))))
7455 (message "Updating dynamic block `%s' at line %d..." name line)
7456 (funcall cmd params)
7457 (message "Updating dynamic block `%s' at line %d...done" name line)
7458 (goto-char pos))))
7459
7460 (defun org-beginning-of-dblock ()
7461 "Find the beginning of the dynamic block at point.
7462 Error if there is no scuh block at point."
7463 (let ((pos (point))
7464 beg)
7465 (end-of-line 1)
7466 (if (and (re-search-backward org-dblock-start-re nil t)
7467 (setq beg (match-beginning 0))
7468 (re-search-forward org-dblock-end-re nil t)
7469 (> (match-end 0) pos))
7470 (goto-char beg)
7471 (goto-char pos)
7472 (error "Not in a dynamic block"))))
7473
7474 (defun org-update-all-dblocks ()
7475 "Update all dynamic blocks in the buffer.
7476 This function can be used in a hook."
7477 (when (org-mode-p)
7478 (org-map-dblocks 'org-update-dblock)))
7479
7480
7481 ;;;; Completion
7482
7483 (defconst org-additional-option-like-keywords
7484 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7485 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7486 "BEGIN_EXAMPLE" "END_EXAMPLE"
7487 "BEGIN_QUOTE" "END_QUOTE"
7488 "BEGIN_VERSE" "END_VERSE"
7489 "BEGIN_SRC" "END_SRC"))
7490
7491 (defcustom org-structure-template-alist
7492 '(
7493 ("s" "#+begin_src ?\n\n#+end_src"
7494 "<src lang=\"?\">\n\n</src>")
7495 ("e" "#+begin_example\n?\n#+end_example"
7496 "<example>\n?\n</example>")
7497 ("q" "#+begin_quote\n?\n#+end_quote"
7498 "<quote>\n?\n</quote>")
7499 ("v" "#+begin_verse\n?\n#+end_verse"
7500 "<verse>\n?\n/verse>")
7501 ("l" "#+begin_latex\n?\n#+end_latex"
7502 "<literal style=\"latex\">\n?\n</literal>")
7503 ("L" "#+latex: "
7504 "<literal style=\"latex\">?</literal>")
7505 ("h" "#+begin_html\n?\n#+end_html"
7506 "<literal style=\"html\">\n?\n</literal>")
7507 ("H" "#+html: "
7508 "<literal style=\"html\">?</literal>")
7509 ("a" "#+begin_ascii\n?\n#+end_ascii")
7510 ("A" "#+ascii: ")
7511 ("i" "#+include %file ?"
7512 "<include file=%file markup=\"?\">")
7513 )
7514 "Structure completion elements.
7515 This is a list of abbreviation keys and values. The value gets inserted
7516 it you type @samp{.} followed by the key and then the completion key,
7517 usually `M-TAB'. %file will be replaced by a file name after prompting
7518 for the file uning completion.
7519 There are two templates for each key, the first uses the original Org syntax,
7520 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7521 the default when the /org-mtags.el/ module has been loaded. See also the
7522 variable `org-mtags-prefere-muse-templates'.
7523 This is an experimental feature, it is undecided if it is going to stay in."
7524 :group 'org-completion
7525 :type '(repeat
7526 (string :tag "Key")
7527 (string :tag "Template")
7528 (string :tag "Muse Template")))
7529
7530 (defun org-try-structure-completion ()
7531 "Try to complete a structure template before point.
7532 This looks for strings like \"<e\" on an otherwise empty line and
7533 expands them."
7534 (let ((l (buffer-substring (point-at-bol) (point)))
7535 a)
7536 (when (and (looking-at "[ \t]*$")
7537 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7538 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7539 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7540 (match-beginning 1)) a)
7541 t)))
7542
7543 (defun org-complete-expand-structure-template (start cell)
7544 "Expand a structure template."
7545 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
7546 (rpl (nth (if musep 2 1) cell)))
7547 (delete-region start (point))
7548 (when (string-match "\\`#\\+" rpl)
7549 (cond
7550 ((bolp))
7551 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7552 (delete-region (point-at-bol) (point)))
7553 (t (newline))))
7554 (setq start (point))
7555 (if (string-match "%file" rpl)
7556 (setq rpl (replace-match
7557 (concat
7558 "\""
7559 (save-match-data
7560 (abbreviate-file-name (read-file-name "Include file: ")))
7561 "\"")
7562 t t rpl)))
7563 (insert rpl)
7564 (if (re-search-backward "\\?" start t) (delete-char 1))))
7565
7566
7567 (defun org-complete (&optional arg)
7568 "Perform completion on word at point.
7569 At the beginning of a headline, this completes TODO keywords as given in
7570 `org-todo-keywords'.
7571 If the current word is preceded by a backslash, completes the TeX symbols
7572 that are supported for HTML support.
7573 If the current word is preceded by \"#+\", completes special words for
7574 setting file options.
7575 In the line after \"#+STARTUP:, complete valid keywords.\"
7576 At all other locations, this simply calls the value of
7577 `org-completion-fallback-command'."
7578 (interactive "P")
7579 (org-without-partial-completion
7580 (catch 'exit
7581 (let* ((a nil)
7582 (end (point))
7583 (beg1 (save-excursion
7584 (skip-chars-backward (org-re "[:alnum:]_@"))
7585 (point)))
7586 (beg (save-excursion
7587 (skip-chars-backward "a-zA-Z0-9_:$")
7588 (point)))
7589 (confirm (lambda (x) (stringp (car x))))
7590 (searchhead (equal (char-before beg) ?*))
7591 (struct
7592 (when (and (member (char-before beg1) '(?. ?<))
7593 (setq a (assoc (buffer-substring beg1 (point))
7594 org-structure-template-alist)))
7595 (org-complete-expand-structure-template (1- beg1) a)
7596 (throw 'exit t)))
7597 (tag (and (equal (char-before beg1) ?:)
7598 (equal (char-after (point-at-bol)) ?*)))
7599 (prop (and (equal (char-before beg1) ?:)
7600 (not (equal (char-after (point-at-bol)) ?*))))
7601 (texp (equal (char-before beg) ?\\))
7602 (link (equal (char-before beg) ?\[))
7603 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7604 beg)
7605 "#+"))
7606 (startup (string-match "^#\\+STARTUP:.*"
7607 (buffer-substring (point-at-bol) (point))))
7608 (completion-ignore-case opt)
7609 (type nil)
7610 (tbl nil)
7611 (table (cond
7612 (opt
7613 (setq type :opt)
7614 (require 'org-exp)
7615 (append
7616 (mapcar
7617 (lambda (x)
7618 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7619 (cons (match-string 2 x) (match-string 1 x)))
7620 (org-split-string (org-get-current-options) "\n"))
7621 (mapcar 'list org-additional-option-like-keywords)))
7622 (startup
7623 (setq type :startup)
7624 org-startup-options)
7625 (link (append org-link-abbrev-alist-local
7626 org-link-abbrev-alist))
7627 (texp
7628 (setq type :tex)
7629 org-html-entities)
7630 ((string-match "\\`\\*+[ \t]+\\'"
7631 (buffer-substring (point-at-bol) beg))
7632 (setq type :todo)
7633 (mapcar 'list org-todo-keywords-1))
7634 (searchhead
7635 (setq type :searchhead)
7636 (save-excursion
7637 (goto-char (point-min))
7638 (while (re-search-forward org-todo-line-regexp nil t)
7639 (push (list
7640 (org-make-org-heading-search-string
7641 (match-string 3) t))
7642 tbl)))
7643 tbl)
7644 (tag (setq type :tag beg beg1)
7645 (or org-tag-alist (org-get-buffer-tags)))
7646 (prop (setq type :prop beg beg1)
7647 (mapcar 'list (org-buffer-property-keys nil t t)))
7648 (t (progn
7649 (call-interactively org-completion-fallback-command)
7650 (throw 'exit nil)))))
7651 (pattern (buffer-substring-no-properties beg end))
7652 (completion (try-completion pattern table confirm)))
7653 (cond ((eq completion t)
7654 (if (not (assoc (upcase pattern) table))
7655 (message "Already complete")
7656 (if (and (equal type :opt)
7657 (not (member (car (assoc (upcase pattern) table))
7658 org-additional-option-like-keywords)))
7659 (insert (substring (cdr (assoc (upcase pattern) table))
7660 (length pattern)))
7661 (if (memq type '(:tag :prop)) (insert ":")))))
7662 ((null completion)
7663 (message "Can't find completion for \"%s\"" pattern)
7664 (ding))
7665 ((not (string= pattern completion))
7666 (delete-region beg end)
7667 (if (string-match " +$" completion)
7668 (setq completion (replace-match "" t t completion)))
7669 (insert completion)
7670 (if (get-buffer-window "*Completions*")
7671 (delete-window (get-buffer-window "*Completions*")))
7672 (if (assoc completion table)
7673 (if (eq type :todo) (insert " ")
7674 (if (memq type '(:tag :prop)) (insert ":"))))
7675 (if (and (equal type :opt) (assoc completion table))
7676 (message "%s" (substitute-command-keys
7677 "Press \\[org-complete] again to insert example settings"))))
7678 (t
7679 (message "Making completion list...")
7680 (let ((list (sort (all-completions pattern table confirm)
7681 'string<)))
7682 (with-output-to-temp-buffer "*Completions*"
7683 (condition-case nil
7684 ;; Protection needed for XEmacs and emacs 21
7685 (display-completion-list list pattern)
7686 (error (display-completion-list list)))))
7687 (message "Making completion list...%s" "done")))))))
7688
7689 ;;;; TODO, DEADLINE, Comments
7690
7691 (defun org-toggle-comment ()
7692 "Change the COMMENT state of an entry."
7693 (interactive)
7694 (save-excursion
7695 (org-back-to-heading)
7696 (let (case-fold-search)
7697 (if (looking-at (concat outline-regexp
7698 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7699 (replace-match "" t t nil 1)
7700 (if (looking-at outline-regexp)
7701 (progn
7702 (goto-char (match-end 0))
7703 (insert org-comment-string " ")))))))
7704
7705 (defvar org-last-todo-state-is-todo nil
7706 "This is non-nil when the last TODO state change led to a TODO state.
7707 If the last change removed the TODO tag or switched to DONE, then
7708 this is nil.")
7709
7710 (defvar org-setting-tags nil) ; dynamically skiped
7711
7712 (defun org-parse-local-options (string var)
7713 "Parse STRING for startup setting relevant for variable VAR."
7714 (let ((rtn (symbol-value var))
7715 e opts)
7716 (save-match-data
7717 (if (or (not string) (not (string-match "\\S-" string)))
7718 rtn
7719 (setq opts (delq nil (mapcar (lambda (x)
7720 (setq e (assoc x org-startup-options))
7721 (if (eq (nth 1 e) var) e nil))
7722 (org-split-string string "[ \t]+"))))
7723 (if (not opts)
7724 rtn
7725 (setq rtn nil)
7726 (while (setq e (pop opts))
7727 (if (not (nth 3 e))
7728 (setq rtn (nth 2 e))
7729 (if (not (listp rtn)) (setq rtn nil))
7730 (push (nth 2 e) rtn)))
7731 rtn)))))
7732
7733 (defvar org-blocker-hook nil
7734 "Hook for functions that are allowed to block a state change.
7735
7736 Each function gets as its single argument a property list, see
7737 `org-trigger-hook' for more information about this list.
7738
7739 If any of the functions in this hook returns nil, the state change
7740 is blocked.")
7741
7742 (defvar org-trigger-hook nil
7743 "Hook for functions that are triggered by a state change.
7744
7745 Each function gets as its single argument a property list with at least
7746 the following elements:
7747
7748 (:type type-of-change :position pos-at-entry-start
7749 :from old-state :to new-state)
7750
7751 Depending on the type, more properties may be present.
7752
7753 This mechanism is currently implemented for:
7754
7755 TODO state changes
7756 ------------------
7757 :type todo-state-change
7758 :from previous state (keyword as a string), or nil
7759 :to new state (keyword as a string), or nil")
7760
7761
7762 (defun org-todo (&optional arg)
7763 "Change the TODO state of an item.
7764 The state of an item is given by a keyword at the start of the heading,
7765 like
7766 *** TODO Write paper
7767 *** DONE Call mom
7768
7769 The different keywords are specified in the variable `org-todo-keywords'.
7770 By default the available states are \"TODO\" and \"DONE\".
7771 So for this example: when the item starts with TODO, it is changed to DONE.
7772 When it starts with DONE, the DONE is removed. And when neither TODO nor
7773 DONE are present, add TODO at the beginning of the heading.
7774
7775 With C-u prefix arg, use completion to determine the new state.
7776 With numeric prefix arg, switch to that state.
7777
7778 For calling through lisp, arg is also interpreted in the following way:
7779 'none -> empty state
7780 \"\"(empty string) -> switch to empty state
7781 'done -> switch to DONE
7782 'nextset -> switch to the next set of keywords
7783 'previousset -> switch to the previous set of keywords
7784 \"WAITING\" -> switch to the specified keyword, but only if it
7785 really is a member of `org-todo-keywords'."
7786 (interactive "P")
7787 (save-excursion
7788 (catch 'exit
7789 (org-back-to-heading)
7790 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7791 (or (looking-at (concat " +" org-todo-regexp " *"))
7792 (looking-at " *"))
7793 (let* ((match-data (match-data))
7794 (startpos (point-at-bol))
7795 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7796 (org-log-done org-log-done)
7797 (org-log-repeat org-log-repeat)
7798 (org-todo-log-states org-todo-log-states)
7799 (this (match-string 1))
7800 (hl-pos (match-beginning 0))
7801 (head (org-get-todo-sequence-head this))
7802 (ass (assoc head org-todo-kwd-alist))
7803 (interpret (nth 1 ass))
7804 (done-word (nth 3 ass))
7805 (final-done-word (nth 4 ass))
7806 (last-state (or this ""))
7807 (completion-ignore-case t)
7808 (member (member this org-todo-keywords-1))
7809 (tail (cdr member))
7810 (state (cond
7811 ((and org-todo-key-trigger
7812 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7813 (and (not arg) org-use-fast-todo-selection
7814 (not (eq org-use-fast-todo-selection 'prefix)))))
7815 ;; Use fast selection
7816 (org-fast-todo-selection))
7817 ((and (equal arg '(4))
7818 (or (not org-use-fast-todo-selection)
7819 (not org-todo-key-trigger)))
7820 ;; Read a state with completion
7821 (completing-read "State: " (mapcar (lambda(x) (list x))
7822 org-todo-keywords-1)
7823 nil t))
7824 ((eq arg 'right)
7825 (if this
7826 (if tail (car tail) nil)
7827 (car org-todo-keywords-1)))
7828 ((eq arg 'left)
7829 (if (equal member org-todo-keywords-1)
7830 nil
7831 (if this
7832 (nth (- (length org-todo-keywords-1) (length tail) 2)
7833 org-todo-keywords-1)
7834 (org-last org-todo-keywords-1))))
7835 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7836 (setq arg nil))) ; hack to fall back to cycling
7837 (arg
7838 ;; user or caller requests a specific state
7839 (cond
7840 ((equal arg "") nil)
7841 ((eq arg 'none) nil)
7842 ((eq arg 'done) (or done-word (car org-done-keywords)))
7843 ((eq arg 'nextset)
7844 (or (car (cdr (member head org-todo-heads)))
7845 (car org-todo-heads)))
7846 ((eq arg 'previousset)
7847 (let ((org-todo-heads (reverse org-todo-heads)))
7848 (or (car (cdr (member head org-todo-heads)))
7849 (car org-todo-heads))))
7850 ((car (member arg org-todo-keywords-1)))
7851 ((nth (1- (prefix-numeric-value arg))
7852 org-todo-keywords-1))))
7853 ((null member) (or head (car org-todo-keywords-1)))
7854 ((equal this final-done-word) nil) ;; -> make empty
7855 ((null tail) nil) ;; -> first entry
7856 ((eq interpret 'sequence)
7857 (car tail))
7858 ((memq interpret '(type priority))
7859 (if (eq this-command last-command)
7860 (car tail)
7861 (if (> (length tail) 0)
7862 (or done-word (car org-done-keywords))
7863 nil)))
7864 (t nil)))
7865 (next (if state (concat " " state " ") " "))
7866 (change-plist (list :type 'todo-state-change :from this :to state
7867 :position startpos))
7868 dolog now-done-p)
7869 (when org-blocker-hook
7870 (unless (save-excursion
7871 (save-match-data
7872 (run-hook-with-args-until-failure
7873 'org-blocker-hook change-plist)))
7874 (if (interactive-p)
7875 (error "TODO state change from %s to %s blocked" this state)
7876 ;; fail silently
7877 (message "TODO state change from %s to %s blocked" this state)
7878 (throw 'exit nil))))
7879 (store-match-data match-data)
7880 (replace-match next t t)
7881 (unless (pos-visible-in-window-p hl-pos)
7882 (message "TODO state changed to %s" (org-trim next)))
7883 (unless head
7884 (setq head (org-get-todo-sequence-head state)
7885 ass (assoc head org-todo-kwd-alist)
7886 interpret (nth 1 ass)
7887 done-word (nth 3 ass)
7888 final-done-word (nth 4 ass)))
7889 (when (memq arg '(nextset previousset))
7890 (message "Keyword-Set %d/%d: %s"
7891 (- (length org-todo-sets) -1
7892 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7893 (length org-todo-sets)
7894 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7895 (setq org-last-todo-state-is-todo
7896 (not (member state org-done-keywords)))
7897 (setq now-done-p (and (member state org-done-keywords)
7898 (not (member this org-done-keywords))))
7899 (and logging (org-local-logging logging))
7900 (when (and (or org-todo-log-states org-log-done)
7901 (not (memq arg '(nextset previousset))))
7902 ;; we need to look at recording a time and note
7903 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7904 (nth 2 (assoc this org-todo-log-states))))
7905 (when (and state
7906 (member state org-not-done-keywords)
7907 (not (member this org-not-done-keywords)))
7908 ;; This is now a todo state and was not one before
7909 ;; If there was a CLOSED time stamp, get rid of it.
7910 (org-add-planning-info nil nil 'closed))
7911 (when (and now-done-p org-log-done)
7912 ;; It is now done, and it was not done before
7913 (org-add-planning-info 'closed (org-current-time))
7914 (if (and (not dolog) (eq 'note org-log-done))
7915 (org-add-log-setup 'done state 'findpos 'note)))
7916 (when (and state dolog)
7917 ;; This is a non-nil state, and we need to log it
7918 (org-add-log-setup 'state state 'findpos dolog)))
7919 ;; Fixup tag positioning
7920 (org-todo-trigger-tag-changes state)
7921 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7922 (when org-provide-todo-statistics
7923 (org-update-parent-todo-statistics))
7924 (run-hooks 'org-after-todo-state-change-hook)
7925 (if (and arg (not (member state org-done-keywords)))
7926 (setq head (org-get-todo-sequence-head state)))
7927 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7928 ;; Do we need to trigger a repeat?
7929 (when now-done-p (org-auto-repeat-maybe state))
7930 ;; Fixup cursor location if close to the keyword
7931 (if (and (outline-on-heading-p)
7932 (not (bolp))
7933 (save-excursion (beginning-of-line 1)
7934 (looking-at org-todo-line-regexp))
7935 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7936 (progn
7937 (goto-char (or (match-end 2) (match-end 1)))
7938 (just-one-space)))
7939 (when org-trigger-hook
7940 (save-excursion
7941 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7942
7943 (defun org-update-parent-todo-statistics ()
7944 "Update any statistics cookie in the parent of the current headline."
7945 (interactive)
7946 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
7947 level (cnt-all 0) (cnt-done 0) is-percent kwd)
7948 (catch 'exit
7949 (save-excursion
7950 (setq level (org-up-heading-safe))
7951 (unless (and level
7952 (re-search-forward box-re (point-at-eol) t))
7953 (throw 'exit nil))
7954 (setq is-percent (match-end 2))
7955 (save-match-data
7956 (unless (outline-next-heading) (throw 'exit nil))
7957 (while (looking-at org-todo-line-regexp)
7958 (setq kwd (match-string 2))
7959 (and kwd (setq cnt-all (1+ cnt-all)))
7960 (and (member kwd org-done-keywords)
7961 (setq cnt-done (1+ cnt-done)))
7962 (condition-case nil
7963 (org-forward-same-level 1)
7964 (error (end-of-line 1)))))
7965 (replace-match
7966 (if is-percent
7967 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
7968 (format "[%d/%d]" cnt-done cnt-all)))
7969 (run-hook-with-args 'org-after-todo-statistics-hook
7970 cnt-done (- cnt-all cnt-done))))))
7971
7972 (defvar org-after-todo-statistics-hook nil
7973 "Hook that is called after a TODO statistics cookie has been updated.
7974 Each function is called with two arguments: the number of not-done entries
7975 and the number of done entries.
7976
7977 For example, the following function, when added to this hook, will switch
7978 an entry to DONE when all children are done, and back to TODO when new
7979 entries are set to a TODO status. Note that this hook is only called
7980 when there is a statistics cookie in the headline!
7981
7982 (defun org-summary-todo (n-done n-not-done)
7983 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
7984 (let (org-log-done org-log-states) ; turn off logging
7985 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
7986 ")
7987
7988 (defun org-todo-trigger-tag-changes (state)
7989 "Apply the changes defined in `org-todo-state-tags-triggers'."
7990 (let ((l org-todo-state-tags-triggers)
7991 changes)
7992 (when (or (not state) (equal state ""))
7993 (setq changes (append changes (cdr (assoc "" l)))))
7994 (when (and (stringp state) (> (length state) 0))
7995 (setq changes (append changes (cdr (assoc state l)))))
7996 (when (member state org-not-done-keywords)
7997 (setq changes (append changes (cdr (assoc 'todo l)))))
7998 (when (member state org-done-keywords)
7999 (setq changes (append changes (cdr (assoc 'done l)))))
8000 (dolist (c changes)
8001 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8002
8003 (defun org-local-logging (value)
8004 "Get logging settings from a property VALUE."
8005 (let* (words w a)
8006 ;; directly set the variables, they are already local.
8007 (setq org-log-done nil
8008 org-log-repeat nil
8009 org-todo-log-states nil)
8010 (setq words (org-split-string value))
8011 (while (setq w (pop words))
8012 (cond
8013 ((setq a (assoc w org-startup-options))
8014 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8015 (set (nth 1 a) (nth 2 a))))
8016 ((setq a (org-extract-log-state-settings w))
8017 (and (member (car a) org-todo-keywords-1)
8018 (push a org-todo-log-states)))))))
8019
8020 (defun org-get-todo-sequence-head (kwd)
8021 "Return the head of the TODO sequence to which KWD belongs.
8022 If KWD is not set, check if there is a text property remembering the
8023 right sequence."
8024 (let (p)
8025 (cond
8026 ((not kwd)
8027 (or (get-text-property (point-at-bol) 'org-todo-head)
8028 (progn
8029 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8030 nil (point-at-eol)))
8031 (get-text-property p 'org-todo-head))))
8032 ((not (member kwd org-todo-keywords-1))
8033 (car org-todo-keywords-1))
8034 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8035
8036 (defun org-fast-todo-selection ()
8037 "Fast TODO keyword selection with single keys.
8038 Returns the new TODO keyword, or nil if no state change should occur."
8039 (let* ((fulltable org-todo-key-alist)
8040 (done-keywords org-done-keywords) ;; needed for the faces.
8041 (maxlen (apply 'max (mapcar
8042 (lambda (x)
8043 (if (stringp (car x)) (string-width (car x)) 0))
8044 fulltable)))
8045 (expert nil)
8046 (fwidth (+ maxlen 3 1 3))
8047 (ncol (/ (- (window-width) 4) fwidth))
8048 tg cnt e c tbl
8049 groups ingroup)
8050 (save-window-excursion
8051 (if expert
8052 (set-buffer (get-buffer-create " *Org todo*"))
8053 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8054 (erase-buffer)
8055 (org-set-local 'org-done-keywords done-keywords)
8056 (setq tbl fulltable cnt 0)
8057 (while (setq e (pop tbl))
8058 (cond
8059 ((equal e '(:startgroup))
8060 (push '() groups) (setq ingroup t)
8061 (when (not (= cnt 0))
8062 (setq cnt 0)
8063 (insert "\n"))
8064 (insert "{ "))
8065 ((equal e '(:endgroup))
8066 (setq ingroup nil cnt 0)
8067 (insert "}\n"))
8068 (t
8069 (setq tg (car e) c (cdr e))
8070 (if ingroup (push tg (car groups)))
8071 (setq tg (org-add-props tg nil 'face
8072 (org-get-todo-face tg)))
8073 (if (and (= cnt 0) (not ingroup)) (insert " "))
8074 (insert "[" c "] " tg (make-string
8075 (- fwidth 4 (length tg)) ?\ ))
8076 (when (= (setq cnt (1+ cnt)) ncol)
8077 (insert "\n")
8078 (if ingroup (insert " "))
8079 (setq cnt 0)))))
8080 (insert "\n")
8081 (goto-char (point-min))
8082 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8083 (fit-window-to-buffer))
8084 (message "[a-z..]:Set [SPC]:clear")
8085 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8086 (cond
8087 ((or (= c ?\C-g)
8088 (and (= c ?q) (not (rassoc c fulltable))))
8089 (setq quit-flag t))
8090 ((= c ?\ ) nil)
8091 ((setq e (rassoc c fulltable) tg (car e))
8092 tg)
8093 (t (setq quit-flag t))))))
8094
8095 (defun org-entry-is-todo-p ()
8096 (member (org-get-todo-state) org-not-done-keywords))
8097
8098 (defun org-entry-is-done-p ()
8099 (member (org-get-todo-state) org-done-keywords))
8100
8101 (defun org-get-todo-state ()
8102 (save-excursion
8103 (org-back-to-heading t)
8104 (and (looking-at org-todo-line-regexp)
8105 (match-end 2)
8106 (match-string 2))))
8107
8108 (defun org-at-date-range-p (&optional inactive-ok)
8109 "Is the cursor inside a date range?"
8110 (interactive)
8111 (save-excursion
8112 (catch 'exit
8113 (let ((pos (point)))
8114 (skip-chars-backward "^[<\r\n")
8115 (skip-chars-backward "<[")
8116 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8117 (>= (match-end 0) pos)
8118 (throw 'exit t))
8119 (skip-chars-backward "^<[\r\n")
8120 (skip-chars-backward "<[")
8121 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8122 (>= (match-end 0) pos)
8123 (throw 'exit t)))
8124 nil)))
8125
8126 (defun org-get-repeat ()
8127 "Check if there is a deadline/schedule with repeater in this entry."
8128 (save-match-data
8129 (save-excursion
8130 (org-back-to-heading t)
8131 (if (re-search-forward
8132 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8133 (match-string 1)))))
8134
8135 (defvar org-last-changed-timestamp)
8136 (defvar org-last-inserted-timestamp)
8137 (defvar org-log-post-message)
8138 (defvar org-log-note-purpose)
8139 (defvar org-log-note-how)
8140 (defvar org-log-note-extra)
8141 (defun org-auto-repeat-maybe (done-word)
8142 "Check if the current headline contains a repeated deadline/schedule.
8143 If yes, set TODO state back to what it was and change the base date
8144 of repeating deadline/scheduled time stamps to new date.
8145 This function is run automatically after each state change to a DONE state."
8146 ;; last-state is dynamically scoped into this function
8147 (let* ((repeat (org-get-repeat))
8148 (aa (assoc last-state org-todo-kwd-alist))
8149 (interpret (nth 1 aa))
8150 (head (nth 2 aa))
8151 (whata '(("d" . day) ("m" . month) ("y" . year)))
8152 (msg "Entry repeats: ")
8153 (org-log-done nil)
8154 (org-todo-log-states nil)
8155 (nshiftmax 10) (nshift 0)
8156 re type n what ts mb0 time)
8157 (when repeat
8158 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8159 (org-todo (if (eq interpret 'type) last-state head))
8160 (when org-log-repeat
8161 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8162 (memq 'org-add-log-note post-command-hook))
8163 ;; OK, we are already setup for some record
8164 (if (eq org-log-repeat 'note)
8165 ;; make sure we take a note, not only a time stamp
8166 (setq org-log-note-how 'note))
8167 ;; Set up for taking a record
8168 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8169 'findpos org-log-repeat)))
8170 (org-back-to-heading t)
8171 (org-add-planning-info nil nil 'closed)
8172 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8173 org-deadline-time-regexp "\\)\\|\\("
8174 org-ts-regexp "\\)"))
8175 (while (re-search-forward
8176 re (save-excursion (outline-next-heading) (point)) t)
8177 (setq type (if (match-end 1) org-scheduled-string
8178 (if (match-end 3) org-deadline-string "Plain:"))
8179 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8180 mb0 (match-beginning 0))
8181 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8182 (setq n (string-to-number (match-string 2 ts))
8183 what (match-string 3 ts))
8184 (if (equal what "w") (setq n (* n 7) what "d"))
8185 ;; Preparation, see if we need to modify the start date for the change
8186 (when (match-end 1)
8187 (setq time (save-match-data (org-time-string-to-time ts)))
8188 (cond
8189 ((equal (match-string 1 ts) ".")
8190 ;; Shift starting date to today
8191 (org-timestamp-change
8192 (- (time-to-days (current-time)) (time-to-days time))
8193 'day))
8194 ((equal (match-string 1 ts) "+")
8195 (while (or (= nshift 0)
8196 (<= (time-to-days time) (time-to-days (current-time))))
8197 (when (= (incf nshift) nshiftmax)
8198 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8199 (error "Abort")))
8200 (org-timestamp-change n (cdr (assoc what whata)))
8201 (org-at-timestamp-p t)
8202 (setq ts (match-string 1))
8203 (setq time (save-match-data (org-time-string-to-time ts))))
8204 (org-timestamp-change (- n) (cdr (assoc what whata)))
8205 ;; rematch, so that we have everything in place for the real shift
8206 (org-at-timestamp-p t)
8207 (setq ts (match-string 1))
8208 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8209 (org-timestamp-change n (cdr (assoc what whata)))
8210 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8211 (setq org-log-post-message msg)
8212 (message "%s" msg))))
8213
8214 (defun org-show-todo-tree (arg)
8215 "Make a compact tree which shows all headlines marked with TODO.
8216 The tree will show the lines where the regexp matches, and all higher
8217 headlines above the match.
8218 With a \\[universal-argument] prefix, also show the DONE entries.
8219 With a numeric prefix N, construct a sparse tree for the Nth element
8220 of `org-todo-keywords-1'."
8221 (interactive "P")
8222 (let ((case-fold-search nil)
8223 (kwd-re
8224 (cond ((null arg) org-not-done-regexp)
8225 ((equal arg '(4))
8226 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8227 (mapcar 'list org-todo-keywords-1))))
8228 (concat "\\("
8229 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8230 "\\)\\>")))
8231 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8232 (regexp-quote (nth (1- (prefix-numeric-value arg))
8233 org-todo-keywords-1)))
8234 (t (error "Invalid prefix argument: %s" arg)))))
8235 (message "%d TODO entries found"
8236 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8237
8238 (defun org-deadline (&optional remove time)
8239 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8240 With argument REMOVE, remove any deadline from the item.
8241 When TIME is set, it should be an internal time specification, and the
8242 scheduling will use the corresponding date."
8243 (interactive "P")
8244 (if remove
8245 (progn
8246 (org-remove-timestamp-with-keyword org-deadline-string)
8247 (message "Item no longer has a deadline."))
8248 (if (org-get-repeat)
8249 (error "Cannot change deadline on task with repeater, please do that by hand")
8250 (org-add-planning-info 'deadline time 'closed)
8251 (message "Deadline on %s" org-last-inserted-timestamp))))
8252
8253 (defun org-schedule (&optional remove time)
8254 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8255 With argument REMOVE, remove any scheduling date from the item.
8256 When TIME is set, it should be an internal time specification, and the
8257 scheduling will use the corresponding date."
8258 (interactive "P")
8259 (if remove
8260 (progn
8261 (org-remove-timestamp-with-keyword org-scheduled-string)
8262 (message "Item is no longer scheduled."))
8263 (if (org-get-repeat)
8264 (error "Cannot reschedule task with repeater, please do that by hand")
8265 (org-add-planning-info 'scheduled time 'closed)
8266 (message "Scheduled to %s" org-last-inserted-timestamp))))
8267
8268 (defun org-remove-timestamp-with-keyword (keyword)
8269 "Remove all time stamps with KEYWORD in the current entry."
8270 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8271 beg)
8272 (save-excursion
8273 (org-back-to-heading t)
8274 (setq beg (point))
8275 (org-end-of-subtree t t)
8276 (while (re-search-backward re beg t)
8277 (replace-match "")
8278 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8279 (equal (char-before) ?\ ))
8280 (backward-delete-char 1)
8281 (if (string-match "^[ \t]*$" (buffer-substring
8282 (point-at-bol) (point-at-eol)))
8283 (delete-region (point-at-bol)
8284 (min (point-max) (1+ (point-at-eol))))))))))
8285
8286 (defun org-add-planning-info (what &optional time &rest remove)
8287 "Insert new timestamp with keyword in the line directly after the headline.
8288 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8289 If non is given, the user is prompted for a date.
8290 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8291 be removed."
8292 (interactive)
8293 (let (org-time-was-given org-end-time-was-given ts
8294 end default-time default-input)
8295
8296 (when (and (not time) (memq what '(scheduled deadline)))
8297 ;; Try to get a default date/time from existing timestamp
8298 (save-excursion
8299 (org-back-to-heading t)
8300 (setq end (save-excursion (outline-next-heading) (point)))
8301 (when (re-search-forward (if (eq what 'scheduled)
8302 org-scheduled-time-regexp
8303 org-deadline-time-regexp)
8304 end t)
8305 (setq ts (match-string 1)
8306 default-time
8307 (apply 'encode-time (org-parse-time-string ts))
8308 default-input (and ts (org-get-compact-tod ts))))))
8309 (when what
8310 ;; If necessary, get the time from the user
8311 (setq time (or time (org-read-date nil 'to-time nil nil
8312 default-time default-input))))
8313
8314 (when (and org-insert-labeled-timestamps-at-point
8315 (member what '(scheduled deadline)))
8316 (insert
8317 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8318 (org-insert-time-stamp time org-time-was-given
8319 nil nil nil (list org-end-time-was-given))
8320 (setq what nil))
8321 (save-excursion
8322 (save-restriction
8323 (let (col list elt ts buffer-invisibility-spec)
8324 (org-back-to-heading t)
8325 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8326 (goto-char (match-end 1))
8327 (setq col (current-column))
8328 (goto-char (match-end 0))
8329 (if (eobp) (insert "\n") (forward-char 1))
8330 (if (and (not (looking-at outline-regexp))
8331 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8332 "[^\r\n]*"))
8333 (not (equal (match-string 1) org-clock-string)))
8334 (narrow-to-region (match-beginning 0) (match-end 0))
8335 (insert-before-markers "\n")
8336 (backward-char 1)
8337 (narrow-to-region (point) (point))
8338 (and org-adapt-indentation (org-indent-to-column col)))
8339 ;; Check if we have to remove something.
8340 (setq list (cons what remove))
8341 (while list
8342 (setq elt (pop list))
8343 (goto-char (point-min))
8344 (when (or (and (eq elt 'scheduled)
8345 (re-search-forward org-scheduled-time-regexp nil t))
8346 (and (eq elt 'deadline)
8347 (re-search-forward org-deadline-time-regexp nil t))
8348 (and (eq elt 'closed)
8349 (re-search-forward org-closed-time-regexp nil t)))
8350 (replace-match "")
8351 (if (looking-at "--+<[^>]+>") (replace-match ""))
8352 (if (looking-at " +") (replace-match ""))))
8353 (goto-char (point-max))
8354 (when what
8355 (insert
8356 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8357 (cond ((eq what 'scheduled) org-scheduled-string)
8358 ((eq what 'deadline) org-deadline-string)
8359 ((eq what 'closed) org-closed-string))
8360 " ")
8361 (setq ts (org-insert-time-stamp
8362 time
8363 (or org-time-was-given
8364 (and (eq what 'closed) org-log-done-with-time))
8365 (eq what 'closed)
8366 nil nil (list org-end-time-was-given)))
8367 (end-of-line 1))
8368 (goto-char (point-min))
8369 (widen)
8370 (if (and (looking-at "[ \t]+\n")
8371 (equal (char-before) ?\n))
8372 (delete-region (1- (point)) (point-at-eol)))
8373 ts)))))
8374
8375 (defvar org-log-note-marker (make-marker))
8376 (defvar org-log-note-purpose nil)
8377 (defvar org-log-note-state nil)
8378 (defvar org-log-note-how nil)
8379 (defvar org-log-note-extra nil)
8380 (defvar org-log-note-window-configuration nil)
8381 (defvar org-log-note-return-to (make-marker))
8382 (defvar org-log-post-message nil
8383 "Message to be displayed after a log note has been stored.
8384 The auto-repeater uses this.")
8385
8386 (defun org-add-note ()
8387 "Add a note to the current entry.
8388 This is done in the same way as adding a state change note."
8389 (interactive)
8390 (org-add-log-setup 'note nil 'findpos nil))
8391
8392 (defvar org-property-end-re)
8393 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8394 "Set up the post command hook to take a note.
8395 If this is about to TODO state change, the new state is expected in STATE.
8396 When FINDPOS is non-nil, find the correct position for the note in
8397 the current entry. If not, assume that it can be inserted at point.
8398 HOW is an indicator what kind of note should be created.
8399 EXTRA is additional text that will be inserted into the notes buffer."
8400 (save-restriction
8401 (save-excursion
8402 (when findpos
8403 (org-back-to-heading t)
8404 (narrow-to-region (point) (save-excursion
8405 (outline-next-heading) (point)))
8406 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8407 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8408 "[^\r\n]*\\)?"))
8409 (goto-char (match-end 0))
8410 (when (and org-log-state-notes-insert-after-drawers
8411 (save-excursion
8412 (forward-line) (looking-at org-drawer-regexp)))
8413 (progn (forward-line)
8414 (while (looking-at org-drawer-regexp)
8415 (goto-char (match-end 0))
8416 (re-search-forward org-property-end-re (point-max) t)
8417 (forward-line))
8418 (forward-line -1)))
8419 (unless org-log-states-order-reversed
8420 (and (= (char-after) ?\n) (forward-char 1))
8421 (org-skip-over-state-notes)
8422 (skip-chars-backward " \t\n\r")))
8423 (move-marker org-log-note-marker (point))
8424 (setq org-log-note-purpose purpose
8425 org-log-note-state state
8426 org-log-note-how how
8427 org-log-note-extra extra)
8428 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8429
8430 (defun org-skip-over-state-notes ()
8431 "Skip past the list of State notes in an entry."
8432 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8433 (while (looking-at "[ \t]*- State")
8434 (condition-case nil
8435 (org-next-item)
8436 (error (org-end-of-item)))))
8437
8438 (defun org-add-log-note (&optional purpose)
8439 "Pop up a window for taking a note, and add this note later at point."
8440 (remove-hook 'post-command-hook 'org-add-log-note)
8441 (setq org-log-note-window-configuration (current-window-configuration))
8442 (delete-other-windows)
8443 (move-marker org-log-note-return-to (point))
8444 (switch-to-buffer (marker-buffer org-log-note-marker))
8445 (goto-char org-log-note-marker)
8446 (org-switch-to-buffer-other-window "*Org Note*")
8447 (erase-buffer)
8448 (if (memq org-log-note-how '(time state))
8449 (let (current-prefix-arg) (org-store-log-note))
8450 (let ((org-inhibit-startup t)) (org-mode))
8451 (insert (format "# Insert note for %s.
8452 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8453 (cond
8454 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8455 ((eq org-log-note-purpose 'done) "closed todo item")
8456 ((eq org-log-note-purpose 'state)
8457 (format "state change to \"%s\"" org-log-note-state))
8458 ((eq org-log-note-purpose 'note)
8459 "this entry")
8460 (t (error "This should not happen")))))
8461 (if org-log-note-extra (insert org-log-note-extra))
8462 (org-set-local 'org-finish-function 'org-store-log-note)))
8463
8464 (defvar org-note-abort nil) ; dynamically scoped
8465 (defun org-store-log-note ()
8466 "Finish taking a log note, and insert it to where it belongs."
8467 (let ((txt (buffer-string))
8468 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8469 lines ind)
8470 (kill-buffer (current-buffer))
8471 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8472 (setq txt (replace-match "" t t txt)))
8473 (if (string-match "\\s-+\\'" txt)
8474 (setq txt (replace-match "" t t txt)))
8475 (setq lines (org-split-string txt "\n"))
8476 (when (and note (string-match "\\S-" note))
8477 (setq note
8478 (org-replace-escapes
8479 note
8480 (list (cons "%u" (user-login-name))
8481 (cons "%U" user-full-name)
8482 (cons "%t" (format-time-string
8483 (org-time-stamp-format 'long 'inactive)
8484 (current-time)))
8485 (cons "%s" (if org-log-note-state
8486 (concat "\"" org-log-note-state "\"")
8487 "")))))
8488 (if lines (setq note (concat note " \\\\")))
8489 (push note lines))
8490 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8491 (when lines
8492 (save-excursion
8493 (set-buffer (marker-buffer org-log-note-marker))
8494 (save-excursion
8495 (goto-char org-log-note-marker)
8496 (move-marker org-log-note-marker nil)
8497 (end-of-line 1)
8498 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8499 (indent-relative nil)
8500 (insert "- " (pop lines))
8501 (org-indent-line-function)
8502 (beginning-of-line 1)
8503 (looking-at "[ \t]*")
8504 (setq ind (concat (match-string 0) " "))
8505 (end-of-line 1)
8506 (while lines (insert "\n" ind (pop lines)))))))
8507 (set-window-configuration org-log-note-window-configuration)
8508 (with-current-buffer (marker-buffer org-log-note-return-to)
8509 (goto-char org-log-note-return-to))
8510 (move-marker org-log-note-return-to nil)
8511 (and org-log-post-message (message "%s" org-log-post-message)))
8512
8513 (defun org-sparse-tree (&optional arg)
8514 "Create a sparse tree, prompt for the details.
8515 This command can create sparse trees. You first need to select the type
8516 of match used to create the tree:
8517
8518 t Show entries with a specific TODO keyword.
8519 T Show entries selected by a tags match.
8520 p Enter a property name and its value (both with completion on existing
8521 names/values) and show entries with that property.
8522 r Show entries matching a regular expression
8523 d Show deadlines due within `org-deadline-warning-days'."
8524 (interactive "P")
8525 (let (ans kwd value)
8526 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8527 (setq ans (read-char-exclusive))
8528 (cond
8529 ((equal ans ?d)
8530 (call-interactively 'org-check-deadlines))
8531 ((equal ans ?b)
8532 (call-interactively 'org-check-before-date))
8533 ((equal ans ?t)
8534 (org-show-todo-tree '(4)))
8535 ((equal ans ?T)
8536 (call-interactively 'org-tags-sparse-tree))
8537 ((member ans '(?p ?P))
8538 (setq kwd (completing-read "Property: "
8539 (mapcar 'list (org-buffer-property-keys))))
8540 (setq value (completing-read "Value: "
8541 (mapcar 'list (org-property-values kwd))))
8542 (unless (string-match "\\`{.*}\\'" value)
8543 (setq value (concat "\"" value "\"")))
8544 (org-tags-sparse-tree arg (concat kwd "=" value)))
8545 ((member ans '(?r ?R ?/))
8546 (call-interactively 'org-occur))
8547 (t (error "No such sparse tree command \"%c\"" ans)))))
8548
8549 (defvar org-occur-highlights nil
8550 "List of overlays used for occur matches.")
8551 (make-variable-buffer-local 'org-occur-highlights)
8552 (defvar org-occur-parameters nil
8553 "Parameters of the active org-occur calls.
8554 This is a list, each call to org-occur pushes as cons cell,
8555 containing the regular expression and the callback, onto the list.
8556 The list can contain several entries if `org-occur' has been called
8557 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8558 will only contain one set of parameters. When the highlights are
8559 removed (for example with `C-c C-c', or with the next edit (depending
8560 on `org-remove-highlights-with-change'), this variable is emptied
8561 as well.")
8562 (make-variable-buffer-local 'org-occur-parameters)
8563
8564 (defun org-occur (regexp &optional keep-previous callback)
8565 "Make a compact tree which shows all matches of REGEXP.
8566 The tree will show the lines where the regexp matches, and all higher
8567 headlines above the match. It will also show the heading after the match,
8568 to make sure editing the matching entry is easy.
8569 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8570 call to `org-occur' will be kept, to allow stacking of calls to this
8571 command.
8572 If CALLBACK is non-nil, it is a function which is called to confirm
8573 that the match should indeed be shown."
8574 (interactive "sRegexp: \nP")
8575 (unless keep-previous
8576 (org-remove-occur-highlights nil nil t))
8577 (push (cons regexp callback) org-occur-parameters)
8578 (let ((cnt 0))
8579 (save-excursion
8580 (goto-char (point-min))
8581 (if (or (not keep-previous) ; do not want to keep
8582 (not org-occur-highlights)) ; no previous matches
8583 ;; hide everything
8584 (org-overview))
8585 (while (re-search-forward regexp nil t)
8586 (when (or (not callback)
8587 (save-match-data (funcall callback)))
8588 (setq cnt (1+ cnt))
8589 (when org-highlight-sparse-tree-matches
8590 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8591 (org-show-context 'occur-tree))))
8592 (when org-remove-highlights-with-change
8593 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8594 nil 'local))
8595 (unless org-sparse-tree-open-archived-trees
8596 (org-hide-archived-subtrees (point-min) (point-max)))
8597 (run-hooks 'org-occur-hook)
8598 (if (interactive-p)
8599 (message "%d match(es) for regexp %s" cnt regexp))
8600 cnt))
8601
8602 (defun org-show-context (&optional key)
8603 "Make sure point and context and visible.
8604 How much context is shown depends upon the variables
8605 `org-show-hierarchy-above', `org-show-following-heading'. and
8606 `org-show-siblings'."
8607 (let ((heading-p (org-on-heading-p t))
8608 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8609 (following-p (org-get-alist-option org-show-following-heading key))
8610 (entry-p (org-get-alist-option org-show-entry-below key))
8611 (siblings-p (org-get-alist-option org-show-siblings key)))
8612 (catch 'exit
8613 ;; Show heading or entry text
8614 (if (and heading-p (not entry-p))
8615 (org-flag-heading nil) ; only show the heading
8616 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8617 (org-show-hidden-entry))) ; show entire entry
8618 (when following-p
8619 ;; Show next sibling, or heading below text
8620 (save-excursion
8621 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8622 (org-flag-heading nil))))
8623 (when siblings-p (org-show-siblings))
8624 (when hierarchy-p
8625 ;; show all higher headings, possibly with siblings
8626 (save-excursion
8627 (while (and (condition-case nil
8628 (progn (org-up-heading-all 1) t)
8629 (error nil))
8630 (not (bobp)))
8631 (org-flag-heading nil)
8632 (when siblings-p (org-show-siblings))))))))
8633
8634 (defun org-reveal (&optional siblings)
8635 "Show current entry, hierarchy above it, and the following headline.
8636 This can be used to show a consistent set of context around locations
8637 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8638 not t for the search context.
8639
8640 With optional argument SIBLINGS, on each level of the hierarchy all
8641 siblings are shown. This repairs the tree structure to what it would
8642 look like when opened with hierarchical calls to `org-cycle'."
8643 (interactive "P")
8644 (let ((org-show-hierarchy-above t)
8645 (org-show-following-heading t)
8646 (org-show-siblings (if siblings t org-show-siblings)))
8647 (org-show-context nil)))
8648
8649 (defun org-highlight-new-match (beg end)
8650 "Highlight from BEG to END and mark the highlight is an occur headline."
8651 (let ((ov (org-make-overlay beg end)))
8652 (org-overlay-put ov 'face 'secondary-selection)
8653 (push ov org-occur-highlights)))
8654
8655 (defun org-remove-occur-highlights (&optional beg end noremove)
8656 "Remove the occur highlights from the buffer.
8657 BEG and END are ignored. If NOREMOVE is nil, remove this function
8658 from the `before-change-functions' in the current buffer."
8659 (interactive)
8660 (unless org-inhibit-highlight-removal
8661 (mapc 'org-delete-overlay org-occur-highlights)
8662 (setq org-occur-highlights nil)
8663 (setq org-occur-parameters nil)
8664 (unless noremove
8665 (remove-hook 'before-change-functions
8666 'org-remove-occur-highlights 'local))))
8667
8668 ;;;; Priorities
8669
8670 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8671 "Regular expression matching the priority indicator.")
8672
8673 (defvar org-remove-priority-next-time nil)
8674
8675 (defun org-priority-up ()
8676 "Increase the priority of the current item."
8677 (interactive)
8678 (org-priority 'up))
8679
8680 (defun org-priority-down ()
8681 "Decrease the priority of the current item."
8682 (interactive)
8683 (org-priority 'down))
8684
8685 (defun org-priority (&optional action)
8686 "Change the priority of an item by ARG.
8687 ACTION can be `set', `up', `down', or a character."
8688 (interactive)
8689 (setq action (or action 'set))
8690 (let (current new news have remove)
8691 (save-excursion
8692 (org-back-to-heading)
8693 (if (looking-at org-priority-regexp)
8694 (setq current (string-to-char (match-string 2))
8695 have t)
8696 (setq current org-default-priority))
8697 (cond
8698 ((or (eq action 'set)
8699 (if (featurep 'xemacs) (characterp action) (integerp action)))
8700 (if (not (eq action 'set))
8701 (setq new action)
8702 (message "Priority %c-%c, SPC to remove: "
8703 org-highest-priority org-lowest-priority)
8704 (setq new (read-char-exclusive)))
8705 (if (and (= (upcase org-highest-priority) org-highest-priority)
8706 (= (upcase org-lowest-priority) org-lowest-priority))
8707 (setq new (upcase new)))
8708 (cond ((equal new ?\ ) (setq remove t))
8709 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8710 (error "Priority must be between `%c' and `%c'"
8711 org-highest-priority org-lowest-priority))))
8712 ((eq action 'up)
8713 (if (and (not have) (eq last-command this-command))
8714 (setq new org-lowest-priority)
8715 (setq new (if (and org-priority-start-cycle-with-default (not have))
8716 org-default-priority (1- current)))))
8717 ((eq action 'down)
8718 (if (and (not have) (eq last-command this-command))
8719 (setq new org-highest-priority)
8720 (setq new (if (and org-priority-start-cycle-with-default (not have))
8721 org-default-priority (1+ current)))))
8722 (t (error "Invalid action")))
8723 (if (or (< (upcase new) org-highest-priority)
8724 (> (upcase new) org-lowest-priority))
8725 (setq remove t))
8726 (setq news (format "%c" new))
8727 (if have
8728 (if remove
8729 (replace-match "" t t nil 1)
8730 (replace-match news t t nil 2))
8731 (if remove
8732 (error "No priority cookie found in line")
8733 (looking-at org-todo-line-regexp)
8734 (if (match-end 2)
8735 (progn
8736 (goto-char (match-end 2))
8737 (insert " [#" news "]"))
8738 (goto-char (match-beginning 3))
8739 (insert "[#" news "] ")))))
8740 (org-preserve-lc (org-set-tags nil 'align))
8741 (if remove
8742 (message "Priority removed")
8743 (message "Priority of current item set to %s" news))))
8744
8745
8746 (defun org-get-priority (s)
8747 "Find priority cookie and return priority."
8748 (save-match-data
8749 (if (not (string-match org-priority-regexp s))
8750 (* 1000 (- org-lowest-priority org-default-priority))
8751 (* 1000 (- org-lowest-priority
8752 (string-to-char (match-string 2 s)))))))
8753
8754 ;;;; Tags
8755
8756 (defvar org-agenda-archives-mode)
8757 (defun org-scan-tags (action matcher &optional todo-only)
8758 "Scan headline tags with inheritance and produce output ACTION.
8759
8760 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
8761 or `agenda' to produce an entry list for an agenda view. It can also be
8762 a Lisp form or a function that should be called at each matched headline, in
8763 this case the return value is a list of all return values from these calls.
8764
8765 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
8766 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
8767 only lines with a TODO keyword are included in the output."
8768 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8769 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8770 (org-re
8771 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8772 (props (list 'face 'default
8773 'done-face 'org-done
8774 'undone-face 'default
8775 'mouse-face 'highlight
8776 'org-not-done-regexp org-not-done-regexp
8777 'org-todo-regexp org-todo-regexp
8778 'keymap org-agenda-keymap
8779 'help-echo
8780 (format "mouse-2 or RET jump to org file %s"
8781 (abbreviate-file-name
8782 (or (buffer-file-name (buffer-base-buffer))
8783 (buffer-name (buffer-base-buffer)))))))
8784 (case-fold-search nil)
8785 lspos tags tags-list
8786 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
8787 (llast 0) rtn rtn1 level category i txt
8788 todo marker entry priority)
8789 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
8790 (setq action (list 'lambda nil action)))
8791 (save-excursion
8792 (goto-char (point-min))
8793 (when (eq action 'sparse-tree)
8794 (org-overview)
8795 (org-remove-occur-highlights))
8796 (while (re-search-forward re nil t)
8797 (catch :skip
8798 (setq todo (if (match-end 1) (match-string 2))
8799 tags (if (match-end 4) (match-string 4)))
8800 (goto-char (setq lspos (1+ (match-beginning 0))))
8801 (setq level (org-reduced-level (funcall outline-level))
8802 category (org-get-category))
8803 (setq i llast llast level)
8804 ;; remove tag lists from same and sublevels
8805 (while (>= i level)
8806 (when (setq entry (assoc i tags-alist))
8807 (setq tags-alist (delete entry tags-alist)))
8808 (setq i (1- i)))
8809 ;; add the next tags
8810 (when tags
8811 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8812 tags-alist
8813 (cons (cons level tags) tags-alist)))
8814 ;; compile tags for current headline
8815 (setq tags-list
8816 (if org-use-tag-inheritance
8817 (apply 'append (mapcar 'cdr tags-alist))
8818 tags))
8819 (when (and tags org-use-tag-inheritance
8820 (not (eq t org-use-tag-inheritance)))
8821 ;; selective inheritance, remove uninherited ones
8822 (setcdr (car tags-alist)
8823 (org-remove-uniherited-tags (cdar tags-alist))))
8824 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8825 (let ((case-fold-search t)) (eval matcher))
8826 (or
8827 (not (member org-archive-tag tags-list))
8828 ;; we have an archive tag, should we use this anyway?
8829 (or (not org-agenda-skip-archived-trees)
8830 (and (eq action 'agenda) org-agenda-archives-mode))))
8831 (unless (eq action 'sparse-tree) (org-agenda-skip))
8832
8833 ;; select this headline
8834
8835 (cond
8836 ((eq action 'sparse-tree)
8837 (and org-highlight-sparse-tree-matches
8838 (org-get-heading) (match-end 0)
8839 (org-highlight-new-match
8840 (match-beginning 0) (match-beginning 1)))
8841 (org-show-context 'tags-tree))
8842 ((eq action 'agenda)
8843 (setq txt (org-format-agenda-item
8844 ""
8845 (concat
8846 (if org-tags-match-list-sublevels
8847 (make-string (1- level) ?.) "")
8848 (org-get-heading))
8849 category tags-list)
8850 priority (org-get-priority txt))
8851 (goto-char lspos)
8852 (setq marker (org-agenda-new-marker))
8853 (org-add-props txt props
8854 'org-marker marker 'org-hd-marker marker 'org-category category
8855 'priority priority 'type "tagsmatch")
8856 (push txt rtn))
8857 ((functionp action)
8858 (save-excursion
8859 (setq rtn1 (funcall action))
8860 (push rtn1 rtn))
8861 (goto-char (point-at-eol)))
8862 (t (error "Invalid action")))
8863
8864 ;; if we are to skip sublevels, jump to end of subtree
8865 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8866 (when (and (eq action 'sparse-tree)
8867 (not org-sparse-tree-open-archived-trees))
8868 (org-hide-archived-subtrees (point-min) (point-max)))
8869 (nreverse rtn)))
8870
8871 (defun org-remove-uniherited-tags (tags)
8872 "Remove all tags that are not inherited from the list TAGS."
8873 (cond
8874 ((eq org-use-tag-inheritance t) tags)
8875 ((not org-use-tag-inheritance) nil)
8876 ((stringp org-use-tag-inheritance)
8877 (delq nil (mapcar
8878 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8879 tags)))
8880 ((listp org-use-tag-inheritance)
8881 (delq nil (mapcar
8882 (lambda (x) (if (member x org-use-tag-inheritance) x nil))
8883 tags)))))
8884
8885 (defvar todo-only) ;; dynamically scoped
8886
8887 (defun org-tags-sparse-tree (&optional todo-only match)
8888 "Create a sparse tree according to tags string MATCH.
8889 MATCH can contain positive and negative selection of tags, like
8890 \"+WORK+URGENT-WITHBOSS\".
8891 If optional argument TODO_ONLY is non-nil, only select lines that are
8892 also TODO lines."
8893 (interactive "P")
8894 (org-prepare-agenda-buffers (list (current-buffer)))
8895 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8896
8897 (defvar org-cached-props nil)
8898 (defun org-cached-entry-get (pom property)
8899 (if (or (eq t org-use-property-inheritance)
8900 (and (stringp org-use-property-inheritance)
8901 (string-match org-use-property-inheritance property))
8902 (and (listp org-use-property-inheritance)
8903 (member property org-use-property-inheritance)))
8904 ;; Caching is not possible, check it directly
8905 (org-entry-get pom property 'inherit)
8906 ;; Get all properties, so that we can do complicated checks easily
8907 (cdr (assoc property (or org-cached-props
8908 (setq org-cached-props
8909 (org-entry-properties pom)))))))
8910
8911 (defun org-global-tags-completion-table (&optional files)
8912 "Return the list of all tags in all agenda buffer/files."
8913 (save-excursion
8914 (org-uniquify
8915 (delq nil
8916 (apply 'append
8917 (mapcar
8918 (lambda (file)
8919 (set-buffer (find-file-noselect file))
8920 (append (org-get-buffer-tags)
8921 (mapcar (lambda (x) (if (stringp (car-safe x))
8922 (list (car-safe x)) nil))
8923 org-tag-alist)))
8924 (if (and files (car files))
8925 files
8926 (org-agenda-files))))))))
8927
8928 (defun org-make-tags-matcher (match)
8929 "Create the TAGS//TODO matcher form for the selection string MATCH."
8930 ;; todo-only is scoped dynamically into this function, and the function
8931 ;; may change it it the matcher asksk for it.
8932 (unless match
8933 ;; Get a new match request, with completion
8934 (let ((org-last-tags-completion-table
8935 (org-global-tags-completion-table)))
8936 (setq match (completing-read
8937 "Match: " 'org-tags-completion-function nil nil nil
8938 'org-tags-history))))
8939
8940 ;; Parse the string and create a lisp form
8941 (let ((match0 match)
8942 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8943 minus tag mm
8944 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8945 orterms term orlist re-p str-p level-p level-op time-p
8946 prop-p pn pv po cat-p gv)
8947 (if (string-match "/+" match)
8948 ;; match contains also a todo-matching request
8949 (progn
8950 (setq tagsmatch (substring match 0 (match-beginning 0))
8951 todomatch (substring match (match-end 0)))
8952 (if (string-match "^!" todomatch)
8953 (setq todo-only t todomatch (substring todomatch 1)))
8954 (if (string-match "^\\s-*$" todomatch)
8955 (setq todomatch nil)))
8956 ;; only matching tags
8957 (setq tagsmatch match todomatch nil))
8958
8959 ;; Make the tags matcher
8960 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8961 (setq tagsmatcher t)
8962 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8963 (while (setq term (pop orterms))
8964 (while (and (equal (substring term -1) "\\") orterms)
8965 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8966 (while (string-match re term)
8967 (setq minus (and (match-end 1)
8968 (equal (match-string 1 term) "-"))
8969 tag (match-string 2 term)
8970 re-p (equal (string-to-char tag) ?{)
8971 level-p (match-end 4)
8972 prop-p (match-end 5)
8973 mm (cond
8974 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8975 (level-p
8976 (setq level-op (org-op-to-function (match-string 3 term)))
8977 `(,level-op level ,(string-to-number
8978 (match-string 4 term))))
8979 (prop-p
8980 (setq pn (match-string 5 term)
8981 po (match-string 6 term)
8982 pv (match-string 7 term)
8983 cat-p (equal pn "CATEGORY")
8984 re-p (equal (string-to-char pv) ?{)
8985 str-p (equal (string-to-char pv) ?\")
8986 time-p (save-match-data (string-match "^\"<.*>\"$" pv))
8987 pv (if (or re-p str-p) (substring pv 1 -1) pv))
8988 (if time-p (setq pv (org-matcher-time pv)))
8989 (setq po (org-op-to-function po (if time-p 'time str-p)))
8990 (if (equal pn "CATEGORY")
8991 (setq gv '(get-text-property (point) 'org-category))
8992 (setq gv `(org-cached-entry-get nil ,pn)))
8993 (if re-p
8994 (if (eq po 'org<>)
8995 `(not (string-match ,pv (or ,gv "")))
8996 `(string-match ,pv (or ,gv "")))
8997 (if str-p
8998 `(,po (or ,gv "") ,pv)
8999 `(,po (string-to-number (or ,gv ""))
9000 ,(string-to-number pv) ))))
9001 (t `(member ,(downcase tag) tags-list)))
9002 mm (if minus (list 'not mm) mm)
9003 term (substring term (match-end 0)))
9004 (push mm tagsmatcher))
9005 (push (if (> (length tagsmatcher) 1)
9006 (cons 'and tagsmatcher)
9007 (car tagsmatcher))
9008 orlist)
9009 (setq tagsmatcher nil))
9010 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9011 (setq tagsmatcher
9012 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9013 ;; Make the todo matcher
9014 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9015 (setq todomatcher t)
9016 (setq orterms (org-split-string todomatch "|") orlist nil)
9017 (while (setq term (pop orterms))
9018 (while (string-match re term)
9019 (setq minus (and (match-end 1)
9020 (equal (match-string 1 term) "-"))
9021 kwd (match-string 2 term)
9022 re-p (equal (string-to-char kwd) ?{)
9023 term (substring term (match-end 0))
9024 mm (if re-p
9025 `(string-match ,(substring kwd 1 -1) todo)
9026 (list 'equal 'todo kwd))
9027 mm (if minus (list 'not mm) mm))
9028 (push mm todomatcher))
9029 (push (if (> (length todomatcher) 1)
9030 (cons 'and todomatcher)
9031 (car todomatcher))
9032 orlist)
9033 (setq todomatcher nil))
9034 (setq todomatcher (if (> (length orlist) 1)
9035 (cons 'or orlist) (car orlist))))
9036
9037 ;; Return the string and lisp forms of the matcher
9038 (setq matcher (if todomatcher
9039 (list 'and tagsmatcher todomatcher)
9040 tagsmatcher))
9041 (cons match0 matcher)))
9042
9043 (defun org-op-to-function (op &optional stringp)
9044 "Turn an operator into the appropriate function."
9045 (setq op
9046 (cond
9047 ((equal op "<" ) '(< string< org-time<))
9048 ((equal op ">" ) '(> org-string> org-time>))
9049 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9050 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9051 ((member op '("=" "==")) '(= string= org-time=))
9052 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9053 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9054
9055 (defun org<> (a b) (not (= a b)))
9056 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9057 (defun org-string>= (a b) (not (string< a b)))
9058 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9059 (defun org-string<> (a b) (not (string= a b)))
9060 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9061 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9062 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9063 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9064 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9065 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9066 (defun org-2ft (s)
9067 "Convert S to a floating point time.
9068 If S is already a number, just return it. If it is a string, parse
9069 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9070 (cond
9071 ((numberp s) s)
9072 ((stringp s)
9073 (condition-case nil
9074 (float-time (apply 'encode-time (org-parse-time-string s)))
9075 (error 0.)))
9076 (t 0.)))
9077
9078 (defun org-matcher-time (s)
9079 (cond
9080 ((equal s "<now>") (float-time))
9081 ((equal s "<today>")
9082 (float-time (append '(0 0 0) (nthcdr 3 (decode-time)))))
9083 (t (org-2ft s))))
9084
9085 (defun org-match-any-p (re list)
9086 "Does re match any element of list?"
9087 (setq list (mapcar (lambda (x) (string-match re x)) list))
9088 (delq nil list))
9089
9090 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9091 (defvar org-tags-overlay (org-make-overlay 1 1))
9092 (org-detach-overlay org-tags-overlay)
9093
9094 (defun org-get-local-tags-at (&optional pos)
9095 "Get a list of tags defined in the current headline."
9096 (org-get-tags-at pos 'local))
9097
9098 (defun org-get-local-tags ()
9099 "Get a list of tags defined in the current headline."
9100 (org-get-tags-at nil 'local))
9101
9102 (defun org-get-tags-at (&optional pos local)
9103 "Get a list of all headline tags applicable at POS.
9104 POS defaults to point. If tags are inherited, the list contains
9105 the targets in the same sequence as the headlines appear, i.e.
9106 the tags of the current headline come last.
9107 When LOCAL is non-nil, only return tags from the current headline,
9108 ignore inherited ones."
9109 (interactive)
9110 (let (tags ltags lastpos parent)
9111 (save-excursion
9112 (save-restriction
9113 (widen)
9114 (goto-char (or pos (point)))
9115 (save-match-data
9116 (catch 'done
9117 (condition-case nil
9118 (progn
9119 (org-back-to-heading t)
9120 (while (not (equal lastpos (point)))
9121 (setq lastpos (point))
9122 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9123 (setq ltags (org-split-string
9124 (org-match-string-no-properties 1) ":"))
9125 (setq tags (append
9126 (if parent
9127 (org-remove-uniherited-tags ltags)
9128 ltags)
9129 tags)))
9130 (or org-use-tag-inheritance (throw 'done t))
9131 (if local (throw 'done t))
9132 (org-up-heading-all 1)
9133 (setq parent t)))
9134 (error nil)))))
9135 (append (org-remove-uniherited-tags org-file-tags) tags))))
9136
9137 (defun org-toggle-tag (tag &optional onoff)
9138 "Toggle the tag TAG for the current line.
9139 If ONOFF is `on' or `off', don't toggle but set to this state."
9140 (unless (org-on-heading-p t) (error "Not on headling"))
9141 (let (res current)
9142 (save-excursion
9143 (beginning-of-line)
9144 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9145 (point-at-eol) t)
9146 (progn
9147 (setq current (match-string 1))
9148 (replace-match ""))
9149 (setq current ""))
9150 (setq current (nreverse (org-split-string current ":")))
9151 (cond
9152 ((eq onoff 'on)
9153 (setq res t)
9154 (or (member tag current) (push tag current)))
9155 ((eq onoff 'off)
9156 (or (not (member tag current)) (setq current (delete tag current))))
9157 (t (if (member tag current)
9158 (setq current (delete tag current))
9159 (setq res t)
9160 (push tag current))))
9161 (end-of-line 1)
9162 (if current
9163 (progn
9164 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9165 (org-set-tags nil t))
9166 (delete-horizontal-space))
9167 (run-hooks 'org-after-tags-change-hook))
9168 res))
9169
9170 (defun org-align-tags-here (to-col)
9171 ;; Assumes that this is a headline
9172 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9173 (beginning-of-line 1)
9174 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9175 (< pos (match-beginning 2)))
9176 (progn
9177 (setq tags-l (- (match-end 2) (match-beginning 2)))
9178 (goto-char (match-beginning 1))
9179 (insert " ")
9180 (delete-region (point) (1+ (match-beginning 2)))
9181 (setq ncol (max (1+ (current-column))
9182 (1+ col)
9183 (if (> to-col 0)
9184 to-col
9185 (- (abs to-col) tags-l))))
9186 (setq p (point))
9187 (insert (make-string (- ncol (current-column)) ?\ ))
9188 (setq ncol (current-column))
9189 (when indent-tabs-mode (tabify p (point-at-eol)))
9190 (org-move-to-column (min ncol col) t))
9191 (goto-char pos))))
9192
9193 (defun org-set-tags-command (&optional arg just-align)
9194 "Call the set-tags command for the current entry."
9195 (interactive "P")
9196 (if (org-on-heading-p)
9197 (org-set-tags arg just-align)
9198 (save-excursion
9199 (org-back-to-heading t)
9200 (org-set-tags arg just-align))))
9201
9202 (defun org-set-tags (&optional arg just-align)
9203 "Set the tags for the current headline.
9204 With prefix ARG, realign all tags in headings in the current buffer."
9205 (interactive "P")
9206 (let* ((re (concat "^" outline-regexp))
9207 (current (org-get-tags-string))
9208 (col (current-column))
9209 (org-setting-tags t)
9210 table current-tags inherited-tags ; computed below when needed
9211 tags p0 c0 c1 rpl)
9212 (if arg
9213 (save-excursion
9214 (goto-char (point-min))
9215 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9216 (while (re-search-forward re nil t)
9217 (org-set-tags nil t)
9218 (end-of-line 1)))
9219 (message "All tags realigned to column %d" org-tags-column))
9220 (if just-align
9221 (setq tags current)
9222 ;; Get a new set of tags from the user
9223 (save-excursion
9224 (setq table (or org-tag-alist (org-get-buffer-tags))
9225 org-last-tags-completion-table table
9226 current-tags (org-split-string current ":")
9227 inherited-tags (nreverse
9228 (nthcdr (length current-tags)
9229 (nreverse (org-get-tags-at))))
9230 tags
9231 (if (or (eq t org-use-fast-tag-selection)
9232 (and org-use-fast-tag-selection
9233 (delq nil (mapcar 'cdr table))))
9234 (org-fast-tag-selection
9235 current-tags inherited-tags table
9236 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9237 (let ((org-add-colon-after-tag-completion t))
9238 (org-trim
9239 (org-without-partial-completion
9240 (completing-read "Tags: " 'org-tags-completion-function
9241 nil nil current 'org-tags-history)))))))
9242 (while (string-match "[-+&]+" tags)
9243 ;; No boolean logic, just a list
9244 (setq tags (replace-match ":" t t tags))))
9245
9246 (if (string-match "\\`[\t ]*\\'" tags)
9247 (setq tags "")
9248 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9249 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9250
9251 ;; Insert new tags at the correct column
9252 (beginning-of-line 1)
9253 (cond
9254 ((and (equal current "") (equal tags "")))
9255 ((re-search-forward
9256 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9257 (point-at-eol) t)
9258 (if (equal tags "")
9259 (setq rpl "")
9260 (goto-char (match-beginning 0))
9261 (setq c0 (current-column) p0 (point)
9262 c1 (max (1+ c0) (if (> org-tags-column 0)
9263 org-tags-column
9264 (- (- org-tags-column) (length tags))))
9265 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9266 (replace-match rpl t t)
9267 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9268 tags)
9269 (t (error "Tags alignment failed")))
9270 (org-move-to-column col)
9271 (unless just-align
9272 (run-hooks 'org-after-tags-change-hook)))))
9273
9274 (defun org-change-tag-in-region (beg end tag off)
9275 "Add or remove TAG for each entry in the region.
9276 This works in the agenda, and also in an org-mode buffer."
9277 (interactive
9278 (list (region-beginning) (region-end)
9279 (let ((org-last-tags-completion-table
9280 (if (org-mode-p)
9281 (org-get-buffer-tags)
9282 (org-global-tags-completion-table))))
9283 (completing-read
9284 "Tag: " 'org-tags-completion-function nil nil nil
9285 'org-tags-history))
9286 (progn
9287 (message "[s]et or [r]emove? ")
9288 (equal (read-char-exclusive) ?r))))
9289 (if (fboundp 'deactivate-mark) (deactivate-mark))
9290 (let ((agendap (equal major-mode 'org-agenda-mode))
9291 l1 l2 m buf pos newhead (cnt 0))
9292 (goto-char end)
9293 (setq l2 (1- (org-current-line)))
9294 (goto-char beg)
9295 (setq l1 (org-current-line))
9296 (loop for l from l1 to l2 do
9297 (goto-line l)
9298 (setq m (get-text-property (point) 'org-hd-marker))
9299 (when (or (and (org-mode-p) (org-on-heading-p))
9300 (and agendap m))
9301 (setq buf (if agendap (marker-buffer m) (current-buffer))
9302 pos (if agendap m (point)))
9303 (with-current-buffer buf
9304 (save-excursion
9305 (save-restriction
9306 (goto-char pos)
9307 (setq cnt (1+ cnt))
9308 (org-toggle-tag tag (if off 'off 'on))
9309 (setq newhead (org-get-heading)))))
9310 (and agendap (org-agenda-change-all-lines newhead m))))
9311 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9312
9313 (defun org-tags-completion-function (string predicate &optional flag)
9314 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9315 (confirm (lambda (x) (stringp (car x)))))
9316 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9317 (setq s1 (match-string 1 string)
9318 s2 (match-string 2 string))
9319 (setq s1 "" s2 string))
9320 (cond
9321 ((eq flag nil)
9322 ;; try completion
9323 (setq rtn (try-completion s2 ctable confirm))
9324 (if (stringp rtn)
9325 (setq rtn
9326 (concat s1 s2 (substring rtn (length s2))
9327 (if (and org-add-colon-after-tag-completion
9328 (assoc rtn ctable))
9329 ":" ""))))
9330 rtn)
9331 ((eq flag t)
9332 ;; all-completions
9333 (all-completions s2 ctable confirm)
9334 )
9335 ((eq flag 'lambda)
9336 ;; exact match?
9337 (assoc s2 ctable)))
9338 ))
9339
9340 (defun org-fast-tag-insert (kwd tags face &optional end)
9341 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9342 (insert (format "%-12s" (concat kwd ":"))
9343 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9344 (or end "")))
9345
9346 (defun org-fast-tag-show-exit (flag)
9347 (save-excursion
9348 (goto-line 3)
9349 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9350 (replace-match ""))
9351 (when flag
9352 (end-of-line 1)
9353 (org-move-to-column (- (window-width) 19) t)
9354 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9355
9356 (defun org-set-current-tags-overlay (current prefix)
9357 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9358 (if (featurep 'xemacs)
9359 (org-overlay-display org-tags-overlay (concat prefix s)
9360 'secondary-selection)
9361 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9362 (org-overlay-display org-tags-overlay (concat prefix s)))))
9363
9364 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9365 "Fast tag selection with single keys.
9366 CURRENT is the current list of tags in the headline, INHERITED is the
9367 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9368 possibly with grouping information. TODO-TABLE is a similar table with
9369 TODO keywords, should these have keys assigned to them.
9370 If the keys are nil, a-z are automatically assigned.
9371 Returns the new tags string, or nil to not change the current settings."
9372 (let* ((fulltable (append table todo-table))
9373 (maxlen (apply 'max (mapcar
9374 (lambda (x)
9375 (if (stringp (car x)) (string-width (car x)) 0))
9376 fulltable)))
9377 (buf (current-buffer))
9378 (expert (eq org-fast-tag-selection-single-key 'expert))
9379 (buffer-tags nil)
9380 (fwidth (+ maxlen 3 1 3))
9381 (ncol (/ (- (window-width) 4) fwidth))
9382 (i-face 'org-done)
9383 (c-face 'org-todo)
9384 tg cnt e c char c1 c2 ntable tbl rtn
9385 ov-start ov-end ov-prefix
9386 (exit-after-next org-fast-tag-selection-single-key)
9387 (done-keywords org-done-keywords)
9388 groups ingroup)
9389 (save-excursion
9390 (beginning-of-line 1)
9391 (if (looking-at
9392 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9393 (setq ov-start (match-beginning 1)
9394 ov-end (match-end 1)
9395 ov-prefix "")
9396 (setq ov-start (1- (point-at-eol))
9397 ov-end (1+ ov-start))
9398 (skip-chars-forward "^\n\r")
9399 (setq ov-prefix
9400 (concat
9401 (buffer-substring (1- (point)) (point))
9402 (if (> (current-column) org-tags-column)
9403 " "
9404 (make-string (- org-tags-column (current-column)) ?\ ))))))
9405 (org-move-overlay org-tags-overlay ov-start ov-end)
9406 (save-window-excursion
9407 (if expert
9408 (set-buffer (get-buffer-create " *Org tags*"))
9409 (delete-other-windows)
9410 (split-window-vertically)
9411 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9412 (erase-buffer)
9413 (org-set-local 'org-done-keywords done-keywords)
9414 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9415 (org-fast-tag-insert "Current" current c-face "\n\n")
9416 (org-fast-tag-show-exit exit-after-next)
9417 (org-set-current-tags-overlay current ov-prefix)
9418 (setq tbl fulltable char ?a cnt 0)
9419 (while (setq e (pop tbl))
9420 (cond
9421 ((equal e '(:startgroup))
9422 (push '() groups) (setq ingroup t)
9423 (when (not (= cnt 0))
9424 (setq cnt 0)
9425 (insert "\n"))
9426 (insert "{ "))
9427 ((equal e '(:endgroup))
9428 (setq ingroup nil cnt 0)
9429 (insert "}\n"))
9430 (t
9431 (setq tg (car e) c2 nil)
9432 (if (cdr e)
9433 (setq c (cdr e))
9434 ;; automatically assign a character.
9435 (setq c1 (string-to-char
9436 (downcase (substring
9437 tg (if (= (string-to-char tg) ?@) 1 0)))))
9438 (if (or (rassoc c1 ntable) (rassoc c1 table))
9439 (while (or (rassoc char ntable) (rassoc char table))
9440 (setq char (1+ char)))
9441 (setq c2 c1))
9442 (setq c (or c2 char)))
9443 (if ingroup (push tg (car groups)))
9444 (setq tg (org-add-props tg nil 'face
9445 (cond
9446 ((not (assoc tg table))
9447 (org-get-todo-face tg))
9448 ((member tg current) c-face)
9449 ((member tg inherited) i-face)
9450 (t nil))))
9451 (if (and (= cnt 0) (not ingroup)) (insert " "))
9452 (insert "[" c "] " tg (make-string
9453 (- fwidth 4 (length tg)) ?\ ))
9454 (push (cons tg c) ntable)
9455 (when (= (setq cnt (1+ cnt)) ncol)
9456 (insert "\n")
9457 (if ingroup (insert " "))
9458 (setq cnt 0)))))
9459 (setq ntable (nreverse ntable))
9460 (insert "\n")
9461 (goto-char (point-min))
9462 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9463 (fit-window-to-buffer))
9464 (setq rtn
9465 (catch 'exit
9466 (while t
9467 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9468 (if groups " [!] no groups" " [!]groups")
9469 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9470 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9471 (cond
9472 ((= c ?\r) (throw 'exit t))
9473 ((= c ?!)
9474 (setq groups (not groups))
9475 (goto-char (point-min))
9476 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9477 ((= c ?\C-c)
9478 (if (not expert)
9479 (org-fast-tag-show-exit
9480 (setq exit-after-next (not exit-after-next)))
9481 (setq expert nil)
9482 (delete-other-windows)
9483 (split-window-vertically)
9484 (org-switch-to-buffer-other-window " *Org tags*")
9485 (and (fboundp 'fit-window-to-buffer)
9486 (fit-window-to-buffer))))
9487 ((or (= c ?\C-g)
9488 (and (= c ?q) (not (rassoc c ntable))))
9489 (org-detach-overlay org-tags-overlay)
9490 (setq quit-flag t))
9491 ((= c ?\ )
9492 (setq current nil)
9493 (if exit-after-next (setq exit-after-next 'now)))
9494 ((= c ?\t)
9495 (condition-case nil
9496 (setq tg (completing-read
9497 "Tag: "
9498 (or buffer-tags
9499 (with-current-buffer buf
9500 (org-get-buffer-tags)))))
9501 (quit (setq tg "")))
9502 (when (string-match "\\S-" tg)
9503 (add-to-list 'buffer-tags (list tg))
9504 (if (member tg current)
9505 (setq current (delete tg current))
9506 (push tg current)))
9507 (if exit-after-next (setq exit-after-next 'now)))
9508 ((setq e (rassoc c todo-table) tg (car e))
9509 (with-current-buffer buf
9510 (save-excursion (org-todo tg)))
9511 (if exit-after-next (setq exit-after-next 'now)))
9512 ((setq e (rassoc c ntable) tg (car e))
9513 (if (member tg current)
9514 (setq current (delete tg current))
9515 (loop for g in groups do
9516 (if (member tg g)
9517 (mapc (lambda (x)
9518 (setq current (delete x current)))
9519 g)))
9520 (push tg current))
9521 (if exit-after-next (setq exit-after-next 'now))))
9522
9523 ;; Create a sorted list
9524 (setq current
9525 (sort current
9526 (lambda (a b)
9527 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9528 (if (eq exit-after-next 'now) (throw 'exit t))
9529 (goto-char (point-min))
9530 (beginning-of-line 2)
9531 (delete-region (point) (point-at-eol))
9532 (org-fast-tag-insert "Current" current c-face)
9533 (org-set-current-tags-overlay current ov-prefix)
9534 (while (re-search-forward
9535 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9536 (setq tg (match-string 1))
9537 (add-text-properties
9538 (match-beginning 1) (match-end 1)
9539 (list 'face
9540 (cond
9541 ((member tg current) c-face)
9542 ((member tg inherited) i-face)
9543 (t (get-text-property (match-beginning 1) 'face))))))
9544 (goto-char (point-min)))))
9545 (org-detach-overlay org-tags-overlay)
9546 (if rtn
9547 (mapconcat 'identity current ":")
9548 nil))))
9549
9550 (defun org-get-tags-string ()
9551 "Get the TAGS string in the current headline."
9552 (unless (org-on-heading-p t)
9553 (error "Not on a heading"))
9554 (save-excursion
9555 (beginning-of-line 1)
9556 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9557 (org-match-string-no-properties 1)
9558 "")))
9559
9560 (defun org-get-tags ()
9561 "Get the list of tags specified in the current headline."
9562 (org-split-string (org-get-tags-string) ":"))
9563
9564 (defun org-get-buffer-tags ()
9565 "Get a table of all tags used in the buffer, for completion."
9566 (let (tags)
9567 (save-excursion
9568 (goto-char (point-min))
9569 (while (re-search-forward
9570 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9571 (when (equal (char-after (point-at-bol 0)) ?*)
9572 (mapc (lambda (x) (add-to-list 'tags x))
9573 (org-split-string (org-match-string-no-properties 1) ":")))))
9574 (mapcar 'list tags)))
9575
9576 ;;;; The mapping API
9577
9578 ;;;###autoload
9579 (defun org-map-entries (func &optional match scope &rest skip)
9580 "Call FUNC at each headline selected by MATCH in SCOPE.
9581
9582 FUNC is a function or a lisp form. The function will be called without
9583 arguments, with the cursor positioned at the beginning of the headline.
9584 The return values of all calls to the function will be collected and
9585 returned as a list.
9586
9587 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9588 Only headlines that are matched by this query will be considered during
9589 the iteration. When MATCH is nil or t, all headlines will be
9590 visited by the iteration.
9591
9592 SCOPE determines the scope of this command. It can be any of:
9593
9594 nil The current buffer, respecting the restriction if any
9595 tree The subtree started with the entry at point
9596 file The current buffer, without restriction
9597 file-with-archives
9598 The current buffer, and any archives associated with it
9599 agenda All agenda files
9600 agenda-with-archives
9601 All agenda files with any archive files associated with them
9602 \(file1 file2 ...)
9603 If this is a list, all files in the list will be scanned
9604
9605 The remaining args are treated as settings for the skipping facilities of
9606 the scanner. The following items can be given here:
9607
9608 archive skip trees with the archive tag.
9609 comment skip trees with the COMMENT keyword
9610 function or Emacs Lisp form:
9611 will be used as value for `org-agenda-skip-function', so whenever
9612 the the function returns t, FUNC will not be called for that
9613 entry and search will continue from the point where the
9614 function leaves it."
9615 (let* ((org-agenda-archives-mode nil) ; just to make sure
9616 (org-agenda-skip-archived-trees (memq 'archive skip))
9617 (org-agenda-skip-comment-trees (memq 'comment skip))
9618 (org-agenda-skip-function
9619 (car (org-delete-all '(comment archive) skip)))
9620 (org-tags-match-list-sublevels t)
9621 matcher pos file
9622 org-todo-keywords-for-agenda
9623 org-done-keywords-for-agenda
9624 org-todo-keyword-alist-for-agenda
9625 org-tag-alist-for-agenda)
9626
9627 (cond
9628 ((eq match t) (setq matcher t))
9629 ((eq match nil) (setq matcher t))
9630 (t (setq matcher (if match (org-make-tags-matcher match) t))))
9631
9632 (when (eq scope 'tree)
9633 (org-back-to-heading t)
9634 (org-narrow-to-subtree)
9635 (setq scope nil))
9636
9637 (if (not scope)
9638 (progn
9639 (org-prepare-agenda-buffers
9640 (list (buffer-file-name (current-buffer))))
9641 (org-scan-tags func matcher))
9642 ;; Get the right scope
9643 (setq pos (point))
9644 (cond
9645 ((and scope (listp scope) (symbolp (car scope)))
9646 (setq scope (eval scope)))
9647 ((eq scope 'agenda)
9648 (setq scope (org-agenda-files t)))
9649 ((eq scope 'agenda-with-archives)
9650 (setq scope (org-agenda-files t))
9651 (setq scope (org-add-archive-files scope)))
9652 ((eq scope 'file)
9653 (setq scope (list (buffer-file-name))))
9654 ((eq scope 'file-with-archives)
9655 (setq scope (org-add-archive-files (list (buffer-file-name))))))
9656 (org-prepare-agenda-buffers scope)
9657 (while (setq file (pop scope))
9658 (with-current-buffer (org-find-base-buffer-visiting file)
9659 (save-excursion
9660 (save-restriction
9661 (widen)
9662 (goto-char (point-min))
9663 (org-scan-tags func matcher))))))))
9664
9665 ;;;; Properties
9666
9667 ;;; Setting and retrieving properties
9668
9669 (defconst org-special-properties
9670 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9671 "TIMESTAMP" "TIMESTAMP_IA")
9672 "The special properties valid in Org-mode.
9673
9674 These are properties that are not defined in the property drawer,
9675 but in some other way.")
9676
9677 (defconst org-default-properties
9678 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9679 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9680 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9681 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9682 "Some properties that are used by Org-mode for various purposes.
9683 Being in this list makes sure that they are offered for completion.")
9684
9685 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9686 "Regular expression matching the first line of a property drawer.")
9687
9688 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9689 "Regular expression matching the first line of a property drawer.")
9690
9691 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
9692 "Regular expression matching the first line of a property drawer.")
9693
9694 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
9695 "Regular expression matching the first line of a property drawer.")
9696
9697 (defconst org-property-drawer-re
9698 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
9699 org-property-end-re "\\)\n?")
9700 "Matches an entire property drawer.")
9701
9702 (defconst org-clock-drawer-re
9703 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
9704 org-property-end-re "\\)\n?")
9705 "Matches an entire clock drawer.")
9706
9707 (defun org-property-action ()
9708 "Do an action on properties."
9709 (interactive)
9710 (let (c)
9711 (org-at-property-p)
9712 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9713 (setq c (read-char-exclusive))
9714 (cond
9715 ((equal c ?s)
9716 (call-interactively 'org-set-property))
9717 ((equal c ?d)
9718 (call-interactively 'org-delete-property))
9719 ((equal c ?D)
9720 (call-interactively 'org-delete-property-globally))
9721 ((equal c ?c)
9722 (call-interactively 'org-compute-property-at-point))
9723 (t (error "No such property action %c" c)))))
9724
9725 (defun org-at-property-p ()
9726 "Is the cursor in a property line?"
9727 ;; FIXME: Does not check if we are actually in the drawer.
9728 ;; FIXME: also returns true on any drawers.....
9729 ;; This is used by C-c C-c for property action.
9730 (save-excursion
9731 (beginning-of-line 1)
9732 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9733
9734 (defun org-get-property-block (&optional beg end force)
9735 "Return the (beg . end) range of the body of the property drawer.
9736 BEG and END can be beginning and end of subtree, if not given
9737 they will be found.
9738 If the drawer does not exist and FORCE is non-nil, create the drawer."
9739 (catch 'exit
9740 (save-excursion
9741 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9742 (end (or end (progn (outline-next-heading) (point)))))
9743 (goto-char beg)
9744 (if (re-search-forward org-property-start-re end t)
9745 (setq beg (1+ (match-end 0)))
9746 (if force
9747 (save-excursion
9748 (org-insert-property-drawer)
9749 (setq end (progn (outline-next-heading) (point))))
9750 (throw 'exit nil))
9751 (goto-char beg)
9752 (if (re-search-forward org-property-start-re end t)
9753 (setq beg (1+ (match-end 0)))))
9754 (if (re-search-forward org-property-end-re end t)
9755 (setq end (match-beginning 0))
9756 (or force (throw 'exit nil))
9757 (goto-char beg)
9758 (setq end beg)
9759 (org-indent-line-function)
9760 (insert ":END:\n"))
9761 (cons beg end)))))
9762
9763 (defun org-entry-properties (&optional pom which)
9764 "Get all properties of the entry at point-or-marker POM.
9765 This includes the TODO keyword, the tags, time strings for deadline,
9766 scheduled, and clocking, and any additional properties defined in the
9767 entry. The return value is an alist, keys may occur multiple times
9768 if the property key was used several times.
9769 POM may also be nil, in which case the current entry is used.
9770 If WHICH is nil or `all', get all properties. If WHICH is
9771 `special' or `standard', only get that subclass."
9772 (setq which (or which 'all))
9773 (org-with-point-at pom
9774 (let ((clockstr (substring org-clock-string 0 -1))
9775 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9776 beg end range props sum-props key value string clocksum)
9777 (save-excursion
9778 (when (condition-case nil (org-back-to-heading t) (error nil))
9779 (setq beg (point))
9780 (setq sum-props (get-text-property (point) 'org-summaries))
9781 (setq clocksum (get-text-property (point) :org-clock-minutes))
9782 (outline-next-heading)
9783 (setq end (point))
9784 (when (memq which '(all special))
9785 ;; Get the special properties, like TODO and tags
9786 (goto-char beg)
9787 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9788 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9789 (when (looking-at org-priority-regexp)
9790 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9791 (when (and (setq value (org-get-tags-string))
9792 (string-match "\\S-" value))
9793 (push (cons "TAGS" value) props))
9794 (when (setq value (org-get-tags-at))
9795 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9796 props))
9797 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9798 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9799 string (if (equal key clockstr)
9800 (org-no-properties
9801 (org-trim
9802 (buffer-substring
9803 (match-beginning 3) (goto-char (point-at-eol)))))
9804 (substring (org-match-string-no-properties 3) 1 -1)))
9805 (unless key
9806 (if (= (char-after (match-beginning 3)) ?\[)
9807 (setq key "TIMESTAMP_IA")
9808 (setq key "TIMESTAMP")))
9809 (when (or (equal key clockstr) (not (assoc key props)))
9810 (push (cons key string) props)))
9811
9812 )
9813
9814 (when (memq which '(all standard))
9815 ;; Get the standard properties, like :PORP: ...
9816 (setq range (org-get-property-block beg end))
9817 (when range
9818 (goto-char (car range))
9819 (while (re-search-forward
9820 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9821 (cdr range) t)
9822 (setq key (org-match-string-no-properties 1)
9823 value (org-trim (or (org-match-string-no-properties 2) "")))
9824 (unless (member key excluded)
9825 (push (cons key (or value "")) props)))))
9826 (if clocksum
9827 (push (cons "CLOCKSUM"
9828 (org-columns-number-to-string (/ (float clocksum) 60.)
9829 'add_times))
9830 props))
9831 (unless (assoc "CATEGORY" props)
9832 (setq value (or (org-get-category)
9833 (progn (org-refresh-category-properties)
9834 (org-get-category))))
9835 (push (cons "CATEGORY" value) props))
9836 (append sum-props (nreverse props)))))))
9837
9838 (defun org-entry-get (pom property &optional inherit)
9839 "Get value of PROPERTY for entry at point-or-marker POM.
9840 If INHERIT is non-nil and the entry does not have the property,
9841 then also check higher levels of the hierarchy.
9842 If INHERIT is the symbol `selective', use inheritance only if the setting
9843 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9844 If the property is present but empty, the return value is the empty string.
9845 If the property is not present at all, nil is returned."
9846 (org-with-point-at pom
9847 (if (and inherit (if (eq inherit 'selective)
9848 (org-property-inherit-p property)
9849 t))
9850 (org-entry-get-with-inheritance property)
9851 (if (member property org-special-properties)
9852 ;; We need a special property. Use brute force, get all properties.
9853 (cdr (assoc property (org-entry-properties nil 'special)))
9854 (let ((range (org-get-property-block)))
9855 (if (and range
9856 (goto-char (car range))
9857 (re-search-forward
9858 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9859 (cdr range) t))
9860 ;; Found the property, return it.
9861 (if (match-end 1)
9862 (org-match-string-no-properties 1)
9863 "")))))))
9864
9865 (defun org-property-or-variable-value (var &optional inherit)
9866 "Check if there is a property fixing the value of VAR.
9867 If yes, return this value. If not, return the current value of the variable."
9868 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9869 (if (and prop (stringp prop) (string-match "\\S-" prop))
9870 (read prop)
9871 (symbol-value var))))
9872
9873 (defun org-entry-delete (pom property)
9874 "Delete the property PROPERTY from entry at point-or-marker POM."
9875 (org-with-point-at pom
9876 (if (member property org-special-properties)
9877 nil ; cannot delete these properties.
9878 (let ((range (org-get-property-block)))
9879 (if (and range
9880 (goto-char (car range))
9881 (re-search-forward
9882 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9883 (cdr range) t))
9884 (progn
9885 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9886 t)
9887 nil)))))
9888
9889 ;; Multi-values properties are properties that contain multiple values
9890 ;; These values are assumed to be single words, separated by whitespace.
9891 (defun org-entry-add-to-multivalued-property (pom property value)
9892 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9893 (let* ((old (org-entry-get pom property))
9894 (values (and old (org-split-string old "[ \t]"))))
9895 (setq value (org-entry-protect-space value))
9896 (unless (member value values)
9897 (setq values (cons value values))
9898 (org-entry-put pom property
9899 (mapconcat 'identity values " ")))))
9900
9901 (defun org-entry-remove-from-multivalued-property (pom property value)
9902 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9903 (let* ((old (org-entry-get pom property))
9904 (values (and old (org-split-string old "[ \t]"))))
9905 (setq value (org-entry-protect-space value))
9906 (when (member value values)
9907 (setq values (delete value values))
9908 (org-entry-put pom property
9909 (mapconcat 'identity values " ")))))
9910
9911 (defun org-entry-member-in-multivalued-property (pom property value)
9912 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9913 (let* ((old (org-entry-get pom property))
9914 (values (and old (org-split-string old "[ \t]"))))
9915 (setq value (org-entry-protect-space value))
9916 (member value values)))
9917
9918 (defun org-entry-get-multivalued-property (pom property)
9919 "Return a list of values in a multivalued property."
9920 (let* ((value (org-entry-get pom property))
9921 (values (and value (org-split-string value "[ \t]"))))
9922 (mapcar 'org-entry-restore-space values)))
9923
9924 (defun org-entry-put-multivalued-property (pom property &rest values)
9925 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
9926 VALUES should be a list of strings. Spaces will be protected."
9927 (org-entry-put pom property
9928 (mapconcat 'org-entry-protect-space values " "))
9929 (let* ((value (org-entry-get pom property))
9930 (values (and value (org-split-string value "[ \t]"))))
9931 (mapcar 'org-entry-restore-space values)))
9932
9933 (defun org-entry-protect-space (s)
9934 "Protect spaces and newline in string S."
9935 (while (string-match " " s)
9936 (setq s (replace-match "%20" t t s)))
9937 (while (string-match "\n" s)
9938 (setq s (replace-match "%0A" t t s)))
9939 s)
9940
9941 (defun org-entry-restore-space (s)
9942 "Restore spaces and newline in string S."
9943 (while (string-match "%20" s)
9944 (setq s (replace-match " " t t s)))
9945 (while (string-match "%0A" s)
9946 (setq s (replace-match "\n" t t s)))
9947 s)
9948
9949 (defvar org-entry-property-inherited-from (make-marker)
9950 "Marker pointing to the entry from where a proerty was inherited.
9951 Each call to `org-entry-get-with-inheritance' will set this marker to the
9952 location of the entry where the inheriance search matched. If there was
9953 no match, the marker will point nowhere.
9954 Note that also `org-entry-get' calls this function, if the INHERIT flag
9955 is set.")
9956
9957 (defun org-entry-get-with-inheritance (property)
9958 "Get entry property, and search higher levels if not present."
9959 (move-marker org-entry-property-inherited-from nil)
9960 (let (tmp)
9961 (save-excursion
9962 (save-restriction
9963 (widen)
9964 (catch 'ex
9965 (while t
9966 (when (setq tmp (org-entry-get nil property))
9967 (org-back-to-heading t)
9968 (move-marker org-entry-property-inherited-from (point))
9969 (throw 'ex tmp))
9970 (or (org-up-heading-safe) (throw 'ex nil)))))
9971 (or tmp
9972 (cdr (assoc property org-file-properties))
9973 (cdr (assoc property org-global-properties))
9974 (cdr (assoc property org-global-properties-fixed))))))
9975
9976 (defun org-entry-put (pom property value)
9977 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9978 (org-with-point-at pom
9979 (org-back-to-heading t)
9980 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9981 range)
9982 (cond
9983 ((equal property "TODO")
9984 (when (and (stringp value) (string-match "\\S-" value)
9985 (not (member value org-todo-keywords-1)))
9986 (error "\"%s\" is not a valid TODO state" value))
9987 (if (or (not value)
9988 (not (string-match "\\S-" value)))
9989 (setq value 'none))
9990 (org-todo value)
9991 (org-set-tags nil 'align))
9992 ((equal property "PRIORITY")
9993 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9994 (string-to-char value) ?\ ))
9995 (org-set-tags nil 'align))
9996 ((equal property "SCHEDULED")
9997 (if (re-search-forward org-scheduled-time-regexp end t)
9998 (cond
9999 ((eq value 'earlier) (org-timestamp-change -1 'day))
10000 ((eq value 'later) (org-timestamp-change 1 'day))
10001 (t (call-interactively 'org-schedule)))
10002 (call-interactively 'org-schedule)))
10003 ((equal property "DEADLINE")
10004 (if (re-search-forward org-deadline-time-regexp end t)
10005 (cond
10006 ((eq value 'earlier) (org-timestamp-change -1 'day))
10007 ((eq value 'later) (org-timestamp-change 1 'day))
10008 (t (call-interactively 'org-deadline)))
10009 (call-interactively 'org-deadline)))
10010 ((member property org-special-properties)
10011 (error "The %s property can not yet be set with `org-entry-put'"
10012 property))
10013 (t ; a non-special property
10014 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10015 (setq range (org-get-property-block beg end 'force))
10016 (goto-char (car range))
10017 (if (re-search-forward
10018 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10019 (progn
10020 (delete-region (match-beginning 1) (match-end 1))
10021 (goto-char (match-beginning 1)))
10022 (goto-char (cdr range))
10023 (insert "\n")
10024 (backward-char 1)
10025 (org-indent-line-function)
10026 (insert ":" property ":"))
10027 (and value (insert " " value))
10028 (org-indent-line-function)))))))
10029
10030 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10031 "Get all property keys in the current buffer.
10032 With INCLUDE-SPECIALS, also list the special properties that relect things
10033 like tags and TODO state.
10034 With INCLUDE-DEFAULTS, also include properties that has special meaning
10035 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10036 With INCLUDE-COLUMNS, also include property names given in COLUMN
10037 formats in the current buffer."
10038 (let (rtn range cfmt cols s p)
10039 (save-excursion
10040 (save-restriction
10041 (widen)
10042 (goto-char (point-min))
10043 (while (re-search-forward org-property-start-re nil t)
10044 (setq range (org-get-property-block))
10045 (goto-char (car range))
10046 (while (re-search-forward
10047 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10048 (cdr range) t)
10049 (add-to-list 'rtn (org-match-string-no-properties 1)))
10050 (outline-next-heading))))
10051
10052 (when include-specials
10053 (setq rtn (append org-special-properties rtn)))
10054
10055 (when include-defaults
10056 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10057
10058 (when include-columns
10059 (save-excursion
10060 (save-restriction
10061 (widen)
10062 (goto-char (point-min))
10063 (while (re-search-forward
10064 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10065 nil t)
10066 (setq cfmt (match-string 2) s 0)
10067 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10068 cfmt s)
10069 (setq s (match-end 0)
10070 p (match-string 1 cfmt))
10071 (unless (or (equal p "ITEM")
10072 (member p org-special-properties))
10073 (add-to-list 'rtn (match-string 1 cfmt))))))))
10074
10075 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10076
10077 (defun org-property-values (key)
10078 "Return a list of all values of property KEY."
10079 (save-excursion
10080 (save-restriction
10081 (widen)
10082 (goto-char (point-min))
10083 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10084 values)
10085 (while (re-search-forward re nil t)
10086 (add-to-list 'values (org-trim (match-string 1))))
10087 (delete "" values)))))
10088
10089 (defun org-insert-property-drawer ()
10090 "Insert a property drawer into the current entry."
10091 (interactive)
10092 (org-back-to-heading t)
10093 (looking-at outline-regexp)
10094 (let ((indent (- (match-end 0)(match-beginning 0)))
10095 (beg (point))
10096 (re (concat "^[ \t]*" org-keyword-time-regexp))
10097 end hiddenp)
10098 (outline-next-heading)
10099 (setq end (point))
10100 (goto-char beg)
10101 (while (re-search-forward re end t))
10102 (setq hiddenp (org-invisible-p))
10103 (end-of-line 1)
10104 (and (equal (char-after) ?\n) (forward-char 1))
10105 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10106 (beginning-of-line 2))
10107 (org-skip-over-state-notes)
10108 (skip-chars-backward " \t\n\r")
10109 (if (eq (char-before) ?*) (forward-char 1))
10110 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10111 (beginning-of-line 0)
10112 (org-indent-to-column indent)
10113 (beginning-of-line 2)
10114 (org-indent-to-column indent)
10115 (beginning-of-line 0)
10116 (if hiddenp
10117 (save-excursion
10118 (org-back-to-heading t)
10119 (hide-entry))
10120 (org-flag-drawer t))))
10121
10122 (defun org-set-property (property value)
10123 "In the current entry, set PROPERTY to VALUE.
10124 When called interactively, this will prompt for a property name, offering
10125 completion on existing and default properties. And then it will prompt
10126 for a value, offering competion either on allowed values (via an inherited
10127 xxx_ALL property) or on existing values in other instances of this property
10128 in the current file."
10129 (interactive
10130 (let* ((completion-ignore-case t)
10131 (keys (org-buffer-property-keys nil t t))
10132 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10133 (prop (if (member prop0 keys)
10134 prop0
10135 (or (cdr (assoc (downcase prop0)
10136 (mapcar (lambda (x) (cons (downcase x) x))
10137 keys)))
10138 prop0)))
10139 (cur (org-entry-get nil prop))
10140 (allowed (org-property-get-allowed-values nil prop 'table))
10141 (existing (mapcar 'list (org-property-values prop)))
10142 (val (if allowed
10143 (org-completing-read "Value: " allowed nil 'req-match)
10144 (org-completing-read
10145 (concat "Value" (if (and cur (string-match "\\S-" cur))
10146 (concat "[" cur "]") "")
10147 ": ")
10148 existing nil nil "" nil cur))))
10149 (list prop (if (equal val "") cur val))))
10150 (unless (equal (org-entry-get nil property) value)
10151 (org-entry-put nil property value)))
10152
10153 (defun org-delete-property (property)
10154 "In the current entry, delete PROPERTY."
10155 (interactive
10156 (let* ((completion-ignore-case t)
10157 (prop (completing-read
10158 "Property: " (org-entry-properties nil 'standard))))
10159 (list prop)))
10160 (message "Property %s %s" property
10161 (if (org-entry-delete nil property)
10162 "deleted"
10163 "was not present in the entry")))
10164
10165 (defun org-delete-property-globally (property)
10166 "Remove PROPERTY globally, from all entries."
10167 (interactive
10168 (let* ((completion-ignore-case t)
10169 (prop (completing-read
10170 "Globally remove property: "
10171 (mapcar 'list (org-buffer-property-keys)))))
10172 (list prop)))
10173 (save-excursion
10174 (save-restriction
10175 (widen)
10176 (goto-char (point-min))
10177 (let ((cnt 0))
10178 (while (re-search-forward
10179 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10180 nil t)
10181 (setq cnt (1+ cnt))
10182 (replace-match ""))
10183 (message "Property \"%s\" removed from %d entries" property cnt)))))
10184
10185 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10186
10187 (defun org-compute-property-at-point ()
10188 "Compute the property at point.
10189 This looks for an enclosing column format, extracts the operator and
10190 then applies it to the proerty in the column format's scope."
10191 (interactive)
10192 (unless (org-at-property-p)
10193 (error "Not at a property"))
10194 (let ((prop (org-match-string-no-properties 2)))
10195 (org-columns-get-format-and-top-level)
10196 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10197 (error "No operator defined for property %s" prop))
10198 (org-columns-compute prop)))
10199
10200 (defun org-property-get-allowed-values (pom property &optional table)
10201 "Get allowed values for the property PROPERTY.
10202 When TABLE is non-nil, return an alist that can directly be used for
10203 completion."
10204 (let (vals)
10205 (cond
10206 ((equal property "TODO")
10207 (setq vals (org-with-point-at pom
10208 (append org-todo-keywords-1 '("")))))
10209 ((equal property "PRIORITY")
10210 (let ((n org-lowest-priority))
10211 (while (>= n org-highest-priority)
10212 (push (char-to-string n) vals)
10213 (setq n (1- n)))))
10214 ((member property org-special-properties))
10215 (t
10216 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10217
10218 (when (and vals (string-match "\\S-" vals))
10219 (setq vals (car (read-from-string (concat "(" vals ")"))))
10220 (setq vals (mapcar (lambda (x)
10221 (cond ((stringp x) x)
10222 ((numberp x) (number-to-string x))
10223 ((symbolp x) (symbol-name x))
10224 (t "???")))
10225 vals)))))
10226 (if table (mapcar 'list vals) vals)))
10227
10228 (defun org-property-previous-allowed-value (&optional previous)
10229 "Switch to the next allowed value for this property."
10230 (interactive)
10231 (org-property-next-allowed-value t))
10232
10233 (defun org-property-next-allowed-value (&optional previous)
10234 "Switch to the next allowed value for this property."
10235 (interactive)
10236 (unless (org-at-property-p)
10237 (error "Not at a property"))
10238 (let* ((key (match-string 2))
10239 (value (match-string 3))
10240 (allowed (or (org-property-get-allowed-values (point) key)
10241 (and (member value '("[ ]" "[-]" "[X]"))
10242 '("[ ]" "[X]"))))
10243 nval)
10244 (unless allowed
10245 (error "Allowed values for this property have not been defined"))
10246 (if previous (setq allowed (reverse allowed)))
10247 (if (member value allowed)
10248 (setq nval (car (cdr (member value allowed)))))
10249 (setq nval (or nval (car allowed)))
10250 (if (equal nval value)
10251 (error "Only one allowed value for this property"))
10252 (org-at-property-p)
10253 (replace-match (concat " :" key ": " nval) t t)
10254 (org-indent-line-function)
10255 (beginning-of-line 1)
10256 (skip-chars-forward " \t")))
10257
10258 (defun org-find-entry-with-id (ident)
10259 "Locate the entry that contains the ID property with exact value IDENT.
10260 IDENT can be a string, a symbol or a number, this function will search for
10261 the string representation of it.
10262 Return the position where this entry starts, or nil if there is no such entry."
10263 (let ((id (cond
10264 ((stringp ident) ident)
10265 ((symbol-name ident) (symbol-name ident))
10266 ((numberp ident) (number-to-string ident))
10267 (t (error "IDENT %s must be a string, symbol or number" ident))))
10268 (case-fold-search nil))
10269 (save-excursion
10270 (save-restriction
10271 (widen)
10272 (goto-char (point-min))
10273 (when (re-search-forward
10274 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10275 nil t)
10276 (org-back-to-heading)
10277 (point))))))
10278
10279 ;;;; Timestamps
10280
10281 (defvar org-last-changed-timestamp nil)
10282 (defvar org-last-inserted-timestamp nil
10283 "The last time stamp inserted with `org-insert-time-stamp'.")
10284 (defvar org-time-was-given) ; dynamically scoped parameter
10285 (defvar org-end-time-was-given) ; dynamically scoped parameter
10286 (defvar org-ts-what) ; dynamically scoped parameter
10287
10288 (defun org-time-stamp (arg &optional inactive)
10289 "Prompt for a date/time and insert a time stamp.
10290 If the user specifies a time like HH:MM, or if this command is called
10291 with a prefix argument, the time stamp will contain date and time.
10292 Otherwise, only the date will be included. All parts of a date not
10293 specified by the user will be filled in from the current date/time.
10294 So if you press just return without typing anything, the time stamp
10295 will represent the current date/time. If there is already a timestamp
10296 at the cursor, it will be modified."
10297 (interactive "P")
10298 (let* ((ts nil)
10299 (default-time
10300 ;; Default time is either today, or, when entering a range,
10301 ;; the range start.
10302 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10303 (save-excursion
10304 (re-search-backward
10305 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10306 (- (point) 20) t)))
10307 (apply 'encode-time (org-parse-time-string (match-string 1)))
10308 (current-time)))
10309 (default-input (and ts (org-get-compact-tod ts)))
10310 org-time-was-given org-end-time-was-given time)
10311 (cond
10312 ((and (org-at-timestamp-p t)
10313 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10314 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10315 (insert "--")
10316 (setq time (let ((this-command this-command))
10317 (org-read-date arg 'totime nil nil
10318 default-time default-input)))
10319 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10320 ((org-at-timestamp-p t)
10321 (setq time (let ((this-command this-command))
10322 (org-read-date arg 'totime nil nil default-time default-input)))
10323 (when (org-at-timestamp-p t) ; just to get the match data
10324 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10325 (replace-match "")
10326 (setq org-last-changed-timestamp
10327 (org-insert-time-stamp
10328 time (or org-time-was-given arg)
10329 inactive nil nil (list org-end-time-was-given))))
10330 (message "Timestamp updated"))
10331 (t
10332 (setq time (let ((this-command this-command))
10333 (org-read-date arg 'totime nil nil default-time default-input)))
10334 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10335 nil nil (list org-end-time-was-given))))))
10336
10337 ;; FIXME: can we use this for something else, like computing time differences?
10338 (defun org-get-compact-tod (s)
10339 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10340 (let* ((t1 (match-string 1 s))
10341 (h1 (string-to-number (match-string 2 s)))
10342 (m1 (string-to-number (match-string 3 s)))
10343 (t2 (and (match-end 4) (match-string 5 s)))
10344 (h2 (and t2 (string-to-number (match-string 6 s))))
10345 (m2 (and t2 (string-to-number (match-string 7 s))))
10346 dh dm)
10347 (if (not t2)
10348 t1
10349 (setq dh (- h2 h1) dm (- m2 m1))
10350 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10351 (concat t1 "+" (number-to-string dh)
10352 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10353
10354 (defun org-time-stamp-inactive (&optional arg)
10355 "Insert an inactive time stamp.
10356 An inactive time stamp is enclosed in square brackets instead of angle
10357 brackets. It is inactive in the sense that it does not trigger agenda entries,
10358 does not link to the calendar and cannot be changed with the S-cursor keys.
10359 So these are more for recording a certain time/date."
10360 (interactive "P")
10361 (org-time-stamp arg 'inactive))
10362
10363 (defvar org-date-ovl (org-make-overlay 1 1))
10364 (org-overlay-put org-date-ovl 'face 'org-warning)
10365 (org-detach-overlay org-date-ovl)
10366
10367 (defvar org-ans1) ; dynamically scoped parameter
10368 (defvar org-ans2) ; dynamically scoped parameter
10369
10370 (defvar org-plain-time-of-day-regexp) ; defined below
10371
10372 (defvar org-overriding-default-time nil) ; dynamically scoped
10373 (defvar org-read-date-overlay nil)
10374 (defvar org-dcst nil) ; dynamically scoped
10375
10376 (defun org-read-date (&optional with-time to-time from-string prompt
10377 default-time default-input)
10378 "Read a date, possibly a time, and make things smooth for the user.
10379 The prompt will suggest to enter an ISO date, but you can also enter anything
10380 which will at least partially be understood by `parse-time-string'.
10381 Unrecognized parts of the date will default to the current day, month, year,
10382 hour and minute. If this command is called to replace a timestamp at point,
10383 of to enter the second timestamp of a range, the default time is taken from the
10384 existing stamp. For example,
10385 3-2-5 --> 2003-02-05
10386 feb 15 --> currentyear-02-15
10387 sep 12 9 --> 2009-09-12
10388 12:45 --> today 12:45
10389 22 sept 0:34 --> currentyear-09-22 0:34
10390 12 --> currentyear-currentmonth-12
10391 Fri --> nearest Friday (today or later)
10392 etc.
10393
10394 Furthermore you can specify a relative date by giving, as the *first* thing
10395 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10396 change in days weeks, months, years.
10397 With a single plus or minus, the date is relative to today. With a double
10398 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10399 +4d --> four days from today
10400 +4 --> same as above
10401 +2w --> two weeks from today
10402 ++5 --> five days from default date
10403
10404 The function understands only English month and weekday abbreviations,
10405 but this can be configured with the variables `parse-time-months' and
10406 `parse-time-weekdays'.
10407
10408 While prompting, a calendar is popped up - you can also select the
10409 date with the mouse (button 1). The calendar shows a period of three
10410 months. To scroll it to other months, use the keys `>' and `<'.
10411 If you don't like the calendar, turn it off with
10412 \(setq org-read-date-popup-calendar nil)
10413
10414 With optional argument TO-TIME, the date will immediately be converted
10415 to an internal time.
10416 With an optional argument WITH-TIME, the prompt will suggest to also
10417 insert a time. Note that when WITH-TIME is not set, you can still
10418 enter a time, and this function will inform the calling routine about
10419 this change. The calling routine may then choose to change the format
10420 used to insert the time stamp into the buffer to include the time.
10421 With optional argument FROM-STRING, read from this string instead from
10422 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10423 the time/date that is used for everything that is not specified by the
10424 user."
10425 (require 'parse-time)
10426 (let* ((org-time-stamp-rounding-minutes
10427 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10428 (org-dcst org-display-custom-times)
10429 (ct (org-current-time))
10430 (def (or org-overriding-default-time default-time ct))
10431 (defdecode (decode-time def))
10432 (dummy (progn
10433 (when (< (nth 2 defdecode) org-extend-today-until)
10434 (setcar (nthcdr 2 defdecode) -1)
10435 (setcar (nthcdr 1 defdecode) 59)
10436 (setq def (apply 'encode-time defdecode)
10437 defdecode (decode-time def)))))
10438 (calendar-move-hook nil)
10439 (calendar-view-diary-initially-flag nil)
10440 (view-diary-entries-initially nil)
10441 (calendar-view-holidays-initially-flag nil)
10442 (view-calendar-holidays-initially nil)
10443 (timestr (format-time-string
10444 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10445 (prompt (concat (if prompt (concat prompt " ") "")
10446 (format "Date+time [%s]: " timestr)))
10447 ans (org-ans0 "") org-ans1 org-ans2 final)
10448
10449 (cond
10450 (from-string (setq ans from-string))
10451 (org-read-date-popup-calendar
10452 (save-excursion
10453 (save-window-excursion
10454 (calendar)
10455 (calendar-forward-day (- (time-to-days def)
10456 (calendar-absolute-from-gregorian
10457 (calendar-current-date))))
10458 (org-eval-in-calendar nil t)
10459 (let* ((old-map (current-local-map))
10460 (map (copy-keymap calendar-mode-map))
10461 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10462 (org-defkey map (kbd "RET") 'org-calendar-select)
10463 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10464 'org-calendar-select-mouse)
10465 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10466 'org-calendar-select-mouse)
10467 (org-defkey minibuffer-local-map [(meta shift left)]
10468 (lambda () (interactive)
10469 (org-eval-in-calendar '(calendar-backward-month 1))))
10470 (org-defkey minibuffer-local-map [(meta shift right)]
10471 (lambda () (interactive)
10472 (org-eval-in-calendar '(calendar-forward-month 1))))
10473 (org-defkey minibuffer-local-map [(meta shift up)]
10474 (lambda () (interactive)
10475 (org-eval-in-calendar '(calendar-backward-year 1))))
10476 (org-defkey minibuffer-local-map [(meta shift down)]
10477 (lambda () (interactive)
10478 (org-eval-in-calendar '(calendar-forward-year 1))))
10479 (org-defkey minibuffer-local-map [(shift up)]
10480 (lambda () (interactive)
10481 (org-eval-in-calendar '(calendar-backward-week 1))))
10482 (org-defkey minibuffer-local-map [(shift down)]
10483 (lambda () (interactive)
10484 (org-eval-in-calendar '(calendar-forward-week 1))))
10485 (org-defkey minibuffer-local-map [(shift left)]
10486 (lambda () (interactive)
10487 (org-eval-in-calendar '(calendar-backward-day 1))))
10488 (org-defkey minibuffer-local-map [(shift right)]
10489 (lambda () (interactive)
10490 (org-eval-in-calendar '(calendar-forward-day 1))))
10491 (org-defkey minibuffer-local-map ">"
10492 (lambda () (interactive)
10493 (org-eval-in-calendar '(scroll-calendar-left 1))))
10494 (org-defkey minibuffer-local-map "<"
10495 (lambda () (interactive)
10496 (org-eval-in-calendar '(scroll-calendar-right 1))))
10497 (unwind-protect
10498 (progn
10499 (use-local-map map)
10500 (add-hook 'post-command-hook 'org-read-date-display)
10501 (setq org-ans0 (read-string prompt default-input nil nil))
10502 ;; org-ans0: from prompt
10503 ;; org-ans1: from mouse click
10504 ;; org-ans2: from calendar motion
10505 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10506 (remove-hook 'post-command-hook 'org-read-date-display)
10507 (use-local-map old-map)
10508 (when org-read-date-overlay
10509 (org-delete-overlay org-read-date-overlay)
10510 (setq org-read-date-overlay nil)))))))
10511
10512 (t ; Naked prompt only
10513 (unwind-protect
10514 (setq ans (read-string prompt default-input nil timestr))
10515 (when org-read-date-overlay
10516 (org-delete-overlay org-read-date-overlay)
10517 (setq org-read-date-overlay nil)))))
10518
10519 (setq final (org-read-date-analyze ans def defdecode))
10520
10521 (if to-time
10522 (apply 'encode-time final)
10523 (if (and (boundp 'org-time-was-given) org-time-was-given)
10524 (format "%04d-%02d-%02d %02d:%02d"
10525 (nth 5 final) (nth 4 final) (nth 3 final)
10526 (nth 2 final) (nth 1 final))
10527 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10528 (defvar def)
10529 (defvar defdecode)
10530 (defvar with-time)
10531 (defun org-read-date-display ()
10532 "Display the currrent date prompt interpretation in the minibuffer."
10533 (when org-read-date-display-live
10534 (when org-read-date-overlay
10535 (org-delete-overlay org-read-date-overlay))
10536 (let ((p (point)))
10537 (end-of-line 1)
10538 (while (not (equal (buffer-substring
10539 (max (point-min) (- (point) 4)) (point))
10540 " "))
10541 (insert " "))
10542 (goto-char p))
10543 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10544 " " (or org-ans1 org-ans2)))
10545 (org-end-time-was-given nil)
10546 (f (org-read-date-analyze ans def defdecode))
10547 (fmts (if org-dcst
10548 org-time-stamp-custom-formats
10549 org-time-stamp-formats))
10550 (fmt (if (or with-time
10551 (and (boundp 'org-time-was-given) org-time-was-given))
10552 (cdr fmts)
10553 (car fmts)))
10554 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10555 (when (and org-end-time-was-given
10556 (string-match org-plain-time-of-day-regexp txt))
10557 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10558 org-end-time-was-given
10559 (substring txt (match-end 0)))))
10560 (setq org-read-date-overlay
10561 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10562 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10563
10564 (defun org-read-date-analyze (ans def defdecode)
10565 "Analyze the combined answer of the date prompt."
10566 ;; FIXME: cleanup and comment
10567 (let (delta deltan deltaw deltadef year month day
10568 hour minute second wday pm h2 m2 tl wday1
10569 iso-year iso-weekday iso-week iso-year iso-date)
10570
10571 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10572 (setq ans "+0"))
10573
10574 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10575 (setq ans (replace-match "" t t ans)
10576 deltan (car delta)
10577 deltaw (nth 1 delta)
10578 deltadef (nth 2 delta)))
10579
10580 ;; Check if there is an iso week date in there
10581 ;; If yes, sore the info and ostpone interpreting it until the rest
10582 ;; of the parsing is done
10583 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10584 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10585 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10586 iso-week (string-to-number (match-string 2 ans)))
10587 (setq ans (replace-match "" t t ans)))
10588
10589 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10590 (when (string-match
10591 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10592 (setq year (if (match-end 2)
10593 (string-to-number (match-string 2 ans))
10594 (string-to-number (format-time-string "%Y")))
10595 month (string-to-number (match-string 3 ans))
10596 day (string-to-number (match-string 4 ans)))
10597 (if (< year 100) (setq year (+ 2000 year)))
10598 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10599 t nil ans)))
10600 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10601 ;; If there is a time with am/pm, and *no* time without it, we convert
10602 ;; so that matching will be successful.
10603 (loop for i from 1 to 2 do ; twice, for end time as well
10604 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10605 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10606 (setq hour (string-to-number (match-string 1 ans))
10607 minute (if (match-end 3)
10608 (string-to-number (match-string 3 ans))
10609 0)
10610 pm (equal ?p
10611 (string-to-char (downcase (match-string 4 ans)))))
10612 (if (and (= hour 12) (not pm))
10613 (setq hour 0)
10614 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10615 (setq ans (replace-match (format "%02d:%02d" hour minute)
10616 t t ans))))
10617
10618 ;; Check if a time range is given as a duration
10619 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10620 (setq hour (string-to-number (match-string 1 ans))
10621 h2 (+ hour (string-to-number (match-string 3 ans)))
10622 minute (string-to-number (match-string 2 ans))
10623 m2 (+ minute (if (match-end 5) (string-to-number
10624 (match-string 5 ans))0)))
10625 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10626 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10627 t t ans)))
10628
10629 ;; Check if there is a time range
10630 (when (boundp 'org-end-time-was-given)
10631 (setq org-time-was-given nil)
10632 (when (and (string-match org-plain-time-of-day-regexp ans)
10633 (match-end 8))
10634 (setq org-end-time-was-given (match-string 8 ans))
10635 (setq ans (concat (substring ans 0 (match-beginning 7))
10636 (substring ans (match-end 7))))))
10637
10638 (setq tl (parse-time-string ans)
10639 day (or (nth 3 tl) (nth 3 defdecode))
10640 month (or (nth 4 tl)
10641 (if (and org-read-date-prefer-future
10642 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10643 (1+ (nth 4 defdecode))
10644 (nth 4 defdecode)))
10645 year (or (nth 5 tl)
10646 (if (and org-read-date-prefer-future
10647 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10648 (1+ (nth 5 defdecode))
10649 (nth 5 defdecode)))
10650 hour (or (nth 2 tl) (nth 2 defdecode))
10651 minute (or (nth 1 tl) (nth 1 defdecode))
10652 second (or (nth 0 tl) 0)
10653 wday (nth 6 tl))
10654
10655 ;; Special date definitions below
10656 (cond
10657 (iso-week
10658 ;; There was an iso week
10659 (setq year (or iso-year year)
10660 day (or iso-weekday wday 1)
10661 wday nil ; to make sure that the trigger below does not match
10662 iso-date (calendar-gregorian-from-absolute
10663 (calendar-absolute-from-iso
10664 (list iso-week day year))))
10665 ; FIXME: Should we also push ISO weeks into the future?
10666 ; (when (and org-read-date-prefer-future
10667 ; (not iso-year)
10668 ; (< (calendar-absolute-from-gregorian iso-date)
10669 ; (time-to-days (current-time))))
10670 ; (setq year (1+ year)
10671 ; iso-date (calendar-gregorian-from-absolute
10672 ; (calendar-absolute-from-iso
10673 ; (list iso-week day year)))))
10674 (setq month (car iso-date)
10675 year (nth 2 iso-date)
10676 day (nth 1 iso-date)))
10677 (deltan
10678 (unless deltadef
10679 (let ((now (decode-time (current-time))))
10680 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10681 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10682 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10683 ((equal deltaw "m") (setq month (+ month deltan)))
10684 ((equal deltaw "y") (setq year (+ year deltan)))))
10685 ((and wday (not (nth 3 tl)))
10686 ;; Weekday was given, but no day, so pick that day in the week
10687 ;; on or after the derived date.
10688 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10689 (unless (equal wday wday1)
10690 (setq day (+ day (% (- wday wday1 -7) 7))))))
10691 (if (and (boundp 'org-time-was-given)
10692 (nth 2 tl))
10693 (setq org-time-was-given t))
10694 (if (< year 100) (setq year (+ 2000 year)))
10695 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10696 (list second minute hour day month year)))
10697
10698 (defvar parse-time-weekdays)
10699
10700 (defun org-read-date-get-relative (s today default)
10701 "Check string S for special relative date string.
10702 TODAY and DEFAULT are internal times, for today and for a default.
10703 Return shift list (N what def-flag)
10704 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10705 N is the number of WHATs to shift.
10706 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10707 the DEFAULT date rather than TODAY."
10708 (when (and
10709 (string-match
10710 (concat
10711 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
10712 "\\([0-9]+\\)?"
10713 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10714 "\\([ \t]\\|$\\)") s)
10715 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
10716 (let* ((dir (if (> (match-end 1) (match-beginning 1))
10717 (string-to-char (substring (match-string 1 s) -1))
10718 ?+))
10719 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10720 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10721 (what (if (match-end 3) (match-string 3 s) "d"))
10722 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10723 (date (if rel default today))
10724 (wday (nth 6 (decode-time date)))
10725 delta)
10726 (if wday1
10727 (progn
10728 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10729 (if (= dir ?-) (setq delta (- delta 7)))
10730 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10731 (list delta "d" rel))
10732 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10733
10734 (defun org-eval-in-calendar (form &optional keepdate)
10735 "Eval FORM in the calendar window and return to current window.
10736 Also, store the cursor date in variable org-ans2."
10737 (let ((sw (selected-window)))
10738 (select-window (get-buffer-window "*Calendar*"))
10739 (eval form)
10740 (when (and (not keepdate) (calendar-cursor-to-date))
10741 (let* ((date (calendar-cursor-to-date))
10742 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10743 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10744 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10745 (select-window sw)))
10746
10747 (defun org-calendar-select ()
10748 "Return to `org-read-date' with the date currently selected.
10749 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10750 (interactive)
10751 (when (calendar-cursor-to-date)
10752 (let* ((date (calendar-cursor-to-date))
10753 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10754 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10755 (if (active-minibuffer-window) (exit-minibuffer))))
10756
10757 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10758 "Insert a date stamp for the date given by the internal TIME.
10759 WITH-HM means, use the stamp format that includes the time of the day.
10760 INACTIVE means use square brackets instead of angular ones, so that the
10761 stamp will not contribute to the agenda.
10762 PRE and POST are optional strings to be inserted before and after the
10763 stamp.
10764 The command returns the inserted time stamp."
10765 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10766 stamp)
10767 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10768 (insert-before-markers (or pre ""))
10769 (insert-before-markers (setq stamp (format-time-string fmt time)))
10770 (when (listp extra)
10771 (setq extra (car extra))
10772 (if (and (stringp extra)
10773 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10774 (setq extra (format "-%02d:%02d"
10775 (string-to-number (match-string 1 extra))
10776 (string-to-number (match-string 2 extra))))
10777 (setq extra nil)))
10778 (when extra
10779 (backward-char 1)
10780 (insert-before-markers extra)
10781 (forward-char 1))
10782 (insert-before-markers (or post ""))
10783 (setq org-last-inserted-timestamp stamp)))
10784
10785 (defun org-toggle-time-stamp-overlays ()
10786 "Toggle the use of custom time stamp formats."
10787 (interactive)
10788 (setq org-display-custom-times (not org-display-custom-times))
10789 (unless org-display-custom-times
10790 (let ((p (point-min)) (bmp (buffer-modified-p)))
10791 (while (setq p (next-single-property-change p 'display))
10792 (if (and (get-text-property p 'display)
10793 (eq (get-text-property p 'face) 'org-date))
10794 (remove-text-properties
10795 p (setq p (next-single-property-change p 'display))
10796 '(display t))))
10797 (set-buffer-modified-p bmp)))
10798 (if (featurep 'xemacs)
10799 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10800 (org-restart-font-lock)
10801 (setq org-table-may-need-update t)
10802 (if org-display-custom-times
10803 (message "Time stamps are overlayed with custom format")
10804 (message "Time stamp overlays removed")))
10805
10806 (defun org-display-custom-time (beg end)
10807 "Overlay modified time stamp format over timestamp between BEG and END."
10808 (let* ((ts (buffer-substring beg end))
10809 t1 w1 with-hm tf time str w2 (off 0))
10810 (save-match-data
10811 (setq t1 (org-parse-time-string ts t))
10812 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10813 (setq off (- (match-end 0) (match-beginning 0)))))
10814 (setq end (- end off))
10815 (setq w1 (- end beg)
10816 with-hm (and (nth 1 t1) (nth 2 t1))
10817 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10818 time (org-fix-decoded-time t1)
10819 str (org-add-props
10820 (format-time-string
10821 (substring tf 1 -1) (apply 'encode-time time))
10822 nil 'mouse-face 'highlight)
10823 w2 (length str))
10824 (if (not (= w2 w1))
10825 (add-text-properties (1+ beg) (+ 2 beg)
10826 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10827 (if (featurep 'xemacs)
10828 (progn
10829 (put-text-property beg end 'invisible t)
10830 (put-text-property beg end 'end-glyph (make-glyph str)))
10831 (put-text-property beg end 'display str))))
10832
10833 (defun org-translate-time (string)
10834 "Translate all timestamps in STRING to custom format.
10835 But do this only if the variable `org-display-custom-times' is set."
10836 (when org-display-custom-times
10837 (save-match-data
10838 (let* ((start 0)
10839 (re org-ts-regexp-both)
10840 t1 with-hm inactive tf time str beg end)
10841 (while (setq start (string-match re string start))
10842 (setq beg (match-beginning 0)
10843 end (match-end 0)
10844 t1 (save-match-data
10845 (org-parse-time-string (substring string beg end) t))
10846 with-hm (and (nth 1 t1) (nth 2 t1))
10847 inactive (equal (substring string beg (1+ beg)) "[")
10848 tf (funcall (if with-hm 'cdr 'car)
10849 org-time-stamp-custom-formats)
10850 time (org-fix-decoded-time t1)
10851 str (format-time-string
10852 (concat
10853 (if inactive "[" "<") (substring tf 1 -1)
10854 (if inactive "]" ">"))
10855 (apply 'encode-time time))
10856 string (replace-match str t t string)
10857 start (+ start (length str)))))))
10858 string)
10859
10860 (defun org-fix-decoded-time (time)
10861 "Set 0 instead of nil for the first 6 elements of time.
10862 Don't touch the rest."
10863 (let ((n 0))
10864 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10865
10866 (defun org-days-to-time (timestamp-string)
10867 "Difference between TIMESTAMP-STRING and now in days."
10868 (- (time-to-days (org-time-string-to-time timestamp-string))
10869 (time-to-days (current-time))))
10870
10871 (defun org-deadline-close (timestamp-string &optional ndays)
10872 "Is the time in TIMESTAMP-STRING close to the current date?"
10873 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10874 (and (< (org-days-to-time timestamp-string) ndays)
10875 (not (org-entry-is-done-p))))
10876
10877 (defun org-get-wdays (ts)
10878 "Get the deadline lead time appropriate for timestring TS."
10879 (cond
10880 ((<= org-deadline-warning-days 0)
10881 ;; 0 or negative, enforce this value no matter what
10882 (- org-deadline-warning-days))
10883 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10884 ;; lead time is specified.
10885 (floor (* (string-to-number (match-string 1 ts))
10886 (cdr (assoc (match-string 2 ts)
10887 '(("d" . 1) ("w" . 7)
10888 ("m" . 30.4) ("y" . 365.25)))))))
10889 ;; go for the default.
10890 (t org-deadline-warning-days)))
10891
10892 (defun org-calendar-select-mouse (ev)
10893 "Return to `org-read-date' with the date currently selected.
10894 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10895 (interactive "e")
10896 (mouse-set-point ev)
10897 (when (calendar-cursor-to-date)
10898 (let* ((date (calendar-cursor-to-date))
10899 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10900 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10901 (if (active-minibuffer-window) (exit-minibuffer))))
10902
10903 (defun org-check-deadlines (ndays)
10904 "Check if there are any deadlines due or past due.
10905 A deadline is considered due if it happens within `org-deadline-warning-days'
10906 days from today's date. If the deadline appears in an entry marked DONE,
10907 it is not shown. The prefix arg NDAYS can be used to test that many
10908 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10909 (interactive "P")
10910 (let* ((org-warn-days
10911 (cond
10912 ((equal ndays '(4)) 100000)
10913 (ndays (prefix-numeric-value ndays))
10914 (t (abs org-deadline-warning-days))))
10915 (case-fold-search nil)
10916 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10917 (callback
10918 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10919
10920 (message "%d deadlines past-due or due within %d days"
10921 (org-occur regexp nil callback)
10922 org-warn-days)))
10923
10924 (defun org-check-before-date (date)
10925 "Check if there are deadlines or scheduled entries before DATE."
10926 (interactive (list (org-read-date)))
10927 (let ((case-fold-search nil)
10928 (regexp (concat "\\<\\(" org-deadline-string
10929 "\\|" org-scheduled-string
10930 "\\) *<\\([^>]+\\)>"))
10931 (callback
10932 (lambda () (time-less-p
10933 (org-time-string-to-time (match-string 2))
10934 (org-time-string-to-time date)))))
10935 (message "%d entries before %s"
10936 (org-occur regexp nil callback) date)))
10937
10938 (defun org-evaluate-time-range (&optional to-buffer)
10939 "Evaluate a time range by computing the difference between start and end.
10940 Normally the result is just printed in the echo area, but with prefix arg
10941 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10942 If the time range is actually in a table, the result is inserted into the
10943 next column.
10944 For time difference computation, a year is assumed to be exactly 365
10945 days in order to avoid rounding problems."
10946 (interactive "P")
10947 (or
10948 (org-clock-update-time-maybe)
10949 (save-excursion
10950 (unless (org-at-date-range-p t)
10951 (goto-char (point-at-bol))
10952 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10953 (if (not (org-at-date-range-p t))
10954 (error "Not at a time-stamp range, and none found in current line")))
10955 (let* ((ts1 (match-string 1))
10956 (ts2 (match-string 2))
10957 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10958 (match-end (match-end 0))
10959 (time1 (org-time-string-to-time ts1))
10960 (time2 (org-time-string-to-time ts2))
10961 (t1 (time-to-seconds time1))
10962 (t2 (time-to-seconds time2))
10963 (diff (abs (- t2 t1)))
10964 (negative (< (- t2 t1) 0))
10965 ;; (ys (floor (* 365 24 60 60)))
10966 (ds (* 24 60 60))
10967 (hs (* 60 60))
10968 (fy "%dy %dd %02d:%02d")
10969 (fy1 "%dy %dd")
10970 (fd "%dd %02d:%02d")
10971 (fd1 "%dd")
10972 (fh "%02d:%02d")
10973 y d h m align)
10974 (if havetime
10975 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10976 y 0
10977 d (floor (/ diff ds)) diff (mod diff ds)
10978 h (floor (/ diff hs)) diff (mod diff hs)
10979 m (floor (/ diff 60)))
10980 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10981 y 0
10982 d (floor (+ (/ diff ds) 0.5))
10983 h 0 m 0))
10984 (if (not to-buffer)
10985 (message "%s" (org-make-tdiff-string y d h m))
10986 (if (org-at-table-p)
10987 (progn
10988 (goto-char match-end)
10989 (setq align t)
10990 (and (looking-at " *|") (goto-char (match-end 0))))
10991 (goto-char match-end))
10992 (if (looking-at
10993 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10994 (replace-match ""))
10995 (if negative (insert " -"))
10996 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10997 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10998 (insert " " (format fh h m))))
10999 (if align (org-table-align))
11000 (message "Time difference inserted")))))
11001
11002 (defun org-make-tdiff-string (y d h m)
11003 (let ((fmt "")
11004 (l nil))
11005 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11006 l (push y l)))
11007 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11008 l (push d l)))
11009 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11010 l (push h l)))
11011 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11012 l (push m l)))
11013 (apply 'format fmt (nreverse l))))
11014
11015 (defun org-time-string-to-time (s)
11016 (apply 'encode-time (org-parse-time-string s)))
11017
11018 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11019 "Convert a time stamp to an absolute day number.
11020 If there is a specifyer for a cyclic time stamp, get the closest date to
11021 DAYNR.
11022 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11023 (cond
11024 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11025 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11026 daynr
11027 (+ daynr 1000)))
11028 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11029 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11030 (time-to-days (current-time))) (match-string 0 s)
11031 prefer show-all))
11032 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11033
11034 (defun org-days-to-iso-week (days)
11035 "Return the iso week number."
11036 (require 'cal-iso)
11037 (car (calendar-iso-from-absolute days)))
11038
11039 (defun org-small-year-to-year (year)
11040 "Convert 2-digit years into 4-digit years.
11041 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11042 The year 2000 cannot be abbreviated. Any year lager than 99
11043 is retrned unchanged."
11044 (if (< year 38)
11045 (setq year (+ 2000 year))
11046 (if (< year 100)
11047 (setq year (+ 1900 year))))
11048 year)
11049
11050 (defun org-time-from-absolute (d)
11051 "Return the time corresponding to date D.
11052 D may be an absolute day number, or a calendar-type list (month day year)."
11053 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11054 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11055
11056 (defun org-calendar-holiday ()
11057 "List of holidays, for Diary display in Org-mode."
11058 (require 'holidays)
11059 (let ((hl (funcall
11060 (if (fboundp 'calendar-check-holidays)
11061 'calendar-check-holidays 'check-calendar-holidays) date)))
11062 (if hl (mapconcat 'identity hl "; "))))
11063
11064 (defun org-diary-sexp-entry (sexp entry date)
11065 "Process a SEXP diary ENTRY for DATE."
11066 (require 'diary-lib)
11067 (let ((result (if calendar-debug-sexp
11068 (let ((stack-trace-on-error t))
11069 (eval (car (read-from-string sexp))))
11070 (condition-case nil
11071 (eval (car (read-from-string sexp)))
11072 (error
11073 (beep)
11074 (message "Bad sexp at line %d in %s: %s"
11075 (org-current-line)
11076 (buffer-file-name) sexp)
11077 (sleep-for 2))))))
11078 (cond ((stringp result) result)
11079 ((and (consp result)
11080 (stringp (cdr result))) (cdr result))
11081 (result entry)
11082 (t nil))))
11083
11084 (defun org-diary-to-ical-string (frombuf)
11085 "Get iCalendar entries from diary entries in buffer FROMBUF.
11086 This uses the icalendar.el library."
11087 (let* ((tmpdir (if (featurep 'xemacs)
11088 (temp-directory)
11089 temporary-file-directory))
11090 (tmpfile (make-temp-name
11091 (expand-file-name "orgics" tmpdir)))
11092 buf rtn b e)
11093 (save-excursion
11094 (set-buffer frombuf)
11095 (icalendar-export-region (point-min) (point-max) tmpfile)
11096 (setq buf (find-buffer-visiting tmpfile))
11097 (set-buffer buf)
11098 (goto-char (point-min))
11099 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11100 (setq b (match-beginning 0)))
11101 (goto-char (point-max))
11102 (if (re-search-backward "^END:VEVENT" nil t)
11103 (setq e (match-end 0)))
11104 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11105 (kill-buffer buf)
11106 (delete-file tmpfile)
11107 rtn))
11108
11109 (defun org-closest-date (start current change prefer show-all)
11110 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11111 When PREFER is `past' return a date that is either CURRENT or past.
11112 When PREFER is `future', return a date that is either CURRENT or future.
11113 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11114 ;; Make the proper lists from the dates
11115 (catch 'exit
11116 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11117 dn dw sday cday n1 n2
11118 d m y y1 y2 date1 date2 nmonths nm ny m2)
11119
11120 (setq start (org-date-to-gregorian start)
11121 current (org-date-to-gregorian
11122 (if show-all
11123 current
11124 (time-to-days (current-time))))
11125 sday (calendar-absolute-from-gregorian start)
11126 cday (calendar-absolute-from-gregorian current))
11127
11128 (if (<= cday sday) (throw 'exit sday))
11129
11130 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11131 (setq dn (string-to-number (match-string 1 change))
11132 dw (cdr (assoc (match-string 2 change) a1)))
11133 (error "Invalid change specifyer: %s" change))
11134 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11135 (cond
11136 ((eq dw 'day)
11137 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11138 n2 (+ n1 dn)))
11139 ((eq dw 'year)
11140 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11141 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11142 (setq date1 (list m d y1)
11143 n1 (calendar-absolute-from-gregorian date1)
11144 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11145 n2 (calendar-absolute-from-gregorian date2)))
11146 ((eq dw 'month)
11147 ;; approx number of month between the two dates
11148 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11149 ;; How often does dn fit in there?
11150 (setq d (nth 1 start) m (car start) y (nth 2 start)
11151 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11152 m (+ m nm)
11153 ny (floor (/ m 12))
11154 y (+ y ny)
11155 m (- m (* ny 12)))
11156 (while (> m 12) (setq m (- m 12) y (1+ y)))
11157 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11158 (setq m2 (+ m dn) y2 y)
11159 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11160 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11161 (while (<= n2 cday)
11162 (setq n1 n2 m m2 y y2)
11163 (setq m2 (+ m dn) y2 y)
11164 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11165 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11166 (if show-all
11167 (cond
11168 ((eq prefer 'past) n1)
11169 ((eq prefer 'future) (if (= cday n1) n1 n2))
11170 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11171 (cond
11172 ((eq prefer 'past) n1)
11173 ((eq prefer 'future) (if (= cday n1) n1 n2))
11174 (t (if (= cday n1) n1 n2)))))))
11175
11176 (defun org-date-to-gregorian (date)
11177 "Turn any specification of DATE into a gregorian date for the calendar."
11178 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11179 ((and (listp date) (= (length date) 3)) date)
11180 ((stringp date)
11181 (setq date (org-parse-time-string date))
11182 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11183 ((listp date)
11184 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11185
11186 (defun org-parse-time-string (s &optional nodefault)
11187 "Parse the standard Org-mode time string.
11188 This should be a lot faster than the normal `parse-time-string'.
11189 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11190 hour and minute fields will be nil if not given."
11191 (if (string-match org-ts-regexp0 s)
11192 (list 0
11193 (if (or (match-beginning 8) (not nodefault))
11194 (string-to-number (or (match-string 8 s) "0")))
11195 (if (or (match-beginning 7) (not nodefault))
11196 (string-to-number (or (match-string 7 s) "0")))
11197 (string-to-number (match-string 4 s))
11198 (string-to-number (match-string 3 s))
11199 (string-to-number (match-string 2 s))
11200 nil nil nil)
11201 (make-list 9 0)))
11202
11203 (defun org-timestamp-up (&optional arg)
11204 "Increase the date item at the cursor by one.
11205 If the cursor is on the year, change the year. If it is on the month or
11206 the day, change that.
11207 With prefix ARG, change by that many units."
11208 (interactive "p")
11209 (org-timestamp-change (prefix-numeric-value arg)))
11210
11211 (defun org-timestamp-down (&optional arg)
11212 "Decrease the date item at the cursor by one.
11213 If the cursor is on the year, change the year. If it is on the month or
11214 the day, change that.
11215 With prefix ARG, change by that many units."
11216 (interactive "p")
11217 (org-timestamp-change (- (prefix-numeric-value arg))))
11218
11219 (defun org-timestamp-up-day (&optional arg)
11220 "Increase the date in the time stamp by one day.
11221 With prefix ARG, change that many days."
11222 (interactive "p")
11223 (if (and (not (org-at-timestamp-p t))
11224 (org-on-heading-p))
11225 (org-todo 'up)
11226 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11227
11228 (defun org-timestamp-down-day (&optional arg)
11229 "Decrease the date in the time stamp by one day.
11230 With prefix ARG, change that many days."
11231 (interactive "p")
11232 (if (and (not (org-at-timestamp-p t))
11233 (org-on-heading-p))
11234 (org-todo 'down)
11235 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11236
11237 (defun org-at-timestamp-p (&optional inactive-ok)
11238 "Determine if the cursor is in or at a timestamp."
11239 (interactive)
11240 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11241 (pos (point))
11242 (ans (or (looking-at tsr)
11243 (save-excursion
11244 (skip-chars-backward "^[<\n\r\t")
11245 (if (> (point) (point-min)) (backward-char 1))
11246 (and (looking-at tsr)
11247 (> (- (match-end 0) pos) -1))))))
11248 (and ans
11249 (boundp 'org-ts-what)
11250 (setq org-ts-what
11251 (cond
11252 ((= pos (match-beginning 0)) 'bracket)
11253 ((= pos (1- (match-end 0))) 'bracket)
11254 ((org-pos-in-match-range pos 2) 'year)
11255 ((org-pos-in-match-range pos 3) 'month)
11256 ((org-pos-in-match-range pos 7) 'hour)
11257 ((org-pos-in-match-range pos 8) 'minute)
11258 ((or (org-pos-in-match-range pos 4)
11259 (org-pos-in-match-range pos 5)) 'day)
11260 ((and (> pos (or (match-end 8) (match-end 5)))
11261 (< pos (match-end 0)))
11262 (- pos (or (match-end 8) (match-end 5))))
11263 (t 'day))))
11264 ans))
11265
11266 (defun org-toggle-timestamp-type ()
11267 "Toggle the type (<active> or [inactive]) of a time stamp."
11268 (interactive)
11269 (when (org-at-timestamp-p t)
11270 (save-excursion
11271 (goto-char (match-beginning 0))
11272 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11273 (goto-char (1- (match-end 0)))
11274 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11275 (message "Timestamp is now %sactive"
11276 (if (equal (char-before) ?>) "in" ""))))
11277
11278 (defun org-timestamp-change (n &optional what)
11279 "Change the date in the time stamp at point.
11280 The date will be changed by N times WHAT. WHAT can be `day', `month',
11281 `year', `minute', `second'. If WHAT is not given, the cursor position
11282 in the timestamp determines what will be changed."
11283 (let ((pos (point))
11284 with-hm inactive
11285 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11286 org-ts-what
11287 extra rem
11288 ts time time0)
11289 (if (not (org-at-timestamp-p t))
11290 (error "Not at a timestamp"))
11291 (if (and (not what) (eq org-ts-what 'bracket))
11292 (org-toggle-timestamp-type)
11293 (if (and (not what) (not (eq org-ts-what 'day))
11294 org-display-custom-times
11295 (get-text-property (point) 'display)
11296 (not (get-text-property (1- (point)) 'display)))
11297 (setq org-ts-what 'day))
11298 (setq org-ts-what (or what org-ts-what)
11299 inactive (= (char-after (match-beginning 0)) ?\[)
11300 ts (match-string 0))
11301 (replace-match "")
11302 (if (string-match
11303 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11304 ts)
11305 (setq extra (match-string 1 ts)))
11306 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11307 (setq with-hm t))
11308 (setq time0 (org-parse-time-string ts))
11309 (when (and (eq org-ts-what 'minute)
11310 (eq current-prefix-arg nil))
11311 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11312 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11313 (setcar (cdr time0) (+ (nth 1 time0)
11314 (if (> n 0) (- rem) (- dm rem))))))
11315 (setq time
11316 (encode-time (or (car time0) 0)
11317 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11318 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11319 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11320 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11321 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11322 (nthcdr 6 time0)))
11323 (when (integerp org-ts-what)
11324 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11325 (if (eq what 'calendar)
11326 (let ((cal-date (org-get-date-from-calendar)))
11327 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11328 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11329 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11330 (setcar time0 (or (car time0) 0))
11331 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11332 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11333 (setq time (apply 'encode-time time0))))
11334 (setq org-last-changed-timestamp
11335 (org-insert-time-stamp time with-hm inactive nil nil extra))
11336 (org-clock-update-time-maybe)
11337 (goto-char pos)
11338 ;; Try to recenter the calendar window, if any
11339 (if (and org-calendar-follow-timestamp-change
11340 (get-buffer-window "*Calendar*" t)
11341 (memq org-ts-what '(day month year)))
11342 (org-recenter-calendar (time-to-days time))))))
11343
11344 (defun org-modify-ts-extra (s pos n dm)
11345 "Change the different parts of the lead-time and repeat fields in timestamp."
11346 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11347 ng h m new rem)
11348 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11349 (cond
11350 ((or (org-pos-in-match-range pos 2)
11351 (org-pos-in-match-range pos 3))
11352 (setq m (string-to-number (match-string 3 s))
11353 h (string-to-number (match-string 2 s)))
11354 (if (org-pos-in-match-range pos 2)
11355 (setq h (+ h n))
11356 (setq n (* dm (org-no-warnings (signum n))))
11357 (when (not (= 0 (setq rem (% m dm))))
11358 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11359 (setq m (+ m n)))
11360 (if (< m 0) (setq m (+ m 60) h (1- h)))
11361 (if (> m 59) (setq m (- m 60) h (1+ h)))
11362 (setq h (min 24 (max 0 h)))
11363 (setq ng 1 new (format "-%02d:%02d" h m)))
11364 ((org-pos-in-match-range pos 6)
11365 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11366 ((org-pos-in-match-range pos 5)
11367 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11368
11369 ((org-pos-in-match-range pos 9)
11370 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11371 ((org-pos-in-match-range pos 8)
11372 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11373
11374 (when ng
11375 (setq s (concat
11376 (substring s 0 (match-beginning ng))
11377 new
11378 (substring s (match-end ng))))))
11379 s))
11380
11381 (defun org-recenter-calendar (date)
11382 "If the calendar is visible, recenter it to DATE."
11383 (let* ((win (selected-window))
11384 (cwin (get-buffer-window "*Calendar*" t))
11385 (calendar-move-hook nil))
11386 (when cwin
11387 (select-window cwin)
11388 (calendar-goto-date (if (listp date) date
11389 (calendar-gregorian-from-absolute date)))
11390 (select-window win))))
11391
11392 (defun org-goto-calendar (&optional arg)
11393 "Go to the Emacs calendar at the current date.
11394 If there is a time stamp in the current line, go to that date.
11395 A prefix ARG can be used to force the current date."
11396 (interactive "P")
11397 (let ((tsr org-ts-regexp) diff
11398 (calendar-move-hook nil)
11399 (calendar-view-holidays-initially-flag nil)
11400 (view-calendar-holidays-initially nil)
11401 (calendar-view-diary-initially-flag nil)
11402 (view-diary-entries-initially nil))
11403 (if (or (org-at-timestamp-p)
11404 (save-excursion
11405 (beginning-of-line 1)
11406 (looking-at (concat ".*" tsr))))
11407 (let ((d1 (time-to-days (current-time)))
11408 (d2 (time-to-days
11409 (org-time-string-to-time (match-string 1)))))
11410 (setq diff (- d2 d1))))
11411 (calendar)
11412 (calendar-goto-today)
11413 (if (and diff (not arg)) (calendar-forward-day diff))))
11414
11415 (defun org-get-date-from-calendar ()
11416 "Return a list (month day year) of date at point in calendar."
11417 (with-current-buffer "*Calendar*"
11418 (save-match-data
11419 (calendar-cursor-to-date))))
11420
11421 (defun org-date-from-calendar ()
11422 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11423 If there is already a time stamp at the cursor position, update it."
11424 (interactive)
11425 (if (org-at-timestamp-p t)
11426 (org-timestamp-change 0 'calendar)
11427 (let ((cal-date (org-get-date-from-calendar)))
11428 (org-insert-time-stamp
11429 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11430
11431 (defun org-minutes-to-hh:mm-string (m)
11432 "Compute H:MM from a number of minutes."
11433 (let ((h (/ m 60)))
11434 (setq m (- m (* 60 h)))
11435 (format org-time-clocksum-format h m)))
11436
11437 (defun org-hh:mm-string-to-minutes (s)
11438 "Convert a string H:MM to a number of minutes."
11439 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11440 (+ (* (string-to-number (match-string 1 s)) 60)
11441 (string-to-number (match-string 2 s)))
11442 0))
11443
11444 ;;;; Agenda files
11445
11446 ;;;###autoload
11447 (defun org-iswitchb (&optional arg)
11448 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11449 With a prefix argument, restrict available to files.
11450 With two prefix arguments, restrict available buffers to agenda files.
11451
11452 Due to some yet unresolved reason, the global function
11453 `iswitchb-mode' needs to be active for this function to work."
11454 (interactive "P")
11455 (require 'iswitchb)
11456 (let ((enabled iswitchb-mode) blist)
11457 (or enabled (iswitchb-mode 1))
11458 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11459 ((equal arg '(16)) (org-buffer-list 'agenda))
11460 (t (org-buffer-list))))
11461 (unwind-protect
11462 (let ((iswitchb-make-buflist-hook
11463 (lambda ()
11464 (setq iswitchb-temp-buflist
11465 (mapcar 'buffer-name blist)))))
11466 (switch-to-buffer
11467 (iswitchb-read-buffer
11468 "Switch-to: " nil t))
11469 (or enabled (iswitchb-mode -1))))))
11470
11471 (defun org-buffer-list (&optional predicate exclude-tmp)
11472 "Return a list of Org buffers.
11473 PREDICATE can be `export', `files' or `agenda'.
11474
11475 export restrict the list to Export buffers.
11476 files restrict the list to buffers visiting Org files.
11477 agenda restrict the list to buffers visiting agenda files.
11478
11479 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11480 (let* ((bfn nil)
11481 (agenda-files (and (eq predicate 'agenda)
11482 (mapcar 'file-truename (org-agenda-files t))))
11483 (filter
11484 (cond
11485 ((eq predicate 'files)
11486 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11487 ((eq predicate 'export)
11488 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11489 ((eq predicate 'agenda)
11490 (lambda (b)
11491 (with-current-buffer b
11492 (and (eq major-mode 'org-mode)
11493 (setq bfn (buffer-file-name b))
11494 (member (file-truename bfn) agenda-files)))))
11495 (t (lambda (b) (with-current-buffer b
11496 (or (eq major-mode 'org-mode)
11497 (string-match "\*Org .*Export"
11498 (buffer-name b)))))))))
11499 (delq nil
11500 (mapcar
11501 (lambda(b)
11502 (if (and (funcall filter b)
11503 (or (not exclude-tmp)
11504 (not (string-match "tmp" (buffer-name b)))))
11505 b
11506 nil))
11507 (buffer-list)))))
11508
11509 (defun org-agenda-files (&optional unrestricted archives)
11510 "Get the list of agenda files.
11511 Optional UNRESTRICTED means return the full list even if a restriction
11512 is currently in place.
11513 When ARCHIVES is t, include all archive files hat are really being
11514 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11515 `org-agenda-archives-mode' is t."
11516 (let ((files
11517 (cond
11518 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11519 ((stringp org-agenda-files) (org-read-agenda-file-list))
11520 ((listp org-agenda-files) org-agenda-files)
11521 (t (error "Invalid value of `org-agenda-files'")))))
11522 (setq files (apply 'append
11523 (mapcar (lambda (f)
11524 (if (file-directory-p f)
11525 (directory-files
11526 f t org-agenda-file-regexp)
11527 (list f)))
11528 files)))
11529 (when org-agenda-skip-unavailable-files
11530 (setq files (delq nil
11531 (mapcar (function
11532 (lambda (file)
11533 (and (file-readable-p file) file)))
11534 files))))
11535 (when (or (eq archives t)
11536 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11537 (setq files (org-add-archive-files files)))
11538 files))
11539
11540 (defun org-edit-agenda-file-list ()
11541 "Edit the list of agenda files.
11542 Depending on setup, this either uses customize to edit the variable
11543 `org-agenda-files', or it visits the file that is holding the list. In the
11544 latter case, the buffer is set up in a way that saving it automatically kills
11545 the buffer and restores the previous window configuration."
11546 (interactive)
11547 (if (stringp org-agenda-files)
11548 (let ((cw (current-window-configuration)))
11549 (find-file org-agenda-files)
11550 (org-set-local 'org-window-configuration cw)
11551 (org-add-hook 'after-save-hook
11552 (lambda ()
11553 (set-window-configuration
11554 (prog1 org-window-configuration
11555 (kill-buffer (current-buffer))))
11556 (org-install-agenda-files-menu)
11557 (message "New agenda file list installed"))
11558 nil 'local)
11559 (message "%s" (substitute-command-keys
11560 "Edit list and finish with \\[save-buffer]")))
11561 (customize-variable 'org-agenda-files)))
11562
11563 (defun org-store-new-agenda-file-list (list)
11564 "Set new value for the agenda file list and save it correcly."
11565 (if (stringp org-agenda-files)
11566 (let ((f org-agenda-files) b)
11567 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11568 (with-temp-file f
11569 (insert (mapconcat 'identity list "\n") "\n")))
11570 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11571 (setq org-agenda-files list)
11572 (customize-save-variable 'org-agenda-files org-agenda-files))))
11573
11574 (defun org-read-agenda-file-list ()
11575 "Read the list of agenda files from a file."
11576 (when (file-directory-p org-agenda-files)
11577 (error "`org-agenda-files' cannot be a single directory"))
11578 (when (stringp org-agenda-files)
11579 (with-temp-buffer
11580 (insert-file-contents org-agenda-files)
11581 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11582
11583
11584 ;;;###autoload
11585 (defun org-cycle-agenda-files ()
11586 "Cycle through the files in `org-agenda-files'.
11587 If the current buffer visits an agenda file, find the next one in the list.
11588 If the current buffer does not, find the first agenda file."
11589 (interactive)
11590 (let* ((fs (org-agenda-files t))
11591 (files (append fs (list (car fs))))
11592 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11593 file)
11594 (unless files (error "No agenda files"))
11595 (catch 'exit
11596 (while (setq file (pop files))
11597 (if (equal (file-truename file) tcf)
11598 (when (car files)
11599 (find-file (car files))
11600 (throw 'exit t))))
11601 (find-file (car fs)))
11602 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11603
11604 (defun org-agenda-file-to-front (&optional to-end)
11605 "Move/add the current file to the top of the agenda file list.
11606 If the file is not present in the list, it is added to the front. If it is
11607 present, it is moved there. With optional argument TO-END, add/move to the
11608 end of the list."
11609 (interactive "P")
11610 (let ((org-agenda-skip-unavailable-files nil)
11611 (file-alist (mapcar (lambda (x)
11612 (cons (file-truename x) x))
11613 (org-agenda-files t)))
11614 (ctf (file-truename buffer-file-name))
11615 x had)
11616 (setq x (assoc ctf file-alist) had x)
11617
11618 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11619 (if to-end
11620 (setq file-alist (append (delq x file-alist) (list x)))
11621 (setq file-alist (cons x (delq x file-alist))))
11622 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11623 (org-install-agenda-files-menu)
11624 (message "File %s to %s of agenda file list"
11625 (if had "moved" "added") (if to-end "end" "front"))))
11626
11627 (defun org-remove-file (&optional file)
11628 "Remove current file from the list of files in variable `org-agenda-files'.
11629 These are the files which are being checked for agenda entries.
11630 Optional argument FILE means, use this file instead of the current."
11631 (interactive)
11632 (let* ((org-agenda-skip-unavailable-files nil)
11633 (file (or file buffer-file-name))
11634 (true-file (file-truename file))
11635 (afile (abbreviate-file-name file))
11636 (files (delq nil (mapcar
11637 (lambda (x)
11638 (if (equal true-file
11639 (file-truename x))
11640 nil x))
11641 (org-agenda-files t)))))
11642 (if (not (= (length files) (length (org-agenda-files t))))
11643 (progn
11644 (org-store-new-agenda-file-list files)
11645 (org-install-agenda-files-menu)
11646 (message "Removed file: %s" afile))
11647 (message "File was not in list: %s (not removed)" afile))))
11648
11649 (defun org-file-menu-entry (file)
11650 (vector file (list 'find-file file) t))
11651
11652 (defun org-check-agenda-file (file)
11653 "Make sure FILE exists. If not, ask user what to do."
11654 (when (not (file-exists-p file))
11655 (message "non-existent file %s. [R]emove from list or [A]bort?"
11656 (abbreviate-file-name file))
11657 (let ((r (downcase (read-char-exclusive))))
11658 (cond
11659 ((equal r ?r)
11660 (org-remove-file file)
11661 (throw 'nextfile t))
11662 (t (error "Abort"))))))
11663
11664 (defun org-get-agenda-file-buffer (file)
11665 "Get a buffer visiting FILE. If the buffer needs to be created, add
11666 it to the list of buffers which might be released later."
11667 (let ((buf (org-find-base-buffer-visiting file)))
11668 (if buf
11669 buf ; just return it
11670 ;; Make a new buffer and remember it
11671 (setq buf (find-file-noselect file))
11672 (if buf (push buf org-agenda-new-buffers))
11673 buf)))
11674
11675 (defun org-release-buffers (blist)
11676 "Release all buffers in list, asking the user for confirmation when needed.
11677 When a buffer is unmodified, it is just killed. When modified, it is saved
11678 \(if the user agrees) and then killed."
11679 (let (buf file)
11680 (while (setq buf (pop blist))
11681 (setq file (buffer-file-name buf))
11682 (when (and (buffer-modified-p buf)
11683 file
11684 (y-or-n-p (format "Save file %s? " file)))
11685 (with-current-buffer buf (save-buffer)))
11686 (kill-buffer buf))))
11687
11688 (defun org-prepare-agenda-buffers (files)
11689 "Create buffers for all agenda files, protect archived trees and comments."
11690 (interactive)
11691 (let ((pa '(:org-archived t))
11692 (pc '(:org-comment t))
11693 (pall '(:org-archived t :org-comment t))
11694 (inhibit-read-only t)
11695 (rea (concat ":" org-archive-tag ":"))
11696 bmp file re)
11697 (save-excursion
11698 (save-restriction
11699 (while (setq file (pop files))
11700 (if (bufferp file)
11701 (set-buffer file)
11702 (org-check-agenda-file file)
11703 (set-buffer (org-get-agenda-file-buffer file)))
11704 (widen)
11705 (setq bmp (buffer-modified-p))
11706 (org-refresh-category-properties)
11707 (setq org-todo-keywords-for-agenda
11708 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11709 (setq org-done-keywords-for-agenda
11710 (append org-done-keywords-for-agenda org-done-keywords))
11711 (setq org-todo-keyword-alist-for-agenda
11712 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
11713 (setq org-tag-alist-for-agenda
11714 (append org-tag-alist-for-agenda org-tag-alist))
11715
11716 (save-excursion
11717 (remove-text-properties (point-min) (point-max) pall)
11718 (when org-agenda-skip-archived-trees
11719 (goto-char (point-min))
11720 (while (re-search-forward rea nil t)
11721 (if (org-on-heading-p t)
11722 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11723 (goto-char (point-min))
11724 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11725 (while (re-search-forward re nil t)
11726 (add-text-properties
11727 (match-beginning 0) (org-end-of-subtree t) pc)))
11728 (set-buffer-modified-p bmp))))
11729 (setq org-todo-keyword-alist-for-agenda
11730 (org-uniquify org-todo-keyword-alist-for-agenda)
11731 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
11732
11733 ;;;; Embedded LaTeX
11734
11735 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11736 "Keymap for the minor `org-cdlatex-mode'.")
11737
11738 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11739 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11740 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11741 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11742 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11743
11744 (defvar org-cdlatex-texmathp-advice-is-done nil
11745 "Flag remembering if we have applied the advice to texmathp already.")
11746
11747 (define-minor-mode org-cdlatex-mode
11748 "Toggle the minor `org-cdlatex-mode'.
11749 This mode supports entering LaTeX environment and math in LaTeX fragments
11750 in Org-mode.
11751 \\{org-cdlatex-mode-map}"
11752 nil " OCDL" nil
11753 (when org-cdlatex-mode (require 'cdlatex))
11754 (unless org-cdlatex-texmathp-advice-is-done
11755 (setq org-cdlatex-texmathp-advice-is-done t)
11756 (defadvice texmathp (around org-math-always-on activate)
11757 "Always return t in org-mode buffers.
11758 This is because we want to insert math symbols without dollars even outside
11759 the LaTeX math segments. If Orgmode thinks that point is actually inside
11760 en embedded LaTeX fragement, let texmathp do its job.
11761 \\[org-cdlatex-mode-map]"
11762 (interactive)
11763 (let (p)
11764 (cond
11765 ((not (org-mode-p)) ad-do-it)
11766 ((eq this-command 'cdlatex-math-symbol)
11767 (setq ad-return-value t
11768 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11769 (t
11770 (let ((p (org-inside-LaTeX-fragment-p)))
11771 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11772 (setq ad-return-value t
11773 texmathp-why '("Org-mode embedded math" . 0))
11774 (if p ad-do-it)))))))))
11775
11776 (defun turn-on-org-cdlatex ()
11777 "Unconditionally turn on `org-cdlatex-mode'."
11778 (org-cdlatex-mode 1))
11779
11780 (defun org-inside-LaTeX-fragment-p ()
11781 "Test if point is inside a LaTeX fragment.
11782 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11783 sequence appearing also before point.
11784 Even though the matchers for math are configurable, this function assumes
11785 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11786 delimiters are skipped when they have been removed by customization.
11787 The return value is nil, or a cons cell with the delimiter and
11788 and the position of this delimiter.
11789
11790 This function does a reasonably good job, but can locally be fooled by
11791 for example currency specifications. For example it will assume being in
11792 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11793 fragments that are properly closed, but during editing, we have to live
11794 with the uncertainty caused by missing closing delimiters. This function
11795 looks only before point, not after."
11796 (catch 'exit
11797 (let ((pos (point))
11798 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11799 (lim (progn
11800 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11801 (point)))
11802 dd-on str (start 0) m re)
11803 (goto-char pos)
11804 (when dodollar
11805 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11806 re (nth 1 (assoc "$" org-latex-regexps)))
11807 (while (string-match re str start)
11808 (cond
11809 ((= (match-end 0) (length str))
11810 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11811 ((= (match-end 0) (- (length str) 5))
11812 (throw 'exit nil))
11813 (t (setq start (match-end 0))))))
11814 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11815 (goto-char pos)
11816 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11817 (and (match-beginning 2) (throw 'exit nil))
11818 ;; count $$
11819 (while (re-search-backward "\\$\\$" lim t)
11820 (setq dd-on (not dd-on)))
11821 (goto-char pos)
11822 (if dd-on (cons "$$" m))))))
11823
11824
11825 (defun org-try-cdlatex-tab ()
11826 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11827 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11828 - inside a LaTeX fragment, or
11829 - after the first word in a line, where an abbreviation expansion could
11830 insert a LaTeX environment."
11831 (when org-cdlatex-mode
11832 (cond
11833 ((save-excursion
11834 (skip-chars-backward "a-zA-Z0-9*")
11835 (skip-chars-backward " \t")
11836 (bolp))
11837 (cdlatex-tab) t)
11838 ((org-inside-LaTeX-fragment-p)
11839 (cdlatex-tab) t)
11840 (t nil))))
11841
11842 (defun org-cdlatex-underscore-caret (&optional arg)
11843 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11844 Revert to the normal definition outside of these fragments."
11845 (interactive "P")
11846 (if (org-inside-LaTeX-fragment-p)
11847 (call-interactively 'cdlatex-sub-superscript)
11848 (let (org-cdlatex-mode)
11849 (call-interactively (key-binding (vector last-input-event))))))
11850
11851 (defun org-cdlatex-math-modify (&optional arg)
11852 "Execute `cdlatex-math-modify' in LaTeX fragments.
11853 Revert to the normal definition outside of these fragments."
11854 (interactive "P")
11855 (if (org-inside-LaTeX-fragment-p)
11856 (call-interactively 'cdlatex-math-modify)
11857 (let (org-cdlatex-mode)
11858 (call-interactively (key-binding (vector last-input-event))))))
11859
11860 (defvar org-latex-fragment-image-overlays nil
11861 "List of overlays carrying the images of latex fragments.")
11862 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11863
11864 (defun org-remove-latex-fragment-image-overlays ()
11865 "Remove all overlays with LaTeX fragment images in current buffer."
11866 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11867 (setq org-latex-fragment-image-overlays nil))
11868
11869 (defun org-preview-latex-fragment (&optional subtree)
11870 "Preview the LaTeX fragment at point, or all locally or globally.
11871 If the cursor is in a LaTeX fragment, create the image and overlay
11872 it over the source code. If there is no fragment at point, display
11873 all fragments in the current text, from one headline to the next. With
11874 prefix SUBTREE, display all fragments in the current subtree. With a
11875 double prefix `C-u C-u', or when the cursor is before the first headline,
11876 display all fragments in the buffer.
11877 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11878 (interactive "P")
11879 (org-remove-latex-fragment-image-overlays)
11880 (save-excursion
11881 (save-restriction
11882 (let (beg end at msg)
11883 (cond
11884 ((or (equal subtree '(16))
11885 (not (save-excursion
11886 (re-search-backward (concat "^" outline-regexp) nil t))))
11887 (setq beg (point-min) end (point-max)
11888 msg "Creating images for buffer...%s"))
11889 ((equal subtree '(4))
11890 (org-back-to-heading)
11891 (setq beg (point) end (org-end-of-subtree t)
11892 msg "Creating images for subtree...%s"))
11893 (t
11894 (if (setq at (org-inside-LaTeX-fragment-p))
11895 (goto-char (max (point-min) (- (cdr at) 2)))
11896 (org-back-to-heading))
11897 (setq beg (point) end (progn (outline-next-heading) (point))
11898 msg (if at "Creating image...%s"
11899 "Creating images for entry...%s"))))
11900 (message msg "")
11901 (narrow-to-region beg end)
11902 (goto-char beg)
11903 (org-format-latex
11904 (concat "ltxpng/" (file-name-sans-extension
11905 (file-name-nondirectory
11906 buffer-file-name)))
11907 default-directory 'overlays msg at 'forbuffer)
11908 (message msg "done. Use `C-c C-c' to remove images.")))))
11909
11910 (defvar org-latex-regexps
11911 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11912 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11913 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11914 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11915 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11916 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11917 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11918 "Regular expressions for matching embedded LaTeX.")
11919
11920 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11921 "Replace LaTeX fragments with links to an image, and produce images."
11922 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11923 (let* ((prefixnodir (file-name-nondirectory prefix))
11924 (absprefix (expand-file-name prefix dir))
11925 (todir (file-name-directory absprefix))
11926 (opt org-format-latex-options)
11927 (matchers (plist-get opt :matchers))
11928 (re-list org-latex-regexps)
11929 (cnt 0) txt link beg end re e checkdir
11930 m n block linkfile movefile ov)
11931 ;; Check if there are old images files with this prefix, and remove them
11932 (when (file-directory-p todir)
11933 (mapc 'delete-file
11934 (directory-files
11935 todir 'full
11936 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11937 ;; Check the different regular expressions
11938 (while (setq e (pop re-list))
11939 (setq m (car e) re (nth 1 e) n (nth 2 e)
11940 block (if (nth 3 e) "\n\n" ""))
11941 (when (member m matchers)
11942 (goto-char (point-min))
11943 (while (re-search-forward re nil t)
11944 (when (or (not at) (equal (cdr at) (match-beginning n)))
11945 (setq txt (match-string n)
11946 beg (match-beginning n) end (match-end n)
11947 cnt (1+ cnt)
11948 linkfile (format "%s_%04d.png" prefix cnt)
11949 movefile (format "%s_%04d.png" absprefix cnt)
11950 link (concat block "[[file:" linkfile "]]" block))
11951 (if msg (message msg cnt))
11952 (goto-char beg)
11953 (unless checkdir ; make sure the directory exists
11954 (setq checkdir t)
11955 (or (file-directory-p todir) (make-directory todir)))
11956 (org-create-formula-image
11957 txt movefile opt forbuffer)
11958 (if overlays
11959 (progn
11960 (setq ov (org-make-overlay beg end))
11961 (if (featurep 'xemacs)
11962 (progn
11963 (org-overlay-put ov 'invisible t)
11964 (org-overlay-put
11965 ov 'end-glyph
11966 (make-glyph (vector 'png :file movefile))))
11967 (org-overlay-put
11968 ov 'display
11969 (list 'image :type 'png :file movefile :ascent 'center)))
11970 (push ov org-latex-fragment-image-overlays)
11971 (goto-char end))
11972 (delete-region beg end)
11973 (insert link))))))))
11974
11975 ;; This function borrows from Ganesh Swami's latex2png.el
11976 (defun org-create-formula-image (string tofile options buffer)
11977 (let* ((tmpdir (if (featurep 'xemacs)
11978 (temp-directory)
11979 temporary-file-directory))
11980 (texfilebase (make-temp-name
11981 (expand-file-name "orgtex" tmpdir)))
11982 (texfile (concat texfilebase ".tex"))
11983 (dvifile (concat texfilebase ".dvi"))
11984 (pngfile (concat texfilebase ".png"))
11985 (fnh (if (featurep 'xemacs)
11986 (font-height (get-face-font 'default))
11987 (face-attribute 'default :height nil)))
11988 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11989 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11990 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11991 "Black"))
11992 (bg (or (plist-get options (if buffer :background :html-background))
11993 "Transparent")))
11994 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11995 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11996 (with-temp-file texfile
11997 (insert org-format-latex-header
11998 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11999 (let ((dir default-directory))
12000 (condition-case nil
12001 (progn
12002 (cd tmpdir)
12003 (call-process "latex" nil nil nil texfile))
12004 (error nil))
12005 (cd dir))
12006 (if (not (file-exists-p dvifile))
12007 (progn (message "Failed to create dvi file from %s" texfile) nil)
12008 (condition-case nil
12009 (call-process "dvipng" nil nil nil
12010 "-E" "-fg" fg "-bg" bg
12011 "-D" dpi
12012 ;;"-x" scale "-y" scale
12013 "-T" "tight"
12014 "-o" pngfile
12015 dvifile)
12016 (error nil))
12017 (if (not (file-exists-p pngfile))
12018 (progn (message "Failed to create png file from %s" texfile) nil)
12019 ;; Use the requested file name and clean up
12020 (copy-file pngfile tofile 'replace)
12021 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12022 (delete-file (concat texfilebase e)))
12023 pngfile))))
12024
12025 (defun org-dvipng-color (attr)
12026 "Return an rgb color specification for dvipng."
12027 (apply 'format "rgb %s %s %s"
12028 (mapcar 'org-normalize-color
12029 (color-values (face-attribute 'default attr nil)))))
12030
12031 (defun org-normalize-color (value)
12032 "Return string to be used as color value for an RGB component."
12033 (format "%g" (/ value 65535.0)))
12034
12035
12036 ;;;; Key bindings
12037
12038 ;; Make `C-c C-x' a prefix key
12039 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12040
12041 ;; TAB key with modifiers
12042 (org-defkey org-mode-map "\C-i" 'org-cycle)
12043 (org-defkey org-mode-map [(tab)] 'org-cycle)
12044 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12045 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12046 (org-defkey org-mode-map "\M-\t" 'org-complete)
12047 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12048 ;; The following line is necessary under Suse GNU/Linux
12049 (unless (featurep 'xemacs)
12050 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12051 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12052 (define-key org-mode-map [backtab] 'org-shifttab)
12053
12054 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12055 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12056 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12057
12058 ;; Cursor keys with modifiers
12059 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12060 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12061 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12062 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12063
12064 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12065 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12066 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12067 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12068
12069 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12070 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12071 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12072 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12073
12074 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12075 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12076
12077 ;;; Extra keys for tty access.
12078 ;; We only set them when really needed because otherwise the
12079 ;; menus don't show the simple keys
12080
12081 (when (or org-use-extra-keys
12082 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12083 (not window-system))
12084 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12085 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12086 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12087 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12088 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12089 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12090 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12091 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12092 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12093 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12094 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12095 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12096 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12097 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12098 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12099 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12100 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12101 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12102 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12103 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12104 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12105 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12106
12107 ;; All the other keys
12108
12109 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12110 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12111 (if (boundp 'narrow-map)
12112 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12113 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12114 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12115 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12116 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12117 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12118 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12119 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12120 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12121 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12122 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12123 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12124 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12125 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12126 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12127 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12128 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12129 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12130 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12131 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12132 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12133 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12134 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12135 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12136 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12137 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12138 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12139 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12140 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12141 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12142 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12143 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12144 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12145 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12146 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12147 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12148 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12149 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12150 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12151 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12152 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12153 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12154 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12155 (org-defkey org-mode-map "\C-c^" 'org-sort)
12156 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12157 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12158 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12159 (org-defkey org-mode-map "\C-m" 'org-return)
12160 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12161 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12162 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12163 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12164 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12165 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12166 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12167 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12168 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12169 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12170 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12171 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12172 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12173 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12174 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12175 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12176
12177 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12178 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12179 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12180 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12181
12182 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12183 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12184 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12185 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12186 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12187 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12188 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12189 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12190 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12191 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12192 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12193 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12194
12195 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12196
12197 (when (featurep 'xemacs)
12198 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12199
12200 (defvar org-table-auto-blank-field) ; defined in org-table.el
12201 (defun org-self-insert-command (N)
12202 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12203 If the cursor is in a table looking at whitespace, the whitespace is
12204 overwritten, and the table is not marked as requiring realignment."
12205 (interactive "p")
12206 (if (and (org-table-p)
12207 (progn
12208 ;; check if we blank the field, and if that triggers align
12209 (and (featurep 'org-table) org-table-auto-blank-field
12210 (member last-command
12211 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12212 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12213 ;; got extra space, this field does not determine column width
12214 (let (org-table-may-need-update) (org-table-blank-field))
12215 ;; no extra space, this field may determine column width
12216 (org-table-blank-field)))
12217 t)
12218 (eq N 1)
12219 (looking-at "[^|\n]* |"))
12220 (let (org-table-may-need-update)
12221 (goto-char (1- (match-end 0)))
12222 (delete-backward-char 1)
12223 (goto-char (match-beginning 0))
12224 (self-insert-command N))
12225 (setq org-table-may-need-update t)
12226 (self-insert-command N)
12227 (org-fix-tags-on-the-fly)))
12228
12229 (defun org-fix-tags-on-the-fly ()
12230 (when (and (equal (char-after (point-at-bol)) ?*)
12231 (org-on-heading-p))
12232 (org-align-tags-here org-tags-column)))
12233
12234 (defun org-delete-backward-char (N)
12235 "Like `delete-backward-char', insert whitespace at field end in tables.
12236 When deleting backwards, in tables this function will insert whitespace in
12237 front of the next \"|\" separator, to keep the table aligned. The table will
12238 still be marked for re-alignment if the field did fill the entire column,
12239 because, in this case the deletion might narrow the column."
12240 (interactive "p")
12241 (if (and (org-table-p)
12242 (eq N 1)
12243 (string-match "|" (buffer-substring (point-at-bol) (point)))
12244 (looking-at ".*?|"))
12245 (let ((pos (point))
12246 (noalign (looking-at "[^|\n\r]* |"))
12247 (c org-table-may-need-update))
12248 (backward-delete-char N)
12249 (skip-chars-forward "^|")
12250 (insert " ")
12251 (goto-char (1- pos))
12252 ;; noalign: if there were two spaces at the end, this field
12253 ;; does not determine the width of the column.
12254 (if noalign (setq org-table-may-need-update c)))
12255 (backward-delete-char N)
12256 (org-fix-tags-on-the-fly)))
12257
12258 (defun org-delete-char (N)
12259 "Like `delete-char', but insert whitespace at field end in tables.
12260 When deleting characters, in tables this function will insert whitespace in
12261 front of the next \"|\" separator, to keep the table aligned. The table will
12262 still be marked for re-alignment if the field did fill the entire column,
12263 because, in this case the deletion might narrow the column."
12264 (interactive "p")
12265 (if (and (org-table-p)
12266 (not (bolp))
12267 (not (= (char-after) ?|))
12268 (eq N 1))
12269 (if (looking-at ".*?|")
12270 (let ((pos (point))
12271 (noalign (looking-at "[^|\n\r]* |"))
12272 (c org-table-may-need-update))
12273 (replace-match (concat
12274 (substring (match-string 0) 1 -1)
12275 " |"))
12276 (goto-char pos)
12277 ;; noalign: if there were two spaces at the end, this field
12278 ;; does not determine the width of the column.
12279 (if noalign (setq org-table-may-need-update c)))
12280 (delete-char N))
12281 (delete-char N)
12282 (org-fix-tags-on-the-fly)))
12283
12284 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12285 (put 'org-self-insert-command 'delete-selection t)
12286 (put 'orgtbl-self-insert-command 'delete-selection t)
12287 (put 'org-delete-char 'delete-selection 'supersede)
12288 (put 'org-delete-backward-char 'delete-selection 'supersede)
12289
12290 ;; Make `flyspell-mode' delay after some commands
12291 (put 'org-self-insert-command 'flyspell-delayed t)
12292 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12293 (put 'org-delete-char 'flyspell-delayed t)
12294 (put 'org-delete-backward-char 'flyspell-delayed t)
12295
12296 ;; Make pabbrev-mode expand after org-mode commands
12297 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12298 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12299
12300 ;; How to do this: Measure non-white length of current string
12301 ;; If equal to column width, we should realign.
12302
12303 (defun org-remap (map &rest commands)
12304 "In MAP, remap the functions given in COMMANDS.
12305 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12306 (let (new old)
12307 (while commands
12308 (setq old (pop commands) new (pop commands))
12309 (if (fboundp 'command-remapping)
12310 (org-defkey map (vector 'remap old) new)
12311 (substitute-key-definition old new map global-map)))))
12312
12313 (when (eq org-enable-table-editor 'optimized)
12314 ;; If the user wants maximum table support, we need to hijack
12315 ;; some standard editing functions
12316 (org-remap org-mode-map
12317 'self-insert-command 'org-self-insert-command
12318 'delete-char 'org-delete-char
12319 'delete-backward-char 'org-delete-backward-char)
12320 (org-defkey org-mode-map "|" 'org-force-self-insert))
12321
12322 (defun org-shiftcursor-error ()
12323 "Throw an error because Shift-Cursor command was applied in wrong context."
12324 (error "This command is active in special context like tables, headlines or timestamps"))
12325
12326 (defun org-shifttab (&optional arg)
12327 "Global visibility cycling or move to previous table field.
12328 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12329 on context.
12330 See the individual commands for more information."
12331 (interactive "P")
12332 (cond
12333 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12334 ((integerp arg)
12335 (message "Content view to level: %d" arg)
12336 (org-content (prefix-numeric-value arg))
12337 (setq org-cycle-global-status 'overview))
12338 (t (call-interactively 'org-global-cycle))))
12339
12340 (defun org-shiftmetaleft ()
12341 "Promote subtree or delete table column.
12342 Calls `org-promote-subtree', `org-outdent-item',
12343 or `org-table-delete-column', depending on context.
12344 See the individual commands for more information."
12345 (interactive)
12346 (cond
12347 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12348 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12349 ((org-at-item-p) (call-interactively 'org-outdent-item))
12350 (t (org-shiftcursor-error))))
12351
12352 (defun org-shiftmetaright ()
12353 "Demote subtree or insert table column.
12354 Calls `org-demote-subtree', `org-indent-item',
12355 or `org-table-insert-column', depending on context.
12356 See the individual commands for more information."
12357 (interactive)
12358 (cond
12359 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12360 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12361 ((org-at-item-p) (call-interactively 'org-indent-item))
12362 (t (org-shiftcursor-error))))
12363
12364 (defun org-shiftmetaup (&optional arg)
12365 "Move subtree up or kill table row.
12366 Calls `org-move-subtree-up' or `org-table-kill-row' or
12367 `org-move-item-up' depending on context. See the individual commands
12368 for more information."
12369 (interactive "P")
12370 (cond
12371 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12372 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12373 ((org-at-item-p) (call-interactively 'org-move-item-up))
12374 (t (org-shiftcursor-error))))
12375 (defun org-shiftmetadown (&optional arg)
12376 "Move subtree down or insert table row.
12377 Calls `org-move-subtree-down' or `org-table-insert-row' or
12378 `org-move-item-down', depending on context. See the individual
12379 commands for more information."
12380 (interactive "P")
12381 (cond
12382 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12383 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12384 ((org-at-item-p) (call-interactively 'org-move-item-down))
12385 (t (org-shiftcursor-error))))
12386
12387 (defun org-metaleft (&optional arg)
12388 "Promote heading or move table column to left.
12389 Calls `org-do-promote' or `org-table-move-column', depending on context.
12390 With no specific context, calls the Emacs default `backward-word'.
12391 See the individual commands for more information."
12392 (interactive "P")
12393 (cond
12394 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12395 ((or (org-on-heading-p) (org-region-active-p))
12396 (call-interactively 'org-do-promote))
12397 ((org-at-item-p) (call-interactively 'org-outdent-item))
12398 (t (call-interactively 'backward-word))))
12399
12400 (defun org-metaright (&optional arg)
12401 "Demote subtree or move table column to right.
12402 Calls `org-do-demote' or `org-table-move-column', depending on context.
12403 With no specific context, calls the Emacs default `forward-word'.
12404 See the individual commands for more information."
12405 (interactive "P")
12406 (cond
12407 ((org-at-table-p) (call-interactively 'org-table-move-column))
12408 ((or (org-on-heading-p) (org-region-active-p))
12409 (call-interactively 'org-do-demote))
12410 ((org-at-item-p) (call-interactively 'org-indent-item))
12411 (t (call-interactively 'forward-word))))
12412
12413 (defun org-metaup (&optional arg)
12414 "Move subtree up or move table row up.
12415 Calls `org-move-subtree-up' or `org-table-move-row' or
12416 `org-move-item-up', depending on context. See the individual commands
12417 for more information."
12418 (interactive "P")
12419 (cond
12420 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12421 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12422 ((org-at-item-p) (call-interactively 'org-move-item-up))
12423 (t (transpose-lines 1) (beginning-of-line -1))))
12424
12425 (defun org-metadown (&optional arg)
12426 "Move subtree down or move table row down.
12427 Calls `org-move-subtree-down' or `org-table-move-row' or
12428 `org-move-item-down', depending on context. See the individual
12429 commands for more information."
12430 (interactive "P")
12431 (cond
12432 ((org-at-table-p) (call-interactively 'org-table-move-row))
12433 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12434 ((org-at-item-p) (call-interactively 'org-move-item-down))
12435 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12436
12437 (defun org-shiftup (&optional arg)
12438 "Increase item in timestamp or increase priority of current headline.
12439 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12440 depending on context. See the individual commands for more information."
12441 (interactive "P")
12442 (cond
12443 ((org-at-timestamp-p t)
12444 (call-interactively (if org-edit-timestamp-down-means-later
12445 'org-timestamp-down 'org-timestamp-up)))
12446 ((org-on-heading-p) (call-interactively 'org-priority-up))
12447 ((org-at-item-p) (call-interactively 'org-previous-item))
12448 ((org-clocktable-try-shift 'up arg))
12449 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12450
12451 (defun org-shiftdown (&optional arg)
12452 "Decrease item in timestamp or decrease priority of current headline.
12453 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12454 depending on context. See the individual commands for more information."
12455 (interactive "P")
12456 (cond
12457 ((org-at-timestamp-p t)
12458 (call-interactively (if org-edit-timestamp-down-means-later
12459 'org-timestamp-up 'org-timestamp-down)))
12460 ((org-on-heading-p) (call-interactively 'org-priority-down))
12461 ((org-clocktable-try-shift 'down arg))
12462 (t (call-interactively 'org-next-item))))
12463
12464 (defun org-shiftright (&optional arg)
12465 "Next TODO keyword or timestamp one day later, depending on context."
12466 (interactive "P")
12467 (cond
12468 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12469 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12470 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12471 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12472 ((org-clocktable-try-shift 'right arg))
12473 (t (org-shiftcursor-error))))
12474
12475 (defun org-shiftleft (&optional arg)
12476 "Previous TODO keyword or timestamp one day earlier, depending on context."
12477 (interactive "P")
12478 (cond
12479 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12480 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12481 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12482 ((org-at-property-p)
12483 (call-interactively 'org-property-previous-allowed-value))
12484 ((org-clocktable-try-shift 'left arg))
12485 (t (org-shiftcursor-error))))
12486
12487 (defun org-shiftcontrolright ()
12488 "Switch to next TODO set."
12489 (interactive)
12490 (cond
12491 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12492 (t (org-shiftcursor-error))))
12493
12494 (defun org-shiftcontrolleft ()
12495 "Switch to previous TODO set."
12496 (interactive)
12497 (cond
12498 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12499 (t (org-shiftcursor-error))))
12500
12501 (defun org-ctrl-c-ret ()
12502 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12503 (interactive)
12504 (cond
12505 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12506 (t (call-interactively 'org-insert-heading))))
12507
12508 (defun org-copy-special ()
12509 "Copy region in table or copy current subtree.
12510 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12511 See the individual commands for more information."
12512 (interactive)
12513 (call-interactively
12514 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12515
12516 (defun org-cut-special ()
12517 "Cut region in table or cut current subtree.
12518 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12519 See the individual commands for more information."
12520 (interactive)
12521 (call-interactively
12522 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12523
12524 (defun org-paste-special (arg)
12525 "Paste rectangular region into table, or past subtree relative to level.
12526 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12527 See the individual commands for more information."
12528 (interactive "P")
12529 (if (org-at-table-p)
12530 (org-table-paste-rectangle)
12531 (org-paste-subtree arg)))
12532
12533 (defun org-edit-special ()
12534 "Call a special editor for the stuff at point.
12535 When at a table, call the formula editor with `org-table-edit-formulas'.
12536 When at the first line of an src example, call `org-edit-src-code'.
12537 When in an #+include line, visit the include file. Otherwise call
12538 `ffap' to visit the file at point."
12539 (interactive)
12540 (cond
12541 ((org-at-table-p)
12542 (call-interactively 'org-table-edit-formulas))
12543 ((save-excursion
12544 (beginning-of-line 1)
12545 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12546 (find-file (org-trim (match-string 1))))
12547 ((org-edit-src-code))
12548 ((org-edit-fixed-width-region))
12549 (t (call-interactively 'ffap))))
12550
12551 (defun org-ctrl-c-ctrl-c (&optional arg)
12552 "Set tags in headline, or update according to changed information at point.
12553
12554 This command does many different things, depending on context:
12555
12556 - If the cursor is in a headline, prompt for tags and insert them
12557 into the current line, aligned to `org-tags-column'. When called
12558 with prefix arg, realign all tags in the current buffer.
12559
12560 - If the cursor is in one of the special #+KEYWORD lines, this
12561 triggers scanning the buffer for these lines and updating the
12562 information.
12563
12564 - If the cursor is inside a table, realign the table. This command
12565 works even if the automatic table editor has been turned off.
12566
12567 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12568 the entire table.
12569
12570 - If the cursor is a the beginning of a dynamic block, update it.
12571
12572 - If the cursor is inside a table created by the table.el package,
12573 activate that table.
12574
12575 - If the current buffer is a remember buffer, close note and file it.
12576 with a prefix argument, file it without further interaction to the default
12577 location.
12578
12579 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12580 links in this buffer.
12581
12582 - If the cursor is on a numbered item in a plain list, renumber the
12583 ordered list.
12584
12585 - If the cursor is on a checkbox, toggle it."
12586 (interactive "P")
12587 (let ((org-enable-table-editor t))
12588 (cond
12589 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12590 org-occur-highlights
12591 org-latex-fragment-image-overlays)
12592 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12593 (org-remove-occur-highlights)
12594 (org-remove-latex-fragment-image-overlays)
12595 (message "Temporary highlights/overlays removed from current buffer"))
12596 ((and (local-variable-p 'org-finish-function (current-buffer))
12597 (fboundp org-finish-function))
12598 (funcall org-finish-function))
12599 ((org-at-property-p)
12600 (call-interactively 'org-property-action))
12601 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12602 ((org-on-heading-p) (call-interactively 'org-set-tags))
12603 ((org-at-table.el-p)
12604 (require 'table)
12605 (beginning-of-line 1)
12606 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12607 (call-interactively 'table-recognize-table))
12608 ((org-at-table-p)
12609 (org-table-maybe-eval-formula)
12610 (if arg
12611 (call-interactively 'org-table-recalculate)
12612 (org-table-maybe-recalculate-line))
12613 (call-interactively 'org-table-align))
12614 ((org-at-item-checkbox-p)
12615 (call-interactively 'org-toggle-checkbox))
12616 ((org-at-item-p)
12617 (call-interactively 'org-maybe-renumber-ordered-list))
12618 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12619 ;; Dynamic block
12620 (beginning-of-line 1)
12621 (save-excursion (org-update-dblock)))
12622 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12623 (cond
12624 ((equal (match-string 1) "TBLFM")
12625 ;; Recalculate the table before this line
12626 (save-excursion
12627 (beginning-of-line 1)
12628 (skip-chars-backward " \r\n\t")
12629 (if (org-at-table-p)
12630 (org-call-with-arg 'org-table-recalculate t))))
12631 (t
12632 ; (org-set-regexps-and-options)
12633 ; (org-restart-font-lock)
12634 (let ((org-inhibit-startup t)) (org-mode-restart))
12635 (message "Local setup has been refreshed"))))
12636 (t (error "C-c C-c can do nothing useful at this location.")))))
12637
12638 (defun org-mode-restart ()
12639 "Restart Org-mode, to scan again for special lines.
12640 Also updates the keyword regular expressions."
12641 (interactive)
12642 (org-mode)
12643 (message "Org-mode restarted"))
12644
12645 (defun org-kill-note-or-show-branches ()
12646 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12647 (interactive)
12648 (if (not org-finish-function)
12649 (call-interactively 'show-branches)
12650 (let ((org-note-abort t))
12651 (funcall org-finish-function))))
12652
12653 (defun org-return (&optional indent)
12654 "Goto next table row or insert a newline.
12655 Calls `org-table-next-row' or `newline', depending on context.
12656 See the individual commands for more information."
12657 (interactive)
12658 (cond
12659 ((bobp) (if indent (newline-and-indent) (newline)))
12660 ((and (org-at-heading-p)
12661 (looking-at
12662 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12663 (org-show-entry)
12664 (end-of-line 1)
12665 (newline))
12666 ((org-at-table-p)
12667 (org-table-justify-field-maybe)
12668 (call-interactively 'org-table-next-row))
12669 (t (if indent (newline-and-indent) (newline)))))
12670
12671 (defun org-return-indent ()
12672 "Goto next table row or insert a newline and indent.
12673 Calls `org-table-next-row' or `newline-and-indent', depending on
12674 context. See the individual commands for more information."
12675 (interactive)
12676 (org-return t))
12677
12678 (defun org-ctrl-c-star ()
12679 "Compute table, or change heading status of lines.
12680 Calls `org-table-recalculate' or `org-toggle-region-headings',
12681 depending on context. This will also turn a plain list item or a normal
12682 line into a subheading."
12683 (interactive)
12684 (cond
12685 ((org-at-table-p)
12686 (call-interactively 'org-table-recalculate))
12687 ((org-region-active-p)
12688 ;; Convert all lines in region to list items
12689 (call-interactively 'org-toggle-region-headings))
12690 ((org-on-heading-p)
12691 (org-toggle-region-headings (point-at-bol)
12692 (min (1+ (point-at-eol)) (point-max))))
12693 ((org-at-item-p)
12694 ;; Convert to heading
12695 (let ((level (save-match-data
12696 (save-excursion
12697 (condition-case nil
12698 (progn
12699 (org-back-to-heading t)
12700 (funcall outline-level))
12701 (error 0))))))
12702 (replace-match
12703 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12704 (t (org-toggle-region-headings (point-at-bol)
12705 (min (1+ (point-at-eol)) (point-max))))))
12706
12707 (defun org-ctrl-c-minus ()
12708 "Insert separator line in table or modify bullet status of line.
12709 Also turns a plain line or a region of lines into list items.
12710 Calls `org-table-insert-hline', `org-toggle-region-items', or
12711 `org-cycle-list-bullet', depending on context."
12712 (interactive)
12713 (cond
12714 ((org-at-table-p)
12715 (call-interactively 'org-table-insert-hline))
12716 ((org-on-heading-p)
12717 ;; Convert to item
12718 (save-excursion
12719 (beginning-of-line 1)
12720 (if (looking-at "\\*+ ")
12721 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12722 ((org-region-active-p)
12723 ;; Convert all lines in region to list items
12724 (call-interactively 'org-toggle-region-items))
12725 ((org-in-item-p)
12726 (call-interactively 'org-cycle-list-bullet))
12727 (t (org-toggle-region-items (point-at-bol)
12728 (min (1+ (point-at-eol)) (point-max))))))
12729
12730 (defun org-toggle-region-items (beg end)
12731 "Convert all lines in region to list items.
12732 If the first line is already an item, convert all list items in the region
12733 to normal lines."
12734 (interactive "r")
12735 (let (l2 l)
12736 (save-excursion
12737 (goto-char end)
12738 (setq l2 (org-current-line))
12739 (goto-char beg)
12740 (beginning-of-line 1)
12741 (setq l (1- (org-current-line)))
12742 (if (org-at-item-p)
12743 ;; We already have items, de-itemize
12744 (while (< (setq l (1+ l)) l2)
12745 (when (org-at-item-p)
12746 (goto-char (match-beginning 2))
12747 (delete-region (match-beginning 2) (match-end 2))
12748 (and (looking-at "[ \t]+") (replace-match "")))
12749 (beginning-of-line 2))
12750 (while (< (setq l (1+ l)) l2)
12751 (unless (org-at-item-p)
12752 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12753 (replace-match "\\1- \\2")))
12754 (beginning-of-line 2))))))
12755
12756 (defun org-toggle-region-headings (beg end)
12757 "Convert all lines in region to list items.
12758 If the first line is already an item, convert all list items in the region
12759 to normal lines."
12760 (interactive "r")
12761 (let (l2 l)
12762 (save-excursion
12763 (goto-char end)
12764 (setq l2 (org-current-line))
12765 (goto-char beg)
12766 (beginning-of-line 1)
12767 (setq l (1- (org-current-line)))
12768 (if (org-on-heading-p)
12769 ;; We already have headlines, de-star them
12770 (while (< (setq l (1+ l)) l2)
12771 (when (org-on-heading-p t)
12772 (and (looking-at outline-regexp) (replace-match "")))
12773 (beginning-of-line 2))
12774 (let* ((stars (save-excursion
12775 (re-search-backward org-complex-heading-regexp nil t)
12776 (or (match-string 1) "*")))
12777 (add-stars (if org-odd-levels-only "**" "*"))
12778 (rpl (concat stars add-stars " \\2")))
12779 (while (< (setq l (1+ l)) l2)
12780 (unless (org-on-heading-p)
12781 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12782 (replace-match rpl)))
12783 (beginning-of-line 2)))))))
12784
12785 (defun org-meta-return (&optional arg)
12786 "Insert a new heading or wrap a region in a table.
12787 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12788 See the individual commands for more information."
12789 (interactive "P")
12790 (cond
12791 ((org-at-table-p)
12792 (call-interactively 'org-table-wrap-region))
12793 (t (call-interactively 'org-insert-heading))))
12794
12795 ;;; Menu entries
12796
12797 ;; Define the Org-mode menus
12798 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12799 '("Tbl"
12800 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12801 ["Next Field" org-cycle (org-at-table-p)]
12802 ["Previous Field" org-shifttab (org-at-table-p)]
12803 ["Next Row" org-return (org-at-table-p)]
12804 "--"
12805 ["Blank Field" org-table-blank-field (org-at-table-p)]
12806 ["Edit Field" org-table-edit-field (org-at-table-p)]
12807 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12808 "--"
12809 ("Column"
12810 ["Move Column Left" org-metaleft (org-at-table-p)]
12811 ["Move Column Right" org-metaright (org-at-table-p)]
12812 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12813 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12814 ("Row"
12815 ["Move Row Up" org-metaup (org-at-table-p)]
12816 ["Move Row Down" org-metadown (org-at-table-p)]
12817 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12818 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12819 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12820 "--"
12821 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12822 ("Rectangle"
12823 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12824 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12825 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12826 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12827 "--"
12828 ("Calculate"
12829 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12830 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12831 ["Edit Formulas" org-edit-special (org-at-table-p)]
12832 "--"
12833 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12834 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12835 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12836 "--"
12837 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12838 "--"
12839 ["Sum Column/Rectangle" org-table-sum
12840 (or (org-at-table-p) (org-region-active-p))]
12841 ["Which Column?" org-table-current-column (org-at-table-p)])
12842 ["Debug Formulas"
12843 org-table-toggle-formula-debugger
12844 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12845 ["Show Col/Row Numbers"
12846 org-table-toggle-coordinate-overlays
12847 :style toggle
12848 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12849 "--"
12850 ["Create" org-table-create (and (not (org-at-table-p))
12851 org-enable-table-editor)]
12852 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12853 ["Import from File" org-table-import (not (org-at-table-p))]
12854 ["Export to File" org-table-export (org-at-table-p)]
12855 "--"
12856 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12857
12858 (easy-menu-define org-org-menu org-mode-map "Org menu"
12859 '("Org"
12860 ("Show/Hide"
12861 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12862 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12863 ["Sparse Tree..." org-sparse-tree t]
12864 ["Reveal Context" org-reveal t]
12865 ["Show All" show-all t]
12866 "--"
12867 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12868 "--"
12869 ["New Heading" org-insert-heading t]
12870 ("Navigate Headings"
12871 ["Up" outline-up-heading t]
12872 ["Next" outline-next-visible-heading t]
12873 ["Previous" outline-previous-visible-heading t]
12874 ["Next Same Level" outline-forward-same-level t]
12875 ["Previous Same Level" outline-backward-same-level t]
12876 "--"
12877 ["Jump" org-goto t])
12878 ("Edit Structure"
12879 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12880 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12881 "--"
12882 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12883 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12884 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12885 "--"
12886 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12887 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12888 ["Demote Heading" org-metaright (not (org-at-table-p))]
12889 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12890 "--"
12891 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12892 "--"
12893 ["Convert to odd levels" org-convert-to-odd-levels t]
12894 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12895 ("Editing"
12896 ["Emphasis..." org-emphasize t]
12897 ["Edit Source Example" org-edit-special t])
12898 ("Archive"
12899 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12900 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12901 ; :active t :keys "C-u C-c C-x C-a"]
12902 ["Sparse trees open ARCHIVE trees"
12903 (setq org-sparse-tree-open-archived-trees
12904 (not org-sparse-tree-open-archived-trees))
12905 :style toggle :selected org-sparse-tree-open-archived-trees]
12906 ["Cycling opens ARCHIVE trees"
12907 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12908 :style toggle :selected org-cycle-open-archived-trees]
12909 "--"
12910 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
12911 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12912 ; ["Check and Move Children" (org-archive-subtree '(4))
12913 ; :active t :keys "C-u C-c C-x C-s"]
12914 )
12915 "--"
12916 ("TODO Lists"
12917 ["TODO/DONE/-" org-todo t]
12918 ("Select keyword"
12919 ["Next keyword" org-shiftright (org-on-heading-p)]
12920 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12921 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12922 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12923 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12924 ["Show TODO Tree" org-show-todo-tree t]
12925 ["Global TODO list" org-todo-list t]
12926 "--"
12927 ["Set Priority" org-priority t]
12928 ["Priority Up" org-shiftup t]
12929 ["Priority Down" org-shiftdown t])
12930 ("TAGS and Properties"
12931 ["Set Tags" 'org-set-tags-command t]
12932 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12933 "--"
12934 ["Set property" 'org-set-property t]
12935 ["Column view of properties" org-columns t]
12936 ["Insert Column View DBlock" org-insert-columns-dblock t])
12937 ("Dates and Scheduling"
12938 ["Timestamp" org-time-stamp t]
12939 ["Timestamp (inactive)" org-time-stamp-inactive t]
12940 ("Change Date"
12941 ["1 Day Later" org-shiftright t]
12942 ["1 Day Earlier" org-shiftleft t]
12943 ["1 ... Later" org-shiftup t]
12944 ["1 ... Earlier" org-shiftdown t])
12945 ["Compute Time Range" org-evaluate-time-range t]
12946 ["Schedule Item" org-schedule t]
12947 ["Deadline" org-deadline t]
12948 "--"
12949 ["Custom time format" org-toggle-time-stamp-overlays
12950 :style radio :selected org-display-custom-times]
12951 "--"
12952 ["Goto Calendar" org-goto-calendar t]
12953 ["Date from Calendar" org-date-from-calendar t])
12954 ("Logging work"
12955 ["Clock in" org-clock-in t]
12956 ["Clock out" org-clock-out t]
12957 ["Clock cancel" org-clock-cancel t]
12958 ["Goto running clock" org-clock-goto t]
12959 ["Display times" org-clock-display t]
12960 ["Create clock table" org-clock-report t]
12961 "--"
12962 ["Record DONE time"
12963 (progn (setq org-log-done (not org-log-done))
12964 (message "Switching to %s will %s record a timestamp"
12965 (car org-done-keywords)
12966 (if org-log-done "automatically" "not")))
12967 :style toggle :selected org-log-done])
12968 "--"
12969 ["Agenda Command..." org-agenda t]
12970 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12971 ("File List for Agenda")
12972 ("Special views current file"
12973 ["TODO Tree" org-show-todo-tree t]
12974 ["Check Deadlines" org-check-deadlines t]
12975 ["Timeline" org-timeline t]
12976 ["Tags Tree" org-tags-sparse-tree t])
12977 "--"
12978 ("Hyperlinks"
12979 ["Store Link (Global)" org-store-link t]
12980 ["Insert Link" org-insert-link t]
12981 ["Follow Link" org-open-at-point t]
12982 "--"
12983 ["Next link" org-next-link t]
12984 ["Previous link" org-previous-link t]
12985 "--"
12986 ["Descriptive Links"
12987 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12988 :style radio
12989 :selected (member '(org-link) buffer-invisibility-spec)]
12990 ["Literal Links"
12991 (progn
12992 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12993 :style radio
12994 :selected (not (member '(org-link) buffer-invisibility-spec))])
12995 "--"
12996 ["Export/Publish..." org-export t]
12997 ("LaTeX"
12998 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12999 :selected org-cdlatex-mode]
13000 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13001 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13002 ["Modify math symbol" org-cdlatex-math-modify
13003 (org-inside-LaTeX-fragment-p)]
13004 ["Export LaTeX fragments as images"
13005 (if (featurep 'org-exp)
13006 (setq org-export-with-LaTeX-fragments
13007 (not org-export-with-LaTeX-fragments))
13008 (require 'org-exp))
13009 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13010 org-export-with-LaTeX-fragments)])
13011 "--"
13012 ("Documentation"
13013 ["Show Version" org-version t]
13014 ["Info Documentation" org-info t])
13015 ("Customize"
13016 ["Browse Org Group" org-customize t]
13017 "--"
13018 ["Expand This Menu" org-create-customize-menu
13019 (fboundp 'customize-menu-create)])
13020 "--"
13021 ["Refresh setup" org-mode-restart t]
13022 ))
13023
13024 (defun org-info (&optional node)
13025 "Read documentation for Org-mode in the info system.
13026 With optional NODE, go directly to that node."
13027 (interactive)
13028 (info (format "(org)%s" (or node ""))))
13029
13030 (defun org-install-agenda-files-menu ()
13031 (let ((bl (buffer-list)))
13032 (save-excursion
13033 (while bl
13034 (set-buffer (pop bl))
13035 (if (org-mode-p) (setq bl nil)))
13036 (when (org-mode-p)
13037 (easy-menu-change
13038 '("Org") "File List for Agenda"
13039 (append
13040 (list
13041 ["Edit File List" (org-edit-agenda-file-list) t]
13042 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13043 ["Remove Current File from List" org-remove-file t]
13044 ["Cycle through agenda files" org-cycle-agenda-files t]
13045 ["Occur in all agenda files" org-occur-in-agenda-files t]
13046 "--")
13047 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13048
13049 ;;;; Documentation
13050
13051 ;;;###autoload
13052 (defun org-require-autoloaded-modules ()
13053 (interactive)
13054 (mapc 'require
13055 '(org-agenda org-archive org-clock org-colview
13056 org-exp org-id org-export-latex org-publish
13057 org-remember org-table)))
13058
13059 ;;;###autoload
13060 (defun org-customize ()
13061 "Call the customize function with org as argument."
13062 (interactive)
13063 (org-load-modules-maybe)
13064 (org-require-autoloaded-modules)
13065 (customize-browse 'org))
13066
13067 (defun org-create-customize-menu ()
13068 "Create a full customization menu for Org-mode, insert it into the menu."
13069 (interactive)
13070 (org-load-modules-maybe)
13071 (org-require-autoloaded-modules)
13072 (if (fboundp 'customize-menu-create)
13073 (progn
13074 (easy-menu-change
13075 '("Org") "Customize"
13076 `(["Browse Org group" org-customize t]
13077 "--"
13078 ,(customize-menu-create 'org)
13079 ["Set" Custom-set t]
13080 ["Save" Custom-save t]
13081 ["Reset to Current" Custom-reset-current t]
13082 ["Reset to Saved" Custom-reset-saved t]
13083 ["Reset to Standard Settings" Custom-reset-standard t]))
13084 (message "\"Org\"-menu now contains full customization menu"))
13085 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13086
13087 ;;;; Miscellaneous stuff
13088
13089 ;;; Generally useful functions
13090
13091 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13092 "Display the given MESSAGE as a warning."
13093 (if (fboundp 'display-warning)
13094 (display-warning 'org message
13095 (if (featurep 'xemacs)
13096 'warning
13097 :warning))
13098 (let ((buf (get-buffer-create "*Org warnings*")))
13099 (with-current-buffer buf
13100 (goto-char (point-max))
13101 (insert "Warning (Org): " message)
13102 (unless (bolp)
13103 (newline)))
13104 (display-buffer buf)
13105 (sit-for 0))))
13106
13107 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13108 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13109 (if (and marker (marker-buffer marker)
13110 (buffer-live-p (marker-buffer marker)))
13111 (progn
13112 (switch-to-buffer (marker-buffer marker))
13113 (if (or (> marker (point-max)) (< marker (point-min)))
13114 (widen))
13115 (goto-char marker))
13116 (if bookmark
13117 (bookmark-jump bookmark)
13118 (error "Cannot find location"))))
13119
13120 (defun org-quote-csv-field (s)
13121 "Quote field for inclusion in CSV material."
13122 (if (string-match "[\",]" s)
13123 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13124 s))
13125
13126 (defun org-plist-delete (plist property)
13127 "Delete PROPERTY from PLIST.
13128 This is in contrast to merely setting it to 0."
13129 (let (p)
13130 (while plist
13131 (if (not (eq property (car plist)))
13132 (setq p (plist-put p (car plist) (nth 1 plist))))
13133 (setq plist (cddr plist)))
13134 p))
13135
13136 (defun org-force-self-insert (N)
13137 "Needed to enforce self-insert under remapping."
13138 (interactive "p")
13139 (self-insert-command N))
13140
13141 (defun org-string-width (s)
13142 "Compute width of string, ignoring invisible characters.
13143 This ignores character with invisibility property `org-link', and also
13144 characters with property `org-cwidth', because these will become invisible
13145 upon the next fontification round."
13146 (let (b l)
13147 (when (or (eq t buffer-invisibility-spec)
13148 (assq 'org-link buffer-invisibility-spec))
13149 (while (setq b (text-property-any 0 (length s)
13150 'invisible 'org-link s))
13151 (setq s (concat (substring s 0 b)
13152 (substring s (or (next-single-property-change
13153 b 'invisible s) (length s)))))))
13154 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13155 (setq s (concat (substring s 0 b)
13156 (substring s (or (next-single-property-change
13157 b 'org-cwidth s) (length s))))))
13158 (setq l (string-width s) b -1)
13159 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13160 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13161 l))
13162
13163 (defun org-get-indentation (&optional line)
13164 "Get the indentation of the current line, interpreting tabs.
13165 When LINE is given, assume it represents a line and compute its indentation."
13166 (if line
13167 (if (string-match "^ *" (org-remove-tabs line))
13168 (match-end 0))
13169 (save-excursion
13170 (beginning-of-line 1)
13171 (skip-chars-forward " \t")
13172 (current-column))))
13173
13174 (defun org-remove-tabs (s &optional width)
13175 "Replace tabulators in S with spaces.
13176 Assumes that s is a single line, starting in column 0."
13177 (setq width (or width tab-width))
13178 (while (string-match "\t" s)
13179 (setq s (replace-match
13180 (make-string
13181 (- (* width (/ (+ (match-beginning 0) width) width))
13182 (match-beginning 0)) ?\ )
13183 t t s)))
13184 s)
13185
13186 (defun org-fix-indentation (line ind)
13187 "Fix indentation in LINE.
13188 IND is a cons cell with target and minimum indentation.
13189 If the current indenation in LINE is smaller than the minimum,
13190 leave it alone. If it is larger than ind, set it to the target."
13191 (let* ((l (org-remove-tabs line))
13192 (i (org-get-indentation l))
13193 (i1 (car ind)) (i2 (cdr ind)))
13194 (if (>= i i2) (setq l (substring line i2)))
13195 (if (> i1 0)
13196 (concat (make-string i1 ?\ ) l)
13197 l)))
13198
13199 (defun org-base-buffer (buffer)
13200 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13201 (if (not buffer)
13202 buffer
13203 (or (buffer-base-buffer buffer)
13204 buffer)))
13205
13206 (defun org-trim (s)
13207 "Remove whitespace at beginning and end of string."
13208 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13209 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13210 s)
13211
13212 (defun org-wrap (string &optional width lines)
13213 "Wrap string to either a number of lines, or a width in characters.
13214 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13215 that costs. If there is a word longer than WIDTH, the text is actually
13216 wrapped to the length of that word.
13217 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13218 many lines, whatever width that takes.
13219 The return value is a list of lines, without newlines at the end."
13220 (let* ((words (org-split-string string "[ \t\n]+"))
13221 (maxword (apply 'max (mapcar 'org-string-width words)))
13222 w ll)
13223 (cond (width
13224 (org-do-wrap words (max maxword width)))
13225 (lines
13226 (setq w maxword)
13227 (setq ll (org-do-wrap words maxword))
13228 (if (<= (length ll) lines)
13229 ll
13230 (setq ll words)
13231 (while (> (length ll) lines)
13232 (setq w (1+ w))
13233 (setq ll (org-do-wrap words w)))
13234 ll))
13235 (t (error "Cannot wrap this")))))
13236
13237 (defun org-do-wrap (words width)
13238 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13239 (let (lines line)
13240 (while words
13241 (setq line (pop words))
13242 (while (and words (< (+ (length line) (length (car words))) width))
13243 (setq line (concat line " " (pop words))))
13244 (setq lines (push line lines)))
13245 (nreverse lines)))
13246
13247 (defun org-split-string (string &optional separators)
13248 "Splits STRING into substrings at SEPARATORS.
13249 No empty strings are returned if there are matches at the beginning
13250 and end of string."
13251 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13252 (start 0)
13253 notfirst
13254 (list nil))
13255 (while (and (string-match rexp string
13256 (if (and notfirst
13257 (= start (match-beginning 0))
13258 (< start (length string)))
13259 (1+ start) start))
13260 (< (match-beginning 0) (length string)))
13261 (setq notfirst t)
13262 (or (eq (match-beginning 0) 0)
13263 (and (eq (match-beginning 0) (match-end 0))
13264 (eq (match-beginning 0) start))
13265 (setq list
13266 (cons (substring string start (match-beginning 0))
13267 list)))
13268 (setq start (match-end 0)))
13269 (or (eq start (length string))
13270 (setq list
13271 (cons (substring string start)
13272 list)))
13273 (nreverse list)))
13274
13275 (defun org-context ()
13276 "Return a list of contexts of the current cursor position.
13277 If several contexts apply, all are returned.
13278 Each context entry is a list with a symbol naming the context, and
13279 two positions indicating start and end of the context. Possible
13280 contexts are:
13281
13282 :headline anywhere in a headline
13283 :headline-stars on the leading stars in a headline
13284 :todo-keyword on a TODO keyword (including DONE) in a headline
13285 :tags on the TAGS in a headline
13286 :priority on the priority cookie in a headline
13287 :item on the first line of a plain list item
13288 :item-bullet on the bullet/number of a plain list item
13289 :checkbox on the checkbox in a plain list item
13290 :table in an org-mode table
13291 :table-special on a special filed in a table
13292 :table-table in a table.el table
13293 :link on a hyperlink
13294 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13295 :target on a <<target>>
13296 :radio-target on a <<<radio-target>>>
13297 :latex-fragment on a LaTeX fragment
13298 :latex-preview on a LaTeX fragment with overlayed preview image
13299
13300 This function expects the position to be visible because it uses font-lock
13301 faces as a help to recognize the following contexts: :table-special, :link,
13302 and :keyword."
13303 (let* ((f (get-text-property (point) 'face))
13304 (faces (if (listp f) f (list f)))
13305 (p (point)) clist o)
13306 ;; First the large context
13307 (cond
13308 ((org-on-heading-p t)
13309 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13310 (when (progn
13311 (beginning-of-line 1)
13312 (looking-at org-todo-line-tags-regexp))
13313 (push (org-point-in-group p 1 :headline-stars) clist)
13314 (push (org-point-in-group p 2 :todo-keyword) clist)
13315 (push (org-point-in-group p 4 :tags) clist))
13316 (goto-char p)
13317 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13318 (if (looking-at "\\[#[A-Z0-9]\\]")
13319 (push (org-point-in-group p 0 :priority) clist)))
13320
13321 ((org-at-item-p)
13322 (push (org-point-in-group p 2 :item-bullet) clist)
13323 (push (list :item (point-at-bol)
13324 (save-excursion (org-end-of-item) (point)))
13325 clist)
13326 (and (org-at-item-checkbox-p)
13327 (push (org-point-in-group p 0 :checkbox) clist)))
13328
13329 ((org-at-table-p)
13330 (push (list :table (org-table-begin) (org-table-end)) clist)
13331 (if (memq 'org-formula faces)
13332 (push (list :table-special
13333 (previous-single-property-change p 'face)
13334 (next-single-property-change p 'face)) clist)))
13335 ((org-at-table-p 'any)
13336 (push (list :table-table) clist)))
13337 (goto-char p)
13338
13339 ;; Now the small context
13340 (cond
13341 ((org-at-timestamp-p)
13342 (push (org-point-in-group p 0 :timestamp) clist))
13343 ((memq 'org-link faces)
13344 (push (list :link
13345 (previous-single-property-change p 'face)
13346 (next-single-property-change p 'face)) clist))
13347 ((memq 'org-special-keyword faces)
13348 (push (list :keyword
13349 (previous-single-property-change p 'face)
13350 (next-single-property-change p 'face)) clist))
13351 ((org-on-target-p)
13352 (push (org-point-in-group p 0 :target) clist)
13353 (goto-char (1- (match-beginning 0)))
13354 (if (looking-at org-radio-target-regexp)
13355 (push (org-point-in-group p 0 :radio-target) clist))
13356 (goto-char p))
13357 ((setq o (car (delq nil
13358 (mapcar
13359 (lambda (x)
13360 (if (memq x org-latex-fragment-image-overlays) x))
13361 (org-overlays-at (point))))))
13362 (push (list :latex-fragment
13363 (org-overlay-start o) (org-overlay-end o)) clist)
13364 (push (list :latex-preview
13365 (org-overlay-start o) (org-overlay-end o)) clist))
13366 ((org-inside-LaTeX-fragment-p)
13367 ;; FIXME: positions wrong.
13368 (push (list :latex-fragment (point) (point)) clist)))
13369
13370 (setq clist (nreverse (delq nil clist)))
13371 clist))
13372
13373 ;; FIXME: Compare with at-regexp-p Do we need both?
13374 (defun org-in-regexp (re &optional nlines visually)
13375 "Check if point is inside a match of regexp.
13376 Normally only the current line is checked, but you can include NLINES extra
13377 lines both before and after point into the search.
13378 If VISUALLY is set, require that the cursor is not after the match but
13379 really on, so that the block visually is on the match."
13380 (catch 'exit
13381 (let ((pos (point))
13382 (eol (point-at-eol (+ 1 (or nlines 0))))
13383 (inc (if visually 1 0)))
13384 (save-excursion
13385 (beginning-of-line (- 1 (or nlines 0)))
13386 (while (re-search-forward re eol t)
13387 (if (and (<= (match-beginning 0) pos)
13388 (>= (+ inc (match-end 0)) pos))
13389 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13390
13391 (defun org-at-regexp-p (regexp)
13392 "Is point inside a match of REGEXP in the current line?"
13393 (catch 'exit
13394 (save-excursion
13395 (let ((pos (point)) (end (point-at-eol)))
13396 (beginning-of-line 1)
13397 (while (re-search-forward regexp end t)
13398 (if (and (<= (match-beginning 0) pos)
13399 (>= (match-end 0) pos))
13400 (throw 'exit t)))
13401 nil))))
13402
13403 (defun org-occur-in-agenda-files (regexp &optional nlines)
13404 "Call `multi-occur' with buffers for all agenda files."
13405 (interactive "sOrg-files matching: \np")
13406 (let* ((files (org-agenda-files))
13407 (tnames (mapcar 'file-truename files))
13408 (extra org-agenda-text-search-extra-files)
13409 f)
13410 (when (eq (car extra) 'agenda-archives)
13411 (setq extra (cdr extra))
13412 (setq files (org-add-archive-files files)))
13413 (while (setq f (pop extra))
13414 (unless (member (file-truename f) tnames)
13415 (add-to-list 'files f 'append)
13416 (add-to-list 'tnames (file-truename f) 'append)))
13417 (multi-occur
13418 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13419 regexp)))
13420
13421 (if (boundp 'occur-mode-find-occurrence-hook)
13422 ;; Emacs 23
13423 (add-hook 'occur-mode-find-occurrence-hook
13424 (lambda ()
13425 (when (org-mode-p)
13426 (org-reveal))))
13427 ;; Emacs 22
13428 (defadvice occur-mode-goto-occurrence
13429 (after org-occur-reveal activate)
13430 (and (org-mode-p) (org-reveal)))
13431 (defadvice occur-mode-goto-occurrence-other-window
13432 (after org-occur-reveal activate)
13433 (and (org-mode-p) (org-reveal)))
13434 (defadvice occur-mode-display-occurrence
13435 (after org-occur-reveal activate)
13436 (when (org-mode-p)
13437 (let ((pos (occur-mode-find-occurrence)))
13438 (with-current-buffer (marker-buffer pos)
13439 (save-excursion
13440 (goto-char pos)
13441 (org-reveal)))))))
13442
13443 (defun org-uniquify (list)
13444 "Remove duplicate elements from LIST."
13445 (let (res)
13446 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13447 res))
13448
13449 (defun org-delete-all (elts list)
13450 "Remove all elements in ELTS from LIST."
13451 (while elts
13452 (setq list (delete (pop elts) list)))
13453 list)
13454
13455 (defun org-back-over-empty-lines ()
13456 "Move backwards over witespace, to the beginning of the first empty line.
13457 Returns the number of empty lines passed."
13458 (let ((pos (point)))
13459 (skip-chars-backward " \t\n\r")
13460 (beginning-of-line 2)
13461 (goto-char (min (point) pos))
13462 (count-lines (point) pos)))
13463
13464 (defun org-skip-whitespace ()
13465 (skip-chars-forward " \t\n\r"))
13466
13467 (defun org-point-in-group (point group &optional context)
13468 "Check if POINT is in match-group GROUP.
13469 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13470 match. If the match group does ot exist or point is not inside it,
13471 return nil."
13472 (and (match-beginning group)
13473 (>= point (match-beginning group))
13474 (<= point (match-end group))
13475 (if context
13476 (list context (match-beginning group) (match-end group))
13477 t)))
13478
13479 (defun org-switch-to-buffer-other-window (&rest args)
13480 "Switch to buffer in a second window on the current frame.
13481 In particular, do not allow pop-up frames."
13482 (let (pop-up-frames special-display-buffer-names special-display-regexps
13483 special-display-function)
13484 (apply 'switch-to-buffer-other-window args)))
13485
13486 (defun org-combine-plists (&rest plists)
13487 "Create a single property list from all plists in PLISTS.
13488 The process starts by copying the first list, and then setting properties
13489 from the other lists. Settings in the last list are the most significant
13490 ones and overrule settings in the other lists."
13491 (let ((rtn (copy-sequence (pop plists)))
13492 p v ls)
13493 (while plists
13494 (setq ls (pop plists))
13495 (while ls
13496 (setq p (pop ls) v (pop ls))
13497 (setq rtn (plist-put rtn p v))))
13498 rtn))
13499
13500 (defun org-move-line-down (arg)
13501 "Move the current line down. With prefix argument, move it past ARG lines."
13502 (interactive "p")
13503 (let ((col (current-column))
13504 beg end pos)
13505 (beginning-of-line 1) (setq beg (point))
13506 (beginning-of-line 2) (setq end (point))
13507 (beginning-of-line (+ 1 arg))
13508 (setq pos (move-marker (make-marker) (point)))
13509 (insert (delete-and-extract-region beg end))
13510 (goto-char pos)
13511 (org-move-to-column col)))
13512
13513 (defun org-move-line-up (arg)
13514 "Move the current line up. With prefix argument, move it past ARG lines."
13515 (interactive "p")
13516 (let ((col (current-column))
13517 beg end pos)
13518 (beginning-of-line 1) (setq beg (point))
13519 (beginning-of-line 2) (setq end (point))
13520 (beginning-of-line (- arg))
13521 (setq pos (move-marker (make-marker) (point)))
13522 (insert (delete-and-extract-region beg end))
13523 (goto-char pos)
13524 (org-move-to-column col)))
13525
13526 (defun org-replace-escapes (string table)
13527 "Replace %-escapes in STRING with values in TABLE.
13528 TABLE is an association list with keys like \"%a\" and string values.
13529 The sequences in STRING may contain normal field width and padding information,
13530 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13531 so values can contain further %-escapes if they are define later in TABLE."
13532 (let ((case-fold-search nil)
13533 e re rpl)
13534 (while (setq e (pop table))
13535 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13536 (while (string-match re string)
13537 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13538 (cdr e)))
13539 (setq string (replace-match rpl t t string))))
13540 string))
13541
13542
13543 (defun org-sublist (list start end)
13544 "Return a section of LIST, from START to END.
13545 Counting starts at 1."
13546 (let (rtn (c start))
13547 (setq list (nthcdr (1- start) list))
13548 (while (and list (<= c end))
13549 (push (pop list) rtn)
13550 (setq c (1+ c)))
13551 (nreverse rtn)))
13552
13553 (defun org-find-base-buffer-visiting (file)
13554 "Like `find-buffer-visiting' but alway return the base buffer and
13555 not an indirect buffer."
13556 (let ((buf (find-buffer-visiting file)))
13557 (if buf
13558 (or (buffer-base-buffer buf) buf)
13559 nil)))
13560
13561 (defun org-image-file-name-regexp ()
13562 "Return regexp matching the file names of images."
13563 (if (fboundp 'image-file-name-regexp)
13564 (image-file-name-regexp)
13565 (let ((image-file-name-extensions
13566 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13567 "xbm" "xpm" "pbm" "pgm" "ppm")))
13568 (concat "\\."
13569 (regexp-opt (nconc (mapcar 'upcase
13570 image-file-name-extensions)
13571 image-file-name-extensions)
13572 t)
13573 "\\'"))))
13574
13575 (defun org-file-image-p (file)
13576 "Return non-nil if FILE is an image."
13577 (save-match-data
13578 (string-match (org-image-file-name-regexp) file)))
13579
13580 (defun org-get-cursor-date ()
13581 "Return the date at cursor in as a time.
13582 This works in the calendar and in the agenda, anywhere else it just
13583 returns the current time."
13584 (let (date day defd)
13585 (cond
13586 ((eq major-mode 'calendar-mode)
13587 (setq date (calendar-cursor-to-date)
13588 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13589 ((eq major-mode 'org-agenda-mode)
13590 (setq day (get-text-property (point) 'day))
13591 (if day
13592 (setq date (calendar-gregorian-from-absolute day)
13593 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13594 (nth 2 date))))))
13595 (or defd (current-time))))
13596
13597 (defvar org-agenda-action-marker (make-marker)
13598 "Marker pointing to the entry for the next agenda action.")
13599
13600 (defun org-mark-entry-for-agenda-action ()
13601 "Mark the current entry as target of an agenda action.
13602 Agenda actions are actions executed from the agenda with the key `k',
13603 which make use of the date at the cursor."
13604 (interactive)
13605 (move-marker org-agenda-action-marker
13606 (save-excursion (org-back-to-heading t) (point))
13607 (current-buffer))
13608 (message
13609 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13610
13611 ;;; Paragraph filling stuff.
13612 ;; We want this to be just right, so use the full arsenal.
13613
13614 (defun org-indent-line-function ()
13615 "Indent line like previous, but further if previous was headline or item."
13616 (interactive)
13617 (let* ((pos (point))
13618 (itemp (org-at-item-p))
13619 column bpos bcol tpos tcol bullet btype bullet-type)
13620 ;; Find the previous relevant line
13621 (beginning-of-line 1)
13622 (cond
13623 ((looking-at "#") (setq column 0))
13624 ((looking-at "\\*+ ") (setq column 0))
13625 (t
13626 (beginning-of-line 0)
13627 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13628 (beginning-of-line 0))
13629 (cond
13630 ((looking-at "\\*+[ \t]+")
13631 (if (not org-adapt-indentation)
13632 (setq column 0)
13633 (goto-char (match-end 0))
13634 (setq column (current-column))))
13635 ((org-in-item-p)
13636 (org-beginning-of-item)
13637 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13638 (setq bpos (match-beginning 1) tpos (match-end 0)
13639 bcol (progn (goto-char bpos) (current-column))
13640 tcol (progn (goto-char tpos) (current-column))
13641 bullet (match-string 1)
13642 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13643 (if (> tcol (+ bcol org-description-max-indent))
13644 (setq tcol (+ bcol 5)))
13645 (if (not itemp)
13646 (setq column tcol)
13647 (goto-char pos)
13648 (beginning-of-line 1)
13649 (if (looking-at "\\S-")
13650 (progn
13651 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13652 (setq bullet (match-string 1)
13653 btype (if (string-match "[0-9]" bullet) "n" bullet))
13654 (setq column (if (equal btype bullet-type) bcol tcol)))
13655 (setq column (org-get-indentation)))))
13656 (t (setq column (org-get-indentation))))))
13657 (goto-char pos)
13658 (if (<= (current-column) (current-indentation))
13659 (org-indent-line-to column)
13660 (save-excursion (org-indent-line-to column)))
13661 (setq column (current-column))
13662 (beginning-of-line 1)
13663 (if (looking-at
13664 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13665 (replace-match (concat "\\1" (format org-property-format
13666 (match-string 2) (match-string 3)))
13667 t nil))
13668 (org-move-to-column column)))
13669
13670 (defun org-set-autofill-regexps ()
13671 (interactive)
13672 ;; In the paragraph separator we include headlines, because filling
13673 ;; text in a line directly attached to a headline would otherwise
13674 ;; fill the headline as well.
13675 (org-set-local 'comment-start-skip "^#+[ \t]*")
13676 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13677 ;; The paragraph starter includes hand-formatted lists.
13678 (org-set-local 'paragraph-start
13679 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13680 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13681 ;; But only if the user has not turned off tables or fixed-width regions
13682 (org-set-local
13683 'auto-fill-inhibit-regexp
13684 (concat "\\*+ \\|#\\+"
13685 "\\|[ \t]*" org-keyword-time-regexp
13686 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13687 (concat
13688 "\\|[ \t]*["
13689 (if org-enable-table-editor "|" "")
13690 (if org-enable-fixed-width-editor ":" "")
13691 "]"))))
13692 ;; We use our own fill-paragraph function, to make sure that tables
13693 ;; and fixed-width regions are not wrapped. That function will pass
13694 ;; through to `fill-paragraph' when appropriate.
13695 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13696 ; Adaptive filling: To get full control, first make sure that
13697 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13698 (org-set-local 'adaptive-fill-regexp "\000")
13699 (org-set-local 'adaptive-fill-function
13700 'org-adaptive-fill-function)
13701 (org-set-local
13702 'align-mode-rules-list
13703 '((org-in-buffer-settings
13704 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13705 (modes . '(org-mode))))))
13706
13707 (defun org-fill-paragraph (&optional justify)
13708 "Re-align a table, pass through to fill-paragraph if no table."
13709 (let ((table-p (org-at-table-p))
13710 (table.el-p (org-at-table.el-p)))
13711 (cond ((and (equal (char-after (point-at-bol)) ?*)
13712 (save-excursion (goto-char (point-at-bol))
13713 (looking-at outline-regexp)))
13714 t) ; skip headlines
13715 (table.el-p t) ; skip table.el tables
13716 (table-p (org-table-align) t) ; align org-mode tables
13717 (t nil)))) ; call paragraph-fill
13718
13719 ;; For reference, this is the default value of adaptive-fill-regexp
13720 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13721
13722 (defun org-adaptive-fill-function ()
13723 "Return a fill prefix for org-mode files.
13724 In particular, this makes sure hanging paragraphs for hand-formatted lists
13725 work correctly."
13726 (cond ((looking-at "#[ \t]+")
13727 (match-string 0))
13728 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
13729 (save-excursion
13730 (if (> (match-end 1) (+ (match-beginning 1)
13731 org-description-max-indent))
13732 (goto-char (+ (match-beginning 1) 5))
13733 (goto-char (match-end 0)))
13734 (make-string (current-column) ?\ )))
13735 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13736 (save-excursion
13737 (goto-char (match-end 0))
13738 (make-string (current-column) ?\ )))
13739 (t nil)))
13740
13741 ;;; Other stuff.
13742
13743 (defun org-toggle-fixed-width-section (arg)
13744 "Toggle the fixed-width export.
13745 If there is no active region, the QUOTE keyword at the current headline is
13746 inserted or removed. When present, it causes the text between this headline
13747 and the next to be exported as fixed-width text, and unmodified.
13748 If there is an active region, this command adds or removes a colon as the
13749 first character of this line. If the first character of a line is a colon,
13750 this line is also exported in fixed-width font."
13751 (interactive "P")
13752 (let* ((cc 0)
13753 (regionp (org-region-active-p))
13754 (beg (if regionp (region-beginning) (point)))
13755 (end (if regionp (region-end)))
13756 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13757 (case-fold-search nil)
13758 (re "[ \t]*\\(:\\)")
13759 off)
13760 (if regionp
13761 (save-excursion
13762 (goto-char beg)
13763 (setq cc (current-column))
13764 (beginning-of-line 1)
13765 (setq off (looking-at re))
13766 (while (> nlines 0)
13767 (setq nlines (1- nlines))
13768 (beginning-of-line 1)
13769 (cond
13770 (arg
13771 (org-move-to-column cc t)
13772 (insert ":\n")
13773 (forward-line -1))
13774 ((and off (looking-at re))
13775 (replace-match "" t t nil 1))
13776 ((not off) (org-move-to-column cc t) (insert ":")))
13777 (forward-line 1)))
13778 (save-excursion
13779 (org-back-to-heading)
13780 (if (looking-at (concat outline-regexp
13781 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13782 (replace-match "" t t nil 1)
13783 (if (looking-at outline-regexp)
13784 (progn
13785 (goto-char (match-end 0))
13786 (insert org-quote-string " "))))))))
13787
13788 ;;;; Functions extending outline functionality
13789
13790 (defun org-beginning-of-line (&optional arg)
13791 "Go to the beginning of the current line. If that is invisible, continue
13792 to a visible line beginning. This makes the function of C-a more intuitive.
13793 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13794 first attempt, and only move to after the tags when the cursor is already
13795 beyond the end of the headline."
13796 (interactive "P")
13797 (let ((pos (point)) refpos)
13798 (beginning-of-line 1)
13799 (if (bobp)
13800 nil
13801 (backward-char 1)
13802 (if (org-invisible-p)
13803 (while (and (not (bobp)) (org-invisible-p))
13804 (backward-char 1)
13805 (beginning-of-line 1))
13806 (forward-char 1)))
13807 (when org-special-ctrl-a/e
13808 (cond
13809 ((and (looking-at org-complex-heading-regexp)
13810 (= (char-after (match-end 1)) ?\ ))
13811 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
13812 (point-at-eol)))
13813 (goto-char
13814 (if (eq org-special-ctrl-a/e t)
13815 (cond ((> pos refpos) refpos)
13816 ((= pos (point)) refpos)
13817 (t (point)))
13818 (cond ((> pos (point)) (point))
13819 ((not (eq last-command this-command)) (point))
13820 (t refpos)))))
13821 ((org-at-item-p)
13822 (goto-char
13823 (if (eq org-special-ctrl-a/e t)
13824 (cond ((> pos (match-end 4)) (match-end 4))
13825 ((= pos (point)) (match-end 4))
13826 (t (point)))
13827 (cond ((> pos (point)) (point))
13828 ((not (eq last-command this-command)) (point))
13829 (t (match-end 4))))))))
13830 (org-no-warnings
13831 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
13832
13833 (defun org-end-of-line (&optional arg)
13834 "Go to the end of the line.
13835 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13836 first attempt, and only move to after the tags when the cursor is already
13837 beyond the end of the headline."
13838 (interactive "P")
13839 (if (or (not org-special-ctrl-a/e)
13840 (not (org-on-heading-p)))
13841 (end-of-line arg)
13842 (let ((pos (point)))
13843 (beginning-of-line 1)
13844 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13845 (if (eq org-special-ctrl-a/e t)
13846 (if (or (< pos (match-beginning 1))
13847 (= pos (match-end 0)))
13848 (goto-char (match-beginning 1))
13849 (goto-char (match-end 0)))
13850 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13851 (goto-char (match-end 0))
13852 (goto-char (match-beginning 1))))
13853 (end-of-line arg))))
13854 (org-no-warnings
13855 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
13856
13857
13858 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13859 (define-key org-mode-map "\C-e" 'org-end-of-line)
13860
13861 (defun org-kill-line (&optional arg)
13862 "Kill line, to tags or end of line."
13863 (interactive "P")
13864 (cond
13865 ((or (not org-special-ctrl-k)
13866 (bolp)
13867 (not (org-on-heading-p)))
13868 (call-interactively 'kill-line))
13869 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13870 (kill-region (point) (match-beginning 1))
13871 (org-set-tags nil t))
13872 (t (kill-region (point) (point-at-eol)))))
13873
13874
13875 (define-key org-mode-map "\C-k" 'org-kill-line)
13876
13877 (defun org-yank ()
13878 "Yank, and if the yanked text is a single subtree, fold it.
13879 In fact, if the yanked text is a sequence of subtrees, fold all of them."
13880 (interactive)
13881 (if org-yank-folded-subtrees
13882 (let ((beg (point)) end)
13883 (call-interactively 'yank)
13884 (setq end (point))
13885 (goto-char beg)
13886 (when (and (bolp)
13887 (org-kill-is-subtree-p))
13888 (or (looking-at outline-regexp)
13889 (re-search-forward (concat "^" outline-regexp) end t))
13890 (while (and (< (point) end) (looking-at outline-regexp))
13891 (hide-subtree)
13892 (org-cycle-show-empty-lines 'folded)
13893 (condition-case nil
13894 (outline-forward-same-level 1)
13895 (error (goto-char end)))))
13896 (goto-char end)
13897 (skip-chars-forward " \t\n\r"))
13898 (call-interactively 'yank)))
13899
13900 (define-key org-mode-map "\C-y" 'org-yank)
13901
13902 (defun org-invisible-p ()
13903 "Check if point is at a character currently not visible."
13904 ;; Early versions of noutline don't have `outline-invisible-p'.
13905 (if (fboundp 'outline-invisible-p)
13906 (outline-invisible-p)
13907 (get-char-property (point) 'invisible)))
13908
13909 (defun org-invisible-p2 ()
13910 "Check if point is at a character currently not visible."
13911 (save-excursion
13912 (if (and (eolp) (not (bobp))) (backward-char 1))
13913 ;; Early versions of noutline don't have `outline-invisible-p'.
13914 (if (fboundp 'outline-invisible-p)
13915 (outline-invisible-p)
13916 (get-char-property (point) 'invisible))))
13917
13918 (defalias 'org-back-to-heading 'outline-back-to-heading)
13919 (defalias 'org-on-heading-p 'outline-on-heading-p)
13920 (defalias 'org-at-heading-p 'outline-on-heading-p)
13921 (defun org-at-heading-or-item-p ()
13922 (or (org-on-heading-p) (org-at-item-p)))
13923
13924 (defun org-on-target-p ()
13925 (or (org-in-regexp org-radio-target-regexp)
13926 (org-in-regexp org-target-regexp)))
13927
13928 (defun org-up-heading-all (arg)
13929 "Move to the heading line of which the present line is a subheading.
13930 This function considers both visible and invisible heading lines.
13931 With argument, move up ARG levels."
13932 (if (fboundp 'outline-up-heading-all)
13933 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13934 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13935
13936 (defun org-up-heading-safe ()
13937 "Move to the heading line of which the present line is a subheading.
13938 This version will not throw an error. It will return the level of the
13939 headline found, or nil if no higher level is found."
13940 (let ((pos (point)) start-level level
13941 (re (concat "^" outline-regexp)))
13942 (catch 'exit
13943 (outline-back-to-heading t)
13944 (setq start-level (funcall outline-level))
13945 (if (equal start-level 1) (throw 'exit nil))
13946 (while (re-search-backward re nil t)
13947 (setq level (funcall outline-level))
13948 (if (< level start-level) (throw 'exit level)))
13949 nil)))
13950
13951 (defun org-first-sibling-p ()
13952 "Is this heading the first child of its parents?"
13953 (interactive)
13954 (let ((re (concat "^" outline-regexp))
13955 level l)
13956 (unless (org-at-heading-p t)
13957 (error "Not at a heading"))
13958 (setq level (funcall outline-level))
13959 (save-excursion
13960 (if (not (re-search-backward re nil t))
13961 t
13962 (setq l (funcall outline-level))
13963 (< l level)))))
13964
13965 (defun org-goto-sibling (&optional previous)
13966 "Goto the next sibling, even if it is invisible.
13967 When PREVIOUS is set, go to the previous sibling instead. Returns t
13968 when a sibling was found. When none is found, return nil and don't
13969 move point."
13970 (let ((fun (if previous 're-search-backward 're-search-forward))
13971 (pos (point))
13972 (re (concat "^" outline-regexp))
13973 level l)
13974 (when (condition-case nil (org-back-to-heading t) (error nil))
13975 (setq level (funcall outline-level))
13976 (catch 'exit
13977 (or previous (forward-char 1))
13978 (while (funcall fun re nil t)
13979 (setq l (funcall outline-level))
13980 (when (< l level) (goto-char pos) (throw 'exit nil))
13981 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13982 (goto-char pos)
13983 nil))))
13984
13985 (defun org-show-siblings ()
13986 "Show all siblings of the current headline."
13987 (save-excursion
13988 (while (org-goto-sibling) (org-flag-heading nil)))
13989 (save-excursion
13990 (while (org-goto-sibling 'previous)
13991 (org-flag-heading nil))))
13992
13993 (defun org-show-hidden-entry ()
13994 "Show an entry where even the heading is hidden."
13995 (save-excursion
13996 (org-show-entry)))
13997
13998 (defun org-flag-heading (flag &optional entry)
13999 "Flag the current heading. FLAG non-nil means make invisible.
14000 When ENTRY is non-nil, show the entire entry."
14001 (save-excursion
14002 (org-back-to-heading t)
14003 ;; Check if we should show the entire entry
14004 (if entry
14005 (progn
14006 (org-show-entry)
14007 (save-excursion
14008 (and (outline-next-heading)
14009 (org-flag-heading nil))))
14010 (outline-flag-region (max (point-min) (1- (point)))
14011 (save-excursion (outline-end-of-heading) (point))
14012 flag))))
14013
14014 (defun org-forward-same-level (arg)
14015 "Move forward to the ARG'th subheading at same level as this one.
14016 Stop at the first and last subheadings of a superior heading.
14017 This is like outline-forward-same-level, but invisible headings are ok."
14018 (interactive "p")
14019 (outline-back-to-heading t)
14020 (while (> arg 0)
14021 (let ((point-to-move-to (save-excursion
14022 (org-get-next-sibling))))
14023 (if point-to-move-to
14024 (progn
14025 (goto-char point-to-move-to)
14026 (setq arg (1- arg)))
14027 (progn
14028 (setq arg 0)
14029 (error "No following same-level heading"))))))
14030
14031 (defun org-get-next-sibling ()
14032 "Move to next heading of the same level, and return point.
14033 If there is no such heading, return nil.
14034 This is like outline-next-sibling, but invisible headings are ok."
14035 (let ((level (funcall outline-level)))
14036 (outline-next-heading)
14037 (while (and (not (eobp)) (> (funcall outline-level) level))
14038 (outline-next-heading))
14039 (if (or (eobp) (< (funcall outline-level) level))
14040 nil
14041 (point))))
14042
14043 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14044 ;; This is an exact copy of the original function, but it uses
14045 ;; `org-back-to-heading', to make it work also in invisible
14046 ;; trees. And is uses an invisible-OK argument.
14047 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14048 (org-back-to-heading invisible-OK)
14049 (let ((first t)
14050 (level (funcall outline-level)))
14051 (while (and (not (eobp))
14052 (or first (> (funcall outline-level) level)))
14053 (setq first nil)
14054 (outline-next-heading))
14055 (unless to-heading
14056 (if (memq (preceding-char) '(?\n ?\^M))
14057 (progn
14058 ;; Go to end of line before heading
14059 (forward-char -1)
14060 (if (memq (preceding-char) '(?\n ?\^M))
14061 ;; leave blank line before heading
14062 (forward-char -1))))))
14063 (point))
14064
14065 (defun org-show-subtree ()
14066 "Show everything after this heading at deeper levels."
14067 (outline-flag-region
14068 (point)
14069 (save-excursion
14070 (outline-end-of-subtree) (outline-next-heading) (point))
14071 nil))
14072
14073 (defun org-show-entry ()
14074 "Show the body directly following this heading.
14075 Show the heading too, if it is currently invisible."
14076 (interactive)
14077 (save-excursion
14078 (condition-case nil
14079 (progn
14080 (org-back-to-heading t)
14081 (outline-flag-region
14082 (max (point-min) (1- (point)))
14083 (save-excursion
14084 (re-search-forward
14085 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14086 (or (match-beginning 1) (point-max)))
14087 nil))
14088 (error nil))))
14089
14090 (defun org-make-options-regexp (kwds)
14091 "Make a regular expression for keyword lines."
14092 (concat
14093 "^"
14094 "#?[ \t]*\\+\\("
14095 (mapconcat 'regexp-quote kwds "\\|")
14096 "\\):[ \t]*"
14097 "\\(.+\\)"))
14098
14099 ;; Make isearch reveal the necessary context
14100 (defun org-isearch-end ()
14101 "Reveal context after isearch exits."
14102 (when isearch-success ; only if search was successful
14103 (if (featurep 'xemacs)
14104 ;; Under XEmacs, the hook is run in the correct place,
14105 ;; we directly show the context.
14106 (org-show-context 'isearch)
14107 ;; In Emacs the hook runs *before* restoring the overlays.
14108 ;; So we have to use a one-time post-command-hook to do this.
14109 ;; (Emacs 22 has a special variable, see function `org-mode')
14110 (unless (and (boundp 'isearch-mode-end-hook-quit)
14111 isearch-mode-end-hook-quit)
14112 ;; Only when the isearch was not quitted.
14113 (org-add-hook 'post-command-hook 'org-isearch-post-command
14114 'append 'local)))))
14115
14116 (defun org-isearch-post-command ()
14117 "Remove self from hook, and show context."
14118 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14119 (org-show-context 'isearch))
14120
14121
14122 ;;;; Integration with and fixes for other packages
14123
14124 ;;; Imenu support
14125
14126 (defvar org-imenu-markers nil
14127 "All markers currently used by Imenu.")
14128 (make-variable-buffer-local 'org-imenu-markers)
14129
14130 (defun org-imenu-new-marker (&optional pos)
14131 "Return a new marker for use by Imenu, and remember the marker."
14132 (let ((m (make-marker)))
14133 (move-marker m (or pos (point)))
14134 (push m org-imenu-markers)
14135 m))
14136
14137 (defun org-imenu-get-tree ()
14138 "Produce the index for Imenu."
14139 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14140 (setq org-imenu-markers nil)
14141 (let* ((n org-imenu-depth)
14142 (re (concat "^" outline-regexp))
14143 (subs (make-vector (1+ n) nil))
14144 (last-level 0)
14145 m tree level head)
14146 (save-excursion
14147 (save-restriction
14148 (widen)
14149 (goto-char (point-max))
14150 (while (re-search-backward re nil t)
14151 (setq level (org-reduced-level (funcall outline-level)))
14152 (when (<= level n)
14153 (looking-at org-complex-heading-regexp)
14154 (setq head (org-link-display-format
14155 (org-match-string-no-properties 4))
14156 m (org-imenu-new-marker))
14157 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14158 (if (>= level last-level)
14159 (push (cons head m) (aref subs level))
14160 (push (cons head (aref subs (1+ level))) (aref subs level))
14161 (loop for i from (1+ level) to n do (aset subs i nil)))
14162 (setq last-level level)))))
14163 (aref subs 1)))
14164
14165 (eval-after-load "imenu"
14166 '(progn
14167 (add-hook 'imenu-after-jump-hook
14168 (lambda ()
14169 (if (eq major-mode 'org-mode)
14170 (org-show-context 'org-goto))))))
14171
14172 (defun org-link-display-format (link)
14173 "Replace a link with either the description, or the link target
14174 if no description is present"
14175 (save-match-data
14176 (if (string-match org-bracket-link-analytic-regexp link)
14177 (replace-match (or (match-string 5 link)
14178 (concat (match-string 1 link)
14179 (match-string 3 link)))
14180 nil nil link)
14181 link)))
14182
14183 ;; Speedbar support
14184
14185 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14186 "Overlay marking the agenda restriction line in speedbar.")
14187 (org-overlay-put org-speedbar-restriction-lock-overlay
14188 'face 'org-agenda-restriction-lock)
14189 (org-overlay-put org-speedbar-restriction-lock-overlay
14190 'help-echo "Agendas are currently limited to this item.")
14191 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14192
14193 (defun org-speedbar-set-agenda-restriction ()
14194 "Restrict future agenda commands to the location at point in speedbar.
14195 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14196 (interactive)
14197 (require 'org-agenda)
14198 (let (p m tp np dir txt w)
14199 (cond
14200 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14201 'org-imenu t))
14202 (setq m (get-text-property p 'org-imenu-marker))
14203 (save-excursion
14204 (save-restriction
14205 (set-buffer (marker-buffer m))
14206 (goto-char m)
14207 (org-agenda-set-restriction-lock 'subtree))))
14208 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14209 'speedbar-function 'speedbar-find-file))
14210 (setq tp (previous-single-property-change
14211 (1+ p) 'speedbar-function)
14212 np (next-single-property-change
14213 tp 'speedbar-function)
14214 dir (speedbar-line-directory)
14215 txt (buffer-substring-no-properties (or tp (point-min))
14216 (or np (point-max))))
14217 (save-excursion
14218 (save-restriction
14219 (set-buffer (find-file-noselect
14220 (let ((default-directory dir))
14221 (expand-file-name txt))))
14222 (unless (org-mode-p)
14223 (error "Cannot restrict to non-Org-mode file"))
14224 (org-agenda-set-restriction-lock 'file))))
14225 (t (error "Don't know how to restrict Org-mode's agenda")))
14226 (org-move-overlay org-speedbar-restriction-lock-overlay
14227 (point-at-bol) (point-at-eol))
14228 (setq current-prefix-arg nil)
14229 (org-agenda-maybe-redo)))
14230
14231 (eval-after-load "speedbar"
14232 '(progn
14233 (speedbar-add-supported-extension ".org")
14234 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14235 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14236 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14237 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14238 (add-hook 'speedbar-visiting-tag-hook
14239 (lambda () (org-show-context 'org-goto)))))
14240
14241
14242 ;;; Fixes and Hacks for problems with other packages
14243
14244 ;; Make flyspell not check words in links, to not mess up our keymap
14245 (defun org-mode-flyspell-verify ()
14246 "Don't let flyspell put overlays at active buttons."
14247 (not (get-text-property (point) 'keymap)))
14248
14249 ;; Make `bookmark-jump' show the jump location if it was hidden.
14250 (eval-after-load "bookmark"
14251 '(if (boundp 'bookmark-after-jump-hook)
14252 ;; We can use the hook
14253 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14254 ;; Hook not available, use advice
14255 (defadvice bookmark-jump (after org-make-visible activate)
14256 "Make the position visible."
14257 (org-bookmark-jump-unhide))))
14258
14259 (defun org-bookmark-jump-unhide ()
14260 "Unhide the current position, to show the bookmark location."
14261 (and (org-mode-p)
14262 (or (org-invisible-p)
14263 (save-excursion (goto-char (max (point-min) (1- (point))))
14264 (org-invisible-p)))
14265 (org-show-context 'bookmark-jump)))
14266
14267 ;; Make session.el ignore our circular variable
14268 (eval-after-load "session"
14269 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14270
14271 ;;;; Experimental code
14272
14273 (defun org-closed-in-range ()
14274 "Sparse tree of items closed in a certain time range.
14275 Still experimental, may disappear in the future."
14276 (interactive)
14277 ;; Get the time interval from the user.
14278 (let* ((time1 (time-to-seconds
14279 (org-read-date nil 'to-time nil "Starting date: ")))
14280 (time2 (time-to-seconds
14281 (org-read-date nil 'to-time nil "End date:")))
14282 ;; callback function
14283 (callback (lambda ()
14284 (let ((time
14285 (time-to-seconds
14286 (apply 'encode-time
14287 (org-parse-time-string
14288 (match-string 1))))))
14289 ;; check if time in interval
14290 (and (>= time time1) (<= time time2))))))
14291 ;; make tree, check each match with the callback
14292 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14293
14294
14295 ;;;; Finish up
14296
14297 (provide 'org)
14298
14299 (run-hooks 'org-load-hook)
14300
14301 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14302
14303 ;;; org.el ends here