]> code.delx.au - gnu-emacs/blob - lisp/org/org.el
Checking in the correct versions of the files, sorry, I hade used the files
[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.14
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.14"
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-modules'."
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-w3m 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 " w3m: Special cut/past from w3m to Org." org-w3m)
176 (const :tag " mouse: Additional mouse support" org-mouse)
177
178 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
179 (const :tag "C annotation-helper: Call Remeber directly from Browser" org-annotation-helper)
180 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
181 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
182 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
183 (const :tag "C eval: Include command output as text" org-eval)
184 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
185 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
186 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
187 (const :tag "C id: Global id's for identifying entries" org-id)
188 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
189 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
190 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
191 (const :tag "C mtags: Support for muse-like tags" org-mtags)
192 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
193 (const :tag "C registry: A registry for Org links" org-registry)
194 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
195 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
196 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
197 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
198 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
199
200
201 (defgroup org-startup nil
202 "Options concerning startup of Org-mode."
203 :tag "Org Startup"
204 :group 'org)
205
206 (defcustom org-startup-folded t
207 "Non-nil means, entering Org-mode will switch to OVERVIEW.
208 This can also be configured on a per-file basis by adding one of
209 the following lines anywhere in the buffer:
210
211 #+STARTUP: fold
212 #+STARTUP: nofold
213 #+STARTUP: content"
214 :group 'org-startup
215 :type '(choice
216 (const :tag "nofold: show all" nil)
217 (const :tag "fold: overview" t)
218 (const :tag "content: all headlines" content)))
219
220 (defcustom org-startup-truncated t
221 "Non-nil means, entering Org-mode will set `truncate-lines'.
222 This is useful since some lines containing links can be very long and
223 uninteresting. Also tables look terrible when wrapped."
224 :group 'org-startup
225 :type 'boolean)
226
227 (defcustom org-startup-align-all-tables nil
228 "Non-nil means, align all tables when visiting a file.
229 This is useful when the column width in tables is forced with <N> cookies
230 in table fields. Such tables will look correct only after the first re-align.
231 This can also be configured on a per-file basis by adding one of
232 the following lines anywhere in the buffer:
233 #+STARTUP: align
234 #+STARTUP: noalign"
235 :group 'org-startup
236 :type 'boolean)
237
238 (defcustom org-insert-mode-line-in-empty-file nil
239 "Non-nil means insert the first line setting Org-mode in empty files.
240 When the function `org-mode' is called interactively in an empty file, this
241 normally means that the file name does not automatically trigger Org-mode.
242 To ensure that the file will always be in Org-mode in the future, a
243 line enforcing Org-mode will be inserted into the buffer, if this option
244 has been set."
245 :group 'org-startup
246 :type 'boolean)
247
248 (defcustom org-replace-disputed-keys nil
249 "Non-nil means use alternative key bindings for some keys.
250 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
251 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
252 If you want to use Org-mode together with one of these other modes,
253 or more generally if you would like to move some Org-mode commands to
254 other keys, set this variable and configure the keys with the variable
255 `org-disputed-keys'.
256
257 This option is only relevant at load-time of Org-mode, and must be set
258 *before* org.el is loaded. Changing it requires a restart of Emacs to
259 become effective."
260 :group 'org-startup
261 :type 'boolean)
262
263 (defcustom org-use-extra-keys nil
264 "Non-nil means use extra key sequence definitions for certain
265 commands. This happens automatically if you run XEmacs or if
266 window-system is nil. This variable lets you do the same
267 manually. You must set it before loading org.
268
269 Example: on Carbon Emacs 22 running graphically, with an external
270 keyboard on a Powerbook, the default way of setting M-left might
271 not work for either Alt or ESC. Setting this variable will make
272 it work for ESC."
273 :group 'org-startup
274 :type 'boolean)
275
276 (if (fboundp 'defvaralias)
277 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
278
279 (defcustom org-disputed-keys
280 '(([(shift up)] . [(meta p)])
281 ([(shift down)] . [(meta n)])
282 ([(shift left)] . [(meta -)])
283 ([(shift right)] . [(meta +)])
284 ([(control shift right)] . [(meta shift +)])
285 ([(control shift left)] . [(meta shift -)]))
286 "Keys for which Org-mode and other modes compete.
287 This is an alist, cars are the default keys, second element specifies
288 the alternative to use when `org-replace-disputed-keys' is t.
289
290 Keys can be specified in any syntax supported by `define-key'.
291 The value of this option takes effect only at Org-mode's startup,
292 therefore you'll have to restart Emacs to apply it after changing."
293 :group 'org-startup
294 :type 'alist)
295
296 (defun org-key (key)
297 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
298 Or return the original if not disputed."
299 (if org-replace-disputed-keys
300 (let* ((nkey (key-description key))
301 (x (org-find-if (lambda (x)
302 (equal (key-description (car x)) nkey))
303 org-disputed-keys)))
304 (if x (cdr x) key))
305 key))
306
307 (defun org-find-if (predicate seq)
308 (catch 'exit
309 (while seq
310 (if (funcall predicate (car seq))
311 (throw 'exit (car seq))
312 (pop seq)))))
313
314 (defun org-defkey (keymap key def)
315 "Define a key, possibly translated, as returned by `org-key'."
316 (define-key keymap (org-key key) def))
317
318 (defcustom org-ellipsis nil
319 "The ellipsis to use in the Org-mode outline.
320 When nil, just use the standard three dots. When a string, use that instead,
321 When a face, use the standart 3 dots, but with the specified face.
322 The change affects only Org-mode (which will then use its own display table).
323 Changing this requires executing `M-x org-mode' in a buffer to become
324 effective."
325 :group 'org-startup
326 :type '(choice (const :tag "Default" nil)
327 (face :tag "Face" :value org-warning)
328 (string :tag "String" :value "...#")))
329
330 (defvar org-display-table nil
331 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
332
333 (defgroup org-keywords nil
334 "Keywords in Org-mode."
335 :tag "Org Keywords"
336 :group 'org)
337
338 (defcustom org-deadline-string "DEADLINE:"
339 "String to mark deadline entries.
340 A deadline is this string, followed by a time stamp. Should be a word,
341 terminated by a colon. You can insert a schedule keyword and
342 a timestamp with \\[org-deadline].
343 Changes become only effective after restarting Emacs."
344 :group 'org-keywords
345 :type 'string)
346
347 (defcustom org-scheduled-string "SCHEDULED:"
348 "String to mark scheduled TODO entries.
349 A schedule is this string, followed by a time stamp. Should be a word,
350 terminated by a colon. You can insert a schedule keyword and
351 a timestamp with \\[org-schedule].
352 Changes become only effective after restarting Emacs."
353 :group 'org-keywords
354 :type 'string)
355
356 (defcustom org-closed-string "CLOSED:"
357 "String used as the prefix for timestamps logging closing a TODO entry."
358 :group 'org-keywords
359 :type 'string)
360
361 (defcustom org-clock-string "CLOCK:"
362 "String used as prefix for timestamps clocking work hours on an item."
363 :group 'org-keywords
364 :type 'string)
365
366 (defcustom org-comment-string "COMMENT"
367 "Entries starting with this keyword will never be exported.
368 An entry can be toggled between COMMENT and normal with
369 \\[org-toggle-comment].
370 Changes become only effective after restarting Emacs."
371 :group 'org-keywords
372 :type 'string)
373
374 (defcustom org-quote-string "QUOTE"
375 "Entries starting with this keyword will be exported in fixed-width font.
376 Quoting applies only to the text in the entry following the headline, and does
377 not extend beyond the next headline, even if that is lower level.
378 An entry can be toggled between QUOTE and normal with
379 \\[org-toggle-fixed-width-section]."
380 :group 'org-keywords
381 :type 'string)
382
383 (defconst org-repeat-re
384 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
385 "Regular expression for specifying repeated events.
386 After a match, group 1 contains the repeat expression.")
387
388 (defgroup org-structure nil
389 "Options concerning the general structure of Org-mode files."
390 :tag "Org Structure"
391 :group 'org)
392
393 (defgroup org-reveal-location nil
394 "Options about how to make context of a location visible."
395 :tag "Org Reveal Location"
396 :group 'org-structure)
397
398 (defconst org-context-choice
399 '(choice
400 (const :tag "Always" t)
401 (const :tag "Never" nil)
402 (repeat :greedy t :tag "Individual contexts"
403 (cons
404 (choice :tag "Context"
405 (const agenda)
406 (const org-goto)
407 (const occur-tree)
408 (const tags-tree)
409 (const link-search)
410 (const mark-goto)
411 (const bookmark-jump)
412 (const isearch)
413 (const default))
414 (boolean))))
415 "Contexts for the reveal options.")
416
417 (defcustom org-show-hierarchy-above '((default . t))
418 "Non-nil means, show full hierarchy when revealing a location.
419 Org-mode often shows locations in an org-mode file which might have
420 been invisible before. When this is set, the hierarchy of headings
421 above the exposed location is shown.
422 Turning this off for example for sparse trees makes them very compact.
423 Instead of t, this can also be an alist specifying this option for different
424 contexts. Valid contexts are
425 agenda when exposing an entry from the agenda
426 org-goto when using the command `org-goto' on key C-c C-j
427 occur-tree when using the command `org-occur' on key C-c /
428 tags-tree when constructing a sparse tree based on tags matches
429 link-search when exposing search matches associated with a link
430 mark-goto when exposing the jump goal of a mark
431 bookmark-jump when exposing a bookmark location
432 isearch when exiting from an incremental search
433 default default for all contexts not set explicitly"
434 :group 'org-reveal-location
435 :type org-context-choice)
436
437 (defcustom org-show-following-heading '((default . nil))
438 "Non-nil means, show following heading when revealing a location.
439 Org-mode often shows locations in an org-mode file which might have
440 been invisible before. When this is set, the heading following the
441 match is shown.
442 Turning this off for example for sparse trees makes them very compact,
443 but makes it harder to edit the location of the match. In such a case,
444 use the command \\[org-reveal] to show more context.
445 Instead of t, this can also be an alist specifying this option for different
446 contexts. See `org-show-hierarchy-above' for valid contexts."
447 :group 'org-reveal-location
448 :type org-context-choice)
449
450 (defcustom org-show-siblings '((default . nil) (isearch t))
451 "Non-nil means, show all sibling heading when revealing a location.
452 Org-mode often shows locations in an org-mode file which might have
453 been invisible before. When this is set, the sibling of the current entry
454 heading are all made visible. If `org-show-hierarchy-above' is t,
455 the same happens on each level of the hierarchy above the current entry.
456
457 By default this is on for the isearch context, off for all other contexts.
458 Turning this off for example for sparse trees makes them very compact,
459 but makes it harder to edit the location of the match. In such a case,
460 use the command \\[org-reveal] to show more context.
461 Instead of t, this can also be an alist specifying this option for different
462 contexts. See `org-show-hierarchy-above' for valid contexts."
463 :group 'org-reveal-location
464 :type org-context-choice)
465
466 (defcustom org-show-entry-below '((default . nil))
467 "Non-nil means, show the entry below a headline when revealing a location.
468 Org-mode often shows locations in an org-mode file which might have
469 been invisible before. When this is set, the text below the headline that is
470 exposed is also shown.
471
472 By default this is off for all contexts.
473 Instead of t, this can also be an alist specifying this option for different
474 contexts. See `org-show-hierarchy-above' for valid contexts."
475 :group 'org-reveal-location
476 :type org-context-choice)
477
478 (defcustom org-indirect-buffer-display 'other-window
479 "How should indirect tree buffers be displayed?
480 This applies to indirect buffers created with the commands
481 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
482 Valid values are:
483 current-window Display in the current window
484 other-window Just display in another window.
485 dedicated-frame Create one new frame, and re-use it each time.
486 new-frame Make a new frame each time. Note that in this case
487 previously-made indirect buffers are kept, and you need to
488 kill these buffers yourself."
489 :group 'org-structure
490 :group 'org-agenda-windows
491 :type '(choice
492 (const :tag "In current window" current-window)
493 (const :tag "In current frame, other window" other-window)
494 (const :tag "Each time a new frame" new-frame)
495 (const :tag "One dedicated frame" dedicated-frame)))
496
497 (defgroup org-cycle nil
498 "Options concerning visibility cycling in Org-mode."
499 :tag "Org Cycle"
500 :group 'org-structure)
501
502 (defcustom org-drawers '("PROPERTIES" "CLOCK")
503 "Names of drawers. Drawers are not opened by cycling on the headline above.
504 Drawers only open with a TAB on the drawer line itself. A drawer looks like
505 this:
506 :DRAWERNAME:
507 .....
508 :END:
509 The drawer \"PROPERTIES\" is special for capturing properties through
510 the property API.
511
512 Drawers can be defined on the per-file basis with a line like:
513
514 #+DRAWERS: HIDDEN STATE PROPERTIES"
515 :group 'org-structure
516 :type '(repeat (string :tag "Drawer Name")))
517
518 (defcustom org-cycle-global-at-bob nil
519 "Cycle globally if cursor is at beginning of buffer and not at a headline.
520 This makes it possible to do global cycling without having to use S-TAB or
521 C-u TAB. For this special case to work, the first line of the buffer
522 must not be a headline - it may be empty ot some other text. When used in
523 this way, `org-cycle-hook' is disables temporarily, to make sure the
524 cursor stays at the beginning of the buffer.
525 When this option is nil, don't do anything special at the beginning
526 of the buffer."
527 :group 'org-cycle
528 :type 'boolean)
529
530 (defcustom org-cycle-emulate-tab t
531 "Where should `org-cycle' emulate TAB.
532 nil Never
533 white Only in completely white lines
534 whitestart Only at the beginning of lines, before the first non-white char
535 t Everywhere except in headlines
536 exc-hl-bol Everywhere except at the start of a headline
537 If TAB is used in a place where it does not emulate TAB, the current subtree
538 visibility is cycled."
539 :group 'org-cycle
540 :type '(choice (const :tag "Never" nil)
541 (const :tag "Only in completely white lines" white)
542 (const :tag "Before first char in a line" whitestart)
543 (const :tag "Everywhere except in headlines" t)
544 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
545 ))
546
547 (defcustom org-cycle-separator-lines 2
548 "Number of empty lines needed to keep an empty line between collapsed trees.
549 If you leave an empty line between the end of a subtree and the following
550 headline, this empty line is hidden when the subtree is folded.
551 Org-mode will leave (exactly) one empty line visible if the number of
552 empty lines is equal or larger to the number given in this variable.
553 So the default 2 means, at least 2 empty lines after the end of a subtree
554 are needed to produce free space between a collapsed subtree and the
555 following headline.
556
557 Special case: when 0, never leave empty lines in collapsed view."
558 :group 'org-cycle
559 :type 'integer)
560 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
561
562 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
563 org-cycle-hide-drawers
564 org-cycle-show-empty-lines
565 org-optimize-window-after-visibility-change)
566 "Hook that is run after `org-cycle' has changed the buffer visibility.
567 The function(s) in this hook must accept a single argument which indicates
568 the new state that was set by the most recent `org-cycle' command. The
569 argument is a symbol. After a global state change, it can have the values
570 `overview', `content', or `all'. After a local state change, it can have
571 the values `folded', `children', or `subtree'."
572 :group 'org-cycle
573 :type 'hook)
574
575 (defgroup org-edit-structure nil
576 "Options concerning structure editing in Org-mode."
577 :tag "Org Edit Structure"
578 :group 'org-structure)
579
580 (defcustom org-odd-levels-only nil
581 "Non-nil means, skip even levels and only use odd levels for the outline.
582 This has the effect that two stars are being added/taken away in
583 promotion/demotion commands. It also influences how levels are
584 handled by the exporters.
585 Changing it requires restart of `font-lock-mode' to become effective
586 for fontification also in regions already fontified.
587 You may also set this on a per-file basis by adding one of the following
588 lines to the buffer:
589
590 #+STARTUP: odd
591 #+STARTUP: oddeven"
592 :group 'org-edit-structure
593 :group 'org-font-lock
594 :type 'boolean)
595
596 (defcustom org-adapt-indentation t
597 "Non-nil means, adapt indentation when promoting and demoting.
598 When this is set and the *entire* text in an entry is indented, the
599 indentation is increased by one space in a demotion command, and
600 decreased by one in a promotion command. If any line in the entry
601 body starts at column 0, indentation is not changed at all."
602 :group 'org-edit-structure
603 :type 'boolean)
604
605 (defcustom org-special-ctrl-a/e nil
606 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
607 When t, `C-a' will bring back the cursor to the beginning of the
608 headline text, i.e. after the stars and after a possible TODO keyword.
609 In an item, this will be the position after the bullet.
610 When the cursor is already at that position, another `C-a' will bring
611 it to the beginning of the line.
612 `C-e' will jump to the end of the headline, ignoring the presence of tags
613 in the headline. A second `C-e' will then jump to the true end of the
614 line, after any tags.
615 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
616 and only a directly following, identical keypress will bring the cursor
617 to the special positions."
618 :group 'org-edit-structure
619 :type '(choice
620 (const :tag "off" nil)
621 (const :tag "after bullet first" t)
622 (const :tag "border first" reversed)))
623
624 (if (fboundp 'defvaralias)
625 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
626
627 (defcustom org-special-ctrl-k nil
628 "Non-nil means `C-k' will behave specially in headlines.
629 When nil, `C-k' will call the default `kill-line' command.
630 When t, the following will happen while the cursor is in the headline:
631
632 - When the cursor is at the beginning of a headline, kill the entire
633 line and possible the folded subtree below the line.
634 - When in the middle of the headline text, kill the headline up to the tags.
635 - When after the headline text, kill the tags."
636 :group 'org-edit-structure
637 :type 'boolean)
638
639 (defcustom org-yank-folded-subtrees t
640 "Non-nil means, when yanking subtrees, fold them.
641 If the kill is a single subtree, or a sequence of subtrees, i.e. if
642 it starts with a heading and all other headings in it are either children
643 or siblings, then fold all the subtrees. However, do this only if no
644 text after the yank would be swallowed into a folded tree by this action."
645 :group 'org-edit-structure
646 :type 'boolean)
647
648 (defcustom org-yank-adjusted-subtrees t
649 "Non-nil means, when yanking subtrees, adjust the level.
650 With this setting, `org-paste-subtree' is used to insert the subtree, see
651 this function for details."
652 :group 'org-edit-structure
653 :type 'boolean)
654
655 (defcustom org-M-RET-may-split-line '((default . t))
656 "Non-nil means, M-RET will split the line at the cursor position.
657 When nil, it will go to the end of the line before making a
658 new line.
659 You may also set this option in a different way for different
660 contexts. Valid contexts are:
661
662 headline when creating a new headline
663 item when creating a new item
664 table in a table field
665 default the value to be used for all contexts not explicitly
666 customized"
667 :group 'org-structure
668 :group 'org-table
669 :type '(choice
670 (const :tag "Always" t)
671 (const :tag "Never" nil)
672 (repeat :greedy t :tag "Individual contexts"
673 (cons
674 (choice :tag "Context"
675 (const headline)
676 (const item)
677 (const table)
678 (const default))
679 (boolean)))))
680
681
682 (defcustom org-insert-heading-respect-content nil
683 "Non-nil means, insert new headings after the current subtree.
684 When nil, the new heading is created directly after the current line.
685 The commands \\[org-insert-heading-respect-content] and
686 \\[org-insert-todo-heading-respect-content] turn this variable on
687 for the duration of the command."
688 :group 'org-structure
689 :type 'boolean)
690
691 (defcustom org-blank-before-new-entry '((heading . nil)
692 (plain-list-item . nil))
693 "Should `org-insert-heading' leave a blank line before new heading/item?
694 The value is an alist, with `heading' and `plain-list-item' as car,
695 and a boolean flag as cdr."
696 :group 'org-edit-structure
697 :type '(list
698 (cons (const heading) (boolean))
699 (cons (const plain-list-item) (boolean))))
700
701 (defcustom org-insert-heading-hook nil
702 "Hook being run after inserting a new heading."
703 :group 'org-edit-structure
704 :type 'hook)
705
706 (defcustom org-enable-fixed-width-editor t
707 "Non-nil means, lines starting with \":\" are treated as fixed-width.
708 This currently only means, they are never auto-wrapped.
709 When nil, such lines will be treated like ordinary lines.
710 See also the QUOTE keyword."
711 :group 'org-edit-structure
712 :type 'boolean)
713
714 (defcustom org-edit-src-region-extra nil
715 "Additional regexps to identify regions for editing with `org-edit-src-code'.
716 For examples see the function `org-edit-src-find-region-and-lang'.
717 The regular expression identifying the begin marker should end with a newline,
718 and the regexp marking the end line should start with a newline, to make sure
719 there are kept outside the narrowed region."
720 :group 'org-edit-structure
721 :type '(repeat
722 (list
723 (regexp :tag "begin regexp")
724 (regexp :tag "end regexp")
725 (choice :tag "language"
726 (string :tag "specify")
727 (integer :tag "from match group")
728 (const :tag "from `lang' element")
729 (const :tag "from `style' element")))))
730
731 (defcustom org-edit-fixed-width-region-mode 'artist-mode
732 "The mode that should be used to edit fixed-width regions.
733 These are the regions where each line starts with a colon."
734 :group 'org-edit-structure
735 :type '(choice
736 (const artist-mode)
737 (const picture-mode)
738 (const fundamental-mode)
739 (function :tag "Other (specify)")))
740
741 (defcustom org-goto-auto-isearch t
742 "Non-nil means, typing characters in org-goto starts incremental search."
743 :group 'org-edit-structure
744 :type 'boolean)
745
746 (defgroup org-sparse-trees nil
747 "Options concerning sparse trees in Org-mode."
748 :tag "Org Sparse Trees"
749 :group 'org-structure)
750
751 (defcustom org-highlight-sparse-tree-matches t
752 "Non-nil means, highlight all matches that define a sparse tree.
753 The highlights will automatically disappear the next time the buffer is
754 changed by an edit command."
755 :group 'org-sparse-trees
756 :type 'boolean)
757
758 (defcustom org-remove-highlights-with-change t
759 "Non-nil means, any change to the buffer will remove temporary highlights.
760 Such highlights are created by `org-occur' and `org-clock-display'.
761 When nil, `C-c C-c needs to be used to get rid of the highlights.
762 The highlights created by `org-preview-latex-fragment' always need
763 `C-c C-c' to be removed."
764 :group 'org-sparse-trees
765 :group 'org-time
766 :type 'boolean)
767
768
769 (defcustom org-occur-hook '(org-first-headline-recenter)
770 "Hook that is run after `org-occur' has constructed a sparse tree.
771 This can be used to recenter the window to show as much of the structure
772 as possible."
773 :group 'org-sparse-trees
774 :type 'hook)
775
776 (defgroup org-imenu-and-speedbar nil
777 "Options concerning imenu and speedbar in Org-mode."
778 :tag "Org Imenu and Speedbar"
779 :group 'org-structure)
780
781 (defcustom org-imenu-depth 2
782 "The maximum level for Imenu access to Org-mode headlines.
783 This also applied for speedbar access."
784 :group 'org-imenu-and-speedbar
785 :type 'number)
786
787 (defgroup org-table nil
788 "Options concerning tables in Org-mode."
789 :tag "Org Table"
790 :group 'org)
791
792 (defcustom org-enable-table-editor 'optimized
793 "Non-nil means, lines starting with \"|\" are handled by the table editor.
794 When nil, such lines will be treated like ordinary lines.
795
796 When equal to the symbol `optimized', the table editor will be optimized to
797 do the following:
798 - Automatic overwrite mode in front of whitespace in table fields.
799 This makes the structure of the table stay in tact as long as the edited
800 field does not exceed the column width.
801 - Minimize the number of realigns. Normally, the table is aligned each time
802 TAB or RET are pressed to move to another field. With optimization this
803 happens only if changes to a field might have changed the column width.
804 Optimization requires replacing the functions `self-insert-command',
805 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
806 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
807 very good at guessing when a re-align will be necessary, but you can always
808 force one with \\[org-ctrl-c-ctrl-c].
809
810 If you would like to use the optimized version in Org-mode, but the
811 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
812
813 This variable can be used to turn on and off the table editor during a session,
814 but in order to toggle optimization, a restart is required.
815
816 See also the variable `org-table-auto-blank-field'."
817 :group 'org-table
818 :type '(choice
819 (const :tag "off" nil)
820 (const :tag "on" t)
821 (const :tag "on, optimized" optimized)))
822
823 (defcustom org-table-tab-recognizes-table.el t
824 "Non-nil means, TAB will automatically notice a table.el table.
825 When it sees such a table, it moves point into it and - if necessary -
826 calls `table-recognize-table'."
827 :group 'org-table-editing
828 :type 'boolean)
829
830 (defgroup org-link nil
831 "Options concerning links in Org-mode."
832 :tag "Org Link"
833 :group 'org)
834
835 (defvar org-link-abbrev-alist-local nil
836 "Buffer-local version of `org-link-abbrev-alist', which see.
837 The value of this is taken from the #+LINK lines.")
838 (make-variable-buffer-local 'org-link-abbrev-alist-local)
839
840 (defcustom org-link-abbrev-alist nil
841 "Alist of link abbreviations.
842 The car of each element is a string, to be replaced at the start of a link.
843 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
844 links in Org-mode buffers can have an optional tag after a double colon, e.g.
845
846 [[linkkey:tag][description]]
847
848 If REPLACE is a string, the tag will simply be appended to create the link.
849 If the string contains \"%s\", the tag will be inserted there. Alternatively,
850 the placeholder \"%h\" will cause a url-encoded version of the tag to
851 be inserted at that point (see the function `url-hexify-string').
852
853 REPLACE may also be a function that will be called with the tag as the
854 only argument to create the link, which should be returned as a string.
855
856 See the manual for examples."
857 :group 'org-link
858 :type '(repeat
859 (cons
860 (string :tag "Protocol")
861 (choice
862 (string :tag "Format")
863 (function)))))
864
865 (defcustom org-descriptive-links t
866 "Non-nil means, hide link part and only show description of bracket links.
867 Bracket links are like [[link][descritpion]]. This variable sets the initial
868 state in new org-mode buffers. The setting can then be toggled on a
869 per-buffer basis from the Org->Hyperlinks menu."
870 :group 'org-link
871 :type 'boolean)
872
873 (defcustom org-link-file-path-type 'adaptive
874 "How the path name in file links should be stored.
875 Valid values are:
876
877 relative Relative to the current directory, i.e. the directory of the file
878 into which the link is being inserted.
879 absolute Absolute path, if possible with ~ for home directory.
880 noabbrev Absolute path, no abbreviation of home directory.
881 adaptive Use relative path for files in the current directory and sub-
882 directories of it. For other files, use an absolute path."
883 :group 'org-link
884 :type '(choice
885 (const relative)
886 (const absolute)
887 (const noabbrev)
888 (const adaptive)))
889
890 (defcustom org-activate-links '(bracket angle plain radio tag date)
891 "Types of links that should be activated in Org-mode files.
892 This is a list of symbols, each leading to the activation of a certain link
893 type. In principle, it does not hurt to turn on most link types - there may
894 be a small gain when turning off unused link types. The types are:
895
896 bracket The recommended [[link][description]] or [[link]] links with hiding.
897 angular Links in angular brackes that may contain whitespace like
898 <bbdb:Carsten Dominik>.
899 plain Plain links in normal text, no whitespace, like http://google.com.
900 radio Text that is matched by a radio target, see manual for details.
901 tag Tag settings in a headline (link to tag search).
902 date Time stamps (link to calendar).
903
904 Changing this variable requires a restart of Emacs to become effective."
905 :group 'org-link
906 :type '(set (const :tag "Double bracket links (new style)" bracket)
907 (const :tag "Angular bracket links (old style)" angular)
908 (const :tag "Plain text links" plain)
909 (const :tag "Radio target matches" radio)
910 (const :tag "Tags" tag)
911 (const :tag "Timestamps" date)))
912
913 (defcustom org-make-link-description-function nil
914 "Function to use to generate link descriptions from links. If
915 nil the link location will be used. This function must take two
916 parameters; the first is the link and the second the description
917 org-insert-link has generated, and should return the description
918 to use."
919 :group 'org-link
920 :type 'function)
921
922 (defgroup org-link-store nil
923 "Options concerning storing links in Org-mode."
924 :tag "Org Store Link"
925 :group 'org-link)
926
927 (defcustom org-email-link-description-format "Email %c: %.30s"
928 "Format of the description part of a link to an email or usenet message.
929 The following %-excapes will be replaced by corresponding information:
930
931 %F full \"From\" field
932 %f name, taken from \"From\" field, address if no name
933 %T full \"To\" field
934 %t first name in \"To\" field, address if no name
935 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
936 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
937 %s subject
938 %m message-id.
939
940 You may use normal field width specification between the % and the letter.
941 This is for example useful to limit the length of the subject.
942
943 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
944 :group 'org-link-store
945 :type 'string)
946
947 (defcustom org-from-is-user-regexp
948 (let (r1 r2)
949 (when (and user-mail-address (not (string= user-mail-address "")))
950 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
951 (when (and user-full-name (not (string= user-full-name "")))
952 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
953 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
954 "Regexp mached against the \"From:\" header of an email or usenet message.
955 It should match if the message is from the user him/herself."
956 :group 'org-link-store
957 :type 'regexp)
958
959 (defcustom org-context-in-file-links t
960 "Non-nil means, file links from `org-store-link' contain context.
961 A search string will be added to the file name with :: as separator and
962 used to find the context when the link is activated by the command
963 `org-open-at-point'.
964 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
965 negates this setting for the duration of the command."
966 :group 'org-link-store
967 :type 'boolean)
968
969 (defcustom org-keep-stored-link-after-insertion nil
970 "Non-nil means, keep link in list for entire session.
971
972 The command `org-store-link' adds a link pointing to the current
973 location to an internal list. These links accumulate during a session.
974 The command `org-insert-link' can be used to insert links into any
975 Org-mode file (offering completion for all stored links). When this
976 option is nil, every link which has been inserted once using \\[org-insert-link]
977 will be removed from the list, to make completing the unused links
978 more efficient."
979 :group 'org-link-store
980 :type 'boolean)
981
982 (defgroup org-link-follow nil
983 "Options concerning following links in Org-mode."
984 :tag "Org Follow Link"
985 :group 'org-link)
986
987 (defcustom org-link-translation-function nil
988 "Function to translate links with different syntax to Org syntax.
989 This can be used to translate links created for example by the Planner
990 or emacs-wiki packages to Org syntax.
991 The function must accept two parameters, a TYPE containing the link
992 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
993 which is everything after the link protocol. It should return a cons
994 with possibly modifed values of type and path.
995 Org contains a function for this, so if you set this variable to
996 `org-translate-link-from-planner', you should be able follow many
997 links created by planner."
998 :group 'org-link-follow
999 :type 'function)
1000
1001 (defcustom org-follow-link-hook nil
1002 "Hook that is run after a link has been followed."
1003 :group 'org-link-follow
1004 :type 'hook)
1005
1006 (defcustom org-tab-follows-link nil
1007 "Non-nil means, on links TAB will follow the link.
1008 Needs to be set before org.el is loaded."
1009 :group 'org-link-follow
1010 :type 'boolean)
1011
1012 (defcustom org-return-follows-link nil
1013 "Non-nil means, on links RET will follow the link.
1014 Needs to be set before org.el is loaded."
1015 :group 'org-link-follow
1016 :type 'boolean)
1017
1018 (defcustom org-mouse-1-follows-link
1019 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1020 "Non-nil means, mouse-1 on a link will follow the link.
1021 A longer mouse click will still set point. Does not work on XEmacs.
1022 Needs to be set before org.el is loaded."
1023 :group 'org-link-follow
1024 :type 'boolean)
1025
1026 (defcustom org-mark-ring-length 4
1027 "Number of different positions to be recorded in the ring
1028 Changing this requires a restart of Emacs to work correctly."
1029 :group 'org-link-follow
1030 :type 'interger)
1031
1032 (defcustom org-link-frame-setup
1033 '((vm . vm-visit-folder-other-frame)
1034 (gnus . gnus-other-frame)
1035 (file . find-file-other-window))
1036 "Setup the frame configuration for following links.
1037 When following a link with Emacs, it may often be useful to display
1038 this link in another window or frame. This variable can be used to
1039 set this up for the different types of links.
1040 For VM, use any of
1041 `vm-visit-folder'
1042 `vm-visit-folder-other-frame'
1043 For Gnus, use any of
1044 `gnus'
1045 `gnus-other-frame'
1046 `org-gnus-no-new-news'
1047 For FILE, use any of
1048 `find-file'
1049 `find-file-other-window'
1050 `find-file-other-frame'
1051 For the calendar, use the variable `calendar-setup'.
1052 For BBDB, it is currently only possible to display the matches in
1053 another window."
1054 :group 'org-link-follow
1055 :type '(list
1056 (cons (const vm)
1057 (choice
1058 (const vm-visit-folder)
1059 (const vm-visit-folder-other-window)
1060 (const vm-visit-folder-other-frame)))
1061 (cons (const gnus)
1062 (choice
1063 (const gnus)
1064 (const gnus-other-frame)
1065 (const org-gnus-no-new-news)))
1066 (cons (const file)
1067 (choice
1068 (const find-file)
1069 (const find-file-other-window)
1070 (const find-file-other-frame)))))
1071
1072 (defcustom org-display-internal-link-with-indirect-buffer nil
1073 "Non-nil means, use indirect buffer to display infile links.
1074 Activating internal links (from one location in a file to another location
1075 in the same file) normally just jumps to the location. When the link is
1076 activated with a C-u prefix (or with mouse-3), the link is displayed in
1077 another window. When this option is set, the other window actually displays
1078 an indirect buffer clone of the current buffer, to avoid any visibility
1079 changes to the current buffer."
1080 :group 'org-link-follow
1081 :type 'boolean)
1082
1083 (defcustom org-open-non-existing-files nil
1084 "Non-nil means, `org-open-file' will open non-existing files.
1085 When nil, an error will be generated."
1086 :group 'org-link-follow
1087 :type 'boolean)
1088
1089 (defcustom org-open-directory-means-index-dot-org nil
1090 "Non-nil means, a link to a directory really means to index.org.
1091 When nil, following a directory link will run dired or open a finder/explorer
1092 window on that directory."
1093 :group 'org-link-follow
1094 :type 'boolean)
1095
1096 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1097 "Function and arguments to call for following mailto links.
1098 This is a list with the first element being a lisp function, and the
1099 remaining elements being arguments to the function. In string arguments,
1100 %a will be replaced by the address, and %s will be replaced by the subject
1101 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1102 :group 'org-link-follow
1103 :type '(choice
1104 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1105 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1106 (const :tag "message-mail" (message-mail "%a" "%s"))
1107 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1108
1109 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1110 "Non-nil means, ask for confirmation before executing shell links.
1111 Shell links can be dangerous: just think about a link
1112
1113 [[shell:rm -rf ~/*][Google Search]]
1114
1115 This link would show up in your Org-mode document as \"Google Search\",
1116 but really it would remove your entire home directory.
1117 Therefore we advise against setting this variable to nil.
1118 Just change it to `y-or-n-p' of you want to confirm with a
1119 single keystroke rather than having to type \"yes\"."
1120 :group 'org-link-follow
1121 :type '(choice
1122 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1123 (const :tag "with y-or-n (faster)" y-or-n-p)
1124 (const :tag "no confirmation (dangerous)" nil)))
1125
1126 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1127 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1128 Elisp links can be dangerous: just think about a link
1129
1130 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1131
1132 This link would show up in your Org-mode document as \"Google Search\",
1133 but really it would remove your entire home directory.
1134 Therefore we advise against setting this variable to nil.
1135 Just change it to `y-or-n-p' of you want to confirm with a
1136 single keystroke rather than having to type \"yes\"."
1137 :group 'org-link-follow
1138 :type '(choice
1139 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1140 (const :tag "with y-or-n (faster)" y-or-n-p)
1141 (const :tag "no confirmation (dangerous)" nil)))
1142
1143 (defconst org-file-apps-defaults-gnu
1144 '((remote . emacs)
1145 (system . mailcap)
1146 (t . mailcap))
1147 "Default file applications on a UNIX or GNU/Linux system.
1148 See `org-file-apps'.")
1149
1150 (defconst org-file-apps-defaults-macosx
1151 '((remote . emacs)
1152 (t . "open %s")
1153 (system . "open %s")
1154 ("ps.gz" . "gv %s")
1155 ("eps.gz" . "gv %s")
1156 ("dvi" . "xdvi %s")
1157 ("fig" . "xfig %s"))
1158 "Default file applications on a MacOS X system.
1159 The system \"open\" is known as a default, but we use X11 applications
1160 for some files for which the OS does not have a good default.
1161 See `org-file-apps'.")
1162
1163 (defconst org-file-apps-defaults-windowsnt
1164 (list
1165 '(remote . emacs)
1166 (cons t
1167 (list (if (featurep 'xemacs)
1168 'mswindows-shell-execute
1169 'w32-shell-execute)
1170 "open" 'file))
1171 (cons 'system
1172 (list (if (featurep 'xemacs)
1173 'mswindows-shell-execute
1174 'w32-shell-execute)
1175 "open" 'file)))
1176 "Default file applications on a Windows NT system.
1177 The system \"open\" is used for most files.
1178 See `org-file-apps'.")
1179
1180 (defcustom org-file-apps
1181 '(
1182 (auto-mode . emacs)
1183 ("\\.x?html?\\'" . default)
1184 ("\\.pdf\\'" . default)
1185 )
1186 "External applications for opening `file:path' items in a document.
1187 Org-mode uses system defaults for different file types, but
1188 you can use this variable to set the application for a given file
1189 extension. The entries in this list are cons cells where the car identifies
1190 files and the cdr the corresponding command. Possible values for the
1191 file identifier are
1192 \"regex\" Regular expression matched against the file name. For backward
1193 compatibility, this can also be a string with only alphanumeric
1194 characters, which is then interpreted as an extension.
1195 `directory' Matches a directory
1196 `remote' Matches a remote file, accessible through tramp or efs.
1197 Remote files most likely should be visited through Emacs
1198 because external applications cannot handle such paths.
1199 `auto-mode' Matches files that are mached by any entry in `auto-mode-alist',
1200 so all files Emacs knows how to handle. Using this with
1201 command `emacs' will open most files in Emacs. Beware that this
1202 will also open html files insite Emacs, unless you add
1203 (\"html\" . default) to the list as well.
1204 t Default for files not matched by any of the other options.
1205 `system' The system command to open files, like `open' on Windows
1206 and Mac OS X, and mailcap under GNU/Linux. This is the command
1207 that will be selected if you call `C-c C-o' with a double
1208 `C-u C-u' prefix.
1209
1210 Possible values for the command are:
1211 `emacs' The file will be visited by the current Emacs process.
1212 `default' Use the default application for this file type, which is the
1213 association for t in the list, most likely in the system-specific
1214 part.
1215 This can be used to overrule an unwanted seting in the
1216 system-specific variable.
1217 `system' Use the system command for opening files, like \"open\".
1218 This command is specified by the entry whose car is `system'.
1219 Most likely, the system-specific version of this variable
1220 does define this command, but you can overrule/replace it
1221 here.
1222 string A command to be executed by a shell; %s will be replaced
1223 by the path to the file.
1224 sexp A Lisp form which will be evaluated. The file path will
1225 be available in the Lisp variable `file'.
1226 For more examples, see the system specific constants
1227 `org-file-apps-defaults-macosx'
1228 `org-file-apps-defaults-windowsnt'
1229 `org-file-apps-defaults-gnu'."
1230 :group 'org-link-follow
1231 :type '(repeat
1232 (cons (choice :value ""
1233 (string :tag "Extension")
1234 (const :tag "System command to open files" system)
1235 (const :tag "Default for unrecognized files" t)
1236 (const :tag "Remote file" remote)
1237 (const :tag "Links to a directory" directory)
1238 (const :tag "Any files that have Emacs modes"
1239 auto-mode))
1240 (choice :value ""
1241 (const :tag "Visit with Emacs" emacs)
1242 (const :tag "Use default" default)
1243 (const :tag "Use the system command" system)
1244 (string :tag "Command")
1245 (sexp :tag "Lisp form")))))
1246
1247 (defgroup org-refile nil
1248 "Options concerning refiling entries in Org-mode."
1249 :tag "Org Refile"
1250 :group 'org)
1251
1252 (defcustom org-directory "~/org"
1253 "Directory with org files.
1254 This directory will be used as default to prompt for org files.
1255 Used by the hooks for remember.el."
1256 :group 'org-refile
1257 :group 'org-remember
1258 :type 'directory)
1259
1260 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1261 "Default target for storing notes.
1262 Used by the hooks for remember.el. This can be a string, or nil to mean
1263 the value of `remember-data-file'.
1264 You can set this on a per-template basis with the variable
1265 `org-remember-templates'."
1266 :group 'org-refile
1267 :group 'org-remember
1268 :type '(choice
1269 (const :tag "Default from remember-data-file" nil)
1270 file))
1271
1272 (defcustom org-goto-interface 'outline
1273 "The default interface to be used for `org-goto'.
1274 Allowed vaues are:
1275 outline The interface shows an outline of the relevant file
1276 and the correct heading is found by moving through
1277 the outline or by searching with incremental search.
1278 outline-path-completion Headlines in the current buffer are offered via
1279 completion. This is the interface also used by
1280 the refile command."
1281 :group 'org-refile
1282 :type '(choice
1283 (const :tag "Outline" outline)
1284 (const :tag "Outline-path-completion" outline-path-completion)))
1285
1286 (defcustom org-reverse-note-order nil
1287 "Non-nil means, store new notes at the beginning of a file or entry.
1288 When nil, new notes will be filed to the end of a file or entry.
1289 This can also be a list with cons cells of regular expressions that
1290 are matched against file names, and values."
1291 :group 'org-remember
1292 :group 'org-refile
1293 :type '(choice
1294 (const :tag "Reverse always" t)
1295 (const :tag "Reverse never" nil)
1296 (repeat :tag "By file name regexp"
1297 (cons regexp boolean))))
1298
1299 (defcustom org-refile-targets nil
1300 "Targets for refiling entries with \\[org-refile].
1301 This is list of cons cells. Each cell contains:
1302 - a specification of the files to be considered, either a list of files,
1303 or a symbol whose function or variable value will be used to retrieve
1304 a file name or a list of file names. Nil means, refile to a different
1305 heading in the current buffer.
1306 - A specification of how to find candidate refile targets. This may be
1307 any of
1308 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1309 This tag has to be present in all target headlines, inheritance will
1310 not be considered.
1311 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1312 todo keyword.
1313 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1314 headlines that are refiling targets.
1315 - a cons cell (:level . N). Any headline of level N is considered a target.
1316 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1317
1318 When this variable is nil, all top-level headlines in the current buffer
1319 are used, equivalent to the value `((nil . (:level . 1))'."
1320 :group 'org-refile
1321 :type '(repeat
1322 (cons
1323 (choice :value org-agenda-files
1324 (const :tag "All agenda files" org-agenda-files)
1325 (const :tag "Current buffer" nil)
1326 (function) (variable) (file))
1327 (choice :tag "Identify target headline by"
1328 (cons :tag "Specific tag" (const :value :tag) (string))
1329 (cons :tag "TODO keyword" (const :value :todo) (string))
1330 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1331 (cons :tag "Level number" (const :value :level) (integer))
1332 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1333
1334 (defcustom org-refile-use-outline-path nil
1335 "Non-nil means, provide refile targets as paths.
1336 So a level 3 headline will be available as level1/level2/level3.
1337 When the value is `file', also include the file name (without directory)
1338 into the path. When `full-file-path', include the full file path."
1339 :group 'org-refile
1340 :type '(choice
1341 (const :tag "Not" nil)
1342 (const :tag "Yes" t)
1343 (const :tag "Start with file name" file)
1344 (const :tag "Start with full file path" full-file-path)))
1345
1346 (defcustom org-outline-path-complete-in-steps t
1347 "Non-nil means, complete the outline path in hierarchical steps.
1348 When Org-mode uses the refile interface to select an outline path
1349 \(see variable `org-refile-use-outline-path'), the completion of
1350 the path can be done is a single go, or if can be done in steps down
1351 the headline hierarchy. Going in steps is probably the best if you
1352 do not use a special completion package like `ido' or `icicles'.
1353 However, when using these packages, going in one step can be very
1354 fast, while still showing the whole path to the entry."
1355 :group 'org-refile
1356 :type 'boolean)
1357
1358 (defgroup org-todo nil
1359 "Options concerning TODO items in Org-mode."
1360 :tag "Org TODO"
1361 :group 'org)
1362
1363 (defgroup org-progress nil
1364 "Options concerning Progress logging in Org-mode."
1365 :tag "Org Progress"
1366 :group 'org-time)
1367
1368 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1369 "List of TODO entry keyword sequences and their interpretation.
1370 \\<org-mode-map>This is a list of sequences.
1371
1372 Each sequence starts with a symbol, either `sequence' or `type',
1373 indicating if the keywords should be interpreted as a sequence of
1374 action steps, or as different types of TODO items. The first
1375 keywords are states requiring action - these states will select a headline
1376 for inclusion into the global TODO list Org-mode produces. If one of
1377 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1378 signify that no further action is necessary. If \"|\" is not found,
1379 the last keyword is treated as the only DONE state of the sequence.
1380
1381 The command \\[org-todo] cycles an entry through these states, and one
1382 additional state where no keyword is present. For details about this
1383 cycling, see the manual.
1384
1385 TODO keywords and interpretation can also be set on a per-file basis with
1386 the special #+SEQ_TODO and #+TYP_TODO lines.
1387
1388 Each keyword can optionally specify a character for fast state selection
1389 \(in combination with the variable `org-use-fast-todo-selection')
1390 and specifiers for state change logging, using the same syntax
1391 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1392 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1393 indicates to record a time stamp each time this state is selected.
1394
1395 Each keyword may also specify if a timestamp or a note should be
1396 recorded when entering or leaving the state, by adding additional
1397 characters in the parenthesis after the keyword. This looks like this:
1398 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1399 record only the time of the state change. With X and Y being either
1400 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1401 Y when leaving the state if and only if the *target* state does not
1402 define X. You may omit any of the fast-selection key or X or /Y,
1403 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1404
1405 For backward compatibility, this variable may also be just a list
1406 of keywords - in this case the interptetation (sequence or type) will be
1407 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1408 :group 'org-todo
1409 :group 'org-keywords
1410 :type '(choice
1411 (repeat :tag "Old syntax, just keywords"
1412 (string :tag "Keyword"))
1413 (repeat :tag "New syntax"
1414 (cons
1415 (choice
1416 :tag "Interpretation"
1417 (const :tag "Sequence (cycling hits every state)" sequence)
1418 (const :tag "Type (cycling directly to DONE)" type))
1419 (repeat
1420 (string :tag "Keyword"))))))
1421
1422 (defvar org-todo-keywords-1 nil
1423 "All TODO and DONE keywords active in a buffer.")
1424 (make-variable-buffer-local 'org-todo-keywords-1)
1425 (defvar org-todo-keywords-for-agenda nil)
1426 (defvar org-done-keywords-for-agenda nil)
1427 (defvar org-todo-keyword-alist-for-agenda nil)
1428 (defvar org-tag-alist-for-agenda nil)
1429 (defvar org-agenda-contributing-files nil)
1430 (defvar org-not-done-keywords nil)
1431 (make-variable-buffer-local 'org-not-done-keywords)
1432 (defvar org-done-keywords nil)
1433 (make-variable-buffer-local 'org-done-keywords)
1434 (defvar org-todo-heads nil)
1435 (make-variable-buffer-local 'org-todo-heads)
1436 (defvar org-todo-sets nil)
1437 (make-variable-buffer-local 'org-todo-sets)
1438 (defvar org-todo-log-states nil)
1439 (make-variable-buffer-local 'org-todo-log-states)
1440 (defvar org-todo-kwd-alist nil)
1441 (make-variable-buffer-local 'org-todo-kwd-alist)
1442 (defvar org-todo-key-alist nil)
1443 (make-variable-buffer-local 'org-todo-key-alist)
1444 (defvar org-todo-key-trigger nil)
1445 (make-variable-buffer-local 'org-todo-key-trigger)
1446
1447 (defcustom org-todo-interpretation 'sequence
1448 "Controls how TODO keywords are interpreted.
1449 This variable is in principle obsolete and is only used for
1450 backward compatibility, if the interpretation of todo keywords is
1451 not given already in `org-todo-keywords'. See that variable for
1452 more information."
1453 :group 'org-todo
1454 :group 'org-keywords
1455 :type '(choice (const sequence)
1456 (const type)))
1457
1458 (defcustom org-use-fast-todo-selection 'prefix
1459 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1460 This variable describes if and under what circumstances the cycling
1461 mechanism for TODO keywords will be replaced by a single-key, direct
1462 selection scheme.
1463
1464 When nil, fast selection is never used.
1465
1466 When the symbol `prefix', it will be used when `org-todo' is called with
1467 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1468 in an agenda buffer.
1469
1470 When t, fast selection is used by default. In this case, the prefix
1471 argument forces cycling instead.
1472
1473 In all cases, the special interface is only used if access keys have actually
1474 been assigned by the user, i.e. if keywords in the configuration are followed
1475 by a letter in parenthesis, like TODO(t)."
1476 :group 'org-todo
1477 :type '(choice
1478 (const :tag "Never" nil)
1479 (const :tag "By default" t)
1480 (const :tag "Only with C-u C-c C-t" prefix)))
1481
1482 (defcustom org-provide-todo-statistics t
1483 "Non-nil means, update todo statistics after insert and toggle.
1484 When this is set, todo statistics is updated in the parent of the current
1485 entry each time a todo state is changed."
1486 :group 'org-todo
1487 :type 'boolean)
1488
1489 (defcustom org-after-todo-state-change-hook nil
1490 "Hook which is run after the state of a TODO item was changed.
1491 The new state (a string with a TODO keyword, or nil) is available in the
1492 Lisp variable `state'."
1493 :group 'org-todo
1494 :type 'hook)
1495
1496 (defcustom org-todo-state-tags-triggers nil
1497 "Tag changes that should be triggered by TODO state changes.
1498 This is a list. Each entry is
1499
1500 (state-change (tag . flag) .......)
1501
1502 State-change can be a string with a state, and empty string to indicate the
1503 state that has no TODO keyword, or it can be one of the symbols `todo'
1504 or `done', meaning any not-done or done state, respectively."
1505 :group 'org-todo
1506 :group 'org-tags
1507 :type '(repeat
1508 (cons (choice :tag "When changing to"
1509 (const :tag "Not-done state" todo)
1510 (const :tag "Done state" done)
1511 (string :tag "State"))
1512 (repeat
1513 (cons :tag "Tag action"
1514 (string :tag "Tag")
1515 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1516
1517 (defcustom org-log-done nil
1518 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1519 When equal to the list (done), also prompt for a closing note.
1520 This can also be configured on a per-file basis by adding one of
1521 the following lines anywhere in the buffer:
1522
1523 #+STARTUP: logdone
1524 #+STARTUP: lognotedone
1525 #+STARTUP: nologdone"
1526 :group 'org-todo
1527 :group 'org-progress
1528 :type '(choice
1529 (const :tag "No logging" nil)
1530 (const :tag "Record CLOSED timestamp" time)
1531 (const :tag "Record CLOSED timestamp with closing note." note)))
1532
1533 ;; Normalize old uses of org-log-done.
1534 (cond
1535 ((eq org-log-done t) (setq org-log-done 'time))
1536 ((and (listp org-log-done) (memq 'done org-log-done))
1537 (setq org-log-done 'note)))
1538
1539 (defcustom org-log-note-clock-out nil
1540 "Non-nil means, record a note when clocking out of an item.
1541 This can also be configured on a per-file basis by adding one of
1542 the following lines anywhere in the buffer:
1543
1544 #+STARTUP: lognoteclock-out
1545 #+STARTUP: nolognoteclock-out"
1546 :group 'org-todo
1547 :group 'org-progress
1548 :type 'boolean)
1549
1550 (defcustom org-log-done-with-time t
1551 "Non-nil means, the CLOSED time stamp will contain date and time.
1552 When nil, only the date will be recorded."
1553 :group 'org-progress
1554 :type 'boolean)
1555
1556 (defcustom org-log-note-headings
1557 '((done . "CLOSING NOTE %t")
1558 (state . "State %-12s %t")
1559 (note . "Note taken on %t")
1560 (clock-out . ""))
1561 "Headings for notes added to entries.
1562 The value is an alist, with the car being a symbol indicating the note
1563 context, and the cdr is the heading to be used. The heading may also be the
1564 empty string.
1565 %t in the heading will be replaced by a time stamp.
1566 %s will be replaced by the new TODO state, in double quotes.
1567 %u will be replaced by the user name.
1568 %U will be replaced by the full user name."
1569 :group 'org-todo
1570 :group 'org-progress
1571 :type '(list :greedy t
1572 (cons (const :tag "Heading when closing an item" done) string)
1573 (cons (const :tag
1574 "Heading when changing todo state (todo sequence only)"
1575 state) string)
1576 (cons (const :tag "Heading when just taking a note" note) string)
1577 (cons (const :tag "Heading when clocking out" clock-out) string)))
1578
1579 (unless (assq 'note org-log-note-headings)
1580 (push '(note . "%t") org-log-note-headings))
1581
1582 (defcustom org-log-state-notes-insert-after-drawers nil
1583 "Non-nil means, insert state change notes after any drawers in entry.
1584 Only the drawers that *immediately* follow the headline and the
1585 deadline/scheduled line are skipped.
1586 When nil, insert notes right after the heading and perhaps the line
1587 with deadline/scheduling if present."
1588 :group 'org-todo
1589 :group 'org-progress
1590 :type 'boolean)
1591
1592 (defcustom org-log-states-order-reversed t
1593 "Non-nil means, the latest state change note will be directly after heading.
1594 When nil, the notes will be orderer according to time."
1595 :group 'org-todo
1596 :group 'org-progress
1597 :type 'boolean)
1598
1599 (defcustom org-log-repeat 'time
1600 "Non-nil means, record moving through the DONE state when triggering repeat.
1601 An auto-repeating tasks is immediately switched back to TODO when marked
1602 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1603 the TODO keyword definition, or recording a closing note by setting
1604 `org-log-done', there will be no record of the task moving through DONE.
1605 This variable forces taking a note anyway. Possible values are:
1606
1607 nil Don't force a record
1608 time Record a time stamp
1609 note Record a note
1610
1611 This option can also be set with on a per-file-basis with
1612
1613 #+STARTUP: logrepeat
1614 #+STARTUP: lognoterepeat
1615 #+STARTUP: nologrepeat
1616
1617 You can have local logging settings for a subtree by setting the LOGGING
1618 property to one or more of these keywords."
1619 :group 'org-todo
1620 :group 'org-progress
1621 :type '(choice
1622 (const :tag "Don't force a record" nil)
1623 (const :tag "Force recording the DONE state" time)
1624 (const :tag "Force recording a note with the DONE state" note)))
1625
1626
1627 (defgroup org-priorities nil
1628 "Priorities in Org-mode."
1629 :tag "Org Priorities"
1630 :group 'org-todo)
1631
1632 (defcustom org-highest-priority ?A
1633 "The highest priority of TODO items. A character like ?A, ?B etc.
1634 Must have a smaller ASCII number than `org-lowest-priority'."
1635 :group 'org-priorities
1636 :type 'character)
1637
1638 (defcustom org-lowest-priority ?C
1639 "The lowest priority of TODO items. A character like ?A, ?B etc.
1640 Must have a larger ASCII number than `org-highest-priority'."
1641 :group 'org-priorities
1642 :type 'character)
1643
1644 (defcustom org-default-priority ?B
1645 "The default priority of TODO items.
1646 This is the priority an item get if no explicit priority is given."
1647 :group 'org-priorities
1648 :type 'character)
1649
1650 (defcustom org-priority-start-cycle-with-default t
1651 "Non-nil means, start with default priority when starting to cycle.
1652 When this is nil, the first step in the cycle will be (depending on the
1653 command used) one higher or lower that the default priority."
1654 :group 'org-priorities
1655 :type 'boolean)
1656
1657 (defgroup org-time nil
1658 "Options concerning time stamps and deadlines in Org-mode."
1659 :tag "Org Time"
1660 :group 'org)
1661
1662 (defcustom org-insert-labeled-timestamps-at-point nil
1663 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1664 When nil, these labeled time stamps are forces into the second line of an
1665 entry, just after the headline. When scheduling from the global TODO list,
1666 the time stamp will always be forced into the second line."
1667 :group 'org-time
1668 :type 'boolean)
1669
1670 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1671 "Formats for `format-time-string' which are used for time stamps.
1672 It is not recommended to change this constant.")
1673
1674 (defcustom org-time-stamp-rounding-minutes '(0 5)
1675 "Number of minutes to round time stamps to.
1676 These are two values, the first applies when first creating a time stamp.
1677 The second applies when changing it with the commands `S-up' and `S-down'.
1678 When changing the time stamp, this means that it will change in steps
1679 of N minutes, as given by the second value.
1680
1681 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1682 numbers should be factors of 60, so for example 5, 10, 15.
1683
1684 When this is larger than 1, you can still force an exact time-stamp by using
1685 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1686 and by using a prefix arg to `S-up/down' to specify the exact number
1687 of minutes to shift."
1688 :group 'org-time
1689 :get '(lambda (var) ; Make sure all entries have 5 elements
1690 (if (integerp (default-value var))
1691 (list (default-value var) 5)
1692 (default-value var)))
1693 :type '(list
1694 (integer :tag "when inserting times")
1695 (integer :tag "when modifying times")))
1696
1697 ;; Normalize old customizations of this variable.
1698 (when (integerp org-time-stamp-rounding-minutes)
1699 (setq org-time-stamp-rounding-minutes
1700 (list org-time-stamp-rounding-minutes
1701 org-time-stamp-rounding-minutes)))
1702
1703 (defcustom org-display-custom-times nil
1704 "Non-nil means, overlay custom formats over all time stamps.
1705 The formats are defined through the variable `org-time-stamp-custom-formats'.
1706 To turn this on on a per-file basis, insert anywhere in the file:
1707 #+STARTUP: customtime"
1708 :group 'org-time
1709 :set 'set-default
1710 :type 'sexp)
1711 (make-variable-buffer-local 'org-display-custom-times)
1712
1713 (defcustom org-time-stamp-custom-formats
1714 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1715 "Custom formats for time stamps. See `format-time-string' for the syntax.
1716 These are overlayed over the default ISO format if the variable
1717 `org-display-custom-times' is set. Time like %H:%M should be at the
1718 end of the second format."
1719 :group 'org-time
1720 :type 'sexp)
1721
1722 (defun org-time-stamp-format (&optional long inactive)
1723 "Get the right format for a time string."
1724 (let ((f (if long (cdr org-time-stamp-formats)
1725 (car org-time-stamp-formats))))
1726 (if inactive
1727 (concat "[" (substring f 1 -1) "]")
1728 f)))
1729
1730 (defcustom org-time-clocksum-format "%d:%02d"
1731 "The format string used when creating CLOCKSUM lines, or when
1732 org-mode generates a time duration."
1733 :group 'org-time
1734 :type 'string)
1735
1736 (defcustom org-deadline-warning-days 14
1737 "No. of days before expiration during which a deadline becomes active.
1738 This variable governs the display in sparse trees and in the agenda.
1739 When 0 or negative, it means use this number (the absolute value of it)
1740 even if a deadline has a different individual lead time specified."
1741 :group 'org-time
1742 :group 'org-agenda-daily/weekly
1743 :type 'number)
1744
1745 (defcustom org-read-date-prefer-future t
1746 "Non-nil means, assume future for incomplete date input from user.
1747 This affects the following situations:
1748 1. The user gives a day, but no month.
1749 For example, if today is the 15th, and you enter \"3\", Org-mode will
1750 read this as the third of *next* month. However, if you enter \"17\",
1751 it will be considered as *this* month.
1752 2. The user gives a month but not a year.
1753 For example, if it is april and you enter \"feb 2\", this will be read
1754 as feb 2, *next* year. \"May 5\", however, will be this year.
1755
1756 Currently this does not work for ISO week specifications.
1757
1758 When this option is nil, the current month and year will always be used
1759 as defaults."
1760 :group 'org-time
1761 :type 'boolean)
1762
1763 (defcustom org-read-date-display-live t
1764 "Non-nil means, display current interpretation of date prompt live.
1765 This display will be in an overlay, in the minibuffer."
1766 :group 'org-time
1767 :type 'boolean)
1768
1769 (defcustom org-read-date-popup-calendar t
1770 "Non-nil means, pop up a calendar when prompting for a date.
1771 In the calendar, the date can be selected with mouse-1. However, the
1772 minibuffer will also be active, and you can simply enter the date as well.
1773 When nil, only the minibuffer will be available."
1774 :group 'org-time
1775 :type 'boolean)
1776 (if (fboundp 'defvaralias)
1777 (defvaralias 'org-popup-calendar-for-date-prompt
1778 'org-read-date-popup-calendar))
1779
1780 (defcustom org-extend-today-until 0
1781 "The hour when your day really ends. Must be an integer.
1782 This has influence for the following applications:
1783 - When switching the agenda to \"today\". It it is still earlier than
1784 the time given here, the day recognized as TODAY is actually yesterday.
1785 - When a date is read from the user and it is still before the time given
1786 here, the current date and time will be assumed to be yesterday, 23:59.
1787 Also, timestamps inserted in remember templates follow this rule.
1788
1789 IMPORTANT: This is a feature whose implementation is and likely will
1790 remain incomplete. Really, it is only here because past midnight seems to
1791 be the favorite working time of John Wiegley :-)"
1792 :group 'org-time
1793 :type 'number)
1794
1795 (defcustom org-edit-timestamp-down-means-later nil
1796 "Non-nil means, S-down will increase the time in a time stamp.
1797 When nil, S-up will increase."
1798 :group 'org-time
1799 :type 'boolean)
1800
1801 (defcustom org-calendar-follow-timestamp-change t
1802 "Non-nil means, make the calendar window follow timestamp changes.
1803 When a timestamp is modified and the calendar window is visible, it will be
1804 moved to the new date."
1805 :group 'org-time
1806 :type 'boolean)
1807
1808 (defgroup org-tags nil
1809 "Options concerning tags in Org-mode."
1810 :tag "Org Tags"
1811 :group 'org)
1812
1813 (defcustom org-tag-alist nil
1814 "List of tags allowed in Org-mode files.
1815 When this list is nil, Org-mode will base TAG input on what is already in the
1816 buffer.
1817 The value of this variable is an alist, the car of each entry must be a
1818 keyword as a string, the cdr may be a character that is used to select
1819 that tag through the fast-tag-selection interface.
1820 See the manual for details."
1821 :group 'org-tags
1822 :type '(repeat
1823 (choice
1824 (cons (string :tag "Tag name")
1825 (character :tag "Access char"))
1826 (const :tag "Start radio group" (:startgroup))
1827 (const :tag "End radio group" (:endgroup)))))
1828
1829 (defvar org-file-tags nil
1830 "List of tags that can be inherited by all entries in the file.
1831 The tags will be inherited if the variable `org-use-tag-inheritance'
1832 says they should be.
1833 This variable is populated from #+TAG lines.")
1834
1835 (defcustom org-use-fast-tag-selection 'auto
1836 "Non-nil means, use fast tag selection scheme.
1837 This is a special interface to select and deselect tags with single keys.
1838 When nil, fast selection is never used.
1839 When the symbol `auto', fast selection is used if and only if selection
1840 characters for tags have been configured, either through the variable
1841 `org-tag-alist' or through a #+TAGS line in the buffer.
1842 When t, fast selection is always used and selection keys are assigned
1843 automatically if necessary."
1844 :group 'org-tags
1845 :type '(choice
1846 (const :tag "Always" t)
1847 (const :tag "Never" nil)
1848 (const :tag "When selection characters are configured" 'auto)))
1849
1850 (defcustom org-fast-tag-selection-single-key nil
1851 "Non-nil means, fast tag selection exits after first change.
1852 When nil, you have to press RET to exit it.
1853 During fast tag selection, you can toggle this flag with `C-c'.
1854 This variable can also have the value `expert'. In this case, the window
1855 displaying the tags menu is not even shown, until you press C-c again."
1856 :group 'org-tags
1857 :type '(choice
1858 (const :tag "No" nil)
1859 (const :tag "Yes" t)
1860 (const :tag "Expert" expert)))
1861
1862 (defvar org-fast-tag-selection-include-todo nil
1863 "Non-nil means, fast tags selection interface will also offer TODO states.
1864 This is an undocumented feature, you should not rely on it.")
1865
1866 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1867 "The column to which tags should be indented in a headline.
1868 If this number is positive, it specifies the column. If it is negative,
1869 it means that the tags should be flushright to that column. For example,
1870 -80 works well for a normal 80 character screen."
1871 :group 'org-tags
1872 :type 'integer)
1873
1874 (defcustom org-auto-align-tags t
1875 "Non-nil means, realign tags after pro/demotion of TODO state change.
1876 These operations change the length of a headline and therefore shift
1877 the tags around. With this options turned on, after each such operation
1878 the tags are again aligned to `org-tags-column'."
1879 :group 'org-tags
1880 :type 'boolean)
1881
1882 (defcustom org-use-tag-inheritance t
1883 "Non-nil means, tags in levels apply also for sublevels.
1884 When nil, only the tags directly given in a specific line apply there.
1885 This may also be a list of tags that should be inherited, or a regexp that
1886 matches tags that should be inherited. Additional control is possible
1887 with the variable `org-tags-exclude-from-inheritance' which gives an
1888 explicit list of tags to be excluded from inheritance., even if the value of
1889 `org-use-tag-inheritance' would select it for inheritance.
1890
1891 If this option is t, a match early-on in a tree can lead to a large
1892 number of matches in the subtree when constructing the agenda or creating
1893 a sparse tree. If you only want to see the first match in a tree during
1894 a search, check out the variable `org-tags-match-list-sublevels'."
1895 :group 'org-tags
1896 :type '(choice
1897 (const :tag "Not" nil)
1898 (const :tag "Always" t)
1899 (repeat :tag "Specific tags" (string :tag "Tag"))
1900 (regexp :tag "Tags matched by regexp")))
1901
1902 (defcustom org-tags-exclude-from-inheritance nil
1903 "List of tags that should never be inherited.
1904 This is a way to exclude a few tags from inheritance. For way to do
1905 the opposite, to actively allow inheritance for selected tags,
1906 see the variable `org-use-tag-inheritance'."
1907 :group 'org-tags
1908 :type '(repeat (string :tag "Tag")))
1909
1910 (defun org-tag-inherit-p (tag)
1911 "Check if TAG is one that should be inherited."
1912 (cond
1913 ((member tag org-tags-exclude-from-inheritance) nil)
1914 ((eq org-use-tag-inheritance t) t)
1915 ((not org-use-tag-inheritance) nil)
1916 ((stringp org-use-tag-inheritance)
1917 (string-match org-use-tag-inheritance tag))
1918 ((listp org-use-tag-inheritance)
1919 (member tag org-use-tag-inheritance))
1920 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1921
1922 (defcustom org-tags-match-list-sublevels t
1923 "Non-nil means list also sublevels of headlines matching tag search.
1924 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1925 the sublevels of a headline matching a tag search often also match
1926 the same search. Listing all of them can create very long lists.
1927 Setting this variable to nil causes subtrees of a match to be skipped.
1928 This option is off by default, because inheritance in on. If you turn
1929 inheritance off, you very likely want to turn this option on.
1930
1931 As a special case, if the tag search is restricted to TODO items, the
1932 value of this variable is ignored and sublevels are always checked, to
1933 make sure all corresponding TODO items find their way into the list.
1934
1935 This variable is semi-obsolete and probably should always be true. It
1936 is better to limit inheritance to certain tags using the variables
1937 `org-use-tag-inheritanc'e and `org-tags-exclude-from-inheritance'."
1938 :group 'org-tags
1939 :type 'boolean)
1940
1941 (defvar org-tags-history nil
1942 "History of minibuffer reads for tags.")
1943 (defvar org-last-tags-completion-table nil
1944 "The last used completion table for tags.")
1945 (defvar org-after-tags-change-hook nil
1946 "Hook that is run after the tags in a line have changed.")
1947
1948 (defgroup org-properties nil
1949 "Options concerning properties in Org-mode."
1950 :tag "Org Properties"
1951 :group 'org)
1952
1953 (defcustom org-property-format "%-10s %s"
1954 "How property key/value pairs should be formatted by `indent-line'.
1955 When `indent-line' hits a property definition, it will format the line
1956 according to this format, mainly to make sure that the values are
1957 lined-up with respect to each other."
1958 :group 'org-properties
1959 :type 'string)
1960
1961 (defcustom org-use-property-inheritance nil
1962 "Non-nil means, properties apply also for sublevels.
1963
1964 This setting is chiefly used during property searches. Turning it on can
1965 cause significant overhead when doing a search, which is why it is not
1966 on by default.
1967
1968 When nil, only the properties directly given in the current entry count.
1969 When t, every property is inherited. The value may also be a list of
1970 properties that should have inheritance, or a regular expression matching
1971 properties that should be inherited.
1972
1973 However, note that some special properties use inheritance under special
1974 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1975 and the properties ending in \"_ALL\" when they are used as descriptor
1976 for valid values of a property.
1977
1978 Note for programmers:
1979 When querying an entry with `org-entry-get', you can control if inheritance
1980 should be used. By default, `org-entry-get' looks only at the local
1981 properties. You can request inheritance by setting the inherit argument
1982 to t (to force inheritance) or to `selective' (to respect the setting
1983 in this variable)."
1984 :group 'org-properties
1985 :type '(choice
1986 (const :tag "Not" nil)
1987 (const :tag "Always" t)
1988 (repeat :tag "Specific properties" (string :tag "Property"))
1989 (regexp :tag "Properties matched by regexp")))
1990
1991 (defun org-property-inherit-p (property)
1992 "Check if PROPERTY is one that should be inherited."
1993 (cond
1994 ((eq org-use-property-inheritance t) t)
1995 ((not org-use-property-inheritance) nil)
1996 ((stringp org-use-property-inheritance)
1997 (string-match org-use-property-inheritance property))
1998 ((listp org-use-property-inheritance)
1999 (member property org-use-property-inheritance))
2000 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2001
2002 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2003 "The default column format, if no other format has been defined.
2004 This variable can be set on the per-file basis by inserting a line
2005
2006 #+COLUMNS: %25ITEM ....."
2007 :group 'org-properties
2008 :type 'string)
2009
2010 (defcustom org-columns-ellipses ".."
2011 "The ellipses to be used when a field in column view is truncated.
2012 When this is the empty string, as many characters as possible are shown,
2013 but then there will be no visual indication that the field has been truncated.
2014 When this is a string of length N, the last N characters of a truncated
2015 field are replaced by this string. If the column is narrower than the
2016 ellipses string, only part of the ellipses string will be shown."
2017 :group 'org-properties
2018 :type 'string)
2019
2020 (defcustom org-columns-modify-value-for-display-function nil
2021 "Function that modifies values for display in column view.
2022 For example, it can be used to cut out a certain part from a time stamp.
2023 The function must take 2 arguments:
2024
2025 column-title The tite of the column (*not* the property name)
2026 value The value that should be modified.
2027
2028 The function should return the value that should be displayed,
2029 or nil if the normal value should be used."
2030 :group 'org-properties
2031 :type 'function)
2032
2033 (defcustom org-effort-property "Effort"
2034 "The property that is being used to keep track of effort estimates.
2035 Effort estimates given in this property need to have the format H:MM."
2036 :group 'org-properties
2037 :group 'org-progress
2038 :type '(string :tag "Property"))
2039
2040 (defconst org-global-properties-fixed
2041 '(("VISIBILITY_ALL" . "folded children content all"))
2042 "List of property/value pairs that can be inherited by any entry.
2043 These are fixed values, for the preset properties.")
2044
2045
2046 (defcustom org-global-properties nil
2047 "List of property/value pairs that can be inherited by any entry.
2048 You can set buffer-local values for the same purpose in the variable
2049 `org-file-properties' this by adding lines like
2050
2051 #+PROPERTY: NAME VALUE"
2052 :group 'org-properties
2053 :type '(repeat
2054 (cons (string :tag "Property")
2055 (string :tag "Value"))))
2056
2057 (defvar org-file-properties nil
2058 "List of property/value pairs that can be inherited by any entry.
2059 Valid for the current buffer.
2060 This variable is populated from #+PROPERTY lines.")
2061 (make-variable-buffer-local 'org-file-properties)
2062
2063 (defgroup org-agenda nil
2064 "Options concerning agenda views in Org-mode."
2065 :tag "Org Agenda"
2066 :group 'org)
2067
2068 (defvar org-category nil
2069 "Variable used by org files to set a category for agenda display.
2070 Such files should use a file variable to set it, for example
2071
2072 # -*- mode: org; org-category: \"ELisp\"
2073
2074 or contain a special line
2075
2076 #+CATEGORY: ELisp
2077
2078 If the file does not specify a category, then file's base name
2079 is used instead.")
2080 (make-variable-buffer-local 'org-category)
2081 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2082
2083 (defcustom org-agenda-files nil
2084 "The files to be used for agenda display.
2085 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2086 \\[org-remove-file]. You can also use customize to edit the list.
2087
2088 If an entry is a directory, all files in that directory that are matched by
2089 `org-agenda-file-regexp' will be part of the file list.
2090
2091 If the value of the variable is not a list but a single file name, then
2092 the list of agenda files is actually stored and maintained in that file, one
2093 agenda file per line."
2094 :group 'org-agenda
2095 :type '(choice
2096 (repeat :tag "List of files and directories" file)
2097 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2098
2099 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2100 "Regular expression to match files for `org-agenda-files'.
2101 If any element in the list in that variable contains a directory instead
2102 of a normal file, all files in that directory that are matched by this
2103 regular expression will be included."
2104 :group 'org-agenda
2105 :type 'regexp)
2106
2107 (defcustom org-agenda-text-search-extra-files nil
2108 "List of extra files to be searched by text search commands.
2109 These files will be search in addition to the agenda files by the
2110 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2111 Note that these files will only be searched for text search commands,
2112 not for the other agenda views like todo lists, tag searches or the weekly
2113 agenda. This variable is intended to list notes and possibly archive files
2114 that should also be searched by these two commands.
2115 In fact, if the first element in the list is the symbol `agenda-archives',
2116 than all archive files of all agenda files will be added to the search
2117 scope."
2118 :group 'org-agenda
2119 :type '(set :greedy t
2120 (const :tag "Agenda Archives" agenda-archives)
2121 (repeat :inline t (file))))
2122
2123 (if (fboundp 'defvaralias)
2124 (defvaralias 'org-agenda-multi-occur-extra-files
2125 'org-agenda-text-search-extra-files))
2126
2127 (defcustom org-agenda-skip-unavailable-files nil
2128 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2129 A nil value means to remove them, after a query, from the list."
2130 :group 'org-agenda
2131 :type 'boolean)
2132
2133 (defcustom org-calendar-to-agenda-key [?c]
2134 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2135 The command `org-calendar-goto-agenda' will be bound to this key. The
2136 default is the character `c' because then `c' can be used to switch back and
2137 forth between agenda and calendar."
2138 :group 'org-agenda
2139 :type 'sexp)
2140
2141 (defcustom org-calendar-agenda-action-key [?k]
2142 "The key to be installed in `calendar-mode-map' for agenda-action.
2143 The command `org-agenda-action' will be bound to this key. The
2144 default is the character `k' because we use the same key in the agenda."
2145 :group 'org-agenda
2146 :type 'sexp)
2147
2148 (eval-after-load "calendar"
2149 '(progn
2150 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2151 'org-calendar-goto-agenda)
2152 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2153 'org-agenda-action)))
2154
2155 (defgroup org-latex nil
2156 "Options for embedding LaTeX code into Org-mode."
2157 :tag "Org LaTeX"
2158 :group 'org)
2159
2160 (defcustom org-format-latex-options
2161 '(:foreground default :background default :scale 1.0
2162 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2163 :matchers ("begin" "$" "$$" "\\(" "\\["))
2164 "Options for creating images from LaTeX fragments.
2165 This is a property list with the following properties:
2166 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2167 `default' means use the foreground of the default face.
2168 :background the background color, or \"Transparent\".
2169 `default' means use the background of the default face.
2170 :scale a scaling factor for the size of the images.
2171 :html-foreground, :html-background, :html-scale
2172 the same numbers for HTML export.
2173 :matchers a list indicating which matchers should be used to
2174 find LaTeX fragments. Valid members of this list are:
2175 \"begin\" find environments
2176 \"$\" find math expressions surrounded by $...$
2177 \"$$\" find math expressions surrounded by $$....$$
2178 \"\\(\" find math expressions surrounded by \\(...\\)
2179 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2180 :group 'org-latex
2181 :type 'plist)
2182
2183 (defcustom org-format-latex-header "\\documentclass{article}
2184 \\usepackage{fullpage} % do not remove
2185 \\usepackage{amssymb}
2186 \\usepackage[usenames]{color}
2187 \\usepackage{amsmath}
2188 \\usepackage{latexsym}
2189 \\usepackage[mathscr]{eucal}
2190 \\pagestyle{empty} % do not remove"
2191 "The document header used for processing LaTeX fragments."
2192 :group 'org-latex
2193 :type 'string)
2194
2195
2196 (defgroup org-font-lock nil
2197 "Font-lock settings for highlighting in Org-mode."
2198 :tag "Org Font Lock"
2199 :group 'org)
2200
2201 (defcustom org-level-color-stars-only nil
2202 "Non-nil means fontify only the stars in each headline.
2203 When nil, the entire headline is fontified.
2204 Changing it requires restart of `font-lock-mode' to become effective
2205 also in regions already fontified."
2206 :group 'org-font-lock
2207 :type 'boolean)
2208
2209 (defcustom org-hide-leading-stars nil
2210 "Non-nil means, hide the first N-1 stars in a headline.
2211 This works by using the face `org-hide' for these stars. This
2212 face is white for a light background, and black for a dark
2213 background. You may have to customize the face `org-hide' to
2214 make this work.
2215 Changing it requires restart of `font-lock-mode' to become effective
2216 also in regions already fontified.
2217 You may also set this on a per-file basis by adding one of the following
2218 lines to the buffer:
2219
2220 #+STARTUP: hidestars
2221 #+STARTUP: showstars"
2222 :group 'org-font-lock
2223 :type 'boolean)
2224
2225 (defcustom org-fontify-done-headline nil
2226 "Non-nil means, change the face of a headline if it is marked DONE.
2227 Normally, only the TODO/DONE keyword indicates the state of a headline.
2228 When this is non-nil, the headline after the keyword is set to the
2229 `org-headline-done' as an additional indication."
2230 :group 'org-font-lock
2231 :type 'boolean)
2232
2233 (defcustom org-fontify-emphasized-text t
2234 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2235 Changing this variable requires a restart of Emacs to take effect."
2236 :group 'org-font-lock
2237 :type 'boolean)
2238
2239 (defcustom org-highlight-latex-fragments-and-specials nil
2240 "Non-nil means, fontify what is treated specially by the exporters."
2241 :group 'org-font-lock
2242 :type 'boolean)
2243
2244 (defcustom org-hide-emphasis-markers nil
2245 "Non-nil mean font-lock should hide the emphasis marker characters."
2246 :group 'org-font-lock
2247 :type 'boolean)
2248
2249 (defvar org-emph-re nil
2250 "Regular expression for matching emphasis.")
2251 (defvar org-verbatim-re nil
2252 "Regular expression for matching verbatim text.")
2253 (defvar org-emphasis-regexp-components) ; defined just below
2254 (defvar org-emphasis-alist) ; defined just below
2255 (defun org-set-emph-re (var val)
2256 "Set variable and compute the emphasis regular expression."
2257 (set var val)
2258 (when (and (boundp 'org-emphasis-alist)
2259 (boundp 'org-emphasis-regexp-components)
2260 org-emphasis-alist org-emphasis-regexp-components)
2261 (let* ((e org-emphasis-regexp-components)
2262 (pre (car e))
2263 (post (nth 1 e))
2264 (border (nth 2 e))
2265 (body (nth 3 e))
2266 (nl (nth 4 e))
2267 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2268 (body1 (concat body "*?"))
2269 (markers (mapconcat 'car org-emphasis-alist ""))
2270 (vmarkers (mapconcat
2271 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2272 org-emphasis-alist "")))
2273 ;; make sure special characters appear at the right position in the class
2274 (if (string-match "\\^" markers)
2275 (setq markers (concat (replace-match "" t t markers) "^")))
2276 (if (string-match "-" markers)
2277 (setq markers (concat (replace-match "" t t markers) "-")))
2278 (if (string-match "\\^" vmarkers)
2279 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2280 (if (string-match "-" vmarkers)
2281 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2282 (if (> nl 0)
2283 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2284 (int-to-string nl) "\\}")))
2285 ;; Make the regexp
2286 (setq org-emph-re
2287 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2288 "\\("
2289 "\\([" markers "]\\)"
2290 "\\("
2291 "[^" border "]\\|"
2292 "[^" border (if (and nil stacked) markers) "]"
2293 body1
2294 "[^" border (if (and nil stacked) markers) "]"
2295 "\\)"
2296 "\\3\\)"
2297 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2298 (setq org-verbatim-re
2299 (concat "\\([" pre "]\\|^\\)"
2300 "\\("
2301 "\\([" vmarkers "]\\)"
2302 "\\("
2303 "[^" border "]\\|"
2304 "[^" border "]"
2305 body1
2306 "[^" border "]"
2307 "\\)"
2308 "\\3\\)"
2309 "\\([" post "]\\|$\\)")))))
2310
2311 (defcustom org-emphasis-regexp-components
2312 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2313 "Components used to build the regular expression for emphasis.
2314 This is a list with 6 entries. Terminology: In an emphasis string
2315 like \" *strong word* \", we call the initial space PREMATCH, the final
2316 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2317 and \"trong wor\" is the body. The different components in this variable
2318 specify what is allowed/forbidden in each part:
2319
2320 pre Chars allowed as prematch. Beginning of line will be allowed too.
2321 post Chars allowed as postmatch. End of line will be allowed too.
2322 border The chars *forbidden* as border characters.
2323 body-regexp A regexp like \".\" to match a body character. Don't use
2324 non-shy groups here, and don't allow newline here.
2325 newline The maximum number of newlines allowed in an emphasis exp.
2326
2327 Use customize to modify this, or restart Emacs after changing it."
2328 :group 'org-font-lock
2329 :set 'org-set-emph-re
2330 :type '(list
2331 (sexp :tag "Allowed chars in pre ")
2332 (sexp :tag "Allowed chars in post ")
2333 (sexp :tag "Forbidden chars in border ")
2334 (sexp :tag "Regexp for body ")
2335 (integer :tag "number of newlines allowed")
2336 (option (boolean :tag "Please ignore this button"))))
2337
2338 (defcustom org-emphasis-alist
2339 `(("*" bold "<b>" "</b>")
2340 ("/" italic "<i>" "</i>")
2341 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2342 ("=" org-code "<code>" "</code>" verbatim)
2343 ("~" org-verbatim "<code>" "</code>" verbatim)
2344 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2345 "<del>" "</del>")
2346 )
2347 "Special syntax for emphasized text.
2348 Text starting and ending with a special character will be emphasized, for
2349 example *bold*, _underlined_ and /italic/. This variable sets the marker
2350 characters, the face to be used by font-lock for highlighting in Org-mode
2351 Emacs buffers, and the HTML tags to be used for this.
2352 Use customize to modify this, or restart Emacs after changing it."
2353 :group 'org-font-lock
2354 :set 'org-set-emph-re
2355 :type '(repeat
2356 (list
2357 (string :tag "Marker character")
2358 (choice
2359 (face :tag "Font-lock-face")
2360 (plist :tag "Face property list"))
2361 (string :tag "HTML start tag")
2362 (string :tag "HTML end tag")
2363 (option (const verbatim)))))
2364
2365 ;;; Miscellaneous options
2366
2367 (defgroup org-completion nil
2368 "Completion in Org-mode."
2369 :tag "Org Completion"
2370 :group 'org)
2371
2372 (defcustom org-completion-use-ido nil
2373 "Non-nil means, use ido completion wherever possible."
2374 :group 'org-completion
2375 :type 'boolean)
2376
2377 (defcustom org-completion-fallback-command 'hippie-expand
2378 "The expansion command called by \\[org-complete] in normal context.
2379 Normal means, no org-mode-specific context."
2380 :group 'org-completion
2381 :type 'function)
2382
2383 ;;; Functions and variables from ther packages
2384 ;; Declared here to avoid compiler warnings
2385
2386 ;; XEmacs only
2387 (defvar outline-mode-menu-heading)
2388 (defvar outline-mode-menu-show)
2389 (defvar outline-mode-menu-hide)
2390 (defvar zmacs-regions) ; XEmacs regions
2391
2392 ;; Emacs only
2393 (defvar mark-active)
2394
2395 ;; Various packages
2396 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2397 (declare-function calendar-forward-day "cal-move" (arg))
2398 (declare-function calendar-goto-date "cal-move" (date))
2399 (declare-function calendar-goto-today "cal-move" ())
2400 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2401 (defvar calc-embedded-close-formula)
2402 (defvar calc-embedded-open-formula)
2403 (declare-function cdlatex-tab "ext:cdlatex" ())
2404 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2405 (defvar font-lock-unfontify-region-function)
2406 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2407 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2408 (defvar iswitchb-temp-buflist)
2409 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2410 (declare-function org-agenda-skip "org-agenda" ())
2411 (declare-function org-format-agenda-item "org-agenda"
2412 (extra txt &optional category tags dotime noprefix remove-re))
2413 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2414 (declare-function org-agenda-change-all-lines "org-agenda"
2415 (newhead hdmarker &optional fixface just-this))
2416 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2417 (declare-function org-agenda-maybe-redo "org-agenda" ())
2418 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2419 (beg end))
2420 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2421 (declare-function parse-time-string "parse-time" (string))
2422 (declare-function remember "remember" (&optional initial))
2423 (declare-function remember-buffer-desc "remember" ())
2424 (declare-function remember-finalize "remember" ())
2425 (defvar remember-save-after-remembering)
2426 (defvar remember-data-file)
2427 (defvar remember-register)
2428 (defvar remember-buffer)
2429 (defvar remember-handler-functions)
2430 (defvar remember-annotation-functions)
2431 (defvar texmathp-why)
2432 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2433 (declare-function table--at-cell-p "table" (position &optional object at-column))
2434
2435 (defvar w3m-current-url)
2436 (defvar w3m-current-title)
2437
2438 (defvar org-latex-regexps)
2439
2440 ;;; Autoload and prepare some org modules
2441
2442 ;; Some table stuff that needs to be defined here, because it is used
2443 ;; by the functions setting up org-mode or checking for table context.
2444
2445 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2446 "Detects an org-type or table-type table.")
2447 (defconst org-table-line-regexp "^[ \t]*|"
2448 "Detects an org-type table line.")
2449 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2450 "Detects an org-type table line.")
2451 (defconst org-table-hline-regexp "^[ \t]*|-"
2452 "Detects an org-type table hline.")
2453 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2454 "Detects a table-type table hline.")
2455 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2456 "Searching from within a table (any type) this finds the first line
2457 outside the table.")
2458
2459 ;; Autoload the functions in org-table.el that are needed by functions here.
2460
2461 (eval-and-compile
2462 (org-autoload "org-table"
2463 '(org-table-align org-table-begin org-table-blank-field
2464 org-table-convert org-table-convert-region org-table-copy-down
2465 org-table-copy-region org-table-create
2466 org-table-create-or-convert-from-region
2467 org-table-create-with-table.el org-table-current-dline
2468 org-table-cut-region org-table-delete-column org-table-edit-field
2469 org-table-edit-formulas org-table-end org-table-eval-formula
2470 org-table-export org-table-field-info
2471 org-table-get-stored-formulas org-table-goto-column
2472 org-table-hline-and-move org-table-import org-table-insert-column
2473 org-table-insert-hline org-table-insert-row org-table-iterate
2474 org-table-justify-field-maybe org-table-kill-row
2475 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2476 org-table-move-column org-table-move-column-left
2477 org-table-move-column-right org-table-move-row
2478 org-table-move-row-down org-table-move-row-up
2479 org-table-next-field org-table-next-row org-table-paste-rectangle
2480 org-table-previous-field org-table-recalculate
2481 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2482 org-table-toggle-coordinate-overlays
2483 org-table-toggle-formula-debugger org-table-wrap-region
2484 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2485
2486 (defun org-at-table-p (&optional table-type)
2487 "Return t if the cursor is inside an org-type table.
2488 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2489 (if org-enable-table-editor
2490 (save-excursion
2491 (beginning-of-line 1)
2492 (looking-at (if table-type org-table-any-line-regexp
2493 org-table-line-regexp)))
2494 nil))
2495 (defsubst org-table-p () (org-at-table-p))
2496
2497 (defun org-at-table.el-p ()
2498 "Return t if and only if we are at a table.el table."
2499 (and (org-at-table-p 'any)
2500 (save-excursion
2501 (goto-char (org-table-begin 'any))
2502 (looking-at org-table1-hline-regexp))))
2503 (defun org-table-recognize-table.el ()
2504 "If there is a table.el table nearby, recognize it and move into it."
2505 (if org-table-tab-recognizes-table.el
2506 (if (org-at-table.el-p)
2507 (progn
2508 (beginning-of-line 1)
2509 (if (looking-at org-table-dataline-regexp)
2510 nil
2511 (if (looking-at org-table1-hline-regexp)
2512 (progn
2513 (beginning-of-line 2)
2514 (if (looking-at org-table-any-border-regexp)
2515 (beginning-of-line -1)))))
2516 (if (re-search-forward "|" (org-table-end t) t)
2517 (progn
2518 (require 'table)
2519 (if (table--at-cell-p (point))
2520 t
2521 (message "recognizing table.el table...")
2522 (table-recognize-table)
2523 (message "recognizing table.el table...done")))
2524 (error "This should not happen..."))
2525 t)
2526 nil)
2527 nil))
2528
2529 (defun org-at-table-hline-p ()
2530 "Return t if the cursor is inside a hline in a table."
2531 (if org-enable-table-editor
2532 (save-excursion
2533 (beginning-of-line 1)
2534 (looking-at org-table-hline-regexp))
2535 nil))
2536
2537 (defvar org-table-clean-did-remove-column nil)
2538
2539 (defun org-table-map-tables (function)
2540 "Apply FUNCTION to the start of all tables in the buffer."
2541 (save-excursion
2542 (save-restriction
2543 (widen)
2544 (goto-char (point-min))
2545 (while (re-search-forward org-table-any-line-regexp nil t)
2546 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2547 (beginning-of-line 1)
2548 (if (looking-at org-table-line-regexp)
2549 (save-excursion (funcall function)))
2550 (re-search-forward org-table-any-border-regexp nil 1))))
2551 (message "Mapping tables: done"))
2552
2553 ;; Declare and autoload functions from org-exp.el
2554
2555 (declare-function org-default-export-plist "org-exp")
2556 (declare-function org-infile-export-plist "org-exp")
2557 (declare-function org-get-current-options "org-exp")
2558 (eval-and-compile
2559 (org-autoload "org-exp"
2560 '(org-export org-export-as-ascii org-export-visible
2561 org-insert-export-options-template org-export-as-html-and-open
2562 org-export-as-html-batch org-export-as-html-to-buffer
2563 org-replace-region-by-html org-export-region-as-html
2564 org-export-as-html org-export-icalendar-this-file
2565 org-export-icalendar-all-agenda-files
2566 org-table-clean-before-export
2567 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2568
2569 ;; Declare and autoload functions from org-agenda.el
2570
2571 (eval-and-compile
2572 (org-autoload "org-agenda"
2573 '(org-agenda org-agenda-list org-search-view
2574 org-todo-list org-tags-view org-agenda-list-stuck-projects
2575 org-diary org-agenda-to-appt)))
2576
2577 ;; Autoload org-remember
2578
2579 (eval-and-compile
2580 (org-autoload "org-remember"
2581 '(org-remember-insinuate org-remember-annotation
2582 org-remember-apply-template org-remember org-remember-handler)))
2583
2584 ;; Autoload org-clock.el
2585
2586
2587 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2588 (beg end))
2589 (declare-function org-update-mode-line "org-clock" ())
2590 (defvar org-clock-start-time)
2591 (defvar org-clock-marker (make-marker)
2592 "Marker recording the last clock-in.")
2593
2594 (eval-and-compile
2595 (org-autoload
2596 "org-clock"
2597 '(org-clock-in org-clock-out org-clock-cancel
2598 org-clock-goto org-clock-sum org-clock-display
2599 org-remove-clock-overlays org-clock-report
2600 org-clocktable-shift org-dblock-write:clocktable
2601 org-get-clocktable)))
2602
2603 (defun org-clock-update-time-maybe ()
2604 "If this is a CLOCK line, update it and return t.
2605 Otherwise, return nil."
2606 (interactive)
2607 (save-excursion
2608 (beginning-of-line 1)
2609 (skip-chars-forward " \t")
2610 (when (looking-at org-clock-string)
2611 (let ((re (concat "[ \t]*" org-clock-string
2612 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2613 "\\([ \t]*=>.*\\)?\\)?"))
2614 ts te h m s neg)
2615 (cond
2616 ((not (looking-at re))
2617 nil)
2618 ((not (match-end 2))
2619 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2620 (> org-clock-marker (point))
2621 (<= org-clock-marker (point-at-eol)))
2622 ;; The clock is running here
2623 (setq org-clock-start-time
2624 (apply 'encode-time
2625 (org-parse-time-string (match-string 1))))
2626 (org-update-mode-line)))
2627 (t
2628 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2629 (end-of-line 1)
2630 (setq ts (match-string 1)
2631 te (match-string 3))
2632 (setq s (- (time-to-seconds
2633 (apply 'encode-time (org-parse-time-string te)))
2634 (time-to-seconds
2635 (apply 'encode-time (org-parse-time-string ts))))
2636 neg (< s 0)
2637 s (abs s)
2638 h (floor (/ s 3600))
2639 s (- s (* 3600 h))
2640 m (floor (/ s 60))
2641 s (- s (* 60 s)))
2642 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2643 t))))))
2644
2645 (defun org-check-running-clock ()
2646 "Check if the current buffer contains the running clock.
2647 If yes, offer to stop it and to save the buffer with the changes."
2648 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2649 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2650 (buffer-name))))
2651 (org-clock-out)
2652 (when (y-or-n-p "Save changed buffer?")
2653 (save-buffer))))
2654
2655 (defun org-clocktable-try-shift (dir n)
2656 "Check if this line starts a clock table, if yes, shift the time block."
2657 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2658 (org-clocktable-shift dir n)))
2659
2660 ;; Autoload org-timer.el
2661
2662 ;(declare-function org-timer "org-timer")
2663
2664 (eval-and-compile
2665 (org-autoload
2666 "org-timer"
2667 '(org-timer-start org-timer org-timer-item
2668 org-timer-change-times-in-region)))
2669
2670
2671 ;; Autoload archiving code
2672 ;; The stuff that is needed for cycling and tags has to be defined here.
2673
2674 (defgroup org-archive nil
2675 "Options concerning archiving in Org-mode."
2676 :tag "Org Archive"
2677 :group 'org-structure)
2678
2679 (defcustom org-archive-location "%s_archive::"
2680 "The location where subtrees should be archived.
2681
2682 The value of this variable is a string, consisting of two parts,
2683 separated by a double-colon. The first part is a filename and
2684 the second part is a headline.
2685
2686 When the filename is omitted, archiving happens in the same file.
2687 %s in the filename will be replaced by the current file
2688 name (without the directory part). Archiving to a different file
2689 is useful to keep archived entries from contributing to the
2690 Org-mode Agenda.
2691
2692 The archived entries will be filed as subtrees of the specified
2693 headline. When the headline is omitted, the subtrees are simply
2694 filed away at the end of the file, as top-level entries.
2695
2696 Here are a few examples:
2697 \"%s_archive::\"
2698 If the current file is Projects.org, archive in file
2699 Projects.org_archive, as top-level trees. This is the default.
2700
2701 \"::* Archived Tasks\"
2702 Archive in the current file, under the top-level headline
2703 \"* Archived Tasks\".
2704
2705 \"~/org/archive.org::\"
2706 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2707
2708 \"basement::** Finished Tasks\"
2709 Archive in file ./basement (relative path), as level 3 trees
2710 below the level 2 heading \"** Finished Tasks\".
2711
2712 You may set this option on a per-file basis by adding to the buffer a
2713 line like
2714
2715 #+ARCHIVE: basement::** Finished Tasks
2716
2717 You may also define it locally for a subtree by setting an ARCHIVE property
2718 in the entry. If such a property is found in an entry, or anywhere up
2719 the hierarchy, it will be used."
2720 :group 'org-archive
2721 :type 'string)
2722
2723 (defcustom org-archive-tag "ARCHIVE"
2724 "The tag that marks a subtree as archived.
2725 An archived subtree does not open during visibility cycling, and does
2726 not contribute to the agenda listings.
2727 After changing this, font-lock must be restarted in the relevant buffers to
2728 get the proper fontification."
2729 :group 'org-archive
2730 :group 'org-keywords
2731 :type 'string)
2732
2733 (defcustom org-agenda-skip-archived-trees t
2734 "Non-nil means, the agenda will skip any items located in archived trees.
2735 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2736 variable is no longer recommended, you should leave it at the value t.
2737 Instead, use the key `v' to cycle the archives-mode in the agenda."
2738 :group 'org-archive
2739 :group 'org-agenda-skip
2740 :type 'boolean)
2741
2742 (defcustom org-cycle-open-archived-trees nil
2743 "Non-nil means, `org-cycle' will open archived trees.
2744 An archived tree is a tree marked with the tag ARCHIVE.
2745 When nil, archived trees will stay folded. You can still open them with
2746 normal outline commands like `show-all', but not with the cycling commands."
2747 :group 'org-archive
2748 :group 'org-cycle
2749 :type 'boolean)
2750
2751 (defcustom org-sparse-tree-open-archived-trees nil
2752 "Non-nil means sparse tree construction shows matches in archived trees.
2753 When nil, matches in these trees are highlighted, but the trees are kept in
2754 collapsed state."
2755 :group 'org-archive
2756 :group 'org-sparse-trees
2757 :type 'boolean)
2758
2759 (defun org-cycle-hide-archived-subtrees (state)
2760 "Re-hide all archived subtrees after a visibility state change."
2761 (when (and (not org-cycle-open-archived-trees)
2762 (not (memq state '(overview folded))))
2763 (save-excursion
2764 (let* ((globalp (memq state '(contents all)))
2765 (beg (if globalp (point-min) (point)))
2766 (end (if globalp (point-max) (org-end-of-subtree t))))
2767 (org-hide-archived-subtrees beg end)
2768 (goto-char beg)
2769 (if (looking-at (concat ".*:" org-archive-tag ":"))
2770 (message "%s" (substitute-command-keys
2771 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2772
2773 (defun org-force-cycle-archived ()
2774 "Cycle subtree even if it is archived."
2775 (interactive)
2776 (setq this-command 'org-cycle)
2777 (let ((org-cycle-open-archived-trees t))
2778 (call-interactively 'org-cycle)))
2779
2780 (defun org-hide-archived-subtrees (beg end)
2781 "Re-hide all archived subtrees after a visibility state change."
2782 (save-excursion
2783 (let* ((re (concat ":" org-archive-tag ":")))
2784 (goto-char beg)
2785 (while (re-search-forward re end t)
2786 (and (org-on-heading-p) (hide-subtree))
2787 (org-end-of-subtree t)))))
2788
2789 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2790
2791 (eval-and-compile
2792 (org-autoload "org-archive"
2793 '(org-add-archive-files org-archive-subtree
2794 org-archive-to-archive-sibling org-toggle-archive-tag)))
2795
2796 ;; Autoload Column View Code
2797
2798 (declare-function org-columns-number-to-string "org-colview")
2799 (declare-function org-columns-get-format-and-top-level "org-colview")
2800 (declare-function org-columns-compute "org-colview")
2801
2802 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2803 '(org-columns-number-to-string org-columns-get-format-and-top-level
2804 org-columns-compute org-agenda-columns org-columns-remove-overlays
2805 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2806
2807 ;; Autoload ID code
2808
2809 (org-autoload "org-id"
2810 '(org-id-get-create org-id-new org-id-copy org-id-get
2811 org-id-get-with-outline-path-completion
2812 org-id-get-with-outline-drilling
2813 org-id-goto org-id-find))
2814
2815 ;;; Variables for pre-computed regular expressions, all buffer local
2816
2817 (defvar org-drawer-regexp nil
2818 "Matches first line of a hidden block.")
2819 (make-variable-buffer-local 'org-drawer-regexp)
2820 (defvar org-todo-regexp nil
2821 "Matches any of the TODO state keywords.")
2822 (make-variable-buffer-local 'org-todo-regexp)
2823 (defvar org-not-done-regexp nil
2824 "Matches any of the TODO state keywords except the last one.")
2825 (make-variable-buffer-local 'org-not-done-regexp)
2826 (defvar org-todo-line-regexp nil
2827 "Matches a headline and puts TODO state into group 2 if present.")
2828 (make-variable-buffer-local 'org-todo-line-regexp)
2829 (defvar org-complex-heading-regexp nil
2830 "Matches a headline and puts everything into groups:
2831 group 1: the stars
2832 group 2: The todo keyword, maybe
2833 group 3: Priority cookie
2834 group 4: True headline
2835 group 5: Tags")
2836 (make-variable-buffer-local 'org-complex-heading-regexp)
2837 (defvar org-todo-line-tags-regexp nil
2838 "Matches a headline and puts TODO state into group 2 if present.
2839 Also put tags into group 4 if tags are present.")
2840 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2841 (defvar org-nl-done-regexp nil
2842 "Matches newline followed by a headline with the DONE keyword.")
2843 (make-variable-buffer-local 'org-nl-done-regexp)
2844 (defvar org-looking-at-done-regexp nil
2845 "Matches the DONE keyword a point.")
2846 (make-variable-buffer-local 'org-looking-at-done-regexp)
2847 (defvar org-ds-keyword-length 12
2848 "Maximum length of the Deadline and SCHEDULED keywords.")
2849 (make-variable-buffer-local 'org-ds-keyword-length)
2850 (defvar org-deadline-regexp nil
2851 "Matches the DEADLINE keyword.")
2852 (make-variable-buffer-local 'org-deadline-regexp)
2853 (defvar org-deadline-time-regexp nil
2854 "Matches the DEADLINE keyword together with a time stamp.")
2855 (make-variable-buffer-local 'org-deadline-time-regexp)
2856 (defvar org-deadline-line-regexp nil
2857 "Matches the DEADLINE keyword and the rest of the line.")
2858 (make-variable-buffer-local 'org-deadline-line-regexp)
2859 (defvar org-scheduled-regexp nil
2860 "Matches the SCHEDULED keyword.")
2861 (make-variable-buffer-local 'org-scheduled-regexp)
2862 (defvar org-scheduled-time-regexp nil
2863 "Matches the SCHEDULED keyword together with a time stamp.")
2864 (make-variable-buffer-local 'org-scheduled-time-regexp)
2865 (defvar org-closed-time-regexp nil
2866 "Matches the CLOSED keyword together with a time stamp.")
2867 (make-variable-buffer-local 'org-closed-time-regexp)
2868
2869 (defvar org-keyword-time-regexp nil
2870 "Matches any of the 4 keywords, together with the time stamp.")
2871 (make-variable-buffer-local 'org-keyword-time-regexp)
2872 (defvar org-keyword-time-not-clock-regexp nil
2873 "Matches any of the 3 keywords, together with the time stamp.")
2874 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2875 (defvar org-maybe-keyword-time-regexp nil
2876 "Matches a timestamp, possibly preceeded by a keyword.")
2877 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2878 (defvar org-planning-or-clock-line-re nil
2879 "Matches a line with planning or clock info.")
2880 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2881
2882 (defconst org-plain-time-of-day-regexp
2883 (concat
2884 "\\(\\<[012]?[0-9]"
2885 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2886 "\\(--?"
2887 "\\(\\<[012]?[0-9]"
2888 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2889 "\\)?")
2890 "Regular expression to match a plain time or time range.
2891 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2892 groups carry important information:
2893 0 the full match
2894 1 the first time, range or not
2895 8 the second time, if it is a range.")
2896
2897 (defconst org-plain-time-extension-regexp
2898 (concat
2899 "\\(\\<[012]?[0-9]"
2900 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2901 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2902 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2903 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2904 groups carry important information:
2905 0 the full match
2906 7 hours of duration
2907 9 minutes of duration")
2908
2909 (defconst org-stamp-time-of-day-regexp
2910 (concat
2911 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2912 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2913 "\\(--?"
2914 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2915 "Regular expression to match a timestamp time or time range.
2916 After a match, the following groups carry important information:
2917 0 the full match
2918 1 date plus weekday, for backreferencing to make sure both times on same day
2919 2 the first time, range or not
2920 4 the second time, if it is a range.")
2921
2922 (defconst org-startup-options
2923 '(("fold" org-startup-folded t)
2924 ("overview" org-startup-folded t)
2925 ("nofold" org-startup-folded nil)
2926 ("showall" org-startup-folded nil)
2927 ("content" org-startup-folded content)
2928 ("hidestars" org-hide-leading-stars t)
2929 ("showstars" org-hide-leading-stars nil)
2930 ("odd" org-odd-levels-only t)
2931 ("oddeven" org-odd-levels-only nil)
2932 ("align" org-startup-align-all-tables t)
2933 ("noalign" org-startup-align-all-tables nil)
2934 ("customtime" org-display-custom-times t)
2935 ("logdone" org-log-done time)
2936 ("lognotedone" org-log-done note)
2937 ("nologdone" org-log-done nil)
2938 ("lognoteclock-out" org-log-note-clock-out t)
2939 ("nolognoteclock-out" org-log-note-clock-out nil)
2940 ("logrepeat" org-log-repeat state)
2941 ("lognoterepeat" org-log-repeat note)
2942 ("nologrepeat" org-log-repeat nil)
2943 ("constcgs" constants-unit-system cgs)
2944 ("constSI" constants-unit-system SI))
2945 "Variable associated with STARTUP options for org-mode.
2946 Each element is a list of three items: The startup options as written
2947 in the #+STARTUP line, the corresponding variable, and the value to
2948 set this variable to if the option is found. An optional forth element PUSH
2949 means to push this value onto the list in the variable.")
2950
2951 (defun org-set-regexps-and-options ()
2952 "Precompute regular expressions for current buffer."
2953 (when (org-mode-p)
2954 (org-set-local 'org-todo-kwd-alist nil)
2955 (org-set-local 'org-todo-key-alist nil)
2956 (org-set-local 'org-todo-key-trigger nil)
2957 (org-set-local 'org-todo-keywords-1 nil)
2958 (org-set-local 'org-done-keywords nil)
2959 (org-set-local 'org-todo-heads nil)
2960 (org-set-local 'org-todo-sets nil)
2961 (org-set-local 'org-todo-log-states nil)
2962 (org-set-local 'org-file-properties nil)
2963 (org-set-local 'org-file-tags nil)
2964 (let ((re (org-make-options-regexp
2965 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2966 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2967 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2968 (splitre "[ \t]+")
2969 kwds kws0 kwsa key log value cat arch tags const links hw dws
2970 tail sep kws1 prio props ftags drawers
2971 ext-setup-or-nil setup-contents (start 0))
2972 (save-excursion
2973 (save-restriction
2974 (widen)
2975 (goto-char (point-min))
2976 (while (or (and ext-setup-or-nil
2977 (string-match re ext-setup-or-nil start)
2978 (setq start (match-end 0)))
2979 (and (setq ext-setup-or-nil nil start 0)
2980 (re-search-forward re nil t)))
2981 (setq key (upcase (match-string 1 ext-setup-or-nil))
2982 value (org-match-string-no-properties 2 ext-setup-or-nil))
2983 (cond
2984 ((equal key "CATEGORY")
2985 (if (string-match "[ \t]+$" value)
2986 (setq value (replace-match "" t t value)))
2987 (setq cat value))
2988 ((member key '("SEQ_TODO" "TODO"))
2989 (push (cons 'sequence (org-split-string value splitre)) kwds))
2990 ((equal key "TYP_TODO")
2991 (push (cons 'type (org-split-string value splitre)) kwds))
2992 ((equal key "TAGS")
2993 (setq tags (append tags (org-split-string value splitre))))
2994 ((equal key "COLUMNS")
2995 (org-set-local 'org-columns-default-format value))
2996 ((equal key "LINK")
2997 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2998 (push (cons (match-string 1 value)
2999 (org-trim (match-string 2 value)))
3000 links)))
3001 ((equal key "PRIORITIES")
3002 (setq prio (org-split-string value " +")))
3003 ((equal key "PROPERTY")
3004 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3005 (push (cons (match-string 1 value) (match-string 2 value))
3006 props)))
3007 ((equal key "FILETAGS")
3008 (when (string-match "\\S-" value)
3009 (setq ftags
3010 (append
3011 ftags
3012 (apply 'append
3013 (mapcar (lambda (x) (org-split-string x ":"))
3014 (org-split-string value)))))))
3015 ((equal key "DRAWERS")
3016 (setq drawers (org-split-string value splitre)))
3017 ((equal key "CONSTANTS")
3018 (setq const (append const (org-split-string value splitre))))
3019 ((equal key "STARTUP")
3020 (let ((opts (org-split-string value splitre))
3021 l var val)
3022 (while (setq l (pop opts))
3023 (when (setq l (assoc l org-startup-options))
3024 (setq var (nth 1 l) val (nth 2 l))
3025 (if (not (nth 3 l))
3026 (set (make-local-variable var) val)
3027 (if (not (listp (symbol-value var)))
3028 (set (make-local-variable var) nil))
3029 (set (make-local-variable var) (symbol-value var))
3030 (add-to-list var val))))))
3031 ((equal key "ARCHIVE")
3032 (string-match " *$" value)
3033 (setq arch (replace-match "" t t value))
3034 (remove-text-properties 0 (length arch)
3035 '(face t fontified t) arch))
3036 ((equal key "SETUPFILE")
3037 (setq setup-contents (org-file-contents
3038 (expand-file-name
3039 (org-remove-double-quotes value))
3040 'noerror))
3041 (if (not ext-setup-or-nil)
3042 (setq ext-setup-or-nil setup-contents start 0)
3043 (setq ext-setup-or-nil
3044 (concat (substring ext-setup-or-nil 0 start)
3045 "\n" setup-contents "\n"
3046 (substring ext-setup-or-nil start)))))
3047 ))))
3048 (when cat
3049 (org-set-local 'org-category (intern cat))
3050 (push (cons "CATEGORY" cat) props))
3051 (when prio
3052 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3053 (setq prio (mapcar 'string-to-char prio))
3054 (org-set-local 'org-highest-priority (nth 0 prio))
3055 (org-set-local 'org-lowest-priority (nth 1 prio))
3056 (org-set-local 'org-default-priority (nth 2 prio)))
3057 (and props (org-set-local 'org-file-properties (nreverse props)))
3058 (and ftags (org-set-local 'org-file-tags ftags))
3059 (and drawers (org-set-local 'org-drawers drawers))
3060 (and arch (org-set-local 'org-archive-location arch))
3061 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3062 ;; Process the TODO keywords
3063 (unless kwds
3064 ;; Use the global values as if they had been given locally.
3065 (setq kwds (default-value 'org-todo-keywords))
3066 (if (stringp (car kwds))
3067 (setq kwds (list (cons org-todo-interpretation
3068 (default-value 'org-todo-keywords)))))
3069 (setq kwds (reverse kwds)))
3070 (setq kwds (nreverse kwds))
3071 (let (inter kws kw)
3072 (while (setq kws (pop kwds))
3073 (setq inter (pop kws) sep (member "|" kws)
3074 kws0 (delete "|" (copy-sequence kws))
3075 kwsa nil
3076 kws1 (mapcar
3077 (lambda (x)
3078 ;; 1 2
3079 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3080 (progn
3081 (setq kw (match-string 1 x)
3082 key (and (match-end 2) (match-string 2 x))
3083 log (org-extract-log-state-settings x))
3084 (push (cons kw (and key (string-to-char key))) kwsa)
3085 (and log (push log org-todo-log-states))
3086 kw)
3087 (error "Invalid TODO keyword %s" x)))
3088 kws0)
3089 kwsa (if kwsa (append '((:startgroup))
3090 (nreverse kwsa)
3091 '((:endgroup))))
3092 hw (car kws1)
3093 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3094 tail (list inter hw (car dws) (org-last dws)))
3095 (add-to-list 'org-todo-heads hw 'append)
3096 (push kws1 org-todo-sets)
3097 (setq org-done-keywords (append org-done-keywords dws nil))
3098 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3099 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3100 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3101 (setq org-todo-sets (nreverse org-todo-sets)
3102 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3103 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3104 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3105 ;; Process the constants
3106 (when const
3107 (let (e cst)
3108 (while (setq e (pop const))
3109 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3110 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3111 (setq org-table-formula-constants-local cst)))
3112
3113 ;; Process the tags.
3114 (when tags
3115 (let (e tgs)
3116 (while (setq e (pop tags))
3117 (cond
3118 ((equal e "{") (push '(:startgroup) tgs))
3119 ((equal e "}") (push '(:endgroup) tgs))
3120 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3121 (push (cons (match-string 1 e)
3122 (string-to-char (match-string 2 e)))
3123 tgs))
3124 (t (push (list e) tgs))))
3125 (org-set-local 'org-tag-alist nil)
3126 (while (setq e (pop tgs))
3127 (or (and (stringp (car e))
3128 (assoc (car e) org-tag-alist))
3129 (push e org-tag-alist)))))
3130
3131 ;; Compute the regular expressions and other local variables
3132 (if (not org-done-keywords)
3133 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3134 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3135 (length org-scheduled-string)
3136 (length org-clock-string)
3137 (length org-closed-string)))
3138 org-drawer-regexp
3139 (concat "^[ \t]*:\\("
3140 (mapconcat 'regexp-quote org-drawers "\\|")
3141 "\\):[ \t]*$")
3142 org-not-done-keywords
3143 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3144 org-todo-regexp
3145 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3146 "\\|") "\\)\\>")
3147 org-not-done-regexp
3148 (concat "\\<\\("
3149 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3150 "\\)\\>")
3151 org-todo-line-regexp
3152 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3153 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3154 "\\)\\>\\)?[ \t]*\\(.*\\)")
3155 org-complex-heading-regexp
3156 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3157 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3158 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3159 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3160 org-nl-done-regexp
3161 (concat "\n\\*+[ \t]+"
3162 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3163 "\\)" "\\>")
3164 org-todo-line-tags-regexp
3165 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3166 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3167 (org-re
3168 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3169 org-looking-at-done-regexp
3170 (concat "^" "\\(?:"
3171 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3172 "\\>")
3173 org-deadline-regexp (concat "\\<" org-deadline-string)
3174 org-deadline-time-regexp
3175 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3176 org-deadline-line-regexp
3177 (concat "\\<\\(" org-deadline-string "\\).*")
3178 org-scheduled-regexp
3179 (concat "\\<" org-scheduled-string)
3180 org-scheduled-time-regexp
3181 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3182 org-closed-time-regexp
3183 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3184 org-keyword-time-regexp
3185 (concat "\\<\\(" org-scheduled-string
3186 "\\|" org-deadline-string
3187 "\\|" org-closed-string
3188 "\\|" org-clock-string "\\)"
3189 " *[[<]\\([^]>]+\\)[]>]")
3190 org-keyword-time-not-clock-regexp
3191 (concat "\\<\\(" org-scheduled-string
3192 "\\|" org-deadline-string
3193 "\\|" org-closed-string
3194 "\\)"
3195 " *[[<]\\([^]>]+\\)[]>]")
3196 org-maybe-keyword-time-regexp
3197 (concat "\\(\\<\\(" org-scheduled-string
3198 "\\|" org-deadline-string
3199 "\\|" org-closed-string
3200 "\\|" org-clock-string "\\)\\)?"
3201 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3202 org-planning-or-clock-line-re
3203 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3204 "\\|" org-deadline-string
3205 "\\|" org-closed-string "\\|" org-clock-string
3206 "\\)\\>\\)")
3207 )
3208 (org-compute-latex-and-specials-regexp)
3209 (org-set-font-lock-defaults))))
3210
3211 (defun org-file-contents (file &optional noerror)
3212 "Return the contents of FILE, as a string."
3213 (if (or (not file)
3214 (not (file-readable-p file)))
3215 (if noerror
3216 (progn
3217 (message "Cannot read file %s" file)
3218 (ding) (sit-for 2)
3219 "")
3220 (error "Cannot read file %s" file))
3221 (with-temp-buffer
3222 (insert-file-contents file)
3223 (buffer-string))))
3224
3225 (defun org-extract-log-state-settings (x)
3226 "Extract the log state setting from a TODO keyword string.
3227 This will extract info from a string like \"WAIT(w@/!)\"."
3228 (let (kw key log1 log2)
3229 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3230 (setq kw (match-string 1 x)
3231 key (and (match-end 2) (match-string 2 x))
3232 log1 (and (match-end 3) (match-string 3 x))
3233 log2 (and (match-end 4) (match-string 4 x)))
3234 (and (or log1 log2)
3235 (list kw
3236 (and log1 (if (equal log1 "!") 'time 'note))
3237 (and log2 (if (equal log2 "!") 'time 'note)))))))
3238
3239 (defun org-remove-keyword-keys (list)
3240 "Remove a pair of parenthesis at the end of each string in LIST."
3241 (mapcar (lambda (x)
3242 (if (string-match "(.*)$" x)
3243 (substring x 0 (match-beginning 0))
3244 x))
3245 list))
3246
3247 ;; FIXME: this could be done much better, using second characters etc.
3248 (defun org-assign-fast-keys (alist)
3249 "Assign fast keys to a keyword-key alist.
3250 Respect keys that are already there."
3251 (let (new e k c c1 c2 (char ?a))
3252 (while (setq e (pop alist))
3253 (cond
3254 ((equal e '(:startgroup)) (push e new))
3255 ((equal e '(:endgroup)) (push e new))
3256 (t
3257 (setq k (car e) c2 nil)
3258 (if (cdr e)
3259 (setq c (cdr e))
3260 ;; automatically assign a character.
3261 (setq c1 (string-to-char
3262 (downcase (substring
3263 k (if (= (string-to-char k) ?@) 1 0)))))
3264 (if (or (rassoc c1 new) (rassoc c1 alist))
3265 (while (or (rassoc char new) (rassoc char alist))
3266 (setq char (1+ char)))
3267 (setq c2 c1))
3268 (setq c (or c2 char)))
3269 (push (cons k c) new))))
3270 (nreverse new)))
3271
3272 ;;; Some variables used in various places
3273
3274 (defvar org-window-configuration nil
3275 "Used in various places to store a window configuration.")
3276 (defvar org-finish-function nil
3277 "Function to be called when `C-c C-c' is used.
3278 This is for getting out of special buffers like remember.")
3279
3280
3281 ;; FIXME: Occasionally check by commenting these, to make sure
3282 ;; no other functions uses these, forgetting to let-bind them.
3283 (defvar entry)
3284 (defvar state)
3285 (defvar last-state)
3286 (defvar date)
3287 (defvar description)
3288
3289 ;; Defined somewhere in this file, but used before definition.
3290 (defvar org-html-entities)
3291 (defvar org-struct-menu)
3292 (defvar org-org-menu)
3293 (defvar org-tbl-menu)
3294 (defvar org-agenda-keymap)
3295
3296 ;;;; Define the Org-mode
3297
3298 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3299 (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."))
3300
3301
3302 ;; We use a before-change function to check if a table might need
3303 ;; an update.
3304 (defvar org-table-may-need-update t
3305 "Indicates that a table might need an update.
3306 This variable is set by `org-before-change-function'.
3307 `org-table-align' sets it back to nil.")
3308 (defun org-before-change-function (beg end)
3309 "Every change indicates that a table might need an update."
3310 (setq org-table-may-need-update t))
3311 (defvar org-mode-map)
3312 (defvar org-mode-hook nil)
3313 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3314 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3315 (defvar org-table-buffer-is-an nil)
3316 (defconst org-outline-regexp "\\*+ ")
3317
3318 ;;;###autoload
3319 (define-derived-mode org-mode outline-mode "Org"
3320 "Outline-based notes management and organizer, alias
3321 \"Carsten's outline-mode for keeping track of everything.\"
3322
3323 Org-mode develops organizational tasks around a NOTES file which
3324 contains information about projects as plain text. Org-mode is
3325 implemented on top of outline-mode, which is ideal to keep the content
3326 of large files well structured. It supports ToDo items, deadlines and
3327 time stamps, which magically appear in the diary listing of the Emacs
3328 calendar. Tables are easily created with a built-in table editor.
3329 Plain text URL-like links connect to websites, emails (VM), Usenet
3330 messages (Gnus), BBDB entries, and any files related to the project.
3331 For printing and sharing of notes, an Org-mode file (or a part of it)
3332 can be exported as a structured ASCII or HTML file.
3333
3334 The following commands are available:
3335
3336 \\{org-mode-map}"
3337
3338 ;; Get rid of Outline menus, they are not needed
3339 ;; Need to do this here because define-derived-mode sets up
3340 ;; the keymap so late. Still, it is a waste to call this each time
3341 ;; we switch another buffer into org-mode.
3342 (if (featurep 'xemacs)
3343 (when (boundp 'outline-mode-menu-heading)
3344 ;; Assume this is Greg's port, it used easymenu
3345 (easy-menu-remove outline-mode-menu-heading)
3346 (easy-menu-remove outline-mode-menu-show)
3347 (easy-menu-remove outline-mode-menu-hide))
3348 (define-key org-mode-map [menu-bar headings] 'undefined)
3349 (define-key org-mode-map [menu-bar hide] 'undefined)
3350 (define-key org-mode-map [menu-bar show] 'undefined))
3351
3352 (org-load-modules-maybe)
3353 (easy-menu-add org-org-menu)
3354 (easy-menu-add org-tbl-menu)
3355 (org-install-agenda-files-menu)
3356 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3357 (org-add-to-invisibility-spec '(org-cwidth))
3358 (when (featurep 'xemacs)
3359 (org-set-local 'line-move-ignore-invisible t))
3360 (org-set-local 'outline-regexp org-outline-regexp)
3361 (org-set-local 'outline-level 'org-outline-level)
3362 (when (and org-ellipsis
3363 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3364 (fboundp 'make-glyph-code))
3365 (unless org-display-table
3366 (setq org-display-table (make-display-table)))
3367 (set-display-table-slot
3368 org-display-table 4
3369 (vconcat (mapcar
3370 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3371 org-ellipsis)))
3372 (if (stringp org-ellipsis) org-ellipsis "..."))))
3373 (setq buffer-display-table org-display-table))
3374 (org-set-regexps-and-options)
3375 ;; Calc embedded
3376 (org-set-local 'calc-embedded-open-mode "# ")
3377 (modify-syntax-entry ?# "<")
3378 (modify-syntax-entry ?@ "w")
3379 (if org-startup-truncated (setq truncate-lines t))
3380 (org-set-local 'font-lock-unfontify-region-function
3381 'org-unfontify-region)
3382 ;; Activate before-change-function
3383 (org-set-local 'org-table-may-need-update t)
3384 (org-add-hook 'before-change-functions 'org-before-change-function nil
3385 'local)
3386 ;; Check for running clock before killing a buffer
3387 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3388 ;; Paragraphs and auto-filling
3389 (org-set-autofill-regexps)
3390 (setq indent-line-function 'org-indent-line-function)
3391 (org-update-radio-target-regexp)
3392
3393 ;; Comment characters
3394 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3395 (org-set-local 'comment-padding " ")
3396
3397 ;; Align options lines
3398 (org-set-local
3399 'align-mode-rules-list
3400 '((org-in-buffer-settings
3401 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3402 (modes . '(org-mode)))))
3403
3404 ;; Imenu
3405 (org-set-local 'imenu-create-index-function
3406 'org-imenu-get-tree)
3407
3408 ;; Make isearch reveal context
3409 (if (or (featurep 'xemacs)
3410 (not (boundp 'outline-isearch-open-invisible-function)))
3411 ;; Emacs 21 and XEmacs make use of the hook
3412 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3413 ;; Emacs 22 deals with this through a special variable
3414 (org-set-local 'outline-isearch-open-invisible-function
3415 (lambda (&rest ignore) (org-show-context 'isearch))))
3416
3417 ;; If empty file that did not turn on org-mode automatically, make it to.
3418 (if (and org-insert-mode-line-in-empty-file
3419 (interactive-p)
3420 (= (point-min) (point-max)))
3421 (insert "# -*- mode: org -*-\n\n"))
3422
3423 (unless org-inhibit-startup
3424 (when org-startup-align-all-tables
3425 (let ((bmp (buffer-modified-p)))
3426 (org-table-map-tables 'org-table-align)
3427 (set-buffer-modified-p bmp)))
3428 (org-set-startup-visibility)))
3429
3430 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3431
3432 (defun org-current-time ()
3433 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3434 (if (> (car org-time-stamp-rounding-minutes) 1)
3435 (let ((r (car org-time-stamp-rounding-minutes))
3436 (time (decode-time)))
3437 (apply 'encode-time
3438 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3439 (nthcdr 2 time))))
3440 (current-time)))
3441
3442 ;;;; Font-Lock stuff, including the activators
3443
3444 (defvar org-mouse-map (make-sparse-keymap))
3445 (org-defkey org-mouse-map
3446 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3447 (org-defkey org-mouse-map
3448 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3449 (when org-mouse-1-follows-link
3450 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3451 (when org-tab-follows-link
3452 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3453 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3454 (when org-return-follows-link
3455 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3456 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3457
3458 (require 'font-lock)
3459
3460 (defconst org-non-link-chars "]\t\n\r<>")
3461 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3462 "shell" "elisp"))
3463 (defvar org-link-types-re nil
3464 "Matches a link that has a url-like prefix like \"http:\"")
3465 (defvar org-link-re-with-space nil
3466 "Matches a link with spaces, optional angular brackets around it.")
3467 (defvar org-link-re-with-space2 nil
3468 "Matches a link with spaces, optional angular brackets around it.")
3469 (defvar org-link-re-with-space3 nil
3470 "Matches a link with spaces, only for internal part in bracket links.")
3471 (defvar org-angle-link-re nil
3472 "Matches link with angular brackets, spaces are allowed.")
3473 (defvar org-plain-link-re nil
3474 "Matches plain link, without spaces.")
3475 (defvar org-bracket-link-regexp nil
3476 "Matches a link in double brackets.")
3477 (defvar org-bracket-link-analytic-regexp nil
3478 "Regular expression used to analyze links.
3479 Here is what the match groups contain after a match:
3480 1: http:
3481 2: http
3482 3: path
3483 4: [desc]
3484 5: desc")
3485 (defvar org-any-link-re nil
3486 "Regular expression matching any link.")
3487
3488 (defun org-make-link-regexps ()
3489 "Update the link regular expressions.
3490 This should be called after the variable `org-link-types' has changed."
3491 (setq org-link-types-re
3492 (concat
3493 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3494 org-link-re-with-space
3495 (concat
3496 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3497 "\\([^" org-non-link-chars " ]"
3498 "[^" org-non-link-chars "]*"
3499 "[^" org-non-link-chars " ]\\)>?")
3500 org-link-re-with-space2
3501 (concat
3502 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3503 "\\([^" org-non-link-chars " ]"
3504 "[^\t\n\r]*"
3505 "[^" org-non-link-chars " ]\\)>?")
3506 org-link-re-with-space3
3507 (concat
3508 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3509 "\\([^" org-non-link-chars " ]"
3510 "[^\t\n\r]*\\)")
3511 org-angle-link-re
3512 (concat
3513 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3514 "\\([^" org-non-link-chars " ]"
3515 "[^" org-non-link-chars "]*"
3516 "\\)>")
3517 org-plain-link-re
3518 (concat
3519 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3520 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3521 org-bracket-link-regexp
3522 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3523 org-bracket-link-analytic-regexp
3524 (concat
3525 "\\[\\["
3526 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3527 "\\([^]]+\\)"
3528 "\\]"
3529 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3530 "\\]")
3531 org-any-link-re
3532 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3533 org-angle-link-re "\\)\\|\\("
3534 org-plain-link-re "\\)")))
3535
3536 (org-make-link-regexps)
3537
3538 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3539 "Regular expression for fast time stamp matching.")
3540 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3541 "Regular expression for fast time stamp matching.")
3542 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3543 "Regular expression matching time strings for analysis.
3544 This one does not require the space after the date, so it can be used
3545 on a string that terminates immediately after the date.")
3546 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3547 "Regular expression matching time strings for analysis.")
3548 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3549 "Regular expression matching time stamps, with groups.")
3550 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3551 "Regular expression matching time stamps (also [..]), with groups.")
3552 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3553 "Regular expression matching a time stamp range.")
3554 (defconst org-tr-regexp-both
3555 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3556 "Regular expression matching a time stamp range.")
3557 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3558 org-ts-regexp "\\)?")
3559 "Regular expression matching a time stamp or time stamp range.")
3560 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3561 org-ts-regexp-both "\\)?")
3562 "Regular expression matching a time stamp or time stamp range.
3563 The time stamps may be either active or inactive.")
3564
3565 (defvar org-emph-face nil)
3566
3567 (defun org-do-emphasis-faces (limit)
3568 "Run through the buffer and add overlays to links."
3569 (let (rtn)
3570 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3571 (if (not (= (char-after (match-beginning 3))
3572 (char-after (match-beginning 4))))
3573 (progn
3574 (setq rtn t)
3575 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3576 'face
3577 (nth 1 (assoc (match-string 3)
3578 org-emphasis-alist)))
3579 (add-text-properties (match-beginning 2) (match-end 2)
3580 '(font-lock-multiline t))
3581 (when org-hide-emphasis-markers
3582 (add-text-properties (match-end 4) (match-beginning 5)
3583 '(invisible org-link))
3584 (add-text-properties (match-beginning 3) (match-end 3)
3585 '(invisible org-link)))))
3586 (backward-char 1))
3587 rtn))
3588
3589 (defun org-emphasize (&optional char)
3590 "Insert or change an emphasis, i.e. a font like bold or italic.
3591 If there is an active region, change that region to a new emphasis.
3592 If there is no region, just insert the marker characters and position
3593 the cursor between them.
3594 CHAR should be either the marker character, or the first character of the
3595 HTML tag associated with that emphasis. If CHAR is a space, the means
3596 to remove the emphasis of the selected region.
3597 If char is not given (for example in an interactive call) it
3598 will be prompted for."
3599 (interactive)
3600 (let ((eal org-emphasis-alist) e det
3601 (erc org-emphasis-regexp-components)
3602 (prompt "")
3603 (string "") beg end move tag c s)
3604 (if (org-region-active-p)
3605 (setq beg (region-beginning) end (region-end)
3606 string (buffer-substring beg end))
3607 (setq move t))
3608
3609 (while (setq e (pop eal))
3610 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3611 c (aref tag 0))
3612 (push (cons c (string-to-char (car e))) det)
3613 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3614 (substring tag 1)))))
3615 (setq det (nreverse det))
3616 (unless char
3617 (message "%s" (concat "Emphasis marker or tag:" prompt))
3618 (setq char (read-char-exclusive)))
3619 (setq char (or (cdr (assoc char det)) char))
3620 (if (equal char ?\ )
3621 (setq s "" move nil)
3622 (unless (assoc (char-to-string char) org-emphasis-alist)
3623 (error "No such emphasis marker: \"%c\"" char))
3624 (setq s (char-to-string char)))
3625 (while (and (> (length string) 1)
3626 (equal (substring string 0 1) (substring string -1))
3627 (assoc (substring string 0 1) org-emphasis-alist))
3628 (setq string (substring string 1 -1)))
3629 (setq string (concat s string s))
3630 (if beg (delete-region beg end))
3631 (unless (or (bolp)
3632 (string-match (concat "[" (nth 0 erc) "\n]")
3633 (char-to-string (char-before (point)))))
3634 (insert " "))
3635 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3636 (char-to-string (char-after (point))))
3637 (insert " ") (backward-char 1))
3638 (insert string)
3639 (and move (backward-char 1))))
3640
3641 (defconst org-nonsticky-props
3642 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3643
3644
3645 (defun org-activate-plain-links (limit)
3646 "Run through the buffer and add overlays to links."
3647 (catch 'exit
3648 (let (f)
3649 (while (re-search-forward org-plain-link-re limit t)
3650 (setq f (get-text-property (match-beginning 0) 'face))
3651 (if (or (eq f 'org-tag)
3652 (and (listp f) (memq 'org-tag f)))
3653 nil
3654 (add-text-properties (match-beginning 0) (match-end 0)
3655 (list 'mouse-face 'highlight
3656 'rear-nonsticky org-nonsticky-props
3657 'keymap org-mouse-map
3658 ))
3659 (throw 'exit t))))))
3660
3661 (defun org-activate-code (limit)
3662 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3663 (progn
3664 (remove-text-properties (match-beginning 0) (match-end 0)
3665 '(display t invisible t intangible t))
3666 t)))
3667
3668 (defun org-activate-angle-links (limit)
3669 "Run through the buffer and add overlays to links."
3670 (if (re-search-forward org-angle-link-re limit t)
3671 (progn
3672 (add-text-properties (match-beginning 0) (match-end 0)
3673 (list 'mouse-face 'highlight
3674 'rear-nonsticky org-nonsticky-props
3675 'keymap org-mouse-map
3676 ))
3677 t)))
3678
3679 (defun org-activate-bracket-links (limit)
3680 "Run through the buffer and add overlays to bracketed links."
3681 (if (re-search-forward org-bracket-link-regexp limit t)
3682 (let* ((help (concat "LINK: "
3683 (org-match-string-no-properties 1)))
3684 ;; FIXME: above we should remove the escapes.
3685 ;; but that requires another match, protecting match data,
3686 ;; a lot of overhead for font-lock.
3687 (ip (org-maybe-intangible
3688 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3689 'keymap org-mouse-map 'mouse-face 'highlight
3690 'font-lock-multiline t 'help-echo help)))
3691 (vp (list 'rear-nonsticky org-nonsticky-props
3692 'keymap org-mouse-map 'mouse-face 'highlight
3693 ' font-lock-multiline t 'help-echo help)))
3694 ;; We need to remove the invisible property here. Table narrowing
3695 ;; may have made some of this invisible.
3696 (remove-text-properties (match-beginning 0) (match-end 0)
3697 '(invisible nil))
3698 (if (match-end 3)
3699 (progn
3700 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3701 (add-text-properties (match-beginning 3) (match-end 3) vp)
3702 (add-text-properties (match-end 3) (match-end 0) ip))
3703 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3704 (add-text-properties (match-beginning 1) (match-end 1) vp)
3705 (add-text-properties (match-end 1) (match-end 0) ip))
3706 t)))
3707
3708 (defun org-activate-dates (limit)
3709 "Run through the buffer and add overlays to dates."
3710 (if (re-search-forward org-tsr-regexp-both limit t)
3711 (progn
3712 (add-text-properties (match-beginning 0) (match-end 0)
3713 (list 'mouse-face 'highlight
3714 'rear-nonsticky org-nonsticky-props
3715 'keymap org-mouse-map))
3716 (when org-display-custom-times
3717 (if (match-end 3)
3718 (org-display-custom-time (match-beginning 3) (match-end 3)))
3719 (org-display-custom-time (match-beginning 1) (match-end 1)))
3720 t)))
3721
3722 (defvar org-target-link-regexp nil
3723 "Regular expression matching radio targets in plain text.")
3724 (make-variable-buffer-local 'org-target-link-regexp)
3725 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3726 "Regular expression matching a link target.")
3727 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3728 "Regular expression matching a radio target.")
3729 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3730 "Regular expression matching any target.")
3731
3732 (defun org-activate-target-links (limit)
3733 "Run through the buffer and add overlays to target matches."
3734 (when org-target-link-regexp
3735 (let ((case-fold-search t))
3736 (if (re-search-forward org-target-link-regexp limit t)
3737 (progn
3738 (add-text-properties (match-beginning 0) (match-end 0)
3739 (list 'mouse-face 'highlight
3740 'rear-nonsticky org-nonsticky-props
3741 'keymap org-mouse-map
3742 'help-echo "Radio target link"
3743 'org-linked-text t))
3744 t)))))
3745
3746 (defun org-update-radio-target-regexp ()
3747 "Find all radio targets in this file and update the regular expression."
3748 (interactive)
3749 (when (memq 'radio org-activate-links)
3750 (setq org-target-link-regexp
3751 (org-make-target-link-regexp (org-all-targets 'radio)))
3752 (org-restart-font-lock)))
3753
3754 (defun org-hide-wide-columns (limit)
3755 (let (s e)
3756 (setq s (text-property-any (point) (or limit (point-max))
3757 'org-cwidth t))
3758 (when s
3759 (setq e (next-single-property-change s 'org-cwidth))
3760 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3761 (goto-char e)
3762 t)))
3763
3764 (defvar org-latex-and-specials-regexp nil
3765 "Regular expression for highlighting export special stuff.")
3766 (defvar org-match-substring-regexp)
3767 (defvar org-match-substring-with-braces-regexp)
3768 (defvar org-export-html-special-string-regexps)
3769
3770 (defun org-compute-latex-and-specials-regexp ()
3771 "Compute regular expression for stuff treated specially by exporters."
3772 (if (not org-highlight-latex-fragments-and-specials)
3773 (org-set-local 'org-latex-and-specials-regexp nil)
3774 (require 'org-exp)
3775 (let*
3776 ((matchers (plist-get org-format-latex-options :matchers))
3777 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3778 org-latex-regexps)))
3779 (options (org-combine-plists (org-default-export-plist)
3780 (org-infile-export-plist)))
3781 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3782 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3783 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3784 (org-export-html-expand (plist-get options :expand-quoted-html))
3785 (org-export-with-special-strings (plist-get options :special-strings))
3786 (re-sub
3787 (cond
3788 ((equal org-export-with-sub-superscripts '{})
3789 (list org-match-substring-with-braces-regexp))
3790 (org-export-with-sub-superscripts
3791 (list org-match-substring-regexp))
3792 (t nil)))
3793 (re-latex
3794 (if org-export-with-LaTeX-fragments
3795 (mapcar (lambda (x) (nth 1 x)) latexs)))
3796 (re-macros
3797 (if org-export-with-TeX-macros
3798 (list (concat "\\\\"
3799 (regexp-opt
3800 (append (mapcar 'car org-html-entities)
3801 (if (boundp 'org-latex-entities)
3802 org-latex-entities nil))
3803 'words))) ; FIXME
3804 ))
3805 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3806 (re-special (if org-export-with-special-strings
3807 (mapcar (lambda (x) (car x))
3808 org-export-html-special-string-regexps)))
3809 (re-rest
3810 (delq nil
3811 (list
3812 (if org-export-html-expand "@<[^>\n]+>")
3813 ))))
3814 (org-set-local
3815 'org-latex-and-specials-regexp
3816 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3817 re-rest) "\\|")))))
3818
3819 (defun org-do-latex-and-special-faces (limit)
3820 "Run through the buffer and add overlays to links."
3821 (when org-latex-and-specials-regexp
3822 (let (rtn d)
3823 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3824 limit t))
3825 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3826 'face))
3827 '(org-code org-verbatim underline)))
3828 (progn
3829 (setq rtn t
3830 d (cond ((member (char-after (1+ (match-beginning 0)))
3831 '(?_ ?^)) 1)
3832 (t 0)))
3833 (font-lock-prepend-text-property
3834 (+ d (match-beginning 0)) (match-end 0)
3835 'face 'org-latex-and-export-specials)
3836 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3837 '(font-lock-multiline t)))))
3838 rtn)))
3839
3840 (defun org-restart-font-lock ()
3841 "Restart font-lock-mode, to force refontification."
3842 (when (and (boundp 'font-lock-mode) font-lock-mode)
3843 (font-lock-mode -1)
3844 (font-lock-mode 1)))
3845
3846 (defun org-all-targets (&optional radio)
3847 "Return a list of all targets in this file.
3848 With optional argument RADIO, only find radio targets."
3849 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3850 rtn)
3851 (save-excursion
3852 (goto-char (point-min))
3853 (while (re-search-forward re nil t)
3854 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3855 rtn)))
3856
3857 (defun org-make-target-link-regexp (targets)
3858 "Make regular expression matching all strings in TARGETS.
3859 The regular expression finds the targets also if there is a line break
3860 between words."
3861 (and targets
3862 (concat
3863 "\\<\\("
3864 (mapconcat
3865 (lambda (x)
3866 (while (string-match " +" x)
3867 (setq x (replace-match "\\s-+" t t x)))
3868 x)
3869 targets
3870 "\\|")
3871 "\\)\\>")))
3872
3873 (defun org-activate-tags (limit)
3874 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3875 (progn
3876 (add-text-properties (match-beginning 1) (match-end 1)
3877 (list 'mouse-face 'highlight
3878 'rear-nonsticky org-nonsticky-props
3879 'keymap org-mouse-map))
3880 t)))
3881
3882 (defun org-outline-level ()
3883 (save-excursion
3884 (looking-at outline-regexp)
3885 (if (match-beginning 1)
3886 (+ (org-get-string-indentation (match-string 1)) 1000)
3887 (1- (- (match-end 0) (match-beginning 0))))))
3888
3889 (defvar org-font-lock-keywords nil)
3890
3891 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3892 "Regular expression matching a property line.")
3893
3894 (defvar org-font-lock-hook nil
3895 "Functions to be called for special font lock stuff.")
3896
3897 (defun org-font-lock-hook (limit)
3898 (run-hook-with-args 'org-font-lock-hook limit))
3899
3900 (defun org-set-font-lock-defaults ()
3901 (let* ((em org-fontify-emphasized-text)
3902 (lk org-activate-links)
3903 (org-font-lock-extra-keywords
3904 (list
3905 ;; Call the hook
3906 '(org-font-lock-hook)
3907 ;; Headlines
3908 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3909 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3910 ;; Table lines
3911 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3912 (1 'org-table t))
3913 ;; Table internals
3914 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3915 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3916 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3917 ;; Drawers
3918 (list org-drawer-regexp '(0 'org-special-keyword t))
3919 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3920 ;; Properties
3921 (list org-property-re
3922 '(1 'org-special-keyword t)
3923 '(3 'org-property-value t))
3924 (if org-format-transports-properties-p
3925 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3926 ;; Links
3927 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3928 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3929 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3930 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3931 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3932 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3933 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3934 '(org-hide-wide-columns (0 nil append))
3935 ;; TODO lines
3936 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3937 '(1 (org-get-todo-face 1) t))
3938 ;; DONE
3939 (if org-fontify-done-headline
3940 (list (concat "^[*]+ +\\<\\("
3941 (mapconcat 'regexp-quote org-done-keywords "\\|")
3942 "\\)\\(.*\\)")
3943 '(2 'org-headline-done t))
3944 nil)
3945 ;; Priorities
3946 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3947 ;; Tags
3948 '(org-font-lock-add-tag-faces)
3949 ;; Special keywords
3950 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3951 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3952 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3953 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3954 ;; Emphasis
3955 (if em
3956 (if (featurep 'xemacs)
3957 '(org-do-emphasis-faces (0 nil append))
3958 '(org-do-emphasis-faces)))
3959 ;; Checkboxes
3960 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3961 2 'bold prepend)
3962 (if org-provide-checkbox-statistics
3963 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3964 (0 (org-get-checkbox-statistics-face) t)))
3965 ;; Description list items
3966 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3967 2 'bold prepend)
3968 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3969 '(1 'org-archived prepend))
3970 ;; Specials
3971 '(org-do-latex-and-special-faces)
3972 ;; Code
3973 '(org-activate-code (1 'org-code t))
3974 ;; COMMENT
3975 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3976 "\\|" org-quote-string "\\)\\>")
3977 '(1 'org-special-keyword t))
3978 '("^#.*" (0 'font-lock-comment-face t))
3979 )))
3980 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3981 ;; Now set the full font-lock-keywords
3982 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3983 (org-set-local 'font-lock-defaults
3984 '(org-font-lock-keywords t nil nil backward-paragraph))
3985 (kill-local-variable 'font-lock-keywords) nil))
3986
3987 (defvar org-m nil)
3988 (defvar org-l nil)
3989 (defvar org-f nil)
3990 (defun org-get-level-face (n)
3991 "Get the right face for match N in font-lock matching of healdines."
3992 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3993 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3994 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3995 (cond
3996 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3997 ((eq n 2) org-f)
3998 (t (if org-level-color-stars-only nil org-f))))
3999
4000 (defun org-get-todo-face (kwd)
4001 "Get the right face for a TODO keyword KWD.
4002 If KWD is a number, get the corresponding match group."
4003 (if (numberp kwd) (setq kwd (match-string kwd)))
4004 (or (cdr (assoc kwd org-todo-keyword-faces))
4005 (and (member kwd org-done-keywords) 'org-done)
4006 'org-todo))
4007
4008 (defun org-font-lock-add-tag-faces (limit)
4009 "Add the special tag faces."
4010 (when (and org-tag-faces org-tags-special-faces-re)
4011 (while (re-search-forward org-tags-special-faces-re limit t)
4012 (add-text-properties (match-beginning 1) (match-end 1)
4013 (list 'face (org-get-tag-face 1)
4014 'font-lock-fontified t))
4015 (backward-char 1))))
4016
4017 (defun org-get-tag-face (kwd)
4018 "Get the right face for a TODO keyword KWD.
4019 If KWD is a number, get the corresponding match group."
4020 (if (numberp kwd) (setq kwd (match-string kwd)))
4021 (or (cdr (assoc kwd org-tag-faces))
4022 'org-tag))
4023
4024 (defun org-unfontify-region (beg end &optional maybe_loudly)
4025 "Remove fontification and activation overlays from links."
4026 (font-lock-default-unfontify-region beg end)
4027 (let* ((buffer-undo-list t)
4028 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4029 (inhibit-modification-hooks t)
4030 deactivate-mark buffer-file-name buffer-file-truename)
4031 (remove-text-properties beg end
4032 '(mouse-face t keymap t org-linked-text t
4033 invisible t intangible t))))
4034
4035 ;;;; Visibility cycling, including org-goto and indirect buffer
4036
4037 ;;; Cycling
4038
4039 (defvar org-cycle-global-status nil)
4040 (make-variable-buffer-local 'org-cycle-global-status)
4041 (defvar org-cycle-subtree-status nil)
4042 (make-variable-buffer-local 'org-cycle-subtree-status)
4043
4044 ;;;###autoload
4045 (defun org-cycle (&optional arg)
4046 "Visibility cycling for Org-mode.
4047
4048 - When this function is called with a prefix argument, rotate the entire
4049 buffer through 3 states (global cycling)
4050 1. OVERVIEW: Show only top-level headlines.
4051 2. CONTENTS: Show all headlines of all levels, but no body text.
4052 3. SHOW ALL: Show everything.
4053 When called with two C-u C-u prefixes, switch to the startup visibility,
4054 determined by the variable `org-startup-folded', and by any VISIBILITY
4055 properties in the buffer.
4056 When called with three C-u C-u C-u prefixed, show the entire buffer,
4057 including drawers.
4058
4059 - When point is at the beginning of a headline, rotate the subtree started
4060 by this line through 3 different states (local cycling)
4061 1. FOLDED: Only the main headline is shown.
4062 2. CHILDREN: The main headline and the direct children are shown.
4063 From this state, you can move to one of the children
4064 and zoom in further.
4065 3. SUBTREE: Show the entire subtree, including body text.
4066
4067 - When there is a numeric prefix, go up to a heading with level ARG, do
4068 a `show-subtree' and return to the previous cursor position. If ARG
4069 is negative, go up that many levels.
4070
4071 - When point is not at the beginning of a headline, execute the global
4072 binding for TAB, which is re-indenting the line. See the option
4073 `org-cycle-emulate-tab' for details.
4074
4075 - Special case: if point is at the beginning of the buffer and there is
4076 no headline in line 1, this function will act as if called with prefix arg.
4077 But only if also the variable `org-cycle-global-at-bob' is t."
4078 (interactive "P")
4079 (org-load-modules-maybe)
4080 (let* ((outline-regexp
4081 (if (and (org-mode-p) org-cycle-include-plain-lists)
4082 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4083 outline-regexp))
4084 (bob-special (and org-cycle-global-at-bob (bobp)
4085 (not (looking-at outline-regexp))))
4086 (org-cycle-hook
4087 (if bob-special
4088 (delq 'org-optimize-window-after-visibility-change
4089 (copy-sequence org-cycle-hook))
4090 org-cycle-hook))
4091 (pos (point)))
4092
4093 (if (or bob-special (equal arg '(4)))
4094 ;; special case: use global cycling
4095 (setq arg t))
4096
4097 (cond
4098
4099 ((equal arg '(16))
4100 (org-set-startup-visibility)
4101 (message "Startup visibility, plus VISIBILITY properties"))
4102
4103 ((equal arg '(64))
4104 (show-all)
4105 (message "Entire buffer visible, including drawers"))
4106
4107 ((org-at-table-p 'any)
4108 ;; Enter the table or move to the next field in the table
4109 (or (org-table-recognize-table.el)
4110 (progn
4111 (if arg (org-table-edit-field t)
4112 (org-table-justify-field-maybe)
4113 (call-interactively 'org-table-next-field)))))
4114
4115 ((eq arg t) ;; Global cycling
4116
4117 (cond
4118 ((and (eq last-command this-command)
4119 (eq org-cycle-global-status 'overview))
4120 ;; We just created the overview - now do table of contents
4121 ;; This can be slow in very large buffers, so indicate action
4122 (message "CONTENTS...")
4123 (org-content)
4124 (message "CONTENTS...done")
4125 (setq org-cycle-global-status 'contents)
4126 (run-hook-with-args 'org-cycle-hook 'contents))
4127
4128 ((and (eq last-command this-command)
4129 (eq org-cycle-global-status 'contents))
4130 ;; We just showed the table of contents - now show everything
4131 (show-all)
4132 (message "SHOW ALL")
4133 (setq org-cycle-global-status 'all)
4134 (run-hook-with-args 'org-cycle-hook 'all))
4135
4136 (t
4137 ;; Default action: go to overview
4138 (org-overview)
4139 (message "OVERVIEW")
4140 (setq org-cycle-global-status 'overview)
4141 (run-hook-with-args 'org-cycle-hook 'overview))))
4142
4143 ((and org-drawers org-drawer-regexp
4144 (save-excursion
4145 (beginning-of-line 1)
4146 (looking-at org-drawer-regexp)))
4147 ;; Toggle block visibility
4148 (org-flag-drawer
4149 (not (get-char-property (match-end 0) 'invisible))))
4150
4151 ((integerp arg)
4152 ;; Show-subtree, ARG levels up from here.
4153 (save-excursion
4154 (org-back-to-heading)
4155 (outline-up-heading (if (< arg 0) (- arg)
4156 (- (funcall outline-level) arg)))
4157 (org-show-subtree)))
4158
4159 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4160 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4161 ;; At a heading: rotate between three different views
4162 (org-back-to-heading)
4163 (let ((goal-column 0) eoh eol eos)
4164 ;; First, some boundaries
4165 (save-excursion
4166 (org-back-to-heading)
4167 (save-excursion
4168 (beginning-of-line 2)
4169 (while (and (not (eobp)) ;; this is like `next-line'
4170 (get-char-property (1- (point)) 'invisible))
4171 (beginning-of-line 2)) (setq eol (point)))
4172 (outline-end-of-heading) (setq eoh (point))
4173 (org-end-of-subtree t)
4174 (unless (eobp)
4175 (skip-chars-forward " \t\n")
4176 (beginning-of-line 1) ; in case this is an item
4177 )
4178 (setq eos (1- (point))))
4179 ;; Find out what to do next and set `this-command'
4180 (cond
4181 ((= eos eoh)
4182 ;; Nothing is hidden behind this heading
4183 (message "EMPTY ENTRY")
4184 (setq org-cycle-subtree-status nil)
4185 (save-excursion
4186 (goto-char eos)
4187 (outline-next-heading)
4188 (if (org-invisible-p) (org-flag-heading nil))))
4189 ((or (>= eol eos)
4190 (not (string-match "\\S-" (buffer-substring eol eos))))
4191 ;; Entire subtree is hidden in one line: open it
4192 (org-show-entry)
4193 (show-children)
4194 (message "CHILDREN")
4195 (save-excursion
4196 (goto-char eos)
4197 (outline-next-heading)
4198 (if (org-invisible-p) (org-flag-heading nil)))
4199 (setq org-cycle-subtree-status 'children)
4200 (run-hook-with-args 'org-cycle-hook 'children))
4201 ((and (eq last-command this-command)
4202 (eq org-cycle-subtree-status 'children))
4203 ;; We just showed the children, now show everything.
4204 (org-show-subtree)
4205 (message "SUBTREE")
4206 (setq org-cycle-subtree-status 'subtree)
4207 (run-hook-with-args 'org-cycle-hook 'subtree))
4208 (t
4209 ;; Default action: hide the subtree.
4210 (hide-subtree)
4211 (message "FOLDED")
4212 (setq org-cycle-subtree-status 'folded)
4213 (run-hook-with-args 'org-cycle-hook 'folded)))))
4214
4215 ;; TAB emulation and template completion
4216 (buffer-read-only (org-back-to-heading))
4217
4218 ((org-try-structure-completion))
4219
4220 ((org-try-cdlatex-tab))
4221
4222 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4223 (or (not (bolp))
4224 (not (looking-at outline-regexp))))
4225 (call-interactively (global-key-binding "\t")))
4226
4227 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4228 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4229 (or (and (eq org-cycle-emulate-tab 'white)
4230 (= (match-end 0) (point-at-eol)))
4231 (and (eq org-cycle-emulate-tab 'whitestart)
4232 (>= (match-end 0) pos))))
4233 t
4234 (eq org-cycle-emulate-tab t))
4235 (call-interactively (global-key-binding "\t")))
4236
4237 (t (save-excursion
4238 (org-back-to-heading)
4239 (org-cycle))))))
4240
4241 ;;;###autoload
4242 (defun org-global-cycle (&optional arg)
4243 "Cycle the global visibility. For details see `org-cycle'.
4244 With C-u prefix arg, switch to startup visibility.
4245 With a numeric prefix, show all headlines up to that level."
4246 (interactive "P")
4247 (let ((org-cycle-include-plain-lists
4248 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4249 (cond
4250 ((integerp arg)
4251 (show-all)
4252 (hide-sublevels arg)
4253 (setq org-cycle-global-status 'contents))
4254 ((equal arg '(4))
4255 (org-set-startup-visibility)
4256 (message "Startup visibility, plus VISIBILITY properties."))
4257 (t
4258 (org-cycle '(4))))))
4259
4260 (defun org-set-startup-visibility ()
4261 "Set the visibility required by startup options and properties."
4262 (cond
4263 ((eq org-startup-folded t)
4264 (org-cycle '(4)))
4265 ((eq org-startup-folded 'content)
4266 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4267 (org-cycle '(4)) (org-cycle '(4)))))
4268 (org-set-visibility-according-to-property 'no-cleanup)
4269 (org-cycle-hide-archived-subtrees 'all)
4270 (org-cycle-hide-drawers 'all)
4271 (org-cycle-show-empty-lines 'all))
4272
4273 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4274 "Switch subtree visibilities according to :VISIBILITY: property."
4275 (interactive)
4276 (let (state)
4277 (save-excursion
4278 (goto-char (point-min))
4279 (while (re-search-forward
4280 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4281 nil t)
4282 (setq state (match-string 1))
4283 (save-excursion
4284 (org-back-to-heading t)
4285 (hide-subtree)
4286 (org-reveal)
4287 (cond
4288 ((equal state '("fold" "folded"))
4289 (hide-subtree))
4290 ((equal state "children")
4291 (org-show-hidden-entry)
4292 (show-children))
4293 ((equal state "content")
4294 (save-excursion
4295 (save-restriction
4296 (org-narrow-to-subtree)
4297 (org-content))))
4298 ((member state '("all" "showall"))
4299 (show-subtree)))))
4300 (unless no-cleanup
4301 (org-cycle-hide-archived-subtrees 'all)
4302 (org-cycle-hide-drawers 'all)
4303 (org-cycle-show-empty-lines 'all)))))
4304
4305 (defun org-overview ()
4306 "Switch to overview mode, shoing only top-level headlines.
4307 Really, this shows all headlines with level equal or greater than the level
4308 of the first headline in the buffer. This is important, because if the
4309 first headline is not level one, then (hide-sublevels 1) gives confusing
4310 results."
4311 (interactive)
4312 (let ((level (save-excursion
4313 (goto-char (point-min))
4314 (if (re-search-forward (concat "^" outline-regexp) nil t)
4315 (progn
4316 (goto-char (match-beginning 0))
4317 (funcall outline-level))))))
4318 (and level (hide-sublevels level))))
4319
4320 (defun org-content (&optional arg)
4321 "Show all headlines in the buffer, like a table of contents.
4322 With numerical argument N, show content up to level N."
4323 (interactive "P")
4324 (save-excursion
4325 ;; Visit all headings and show their offspring
4326 (and (integerp arg) (org-overview))
4327 (goto-char (point-max))
4328 (catch 'exit
4329 (while (and (progn (condition-case nil
4330 (outline-previous-visible-heading 1)
4331 (error (goto-char (point-min))))
4332 t)
4333 (looking-at outline-regexp))
4334 (if (integerp arg)
4335 (show-children (1- arg))
4336 (show-branches))
4337 (if (bobp) (throw 'exit nil))))))
4338
4339
4340 (defun org-optimize-window-after-visibility-change (state)
4341 "Adjust the window after a change in outline visibility.
4342 This function is the default value of the hook `org-cycle-hook'."
4343 (when (get-buffer-window (current-buffer))
4344 (cond
4345 ; ((eq state 'overview) (org-first-headline-recenter 1))
4346 ; ((eq state 'overview) (org-beginning-of-line))
4347 ((eq state 'content) nil)
4348 ((eq state 'all) nil)
4349 ((eq state 'folded) nil)
4350 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4351 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4352
4353 (defun org-compact-display-after-subtree-move ()
4354 (let (beg end)
4355 (save-excursion
4356 (if (org-up-heading-safe)
4357 (progn
4358 (hide-subtree)
4359 (show-entry)
4360 (show-children)
4361 (org-cycle-show-empty-lines 'children)
4362 (org-cycle-hide-drawers 'children))
4363 (org-overview)))))
4364
4365 (defun org-cycle-show-empty-lines (state)
4366 "Show empty lines above all visible headlines.
4367 The region to be covered depends on STATE when called through
4368 `org-cycle-hook'. Lisp program can use t for STATE to get the
4369 entire buffer covered. Note that an empty line is only shown if there
4370 are at least `org-cycle-separator-lines' empty lines before the headeline."
4371 (when (> org-cycle-separator-lines 0)
4372 (save-excursion
4373 (let* ((n org-cycle-separator-lines)
4374 (re (cond
4375 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4376 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4377 (t (let ((ns (number-to-string (- n 2))))
4378 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4379 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4380 beg end)
4381 (cond
4382 ((memq state '(overview contents t))
4383 (setq beg (point-min) end (point-max)))
4384 ((memq state '(children folded))
4385 (setq beg (point) end (progn (org-end-of-subtree t t)
4386 (beginning-of-line 2)
4387 (point)))))
4388 (when beg
4389 (goto-char beg)
4390 (while (re-search-forward re end t)
4391 (if (not (get-char-property (match-end 1) 'invisible))
4392 (outline-flag-region
4393 (match-beginning 1) (match-end 1) nil)))))))
4394 ;; Never hide empty lines at the end of the file.
4395 (save-excursion
4396 (goto-char (point-max))
4397 (outline-previous-heading)
4398 (outline-end-of-heading)
4399 (if (and (looking-at "[ \t\n]+")
4400 (= (match-end 0) (point-max)))
4401 (outline-flag-region (point) (match-end 0) nil))))
4402
4403 (defun org-show-empty-lines-in-parent ()
4404 "Move to the parent and re-show empty lines before visible headlines."
4405 (save-excursion
4406 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4407 (org-cycle-show-empty-lines context))))
4408
4409 (defun org-cycle-hide-drawers (state)
4410 "Re-hide all drawers after a visibility state change."
4411 (when (and (org-mode-p)
4412 (not (memq state '(overview folded))))
4413 (save-excursion
4414 (let* ((globalp (memq state '(contents all)))
4415 (beg (if globalp (point-min) (point)))
4416 (end (if globalp (point-max) (org-end-of-subtree t))))
4417 (goto-char beg)
4418 (while (re-search-forward org-drawer-regexp end t)
4419 (org-flag-drawer t))))))
4420
4421 (defun org-flag-drawer (flag)
4422 (save-excursion
4423 (beginning-of-line 1)
4424 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4425 (let ((b (match-end 0))
4426 (outline-regexp org-outline-regexp))
4427 (if (re-search-forward
4428 "^[ \t]*:END:"
4429 (save-excursion (outline-next-heading) (point)) t)
4430 (outline-flag-region b (point-at-eol) flag)
4431 (error ":END: line missing"))))))
4432
4433 (defun org-subtree-end-visible-p ()
4434 "Is the end of the current subtree visible?"
4435 (pos-visible-in-window-p
4436 (save-excursion (org-end-of-subtree t) (point))))
4437
4438 (defun org-first-headline-recenter (&optional N)
4439 "Move cursor to the first headline and recenter the headline.
4440 Optional argument N means, put the headline into the Nth line of the window."
4441 (goto-char (point-min))
4442 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4443 (beginning-of-line)
4444 (recenter (prefix-numeric-value N))))
4445
4446 ;;; Org-goto
4447
4448 (defvar org-goto-window-configuration nil)
4449 (defvar org-goto-marker nil)
4450 (defvar org-goto-map
4451 (let ((map (make-sparse-keymap)))
4452 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4453 (while (setq cmd (pop cmds))
4454 (substitute-key-definition cmd cmd map global-map)))
4455 (suppress-keymap map)
4456 (org-defkey map "\C-m" 'org-goto-ret)
4457 (org-defkey map [(return)] 'org-goto-ret)
4458 (org-defkey map [(left)] 'org-goto-left)
4459 (org-defkey map [(right)] 'org-goto-right)
4460 (org-defkey map [(control ?g)] 'org-goto-quit)
4461 (org-defkey map "\C-i" 'org-cycle)
4462 (org-defkey map [(tab)] 'org-cycle)
4463 (org-defkey map [(down)] 'outline-next-visible-heading)
4464 (org-defkey map [(up)] 'outline-previous-visible-heading)
4465 (if org-goto-auto-isearch
4466 (if (fboundp 'define-key-after)
4467 (define-key-after map [t] 'org-goto-local-auto-isearch)
4468 nil)
4469 (org-defkey map "q" 'org-goto-quit)
4470 (org-defkey map "n" 'outline-next-visible-heading)
4471 (org-defkey map "p" 'outline-previous-visible-heading)
4472 (org-defkey map "f" 'outline-forward-same-level)
4473 (org-defkey map "b" 'outline-backward-same-level)
4474 (org-defkey map "u" 'outline-up-heading))
4475 (org-defkey map "/" 'org-occur)
4476 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4477 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4478 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4479 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4480 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4481 map))
4482
4483 (defconst org-goto-help
4484 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4485 RET=jump to location [Q]uit and return to previous location
4486 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4487
4488 (defvar org-goto-start-pos) ; dynamically scoped parameter
4489
4490 ;; FIXME: Docstring doe not mention both interfaces
4491 (defun org-goto (&optional alternative-interface)
4492 "Look up a different location in the current file, keeping current visibility.
4493
4494 When you want look-up or go to a different location in a document, the
4495 fastest way is often to fold the entire buffer and then dive into the tree.
4496 This method has the disadvantage, that the previous location will be folded,
4497 which may not be what you want.
4498
4499 This command works around this by showing a copy of the current buffer
4500 in an indirect buffer, in overview mode. You can dive into the tree in
4501 that copy, use org-occur and incremental search to find a location.
4502 When pressing RET or `Q', the command returns to the original buffer in
4503 which the visibility is still unchanged. After RET is will also jump to
4504 the location selected in the indirect buffer and expose the
4505 the headline hierarchy above."
4506 (interactive "P")
4507 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4508 (org-refile-use-outline-path t)
4509 (interface
4510 (if (not alternative-interface)
4511 org-goto-interface
4512 (if (eq org-goto-interface 'outline)
4513 'outline-path-completion
4514 'outline)))
4515 (org-goto-start-pos (point))
4516 (selected-point
4517 (if (eq interface 'outline)
4518 (car (org-get-location (current-buffer) org-goto-help))
4519 (nth 3 (org-refile-get-location "Goto: ")))))
4520 (if selected-point
4521 (progn
4522 (org-mark-ring-push org-goto-start-pos)
4523 (goto-char selected-point)
4524 (if (or (org-invisible-p) (org-invisible-p2))
4525 (org-show-context 'org-goto)))
4526 (message "Quit"))))
4527
4528 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4529 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4530 (defvar org-goto-local-auto-isearch-map) ; defined below
4531
4532 (defun org-get-location (buf help)
4533 "Let the user select a location in the Org-mode buffer BUF.
4534 This function uses a recursive edit. It returns the selected position
4535 or nil."
4536 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4537 (isearch-hide-immediately nil)
4538 (isearch-search-fun-function
4539 (lambda () 'org-goto-local-search-headings))
4540 (org-goto-selected-point org-goto-exit-command))
4541 (save-excursion
4542 (save-window-excursion
4543 (delete-other-windows)
4544 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4545 (switch-to-buffer
4546 (condition-case nil
4547 (make-indirect-buffer (current-buffer) "*org-goto*")
4548 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4549 (with-output-to-temp-buffer "*Help*"
4550 (princ help))
4551 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4552 (setq buffer-read-only nil)
4553 (let ((org-startup-truncated t)
4554 (org-startup-folded nil)
4555 (org-startup-align-all-tables nil))
4556 (org-mode)
4557 (org-overview))
4558 (setq buffer-read-only t)
4559 (if (and (boundp 'org-goto-start-pos)
4560 (integer-or-marker-p org-goto-start-pos))
4561 (let ((org-show-hierarchy-above t)
4562 (org-show-siblings t)
4563 (org-show-following-heading t))
4564 (goto-char org-goto-start-pos)
4565 (and (org-invisible-p) (org-show-context)))
4566 (goto-char (point-min)))
4567 (org-beginning-of-line)
4568 (message "Select location and press RET")
4569 (use-local-map org-goto-map)
4570 (recursive-edit)
4571 ))
4572 (kill-buffer "*org-goto*")
4573 (cons org-goto-selected-point org-goto-exit-command)))
4574
4575 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4576 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4577 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4578 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4579
4580 (defun org-goto-local-search-headings (string bound noerror)
4581 "Search and make sure that any matches are in headlines."
4582 (catch 'return
4583 (while (if isearch-forward
4584 (search-forward string bound noerror)
4585 (search-backward string bound noerror))
4586 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4587 (and (member :headline context)
4588 (not (member :tags context))))
4589 (throw 'return (point))))))
4590
4591 (defun org-goto-local-auto-isearch ()
4592 "Start isearch."
4593 (interactive)
4594 (goto-char (point-min))
4595 (let ((keys (this-command-keys)))
4596 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4597 (isearch-mode t)
4598 (isearch-process-search-char (string-to-char keys)))))
4599
4600 (defun org-goto-ret (&optional arg)
4601 "Finish `org-goto' by going to the new location."
4602 (interactive "P")
4603 (setq org-goto-selected-point (point)
4604 org-goto-exit-command 'return)
4605 (throw 'exit nil))
4606
4607 (defun org-goto-left ()
4608 "Finish `org-goto' by going to the new location."
4609 (interactive)
4610 (if (org-on-heading-p)
4611 (progn
4612 (beginning-of-line 1)
4613 (setq org-goto-selected-point (point)
4614 org-goto-exit-command 'left)
4615 (throw 'exit nil))
4616 (error "Not on a heading")))
4617
4618 (defun org-goto-right ()
4619 "Finish `org-goto' by going to the new location."
4620 (interactive)
4621 (if (org-on-heading-p)
4622 (progn
4623 (setq org-goto-selected-point (point)
4624 org-goto-exit-command 'right)
4625 (throw 'exit nil))
4626 (error "Not on a heading")))
4627
4628 (defun org-goto-quit ()
4629 "Finish `org-goto' without cursor motion."
4630 (interactive)
4631 (setq org-goto-selected-point nil)
4632 (setq org-goto-exit-command 'quit)
4633 (throw 'exit nil))
4634
4635 ;;; Indirect buffer display of subtrees
4636
4637 (defvar org-indirect-dedicated-frame nil
4638 "This is the frame being used for indirect tree display.")
4639 (defvar org-last-indirect-buffer nil)
4640
4641 (defun org-tree-to-indirect-buffer (&optional arg)
4642 "Create indirect buffer and narrow it to current subtree.
4643 With numerical prefix ARG, go up to this level and then take that tree.
4644 If ARG is negative, go up that many levels.
4645 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4646 indirect buffer previously made with this command, to avoid proliferation of
4647 indirect buffers. However, when you call the command with a `C-u' prefix, or
4648 when `org-indirect-buffer-display' is `new-frame', the last buffer
4649 is kept so that you can work with several indirect buffers at the same time.
4650 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4651 requests that a new frame be made for the new buffer, so that the dedicated
4652 frame is not changed."
4653 (interactive "P")
4654 (let ((cbuf (current-buffer))
4655 (cwin (selected-window))
4656 (pos (point))
4657 beg end level heading ibuf)
4658 (save-excursion
4659 (org-back-to-heading t)
4660 (when (numberp arg)
4661 (setq level (org-outline-level))
4662 (if (< arg 0) (setq arg (+ level arg)))
4663 (while (> (setq level (org-outline-level)) arg)
4664 (outline-up-heading 1 t)))
4665 (setq beg (point)
4666 heading (org-get-heading))
4667 (org-end-of-subtree t) (setq end (point)))
4668 (if (and (buffer-live-p org-last-indirect-buffer)
4669 (not (eq org-indirect-buffer-display 'new-frame))
4670 (not arg))
4671 (kill-buffer org-last-indirect-buffer))
4672 (setq ibuf (org-get-indirect-buffer cbuf)
4673 org-last-indirect-buffer ibuf)
4674 (cond
4675 ((or (eq org-indirect-buffer-display 'new-frame)
4676 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4677 (select-frame (make-frame))
4678 (delete-other-windows)
4679 (switch-to-buffer ibuf)
4680 (org-set-frame-title heading))
4681 ((eq org-indirect-buffer-display 'dedicated-frame)
4682 (raise-frame
4683 (select-frame (or (and org-indirect-dedicated-frame
4684 (frame-live-p org-indirect-dedicated-frame)
4685 org-indirect-dedicated-frame)
4686 (setq org-indirect-dedicated-frame (make-frame)))))
4687 (delete-other-windows)
4688 (switch-to-buffer ibuf)
4689 (org-set-frame-title (concat "Indirect: " heading)))
4690 ((eq org-indirect-buffer-display 'current-window)
4691 (switch-to-buffer ibuf))
4692 ((eq org-indirect-buffer-display 'other-window)
4693 (pop-to-buffer ibuf))
4694 (t (error "Invalid value.")))
4695 (if (featurep 'xemacs)
4696 (save-excursion (org-mode) (turn-on-font-lock)))
4697 (narrow-to-region beg end)
4698 (show-all)
4699 (goto-char pos)
4700 (and (window-live-p cwin) (select-window cwin))))
4701
4702 (defun org-get-indirect-buffer (&optional buffer)
4703 (setq buffer (or buffer (current-buffer)))
4704 (let ((n 1) (base (buffer-name buffer)) bname)
4705 (while (buffer-live-p
4706 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4707 (setq n (1+ n)))
4708 (condition-case nil
4709 (make-indirect-buffer buffer bname 'clone)
4710 (error (make-indirect-buffer buffer bname)))))
4711
4712 (defun org-set-frame-title (title)
4713 "Set the title of the current frame to the string TITLE."
4714 ;; FIXME: how to name a single frame in XEmacs???
4715 (unless (featurep 'xemacs)
4716 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4717
4718 ;;;; Structure editing
4719
4720 ;;; Inserting headlines
4721
4722 (defun org-insert-heading (&optional force-heading)
4723 "Insert a new heading or item with same depth at point.
4724 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4725 If point is at the beginning of a headline, insert a sibling before the
4726 current headline. If point is not at the beginning, do not split the line,
4727 but create the new headline after the current line."
4728 (interactive "P")
4729 (if (= (buffer-size) 0)
4730 (insert "\n* ")
4731 (when (or force-heading (not (org-insert-item)))
4732 (let* ((head (save-excursion
4733 (condition-case nil
4734 (progn
4735 (org-back-to-heading)
4736 (match-string 0))
4737 (error "*"))))
4738 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4739 pos hide-previous previous-pos)
4740 (cond
4741 ((and (org-on-heading-p) (bolp)
4742 (or (bobp)
4743 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4744 ;; insert before the current line
4745 (open-line (if blank 2 1)))
4746 ((and (bolp)
4747 (or (bobp)
4748 (save-excursion
4749 (backward-char 1) (not (org-invisible-p)))))
4750 ;; insert right here
4751 nil)
4752 (t
4753 ;; somewhere in the line
4754 (save-excursion
4755 (setq previous-pos (point-at-bol))
4756 (end-of-line)
4757 (setq hide-previous (org-invisible-p)))
4758 (and org-insert-heading-respect-content (org-show-subtree))
4759 (let ((split
4760 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
4761 (save-excursion
4762 (let ((p (point)))
4763 (goto-char (point-at-bol))
4764 (and (looking-at org-complex-heading-regexp)
4765 (> p (match-beginning 4)))))))
4766 tags pos)
4767 (cond
4768 (org-insert-heading-respect-content
4769 (org-end-of-subtree nil t)
4770 (or (bolp) (newline))
4771 (open-line 1))
4772 ((org-on-heading-p)
4773 (when hide-previous
4774 (show-children)
4775 (org-show-entry))
4776 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4777 (setq tags (and (match-end 2) (match-string 2)))
4778 (and (match-end 1)
4779 (delete-region (match-beginning 1) (match-end 1)))
4780 (setq pos (point-at-bol))
4781 (or split (end-of-line 1))
4782 (delete-horizontal-space)
4783 (newline (if blank 2 1))
4784 (when tags
4785 (save-excursion
4786 (goto-char pos)
4787 (end-of-line 1)
4788 (insert " " tags)
4789 (org-set-tags nil 'align))))
4790 (t
4791 (or split (end-of-line 1))
4792 (newline (if blank 2 1)))))))
4793 (insert head) (just-one-space)
4794 (setq pos (point))
4795 (end-of-line 1)
4796 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4797 (when (and org-insert-heading-respect-content hide-previous)
4798 (save-excursion
4799 (goto-char previous-pos)
4800 (hide-subtree)))
4801 (run-hooks 'org-insert-heading-hook)))))
4802
4803 (defun org-get-heading (&optional no-tags)
4804 "Return the heading of the current entry, without the stars."
4805 (save-excursion
4806 (org-back-to-heading t)
4807 (if (looking-at
4808 (if no-tags
4809 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4810 "\\*+[ \t]+\\([^\r\n]*\\)"))
4811 (match-string 1) "")))
4812
4813 (defun org-insert-heading-after-current ()
4814 "Insert a new heading with same level as current, after current subtree."
4815 (interactive)
4816 (org-back-to-heading)
4817 (org-insert-heading)
4818 (org-move-subtree-down)
4819 (end-of-line 1))
4820
4821 (defun org-insert-heading-respect-content ()
4822 (interactive)
4823 (let ((org-insert-heading-respect-content t))
4824 (org-insert-heading t)))
4825
4826 (defun org-insert-todo-heading-respect-content (&optional force-state)
4827 (interactive "P")
4828 (let ((org-insert-heading-respect-content t))
4829 (org-insert-todo-heading force-state t)))
4830
4831 (defun org-insert-todo-heading (arg &optional force-heading)
4832 "Insert a new heading with the same level and TODO state as current heading.
4833 If the heading has no TODO state, or if the state is DONE, use the first
4834 state (TODO by default). Also with prefix arg, force first state."
4835 (interactive "P")
4836 (when (or force-heading (not (org-insert-item 'checkbox)))
4837 (org-insert-heading force-heading)
4838 (save-excursion
4839 (org-back-to-heading)
4840 (outline-previous-heading)
4841 (looking-at org-todo-line-regexp))
4842 (if (or arg
4843 (not (match-beginning 2))
4844 (member (match-string 2) org-done-keywords))
4845 (insert (car org-todo-keywords-1) " ")
4846 (insert (match-string 2) " "))
4847 (when org-provide-todo-statistics
4848 (org-update-parent-todo-statistics))))
4849
4850 (defun org-insert-subheading (arg)
4851 "Insert a new subheading and demote it.
4852 Works for outline headings and for plain lists alike."
4853 (interactive "P")
4854 (org-insert-heading arg)
4855 (cond
4856 ((org-on-heading-p) (org-do-demote))
4857 ((org-at-item-p) (org-indent-item 1))))
4858
4859 (defun org-insert-todo-subheading (arg)
4860 "Insert a new subheading with TODO keyword or checkbox and demote it.
4861 Works for outline headings and for plain lists alike."
4862 (interactive "P")
4863 (org-insert-todo-heading arg)
4864 (cond
4865 ((org-on-heading-p) (org-do-demote))
4866 ((org-at-item-p) (org-indent-item 1))))
4867
4868 ;;; Promotion and Demotion
4869
4870 (defun org-promote-subtree ()
4871 "Promote the entire subtree.
4872 See also `org-promote'."
4873 (interactive)
4874 (save-excursion
4875 (org-map-tree 'org-promote))
4876 (org-fix-position-after-promote))
4877
4878 (defun org-demote-subtree ()
4879 "Demote the entire subtree. See `org-demote'.
4880 See also `org-promote'."
4881 (interactive)
4882 (save-excursion
4883 (org-map-tree 'org-demote))
4884 (org-fix-position-after-promote))
4885
4886
4887 (defun org-do-promote ()
4888 "Promote the current heading higher up the tree.
4889 If the region is active in `transient-mark-mode', promote all headings
4890 in the region."
4891 (interactive)
4892 (save-excursion
4893 (if (org-region-active-p)
4894 (org-map-region 'org-promote (region-beginning) (region-end))
4895 (org-promote)))
4896 (org-fix-position-after-promote))
4897
4898 (defun org-do-demote ()
4899 "Demote the current heading lower down the tree.
4900 If the region is active in `transient-mark-mode', demote all headings
4901 in the region."
4902 (interactive)
4903 (save-excursion
4904 (if (org-region-active-p)
4905 (org-map-region 'org-demote (region-beginning) (region-end))
4906 (org-demote)))
4907 (org-fix-position-after-promote))
4908
4909 (defun org-fix-position-after-promote ()
4910 "Make sure that after pro/demotion cursor position is right."
4911 (let ((pos (point)))
4912 (when (save-excursion
4913 (beginning-of-line 1)
4914 (looking-at org-todo-line-regexp)
4915 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4916 (cond ((eobp) (insert " "))
4917 ((eolp) (insert " "))
4918 ((equal (char-after) ?\ ) (forward-char 1))))))
4919
4920 (defun org-reduced-level (l)
4921 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4922
4923 (defun org-get-valid-level (level &optional change)
4924 "Rectify a level change under the influence of `org-odd-levels-only'
4925 LEVEL is a current level, CHANGE is by how much the level should be
4926 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4927 even level numbers will become the next higher odd number."
4928 (if org-odd-levels-only
4929 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4930 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4931 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4932 (max 1 (+ level change))))
4933
4934 (if (boundp 'define-obsolete-function-alias)
4935 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4936 (define-obsolete-function-alias 'org-get-legal-level
4937 'org-get-valid-level)
4938 (define-obsolete-function-alias 'org-get-legal-level
4939 'org-get-valid-level "23.1")))
4940
4941 (defun org-promote ()
4942 "Promote the current heading higher up the tree.
4943 If the region is active in `transient-mark-mode', promote all headings
4944 in the region."
4945 (org-back-to-heading t)
4946 (let* ((level (save-match-data (funcall outline-level)))
4947 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4948 (diff (abs (- level (length up-head) -1))))
4949 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4950 (replace-match up-head nil t)
4951 ;; Fixup tag positioning
4952 (and org-auto-align-tags (org-set-tags nil t))
4953 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4954
4955 (defun org-demote ()
4956 "Demote the current heading lower down the tree.
4957 If the region is active in `transient-mark-mode', demote all headings
4958 in the region."
4959 (org-back-to-heading t)
4960 (let* ((level (save-match-data (funcall outline-level)))
4961 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4962 (diff (abs (- level (length down-head) -1))))
4963 (replace-match down-head nil t)
4964 ;; Fixup tag positioning
4965 (and org-auto-align-tags (org-set-tags nil t))
4966 (if org-adapt-indentation (org-fixup-indentation diff))))
4967
4968 (defun org-map-tree (fun)
4969 "Call FUN for every heading underneath the current one."
4970 (org-back-to-heading)
4971 (let ((level (funcall outline-level)))
4972 (save-excursion
4973 (funcall fun)
4974 (while (and (progn
4975 (outline-next-heading)
4976 (> (funcall outline-level) level))
4977 (not (eobp)))
4978 (funcall fun)))))
4979
4980 (defun org-map-region (fun beg end)
4981 "Call FUN for every heading between BEG and END."
4982 (let ((org-ignore-region t))
4983 (save-excursion
4984 (setq end (copy-marker end))
4985 (goto-char beg)
4986 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4987 (< (point) end))
4988 (funcall fun))
4989 (while (and (progn
4990 (outline-next-heading)
4991 (< (point) end))
4992 (not (eobp)))
4993 (funcall fun)))))
4994
4995 (defun org-fixup-indentation (diff)
4996 "Change the indentation in the current entry by DIFF
4997 However, if any line in the current entry has no indentation, or if it
4998 would end up with no indentation after the change, nothing at all is done."
4999 (save-excursion
5000 (let ((end (save-excursion (outline-next-heading)
5001 (point-marker)))
5002 (prohibit (if (> diff 0)
5003 "^\\S-"
5004 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5005 col)
5006 (unless (save-excursion (end-of-line 1)
5007 (re-search-forward prohibit end t))
5008 (while (and (< (point) end)
5009 (re-search-forward "^[ \t]+" end t))
5010 (goto-char (match-end 0))
5011 (setq col (current-column))
5012 (if (< diff 0) (replace-match ""))
5013 (org-indent-to-column (+ diff col))))
5014 (move-marker end nil))))
5015
5016 (defun org-convert-to-odd-levels ()
5017 "Convert an org-mode file with all levels allowed to one with odd levels.
5018 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5019 level 5 etc."
5020 (interactive)
5021 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5022 (let ((org-odd-levels-only nil) n)
5023 (save-excursion
5024 (goto-char (point-min))
5025 (while (re-search-forward "^\\*\\*+ " nil t)
5026 (setq n (- (length (match-string 0)) 2))
5027 (while (>= (setq n (1- n)) 0)
5028 (org-demote))
5029 (end-of-line 1))))))
5030
5031
5032 (defun org-convert-to-oddeven-levels ()
5033 "Convert an org-mode file with only odd levels to one with odd and even levels.
5034 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5035 section with an even level, conversion would destroy the structure of the file. An error
5036 is signaled in this case."
5037 (interactive)
5038 (goto-char (point-min))
5039 ;; First check if there are no even levels
5040 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5041 (org-show-context t)
5042 (error "Not all levels are odd in this file. Conversion not possible."))
5043 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5044 (let ((org-odd-levels-only nil) n)
5045 (save-excursion
5046 (goto-char (point-min))
5047 (while (re-search-forward "^\\*\\*+ " nil t)
5048 (setq n (/ (1- (length (match-string 0))) 2))
5049 (while (>= (setq n (1- n)) 0)
5050 (org-promote))
5051 (end-of-line 1))))))
5052
5053 (defun org-tr-level (n)
5054 "Make N odd if required."
5055 (if org-odd-levels-only (1+ (/ n 2)) n))
5056
5057 ;;; Vertical tree motion, cutting and pasting of subtrees
5058
5059 (defun org-move-subtree-up (&optional arg)
5060 "Move the current subtree up past ARG headlines of the same level."
5061 (interactive "p")
5062 (org-move-subtree-down (- (prefix-numeric-value arg))))
5063
5064 (defun org-move-subtree-down (&optional arg)
5065 "Move the current subtree down past ARG headlines of the same level."
5066 (interactive "p")
5067 (setq arg (prefix-numeric-value arg))
5068 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5069 'outline-get-last-sibling))
5070 (ins-point (make-marker))
5071 (cnt (abs arg))
5072 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5073 ;; Select the tree
5074 (org-back-to-heading)
5075 (setq beg0 (point))
5076 (save-excursion
5077 (setq ne-beg (org-back-over-empty-lines))
5078 (setq beg (point)))
5079 (save-match-data
5080 (save-excursion (outline-end-of-heading)
5081 (setq folded (org-invisible-p)))
5082 (outline-end-of-subtree))
5083 (outline-next-heading)
5084 (setq ne-end (org-back-over-empty-lines))
5085 (setq end (point))
5086 (goto-char beg0)
5087 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5088 ;; include less whitespace
5089 (save-excursion
5090 (goto-char beg)
5091 (forward-line (- ne-beg ne-end))
5092 (setq beg (point))))
5093 ;; Find insertion point, with error handling
5094 (while (> cnt 0)
5095 (or (and (funcall movfunc) (looking-at outline-regexp))
5096 (progn (goto-char beg0)
5097 (error "Cannot move past superior level or buffer limit")))
5098 (setq cnt (1- cnt)))
5099 (if (> arg 0)
5100 ;; Moving forward - still need to move over subtree
5101 (progn (org-end-of-subtree t t)
5102 (save-excursion
5103 (org-back-over-empty-lines)
5104 (or (bolp) (newline)))))
5105 (setq ne-ins (org-back-over-empty-lines))
5106 (move-marker ins-point (point))
5107 (setq txt (buffer-substring beg end))
5108 (org-save-markers-in-region beg end)
5109 (delete-region beg end)
5110 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5111 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5112 (let ((bbb (point)))
5113 (insert-before-markers txt)
5114 (org-reinstall-markers-in-region bbb)
5115 (move-marker ins-point bbb))
5116 (or (bolp) (insert "\n"))
5117 (setq ins-end (point))
5118 (goto-char ins-point)
5119 (org-skip-whitespace)
5120 (when (and (< arg 0)
5121 (org-first-sibling-p)
5122 (> ne-ins ne-beg))
5123 ;; Move whitespace back to beginning
5124 (save-excursion
5125 (goto-char ins-end)
5126 (let ((kill-whole-line t))
5127 (kill-line (- ne-ins ne-beg)) (point)))
5128 (insert (make-string (- ne-ins ne-beg) ?\n)))
5129 (move-marker ins-point nil)
5130 (org-compact-display-after-subtree-move)
5131 (org-show-empty-lines-in-parent)
5132 (unless folded
5133 (org-show-entry)
5134 (show-children)
5135 (org-cycle-hide-drawers 'children))))
5136
5137 (defvar org-subtree-clip ""
5138 "Clipboard for cut and paste of subtrees.
5139 This is actually only a copy of the kill, because we use the normal kill
5140 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5141
5142 (defvar org-subtree-clip-folded nil
5143 "Was the last copied subtree folded?
5144 This is used to fold the tree back after pasting.")
5145
5146 (defun org-cut-subtree (&optional n)
5147 "Cut the current subtree into the clipboard.
5148 With prefix arg N, cut this many sequential subtrees.
5149 This is a short-hand for marking the subtree and then cutting it."
5150 (interactive "p")
5151 (org-copy-subtree n 'cut))
5152
5153 (defun org-copy-subtree (&optional n cut force-store-markers)
5154 "Cut the current subtree into the clipboard.
5155 With prefix arg N, cut this many sequential subtrees.
5156 This is a short-hand for marking the subtree and then copying it.
5157 If CUT is non-nil, actually cut the subtree.
5158 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5159 of some markers in the region, even if CUT is non-nil. This is
5160 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5161 (interactive "p")
5162 (let (beg end folded (beg0 (point)))
5163 (if (interactive-p)
5164 (org-back-to-heading nil) ; take what looks like a subtree
5165 (org-back-to-heading t)) ; take what is really there
5166 (org-back-over-empty-lines)
5167 (setq beg (point))
5168 (skip-chars-forward " \t\r\n")
5169 (save-match-data
5170 (save-excursion (outline-end-of-heading)
5171 (setq folded (org-invisible-p)))
5172 (condition-case nil
5173 (outline-forward-same-level (1- n))
5174 (error nil))
5175 (org-end-of-subtree t t))
5176 (org-back-over-empty-lines)
5177 (setq end (point))
5178 (goto-char beg0)
5179 (when (> end beg)
5180 (setq org-subtree-clip-folded folded)
5181 (when (or cut force-store-markers)
5182 (org-save-markers-in-region beg end))
5183 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5184 (setq org-subtree-clip (current-kill 0))
5185 (message "%s: Subtree(s) with %d characters"
5186 (if cut "Cut" "Copied")
5187 (length org-subtree-clip)))))
5188
5189 (defun org-paste-subtree (&optional level tree for-yank)
5190 "Paste the clipboard as a subtree, with modification of headline level.
5191 The entire subtree is promoted or demoted in order to match a new headline
5192 level.
5193
5194 If the cursor is at the beginning of a headline, the same level as
5195 that headline is used to paste the tree
5196
5197 If not, the new level is derived from the *visible* headings
5198 before and after the insertion point, and taken to be the inferior headline
5199 level of the two. So if the previous visible heading is level 3 and the
5200 next is level 4 (or vice versa), level 4 will be used for insertion.
5201 This makes sure that the subtree remains an independent subtree and does
5202 not swallow low level entries.
5203
5204 You can also force a different level, either by using a numeric prefix
5205 argument, or by inserting the heading marker by hand. For example, if the
5206 cursor is after \"*****\", then the tree will be shifted to level 5.
5207
5208 If optional TREE is given, use this text instead of the kill ring.
5209
5210 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5211 move back over whitespace before inserting, and move point to the end of
5212 the inserted text when done."
5213 (interactive "P")
5214 (unless (org-kill-is-subtree-p tree)
5215 (error "%s"
5216 (substitute-command-keys
5217 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5218 (let* ((visp (not (org-invisible-p)))
5219 (txt (or tree (and kill-ring (current-kill 0))))
5220 (^re (concat "^\\(" outline-regexp "\\)"))
5221 (re (concat "\\(" outline-regexp "\\)"))
5222 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5223
5224 (old-level (if (string-match ^re txt)
5225 (- (match-end 0) (match-beginning 0) 1)
5226 -1))
5227 (force-level (cond (level (prefix-numeric-value level))
5228 ((and (looking-at "[ \t]*$")
5229 (string-match
5230 ^re_ (buffer-substring
5231 (point-at-bol) (point))))
5232 (- (match-end 1) (match-beginning 1)))
5233 ((and (bolp)
5234 (looking-at org-outline-regexp))
5235 (- (match-end 0) (point) 1))
5236 (t nil)))
5237 (previous-level (save-excursion
5238 (condition-case nil
5239 (progn
5240 (outline-previous-visible-heading 1)
5241 (if (looking-at re)
5242 (- (match-end 0) (match-beginning 0) 1)
5243 1))
5244 (error 1))))
5245 (next-level (save-excursion
5246 (condition-case nil
5247 (progn
5248 (or (looking-at outline-regexp)
5249 (outline-next-visible-heading 1))
5250 (if (looking-at re)
5251 (- (match-end 0) (match-beginning 0) 1)
5252 1))
5253 (error 1))))
5254 (new-level (or force-level (max previous-level next-level)))
5255 (shift (if (or (= old-level -1)
5256 (= new-level -1)
5257 (= old-level new-level))
5258 0
5259 (- new-level old-level)))
5260 (delta (if (> shift 0) -1 1))
5261 (func (if (> shift 0) 'org-demote 'org-promote))
5262 (org-odd-levels-only nil)
5263 beg end newend)
5264 ;; Remove the forced level indicator
5265 (if force-level
5266 (delete-region (point-at-bol) (point)))
5267 ;; Paste
5268 (beginning-of-line 1)
5269 (unless for-yank (org-back-over-empty-lines))
5270 (setq beg (point))
5271 (insert-before-markers txt)
5272 (unless (string-match "\n\\'" txt) (insert "\n"))
5273 (setq newend (point))
5274 (org-reinstall-markers-in-region beg)
5275 (setq end (point))
5276 (goto-char beg)
5277 (skip-chars-forward " \t\n\r")
5278 (setq beg (point))
5279 (if (and (org-invisible-p) visp)
5280 (save-excursion (outline-show-heading)))
5281 ;; Shift if necessary
5282 (unless (= shift 0)
5283 (save-restriction
5284 (narrow-to-region beg end)
5285 (while (not (= shift 0))
5286 (org-map-region func (point-min) (point-max))
5287 (setq shift (+ delta shift)))
5288 (goto-char (point-min))
5289 (setq newend (point-max))))
5290 (when (or (interactive-p) for-yank)
5291 (message "Clipboard pasted as level %d subtree" new-level))
5292 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5293 kill-ring
5294 (eq org-subtree-clip (current-kill 0))
5295 org-subtree-clip-folded)
5296 ;; The tree was folded before it was killed/copied
5297 (hide-subtree))
5298 (and for-yank (goto-char newend))))
5299
5300 (defun org-kill-is-subtree-p (&optional txt)
5301 "Check if the current kill is an outline subtree, or a set of trees.
5302 Returns nil if kill does not start with a headline, or if the first
5303 headline level is not the largest headline level in the tree.
5304 So this will actually accept several entries of equal levels as well,
5305 which is OK for `org-paste-subtree'.
5306 If optional TXT is given, check this string instead of the current kill."
5307 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5308 (start-level (and kill
5309 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5310 org-outline-regexp "\\)")
5311 kill)
5312 (- (match-end 2) (match-beginning 2) 1)))
5313 (re (concat "^" org-outline-regexp))
5314 (start (1+ (or (match-beginning 2) -1))))
5315 (if (not start-level)
5316 (progn
5317 nil) ;; does not even start with a heading
5318 (catch 'exit
5319 (while (setq start (string-match re kill (1+ start)))
5320 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5321 (throw 'exit nil)))
5322 t))))
5323
5324 (defvar org-markers-to-move nil
5325 "Markers that should be moved with a cut-and-paste operation.
5326 Those markers are stored together with their positions relative to
5327 the start of the region.")
5328
5329 (defun org-save-markers-in-region (beg end)
5330 "Check markers in region.
5331 If these markers are between BEG and END, record their position relative
5332 to BEG, so that after moving the block of text, we can put the markers back
5333 into place.
5334 This function gets called just before an entry or tree gets cut from the
5335 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5336 called immediately, to move the markers with the entries."
5337 (setq org-markers-to-move nil)
5338 (when (featurep 'org-clock)
5339 (org-clock-save-markers-for-cut-and-paste beg end))
5340 (when (featurep 'org-agenda)
5341 (org-agenda-save-markers-for-cut-and-paste beg end)))
5342
5343 (defun org-check-and-save-marker (marker beg end)
5344 "Check if MARKER is between BEG and END.
5345 If yes, remember the marker and the distance to BEG."
5346 (when (and (marker-buffer marker)
5347 (equal (marker-buffer marker) (current-buffer)))
5348 (if (and (>= marker beg) (< marker end))
5349 (push (cons marker (- marker beg)) org-markers-to-move))))
5350
5351 (defun org-reinstall-markers-in-region (beg)
5352 "Move all remembered markers to their position relative to BEG."
5353 (mapc (lambda (x)
5354 (move-marker (car x) (+ beg (cdr x))))
5355 org-markers-to-move)
5356 (setq org-markers-to-move nil))
5357
5358 (defun org-narrow-to-subtree ()
5359 "Narrow buffer to the current subtree."
5360 (interactive)
5361 (save-excursion
5362 (save-match-data
5363 (narrow-to-region
5364 (progn (org-back-to-heading) (point))
5365 (progn (org-end-of-subtree t) (point))))))
5366
5367
5368 ;;; Outline Sorting
5369
5370 (defun org-sort (with-case)
5371 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5372 Optional argument WITH-CASE means sort case-sensitively."
5373 (interactive "P")
5374 (if (org-at-table-p)
5375 (org-call-with-arg 'org-table-sort-lines with-case)
5376 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5377
5378 (defun org-sort-remove-invisible (s)
5379 (remove-text-properties 0 (length s) org-rm-props s)
5380 (while (string-match org-bracket-link-regexp s)
5381 (setq s (replace-match (if (match-end 2)
5382 (match-string 3 s)
5383 (match-string 1 s)) t t s)))
5384 s)
5385
5386 (defvar org-priority-regexp) ; defined later in the file
5387
5388 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5389 "Sort entries on a certain level of an outline tree.
5390 If there is an active region, the entries in the region are sorted.
5391 Else, if the cursor is before the first entry, sort the top-level items.
5392 Else, the children of the entry at point are sorted.
5393
5394 Sorting can be alphabetically, numerically, and by date/time as given by
5395 the first time stamp in the entry. The command prompts for the sorting
5396 type unless it has been given to the function through the SORTING-TYPE
5397 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5398 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5399 called with point at the beginning of the record. It must return either
5400 a string or a number that should serve as the sorting key for that record.
5401
5402 Comparing entries ignores case by default. However, with an optional argument
5403 WITH-CASE, the sorting considers case as well."
5404 (interactive "P")
5405 (let ((case-func (if with-case 'identity 'downcase))
5406 start beg end stars re re2
5407 txt what tmp plain-list-p)
5408 ;; Find beginning and end of region to sort
5409 (cond
5410 ((org-region-active-p)
5411 ;; we will sort the region
5412 (setq end (region-end)
5413 what "region")
5414 (goto-char (region-beginning))
5415 (if (not (org-on-heading-p)) (outline-next-heading))
5416 (setq start (point)))
5417 ((org-at-item-p)
5418 ;; we will sort this plain list
5419 (org-beginning-of-item-list) (setq start (point))
5420 (org-end-of-item-list) (setq end (point))
5421 (goto-char start)
5422 (setq plain-list-p t
5423 what "plain list"))
5424 ((or (org-on-heading-p)
5425 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5426 ;; we will sort the children of the current headline
5427 (org-back-to-heading)
5428 (setq start (point)
5429 end (progn (org-end-of-subtree t t)
5430 (org-back-over-empty-lines)
5431 (point))
5432 what "children")
5433 (goto-char start)
5434 (show-subtree)
5435 (outline-next-heading))
5436 (t
5437 ;; we will sort the top-level entries in this file
5438 (goto-char (point-min))
5439 (or (org-on-heading-p) (outline-next-heading))
5440 (setq start (point) end (point-max) what "top-level")
5441 (goto-char start)
5442 (show-all)))
5443
5444 (setq beg (point))
5445 (if (>= beg end) (error "Nothing to sort"))
5446
5447 (unless plain-list-p
5448 (looking-at "\\(\\*+\\)")
5449 (setq stars (match-string 1)
5450 re (concat "^" (regexp-quote stars) " +")
5451 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5452 txt (buffer-substring beg end))
5453 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5454 (if (and (not (equal stars "*")) (string-match re2 txt))
5455 (error "Region to sort contains a level above the first entry")))
5456
5457 (unless sorting-type
5458 (message
5459 (if plain-list-p
5460 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5461 "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:")
5462 what)
5463 (setq sorting-type (read-char-exclusive))
5464
5465 (and (= (downcase sorting-type) ?f)
5466 (setq getkey-func
5467 (org-ido-completing-read "Sort using function: "
5468 obarray 'fboundp t nil nil))
5469 (setq getkey-func (intern getkey-func)))
5470
5471 (and (= (downcase sorting-type) ?r)
5472 (setq property
5473 (org-ido-completing-read "Property: "
5474 (mapcar 'list (org-buffer-property-keys t))
5475 nil t))))
5476
5477 (message "Sorting entries...")
5478
5479 (save-restriction
5480 (narrow-to-region start end)
5481
5482 (let ((dcst (downcase sorting-type))
5483 (now (current-time)))
5484 (sort-subr
5485 (/= dcst sorting-type)
5486 ;; This function moves to the beginning character of the "record" to
5487 ;; be sorted.
5488 (if plain-list-p
5489 (lambda nil
5490 (if (org-at-item-p) t (goto-char (point-max))))
5491 (lambda nil
5492 (if (re-search-forward re nil t)
5493 (goto-char (match-beginning 0))
5494 (goto-char (point-max)))))
5495 ;; This function moves to the last character of the "record" being
5496 ;; sorted.
5497 (if plain-list-p
5498 'org-end-of-item
5499 (lambda nil
5500 (save-match-data
5501 (condition-case nil
5502 (outline-forward-same-level 1)
5503 (error
5504 (goto-char (point-max)))))))
5505
5506 ;; This function returns the value that gets sorted against.
5507 (if plain-list-p
5508 (lambda nil
5509 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5510 (cond
5511 ((= dcst ?n)
5512 (string-to-number (buffer-substring (match-end 0)
5513 (point-at-eol))))
5514 ((= dcst ?a)
5515 (buffer-substring (match-end 0) (point-at-eol)))
5516 ((= dcst ?t)
5517 (if (re-search-forward org-ts-regexp
5518 (point-at-eol) t)
5519 (org-time-string-to-time (match-string 0))
5520 now))
5521 ((= dcst ?f)
5522 (if getkey-func
5523 (progn
5524 (setq tmp (funcall getkey-func))
5525 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5526 tmp)
5527 (error "Invalid key function `%s'" getkey-func)))
5528 (t (error "Invalid sorting type `%c'" sorting-type)))))
5529 (lambda nil
5530 (cond
5531 ((= dcst ?n)
5532 (if (looking-at org-complex-heading-regexp)
5533 (string-to-number (match-string 4))
5534 nil))
5535 ((= dcst ?a)
5536 (if (looking-at org-complex-heading-regexp)
5537 (funcall case-func (match-string 4))
5538 nil))
5539 ((= dcst ?t)
5540 (if (re-search-forward org-ts-regexp
5541 (save-excursion
5542 (forward-line 2)
5543 (point)) t)
5544 (org-time-string-to-time (match-string 0))
5545 now))
5546 ((= dcst ?p)
5547 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5548 (string-to-char (match-string 2))
5549 org-default-priority))
5550 ((= dcst ?r)
5551 (or (org-entry-get nil property) ""))
5552 ((= dcst ?o)
5553 (if (looking-at org-complex-heading-regexp)
5554 (- 9999 (length (member (match-string 2)
5555 org-todo-keywords-1)))))
5556 ((= dcst ?f)
5557 (if getkey-func
5558 (progn
5559 (setq tmp (funcall getkey-func))
5560 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5561 tmp)
5562 (error "Invalid key function `%s'" getkey-func)))
5563 (t (error "Invalid sorting type `%c'" sorting-type)))))
5564 nil
5565 (cond
5566 ((= dcst ?a) 'string<)
5567 ((= dcst ?t) 'time-less-p)
5568 (t nil)))))
5569 (message "Sorting entries...done")))
5570
5571 (defun org-do-sort (table what &optional with-case sorting-type)
5572 "Sort TABLE of WHAT according to SORTING-TYPE.
5573 The user will be prompted for the SORTING-TYPE if the call to this
5574 function does not specify it. WHAT is only for the prompt, to indicate
5575 what is being sorted. The sorting key will be extracted from
5576 the car of the elements of the table.
5577 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5578 (unless sorting-type
5579 (message
5580 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5581 what)
5582 (setq sorting-type (read-char-exclusive)))
5583 (let ((dcst (downcase sorting-type))
5584 extractfun comparefun)
5585 ;; Define the appropriate functions
5586 (cond
5587 ((= dcst ?n)
5588 (setq extractfun 'string-to-number
5589 comparefun (if (= dcst sorting-type) '< '>)))
5590 ((= dcst ?a)
5591 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5592 (lambda(x) (downcase (org-sort-remove-invisible x))))
5593 comparefun (if (= dcst sorting-type)
5594 'string<
5595 (lambda (a b) (and (not (string< a b))
5596 (not (string= a b)))))))
5597 ((= dcst ?t)
5598 (setq extractfun
5599 (lambda (x)
5600 (if (string-match org-ts-regexp x)
5601 (time-to-seconds
5602 (org-time-string-to-time (match-string 0 x)))
5603 0))
5604 comparefun (if (= dcst sorting-type) '< '>)))
5605 (t (error "Invalid sorting type `%c'" sorting-type)))
5606
5607 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5608 table)
5609 (lambda (a b) (funcall comparefun (car a) (car b))))))
5610
5611 ;;; Editing source examples
5612
5613 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5614 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5615 (defvar org-edit-src-force-single-line nil)
5616 (defvar org-edit-src-from-org-mode nil)
5617 (defvar org-edit-src-picture nil)
5618
5619 (define-minor-mode org-exit-edit-mode
5620 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5621
5622 (defun org-edit-src-code ()
5623 "Edit the source code example at point.
5624 An indirect buffer is created, and that buffer is then narrowed to the
5625 example at point and switched to the correct language mode. When done,
5626 exit by killing the buffer with \\[org-edit-src-exit]."
5627 (interactive)
5628 (let ((line (org-current-line))
5629 (case-fold-search t)
5630 (msg (substitute-command-keys
5631 "Edit, then exit with C-c ' (C-c and single quote)"))
5632 (info (org-edit-src-find-region-and-lang))
5633 (org-mode-p (eq major-mode 'org-mode))
5634 beg end lang lang-f single)
5635 (if (not info)
5636 nil
5637 (setq beg (nth 0 info)
5638 end (nth 1 info)
5639 lang (nth 2 info)
5640 single (nth 3 info)
5641 lang-f (intern (concat lang "-mode")))
5642 (unless (functionp lang-f)
5643 (error "No such language mode: %s" lang-f))
5644 (goto-line line)
5645 (if (get-buffer "*Org Edit Src Example*")
5646 (kill-buffer "*Org Edit Src Example*"))
5647 (switch-to-buffer (make-indirect-buffer (current-buffer)
5648 "*Org Edit Src Example*"))
5649 (narrow-to-region beg end)
5650 (remove-text-properties beg end '(display nil invisible nil
5651 intangible nil))
5652 (let ((org-inhibit-startup t))
5653 (funcall lang-f))
5654 (set (make-local-variable 'org-edit-src-force-single-line) single)
5655 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5656 (when org-mode-p
5657 (goto-char (point-min))
5658 (while (re-search-forward "^," nil t)
5659 (replace-match "")))
5660 (goto-line line)
5661 (org-exit-edit-mode)
5662 (org-set-local 'header-line-format msg)
5663 (message "%s" msg)
5664 t)))
5665
5666 (defun org-edit-fixed-width-region ()
5667 "Edit the fixed-width ascii drawing at point.
5668 This must be a region where each line starts with ca colon followed by
5669 a space character.
5670 An indirect buffer is created, and that buffer is then narrowed to the
5671 example at point and switched to artist-mode. When done,
5672 exit by killing the buffer with \\[org-edit-src-exit]."
5673 (interactive)
5674 (let ((line (org-current-line))
5675 (case-fold-search t)
5676 (msg (substitute-command-keys
5677 "Edit, then exit with C-c ' (C-c and single quote)"))
5678 (org-mode-p (eq major-mode 'org-mode))
5679 beg end lang lang-f)
5680 (beginning-of-line 1)
5681 (if (looking-at "[ \t]*[^:\n \t]")
5682 nil
5683 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5684 (setq beg (point) end beg)
5685 (save-excursion
5686 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5687 (setq beg (point-at-bol 2))
5688 (setq beg (point))))
5689 (save-excursion
5690 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5691 (setq end (1- (match-beginning 0)))
5692 (setq end (point))))
5693 (goto-line line))
5694 (if (get-buffer "*Org Edit Picture*")
5695 (kill-buffer "*Org Edit Picture*"))
5696 (switch-to-buffer (make-indirect-buffer (current-buffer)
5697 "*Org Edit Picture*"))
5698 (narrow-to-region beg end)
5699 (remove-text-properties beg end '(display nil invisible nil
5700 intangible nil))
5701 (when (fboundp 'font-lock-unfontify-region)
5702 (font-lock-unfontify-region (point-min) (point-max)))
5703 (cond
5704 ((eq org-edit-fixed-width-region-mode 'artist-mode)
5705 (fundamental-mode)
5706 (artist-mode 1))
5707 (t (funcall org-edit-fixed-width-region-mode)))
5708 (set (make-local-variable 'org-edit-src-force-single-line) nil)
5709 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5710 (set (make-local-variable 'org-edit-src-picture) t)
5711 (goto-char (point-min))
5712 (while (re-search-forward "^[ \t]*: ?" nil t)
5713 (replace-match ""))
5714 (goto-line line)
5715 (org-exit-edit-mode)
5716 (org-set-local 'header-line-format msg)
5717 (message "%s" msg)
5718 t)))
5719
5720
5721 (defun org-edit-src-find-region-and-lang ()
5722 "Find the region and language for a local edit.
5723 Return a list with beginning and end of the region, a string representing
5724 the language, a switch telling of the content should be in a single line."
5725 (let ((re-list
5726 (append
5727 org-edit-src-region-extra
5728 '(
5729 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5730 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5731 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5732 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5733 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5734 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5735 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5736 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5737 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
5738 ("^#\\+html:" "\n" "html" single-line)
5739 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5740 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5741 ("^#\\+latex:" "\n" "latex" single-line)
5742 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5743 ("^#\\+ascii:" "\n" "ascii" single-line)
5744 )))
5745 (pos (point))
5746 re re1 re2 single beg end lang)
5747 (catch 'exit
5748 (while (setq entry (pop re-list))
5749 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5750 single (nth 3 entry))
5751 (save-excursion
5752 (if (or (looking-at re1)
5753 (re-search-backward re1 nil t))
5754 (progn
5755 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5756 (if (and (re-search-forward re2 nil t)
5757 (>= (match-end 0) pos))
5758 (throw 'exit (list beg (match-beginning 0) lang single))))
5759 (if (or (looking-at re2)
5760 (re-search-forward re2 nil t))
5761 (progn
5762 (setq end (match-beginning 0))
5763 (if (and (re-search-backward re1 nil t)
5764 (<= (match-beginning 0) pos))
5765 (throw 'exit
5766 (list (match-end 0) end
5767 (org-edit-src-get-lang lang) single)))))))))))
5768
5769 (defun org-edit-src-get-lang (lang)
5770 "Extract the src language."
5771 (let ((m (match-string 0)))
5772 (cond
5773 ((stringp lang) lang)
5774 ((integerp lang) (match-string lang))
5775 ((and (eq lang 'lang)
5776 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5777 (match-string 1 m))
5778 ((and (eq lang 'style)
5779 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5780 (match-string 1 m))
5781 (t "fundamental"))))
5782
5783 (defun org-edit-src-exit ()
5784 "Exit special edit and protect problematic lines."
5785 (interactive)
5786 (unless (buffer-base-buffer (current-buffer))
5787 (error "This is not an indirect buffer, something is wrong..."))
5788 (unless (> (point-min) 1)
5789 (error "This buffer is not narrowed, something is wrong..."))
5790 (goto-char (point-min))
5791 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5792 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5793 (when (org-bound-and-true-p org-edit-src-force-single-line)
5794 (goto-char (point-min))
5795 (while (re-search-forward "\n" nil t)
5796 (replace-match " "))
5797 (goto-char (point-min))
5798 (if (looking-at "\\s-*") (replace-match " "))
5799 (if (re-search-forward "\\s-+\\'" nil t)
5800 (replace-match "")))
5801 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5802 (goto-char (point-min))
5803 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5804 (replace-match ",\\1"))
5805 (when font-lock-mode
5806 (font-lock-unfontify-region (point-min) (point-max)))
5807 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5808 (when (org-bound-and-true-p org-edit-src-picture)
5809 (untabify (point-min) (point-max))
5810 (goto-char (point-min))
5811 (while (re-search-forward "^" nil t)
5812 (replace-match ": "))
5813 (when font-lock-mode
5814 (font-lock-unfontify-region (point-min) (point-max)))
5815 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5816 (kill-buffer (current-buffer))
5817 (and (org-mode-p) (org-restart-font-lock)))
5818
5819
5820 ;;; The orgstruct minor mode
5821
5822 ;; Define a minor mode which can be used in other modes in order to
5823 ;; integrate the org-mode structure editing commands.
5824
5825 ;; This is really a hack, because the org-mode structure commands use
5826 ;; keys which normally belong to the major mode. Here is how it
5827 ;; works: The minor mode defines all the keys necessary to operate the
5828 ;; structure commands, but wraps the commands into a function which
5829 ;; tests if the cursor is currently at a headline or a plain list
5830 ;; item. If that is the case, the structure command is used,
5831 ;; temporarily setting many Org-mode variables like regular
5832 ;; expressions for filling etc. However, when any of those keys is
5833 ;; used at a different location, function uses `key-binding' to look
5834 ;; up if the key has an associated command in another currently active
5835 ;; keymap (minor modes, major mode, global), and executes that
5836 ;; command. There might be problems if any of the keys is otherwise
5837 ;; used as a prefix key.
5838
5839 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5840 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5841 ;; addresses this by checking explicitly for both bindings.
5842
5843 (defvar orgstruct-mode-map (make-sparse-keymap)
5844 "Keymap for the minor `orgstruct-mode'.")
5845
5846 (defvar org-local-vars nil
5847 "List of local variables, for use by `orgstruct-mode'")
5848
5849 ;;;###autoload
5850 (define-minor-mode orgstruct-mode
5851 "Toggle the minor more `orgstruct-mode'.
5852 This mode is for using Org-mode structure commands in other modes.
5853 The following key behave as if Org-mode was active, if the cursor
5854 is on a headline, or on a plain list item (both in the definition
5855 of Org-mode).
5856
5857 M-up Move entry/item up
5858 M-down Move entry/item down
5859 M-left Promote
5860 M-right Demote
5861 M-S-up Move entry/item up
5862 M-S-down Move entry/item down
5863 M-S-left Promote subtree
5864 M-S-right Demote subtree
5865 M-q Fill paragraph and items like in Org-mode
5866 C-c ^ Sort entries
5867 C-c - Cycle list bullet
5868 TAB Cycle item visibility
5869 M-RET Insert new heading/item
5870 S-M-RET Insert new TODO heading / Chekbox item
5871 C-c C-c Set tags / toggle checkbox"
5872 nil " OrgStruct" nil
5873 (org-load-modules-maybe)
5874 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5875
5876 ;;;###autoload
5877 (defun turn-on-orgstruct ()
5878 "Unconditionally turn on `orgstruct-mode'."
5879 (orgstruct-mode 1))
5880
5881 ;;;###autoload
5882 (defun turn-on-orgstruct++ ()
5883 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5884 In addition to setting orgstruct-mode, this also exports all indentation and
5885 autofilling variables from org-mode into the buffer. Note that turning
5886 off orgstruct-mode will *not* remove these additional settings."
5887 (orgstruct-mode 1)
5888 (let (var val)
5889 (mapc
5890 (lambda (x)
5891 (when (string-match
5892 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5893 (symbol-name (car x)))
5894 (setq var (car x) val (nth 1 x))
5895 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5896 org-local-vars)))
5897
5898 (defun orgstruct-error ()
5899 "Error when there is no default binding for a structure key."
5900 (interactive)
5901 (error "This key has no function outside structure elements"))
5902
5903 (defun orgstruct-setup ()
5904 "Setup orgstruct keymaps."
5905 (let ((nfunc 0)
5906 (bindings
5907 (list
5908 '([(meta up)] org-metaup)
5909 '([(meta down)] org-metadown)
5910 '([(meta left)] org-metaleft)
5911 '([(meta right)] org-metaright)
5912 '([(meta shift up)] org-shiftmetaup)
5913 '([(meta shift down)] org-shiftmetadown)
5914 '([(meta shift left)] org-shiftmetaleft)
5915 '([(meta shift right)] org-shiftmetaright)
5916 '([(shift up)] org-shiftup)
5917 '([(shift down)] org-shiftdown)
5918 '([(shift left)] org-shiftleft)
5919 '([(shift right)] org-shiftright)
5920 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5921 '("\M-q" fill-paragraph)
5922 '("\C-c^" org-sort)
5923 '("\C-c-" org-cycle-list-bullet)))
5924 elt key fun cmd)
5925 (while (setq elt (pop bindings))
5926 (setq nfunc (1+ nfunc))
5927 (setq key (org-key (car elt))
5928 fun (nth 1 elt)
5929 cmd (orgstruct-make-binding fun nfunc key))
5930 (org-defkey orgstruct-mode-map key cmd))
5931
5932 ;; Special treatment needed for TAB and RET
5933 (org-defkey orgstruct-mode-map [(tab)]
5934 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5935 (org-defkey orgstruct-mode-map "\C-i"
5936 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5937
5938 (org-defkey orgstruct-mode-map "\M-\C-m"
5939 (orgstruct-make-binding 'org-insert-heading 105
5940 "\M-\C-m" [(meta return)]))
5941 (org-defkey orgstruct-mode-map [(meta return)]
5942 (orgstruct-make-binding 'org-insert-heading 106
5943 [(meta return)] "\M-\C-m"))
5944
5945 (org-defkey orgstruct-mode-map [(shift meta return)]
5946 (orgstruct-make-binding 'org-insert-todo-heading 107
5947 [(meta return)] "\M-\C-m"))
5948
5949 (unless org-local-vars
5950 (setq org-local-vars (org-get-local-variables)))
5951
5952 t))
5953
5954 (defun orgstruct-make-binding (fun n &rest keys)
5955 "Create a function for binding in the structure minor mode.
5956 FUN is the command to call inside a table. N is used to create a unique
5957 command name. KEYS are keys that should be checked in for a command
5958 to execute outside of tables."
5959 (eval
5960 (list 'defun
5961 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5962 '(arg)
5963 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5964 "Outside of structure, run the binding of `"
5965 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5966 "'.")
5967 '(interactive "p")
5968 (list 'if
5969 '(org-context-p 'headline 'item)
5970 (list 'org-run-like-in-org-mode (list 'quote fun))
5971 (list 'let '(orgstruct-mode)
5972 (list 'call-interactively
5973 (append '(or)
5974 (mapcar (lambda (k)
5975 (list 'key-binding k))
5976 keys)
5977 '('orgstruct-error))))))))
5978
5979 (defun org-context-p (&rest contexts)
5980 "Check if local context is any of CONTEXTS.
5981 Possible values in the list of contexts are `table', `headline', and `item'."
5982 (let ((pos (point)))
5983 (goto-char (point-at-bol))
5984 (prog1 (or (and (memq 'table contexts)
5985 (looking-at "[ \t]*|"))
5986 (and (memq 'headline contexts)
5987 ;;????????? (looking-at "\\*+"))
5988 (looking-at outline-regexp))
5989 (and (memq 'item contexts)
5990 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5991 (goto-char pos))))
5992
5993 (defun org-get-local-variables ()
5994 "Return a list of all local variables in an org-mode buffer."
5995 (let (varlist)
5996 (with-current-buffer (get-buffer-create "*Org tmp*")
5997 (erase-buffer)
5998 (org-mode)
5999 (setq varlist (buffer-local-variables)))
6000 (kill-buffer "*Org tmp*")
6001 (delq nil
6002 (mapcar
6003 (lambda (x)
6004 (setq x
6005 (if (symbolp x)
6006 (list x)
6007 (list (car x) (list 'quote (cdr x)))))
6008 (if (string-match
6009 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6010 (symbol-name (car x)))
6011 x nil))
6012 varlist))))
6013
6014 ;;;###autoload
6015 (defun org-run-like-in-org-mode (cmd)
6016 (org-load-modules-maybe)
6017 (unless org-local-vars
6018 (setq org-local-vars (org-get-local-variables)))
6019 (eval (list 'let org-local-vars
6020 (list 'call-interactively (list 'quote cmd)))))
6021
6022 ;;;; Archiving
6023
6024 (defun org-get-category (&optional pos)
6025 "Get the category applying to position POS."
6026 (get-text-property (or pos (point)) 'org-category))
6027
6028 (defun org-refresh-category-properties ()
6029 "Refresh category text properties in the buffer."
6030 (let ((def-cat (cond
6031 ((null org-category)
6032 (if buffer-file-name
6033 (file-name-sans-extension
6034 (file-name-nondirectory buffer-file-name))
6035 "???"))
6036 ((symbolp org-category) (symbol-name org-category))
6037 (t org-category)))
6038 beg end cat pos optionp)
6039 (org-unmodified
6040 (save-excursion
6041 (save-restriction
6042 (widen)
6043 (goto-char (point-min))
6044 (put-text-property (point) (point-max) 'org-category def-cat)
6045 (while (re-search-forward
6046 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6047 (setq pos (match-end 0)
6048 optionp (equal (char-after (match-beginning 0)) ?#)
6049 cat (org-trim (match-string 2)))
6050 (if optionp
6051 (setq beg (point-at-bol) end (point-max))
6052 (org-back-to-heading t)
6053 (setq beg (point) end (org-end-of-subtree t t)))
6054 (put-text-property beg end 'org-category cat)
6055 (goto-char pos)))))))
6056
6057
6058 ;;;; Link Stuff
6059
6060 ;;; Link abbreviations
6061
6062 (defun org-link-expand-abbrev (link)
6063 "Apply replacements as defined in `org-link-abbrev-alist."
6064 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6065 (let* ((key (match-string 1 link))
6066 (as (or (assoc key org-link-abbrev-alist-local)
6067 (assoc key org-link-abbrev-alist)))
6068 (tag (and (match-end 2) (match-string 3 link)))
6069 rpl)
6070 (if (not as)
6071 link
6072 (setq rpl (cdr as))
6073 (cond
6074 ((symbolp rpl) (funcall rpl tag))
6075 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6076 ((string-match "%h" rpl)
6077 (replace-match (url-hexify-string (or tag "")) t t rpl))
6078 (t (concat rpl tag)))))
6079 link))
6080
6081 ;;; Storing and inserting links
6082
6083 (defvar org-insert-link-history nil
6084 "Minibuffer history for links inserted with `org-insert-link'.")
6085
6086 (defvar org-stored-links nil
6087 "Contains the links stored with `org-store-link'.")
6088
6089 (defvar org-store-link-plist nil
6090 "Plist with info about the most recently link created with `org-store-link'.")
6091
6092 (defvar org-link-protocols nil
6093 "Link protocols added to Org-mode using `org-add-link-type'.")
6094
6095 (defvar org-store-link-functions nil
6096 "List of functions that are called to create and store a link.
6097 Each function will be called in turn until one returns a non-nil
6098 value. Each function should check if it is responsible for creating
6099 this link (for example by looking at the major mode).
6100 If not, it must exit and return nil.
6101 If yes, it should return a non-nil value after a calling
6102 `org-store-link-props' with a list of properties and values.
6103 Special properties are:
6104
6105 :type The link prefix. like \"http\". This must be given.
6106 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6107 This is obligatory as well.
6108 :description Optional default description for the second pair
6109 of brackets in an Org-mode link. The user can still change
6110 this when inserting this link into an Org-mode buffer.
6111
6112 In addition to these, any additional properties can be specified
6113 and then used in remember templates.")
6114
6115 (defun org-add-link-type (type &optional follow export)
6116 "Add TYPE to the list of `org-link-types'.
6117 Re-compute all regular expressions depending on `org-link-types'
6118
6119 FOLLOW and EXPORT are two functions.
6120
6121 FOLLOW should take the link path as the single argument and do whatever
6122 is necessary to follow the link, for example find a file or display
6123 a mail message.
6124
6125 EXPORT should format the link path for export to one of the export formats.
6126 It should be a function accepting three arguments:
6127
6128 path the path of the link, the text after the prefix (like \"http:\")
6129 desc the description of the link, if any, nil if there was no descripton
6130 format the export format, a symbol like `html' or `latex'.
6131
6132 The function may use the FORMAT information to return different values
6133 depending on the format. The return value will be put literally into
6134 the exported file.
6135 Org-mode has a built-in default for exporting links. If you are happy with
6136 this default, there is no need to define an export function for the link
6137 type. For a simple example of an export function, see `org-bbdb.el'."
6138 (add-to-list 'org-link-types type t)
6139 (org-make-link-regexps)
6140 (if (assoc type org-link-protocols)
6141 (setcdr (assoc type org-link-protocols) (list follow export))
6142 (push (list type follow export) org-link-protocols)))
6143
6144
6145 ;;;###autoload
6146 (defun org-store-link (arg)
6147 "\\<org-mode-map>Store an org-link to the current location.
6148 This link is added to `org-stored-links' and can later be inserted
6149 into an org-buffer with \\[org-insert-link].
6150
6151 For some link types, a prefix arg is interpreted:
6152 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6153 For file links, arg negates `org-context-in-file-links'."
6154 (interactive "P")
6155 (org-load-modules-maybe)
6156 (setq org-store-link-plist nil) ; reset
6157 (let (link cpltxt desc description search txt)
6158 (cond
6159
6160 ((run-hook-with-args-until-success 'org-store-link-functions)
6161 (setq link (plist-get org-store-link-plist :link)
6162 desc (or (plist-get org-store-link-plist :description) link)))
6163
6164 ((eq major-mode 'calendar-mode)
6165 (let ((cd (calendar-cursor-to-date)))
6166 (setq link
6167 (format-time-string
6168 (car org-time-stamp-formats)
6169 (apply 'encode-time
6170 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6171 nil nil nil))))
6172 (org-store-link-props :type "calendar" :date cd)))
6173
6174 ((eq major-mode 'w3-mode)
6175 (setq cpltxt (url-view-url t)
6176 link (org-make-link cpltxt))
6177 (org-store-link-props :type "w3" :url (url-view-url t)))
6178
6179 ((eq major-mode 'w3m-mode)
6180 (setq cpltxt (or w3m-current-title w3m-current-url)
6181 link (org-make-link w3m-current-url))
6182 (org-store-link-props :type "w3m" :url (url-view-url t)))
6183
6184 ((setq search (run-hook-with-args-until-success
6185 'org-create-file-search-functions))
6186 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6187 "::" search))
6188 (setq cpltxt (or description link)))
6189
6190 ((eq major-mode 'image-mode)
6191 (setq cpltxt (concat "file:"
6192 (abbreviate-file-name buffer-file-name))
6193 link (org-make-link cpltxt))
6194 (org-store-link-props :type "image" :file buffer-file-name))
6195
6196 ((eq major-mode 'dired-mode)
6197 ;; link to the file in the current line
6198 (setq cpltxt (concat "file:"
6199 (abbreviate-file-name
6200 (expand-file-name
6201 (dired-get-filename nil t))))
6202 link (org-make-link cpltxt)))
6203
6204 ((and buffer-file-name (org-mode-p))
6205 ;; Just link to current headline
6206 (setq cpltxt (concat "file:"
6207 (abbreviate-file-name buffer-file-name)))
6208 ;; Add a context search string
6209 (when (org-xor org-context-in-file-links arg)
6210 ;; Check if we are on a target
6211 (if (org-in-regexp "<<\\(.*?\\)>>")
6212 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6213 (setq txt (cond
6214 ((org-on-heading-p) nil)
6215 ((org-region-active-p)
6216 (buffer-substring (region-beginning) (region-end)))
6217 (t nil)))
6218 (when (or (null txt) (string-match "\\S-" txt))
6219 (setq cpltxt
6220 (concat cpltxt "::"
6221 (condition-case nil
6222 (org-make-org-heading-search-string txt)
6223 (error "")))
6224 desc "NONE"))))
6225 (if (string-match "::\\'" cpltxt)
6226 (setq cpltxt (substring cpltxt 0 -2)))
6227 (setq link (org-make-link cpltxt)))
6228
6229 ((buffer-file-name (buffer-base-buffer))
6230 ;; Just link to this file here.
6231 (setq cpltxt (concat "file:"
6232 (abbreviate-file-name
6233 (buffer-file-name (buffer-base-buffer)))))
6234 ;; Add a context string
6235 (when (org-xor org-context-in-file-links arg)
6236 (setq txt (if (org-region-active-p)
6237 (buffer-substring (region-beginning) (region-end))
6238 (buffer-substring (point-at-bol) (point-at-eol))))
6239 ;; Only use search option if there is some text.
6240 (when (string-match "\\S-" txt)
6241 (setq cpltxt
6242 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6243 desc "NONE")))
6244 (setq link (org-make-link cpltxt)))
6245
6246 ((interactive-p)
6247 (error "Cannot link to a buffer which is not visiting a file"))
6248
6249 (t (setq link nil)))
6250
6251 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6252 (setq link (or link cpltxt)
6253 desc (or desc cpltxt))
6254 (if (equal desc "NONE") (setq desc nil))
6255
6256 (if (and (interactive-p) link)
6257 (progn
6258 (setq org-stored-links
6259 (cons (list link desc) org-stored-links))
6260 (message "Stored: %s" (or desc link)))
6261 (and link (org-make-link-string link desc)))))
6262
6263 (defun org-store-link-props (&rest plist)
6264 "Store link properties, extract names and addresses."
6265 (let (x adr)
6266 (when (setq x (plist-get plist :from))
6267 (setq adr (mail-extract-address-components x))
6268 (setq plist (plist-put plist :fromname (car adr)))
6269 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6270 (when (setq x (plist-get plist :to))
6271 (setq adr (mail-extract-address-components x))
6272 (setq plist (plist-put plist :toname (car adr)))
6273 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6274 (let ((from (plist-get plist :from))
6275 (to (plist-get plist :to)))
6276 (when (and from to org-from-is-user-regexp)
6277 (setq plist
6278 (plist-put plist :fromto
6279 (if (string-match org-from-is-user-regexp from)
6280 (concat "to %t")
6281 (concat "from %f"))))))
6282 (setq org-store-link-plist plist))
6283
6284 (defun org-add-link-props (&rest plist)
6285 "Add these properties to the link property list."
6286 (let (key value)
6287 (while plist
6288 (setq key (pop plist) value (pop plist))
6289 (setq org-store-link-plist
6290 (plist-put org-store-link-plist key value)))))
6291
6292 (defun org-email-link-description (&optional fmt)
6293 "Return the description part of an email link.
6294 This takes information from `org-store-link-plist' and formats it
6295 according to FMT (default from `org-email-link-description-format')."
6296 (setq fmt (or fmt org-email-link-description-format))
6297 (let* ((p org-store-link-plist)
6298 (to (plist-get p :toaddress))
6299 (from (plist-get p :fromaddress))
6300 (table
6301 (list
6302 (cons "%c" (plist-get p :fromto))
6303 (cons "%F" (plist-get p :from))
6304 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6305 (cons "%T" (plist-get p :to))
6306 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6307 (cons "%s" (plist-get p :subject))
6308 (cons "%m" (plist-get p :message-id)))))
6309 (when (string-match "%c" fmt)
6310 ;; Check if the user wrote this message
6311 (if (and org-from-is-user-regexp from to
6312 (save-match-data (string-match org-from-is-user-regexp from)))
6313 (setq fmt (replace-match "to %t" t t fmt))
6314 (setq fmt (replace-match "from %f" t t fmt))))
6315 (org-replace-escapes fmt table)))
6316
6317 (defun org-make-org-heading-search-string (&optional string heading)
6318 "Make search string for STRING or current headline."
6319 (interactive)
6320 (let ((s (or string (org-get-heading))))
6321 (unless (and string (not heading))
6322 ;; We are using a headline, clean up garbage in there.
6323 (if (string-match org-todo-regexp s)
6324 (setq s (replace-match "" t t s)))
6325 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6326 (setq s (replace-match "" t t s)))
6327 (setq s (org-trim s))
6328 (if (string-match (concat "^\\(" org-quote-string "\\|"
6329 org-comment-string "\\)") s)
6330 (setq s (replace-match "" t t s)))
6331 (while (string-match org-ts-regexp s)
6332 (setq s (replace-match "" t t s))))
6333 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6334 (setq s (replace-match " " t t s)))
6335 (or string (setq s (concat "*" s))) ; Add * for headlines
6336 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6337
6338 (defun org-make-link (&rest strings)
6339 "Concatenate STRINGS."
6340 (apply 'concat strings))
6341
6342 (defun org-make-link-string (link &optional description)
6343 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6344 (unless (string-match "\\S-" link)
6345 (error "Empty link"))
6346 (when (stringp description)
6347 ;; Remove brackets from the description, they are fatal.
6348 (while (string-match "\\[" description)
6349 (setq description (replace-match "{" t t description)))
6350 (while (string-match "\\]" description)
6351 (setq description (replace-match "}" t t description))))
6352 (when (equal (org-link-escape link) description)
6353 ;; No description needed, it is identical
6354 (setq description nil))
6355 (when (and (not description)
6356 (not (equal link (org-link-escape link))))
6357 (setq description (org-extract-attributes link)))
6358 (concat "[[" (org-link-escape link) "]"
6359 (if description (concat "[" description "]") "")
6360 "]"))
6361
6362 (defconst org-link-escape-chars
6363 '((?\ . "%20")
6364 (?\[ . "%5B")
6365 (?\] . "%5D")
6366 (?\340 . "%E0") ; `a
6367 (?\342 . "%E2") ; ^a
6368 (?\347 . "%E7") ; ,c
6369 (?\350 . "%E8") ; `e
6370 (?\351 . "%E9") ; 'e
6371 (?\352 . "%EA") ; ^e
6372 (?\356 . "%EE") ; ^i
6373 (?\364 . "%F4") ; ^o
6374 (?\371 . "%F9") ; `u
6375 (?\373 . "%FB") ; ^u
6376 (?\; . "%3B")
6377 (?? . "%3F")
6378 (?= . "%3D")
6379 (?+ . "%2B")
6380 )
6381 "Association list of escapes for some characters problematic in links.
6382 This is the list that is used for internal purposes.")
6383
6384 (defconst org-link-escape-chars-browser
6385 '((?\ . "%20")) ; 32 for the SPC char
6386 "Association list of escapes for some characters problematic in links.
6387 This is the list that is used before handing over to the browser.")
6388
6389 (defun org-link-escape (text &optional table)
6390 "Escape characters in TEXT that are problematic for links."
6391 (setq table (or table org-link-escape-chars))
6392 (when text
6393 (let ((re (mapconcat (lambda (x) (regexp-quote
6394 (char-to-string (car x))))
6395 table "\\|")))
6396 (while (string-match re text)
6397 (setq text
6398 (replace-match
6399 (cdr (assoc (string-to-char (match-string 0 text))
6400 table))
6401 t t text)))
6402 text)))
6403
6404 (defun org-link-unescape (text &optional table)
6405 "Reverse the action of `org-link-escape'."
6406 (setq table (or table org-link-escape-chars))
6407 (when text
6408 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6409 table "\\|")))
6410 (while (string-match re text)
6411 (setq text
6412 (replace-match
6413 (char-to-string (car (rassoc (match-string 0 text) table)))
6414 t t text)))
6415 text)))
6416
6417 (defun org-xor (a b)
6418 "Exclusive or."
6419 (if a (not b) b))
6420
6421 (defun org-get-header (header)
6422 "Find a header field in the current buffer."
6423 (save-excursion
6424 (goto-char (point-min))
6425 (let ((case-fold-search t) s)
6426 (cond
6427 ((eq header 'from)
6428 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6429 (setq s (match-string 1)))
6430 (while (string-match "\"" s)
6431 (setq s (replace-match "" t t s)))
6432 (if (string-match "[<(].*" s)
6433 (setq s (replace-match "" t t s))))
6434 ((eq header 'message-id)
6435 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6436 (setq s (match-string 1))))
6437 ((eq header 'subject)
6438 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6439 (setq s (match-string 1)))))
6440 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6441 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6442 s)))
6443
6444
6445 (defun org-fixup-message-id-for-http (s)
6446 "Replace special characters in a message id, so it can be used in an http query."
6447 (while (string-match "<" s)
6448 (setq s (replace-match "%3C" t t s)))
6449 (while (string-match ">" s)
6450 (setq s (replace-match "%3E" t t s)))
6451 (while (string-match "@" s)
6452 (setq s (replace-match "%40" t t s)))
6453 s)
6454
6455 ;;;###autoload
6456 (defun org-insert-link-global ()
6457 "Insert a link like Org-mode does.
6458 This command can be called in any mode to insert a link in Org-mode syntax."
6459 (interactive)
6460 (org-load-modules-maybe)
6461 (org-run-like-in-org-mode 'org-insert-link))
6462
6463 (defun org-insert-link (&optional complete-file link-location)
6464 "Insert a link. At the prompt, enter the link.
6465
6466 Completion can be used to insert any of the link protocol prefixes like
6467 http or ftp in use.
6468
6469 The history can be used to select a link previously stored with
6470 `org-store-link'. When the empty string is entered (i.e. if you just
6471 press RET at the prompt), the link defaults to the most recently
6472 stored link. As SPC triggers completion in the minibuffer, you need to
6473 use M-SPC or C-q SPC to force the insertion of a space character.
6474
6475 You will also be prompted for a description, and if one is given, it will
6476 be displayed in the buffer instead of the link.
6477
6478 If there is already a link at point, this command will allow you to edit link
6479 and description parts.
6480
6481 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6482 be selected using completion. The path to the file will be relative to the
6483 current directory if the file is in the current directory or a subdirectory.
6484 Otherwise, the link will be the absolute path as completed in the minibuffer
6485 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6486 option `org-link-file-path-type'.
6487
6488 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6489 the current directory or below.
6490
6491 With three \\[universal-argument] prefixes, negate the meaning of
6492 `org-keep-stored-link-after-insertion'.
6493
6494 If `org-make-link-description-function' is non-nil, this function will be
6495 called with the link target, and the result will be the default
6496 link description.
6497
6498 If the LINK-LOCATION parameter is non-nil, this value will be
6499 used as the link location instead of reading one interactively."
6500 (interactive "P")
6501 (let* ((wcf (current-window-configuration))
6502 (region (if (org-region-active-p)
6503 (buffer-substring (region-beginning) (region-end))))
6504 (remove (and region (list (region-beginning) (region-end))))
6505 (desc region)
6506 tmphist ; byte-compile incorrectly complains about this
6507 (link link-location)
6508 entry file)
6509 (cond
6510 (link-location) ; specified by arg, just use it.
6511 ((org-in-regexp org-bracket-link-regexp 1)
6512 ;; We do have a link at point, and we are going to edit it.
6513 (setq remove (list (match-beginning 0) (match-end 0)))
6514 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6515 (setq link (read-string "Link: "
6516 (org-link-unescape
6517 (org-match-string-no-properties 1)))))
6518 ((or (org-in-regexp org-angle-link-re)
6519 (org-in-regexp org-plain-link-re))
6520 ;; Convert to bracket link
6521 (setq remove (list (match-beginning 0) (match-end 0))
6522 link (read-string "Link: "
6523 (org-remove-angle-brackets (match-string 0)))))
6524 ((member complete-file '((4) (16)))
6525 ;; Completing read for file names.
6526 (setq file (read-file-name "File: "))
6527 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6528 (pwd1 (file-name-as-directory (abbreviate-file-name
6529 (expand-file-name ".")))))
6530 (cond
6531 ((equal complete-file '(16))
6532 (setq link (org-make-link
6533 "file:"
6534 (abbreviate-file-name (expand-file-name file)))))
6535 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6536 (setq link (org-make-link "file:" (match-string 1 file))))
6537 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6538 (expand-file-name file))
6539 (setq link (org-make-link
6540 "file:" (match-string 1 (expand-file-name file)))))
6541 (t (setq link (org-make-link "file:" file))))))
6542 (t
6543 ;; Read link, with completion for stored links.
6544 (with-output-to-temp-buffer "*Org Links*"
6545 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6546 (when org-stored-links
6547 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6548 (princ (mapconcat
6549 (lambda (x)
6550 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6551 (reverse org-stored-links) "\n"))))
6552 (let ((cw (selected-window)))
6553 (select-window (get-buffer-window "*Org Links*"))
6554 (org-fit-window-to-buffer)
6555 (setq truncate-lines t)
6556 (select-window cw))
6557 ;; Fake a link history, containing the stored links.
6558 (setq tmphist (append (mapcar 'car org-stored-links)
6559 org-insert-link-history))
6560 (unwind-protect
6561 (setq link (org-completing-read
6562 "Link: "
6563 (append
6564 (mapcar (lambda (x) (list (concat (car x) ":")))
6565 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6566 (mapcar (lambda (x) (list (concat x ":")))
6567 org-link-types))
6568 nil nil nil
6569 'tmphist
6570 (or (car (car org-stored-links)))))
6571 (set-window-configuration wcf)
6572 (kill-buffer "*Org Links*"))
6573 (setq entry (assoc link org-stored-links))
6574 (or entry (push link org-insert-link-history))
6575 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6576 (not org-keep-stored-link-after-insertion))
6577 (setq org-stored-links (delq (assoc link org-stored-links)
6578 org-stored-links)))
6579 (setq desc (or desc (nth 1 entry)))))
6580
6581 (if (string-match org-plain-link-re link)
6582 ;; URL-like link, normalize the use of angular brackets.
6583 (setq link (org-make-link (org-remove-angle-brackets link))))
6584
6585 ;; Check if we are linking to the current file with a search option
6586 ;; If yes, simplify the link by using only the search option.
6587 (when (and buffer-file-name
6588 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6589 (let* ((path (match-string 1 link))
6590 (case-fold-search nil)
6591 (search (match-string 2 link)))
6592 (save-match-data
6593 (if (equal (file-truename buffer-file-name) (file-truename path))
6594 ;; We are linking to this same file, with a search option
6595 (setq link search)))))
6596
6597 ;; Check if we can/should use a relative path. If yes, simplify the link
6598 (when (string-match "^file:\\(.*\\)" link)
6599 (let* ((path (match-string 1 link))
6600 (origpath path)
6601 (case-fold-search nil))
6602 (cond
6603 ((or (eq org-link-file-path-type 'absolute)
6604 (equal complete-file '(16)))
6605 (setq path (abbreviate-file-name (expand-file-name path))))
6606 ((eq org-link-file-path-type 'noabbrev)
6607 (setq path (expand-file-name path)))
6608 ((eq org-link-file-path-type 'relative)
6609 (setq path (file-relative-name path)))
6610 (t
6611 (save-match-data
6612 (if (string-match (concat "^" (regexp-quote
6613 (file-name-as-directory
6614 (expand-file-name "."))))
6615 (expand-file-name path))
6616 ;; We are linking a file with relative path name.
6617 (setq path (substring (expand-file-name path)
6618 (match-end 0)))
6619 (setq path (abbreviate-file-name (expand-file-name path)))))))
6620 (setq link (concat "file:" path))
6621 (if (equal desc origpath)
6622 (setq desc path))))
6623
6624 (if org-make-link-description-function
6625 (setq desc (funcall org-make-link-description-function link desc)))
6626
6627 (setq desc (read-string "Description: " desc))
6628 (unless (string-match "\\S-" desc) (setq desc nil))
6629 (if remove (apply 'delete-region remove))
6630 (insert (org-make-link-string link desc))))
6631
6632 (defun org-completing-read (&rest args)
6633 "Completing-read with SPACE being a normal character."
6634 (let ((minibuffer-local-completion-map
6635 (copy-keymap minibuffer-local-completion-map)))
6636 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6637 (apply 'org-ido-completing-read args)))
6638
6639 (defun org-ido-completing-read (&rest args)
6640 "Completing-read using `ido-mode' speedups if available"
6641 (if (and org-completion-use-ido
6642 (fboundp 'ido-completing-read)
6643 (boundp 'ido-mode) ido-mode
6644 (listp (second args)))
6645 (apply 'ido-completing-read (concat (car args)) (cdr args))
6646 (apply 'completing-read args)))
6647
6648 (defun org-extract-attributes (s)
6649 "Extract the attributes cookie from a string and set as text property."
6650 (let (a attr (start 0) key value)
6651 (save-match-data
6652 (when (string-match "{{\\([^}]+\\)}}$" s)
6653 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6654 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6655 (setq key (match-string 1 a) value (match-string 2 a)
6656 start (match-end 0)
6657 attr (plist-put attr (intern key) value))))
6658 (org-add-props s nil 'org-attributes attr))
6659 s))
6660
6661 (defun org-attributes-to-string (plist)
6662 "Format a property list into an HTML attribute list."
6663 (let ((s "") key value)
6664 (while plist
6665 (setq key (pop plist) value (pop plist))
6666 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
6667 s))
6668
6669 ;;; Opening/following a link
6670
6671 (defvar org-link-search-failed nil)
6672
6673 (defun org-next-link ()
6674 "Move forward to the next link.
6675 If the link is in hidden text, expose it."
6676 (interactive)
6677 (when (and org-link-search-failed (eq this-command last-command))
6678 (goto-char (point-min))
6679 (message "Link search wrapped back to beginning of buffer"))
6680 (setq org-link-search-failed nil)
6681 (let* ((pos (point))
6682 (ct (org-context))
6683 (a (assoc :link ct)))
6684 (if a (goto-char (nth 2 a)))
6685 (if (re-search-forward org-any-link-re nil t)
6686 (progn
6687 (goto-char (match-beginning 0))
6688 (if (org-invisible-p) (org-show-context)))
6689 (goto-char pos)
6690 (setq org-link-search-failed t)
6691 (error "No further link found"))))
6692
6693 (defun org-previous-link ()
6694 "Move backward to the previous link.
6695 If the link is in hidden text, expose it."
6696 (interactive)
6697 (when (and org-link-search-failed (eq this-command last-command))
6698 (goto-char (point-max))
6699 (message "Link search wrapped back to end of buffer"))
6700 (setq org-link-search-failed nil)
6701 (let* ((pos (point))
6702 (ct (org-context))
6703 (a (assoc :link ct)))
6704 (if a (goto-char (nth 1 a)))
6705 (if (re-search-backward org-any-link-re nil t)
6706 (progn
6707 (goto-char (match-beginning 0))
6708 (if (org-invisible-p) (org-show-context)))
6709 (goto-char pos)
6710 (setq org-link-search-failed t)
6711 (error "No further link found"))))
6712
6713 (defun org-translate-link (s)
6714 "Translate a link string if a translation function has been defined."
6715 (if (and org-link-translation-function
6716 (fboundp org-link-translation-function)
6717 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
6718 (progn
6719 (setq s (funcall org-link-translation-function
6720 (match-string 1) (match-string 2)))
6721 (concat (car s) ":" (cdr s)))
6722 s))
6723
6724 (defun org-translate-link-from-planner (type path)
6725 "Translate a link from Emacs Planner syntax so that Org can follow it.
6726 This is still an experimental function, your mileage may vary."
6727 (cond
6728 ((member type '("http" "https" "news" "ftp"))
6729 ;; standard Internet links are the same.
6730 nil)
6731 ((and (equal type "irc") (string-match "^//" path))
6732 ;; Planner has two / at the beginning of an irc link, we have 1.
6733 ;; We should have zero, actually....
6734 (setq path (substring path 1)))
6735 ((and (equal type "lisp") (string-match "^/" path))
6736 ;; Planner has a slash, we do not.
6737 (setq type "elisp" path (substring path 1)))
6738 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
6739 ;; A typical message link. Planner has the id after the fina slash,
6740 ;; we separate it with a hash mark
6741 (setq path (concat (match-string 1 path) "#"
6742 (org-remove-angle-brackets (match-string 2 path)))))
6743 )
6744 (cons type path))
6745
6746 (defun org-find-file-at-mouse (ev)
6747 "Open file link or URL at mouse."
6748 (interactive "e")
6749 (mouse-set-point ev)
6750 (org-open-at-point 'in-emacs))
6751
6752 (defun org-open-at-mouse (ev)
6753 "Open file link or URL at mouse."
6754 (interactive "e")
6755 (mouse-set-point ev)
6756 (if (eq major-mode 'org-agenda-mode)
6757 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
6758 (org-open-at-point))
6759
6760 (defvar org-window-config-before-follow-link nil
6761 "The window configuration before following a link.
6762 This is saved in case the need arises to restore it.")
6763
6764 (defvar org-open-link-marker (make-marker)
6765 "Marker pointing to the location where `org-open-at-point; was called.")
6766
6767 ;;;###autoload
6768 (defun org-open-at-point-global ()
6769 "Follow a link like Org-mode does.
6770 This command can be called in any mode to follow a link that has
6771 Org-mode syntax."
6772 (interactive)
6773 (org-run-like-in-org-mode 'org-open-at-point))
6774
6775 ;;;###autoload
6776 (defun org-open-link-from-string (s &optional arg)
6777 "Open a link in the string S, as if it was in Org-mode."
6778 (interactive "sLink: \nP")
6779 (with-temp-buffer
6780 (let ((org-inhibit-startup t))
6781 (org-mode)
6782 (insert s)
6783 (goto-char (point-min))
6784 (org-open-at-point arg))))
6785
6786 (defun org-open-at-point (&optional in-emacs)
6787 "Open link at or after point.
6788 If there is no link at point, this function will search forward up to
6789 the end of the current subtree.
6790 Normally, files will be opened by an appropriate application. If the
6791 optional argument IN-EMACS is non-nil, Emacs will visit the file.
6792 With a double prefix argument, try to open outside of Emacs, in the
6793 application the system uses for this file type."
6794 (interactive "P")
6795 (org-load-modules-maybe)
6796 (move-marker org-open-link-marker (point))
6797 (setq org-window-config-before-follow-link (current-window-configuration))
6798 (org-remove-occur-highlights nil nil t)
6799 (if (org-at-timestamp-p t)
6800 (org-follow-timestamp-link)
6801 (let (type path link line search (pos (point)))
6802 (catch 'match
6803 (save-excursion
6804 (skip-chars-forward "^]\n\r")
6805 (when (org-in-regexp org-bracket-link-regexp)
6806 (setq link (org-extract-attributes
6807 (org-link-unescape (org-match-string-no-properties 1))))
6808 (while (string-match " *\n *" link)
6809 (setq link (replace-match " " t t link)))
6810 (setq link (org-link-expand-abbrev link))
6811 (cond
6812 ((or (file-name-absolute-p link)
6813 (string-match "^\\.\\.?/" link))
6814 (setq type "file" path link))
6815 ((string-match org-link-re-with-space3 link)
6816 (setq type (match-string 1 link) path (match-string 2 link)))
6817 (t (setq type "thisfile" path link)))
6818 (throw 'match t)))
6819
6820 (when (get-text-property (point) 'org-linked-text)
6821 (setq type "thisfile"
6822 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6823 (1+ (point)) (point))
6824 path (buffer-substring
6825 (previous-single-property-change pos 'org-linked-text)
6826 (next-single-property-change pos 'org-linked-text)))
6827 (throw 'match t))
6828
6829 (save-excursion
6830 (when (or (org-in-regexp org-angle-link-re)
6831 (org-in-regexp org-plain-link-re))
6832 (setq type (match-string 1) path (match-string 2))
6833 (throw 'match t)))
6834 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6835 (setq type "tree-match"
6836 path (match-string 1))
6837 (throw 'match t))
6838 (save-excursion
6839 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6840 (setq type "tags"
6841 path (match-string 1))
6842 (while (string-match ":" path)
6843 (setq path (replace-match "+" t t path)))
6844 (throw 'match t))))
6845 (unless path
6846 (error "No link found"))
6847 ;; Remove any trailing spaces in path
6848 (if (string-match " +\\'" path)
6849 (setq path (replace-match "" t t path)))
6850 (if (and org-link-translation-function
6851 (fboundp org-link-translation-function))
6852 ;; Check if we need to translate the link
6853 (let ((tmp (funcall org-link-translation-function type path)))
6854 (setq type (car tmp) path (cdr tmp))))
6855
6856 (cond
6857
6858 ((assoc type org-link-protocols)
6859 (funcall (nth 1 (assoc type org-link-protocols)) path))
6860
6861 ((equal type "mailto")
6862 (let ((cmd (car org-link-mailto-program))
6863 (args (cdr org-link-mailto-program)) args1
6864 (address path) (subject "") a)
6865 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6866 (setq address (match-string 1 path)
6867 subject (org-link-escape (match-string 2 path))))
6868 (while args
6869 (cond
6870 ((not (stringp (car args))) (push (pop args) args1))
6871 (t (setq a (pop args))
6872 (if (string-match "%a" a)
6873 (setq a (replace-match address t t a)))
6874 (if (string-match "%s" a)
6875 (setq a (replace-match subject t t a)))
6876 (push a args1))))
6877 (apply cmd (nreverse args1))))
6878
6879 ((member type '("http" "https" "ftp" "news"))
6880 (browse-url (concat type ":" (org-link-escape
6881 path org-link-escape-chars-browser))))
6882
6883 ((member type '("message"))
6884 (browse-url (concat type ":" path)))
6885
6886 ((string= type "tags")
6887 (org-tags-view in-emacs path))
6888 ((string= type "thisfile")
6889 (if in-emacs
6890 (switch-to-buffer-other-window
6891 (org-get-buffer-for-internal-link (current-buffer)))
6892 (org-mark-ring-push))
6893 (let ((cmd `(org-link-search
6894 ,path
6895 ,(cond ((equal in-emacs '(4)) 'occur)
6896 ((equal in-emacs '(16)) 'org-occur)
6897 (t nil))
6898 ,pos)))
6899 (condition-case nil (eval cmd)
6900 (error (progn (widen) (eval cmd))))))
6901
6902 ((string= type "tree-match")
6903 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6904
6905 ((string= type "file")
6906 (if (string-match "::\\([0-9]+\\)\\'" path)
6907 (setq line (string-to-number (match-string 1 path))
6908 path (substring path 0 (match-beginning 0)))
6909 (if (string-match "::\\(.+\\)\\'" path)
6910 (setq search (match-string 1 path)
6911 path (substring path 0 (match-beginning 0)))))
6912 (if (string-match "[*?{]" (file-name-nondirectory path))
6913 (dired path)
6914 (org-open-file path in-emacs line search)))
6915
6916 ((string= type "news")
6917 (require 'org-gnus)
6918 (org-gnus-follow-link path))
6919
6920 ((string= type "shell")
6921 (let ((cmd path))
6922 (if (or (not org-confirm-shell-link-function)
6923 (funcall org-confirm-shell-link-function
6924 (format "Execute \"%s\" in shell? "
6925 (org-add-props cmd nil
6926 'face 'org-warning))))
6927 (progn
6928 (message "Executing %s" cmd)
6929 (shell-command cmd))
6930 (error "Abort"))))
6931
6932 ((string= type "elisp")
6933 (let ((cmd path))
6934 (if (or (not org-confirm-elisp-link-function)
6935 (funcall org-confirm-elisp-link-function
6936 (format "Execute \"%s\" as elisp? "
6937 (org-add-props cmd nil
6938 'face 'org-warning))))
6939 (message "%s => %s" cmd
6940 (if (equal (string-to-char cmd) ?\()
6941 (eval (read cmd))
6942 (call-interactively (read cmd))))
6943 (error "Abort"))))
6944
6945 (t
6946 (browse-url-at-point)))))
6947 (move-marker org-open-link-marker nil)
6948 (run-hook-with-args 'org-follow-link-hook))
6949
6950 ;;;; Time estimates
6951
6952 (defun org-get-effort (&optional pom)
6953 "Get the effort estimate for the current entry."
6954 (org-entry-get pom org-effort-property))
6955
6956 ;;; File search
6957
6958 (defvar org-create-file-search-functions nil
6959 "List of functions to construct the right search string for a file link.
6960 These functions are called in turn with point at the location to
6961 which the link should point.
6962
6963 A function in the hook should first test if it would like to
6964 handle this file type, for example by checking the major-mode or
6965 the file extension. If it decides not to handle this file, it
6966 should just return nil to give other functions a chance. If it
6967 does handle the file, it must return the search string to be used
6968 when following the link. The search string will be part of the
6969 file link, given after a double colon, and `org-open-at-point'
6970 will automatically search for it. If special measures must be
6971 taken to make the search successful, another function should be
6972 added to the companion hook `org-execute-file-search-functions',
6973 which see.
6974
6975 A function in this hook may also use `setq' to set the variable
6976 `description' to provide a suggestion for the descriptive text to
6977 be used for this link when it gets inserted into an Org-mode
6978 buffer with \\[org-insert-link].")
6979
6980 (defvar org-execute-file-search-functions nil
6981 "List of functions to execute a file search triggered by a link.
6982
6983 Functions added to this hook must accept a single argument, the
6984 search string that was part of the file link, the part after the
6985 double colon. The function must first check if it would like to
6986 handle this search, for example by checking the major-mode or the
6987 file extension. If it decides not to handle this search, it
6988 should just return nil to give other functions a chance. If it
6989 does handle the search, it must return a non-nil value to keep
6990 other functions from trying.
6991
6992 Each function can access the current prefix argument through the
6993 variable `current-prefix-argument'. Note that a single prefix is
6994 used to force opening a link in Emacs, so it may be good to only
6995 use a numeric or double prefix to guide the search function.
6996
6997 In case this is needed, a function in this hook can also restore
6998 the window configuration before `org-open-at-point' was called using:
6999
7000 (set-window-configuration org-window-config-before-follow-link)")
7001
7002 (defun org-link-search (s &optional type avoid-pos)
7003 "Search for a link search option.
7004 If S is surrounded by forward slashes, it is interpreted as a
7005 regular expression. In org-mode files, this will create an `org-occur'
7006 sparse tree. In ordinary files, `occur' will be used to list matches.
7007 If the current buffer is in `dired-mode', grep will be used to search
7008 in all files. If AVOID-POS is given, ignore matches near that position."
7009 (let ((case-fold-search t)
7010 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7011 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7012 (append '(("") (" ") ("\t") ("\n"))
7013 org-emphasis-alist)
7014 "\\|") "\\)"))
7015 (pos (point))
7016 (pre nil) (post nil)
7017 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7018 (cond
7019 ;; First check if there are any special
7020 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7021 ;; Now try the builtin stuff
7022 ((save-excursion
7023 (goto-char (point-min))
7024 (and
7025 (re-search-forward
7026 (concat "<<" (regexp-quote s0) ">>") nil t)
7027 (setq type 'dedicated
7028 pos (match-beginning 0))))
7029 ;; There is an exact target for this
7030 (goto-char pos))
7031 ((string-match "^/\\(.*\\)/$" s)
7032 ;; A regular expression
7033 (cond
7034 ((org-mode-p)
7035 (org-occur (match-string 1 s)))
7036 ;;((eq major-mode 'dired-mode)
7037 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7038 (t (org-do-occur (match-string 1 s)))))
7039 (t
7040 ;; A normal search strings
7041 (when (equal (string-to-char s) ?*)
7042 ;; Anchor on headlines, post may include tags.
7043 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7044 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7045 s (substring s 1)))
7046 (remove-text-properties
7047 0 (length s)
7048 '(face nil mouse-face nil keymap nil fontified nil) s)
7049 ;; Make a series of regular expressions to find a match
7050 (setq words (org-split-string s "[ \n\r\t]+")
7051
7052 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7053 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7054 "\\)" markers)
7055 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7056 re2a (concat "[ \t\r\n]" re2a_)
7057 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7058 re4 (concat "[^a-zA-Z_]" re4_)
7059
7060 re1 (concat pre re2 post)
7061 re3 (concat pre (if pre re4_ re4) post)
7062 re5 (concat pre ".*" re4)
7063 re2 (concat pre re2)
7064 re2a (concat pre (if pre re2a_ re2a))
7065 re4 (concat pre (if pre re4_ re4))
7066 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7067 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7068 re5 "\\)"
7069 ))
7070 (cond
7071 ((eq type 'org-occur) (org-occur reall))
7072 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7073 (t (goto-char (point-min))
7074 (setq type 'fuzzy)
7075 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7076 (org-search-not-self 1 re1 nil t)
7077 (org-search-not-self 1 re2 nil t)
7078 (org-search-not-self 1 re2a nil t)
7079 (org-search-not-self 1 re3 nil t)
7080 (org-search-not-self 1 re4 nil t)
7081 (org-search-not-self 1 re5 nil t)
7082 )
7083 (goto-char (match-beginning 1))
7084 (goto-char pos)
7085 (error "No match")))))
7086 (t
7087 ;; Normal string-search
7088 (goto-char (point-min))
7089 (if (search-forward s nil t)
7090 (goto-char (match-beginning 0))
7091 (error "No match"))))
7092 (and (org-mode-p) (org-show-context 'link-search))
7093 type))
7094
7095 (defun org-search-not-self (group &rest args)
7096 "Execute `re-search-forward', but only accept matches that do not
7097 enclose the position of `org-open-link-marker'."
7098 (let ((m org-open-link-marker))
7099 (catch 'exit
7100 (while (apply 're-search-forward args)
7101 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7102 (goto-char (match-end group))
7103 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7104 (> (match-beginning 0) (marker-position m))
7105 (< (match-end 0) (marker-position m)))
7106 (save-match-data
7107 (or (not (org-in-regexp
7108 org-bracket-link-analytic-regexp 1))
7109 (not (match-end 4)) ; no description
7110 (and (<= (match-beginning 4) (point))
7111 (>= (match-end 4) (point))))))
7112 (throw 'exit (point))))))))
7113
7114 (defun org-get-buffer-for-internal-link (buffer)
7115 "Return a buffer to be used for displaying the link target of internal links."
7116 (cond
7117 ((not org-display-internal-link-with-indirect-buffer)
7118 buffer)
7119 ((string-match "(Clone)$" (buffer-name buffer))
7120 (message "Buffer is already a clone, not making another one")
7121 ;; we also do not modify visibility in this case
7122 buffer)
7123 (t ; make a new indirect buffer for displaying the link
7124 (let* ((bn (buffer-name buffer))
7125 (ibn (concat bn "(Clone)"))
7126 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7127 (with-current-buffer ib (org-overview))
7128 ib))))
7129
7130 (defun org-do-occur (regexp &optional cleanup)
7131 "Call the Emacs command `occur'.
7132 If CLEANUP is non-nil, remove the printout of the regular expression
7133 in the *Occur* buffer. This is useful if the regex is long and not useful
7134 to read."
7135 (occur regexp)
7136 (when cleanup
7137 (let ((cwin (selected-window)) win beg end)
7138 (when (setq win (get-buffer-window "*Occur*"))
7139 (select-window win))
7140 (goto-char (point-min))
7141 (when (re-search-forward "match[a-z]+" nil t)
7142 (setq beg (match-end 0))
7143 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7144 (setq end (1- (match-beginning 0)))))
7145 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7146 (goto-char (point-min))
7147 (select-window cwin))))
7148
7149 ;;; The mark ring for links jumps
7150
7151 (defvar org-mark-ring nil
7152 "Mark ring for positions before jumps in Org-mode.")
7153 (defvar org-mark-ring-last-goto nil
7154 "Last position in the mark ring used to go back.")
7155 ;; Fill and close the ring
7156 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7157 (loop for i from 1 to org-mark-ring-length do
7158 (push (make-marker) org-mark-ring))
7159 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7160 org-mark-ring)
7161
7162 (defun org-mark-ring-push (&optional pos buffer)
7163 "Put the current position or POS into the mark ring and rotate it."
7164 (interactive)
7165 (setq pos (or pos (point)))
7166 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7167 (move-marker (car org-mark-ring)
7168 (or pos (point))
7169 (or buffer (current-buffer)))
7170 (message "%s"
7171 (substitute-command-keys
7172 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7173
7174 (defun org-mark-ring-goto (&optional n)
7175 "Jump to the previous position in the mark ring.
7176 With prefix arg N, jump back that many stored positions. When
7177 called several times in succession, walk through the entire ring.
7178 Org-mode commands jumping to a different position in the current file,
7179 or to another Org-mode file, automatically push the old position
7180 onto the ring."
7181 (interactive "p")
7182 (let (p m)
7183 (if (eq last-command this-command)
7184 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7185 (setq p org-mark-ring))
7186 (setq org-mark-ring-last-goto p)
7187 (setq m (car p))
7188 (switch-to-buffer (marker-buffer m))
7189 (goto-char m)
7190 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7191
7192 (defun org-remove-angle-brackets (s)
7193 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7194 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7195 s)
7196 (defun org-add-angle-brackets (s)
7197 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7198 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7199 s)
7200 (defun org-remove-double-quotes (s)
7201 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7202 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7203 s)
7204
7205 ;;; Following specific links
7206
7207 (defun org-follow-timestamp-link ()
7208 (cond
7209 ((org-at-date-range-p t)
7210 (let ((org-agenda-start-on-weekday)
7211 (t1 (match-string 1))
7212 (t2 (match-string 2)))
7213 (setq t1 (time-to-days (org-time-string-to-time t1))
7214 t2 (time-to-days (org-time-string-to-time t2)))
7215 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7216 ((org-at-timestamp-p t)
7217 (org-agenda-list nil (time-to-days (org-time-string-to-time
7218 (substring (match-string 1) 0 10)))
7219 1))
7220 (t (error "This should not happen"))))
7221
7222
7223 ;;; Following file links
7224 (defvar org-wait nil)
7225 (defun org-open-file (path &optional in-emacs line search)
7226 "Open the file at PATH.
7227 First, this expands any special file name abbreviations. Then the
7228 configuration variable `org-file-apps' is checked if it contains an
7229 entry for this file type, and if yes, the corresponding command is launched.
7230
7231 If no application is found, Emacs simply visits the file.
7232
7233 With optional prefix argument IN-EMACS, Emacs will visit the file.
7234 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7235 and o use an external application to visit the file.
7236
7237 Optional LINE specifies a line to go to, optional SEARCH a string to
7238 search for. If LINE or SEARCH is given, the file will always be
7239 opened in Emacs.
7240 If the file does not exist, an error is thrown."
7241 (setq in-emacs (or in-emacs line search))
7242 (let* ((file (if (equal path "")
7243 buffer-file-name
7244 (substitute-in-file-name (expand-file-name path))))
7245 (apps (append org-file-apps (org-default-apps)))
7246 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7247 (dirp (if remp nil (file-directory-p file)))
7248 (file (if (and dirp org-open-directory-means-index-dot-org)
7249 (concat (file-name-as-directory file) "index.org")
7250 file))
7251 (a-m-a-p (assq 'auto-mode apps))
7252 (dfile (downcase file))
7253 (old-buffer (current-buffer))
7254 (old-pos (point))
7255 (old-mode major-mode)
7256 ext cmd)
7257 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7258 (setq ext (match-string 1 dfile))
7259 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7260 (setq ext (match-string 1 dfile))))
7261 (cond
7262 ((equal in-emacs '(16))
7263 (setq cmd (cdr (assoc 'system apps))))
7264 (in-emacs (setq cmd 'emacs))
7265 (t
7266 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7267 (and dirp (cdr (assoc 'directory apps)))
7268 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7269 'string-match)
7270 (cdr (assoc ext apps))
7271 (cdr (assoc t apps))))))
7272 (when (eq cmd 'system)
7273 (setq cmd (cdr (assoc 'system apps))))
7274 (when (eq cmd 'default)
7275 (setq cmd (cdr (assoc t apps))))
7276 (when (eq cmd 'mailcap)
7277 (require 'mailcap)
7278 (mailcap-parse-mailcaps)
7279 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7280 (command (mailcap-mime-info mime-type)))
7281 (if (stringp command)
7282 (setq cmd command)
7283 (setq cmd 'emacs))))
7284 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7285 (not (file-exists-p file))
7286 (not org-open-non-existing-files))
7287 (error "No such file: %s" file))
7288 (cond
7289 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7290 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7291 (while (string-match "['\"]%s['\"]" cmd)
7292 (setq cmd (replace-match "%s" t t cmd)))
7293 (while (string-match "%s" cmd)
7294 (setq cmd (replace-match
7295 (save-match-data
7296 (shell-quote-argument
7297 (convert-standard-filename file)))
7298 t t cmd)))
7299 (save-window-excursion
7300 (start-process-shell-command cmd nil cmd)
7301 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7302 ))
7303 ((or (stringp cmd)
7304 (eq cmd 'emacs))
7305 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7306 (widen)
7307 (if line (goto-line line)
7308 (if search (org-link-search search))))
7309 ((consp cmd)
7310 (let ((file (convert-standard-filename file)))
7311 (eval cmd)))
7312 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7313 (and (org-mode-p) (eq old-mode 'org-mode)
7314 (or (not (equal old-buffer (current-buffer)))
7315 (not (equal old-pos (point))))
7316 (org-mark-ring-push old-pos old-buffer))))
7317
7318 (defun org-default-apps ()
7319 "Return the default applications for this operating system."
7320 (cond
7321 ((eq system-type 'darwin)
7322 org-file-apps-defaults-macosx)
7323 ((eq system-type 'windows-nt)
7324 org-file-apps-defaults-windowsnt)
7325 (t org-file-apps-defaults-gnu)))
7326
7327 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7328 "Convert extensions to regular expressions in the cars of LIST.
7329 Also, weed out any non-string entries, because the return value is used
7330 only for regexp matching.
7331 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7332 point to the symbol `emacs', indicating that the file should
7333 be opened in Emacs."
7334 (append
7335 (delq nil
7336 (mapcar (lambda (x)
7337 (if (not (stringp (car x)))
7338 nil
7339 (if (string-match "\\W" (car x))
7340 x
7341 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7342 list))
7343 (if add-auto-mode
7344 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7345
7346 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7347 (defun org-file-remote-p (file)
7348 "Test whether FILE specifies a location on a remote system.
7349 Return non-nil if the location is indeed remote.
7350
7351 For example, the filename \"/user@host:/foo\" specifies a location
7352 on the system \"/user@host:\"."
7353 (cond ((fboundp 'file-remote-p)
7354 (file-remote-p file))
7355 ((fboundp 'tramp-handle-file-remote-p)
7356 (tramp-handle-file-remote-p file))
7357 ((and (boundp 'ange-ftp-name-format)
7358 (string-match (car ange-ftp-name-format) file))
7359 t)
7360 (t nil)))
7361
7362
7363 ;;;; Refiling
7364
7365 (defun org-get-org-file ()
7366 "Read a filename, with default directory `org-directory'."
7367 (let ((default (or org-default-notes-file remember-data-file)))
7368 (read-file-name (format "File name [%s]: " default)
7369 (file-name-as-directory org-directory)
7370 default)))
7371
7372 (defun org-notes-order-reversed-p ()
7373 "Check if the current file should receive notes in reversed order."
7374 (cond
7375 ((not org-reverse-note-order) nil)
7376 ((eq t org-reverse-note-order) t)
7377 ((not (listp org-reverse-note-order)) nil)
7378 (t (catch 'exit
7379 (let ((all org-reverse-note-order)
7380 entry)
7381 (while (setq entry (pop all))
7382 (if (string-match (car entry) buffer-file-name)
7383 (throw 'exit (cdr entry))))
7384 nil)))))
7385
7386 (defvar org-refile-target-table nil
7387 "The list of refile targets, created by `org-refile'.")
7388
7389 (defvar org-agenda-new-buffers nil
7390 "Buffers created to visit agenda files.")
7391
7392 (defun org-get-refile-targets (&optional default-buffer)
7393 "Produce a table with refile targets."
7394 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7395 targets txt re files f desc descre)
7396 (with-current-buffer (or default-buffer (current-buffer))
7397 (while (setq entry (pop entries))
7398 (setq files (car entry) desc (cdr entry))
7399 (cond
7400 ((null files) (setq files (list (current-buffer))))
7401 ((eq files 'org-agenda-files)
7402 (setq files (org-agenda-files 'unrestricted)))
7403 ((and (symbolp files) (fboundp files))
7404 (setq files (funcall files)))
7405 ((and (symbolp files) (boundp files))
7406 (setq files (symbol-value files))))
7407 (if (stringp files) (setq files (list files)))
7408 (cond
7409 ((eq (car desc) :tag)
7410 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7411 ((eq (car desc) :todo)
7412 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7413 ((eq (car desc) :regexp)
7414 (setq descre (cdr desc)))
7415 ((eq (car desc) :level)
7416 (setq descre (concat "^\\*\\{" (number-to-string
7417 (if org-odd-levels-only
7418 (1- (* 2 (cdr desc)))
7419 (cdr desc)))
7420 "\\}[ \t]")))
7421 ((eq (car desc) :maxlevel)
7422 (setq descre (concat "^\\*\\{1," (number-to-string
7423 (if org-odd-levels-only
7424 (1- (* 2 (cdr desc)))
7425 (cdr desc)))
7426 "\\}[ \t]")))
7427 (t (error "Bad refiling target description %s" desc)))
7428 (while (setq f (pop files))
7429 (save-excursion
7430 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7431 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7432 (save-excursion
7433 (save-restriction
7434 (widen)
7435 (goto-char (point-min))
7436 (while (re-search-forward descre nil t)
7437 (goto-char (point-at-bol))
7438 (when (looking-at org-complex-heading-regexp)
7439 (setq txt (org-link-display-format (match-string 4))
7440 re (concat "^" (regexp-quote
7441 (buffer-substring (match-beginning 1)
7442 (match-end 4)))))
7443 (if (match-end 5) (setq re (concat re "[ \t]+"
7444 (regexp-quote
7445 (match-string 5)))))
7446 (setq re (concat re "[ \t]*$"))
7447 (when org-refile-use-outline-path
7448 (setq txt (mapconcat 'org-protect-slash
7449 (append
7450 (if (eq org-refile-use-outline-path 'file)
7451 (list (file-name-nondirectory
7452 (buffer-file-name (buffer-base-buffer))))
7453 (if (eq org-refile-use-outline-path 'full-file-path)
7454 (list (buffer-file-name (buffer-base-buffer)))))
7455 (org-get-outline-path)
7456 (list txt))
7457 "/")))
7458 (push (list txt f re (point)) targets))
7459 (goto-char (point-at-eol))))))))
7460 (nreverse targets))))
7461
7462 (defun org-protect-slash (s)
7463 (while (string-match "/" s)
7464 (setq s (replace-match "\\" t t s)))
7465 s)
7466
7467 (defun org-get-outline-path ()
7468 "Return the outline path to the current entry, as a list."
7469 (let (rtn)
7470 (save-excursion
7471 (while (org-up-heading-safe)
7472 (when (looking-at org-complex-heading-regexp)
7473 (push (org-match-string-no-properties 4) rtn)))
7474 rtn)))
7475
7476 (defvar org-refile-history nil
7477 "History for refiling operations.")
7478
7479 (defun org-refile (&optional goto default-buffer)
7480 "Move the entry at point to another heading.
7481 The list of target headings is compiled using the information in
7482 `org-refile-targets', which see. This list is created before each use
7483 and will therefore always be up-to-date.
7484
7485 At the target location, the entry is filed as a subitem of the target heading.
7486 Depending on `org-reverse-note-order', the new subitem will either be the
7487 first or the last subitem.
7488
7489 If there is an active region, all entries in that region will be moved.
7490 However, the region must fulfil the requirement that the first heading
7491 is the first one sets the top-level of the moved text - at most siblings
7492 below it are allowed.
7493
7494 With prefix arg GOTO, the command will only visit the target location,
7495 not actually move anything.
7496 With a double prefix `C-u C-u', go to the location where the last refiling
7497 operation has put the subtree."
7498 (interactive "P")
7499 (let* ((cbuf (current-buffer))
7500 (regionp (org-region-active-p))
7501 (region-start (and regionp (region-beginning)))
7502 (region-end (and regionp (region-end)))
7503 (region-length (and regionp (- region-end region-start)))
7504 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7505 pos it nbuf file re level reversed)
7506 (when regionp (goto-char region-start)
7507 (unless (org-kill-is-subtree-p
7508 (buffer-substring region-start region-end))
7509 (error "The region is not a (sequence of) subtree(s)")))
7510 (if (equal goto '(16))
7511 (org-refile-goto-last-stored)
7512 (when (setq it (org-refile-get-location
7513 (if goto "Goto: " "Refile to: ") default-buffer))
7514 (setq file (nth 1 it)
7515 re (nth 2 it)
7516 pos (nth 3 it))
7517 (setq nbuf (or (find-buffer-visiting file)
7518 (find-file-noselect file)))
7519 (if goto
7520 (progn
7521 (switch-to-buffer nbuf)
7522 (goto-char pos)
7523 (org-show-context 'org-goto))
7524 (if regionp
7525 (progn
7526 (kill-new (buffer-substring region-start region-end))
7527 (org-save-markers-in-region region-start region-end))
7528 (org-copy-subtree 1 nil t))
7529 (save-excursion
7530 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7531 (find-file-noselect file))))
7532 (setq reversed (org-notes-order-reversed-p))
7533 (save-excursion
7534 (save-restriction
7535 (widen)
7536 (goto-char pos)
7537 (looking-at outline-regexp)
7538 (setq level (org-get-valid-level (funcall outline-level) 1))
7539 (goto-char
7540 (if reversed
7541 (or (outline-next-heading) (point-max))
7542 (or (save-excursion (outline-get-next-sibling))
7543 (org-end-of-subtree t t)
7544 (point-max))))
7545 (if (not (bolp)) (newline))
7546 (bookmark-set "org-refile-last-stored")
7547 (org-paste-subtree level))))
7548 (if regionp
7549 (delete-region (point) (+ (point) region-length))
7550 (org-cut-subtree))
7551 (setq org-markers-to-move nil)
7552 (message "Refiled to \"%s\"" (car it)))))))
7553
7554 (defun org-refile-goto-last-stored ()
7555 "Go to the location where the last refile was stored."
7556 (interactive)
7557 (bookmark-jump "org-refile-last-stored")
7558 (message "This is the location of the last refile"))
7559
7560 (defun org-refile-get-location (&optional prompt default-buffer)
7561 "Prompt the user for a refile location, using PROMPT."
7562 (let ((org-refile-targets org-refile-targets)
7563 (org-refile-use-outline-path org-refile-use-outline-path))
7564 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7565 (unless org-refile-target-table
7566 (error "No refile targets"))
7567 (let* ((cbuf (current-buffer))
7568 (cfunc (if (and org-refile-use-outline-path
7569 org-outline-path-complete-in-steps)
7570 'org-olpath-completing-read
7571 'org-ido-completing-read))
7572 (extra (if org-refile-use-outline-path "/" ""))
7573 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7574 (fname (and filename (file-truename filename)))
7575 (tbl (mapcar
7576 (lambda (x)
7577 (if (not (equal fname (file-truename (nth 1 x))))
7578 (cons (concat (car x) extra " ("
7579 (file-name-nondirectory (nth 1 x)) ")")
7580 (cdr x))
7581 (cons (concat (car x) extra) (cdr x))))
7582 org-refile-target-table))
7583 (completion-ignore-case t))
7584 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7585 tbl)))
7586
7587 (defun org-olpath-completing-read (prompt collection &rest args)
7588 "Read an outline path like a file name."
7589 (let ((thetable collection))
7590 (apply
7591 'org-ido-completing-read prompt
7592 (lambda (string predicate &optional flag)
7593 (let (rtn r s f (l (length string)))
7594 (cond
7595 ((eq flag nil)
7596 ;; try completion
7597 (try-completion string thetable))
7598 ((eq flag t)
7599 ;; all-completions
7600 (setq rtn (all-completions string thetable predicate))
7601 (mapcar
7602 (lambda (x)
7603 (setq r (substring x l))
7604 (if (string-match " ([^)]*)$" x)
7605 (setq f (match-string 0 x))
7606 (setq f ""))
7607 (if (string-match "/" r)
7608 (concat string (substring r 0 (match-end 0)) f)
7609 x))
7610 rtn))
7611 ((eq flag 'lambda)
7612 ;; exact match?
7613 (assoc string thetable)))
7614 ))
7615 args)))
7616
7617 ;;;; Dynamic blocks
7618
7619 (defun org-find-dblock (name)
7620 "Find the first dynamic block with name NAME in the buffer.
7621 If not found, stay at current position and return nil."
7622 (let (pos)
7623 (save-excursion
7624 (goto-char (point-min))
7625 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7626 nil t)
7627 (match-beginning 0))))
7628 (if pos (goto-char pos))
7629 pos))
7630
7631 (defconst org-dblock-start-re
7632 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7633 "Matches the startline of a dynamic block, with parameters.")
7634
7635 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7636 "Matches the end of a dyhamic block.")
7637
7638 (defun org-create-dblock (plist)
7639 "Create a dynamic block section, with parameters taken from PLIST.
7640 PLIST must containe a :name entry which is used as name of the block."
7641 (unless (bolp) (newline))
7642 (let ((name (plist-get plist :name)))
7643 (insert "#+BEGIN: " name)
7644 (while plist
7645 (if (eq (car plist) :name)
7646 (setq plist (cddr plist))
7647 (insert " " (prin1-to-string (pop plist)))))
7648 (insert "\n\n#+END:\n")
7649 (beginning-of-line -2)))
7650
7651 (defun org-prepare-dblock ()
7652 "Prepare dynamic block for refresh.
7653 This empties the block, puts the cursor at the insert position and returns
7654 the property list including an extra property :name with the block name."
7655 (unless (looking-at org-dblock-start-re)
7656 (error "Not at a dynamic block"))
7657 (let* ((begdel (1+ (match-end 0)))
7658 (name (org-no-properties (match-string 1)))
7659 (params (append (list :name name)
7660 (read (concat "(" (match-string 3) ")")))))
7661 (unless (re-search-forward org-dblock-end-re nil t)
7662 (error "Dynamic block not terminated"))
7663 (setq params
7664 (append params
7665 (list :content (buffer-substring
7666 begdel (match-beginning 0)))))
7667 (delete-region begdel (match-beginning 0))
7668 (goto-char begdel)
7669 (open-line 1)
7670 params))
7671
7672 (defun org-map-dblocks (&optional command)
7673 "Apply COMMAND to all dynamic blocks in the current buffer.
7674 If COMMAND is not given, use `org-update-dblock'."
7675 (let ((cmd (or command 'org-update-dblock))
7676 pos)
7677 (save-excursion
7678 (goto-char (point-min))
7679 (while (re-search-forward org-dblock-start-re nil t)
7680 (goto-char (setq pos (match-beginning 0)))
7681 (condition-case nil
7682 (funcall cmd)
7683 (error (message "Error during update of dynamic block")))
7684 (goto-char pos)
7685 (unless (re-search-forward org-dblock-end-re nil t)
7686 (error "Dynamic block not terminated"))))))
7687
7688 (defun org-dblock-update (&optional arg)
7689 "User command for updating dynamic blocks.
7690 Update the dynamic block at point. With prefix ARG, update all dynamic
7691 blocks in the buffer."
7692 (interactive "P")
7693 (if arg
7694 (org-update-all-dblocks)
7695 (or (looking-at org-dblock-start-re)
7696 (org-beginning-of-dblock))
7697 (org-update-dblock)))
7698
7699 (defun org-update-dblock ()
7700 "Update the dynamic block at point
7701 This means to empty the block, parse for parameters and then call
7702 the correct writing function."
7703 (save-window-excursion
7704 (let* ((pos (point))
7705 (line (org-current-line))
7706 (params (org-prepare-dblock))
7707 (name (plist-get params :name))
7708 (cmd (intern (concat "org-dblock-write:" name))))
7709 (message "Updating dynamic block `%s' at line %d..." name line)
7710 (funcall cmd params)
7711 (message "Updating dynamic block `%s' at line %d...done" name line)
7712 (goto-char pos))))
7713
7714 (defun org-beginning-of-dblock ()
7715 "Find the beginning of the dynamic block at point.
7716 Error if there is no scuh block at point."
7717 (let ((pos (point))
7718 beg)
7719 (end-of-line 1)
7720 (if (and (re-search-backward org-dblock-start-re nil t)
7721 (setq beg (match-beginning 0))
7722 (re-search-forward org-dblock-end-re nil t)
7723 (> (match-end 0) pos))
7724 (goto-char beg)
7725 (goto-char pos)
7726 (error "Not in a dynamic block"))))
7727
7728 (defun org-update-all-dblocks ()
7729 "Update all dynamic blocks in the buffer.
7730 This function can be used in a hook."
7731 (when (org-mode-p)
7732 (org-map-dblocks 'org-update-dblock)))
7733
7734
7735 ;;;; Completion
7736
7737 (defconst org-additional-option-like-keywords
7738 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7739 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7740 "BEGIN_EXAMPLE" "END_EXAMPLE"
7741 "BEGIN_QUOTE" "END_QUOTE"
7742 "BEGIN_VERSE" "END_VERSE"
7743 "BEGIN_SRC" "END_SRC"))
7744
7745 (defcustom org-structure-template-alist
7746 '(
7747 ("s" "#+begin_src ?\n\n#+end_src"
7748 "<src lang=\"?\">\n\n</src>")
7749 ("e" "#+begin_example\n?\n#+end_example"
7750 "<example>\n?\n</example>")
7751 ("q" "#+begin_quote\n?\n#+end_quote"
7752 "<quote>\n?\n</quote>")
7753 ("v" "#+begin_verse\n?\n#+end_verse"
7754 "<verse>\n?\n/verse>")
7755 ("l" "#+begin_latex\n?\n#+end_latex"
7756 "<literal style=\"latex\">\n?\n</literal>")
7757 ("L" "#+latex: "
7758 "<literal style=\"latex\">?</literal>")
7759 ("h" "#+begin_html\n?\n#+end_html"
7760 "<literal style=\"html\">\n?\n</literal>")
7761 ("H" "#+html: "
7762 "<literal style=\"html\">?</literal>")
7763 ("a" "#+begin_ascii\n?\n#+end_ascii")
7764 ("A" "#+ascii: ")
7765 ("i" "#+include %file ?"
7766 "<include file=%file markup=\"?\">")
7767 )
7768 "Structure completion elements.
7769 This is a list of abbreviation keys and values. The value gets inserted
7770 it you type @samp{.} followed by the key and then the completion key,
7771 usually `M-TAB'. %file will be replaced by a file name after prompting
7772 for the file uning completion.
7773 There are two templates for each key, the first uses the original Org syntax,
7774 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
7775 the default when the /org-mtags.el/ module has been loaded. See also the
7776 variable `org-mtags-prefer-muse-templates'.
7777 This is an experimental feature, it is undecided if it is going to stay in."
7778 :group 'org-completion
7779 :type '(repeat
7780 (string :tag "Key")
7781 (string :tag "Template")
7782 (string :tag "Muse Template")))
7783
7784 (defun org-try-structure-completion ()
7785 "Try to complete a structure template before point.
7786 This looks for strings like \"<e\" on an otherwise empty line and
7787 expands them."
7788 (let ((l (buffer-substring (point-at-bol) (point)))
7789 a)
7790 (when (and (looking-at "[ \t]*$")
7791 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
7792 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
7793 (org-complete-expand-structure-template (+ -1 (point-at-bol)
7794 (match-beginning 1)) a)
7795 t)))
7796
7797 (defun org-complete-expand-structure-template (start cell)
7798 "Expand a structure template."
7799 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
7800 (rpl (nth (if musep 2 1) cell)))
7801 (delete-region start (point))
7802 (when (string-match "\\`#\\+" rpl)
7803 (cond
7804 ((bolp))
7805 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
7806 (delete-region (point-at-bol) (point)))
7807 (t (newline))))
7808 (setq start (point))
7809 (if (string-match "%file" rpl)
7810 (setq rpl (replace-match
7811 (concat
7812 "\""
7813 (save-match-data
7814 (abbreviate-file-name (read-file-name "Include file: ")))
7815 "\"")
7816 t t rpl)))
7817 (insert rpl)
7818 (if (re-search-backward "\\?" start t) (delete-char 1))))
7819
7820
7821 (defun org-complete (&optional arg)
7822 "Perform completion on word at point.
7823 At the beginning of a headline, this completes TODO keywords as given in
7824 `org-todo-keywords'.
7825 If the current word is preceded by a backslash, completes the TeX symbols
7826 that are supported for HTML support.
7827 If the current word is preceded by \"#+\", completes special words for
7828 setting file options.
7829 In the line after \"#+STARTUP:, complete valid keywords.\"
7830 At all other locations, this simply calls the value of
7831 `org-completion-fallback-command'."
7832 (interactive "P")
7833 (org-without-partial-completion
7834 (catch 'exit
7835 (let* ((a nil)
7836 (end (point))
7837 (beg1 (save-excursion
7838 (skip-chars-backward (org-re "[:alnum:]_@"))
7839 (point)))
7840 (beg (save-excursion
7841 (skip-chars-backward "a-zA-Z0-9_:$")
7842 (point)))
7843 (confirm (lambda (x) (stringp (car x))))
7844 (searchhead (equal (char-before beg) ?*))
7845 (struct
7846 (when (and (member (char-before beg1) '(?. ?<))
7847 (setq a (assoc (buffer-substring beg1 (point))
7848 org-structure-template-alist)))
7849 (org-complete-expand-structure-template (1- beg1) a)
7850 (throw 'exit t)))
7851 (tag (and (equal (char-before beg1) ?:)
7852 (equal (char-after (point-at-bol)) ?*)))
7853 (prop (and (equal (char-before beg1) ?:)
7854 (not (equal (char-after (point-at-bol)) ?*))))
7855 (texp (equal (char-before beg) ?\\))
7856 (link (equal (char-before beg) ?\[))
7857 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7858 beg)
7859 "#+"))
7860 (startup (string-match "^#\\+STARTUP:.*"
7861 (buffer-substring (point-at-bol) (point))))
7862 (completion-ignore-case opt)
7863 (type nil)
7864 (tbl nil)
7865 (table (cond
7866 (opt
7867 (setq type :opt)
7868 (require 'org-exp)
7869 (append
7870 (mapcar
7871 (lambda (x)
7872 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7873 (cons (match-string 2 x) (match-string 1 x)))
7874 (org-split-string (org-get-current-options) "\n"))
7875 (mapcar 'list org-additional-option-like-keywords)))
7876 (startup
7877 (setq type :startup)
7878 org-startup-options)
7879 (link (append org-link-abbrev-alist-local
7880 org-link-abbrev-alist))
7881 (texp
7882 (setq type :tex)
7883 org-html-entities)
7884 ((string-match "\\`\\*+[ \t]+\\'"
7885 (buffer-substring (point-at-bol) beg))
7886 (setq type :todo)
7887 (mapcar 'list org-todo-keywords-1))
7888 (searchhead
7889 (setq type :searchhead)
7890 (save-excursion
7891 (goto-char (point-min))
7892 (while (re-search-forward org-todo-line-regexp nil t)
7893 (push (list
7894 (org-make-org-heading-search-string
7895 (match-string 3) t))
7896 tbl)))
7897 tbl)
7898 (tag (setq type :tag beg beg1)
7899 (or org-tag-alist (org-get-buffer-tags)))
7900 (prop (setq type :prop beg beg1)
7901 (mapcar 'list (org-buffer-property-keys nil t t)))
7902 (t (progn
7903 (call-interactively org-completion-fallback-command)
7904 (throw 'exit nil)))))
7905 (pattern (buffer-substring-no-properties beg end))
7906 (completion (try-completion pattern table confirm)))
7907 (cond ((eq completion t)
7908 (if (not (assoc (upcase pattern) table))
7909 (message "Already complete")
7910 (if (and (equal type :opt)
7911 (not (member (car (assoc (upcase pattern) table))
7912 org-additional-option-like-keywords)))
7913 (insert (substring (cdr (assoc (upcase pattern) table))
7914 (length pattern)))
7915 (if (memq type '(:tag :prop)) (insert ":")))))
7916 ((null completion)
7917 (message "Can't find completion for \"%s\"" pattern)
7918 (ding))
7919 ((not (string= pattern completion))
7920 (delete-region beg end)
7921 (if (string-match " +$" completion)
7922 (setq completion (replace-match "" t t completion)))
7923 (insert completion)
7924 (if (get-buffer-window "*Completions*")
7925 (delete-window (get-buffer-window "*Completions*")))
7926 (if (assoc completion table)
7927 (if (eq type :todo) (insert " ")
7928 (if (memq type '(:tag :prop)) (insert ":"))))
7929 (if (and (equal type :opt) (assoc completion table))
7930 (message "%s" (substitute-command-keys
7931 "Press \\[org-complete] again to insert example settings"))))
7932 (t
7933 (message "Making completion list...")
7934 (let ((list (sort (all-completions pattern table confirm)
7935 'string<)))
7936 (with-output-to-temp-buffer "*Completions*"
7937 (condition-case nil
7938 ;; Protection needed for XEmacs and emacs 21
7939 (display-completion-list list pattern)
7940 (error (display-completion-list list)))))
7941 (message "Making completion list...%s" "done")))))))
7942
7943 ;;;; TODO, DEADLINE, Comments
7944
7945 (defun org-toggle-comment ()
7946 "Change the COMMENT state of an entry."
7947 (interactive)
7948 (save-excursion
7949 (org-back-to-heading)
7950 (let (case-fold-search)
7951 (if (looking-at (concat outline-regexp
7952 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7953 (replace-match "" t t nil 1)
7954 (if (looking-at outline-regexp)
7955 (progn
7956 (goto-char (match-end 0))
7957 (insert org-comment-string " ")))))))
7958
7959 (defvar org-last-todo-state-is-todo nil
7960 "This is non-nil when the last TODO state change led to a TODO state.
7961 If the last change removed the TODO tag or switched to DONE, then
7962 this is nil.")
7963
7964 (defvar org-setting-tags nil) ; dynamically skiped
7965
7966 (defun org-parse-local-options (string var)
7967 "Parse STRING for startup setting relevant for variable VAR."
7968 (let ((rtn (symbol-value var))
7969 e opts)
7970 (save-match-data
7971 (if (or (not string) (not (string-match "\\S-" string)))
7972 rtn
7973 (setq opts (delq nil (mapcar (lambda (x)
7974 (setq e (assoc x org-startup-options))
7975 (if (eq (nth 1 e) var) e nil))
7976 (org-split-string string "[ \t]+"))))
7977 (if (not opts)
7978 rtn
7979 (setq rtn nil)
7980 (while (setq e (pop opts))
7981 (if (not (nth 3 e))
7982 (setq rtn (nth 2 e))
7983 (if (not (listp rtn)) (setq rtn nil))
7984 (push (nth 2 e) rtn)))
7985 rtn)))))
7986
7987 (defvar org-blocker-hook nil
7988 "Hook for functions that are allowed to block a state change.
7989
7990 Each function gets as its single argument a property list, see
7991 `org-trigger-hook' for more information about this list.
7992
7993 If any of the functions in this hook returns nil, the state change
7994 is blocked.")
7995
7996 (defvar org-trigger-hook nil
7997 "Hook for functions that are triggered by a state change.
7998
7999 Each function gets as its single argument a property list with at least
8000 the following elements:
8001
8002 (:type type-of-change :position pos-at-entry-start
8003 :from old-state :to new-state)
8004
8005 Depending on the type, more properties may be present.
8006
8007 This mechanism is currently implemented for:
8008
8009 TODO state changes
8010 ------------------
8011 :type todo-state-change
8012 :from previous state (keyword as a string), or nil
8013 :to new state (keyword as a string), or nil")
8014
8015 (defvar org-agenda-headline-snapshot-before-repeat)
8016 (defun org-todo (&optional arg)
8017 "Change the TODO state of an item.
8018 The state of an item is given by a keyword at the start of the heading,
8019 like
8020 *** TODO Write paper
8021 *** DONE Call mom
8022
8023 The different keywords are specified in the variable `org-todo-keywords'.
8024 By default the available states are \"TODO\" and \"DONE\".
8025 So for this example: when the item starts with TODO, it is changed to DONE.
8026 When it starts with DONE, the DONE is removed. And when neither TODO nor
8027 DONE are present, add TODO at the beginning of the heading.
8028
8029 With C-u prefix arg, use completion to determine the new state.
8030 With numeric prefix arg, switch to that state.
8031
8032 For calling through lisp, arg is also interpreted in the following way:
8033 'none -> empty state
8034 \"\"(empty string) -> switch to empty state
8035 'done -> switch to DONE
8036 'nextset -> switch to the next set of keywords
8037 'previousset -> switch to the previous set of keywords
8038 \"WAITING\" -> switch to the specified keyword, but only if it
8039 really is a member of `org-todo-keywords'."
8040 (interactive "P")
8041 (save-excursion
8042 (catch 'exit
8043 (org-back-to-heading)
8044 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8045 (or (looking-at (concat " +" org-todo-regexp " *"))
8046 (looking-at " *"))
8047 (let* ((match-data (match-data))
8048 (startpos (point-at-bol))
8049 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8050 (org-log-done org-log-done)
8051 (org-log-repeat org-log-repeat)
8052 (org-todo-log-states org-todo-log-states)
8053 (this (match-string 1))
8054 (hl-pos (match-beginning 0))
8055 (head (org-get-todo-sequence-head this))
8056 (ass (assoc head org-todo-kwd-alist))
8057 (interpret (nth 1 ass))
8058 (done-word (nth 3 ass))
8059 (final-done-word (nth 4 ass))
8060 (last-state (or this ""))
8061 (completion-ignore-case t)
8062 (member (member this org-todo-keywords-1))
8063 (tail (cdr member))
8064 (state (cond
8065 ((and org-todo-key-trigger
8066 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8067 (and (not arg) org-use-fast-todo-selection
8068 (not (eq org-use-fast-todo-selection 'prefix)))))
8069 ;; Use fast selection
8070 (org-fast-todo-selection))
8071 ((and (equal arg '(4))
8072 (or (not org-use-fast-todo-selection)
8073 (not org-todo-key-trigger)))
8074 ;; Read a state with completion
8075 (org-ido-completing-read "State: " (mapcar (lambda(x) (list x))
8076 org-todo-keywords-1)
8077 nil t))
8078 ((eq arg 'right)
8079 (if this
8080 (if tail (car tail) nil)
8081 (car org-todo-keywords-1)))
8082 ((eq arg 'left)
8083 (if (equal member org-todo-keywords-1)
8084 nil
8085 (if this
8086 (nth (- (length org-todo-keywords-1) (length tail) 2)
8087 org-todo-keywords-1)
8088 (org-last org-todo-keywords-1))))
8089 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8090 (setq arg nil))) ; hack to fall back to cycling
8091 (arg
8092 ;; user or caller requests a specific state
8093 (cond
8094 ((equal arg "") nil)
8095 ((eq arg 'none) nil)
8096 ((eq arg 'done) (or done-word (car org-done-keywords)))
8097 ((eq arg 'nextset)
8098 (or (car (cdr (member head org-todo-heads)))
8099 (car org-todo-heads)))
8100 ((eq arg 'previousset)
8101 (let ((org-todo-heads (reverse org-todo-heads)))
8102 (or (car (cdr (member head org-todo-heads)))
8103 (car org-todo-heads))))
8104 ((car (member arg org-todo-keywords-1)))
8105 ((nth (1- (prefix-numeric-value arg))
8106 org-todo-keywords-1))))
8107 ((null member) (or head (car org-todo-keywords-1)))
8108 ((equal this final-done-word) nil) ;; -> make empty
8109 ((null tail) nil) ;; -> first entry
8110 ((eq interpret 'sequence)
8111 (car tail))
8112 ((memq interpret '(type priority))
8113 (if (eq this-command last-command)
8114 (car tail)
8115 (if (> (length tail) 0)
8116 (or done-word (car org-done-keywords))
8117 nil)))
8118 (t nil)))
8119 (next (if state (concat " " state " ") " "))
8120 (change-plist (list :type 'todo-state-change :from this :to state
8121 :position startpos))
8122 dolog now-done-p)
8123 (when org-blocker-hook
8124 (unless (save-excursion
8125 (save-match-data
8126 (run-hook-with-args-until-failure
8127 'org-blocker-hook change-plist)))
8128 (if (interactive-p)
8129 (error "TODO state change from %s to %s blocked" this state)
8130 ;; fail silently
8131 (message "TODO state change from %s to %s blocked" this state)
8132 (throw 'exit nil))))
8133 (store-match-data match-data)
8134 (replace-match next t t)
8135 (unless (pos-visible-in-window-p hl-pos)
8136 (message "TODO state changed to %s" (org-trim next)))
8137 (unless head
8138 (setq head (org-get-todo-sequence-head state)
8139 ass (assoc head org-todo-kwd-alist)
8140 interpret (nth 1 ass)
8141 done-word (nth 3 ass)
8142 final-done-word (nth 4 ass)))
8143 (when (memq arg '(nextset previousset))
8144 (message "Keyword-Set %d/%d: %s"
8145 (- (length org-todo-sets) -1
8146 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8147 (length org-todo-sets)
8148 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8149 (setq org-last-todo-state-is-todo
8150 (not (member state org-done-keywords)))
8151 (setq now-done-p (and (member state org-done-keywords)
8152 (not (member this org-done-keywords))))
8153 (and logging (org-local-logging logging))
8154 (when (and (or org-todo-log-states org-log-done)
8155 (not (memq arg '(nextset previousset))))
8156 ;; we need to look at recording a time and note
8157 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8158 (nth 2 (assoc this org-todo-log-states))))
8159 (when (and state
8160 (member state org-not-done-keywords)
8161 (not (member this org-not-done-keywords)))
8162 ;; This is now a todo state and was not one before
8163 ;; If there was a CLOSED time stamp, get rid of it.
8164 (org-add-planning-info nil nil 'closed))
8165 (when (and now-done-p org-log-done)
8166 ;; It is now done, and it was not done before
8167 (org-add-planning-info 'closed (org-current-time))
8168 (if (and (not dolog) (eq 'note org-log-done))
8169 (org-add-log-setup 'done state 'findpos 'note)))
8170 (when (and state dolog)
8171 ;; This is a non-nil state, and we need to log it
8172 (org-add-log-setup 'state state 'findpos dolog)))
8173 ;; Fixup tag positioning
8174 (org-todo-trigger-tag-changes state)
8175 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8176 (when org-provide-todo-statistics
8177 (org-update-parent-todo-statistics))
8178 (run-hooks 'org-after-todo-state-change-hook)
8179 (if (and arg (not (member state org-done-keywords)))
8180 (setq head (org-get-todo-sequence-head state)))
8181 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8182 ;; Do we need to trigger a repeat?
8183 (when now-done-p
8184 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8185 ;; This is for the agenda, take a snapshot of the headline.
8186 (save-match-data
8187 (setq org-agenda-headline-snapshot-before-repeat
8188 (org-get-heading))))
8189 (org-auto-repeat-maybe state))
8190 ;; Fixup cursor location if close to the keyword
8191 (if (and (outline-on-heading-p)
8192 (not (bolp))
8193 (save-excursion (beginning-of-line 1)
8194 (looking-at org-todo-line-regexp))
8195 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8196 (progn
8197 (goto-char (or (match-end 2) (match-end 1)))
8198 (just-one-space)))
8199 (when org-trigger-hook
8200 (save-excursion
8201 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8202
8203 (defun org-update-parent-todo-statistics ()
8204 "Update any statistics cookie in the parent of the current headline."
8205 (interactive)
8206 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8207 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8208 (catch 'exit
8209 (save-excursion
8210 (setq level (org-up-heading-safe))
8211 (unless (and level
8212 (re-search-forward box-re (point-at-eol) t))
8213 (throw 'exit nil))
8214 (setq is-percent (match-end 2))
8215 (save-match-data
8216 (unless (outline-next-heading) (throw 'exit nil))
8217 (while (looking-at org-todo-line-regexp)
8218 (setq kwd (match-string 2))
8219 (and kwd (setq cnt-all (1+ cnt-all)))
8220 (and (member kwd org-done-keywords)
8221 (setq cnt-done (1+ cnt-done)))
8222 (condition-case nil
8223 (org-forward-same-level 1)
8224 (error (end-of-line 1)))))
8225 (replace-match
8226 (if is-percent
8227 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8228 (format "[%d/%d]" cnt-done cnt-all)))
8229 (run-hook-with-args 'org-after-todo-statistics-hook
8230 cnt-done (- cnt-all cnt-done))))))
8231
8232 (defvar org-after-todo-statistics-hook nil
8233 "Hook that is called after a TODO statistics cookie has been updated.
8234 Each function is called with two arguments: the number of not-done entries
8235 and the number of done entries.
8236
8237 For example, the following function, when added to this hook, will switch
8238 an entry to DONE when all children are done, and back to TODO when new
8239 entries are set to a TODO status. Note that this hook is only called
8240 when there is a statistics cookie in the headline!
8241
8242 (defun org-summary-todo (n-done n-not-done)
8243 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8244 (let (org-log-done org-log-states) ; turn off logging
8245 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8246 ")
8247
8248 (defun org-todo-trigger-tag-changes (state)
8249 "Apply the changes defined in `org-todo-state-tags-triggers'."
8250 (let ((l org-todo-state-tags-triggers)
8251 changes)
8252 (when (or (not state) (equal state ""))
8253 (setq changes (append changes (cdr (assoc "" l)))))
8254 (when (and (stringp state) (> (length state) 0))
8255 (setq changes (append changes (cdr (assoc state l)))))
8256 (when (member state org-not-done-keywords)
8257 (setq changes (append changes (cdr (assoc 'todo l)))))
8258 (when (member state org-done-keywords)
8259 (setq changes (append changes (cdr (assoc 'done l)))))
8260 (dolist (c changes)
8261 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8262
8263 (defun org-local-logging (value)
8264 "Get logging settings from a property VALUE."
8265 (let* (words w a)
8266 ;; directly set the variables, they are already local.
8267 (setq org-log-done nil
8268 org-log-repeat nil
8269 org-todo-log-states nil)
8270 (setq words (org-split-string value))
8271 (while (setq w (pop words))
8272 (cond
8273 ((setq a (assoc w org-startup-options))
8274 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8275 (set (nth 1 a) (nth 2 a))))
8276 ((setq a (org-extract-log-state-settings w))
8277 (and (member (car a) org-todo-keywords-1)
8278 (push a org-todo-log-states)))))))
8279
8280 (defun org-get-todo-sequence-head (kwd)
8281 "Return the head of the TODO sequence to which KWD belongs.
8282 If KWD is not set, check if there is a text property remembering the
8283 right sequence."
8284 (let (p)
8285 (cond
8286 ((not kwd)
8287 (or (get-text-property (point-at-bol) 'org-todo-head)
8288 (progn
8289 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8290 nil (point-at-eol)))
8291 (get-text-property p 'org-todo-head))))
8292 ((not (member kwd org-todo-keywords-1))
8293 (car org-todo-keywords-1))
8294 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8295
8296 (defun org-fast-todo-selection ()
8297 "Fast TODO keyword selection with single keys.
8298 Returns the new TODO keyword, or nil if no state change should occur."
8299 (let* ((fulltable org-todo-key-alist)
8300 (done-keywords org-done-keywords) ;; needed for the faces.
8301 (maxlen (apply 'max (mapcar
8302 (lambda (x)
8303 (if (stringp (car x)) (string-width (car x)) 0))
8304 fulltable)))
8305 (expert nil)
8306 (fwidth (+ maxlen 3 1 3))
8307 (ncol (/ (- (window-width) 4) fwidth))
8308 tg cnt e c tbl
8309 groups ingroup)
8310 (save-window-excursion
8311 (if expert
8312 (set-buffer (get-buffer-create " *Org todo*"))
8313 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8314 (erase-buffer)
8315 (org-set-local 'org-done-keywords done-keywords)
8316 (setq tbl fulltable cnt 0)
8317 (while (setq e (pop tbl))
8318 (cond
8319 ((equal e '(:startgroup))
8320 (push '() groups) (setq ingroup t)
8321 (when (not (= cnt 0))
8322 (setq cnt 0)
8323 (insert "\n"))
8324 (insert "{ "))
8325 ((equal e '(:endgroup))
8326 (setq ingroup nil cnt 0)
8327 (insert "}\n"))
8328 (t
8329 (setq tg (car e) c (cdr e))
8330 (if ingroup (push tg (car groups)))
8331 (setq tg (org-add-props tg nil 'face
8332 (org-get-todo-face tg)))
8333 (if (and (= cnt 0) (not ingroup)) (insert " "))
8334 (insert "[" c "] " tg (make-string
8335 (- fwidth 4 (length tg)) ?\ ))
8336 (when (= (setq cnt (1+ cnt)) ncol)
8337 (insert "\n")
8338 (if ingroup (insert " "))
8339 (setq cnt 0)))))
8340 (insert "\n")
8341 (goto-char (point-min))
8342 (if (not expert) (org-fit-window-to-buffer))
8343 (message "[a-z..]:Set [SPC]:clear")
8344 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8345 (cond
8346 ((or (= c ?\C-g)
8347 (and (= c ?q) (not (rassoc c fulltable))))
8348 (setq quit-flag t))
8349 ((= c ?\ ) nil)
8350 ((setq e (rassoc c fulltable) tg (car e))
8351 tg)
8352 (t (setq quit-flag t))))))
8353
8354 (defun org-entry-is-todo-p ()
8355 (member (org-get-todo-state) org-not-done-keywords))
8356
8357 (defun org-entry-is-done-p ()
8358 (member (org-get-todo-state) org-done-keywords))
8359
8360 (defun org-get-todo-state ()
8361 (save-excursion
8362 (org-back-to-heading t)
8363 (and (looking-at org-todo-line-regexp)
8364 (match-end 2)
8365 (match-string 2))))
8366
8367 (defun org-at-date-range-p (&optional inactive-ok)
8368 "Is the cursor inside a date range?"
8369 (interactive)
8370 (save-excursion
8371 (catch 'exit
8372 (let ((pos (point)))
8373 (skip-chars-backward "^[<\r\n")
8374 (skip-chars-backward "<[")
8375 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8376 (>= (match-end 0) pos)
8377 (throw 'exit t))
8378 (skip-chars-backward "^<[\r\n")
8379 (skip-chars-backward "<[")
8380 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8381 (>= (match-end 0) pos)
8382 (throw 'exit t)))
8383 nil)))
8384
8385 (defun org-get-repeat ()
8386 "Check if there is a deadline/schedule with repeater in this entry."
8387 (save-match-data
8388 (save-excursion
8389 (org-back-to-heading t)
8390 (if (re-search-forward
8391 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8392 (match-string 1)))))
8393
8394 (defvar org-last-changed-timestamp)
8395 (defvar org-last-inserted-timestamp)
8396 (defvar org-log-post-message)
8397 (defvar org-log-note-purpose)
8398 (defvar org-log-note-how)
8399 (defvar org-log-note-extra)
8400 (defun org-auto-repeat-maybe (done-word)
8401 "Check if the current headline contains a repeated deadline/schedule.
8402 If yes, set TODO state back to what it was and change the base date
8403 of repeating deadline/scheduled time stamps to new date.
8404 This function is run automatically after each state change to a DONE state."
8405 ;; last-state is dynamically scoped into this function
8406 (let* ((repeat (org-get-repeat))
8407 (aa (assoc last-state org-todo-kwd-alist))
8408 (interpret (nth 1 aa))
8409 (head (nth 2 aa))
8410 (whata '(("d" . day) ("m" . month) ("y" . year)))
8411 (msg "Entry repeats: ")
8412 (org-log-done nil)
8413 (org-todo-log-states nil)
8414 (nshiftmax 10) (nshift 0)
8415 re type n what ts mb0 time)
8416 (when repeat
8417 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8418 (org-todo (if (eq interpret 'type) last-state head))
8419 (when org-log-repeat
8420 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8421 (memq 'org-add-log-note post-command-hook))
8422 ;; OK, we are already setup for some record
8423 (if (eq org-log-repeat 'note)
8424 ;; make sure we take a note, not only a time stamp
8425 (setq org-log-note-how 'note))
8426 ;; Set up for taking a record
8427 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8428 'findpos org-log-repeat)))
8429 (org-back-to-heading t)
8430 (org-add-planning-info nil nil 'closed)
8431 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8432 org-deadline-time-regexp "\\)\\|\\("
8433 org-ts-regexp "\\)"))
8434 (while (re-search-forward
8435 re (save-excursion (outline-next-heading) (point)) t)
8436 (setq type (if (match-end 1) org-scheduled-string
8437 (if (match-end 3) org-deadline-string "Plain:"))
8438 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8439 mb0 (match-beginning 0))
8440 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8441 (setq n (string-to-number (match-string 2 ts))
8442 what (match-string 3 ts))
8443 (if (equal what "w") (setq n (* n 7) what "d"))
8444 ;; Preparation, see if we need to modify the start date for the change
8445 (when (match-end 1)
8446 (setq time (save-match-data (org-time-string-to-time ts)))
8447 (cond
8448 ((equal (match-string 1 ts) ".")
8449 ;; Shift starting date to today
8450 (org-timestamp-change
8451 (- (time-to-days (current-time)) (time-to-days time))
8452 'day))
8453 ((equal (match-string 1 ts) "+")
8454 (while (or (= nshift 0)
8455 (<= (time-to-days time) (time-to-days (current-time))))
8456 (when (= (incf nshift) nshiftmax)
8457 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8458 (error "Abort")))
8459 (org-timestamp-change n (cdr (assoc what whata)))
8460 (org-at-timestamp-p t)
8461 (setq ts (match-string 1))
8462 (setq time (save-match-data (org-time-string-to-time ts))))
8463 (org-timestamp-change (- n) (cdr (assoc what whata)))
8464 ;; rematch, so that we have everything in place for the real shift
8465 (org-at-timestamp-p t)
8466 (setq ts (match-string 1))
8467 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8468 (org-timestamp-change n (cdr (assoc what whata)))
8469 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8470 (setq org-log-post-message msg)
8471 (message "%s" msg))))
8472
8473 (defun org-show-todo-tree (arg)
8474 "Make a compact tree which shows all headlines marked with TODO.
8475 The tree will show the lines where the regexp matches, and all higher
8476 headlines above the match.
8477 With a \\[universal-argument] prefix, also show the DONE entries.
8478 With a numeric prefix N, construct a sparse tree for the Nth element
8479 of `org-todo-keywords-1'."
8480 (interactive "P")
8481 (let ((case-fold-search nil)
8482 (kwd-re
8483 (cond ((null arg) org-not-done-regexp)
8484 ((equal arg '(4))
8485 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8486 (mapcar 'list org-todo-keywords-1))))
8487 (concat "\\("
8488 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8489 "\\)\\>")))
8490 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8491 (regexp-quote (nth (1- (prefix-numeric-value arg))
8492 org-todo-keywords-1)))
8493 (t (error "Invalid prefix argument: %s" arg)))))
8494 (message "%d TODO entries found"
8495 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8496
8497 (defun org-deadline (&optional remove time)
8498 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8499 With argument REMOVE, remove any deadline from the item.
8500 When TIME is set, it should be an internal time specification, and the
8501 scheduling will use the corresponding date."
8502 (interactive "P")
8503 (if remove
8504 (progn
8505 (org-remove-timestamp-with-keyword org-deadline-string)
8506 (message "Item no longer has a deadline."))
8507 (if (org-get-repeat)
8508 (error "Cannot change deadline on task with repeater, please do that by hand")
8509 (org-add-planning-info 'deadline time 'closed)
8510 (message "Deadline on %s" org-last-inserted-timestamp))))
8511
8512 (defun org-schedule (&optional remove time)
8513 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8514 With argument REMOVE, remove any scheduling date from the item.
8515 When TIME is set, it should be an internal time specification, and the
8516 scheduling will use the corresponding date."
8517 (interactive "P")
8518 (if remove
8519 (progn
8520 (org-remove-timestamp-with-keyword org-scheduled-string)
8521 (message "Item is no longer scheduled."))
8522 (if (org-get-repeat)
8523 (error "Cannot reschedule task with repeater, please do that by hand")
8524 (org-add-planning-info 'scheduled time 'closed)
8525 (message "Scheduled to %s" org-last-inserted-timestamp))))
8526
8527 (defun org-remove-timestamp-with-keyword (keyword)
8528 "Remove all time stamps with KEYWORD in the current entry."
8529 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8530 beg)
8531 (save-excursion
8532 (org-back-to-heading t)
8533 (setq beg (point))
8534 (org-end-of-subtree t t)
8535 (while (re-search-backward re beg t)
8536 (replace-match "")
8537 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8538 (equal (char-before) ?\ ))
8539 (backward-delete-char 1)
8540 (if (string-match "^[ \t]*$" (buffer-substring
8541 (point-at-bol) (point-at-eol)))
8542 (delete-region (point-at-bol)
8543 (min (point-max) (1+ (point-at-eol))))))))))
8544
8545 (defun org-add-planning-info (what &optional time &rest remove)
8546 "Insert new timestamp with keyword in the line directly after the headline.
8547 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8548 If non is given, the user is prompted for a date.
8549 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8550 be removed."
8551 (interactive)
8552 (let (org-time-was-given org-end-time-was-given ts
8553 end default-time default-input)
8554
8555 (when (and (not time) (memq what '(scheduled deadline)))
8556 ;; Try to get a default date/time from existing timestamp
8557 (save-excursion
8558 (org-back-to-heading t)
8559 (setq end (save-excursion (outline-next-heading) (point)))
8560 (when (re-search-forward (if (eq what 'scheduled)
8561 org-scheduled-time-regexp
8562 org-deadline-time-regexp)
8563 end t)
8564 (setq ts (match-string 1)
8565 default-time
8566 (apply 'encode-time (org-parse-time-string ts))
8567 default-input (and ts (org-get-compact-tod ts))))))
8568 (when what
8569 ;; If necessary, get the time from the user
8570 (setq time (or time (org-read-date nil 'to-time nil nil
8571 default-time default-input))))
8572
8573 (when (and org-insert-labeled-timestamps-at-point
8574 (member what '(scheduled deadline)))
8575 (insert
8576 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8577 (org-insert-time-stamp time org-time-was-given
8578 nil nil nil (list org-end-time-was-given))
8579 (setq what nil))
8580 (save-excursion
8581 (save-restriction
8582 (let (col list elt ts buffer-invisibility-spec)
8583 (org-back-to-heading t)
8584 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8585 (goto-char (match-end 1))
8586 (setq col (current-column))
8587 (goto-char (match-end 0))
8588 (if (eobp) (insert "\n") (forward-char 1))
8589 (if (and (not (looking-at outline-regexp))
8590 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8591 "[^\r\n]*"))
8592 (not (equal (match-string 1) org-clock-string)))
8593 (narrow-to-region (match-beginning 0) (match-end 0))
8594 (insert-before-markers "\n")
8595 (backward-char 1)
8596 (narrow-to-region (point) (point))
8597 (and org-adapt-indentation (org-indent-to-column col)))
8598 ;; Check if we have to remove something.
8599 (setq list (cons what remove))
8600 (while list
8601 (setq elt (pop list))
8602 (goto-char (point-min))
8603 (when (or (and (eq elt 'scheduled)
8604 (re-search-forward org-scheduled-time-regexp nil t))
8605 (and (eq elt 'deadline)
8606 (re-search-forward org-deadline-time-regexp nil t))
8607 (and (eq elt 'closed)
8608 (re-search-forward org-closed-time-regexp nil t)))
8609 (replace-match "")
8610 (if (looking-at "--+<[^>]+>") (replace-match ""))
8611 (if (looking-at " +") (replace-match ""))))
8612 (goto-char (point-max))
8613 (when what
8614 (insert
8615 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8616 (cond ((eq what 'scheduled) org-scheduled-string)
8617 ((eq what 'deadline) org-deadline-string)
8618 ((eq what 'closed) org-closed-string))
8619 " ")
8620 (setq ts (org-insert-time-stamp
8621 time
8622 (or org-time-was-given
8623 (and (eq what 'closed) org-log-done-with-time))
8624 (eq what 'closed)
8625 nil nil (list org-end-time-was-given)))
8626 (end-of-line 1))
8627 (goto-char (point-min))
8628 (widen)
8629 (if (and (looking-at "[ \t]+\n")
8630 (equal (char-before) ?\n))
8631 (delete-region (1- (point)) (point-at-eol)))
8632 ts)))))
8633
8634 (defvar org-log-note-marker (make-marker))
8635 (defvar org-log-note-purpose nil)
8636 (defvar org-log-note-state nil)
8637 (defvar org-log-note-how nil)
8638 (defvar org-log-note-extra nil)
8639 (defvar org-log-note-window-configuration nil)
8640 (defvar org-log-note-return-to (make-marker))
8641 (defvar org-log-post-message nil
8642 "Message to be displayed after a log note has been stored.
8643 The auto-repeater uses this.")
8644
8645 (defun org-add-note ()
8646 "Add a note to the current entry.
8647 This is done in the same way as adding a state change note."
8648 (interactive)
8649 (org-add-log-setup 'note nil 'findpos nil))
8650
8651 (defvar org-property-end-re)
8652 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
8653 "Set up the post command hook to take a note.
8654 If this is about to TODO state change, the new state is expected in STATE.
8655 When FINDPOS is non-nil, find the correct position for the note in
8656 the current entry. If not, assume that it can be inserted at point.
8657 HOW is an indicator what kind of note should be created.
8658 EXTRA is additional text that will be inserted into the notes buffer."
8659 (save-restriction
8660 (save-excursion
8661 (when findpos
8662 (org-back-to-heading t)
8663 (narrow-to-region (point) (save-excursion
8664 (outline-next-heading) (point)))
8665 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8666 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8667 "[^\r\n]*\\)?"))
8668 (goto-char (match-end 0))
8669 (when (and org-log-state-notes-insert-after-drawers
8670 (save-excursion
8671 (forward-line) (looking-at org-drawer-regexp)))
8672 (progn (forward-line)
8673 (while (looking-at org-drawer-regexp)
8674 (goto-char (match-end 0))
8675 (re-search-forward org-property-end-re (point-max) t)
8676 (forward-line))
8677 (forward-line -1)))
8678 (unless org-log-states-order-reversed
8679 (and (= (char-after) ?\n) (forward-char 1))
8680 (org-skip-over-state-notes)
8681 (skip-chars-backward " \t\n\r")))
8682 (move-marker org-log-note-marker (point))
8683 (setq org-log-note-purpose purpose
8684 org-log-note-state state
8685 org-log-note-how how
8686 org-log-note-extra extra)
8687 (add-hook 'post-command-hook 'org-add-log-note 'append))))
8688
8689 (defun org-skip-over-state-notes ()
8690 "Skip past the list of State notes in an entry."
8691 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8692 (while (looking-at "[ \t]*- State")
8693 (condition-case nil
8694 (org-next-item)
8695 (error (org-end-of-item)))))
8696
8697 (defun org-add-log-note (&optional purpose)
8698 "Pop up a window for taking a note, and add this note later at point."
8699 (remove-hook 'post-command-hook 'org-add-log-note)
8700 (setq org-log-note-window-configuration (current-window-configuration))
8701 (delete-other-windows)
8702 (move-marker org-log-note-return-to (point))
8703 (switch-to-buffer (marker-buffer org-log-note-marker))
8704 (goto-char org-log-note-marker)
8705 (org-switch-to-buffer-other-window "*Org Note*")
8706 (erase-buffer)
8707 (if (memq org-log-note-how '(time state))
8708 (let (current-prefix-arg) (org-store-log-note))
8709 (let ((org-inhibit-startup t)) (org-mode))
8710 (insert (format "# Insert note for %s.
8711 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8712 (cond
8713 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8714 ((eq org-log-note-purpose 'done) "closed todo item")
8715 ((eq org-log-note-purpose 'state)
8716 (format "state change to \"%s\"" org-log-note-state))
8717 ((eq org-log-note-purpose 'note)
8718 "this entry")
8719 (t (error "This should not happen")))))
8720 (if org-log-note-extra (insert org-log-note-extra))
8721 (org-set-local 'org-finish-function 'org-store-log-note)))
8722
8723 (defvar org-note-abort nil) ; dynamically scoped
8724 (defun org-store-log-note ()
8725 "Finish taking a log note, and insert it to where it belongs."
8726 (let ((txt (buffer-string))
8727 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8728 lines ind)
8729 (kill-buffer (current-buffer))
8730 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8731 (setq txt (replace-match "" t t txt)))
8732 (if (string-match "\\s-+\\'" txt)
8733 (setq txt (replace-match "" t t txt)))
8734 (setq lines (org-split-string txt "\n"))
8735 (when (and note (string-match "\\S-" note))
8736 (setq note
8737 (org-replace-escapes
8738 note
8739 (list (cons "%u" (user-login-name))
8740 (cons "%U" user-full-name)
8741 (cons "%t" (format-time-string
8742 (org-time-stamp-format 'long 'inactive)
8743 (current-time)))
8744 (cons "%s" (if org-log-note-state
8745 (concat "\"" org-log-note-state "\"")
8746 "")))))
8747 (if lines (setq note (concat note " \\\\")))
8748 (push note lines))
8749 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8750 (when lines
8751 (save-excursion
8752 (set-buffer (marker-buffer org-log-note-marker))
8753 (save-excursion
8754 (goto-char org-log-note-marker)
8755 (move-marker org-log-note-marker nil)
8756 (end-of-line 1)
8757 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8758 (indent-relative nil)
8759 (insert "- " (pop lines))
8760 (org-indent-line-function)
8761 (beginning-of-line 1)
8762 (looking-at "[ \t]*")
8763 (setq ind (concat (match-string 0) " "))
8764 (end-of-line 1)
8765 (while lines (insert "\n" ind (pop lines)))))))
8766 (set-window-configuration org-log-note-window-configuration)
8767 (with-current-buffer (marker-buffer org-log-note-return-to)
8768 (goto-char org-log-note-return-to))
8769 (move-marker org-log-note-return-to nil)
8770 (and org-log-post-message (message "%s" org-log-post-message)))
8771
8772 (defun org-sparse-tree (&optional arg)
8773 "Create a sparse tree, prompt for the details.
8774 This command can create sparse trees. You first need to select the type
8775 of match used to create the tree:
8776
8777 t Show entries with a specific TODO keyword.
8778 T Show entries selected by a tags match.
8779 p Enter a property name and its value (both with completion on existing
8780 names/values) and show entries with that property.
8781 r Show entries matching a regular expression
8782 d Show deadlines due within `org-deadline-warning-days'."
8783 (interactive "P")
8784 (let (ans kwd value)
8785 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8786 (setq ans (read-char-exclusive))
8787 (cond
8788 ((equal ans ?d)
8789 (call-interactively 'org-check-deadlines))
8790 ((equal ans ?b)
8791 (call-interactively 'org-check-before-date))
8792 ((equal ans ?t)
8793 (org-show-todo-tree '(4)))
8794 ((equal ans ?T)
8795 (call-interactively 'org-tags-sparse-tree))
8796 ((member ans '(?p ?P))
8797 (setq kwd (org-ido-completing-read "Property: "
8798 (mapcar 'list (org-buffer-property-keys))))
8799 (setq value (org-ido-completing-read "Value: "
8800 (mapcar 'list (org-property-values kwd))))
8801 (unless (string-match "\\`{.*}\\'" value)
8802 (setq value (concat "\"" value "\"")))
8803 (org-tags-sparse-tree arg (concat kwd "=" value)))
8804 ((member ans '(?r ?R ?/))
8805 (call-interactively 'org-occur))
8806 (t (error "No such sparse tree command \"%c\"" ans)))))
8807
8808 (defvar org-occur-highlights nil
8809 "List of overlays used for occur matches.")
8810 (make-variable-buffer-local 'org-occur-highlights)
8811 (defvar org-occur-parameters nil
8812 "Parameters of the active org-occur calls.
8813 This is a list, each call to org-occur pushes as cons cell,
8814 containing the regular expression and the callback, onto the list.
8815 The list can contain several entries if `org-occur' has been called
8816 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8817 will only contain one set of parameters. When the highlights are
8818 removed (for example with `C-c C-c', or with the next edit (depending
8819 on `org-remove-highlights-with-change'), this variable is emptied
8820 as well.")
8821 (make-variable-buffer-local 'org-occur-parameters)
8822
8823 (defun org-occur (regexp &optional keep-previous callback)
8824 "Make a compact tree which shows all matches of REGEXP.
8825 The tree will show the lines where the regexp matches, and all higher
8826 headlines above the match. It will also show the heading after the match,
8827 to make sure editing the matching entry is easy.
8828 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8829 call to `org-occur' will be kept, to allow stacking of calls to this
8830 command.
8831 If CALLBACK is non-nil, it is a function which is called to confirm
8832 that the match should indeed be shown."
8833 (interactive "sRegexp: \nP")
8834 (unless keep-previous
8835 (org-remove-occur-highlights nil nil t))
8836 (push (cons regexp callback) org-occur-parameters)
8837 (let ((cnt 0))
8838 (save-excursion
8839 (goto-char (point-min))
8840 (if (or (not keep-previous) ; do not want to keep
8841 (not org-occur-highlights)) ; no previous matches
8842 ;; hide everything
8843 (org-overview))
8844 (while (re-search-forward regexp nil t)
8845 (when (or (not callback)
8846 (save-match-data (funcall callback)))
8847 (setq cnt (1+ cnt))
8848 (when org-highlight-sparse-tree-matches
8849 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8850 (org-show-context 'occur-tree))))
8851 (when org-remove-highlights-with-change
8852 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8853 nil 'local))
8854 (unless org-sparse-tree-open-archived-trees
8855 (org-hide-archived-subtrees (point-min) (point-max)))
8856 (run-hooks 'org-occur-hook)
8857 (if (interactive-p)
8858 (message "%d match(es) for regexp %s" cnt regexp))
8859 cnt))
8860
8861 (defun org-show-context (&optional key)
8862 "Make sure point and context and visible.
8863 How much context is shown depends upon the variables
8864 `org-show-hierarchy-above', `org-show-following-heading'. and
8865 `org-show-siblings'."
8866 (let ((heading-p (org-on-heading-p t))
8867 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8868 (following-p (org-get-alist-option org-show-following-heading key))
8869 (entry-p (org-get-alist-option org-show-entry-below key))
8870 (siblings-p (org-get-alist-option org-show-siblings key)))
8871 (catch 'exit
8872 ;; Show heading or entry text
8873 (if (and heading-p (not entry-p))
8874 (org-flag-heading nil) ; only show the heading
8875 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8876 (org-show-hidden-entry))) ; show entire entry
8877 (when following-p
8878 ;; Show next sibling, or heading below text
8879 (save-excursion
8880 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8881 (org-flag-heading nil))))
8882 (when siblings-p (org-show-siblings))
8883 (when hierarchy-p
8884 ;; show all higher headings, possibly with siblings
8885 (save-excursion
8886 (while (and (condition-case nil
8887 (progn (org-up-heading-all 1) t)
8888 (error nil))
8889 (not (bobp)))
8890 (org-flag-heading nil)
8891 (when siblings-p (org-show-siblings))))))))
8892
8893 (defun org-reveal (&optional siblings)
8894 "Show current entry, hierarchy above it, and the following headline.
8895 This can be used to show a consistent set of context around locations
8896 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8897 not t for the search context.
8898
8899 With optional argument SIBLINGS, on each level of the hierarchy all
8900 siblings are shown. This repairs the tree structure to what it would
8901 look like when opened with hierarchical calls to `org-cycle'."
8902 (interactive "P")
8903 (let ((org-show-hierarchy-above t)
8904 (org-show-following-heading t)
8905 (org-show-siblings (if siblings t org-show-siblings)))
8906 (org-show-context nil)))
8907
8908 (defun org-highlight-new-match (beg end)
8909 "Highlight from BEG to END and mark the highlight is an occur headline."
8910 (let ((ov (org-make-overlay beg end)))
8911 (org-overlay-put ov 'face 'secondary-selection)
8912 (push ov org-occur-highlights)))
8913
8914 (defun org-remove-occur-highlights (&optional beg end noremove)
8915 "Remove the occur highlights from the buffer.
8916 BEG and END are ignored. If NOREMOVE is nil, remove this function
8917 from the `before-change-functions' in the current buffer."
8918 (interactive)
8919 (unless org-inhibit-highlight-removal
8920 (mapc 'org-delete-overlay org-occur-highlights)
8921 (setq org-occur-highlights nil)
8922 (setq org-occur-parameters nil)
8923 (unless noremove
8924 (remove-hook 'before-change-functions
8925 'org-remove-occur-highlights 'local))))
8926
8927 ;;;; Priorities
8928
8929 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8930 "Regular expression matching the priority indicator.")
8931
8932 (defvar org-remove-priority-next-time nil)
8933
8934 (defun org-priority-up ()
8935 "Increase the priority of the current item."
8936 (interactive)
8937 (org-priority 'up))
8938
8939 (defun org-priority-down ()
8940 "Decrease the priority of the current item."
8941 (interactive)
8942 (org-priority 'down))
8943
8944 (defun org-priority (&optional action)
8945 "Change the priority of an item by ARG.
8946 ACTION can be `set', `up', `down', or a character."
8947 (interactive)
8948 (setq action (or action 'set))
8949 (let (current new news have remove)
8950 (save-excursion
8951 (org-back-to-heading)
8952 (if (looking-at org-priority-regexp)
8953 (setq current (string-to-char (match-string 2))
8954 have t)
8955 (setq current org-default-priority))
8956 (cond
8957 ((or (eq action 'set)
8958 (if (featurep 'xemacs) (characterp action) (integerp action)))
8959 (if (not (eq action 'set))
8960 (setq new action)
8961 (message "Priority %c-%c, SPC to remove: "
8962 org-highest-priority org-lowest-priority)
8963 (setq new (read-char-exclusive)))
8964 (if (and (= (upcase org-highest-priority) org-highest-priority)
8965 (= (upcase org-lowest-priority) org-lowest-priority))
8966 (setq new (upcase new)))
8967 (cond ((equal new ?\ ) (setq remove t))
8968 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8969 (error "Priority must be between `%c' and `%c'"
8970 org-highest-priority org-lowest-priority))))
8971 ((eq action 'up)
8972 (if (and (not have) (eq last-command this-command))
8973 (setq new org-lowest-priority)
8974 (setq new (if (and org-priority-start-cycle-with-default (not have))
8975 org-default-priority (1- current)))))
8976 ((eq action 'down)
8977 (if (and (not have) (eq last-command this-command))
8978 (setq new org-highest-priority)
8979 (setq new (if (and org-priority-start-cycle-with-default (not have))
8980 org-default-priority (1+ current)))))
8981 (t (error "Invalid action")))
8982 (if (or (< (upcase new) org-highest-priority)
8983 (> (upcase new) org-lowest-priority))
8984 (setq remove t))
8985 (setq news (format "%c" new))
8986 (if have
8987 (if remove
8988 (replace-match "" t t nil 1)
8989 (replace-match news t t nil 2))
8990 (if remove
8991 (error "No priority cookie found in line")
8992 (looking-at org-todo-line-regexp)
8993 (if (match-end 2)
8994 (progn
8995 (goto-char (match-end 2))
8996 (insert " [#" news "]"))
8997 (goto-char (match-beginning 3))
8998 (insert "[#" news "] ")))))
8999 (org-preserve-lc (org-set-tags nil 'align))
9000 (if remove
9001 (message "Priority removed")
9002 (message "Priority of current item set to %s" news))))
9003
9004
9005 (defun org-get-priority (s)
9006 "Find priority cookie and return priority."
9007 (save-match-data
9008 (if (not (string-match org-priority-regexp s))
9009 (* 1000 (- org-lowest-priority org-default-priority))
9010 (* 1000 (- org-lowest-priority
9011 (string-to-char (match-string 2 s)))))))
9012
9013 ;;;; Tags
9014
9015 (defvar org-agenda-archives-mode)
9016 (defun org-scan-tags (action matcher &optional todo-only)
9017 "Scan headline tags with inheritance and produce output ACTION.
9018
9019 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9020 or `agenda' to produce an entry list for an agenda view. It can also be
9021 a Lisp form or a function that should be called at each matched headline, in
9022 this case the return value is a list of all return values from these calls.
9023
9024 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9025 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9026 only lines with a TODO keyword are included in the output."
9027 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9028 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9029 (org-re
9030 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9031 (props (list 'face 'default
9032 'done-face 'org-done
9033 'undone-face 'default
9034 'mouse-face 'highlight
9035 'org-not-done-regexp org-not-done-regexp
9036 'org-todo-regexp org-todo-regexp
9037 'keymap org-agenda-keymap
9038 'help-echo
9039 (format "mouse-2 or RET jump to org file %s"
9040 (abbreviate-file-name
9041 (or (buffer-file-name (buffer-base-buffer))
9042 (buffer-name (buffer-base-buffer)))))))
9043 (case-fold-search nil)
9044 lspos tags tags-list
9045 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9046 (llast 0) rtn rtn1 level category i txt
9047 todo marker entry priority)
9048 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9049 (setq action (list 'lambda nil action)))
9050 (save-excursion
9051 (goto-char (point-min))
9052 (when (eq action 'sparse-tree)
9053 (org-overview)
9054 (org-remove-occur-highlights))
9055 (while (re-search-forward re nil t)
9056 (catch :skip
9057 (setq todo (if (match-end 1) (match-string 2))
9058 tags (if (match-end 4) (match-string 4)))
9059 (goto-char (setq lspos (1+ (match-beginning 0))))
9060 (setq level (org-reduced-level (funcall outline-level))
9061 category (org-get-category))
9062 (setq i llast llast level)
9063 ;; remove tag lists from same and sublevels
9064 (while (>= i level)
9065 (when (setq entry (assoc i tags-alist))
9066 (setq tags-alist (delete entry tags-alist)))
9067 (setq i (1- i)))
9068 ;; add the next tags
9069 (when tags
9070 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9071 tags-alist
9072 (cons (cons level tags) tags-alist)))
9073 ;; compile tags for current headline
9074 (setq tags-list
9075 (if org-use-tag-inheritance
9076 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9077 tags))
9078 (when org-use-tag-inheritance
9079 (setcdr (car tags-alist)
9080 (mapcar (lambda (x)
9081 (setq x (copy-sequence x))
9082 (org-add-prop-inherited x))
9083 (cdar tags-alist))))
9084 (when (and tags org-use-tag-inheritance
9085 (not (eq t org-use-tag-inheritance)))
9086 ;; selective inheritance, remove uninherited ones
9087 (setcdr (car tags-alist)
9088 (org-remove-uniherited-tags (cdar tags-alist))))
9089 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9090 (let ((case-fold-search t)) (eval matcher))
9091 (or
9092 (not (member org-archive-tag tags-list))
9093 ;; we have an archive tag, should we use this anyway?
9094 (or (not org-agenda-skip-archived-trees)
9095 (and (eq action 'agenda) org-agenda-archives-mode))))
9096 (unless (eq action 'sparse-tree) (org-agenda-skip))
9097
9098 ;; select this headline
9099
9100 (cond
9101 ((eq action 'sparse-tree)
9102 (and org-highlight-sparse-tree-matches
9103 (org-get-heading) (match-end 0)
9104 (org-highlight-new-match
9105 (match-beginning 0) (match-beginning 1)))
9106 (org-show-context 'tags-tree))
9107 ((eq action 'agenda)
9108 (setq txt (org-format-agenda-item
9109 ""
9110 (concat
9111 (if org-tags-match-list-sublevels
9112 (make-string (1- level) ?.) "")
9113 (org-get-heading))
9114 category tags-list)
9115 priority (org-get-priority txt))
9116 (goto-char lspos)
9117 (setq marker (org-agenda-new-marker))
9118 (org-add-props txt props
9119 'org-marker marker 'org-hd-marker marker 'org-category category
9120 'priority priority 'type "tagsmatch")
9121 (push txt rtn))
9122 ((functionp action)
9123 (save-excursion
9124 (setq rtn1 (funcall action))
9125 (push rtn1 rtn))
9126 (goto-char (point-at-eol)))
9127 (t (error "Invalid action")))
9128
9129 ;; if we are to skip sublevels, jump to end of subtree
9130 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9131 (when (and (eq action 'sparse-tree)
9132 (not org-sparse-tree-open-archived-trees))
9133 (org-hide-archived-subtrees (point-min) (point-max)))
9134 (nreverse rtn)))
9135
9136 (defun org-remove-uniherited-tags (tags)
9137 "Remove all tags that are not inherited from the list TAGS."
9138 (cond
9139 ((eq org-use-tag-inheritance t)
9140 (if org-tags-exclude-from-inheritance
9141 (org-delete-all org-tags-exclude-from-inheritance tags)
9142 tags))
9143 ((not org-use-tag-inheritance) nil)
9144 ((stringp org-use-tag-inheritance)
9145 (delq nil (mapcar
9146 (lambda (x)
9147 (if (and (string-match org-use-tag-inheritance x)
9148 (not (member x org-tags-exclude-from-inheritance)))
9149 x nil))
9150 tags)))
9151 ((listp org-use-tag-inheritance)
9152 (delq nil (mapcar
9153 (lambda (x)
9154 (if (member x org-use-tag-inheritance) x nil))
9155 tags)))))
9156
9157 (defvar todo-only) ;; dynamically scoped
9158
9159 (defun org-tags-sparse-tree (&optional todo-only match)
9160 "Create a sparse tree according to tags string MATCH.
9161 MATCH can contain positive and negative selection of tags, like
9162 \"+WORK+URGENT-WITHBOSS\".
9163 If optional argument TODO-ONLY is non-nil, only select lines that are
9164 also TODO lines."
9165 (interactive "P")
9166 (org-prepare-agenda-buffers (list (current-buffer)))
9167 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9168
9169 (defvar org-cached-props nil)
9170 (defun org-cached-entry-get (pom property)
9171 (if (or (eq t org-use-property-inheritance)
9172 (and (stringp org-use-property-inheritance)
9173 (string-match org-use-property-inheritance property))
9174 (and (listp org-use-property-inheritance)
9175 (member property org-use-property-inheritance)))
9176 ;; Caching is not possible, check it directly
9177 (org-entry-get pom property 'inherit)
9178 ;; Get all properties, so that we can do complicated checks easily
9179 (cdr (assoc property (or org-cached-props
9180 (setq org-cached-props
9181 (org-entry-properties pom)))))))
9182
9183 (defun org-global-tags-completion-table (&optional files)
9184 "Return the list of all tags in all agenda buffer/files."
9185 (save-excursion
9186 (org-uniquify
9187 (delq nil
9188 (apply 'append
9189 (mapcar
9190 (lambda (file)
9191 (set-buffer (find-file-noselect file))
9192 (append (org-get-buffer-tags)
9193 (mapcar (lambda (x) (if (stringp (car-safe x))
9194 (list (car-safe x)) nil))
9195 org-tag-alist)))
9196 (if (and files (car files))
9197 files
9198 (org-agenda-files))))))))
9199
9200 (defun org-make-tags-matcher (match)
9201 "Create the TAGS//TODO matcher form for the selection string MATCH."
9202 ;; todo-only is scoped dynamically into this function, and the function
9203 ;; may change it it the matcher asksk for it.
9204 (unless match
9205 ;; Get a new match request, with completion
9206 (let ((org-last-tags-completion-table
9207 (org-global-tags-completion-table)))
9208 (setq match (org-ido-completing-read
9209 "Match: " 'org-tags-completion-function nil nil nil
9210 'org-tags-history))))
9211
9212 ;; Parse the string and create a lisp form
9213 (let ((match0 match)
9214 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9215 minus tag mm
9216 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9217 orterms term orlist re-p str-p level-p level-op time-p
9218 prop-p pn pv po cat-p gv rest)
9219 (if (string-match "/+" match)
9220 ;; match contains also a todo-matching request
9221 (progn
9222 (setq tagsmatch (substring match 0 (match-beginning 0))
9223 todomatch (substring match (match-end 0)))
9224 (if (string-match "^!" todomatch)
9225 (setq todo-only t todomatch (substring todomatch 1)))
9226 (if (string-match "^\\s-*$" todomatch)
9227 (setq todomatch nil)))
9228 ;; only matching tags
9229 (setq tagsmatch match todomatch nil))
9230
9231 ;; Make the tags matcher
9232 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9233 (setq tagsmatcher t)
9234 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9235 (while (setq term (pop orterms))
9236 (while (and (equal (substring term -1) "\\") orterms)
9237 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9238 (while (string-match re term)
9239 (setq rest (substring term (match-end 0))
9240 minus (and (match-end 1)
9241 (equal (match-string 1 term) "-"))
9242 tag (match-string 2 term)
9243 re-p (equal (string-to-char tag) ?{)
9244 level-p (match-end 4)
9245 prop-p (match-end 5)
9246 mm (cond
9247 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9248 (level-p
9249 (setq level-op (org-op-to-function (match-string 3 term)))
9250 `(,level-op level ,(string-to-number
9251 (match-string 4 term))))
9252 (prop-p
9253 (setq pn (match-string 5 term)
9254 po (match-string 6 term)
9255 pv (match-string 7 term)
9256 cat-p (equal pn "CATEGORY")
9257 re-p (equal (string-to-char pv) ?{)
9258 str-p (equal (string-to-char pv) ?\")
9259 time-p (save-match-data
9260 (string-match "^\"[[<].*[]>]\"$" pv))
9261 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9262 (if time-p (setq pv (org-matcher-time pv)))
9263 (setq po (org-op-to-function po (if time-p 'time str-p)))
9264 (cond
9265 ((equal pn "CATEGORY")
9266 (setq gv '(get-text-property (point) 'org-category)))
9267 ((equal pn "TODO")
9268 (setq gv 'todo))
9269 (t
9270 (setq gv `(org-cached-entry-get nil ,pn))))
9271 (if re-p
9272 (if (eq po 'org<>)
9273 `(not (string-match ,pv (or ,gv "")))
9274 `(string-match ,pv (or ,gv "")))
9275 (if str-p
9276 `(,po (or ,gv "") ,pv)
9277 `(,po (string-to-number (or ,gv ""))
9278 ,(string-to-number pv) ))))
9279 (t `(member ,(downcase tag) tags-list)))
9280 mm (if minus (list 'not mm) mm)
9281 term rest)
9282 (push mm tagsmatcher))
9283 (push (if (> (length tagsmatcher) 1)
9284 (cons 'and tagsmatcher)
9285 (car tagsmatcher))
9286 orlist)
9287 (setq tagsmatcher nil))
9288 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9289 (setq tagsmatcher
9290 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9291 ;; Make the todo matcher
9292 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9293 (setq todomatcher t)
9294 (setq orterms (org-split-string todomatch "|") orlist nil)
9295 (while (setq term (pop orterms))
9296 (while (string-match re term)
9297 (setq minus (and (match-end 1)
9298 (equal (match-string 1 term) "-"))
9299 kwd (match-string 2 term)
9300 re-p (equal (string-to-char kwd) ?{)
9301 term (substring term (match-end 0))
9302 mm (if re-p
9303 `(string-match ,(substring kwd 1 -1) todo)
9304 (list 'equal 'todo kwd))
9305 mm (if minus (list 'not mm) mm))
9306 (push mm todomatcher))
9307 (push (if (> (length todomatcher) 1)
9308 (cons 'and todomatcher)
9309 (car todomatcher))
9310 orlist)
9311 (setq todomatcher nil))
9312 (setq todomatcher (if (> (length orlist) 1)
9313 (cons 'or orlist) (car orlist))))
9314
9315 ;; Return the string and lisp forms of the matcher
9316 (setq matcher (if todomatcher
9317 (list 'and tagsmatcher todomatcher)
9318 tagsmatcher))
9319 (cons match0 matcher)))
9320
9321 (defun org-op-to-function (op &optional stringp)
9322 "Turn an operator into the appropriate function."
9323 (setq op
9324 (cond
9325 ((equal op "<" ) '(< string< org-time<))
9326 ((equal op ">" ) '(> org-string> org-time>))
9327 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9328 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9329 ((member op '("=" "==")) '(= string= org-time=))
9330 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9331 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9332
9333 (defun org<> (a b) (not (= a b)))
9334 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9335 (defun org-string>= (a b) (not (string< a b)))
9336 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9337 (defun org-string<> (a b) (not (string= a b)))
9338 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9339 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9340 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9341 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9342 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9343 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9344 (defun org-2ft (s)
9345 "Convert S to a floating point time.
9346 If S is already a number, just return it. If it is a string, parse
9347 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9348 (cond
9349 ((numberp s) s)
9350 ((stringp s)
9351 (condition-case nil
9352 (float-time (apply 'encode-time (org-parse-time-string s)))
9353 (error 0.)))
9354 (t 0.)))
9355
9356 (defun org-time-today ()
9357 "Time in seconds today at 0:00.
9358 Returns the float number of seconds since the beginning of the
9359 epoch to the beginning of today (00:00)."
9360 (float-time (apply 'encode-time
9361 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9362
9363 (defun org-matcher-time (s)
9364 "Interprete a time comparison value."
9365 (save-match-data
9366 (cond
9367 ((string= s "<now>") (float-time))
9368 ((string= s "<today>") (org-time-today))
9369 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9370 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9371 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9372 (+ (org-time-today)
9373 (* (string-to-number (match-string 1 s))
9374 (cdr (assoc (match-string 2 s)
9375 '(("d" . 86400.0) ("w" . 604800.0)
9376 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9377 (t (org-2ft s)))))
9378
9379 (defun org-match-any-p (re list)
9380 "Does re match any element of list?"
9381 (setq list (mapcar (lambda (x) (string-match re x)) list))
9382 (delq nil list))
9383
9384 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9385 (defvar org-tags-overlay (org-make-overlay 1 1))
9386 (org-detach-overlay org-tags-overlay)
9387
9388 (defun org-get-local-tags-at (&optional pos)
9389 "Get a list of tags defined in the current headline."
9390 (org-get-tags-at pos 'local))
9391
9392 (defun org-get-local-tags ()
9393 "Get a list of tags defined in the current headline."
9394 (org-get-tags-at nil 'local))
9395
9396 (defun org-get-tags-at (&optional pos local)
9397 "Get a list of all headline tags applicable at POS.
9398 POS defaults to point. If tags are inherited, the list contains
9399 the targets in the same sequence as the headlines appear, i.e.
9400 the tags of the current headline come last.
9401 When LOCAL is non-nil, only return tags from the current headline,
9402 ignore inherited ones."
9403 (interactive)
9404 (let (tags ltags lastpos parent)
9405 (save-excursion
9406 (save-restriction
9407 (widen)
9408 (goto-char (or pos (point)))
9409 (save-match-data
9410 (catch 'done
9411 (condition-case nil
9412 (progn
9413 (org-back-to-heading t)
9414 (while (not (equal lastpos (point)))
9415 (setq lastpos (point))
9416 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9417 (setq ltags (org-split-string
9418 (org-match-string-no-properties 1) ":"))
9419 (when parent
9420 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9421 (setq tags (append
9422 (if parent
9423 (org-remove-uniherited-tags ltags)
9424 ltags)
9425 tags)))
9426 (or org-use-tag-inheritance (throw 'done t))
9427 (if local (throw 'done t))
9428 (org-up-heading-all 1)
9429 (setq parent t)))
9430 (error nil)))))
9431 (append (org-remove-uniherited-tags org-file-tags) tags))))
9432
9433 (defun org-add-prop-inherited (s)
9434 (add-text-properties 0 (length s) '(inherited t) s)
9435 s)
9436
9437 (defun org-toggle-tag (tag &optional onoff)
9438 "Toggle the tag TAG for the current line.
9439 If ONOFF is `on' or `off', don't toggle but set to this state."
9440 (unless (org-on-heading-p t) (error "Not on headling"))
9441 (let (res current)
9442 (save-excursion
9443 (beginning-of-line)
9444 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9445 (point-at-eol) t)
9446 (progn
9447 (setq current (match-string 1))
9448 (replace-match ""))
9449 (setq current ""))
9450 (setq current (nreverse (org-split-string current ":")))
9451 (cond
9452 ((eq onoff 'on)
9453 (setq res t)
9454 (or (member tag current) (push tag current)))
9455 ((eq onoff 'off)
9456 (or (not (member tag current)) (setq current (delete tag current))))
9457 (t (if (member tag current)
9458 (setq current (delete tag current))
9459 (setq res t)
9460 (push tag current))))
9461 (end-of-line 1)
9462 (if current
9463 (progn
9464 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9465 (org-set-tags nil t))
9466 (delete-horizontal-space))
9467 (run-hooks 'org-after-tags-change-hook))
9468 res))
9469
9470 (defun org-align-tags-here (to-col)
9471 ;; Assumes that this is a headline
9472 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9473 (beginning-of-line 1)
9474 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9475 (< pos (match-beginning 2)))
9476 (progn
9477 (setq tags-l (- (match-end 2) (match-beginning 2)))
9478 (goto-char (match-beginning 1))
9479 (insert " ")
9480 (delete-region (point) (1+ (match-beginning 2)))
9481 (setq ncol (max (1+ (current-column))
9482 (1+ col)
9483 (if (> to-col 0)
9484 to-col
9485 (- (abs to-col) tags-l))))
9486 (setq p (point))
9487 (insert (make-string (- ncol (current-column)) ?\ ))
9488 (setq ncol (current-column))
9489 (when indent-tabs-mode (tabify p (point-at-eol)))
9490 (org-move-to-column (min ncol col) t))
9491 (goto-char pos))))
9492
9493 (defun org-set-tags-command (&optional arg just-align)
9494 "Call the set-tags command for the current entry."
9495 (interactive "P")
9496 (if (org-on-heading-p)
9497 (org-set-tags arg just-align)
9498 (save-excursion
9499 (org-back-to-heading t)
9500 (org-set-tags arg just-align))))
9501
9502 (defun org-set-tags (&optional arg just-align)
9503 "Set the tags for the current headline.
9504 With prefix ARG, realign all tags in headings in the current buffer."
9505 (interactive "P")
9506 (let* ((re (concat "^" outline-regexp))
9507 (current (org-get-tags-string))
9508 (col (current-column))
9509 (org-setting-tags t)
9510 table current-tags inherited-tags ; computed below when needed
9511 tags p0 c0 c1 rpl)
9512 (if arg
9513 (save-excursion
9514 (goto-char (point-min))
9515 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9516 (while (re-search-forward re nil t)
9517 (org-set-tags nil t)
9518 (end-of-line 1)))
9519 (message "All tags realigned to column %d" org-tags-column))
9520 (if just-align
9521 (setq tags current)
9522 ;; Get a new set of tags from the user
9523 (save-excursion
9524 (setq table (or org-tag-alist (org-get-buffer-tags))
9525 org-last-tags-completion-table table
9526 current-tags (org-split-string current ":")
9527 inherited-tags (nreverse
9528 (nthcdr (length current-tags)
9529 (nreverse (org-get-tags-at))))
9530 tags
9531 (if (or (eq t org-use-fast-tag-selection)
9532 (and org-use-fast-tag-selection
9533 (delq nil (mapcar 'cdr table))))
9534 (org-fast-tag-selection
9535 current-tags inherited-tags table
9536 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9537 (let ((org-add-colon-after-tag-completion t))
9538 (org-trim
9539 (org-without-partial-completion
9540 (org-ido-completing-read "Tags: " 'org-tags-completion-function
9541 nil nil current 'org-tags-history)))))))
9542 (while (string-match "[-+&]+" tags)
9543 ;; No boolean logic, just a list
9544 (setq tags (replace-match ":" t t tags))))
9545
9546 (if (string-match "\\`[\t ]*\\'" tags)
9547 (setq tags "")
9548 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9549 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9550
9551 ;; Insert new tags at the correct column
9552 (beginning-of-line 1)
9553 (cond
9554 ((and (equal current "") (equal tags "")))
9555 ((re-search-forward
9556 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9557 (point-at-eol) t)
9558 (if (equal tags "")
9559 (setq rpl "")
9560 (goto-char (match-beginning 0))
9561 (setq c0 (current-column) p0 (point)
9562 c1 (max (1+ c0) (if (> org-tags-column 0)
9563 org-tags-column
9564 (- (- org-tags-column) (length tags))))
9565 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9566 (replace-match rpl t t)
9567 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9568 tags)
9569 (t (error "Tags alignment failed")))
9570 (org-move-to-column col)
9571 (unless just-align
9572 (run-hooks 'org-after-tags-change-hook)))))
9573
9574 (defun org-change-tag-in-region (beg end tag off)
9575 "Add or remove TAG for each entry in the region.
9576 This works in the agenda, and also in an org-mode buffer."
9577 (interactive
9578 (list (region-beginning) (region-end)
9579 (let ((org-last-tags-completion-table
9580 (if (org-mode-p)
9581 (org-get-buffer-tags)
9582 (org-global-tags-completion-table))))
9583 (org-ido-completing-read
9584 "Tag: " 'org-tags-completion-function nil nil nil
9585 'org-tags-history))
9586 (progn
9587 (message "[s]et or [r]emove? ")
9588 (equal (read-char-exclusive) ?r))))
9589 (if (fboundp 'deactivate-mark) (deactivate-mark))
9590 (let ((agendap (equal major-mode 'org-agenda-mode))
9591 l1 l2 m buf pos newhead (cnt 0))
9592 (goto-char end)
9593 (setq l2 (1- (org-current-line)))
9594 (goto-char beg)
9595 (setq l1 (org-current-line))
9596 (loop for l from l1 to l2 do
9597 (goto-line l)
9598 (setq m (get-text-property (point) 'org-hd-marker))
9599 (when (or (and (org-mode-p) (org-on-heading-p))
9600 (and agendap m))
9601 (setq buf (if agendap (marker-buffer m) (current-buffer))
9602 pos (if agendap m (point)))
9603 (with-current-buffer buf
9604 (save-excursion
9605 (save-restriction
9606 (goto-char pos)
9607 (setq cnt (1+ cnt))
9608 (org-toggle-tag tag (if off 'off 'on))
9609 (setq newhead (org-get-heading)))))
9610 (and agendap (org-agenda-change-all-lines newhead m))))
9611 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9612
9613 (defun org-tags-completion-function (string predicate &optional flag)
9614 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9615 (confirm (lambda (x) (stringp (car x)))))
9616 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9617 (setq s1 (match-string 1 string)
9618 s2 (match-string 2 string))
9619 (setq s1 "" s2 string))
9620 (cond
9621 ((eq flag nil)
9622 ;; try completion
9623 (setq rtn (try-completion s2 ctable confirm))
9624 (if (stringp rtn)
9625 (setq rtn
9626 (concat s1 s2 (substring rtn (length s2))
9627 (if (and org-add-colon-after-tag-completion
9628 (assoc rtn ctable))
9629 ":" ""))))
9630 rtn)
9631 ((eq flag t)
9632 ;; all-completions
9633 (all-completions s2 ctable confirm)
9634 )
9635 ((eq flag 'lambda)
9636 ;; exact match?
9637 (assoc s2 ctable)))
9638 ))
9639
9640 (defun org-fast-tag-insert (kwd tags face &optional end)
9641 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9642 (insert (format "%-12s" (concat kwd ":"))
9643 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9644 (or end "")))
9645
9646 (defun org-fast-tag-show-exit (flag)
9647 (save-excursion
9648 (goto-line 3)
9649 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9650 (replace-match ""))
9651 (when flag
9652 (end-of-line 1)
9653 (org-move-to-column (- (window-width) 19) t)
9654 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9655
9656 (defun org-set-current-tags-overlay (current prefix)
9657 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9658 (if (featurep 'xemacs)
9659 (org-overlay-display org-tags-overlay (concat prefix s)
9660 'secondary-selection)
9661 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9662 (org-overlay-display org-tags-overlay (concat prefix s)))))
9663
9664 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9665 "Fast tag selection with single keys.
9666 CURRENT is the current list of tags in the headline, INHERITED is the
9667 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9668 possibly with grouping information. TODO-TABLE is a similar table with
9669 TODO keywords, should these have keys assigned to them.
9670 If the keys are nil, a-z are automatically assigned.
9671 Returns the new tags string, or nil to not change the current settings."
9672 (let* ((fulltable (append table todo-table))
9673 (maxlen (apply 'max (mapcar
9674 (lambda (x)
9675 (if (stringp (car x)) (string-width (car x)) 0))
9676 fulltable)))
9677 (buf (current-buffer))
9678 (expert (eq org-fast-tag-selection-single-key 'expert))
9679 (buffer-tags nil)
9680 (fwidth (+ maxlen 3 1 3))
9681 (ncol (/ (- (window-width) 4) fwidth))
9682 (i-face 'org-done)
9683 (c-face 'org-todo)
9684 tg cnt e c char c1 c2 ntable tbl rtn
9685 ov-start ov-end ov-prefix
9686 (exit-after-next org-fast-tag-selection-single-key)
9687 (done-keywords org-done-keywords)
9688 groups ingroup)
9689 (save-excursion
9690 (beginning-of-line 1)
9691 (if (looking-at
9692 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9693 (setq ov-start (match-beginning 1)
9694 ov-end (match-end 1)
9695 ov-prefix "")
9696 (setq ov-start (1- (point-at-eol))
9697 ov-end (1+ ov-start))
9698 (skip-chars-forward "^\n\r")
9699 (setq ov-prefix
9700 (concat
9701 (buffer-substring (1- (point)) (point))
9702 (if (> (current-column) org-tags-column)
9703 " "
9704 (make-string (- org-tags-column (current-column)) ?\ ))))))
9705 (org-move-overlay org-tags-overlay ov-start ov-end)
9706 (save-window-excursion
9707 (if expert
9708 (set-buffer (get-buffer-create " *Org tags*"))
9709 (delete-other-windows)
9710 (split-window-vertically)
9711 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9712 (erase-buffer)
9713 (org-set-local 'org-done-keywords done-keywords)
9714 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9715 (org-fast-tag-insert "Current" current c-face "\n\n")
9716 (org-fast-tag-show-exit exit-after-next)
9717 (org-set-current-tags-overlay current ov-prefix)
9718 (setq tbl fulltable char ?a cnt 0)
9719 (while (setq e (pop tbl))
9720 (cond
9721 ((equal e '(:startgroup))
9722 (push '() groups) (setq ingroup t)
9723 (when (not (= cnt 0))
9724 (setq cnt 0)
9725 (insert "\n"))
9726 (insert "{ "))
9727 ((equal e '(:endgroup))
9728 (setq ingroup nil cnt 0)
9729 (insert "}\n"))
9730 (t
9731 (setq tg (car e) c2 nil)
9732 (if (cdr e)
9733 (setq c (cdr e))
9734 ;; automatically assign a character.
9735 (setq c1 (string-to-char
9736 (downcase (substring
9737 tg (if (= (string-to-char tg) ?@) 1 0)))))
9738 (if (or (rassoc c1 ntable) (rassoc c1 table))
9739 (while (or (rassoc char ntable) (rassoc char table))
9740 (setq char (1+ char)))
9741 (setq c2 c1))
9742 (setq c (or c2 char)))
9743 (if ingroup (push tg (car groups)))
9744 (setq tg (org-add-props tg nil 'face
9745 (cond
9746 ((not (assoc tg table))
9747 (org-get-todo-face tg))
9748 ((member tg current) c-face)
9749 ((member tg inherited) i-face)
9750 (t nil))))
9751 (if (and (= cnt 0) (not ingroup)) (insert " "))
9752 (insert "[" c "] " tg (make-string
9753 (- fwidth 4 (length tg)) ?\ ))
9754 (push (cons tg c) ntable)
9755 (when (= (setq cnt (1+ cnt)) ncol)
9756 (insert "\n")
9757 (if ingroup (insert " "))
9758 (setq cnt 0)))))
9759 (setq ntable (nreverse ntable))
9760 (insert "\n")
9761 (goto-char (point-min))
9762 (if (not expert) (org-fit-window-to-buffer))
9763 (setq rtn
9764 (catch 'exit
9765 (while t
9766 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9767 (if groups " [!] no groups" " [!]groups")
9768 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9769 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9770 (cond
9771 ((= c ?\r) (throw 'exit t))
9772 ((= c ?!)
9773 (setq groups (not groups))
9774 (goto-char (point-min))
9775 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9776 ((= c ?\C-c)
9777 (if (not expert)
9778 (org-fast-tag-show-exit
9779 (setq exit-after-next (not exit-after-next)))
9780 (setq expert nil)
9781 (delete-other-windows)
9782 (split-window-vertically)
9783 (org-switch-to-buffer-other-window " *Org tags*")
9784 (org-fit-window-to-buffer)))
9785 ((or (= c ?\C-g)
9786 (and (= c ?q) (not (rassoc c ntable))))
9787 (org-detach-overlay org-tags-overlay)
9788 (setq quit-flag t))
9789 ((= c ?\ )
9790 (setq current nil)
9791 (if exit-after-next (setq exit-after-next 'now)))
9792 ((= c ?\t)
9793 (condition-case nil
9794 (setq tg (org-ido-completing-read
9795 "Tag: "
9796 (or buffer-tags
9797 (with-current-buffer buf
9798 (org-get-buffer-tags)))))
9799 (quit (setq tg "")))
9800 (when (string-match "\\S-" tg)
9801 (add-to-list 'buffer-tags (list tg))
9802 (if (member tg current)
9803 (setq current (delete tg current))
9804 (push tg current)))
9805 (if exit-after-next (setq exit-after-next 'now)))
9806 ((setq e (rassoc c todo-table) tg (car e))
9807 (with-current-buffer buf
9808 (save-excursion (org-todo tg)))
9809 (if exit-after-next (setq exit-after-next 'now)))
9810 ((setq e (rassoc c ntable) tg (car e))
9811 (if (member tg current)
9812 (setq current (delete tg current))
9813 (loop for g in groups do
9814 (if (member tg g)
9815 (mapc (lambda (x)
9816 (setq current (delete x current)))
9817 g)))
9818 (push tg current))
9819 (if exit-after-next (setq exit-after-next 'now))))
9820
9821 ;; Create a sorted list
9822 (setq current
9823 (sort current
9824 (lambda (a b)
9825 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9826 (if (eq exit-after-next 'now) (throw 'exit t))
9827 (goto-char (point-min))
9828 (beginning-of-line 2)
9829 (delete-region (point) (point-at-eol))
9830 (org-fast-tag-insert "Current" current c-face)
9831 (org-set-current-tags-overlay current ov-prefix)
9832 (while (re-search-forward
9833 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9834 (setq tg (match-string 1))
9835 (add-text-properties
9836 (match-beginning 1) (match-end 1)
9837 (list 'face
9838 (cond
9839 ((member tg current) c-face)
9840 ((member tg inherited) i-face)
9841 (t (get-text-property (match-beginning 1) 'face))))))
9842 (goto-char (point-min)))))
9843 (org-detach-overlay org-tags-overlay)
9844 (if rtn
9845 (mapconcat 'identity current ":")
9846 nil))))
9847
9848 (defun org-get-tags-string ()
9849 "Get the TAGS string in the current headline."
9850 (unless (org-on-heading-p t)
9851 (error "Not on a heading"))
9852 (save-excursion
9853 (beginning-of-line 1)
9854 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9855 (org-match-string-no-properties 1)
9856 "")))
9857
9858 (defun org-get-tags ()
9859 "Get the list of tags specified in the current headline."
9860 (org-split-string (org-get-tags-string) ":"))
9861
9862 (defun org-get-buffer-tags ()
9863 "Get a table of all tags used in the buffer, for completion."
9864 (let (tags)
9865 (save-excursion
9866 (goto-char (point-min))
9867 (while (re-search-forward
9868 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9869 (when (equal (char-after (point-at-bol 0)) ?*)
9870 (mapc (lambda (x) (add-to-list 'tags x))
9871 (org-split-string (org-match-string-no-properties 1) ":")))))
9872 (mapcar 'list tags)))
9873
9874 ;;;; The mapping API
9875
9876 ;;;###autoload
9877 (defun org-map-entries (func &optional match scope &rest skip)
9878 "Call FUNC at each headline selected by MATCH in SCOPE.
9879
9880 FUNC is a function or a lisp form. The function will be called without
9881 arguments, with the cursor positioned at the beginning of the headline.
9882 The return values of all calls to the function will be collected and
9883 returned as a list.
9884
9885 MATCH is a tags/property/todo match as it is used in the agenda tags view.
9886 Only headlines that are matched by this query will be considered during
9887 the iteration. When MATCH is nil or t, all headlines will be
9888 visited by the iteration.
9889
9890 SCOPE determines the scope of this command. It can be any of:
9891
9892 nil The current buffer, respecting the restriction if any
9893 tree The subtree started with the entry at point
9894 file The current buffer, without restriction
9895 file-with-archives
9896 The current buffer, and any archives associated with it
9897 agenda All agenda files
9898 agenda-with-archives
9899 All agenda files with any archive files associated with them
9900 \(file1 file2 ...)
9901 If this is a list, all files in the list will be scanned
9902
9903 The remaining args are treated as settings for the skipping facilities of
9904 the scanner. The following items can be given here:
9905
9906 archive skip trees with the archive tag.
9907 comment skip trees with the COMMENT keyword
9908 function or Emacs Lisp form:
9909 will be used as value for `org-agenda-skip-function', so whenever
9910 the the function returns t, FUNC will not be called for that
9911 entry and search will continue from the point where the
9912 function leaves it."
9913 (let* ((org-agenda-archives-mode nil) ; just to make sure
9914 (org-agenda-skip-archived-trees (memq 'archive skip))
9915 (org-agenda-skip-comment-trees (memq 'comment skip))
9916 (org-agenda-skip-function
9917 (car (org-delete-all '(comment archive) skip)))
9918 (org-tags-match-list-sublevels t)
9919 matcher pos file res
9920 org-todo-keywords-for-agenda
9921 org-done-keywords-for-agenda
9922 org-todo-keyword-alist-for-agenda
9923 org-tag-alist-for-agenda)
9924
9925 (cond
9926 ((eq match t) (setq matcher t))
9927 ((eq match nil) (setq matcher t))
9928 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
9929
9930 (when (eq scope 'tree)
9931 (org-back-to-heading t)
9932 (org-narrow-to-subtree)
9933 (setq scope nil))
9934
9935 (if (not scope)
9936 (progn
9937 (org-prepare-agenda-buffers
9938 (list (buffer-file-name (current-buffer))))
9939 (org-scan-tags func matcher))
9940 ;; Get the right scope
9941 (setq pos (point))
9942 (cond
9943 ((and scope (listp scope) (symbolp (car scope)))
9944 (setq scope (eval scope)))
9945 ((eq scope 'agenda)
9946 (setq scope (org-agenda-files t)))
9947 ((eq scope 'agenda-with-archives)
9948 (setq scope (org-agenda-files t))
9949 (setq scope (org-add-archive-files scope)))
9950 ((eq scope 'file)
9951 (setq scope (list (buffer-file-name))))
9952 ((eq scope 'file-with-archives)
9953 (setq scope (org-add-archive-files (list (buffer-file-name))))))
9954 (org-prepare-agenda-buffers scope)
9955 (while (setq file (pop scope))
9956 (with-current-buffer (org-find-base-buffer-visiting file)
9957 (save-excursion
9958 (save-restriction
9959 (widen)
9960 (goto-char (point-min))
9961 (setq res (append res (org-scan-tags func matcher)))))))
9962 res)))
9963
9964 ;;;; Properties
9965
9966 ;;; Setting and retrieving properties
9967
9968 (defconst org-special-properties
9969 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
9970 "TIMESTAMP" "TIMESTAMP_IA")
9971 "The special properties valid in Org-mode.
9972
9973 These are properties that are not defined in the property drawer,
9974 but in some other way.")
9975
9976 (defconst org-default-properties
9977 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9978 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
9979 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
9980 "EXPORT_FILE_NAME" "EXPORT_TITLE")
9981 "Some properties that are used by Org-mode for various purposes.
9982 Being in this list makes sure that they are offered for completion.")
9983
9984 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9985 "Regular expression matching the first line of a property drawer.")
9986
9987 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9988 "Regular expression matching the first line of a property drawer.")
9989
9990 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
9991 "Regular expression matching the first line of a property drawer.")
9992
9993 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
9994 "Regular expression matching the first line of a property drawer.")
9995
9996 (defconst org-property-drawer-re
9997 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
9998 org-property-end-re "\\)\n?")
9999 "Matches an entire property drawer.")
10000
10001 (defconst org-clock-drawer-re
10002 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10003 org-property-end-re "\\)\n?")
10004 "Matches an entire clock drawer.")
10005
10006 (defun org-property-action ()
10007 "Do an action on properties."
10008 (interactive)
10009 (let (c)
10010 (org-at-property-p)
10011 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10012 (setq c (read-char-exclusive))
10013 (cond
10014 ((equal c ?s)
10015 (call-interactively 'org-set-property))
10016 ((equal c ?d)
10017 (call-interactively 'org-delete-property))
10018 ((equal c ?D)
10019 (call-interactively 'org-delete-property-globally))
10020 ((equal c ?c)
10021 (call-interactively 'org-compute-property-at-point))
10022 (t (error "No such property action %c" c)))))
10023
10024 (defun org-at-property-p ()
10025 "Is the cursor in a property line?"
10026 ;; FIXME: Does not check if we are actually in the drawer.
10027 ;; FIXME: also returns true on any drawers.....
10028 ;; This is used by C-c C-c for property action.
10029 (save-excursion
10030 (beginning-of-line 1)
10031 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10032
10033 (defun org-get-property-block (&optional beg end force)
10034 "Return the (beg . end) range of the body of the property drawer.
10035 BEG and END can be beginning and end of subtree, if not given
10036 they will be found.
10037 If the drawer does not exist and FORCE is non-nil, create the drawer."
10038 (catch 'exit
10039 (save-excursion
10040 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10041 (end (or end (progn (outline-next-heading) (point)))))
10042 (goto-char beg)
10043 (if (re-search-forward org-property-start-re end t)
10044 (setq beg (1+ (match-end 0)))
10045 (if force
10046 (save-excursion
10047 (org-insert-property-drawer)
10048 (setq end (progn (outline-next-heading) (point))))
10049 (throw 'exit nil))
10050 (goto-char beg)
10051 (if (re-search-forward org-property-start-re end t)
10052 (setq beg (1+ (match-end 0)))))
10053 (if (re-search-forward org-property-end-re end t)
10054 (setq end (match-beginning 0))
10055 (or force (throw 'exit nil))
10056 (goto-char beg)
10057 (setq end beg)
10058 (org-indent-line-function)
10059 (insert ":END:\n"))
10060 (cons beg end)))))
10061
10062 (defun org-entry-properties (&optional pom which)
10063 "Get all properties of the entry at point-or-marker POM.
10064 This includes the TODO keyword, the tags, time strings for deadline,
10065 scheduled, and clocking, and any additional properties defined in the
10066 entry. The return value is an alist, keys may occur multiple times
10067 if the property key was used several times.
10068 POM may also be nil, in which case the current entry is used.
10069 If WHICH is nil or `all', get all properties. If WHICH is
10070 `special' or `standard', only get that subclass."
10071 (setq which (or which 'all))
10072 (org-with-point-at pom
10073 (let ((clockstr (substring org-clock-string 0 -1))
10074 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10075 beg end range props sum-props key value string clocksum)
10076 (save-excursion
10077 (when (condition-case nil (org-back-to-heading t) (error nil))
10078 (setq beg (point))
10079 (setq sum-props (get-text-property (point) 'org-summaries))
10080 (setq clocksum (get-text-property (point) :org-clock-minutes))
10081 (outline-next-heading)
10082 (setq end (point))
10083 (when (memq which '(all special))
10084 ;; Get the special properties, like TODO and tags
10085 (goto-char beg)
10086 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10087 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10088 (when (looking-at org-priority-regexp)
10089 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10090 (when (and (setq value (org-get-tags-string))
10091 (string-match "\\S-" value))
10092 (push (cons "TAGS" value) props))
10093 (when (setq value (org-get-tags-at))
10094 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10095 props))
10096 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10097 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10098 string (if (equal key clockstr)
10099 (org-no-properties
10100 (org-trim
10101 (buffer-substring
10102 (match-beginning 3) (goto-char (point-at-eol)))))
10103 (substring (org-match-string-no-properties 3) 1 -1)))
10104 (unless key
10105 (if (= (char-after (match-beginning 3)) ?\[)
10106 (setq key "TIMESTAMP_IA")
10107 (setq key "TIMESTAMP")))
10108 (when (or (equal key clockstr) (not (assoc key props)))
10109 (push (cons key string) props)))
10110
10111 )
10112
10113 (when (memq which '(all standard))
10114 ;; Get the standard properties, like :PORP: ...
10115 (setq range (org-get-property-block beg end))
10116 (when range
10117 (goto-char (car range))
10118 (while (re-search-forward
10119 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10120 (cdr range) t)
10121 (setq key (org-match-string-no-properties 1)
10122 value (org-trim (or (org-match-string-no-properties 2) "")))
10123 (unless (member key excluded)
10124 (push (cons key (or value "")) props)))))
10125 (if clocksum
10126 (push (cons "CLOCKSUM"
10127 (org-columns-number-to-string (/ (float clocksum) 60.)
10128 'add_times))
10129 props))
10130 (unless (assoc "CATEGORY" props)
10131 (setq value (or (org-get-category)
10132 (progn (org-refresh-category-properties)
10133 (org-get-category))))
10134 (push (cons "CATEGORY" value) props))
10135 (append sum-props (nreverse props)))))))
10136
10137 (defun org-entry-get (pom property &optional inherit)
10138 "Get value of PROPERTY for entry at point-or-marker POM.
10139 If INHERIT is non-nil and the entry does not have the property,
10140 then also check higher levels of the hierarchy.
10141 If INHERIT is the symbol `selective', use inheritance only if the setting
10142 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10143 If the property is present but empty, the return value is the empty string.
10144 If the property is not present at all, nil is returned."
10145 (org-with-point-at pom
10146 (if (and inherit (if (eq inherit 'selective)
10147 (org-property-inherit-p property)
10148 t))
10149 (org-entry-get-with-inheritance property)
10150 (if (member property org-special-properties)
10151 ;; We need a special property. Use brute force, get all properties.
10152 (cdr (assoc property (org-entry-properties nil 'special)))
10153 (let ((range (org-get-property-block)))
10154 (if (and range
10155 (goto-char (car range))
10156 (re-search-forward
10157 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10158 (cdr range) t))
10159 ;; Found the property, return it.
10160 (if (match-end 1)
10161 (org-match-string-no-properties 1)
10162 "")))))))
10163
10164 (defun org-property-or-variable-value (var &optional inherit)
10165 "Check if there is a property fixing the value of VAR.
10166 If yes, return this value. If not, return the current value of the variable."
10167 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10168 (if (and prop (stringp prop) (string-match "\\S-" prop))
10169 (read prop)
10170 (symbol-value var))))
10171
10172 (defun org-entry-delete (pom property)
10173 "Delete the property PROPERTY from entry at point-or-marker POM."
10174 (org-with-point-at pom
10175 (if (member property org-special-properties)
10176 nil ; cannot delete these properties.
10177 (let ((range (org-get-property-block)))
10178 (if (and range
10179 (goto-char (car range))
10180 (re-search-forward
10181 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10182 (cdr range) t))
10183 (progn
10184 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10185 t)
10186 nil)))))
10187
10188 ;; Multi-values properties are properties that contain multiple values
10189 ;; These values are assumed to be single words, separated by whitespace.
10190 (defun org-entry-add-to-multivalued-property (pom property value)
10191 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10192 (let* ((old (org-entry-get pom property))
10193 (values (and old (org-split-string old "[ \t]"))))
10194 (setq value (org-entry-protect-space value))
10195 (unless (member value values)
10196 (setq values (cons value values))
10197 (org-entry-put pom property
10198 (mapconcat 'identity values " ")))))
10199
10200 (defun org-entry-remove-from-multivalued-property (pom property value)
10201 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10202 (let* ((old (org-entry-get pom property))
10203 (values (and old (org-split-string old "[ \t]"))))
10204 (setq value (org-entry-protect-space value))
10205 (when (member value values)
10206 (setq values (delete value values))
10207 (org-entry-put pom property
10208 (mapconcat 'identity values " ")))))
10209
10210 (defun org-entry-member-in-multivalued-property (pom property value)
10211 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10212 (let* ((old (org-entry-get pom property))
10213 (values (and old (org-split-string old "[ \t]"))))
10214 (setq value (org-entry-protect-space value))
10215 (member value values)))
10216
10217 (defun org-entry-get-multivalued-property (pom property)
10218 "Return a list of values in a multivalued property."
10219 (let* ((value (org-entry-get pom property))
10220 (values (and value (org-split-string value "[ \t]"))))
10221 (mapcar 'org-entry-restore-space values)))
10222
10223 (defun org-entry-put-multivalued-property (pom property &rest values)
10224 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10225 VALUES should be a list of strings. Spaces will be protected."
10226 (org-entry-put pom property
10227 (mapconcat 'org-entry-protect-space values " "))
10228 (let* ((value (org-entry-get pom property))
10229 (values (and value (org-split-string value "[ \t]"))))
10230 (mapcar 'org-entry-restore-space values)))
10231
10232 (defun org-entry-protect-space (s)
10233 "Protect spaces and newline in string S."
10234 (while (string-match " " s)
10235 (setq s (replace-match "%20" t t s)))
10236 (while (string-match "\n" s)
10237 (setq s (replace-match "%0A" t t s)))
10238 s)
10239
10240 (defun org-entry-restore-space (s)
10241 "Restore spaces and newline in string S."
10242 (while (string-match "%20" s)
10243 (setq s (replace-match " " t t s)))
10244 (while (string-match "%0A" s)
10245 (setq s (replace-match "\n" t t s)))
10246 s)
10247
10248 (defvar org-entry-property-inherited-from (make-marker)
10249 "Marker pointing to the entry from where a proerty was inherited.
10250 Each call to `org-entry-get-with-inheritance' will set this marker to the
10251 location of the entry where the inheriance search matched. If there was
10252 no match, the marker will point nowhere.
10253 Note that also `org-entry-get' calls this function, if the INHERIT flag
10254 is set.")
10255
10256 (defun org-entry-get-with-inheritance (property)
10257 "Get entry property, and search higher levels if not present."
10258 (move-marker org-entry-property-inherited-from nil)
10259 (let (tmp)
10260 (save-excursion
10261 (save-restriction
10262 (widen)
10263 (catch 'ex
10264 (while t
10265 (when (setq tmp (org-entry-get nil property))
10266 (org-back-to-heading t)
10267 (move-marker org-entry-property-inherited-from (point))
10268 (throw 'ex tmp))
10269 (or (org-up-heading-safe) (throw 'ex nil)))))
10270 (or tmp
10271 (cdr (assoc property org-file-properties))
10272 (cdr (assoc property org-global-properties))
10273 (cdr (assoc property org-global-properties-fixed))))))
10274
10275 (defun org-entry-put (pom property value)
10276 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10277 (org-with-point-at pom
10278 (org-back-to-heading t)
10279 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10280 range)
10281 (cond
10282 ((equal property "TODO")
10283 (when (and (stringp value) (string-match "\\S-" value)
10284 (not (member value org-todo-keywords-1)))
10285 (error "\"%s\" is not a valid TODO state" value))
10286 (if (or (not value)
10287 (not (string-match "\\S-" value)))
10288 (setq value 'none))
10289 (org-todo value)
10290 (org-set-tags nil 'align))
10291 ((equal property "PRIORITY")
10292 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10293 (string-to-char value) ?\ ))
10294 (org-set-tags nil 'align))
10295 ((equal property "SCHEDULED")
10296 (if (re-search-forward org-scheduled-time-regexp end t)
10297 (cond
10298 ((eq value 'earlier) (org-timestamp-change -1 'day))
10299 ((eq value 'later) (org-timestamp-change 1 'day))
10300 (t (call-interactively 'org-schedule)))
10301 (call-interactively 'org-schedule)))
10302 ((equal property "DEADLINE")
10303 (if (re-search-forward org-deadline-time-regexp end t)
10304 (cond
10305 ((eq value 'earlier) (org-timestamp-change -1 'day))
10306 ((eq value 'later) (org-timestamp-change 1 'day))
10307 (t (call-interactively 'org-deadline)))
10308 (call-interactively 'org-deadline)))
10309 ((member property org-special-properties)
10310 (error "The %s property can not yet be set with `org-entry-put'"
10311 property))
10312 (t ; a non-special property
10313 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10314 (setq range (org-get-property-block beg end 'force))
10315 (goto-char (car range))
10316 (if (re-search-forward
10317 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10318 (progn
10319 (delete-region (match-beginning 1) (match-end 1))
10320 (goto-char (match-beginning 1)))
10321 (goto-char (cdr range))
10322 (insert "\n")
10323 (backward-char 1)
10324 (org-indent-line-function)
10325 (insert ":" property ":"))
10326 (and value (insert " " value))
10327 (org-indent-line-function)))))))
10328
10329 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10330 "Get all property keys in the current buffer.
10331 With INCLUDE-SPECIALS, also list the special properties that relect things
10332 like tags and TODO state.
10333 With INCLUDE-DEFAULTS, also include properties that has special meaning
10334 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10335 With INCLUDE-COLUMNS, also include property names given in COLUMN
10336 formats in the current buffer."
10337 (let (rtn range cfmt cols s p)
10338 (save-excursion
10339 (save-restriction
10340 (widen)
10341 (goto-char (point-min))
10342 (while (re-search-forward org-property-start-re nil t)
10343 (setq range (org-get-property-block))
10344 (goto-char (car range))
10345 (while (re-search-forward
10346 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10347 (cdr range) t)
10348 (add-to-list 'rtn (org-match-string-no-properties 1)))
10349 (outline-next-heading))))
10350
10351 (when include-specials
10352 (setq rtn (append org-special-properties rtn)))
10353
10354 (when include-defaults
10355 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10356
10357 (when include-columns
10358 (save-excursion
10359 (save-restriction
10360 (widen)
10361 (goto-char (point-min))
10362 (while (re-search-forward
10363 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10364 nil t)
10365 (setq cfmt (match-string 2) s 0)
10366 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10367 cfmt s)
10368 (setq s (match-end 0)
10369 p (match-string 1 cfmt))
10370 (unless (or (equal p "ITEM")
10371 (member p org-special-properties))
10372 (add-to-list 'rtn (match-string 1 cfmt))))))))
10373
10374 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10375
10376 (defun org-property-values (key)
10377 "Return a list of all values of property KEY."
10378 (save-excursion
10379 (save-restriction
10380 (widen)
10381 (goto-char (point-min))
10382 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10383 values)
10384 (while (re-search-forward re nil t)
10385 (add-to-list 'values (org-trim (match-string 1))))
10386 (delete "" values)))))
10387
10388 (defun org-insert-property-drawer ()
10389 "Insert a property drawer into the current entry."
10390 (interactive)
10391 (org-back-to-heading t)
10392 (looking-at outline-regexp)
10393 (let ((indent (- (match-end 0)(match-beginning 0)))
10394 (beg (point))
10395 (re (concat "^[ \t]*" org-keyword-time-regexp))
10396 end hiddenp)
10397 (outline-next-heading)
10398 (setq end (point))
10399 (goto-char beg)
10400 (while (re-search-forward re end t))
10401 (setq hiddenp (org-invisible-p))
10402 (end-of-line 1)
10403 (and (equal (char-after) ?\n) (forward-char 1))
10404 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10405 (beginning-of-line 2))
10406 (org-skip-over-state-notes)
10407 (skip-chars-backward " \t\n\r")
10408 (if (eq (char-before) ?*) (forward-char 1))
10409 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10410 (beginning-of-line 0)
10411 (org-indent-to-column indent)
10412 (beginning-of-line 2)
10413 (org-indent-to-column indent)
10414 (beginning-of-line 0)
10415 (if hiddenp
10416 (save-excursion
10417 (org-back-to-heading t)
10418 (hide-entry))
10419 (org-flag-drawer t))))
10420
10421 (defun org-set-property (property value)
10422 "In the current entry, set PROPERTY to VALUE.
10423 When called interactively, this will prompt for a property name, offering
10424 completion on existing and default properties. And then it will prompt
10425 for a value, offering competion either on allowed values (via an inherited
10426 xxx_ALL property) or on existing values in other instances of this property
10427 in the current file."
10428 (interactive
10429 (let* ((completion-ignore-case t)
10430 (keys (org-buffer-property-keys nil t t))
10431 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10432 (prop (if (member prop0 keys)
10433 prop0
10434 (or (cdr (assoc (downcase prop0)
10435 (mapcar (lambda (x) (cons (downcase x) x))
10436 keys)))
10437 prop0)))
10438 (cur (org-entry-get nil prop))
10439 (allowed (org-property-get-allowed-values nil prop 'table))
10440 (existing (mapcar 'list (org-property-values prop)))
10441 (val (if allowed
10442 (org-completing-read "Value: " allowed nil 'req-match)
10443 (org-completing-read
10444 (concat "Value" (if (and cur (string-match "\\S-" cur))
10445 (concat "[" cur "]") "")
10446 ": ")
10447 existing nil nil "" nil cur))))
10448 (list prop (if (equal val "") cur val))))
10449 (unless (equal (org-entry-get nil property) value)
10450 (org-entry-put nil property value)))
10451
10452 (defun org-delete-property (property)
10453 "In the current entry, delete PROPERTY."
10454 (interactive
10455 (let* ((completion-ignore-case t)
10456 (prop (org-ido-completing-read
10457 "Property: " (org-entry-properties nil 'standard))))
10458 (list prop)))
10459 (message "Property %s %s" property
10460 (if (org-entry-delete nil property)
10461 "deleted"
10462 "was not present in the entry")))
10463
10464 (defun org-delete-property-globally (property)
10465 "Remove PROPERTY globally, from all entries."
10466 (interactive
10467 (let* ((completion-ignore-case t)
10468 (prop (org-ido-completing-read
10469 "Globally remove property: "
10470 (mapcar 'list (org-buffer-property-keys)))))
10471 (list prop)))
10472 (save-excursion
10473 (save-restriction
10474 (widen)
10475 (goto-char (point-min))
10476 (let ((cnt 0))
10477 (while (re-search-forward
10478 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10479 nil t)
10480 (setq cnt (1+ cnt))
10481 (replace-match ""))
10482 (message "Property \"%s\" removed from %d entries" property cnt)))))
10483
10484 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10485
10486 (defun org-compute-property-at-point ()
10487 "Compute the property at point.
10488 This looks for an enclosing column format, extracts the operator and
10489 then applies it to the proerty in the column format's scope."
10490 (interactive)
10491 (unless (org-at-property-p)
10492 (error "Not at a property"))
10493 (let ((prop (org-match-string-no-properties 2)))
10494 (org-columns-get-format-and-top-level)
10495 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10496 (error "No operator defined for property %s" prop))
10497 (org-columns-compute prop)))
10498
10499 (defun org-property-get-allowed-values (pom property &optional table)
10500 "Get allowed values for the property PROPERTY.
10501 When TABLE is non-nil, return an alist that can directly be used for
10502 completion."
10503 (let (vals)
10504 (cond
10505 ((equal property "TODO")
10506 (setq vals (org-with-point-at pom
10507 (append org-todo-keywords-1 '("")))))
10508 ((equal property "PRIORITY")
10509 (let ((n org-lowest-priority))
10510 (while (>= n org-highest-priority)
10511 (push (char-to-string n) vals)
10512 (setq n (1- n)))))
10513 ((member property org-special-properties))
10514 (t
10515 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10516
10517 (when (and vals (string-match "\\S-" vals))
10518 (setq vals (car (read-from-string (concat "(" vals ")"))))
10519 (setq vals (mapcar (lambda (x)
10520 (cond ((stringp x) x)
10521 ((numberp x) (number-to-string x))
10522 ((symbolp x) (symbol-name x))
10523 (t "???")))
10524 vals)))))
10525 (if table (mapcar 'list vals) vals)))
10526
10527 (defun org-property-previous-allowed-value (&optional previous)
10528 "Switch to the next allowed value for this property."
10529 (interactive)
10530 (org-property-next-allowed-value t))
10531
10532 (defun org-property-next-allowed-value (&optional previous)
10533 "Switch to the next allowed value for this property."
10534 (interactive)
10535 (unless (org-at-property-p)
10536 (error "Not at a property"))
10537 (let* ((key (match-string 2))
10538 (value (match-string 3))
10539 (allowed (or (org-property-get-allowed-values (point) key)
10540 (and (member value '("[ ]" "[-]" "[X]"))
10541 '("[ ]" "[X]"))))
10542 nval)
10543 (unless allowed
10544 (error "Allowed values for this property have not been defined"))
10545 (if previous (setq allowed (reverse allowed)))
10546 (if (member value allowed)
10547 (setq nval (car (cdr (member value allowed)))))
10548 (setq nval (or nval (car allowed)))
10549 (if (equal nval value)
10550 (error "Only one allowed value for this property"))
10551 (org-at-property-p)
10552 (replace-match (concat " :" key ": " nval) t t)
10553 (org-indent-line-function)
10554 (beginning-of-line 1)
10555 (skip-chars-forward " \t")))
10556
10557 (defun org-find-entry-with-id (ident)
10558 "Locate the entry that contains the ID property with exact value IDENT.
10559 IDENT can be a string, a symbol or a number, this function will search for
10560 the string representation of it.
10561 Return the position where this entry starts, or nil if there is no such entry."
10562 (let ((id (cond
10563 ((stringp ident) ident)
10564 ((symbol-name ident) (symbol-name ident))
10565 ((numberp ident) (number-to-string ident))
10566 (t (error "IDENT %s must be a string, symbol or number" ident))))
10567 (case-fold-search nil))
10568 (save-excursion
10569 (save-restriction
10570 (widen)
10571 (goto-char (point-min))
10572 (when (re-search-forward
10573 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10574 nil t)
10575 (org-back-to-heading)
10576 (point))))))
10577
10578 ;;;; Timestamps
10579
10580 (defvar org-last-changed-timestamp nil)
10581 (defvar org-last-inserted-timestamp nil
10582 "The last time stamp inserted with `org-insert-time-stamp'.")
10583 (defvar org-time-was-given) ; dynamically scoped parameter
10584 (defvar org-end-time-was-given) ; dynamically scoped parameter
10585 (defvar org-ts-what) ; dynamically scoped parameter
10586
10587 (defun org-time-stamp (arg &optional inactive)
10588 "Prompt for a date/time and insert a time stamp.
10589 If the user specifies a time like HH:MM, or if this command is called
10590 with a prefix argument, the time stamp will contain date and time.
10591 Otherwise, only the date will be included. All parts of a date not
10592 specified by the user will be filled in from the current date/time.
10593 So if you press just return without typing anything, the time stamp
10594 will represent the current date/time. If there is already a timestamp
10595 at the cursor, it will be modified."
10596 (interactive "P")
10597 (let* ((ts nil)
10598 (default-time
10599 ;; Default time is either today, or, when entering a range,
10600 ;; the range start.
10601 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10602 (save-excursion
10603 (re-search-backward
10604 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10605 (- (point) 20) t)))
10606 (apply 'encode-time (org-parse-time-string (match-string 1)))
10607 (current-time)))
10608 (default-input (and ts (org-get-compact-tod ts)))
10609 org-time-was-given org-end-time-was-given time)
10610 (cond
10611 ((and (org-at-timestamp-p t)
10612 (memq last-command '(org-time-stamp org-time-stamp-inactive))
10613 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
10614 (insert "--")
10615 (setq time (let ((this-command this-command))
10616 (org-read-date arg 'totime nil nil
10617 default-time default-input)))
10618 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
10619 ((org-at-timestamp-p t)
10620 (setq time (let ((this-command this-command))
10621 (org-read-date arg 'totime nil nil default-time default-input)))
10622 (when (org-at-timestamp-p t) ; just to get the match data
10623 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
10624 (replace-match "")
10625 (setq org-last-changed-timestamp
10626 (org-insert-time-stamp
10627 time (or org-time-was-given arg)
10628 inactive nil nil (list org-end-time-was-given))))
10629 (message "Timestamp updated"))
10630 (t
10631 (setq time (let ((this-command this-command))
10632 (org-read-date arg 'totime nil nil default-time default-input)))
10633 (org-insert-time-stamp time (or org-time-was-given arg) inactive
10634 nil nil (list org-end-time-was-given))))))
10635
10636 ;; FIXME: can we use this for something else, like computing time differences?
10637 (defun org-get-compact-tod (s)
10638 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10639 (let* ((t1 (match-string 1 s))
10640 (h1 (string-to-number (match-string 2 s)))
10641 (m1 (string-to-number (match-string 3 s)))
10642 (t2 (and (match-end 4) (match-string 5 s)))
10643 (h2 (and t2 (string-to-number (match-string 6 s))))
10644 (m2 (and t2 (string-to-number (match-string 7 s))))
10645 dh dm)
10646 (if (not t2)
10647 t1
10648 (setq dh (- h2 h1) dm (- m2 m1))
10649 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10650 (concat t1 "+" (number-to-string dh)
10651 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10652
10653 (defun org-time-stamp-inactive (&optional arg)
10654 "Insert an inactive time stamp.
10655 An inactive time stamp is enclosed in square brackets instead of angle
10656 brackets. It is inactive in the sense that it does not trigger agenda entries,
10657 does not link to the calendar and cannot be changed with the S-cursor keys.
10658 So these are more for recording a certain time/date."
10659 (interactive "P")
10660 (org-time-stamp arg 'inactive))
10661
10662 (defvar org-date-ovl (org-make-overlay 1 1))
10663 (org-overlay-put org-date-ovl 'face 'org-warning)
10664 (org-detach-overlay org-date-ovl)
10665
10666 (defvar org-ans1) ; dynamically scoped parameter
10667 (defvar org-ans2) ; dynamically scoped parameter
10668
10669 (defvar org-plain-time-of-day-regexp) ; defined below
10670
10671 (defvar org-overriding-default-time nil) ; dynamically scoped
10672 (defvar org-read-date-overlay nil)
10673 (defvar org-dcst nil) ; dynamically scoped
10674
10675 (defun org-read-date (&optional with-time to-time from-string prompt
10676 default-time default-input)
10677 "Read a date, possibly a time, and make things smooth for the user.
10678 The prompt will suggest to enter an ISO date, but you can also enter anything
10679 which will at least partially be understood by `parse-time-string'.
10680 Unrecognized parts of the date will default to the current day, month, year,
10681 hour and minute. If this command is called to replace a timestamp at point,
10682 of to enter the second timestamp of a range, the default time is taken from the
10683 existing stamp. For example,
10684 3-2-5 --> 2003-02-05
10685 feb 15 --> currentyear-02-15
10686 sep 12 9 --> 2009-09-12
10687 12:45 --> today 12:45
10688 22 sept 0:34 --> currentyear-09-22 0:34
10689 12 --> currentyear-currentmonth-12
10690 Fri --> nearest Friday (today or later)
10691 etc.
10692
10693 Furthermore you can specify a relative date by giving, as the *first* thing
10694 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10695 change in days weeks, months, years.
10696 With a single plus or minus, the date is relative to today. With a double
10697 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10698 +4d --> four days from today
10699 +4 --> same as above
10700 +2w --> two weeks from today
10701 ++5 --> five days from default date
10702
10703 The function understands only English month and weekday abbreviations,
10704 but this can be configured with the variables `parse-time-months' and
10705 `parse-time-weekdays'.
10706
10707 While prompting, a calendar is popped up - you can also select the
10708 date with the mouse (button 1). The calendar shows a period of three
10709 months. To scroll it to other months, use the keys `>' and `<'.
10710 If you don't like the calendar, turn it off with
10711 \(setq org-read-date-popup-calendar nil)
10712
10713 With optional argument TO-TIME, the date will immediately be converted
10714 to an internal time.
10715 With an optional argument WITH-TIME, the prompt will suggest to also
10716 insert a time. Note that when WITH-TIME is not set, you can still
10717 enter a time, and this function will inform the calling routine about
10718 this change. The calling routine may then choose to change the format
10719 used to insert the time stamp into the buffer to include the time.
10720 With optional argument FROM-STRING, read from this string instead from
10721 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10722 the time/date that is used for everything that is not specified by the
10723 user."
10724 (require 'parse-time)
10725 (let* ((org-time-stamp-rounding-minutes
10726 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10727 (org-dcst org-display-custom-times)
10728 (ct (org-current-time))
10729 (def (or org-overriding-default-time default-time ct))
10730 (defdecode (decode-time def))
10731 (dummy (progn
10732 (when (< (nth 2 defdecode) org-extend-today-until)
10733 (setcar (nthcdr 2 defdecode) -1)
10734 (setcar (nthcdr 1 defdecode) 59)
10735 (setq def (apply 'encode-time defdecode)
10736 defdecode (decode-time def)))))
10737 (calendar-move-hook nil)
10738 (calendar-view-diary-initially-flag nil)
10739 (view-diary-entries-initially nil)
10740 (calendar-view-holidays-initially-flag nil)
10741 (view-calendar-holidays-initially nil)
10742 (timestr (format-time-string
10743 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10744 (prompt (concat (if prompt (concat prompt " ") "")
10745 (format "Date+time [%s]: " timestr)))
10746 ans (org-ans0 "") org-ans1 org-ans2 final)
10747
10748 (cond
10749 (from-string (setq ans from-string))
10750 (org-read-date-popup-calendar
10751 (save-excursion
10752 (save-window-excursion
10753 (calendar)
10754 (calendar-forward-day (- (time-to-days def)
10755 (calendar-absolute-from-gregorian
10756 (calendar-current-date))))
10757 (org-eval-in-calendar nil t)
10758 (let* ((old-map (current-local-map))
10759 (map (copy-keymap calendar-mode-map))
10760 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10761 (org-defkey map (kbd "RET") 'org-calendar-select)
10762 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10763 'org-calendar-select-mouse)
10764 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10765 'org-calendar-select-mouse)
10766 (org-defkey minibuffer-local-map [(meta shift left)]
10767 (lambda () (interactive)
10768 (org-eval-in-calendar '(calendar-backward-month 1))))
10769 (org-defkey minibuffer-local-map [(meta shift right)]
10770 (lambda () (interactive)
10771 (org-eval-in-calendar '(calendar-forward-month 1))))
10772 (org-defkey minibuffer-local-map [(meta shift up)]
10773 (lambda () (interactive)
10774 (org-eval-in-calendar '(calendar-backward-year 1))))
10775 (org-defkey minibuffer-local-map [(meta shift down)]
10776 (lambda () (interactive)
10777 (org-eval-in-calendar '(calendar-forward-year 1))))
10778 (org-defkey minibuffer-local-map [(shift up)]
10779 (lambda () (interactive)
10780 (org-eval-in-calendar '(calendar-backward-week 1))))
10781 (org-defkey minibuffer-local-map [(shift down)]
10782 (lambda () (interactive)
10783 (org-eval-in-calendar '(calendar-forward-week 1))))
10784 (org-defkey minibuffer-local-map [(shift left)]
10785 (lambda () (interactive)
10786 (org-eval-in-calendar '(calendar-backward-day 1))))
10787 (org-defkey minibuffer-local-map [(shift right)]
10788 (lambda () (interactive)
10789 (org-eval-in-calendar '(calendar-forward-day 1))))
10790 (org-defkey minibuffer-local-map ">"
10791 (lambda () (interactive)
10792 (org-eval-in-calendar '(scroll-calendar-left 1))))
10793 (org-defkey minibuffer-local-map "<"
10794 (lambda () (interactive)
10795 (org-eval-in-calendar '(scroll-calendar-right 1))))
10796 (unwind-protect
10797 (progn
10798 (use-local-map map)
10799 (add-hook 'post-command-hook 'org-read-date-display)
10800 (setq org-ans0 (read-string prompt default-input nil nil))
10801 ;; org-ans0: from prompt
10802 ;; org-ans1: from mouse click
10803 ;; org-ans2: from calendar motion
10804 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10805 (remove-hook 'post-command-hook 'org-read-date-display)
10806 (use-local-map old-map)
10807 (when org-read-date-overlay
10808 (org-delete-overlay org-read-date-overlay)
10809 (setq org-read-date-overlay nil)))))))
10810
10811 (t ; Naked prompt only
10812 (unwind-protect
10813 (setq ans (read-string prompt default-input nil timestr))
10814 (when org-read-date-overlay
10815 (org-delete-overlay org-read-date-overlay)
10816 (setq org-read-date-overlay nil)))))
10817
10818 (setq final (org-read-date-analyze ans def defdecode))
10819
10820 (if to-time
10821 (apply 'encode-time final)
10822 (if (and (boundp 'org-time-was-given) org-time-was-given)
10823 (format "%04d-%02d-%02d %02d:%02d"
10824 (nth 5 final) (nth 4 final) (nth 3 final)
10825 (nth 2 final) (nth 1 final))
10826 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10827 (defvar def)
10828 (defvar defdecode)
10829 (defvar with-time)
10830 (defun org-read-date-display ()
10831 "Display the currrent date prompt interpretation in the minibuffer."
10832 (when org-read-date-display-live
10833 (when org-read-date-overlay
10834 (org-delete-overlay org-read-date-overlay))
10835 (let ((p (point)))
10836 (end-of-line 1)
10837 (while (not (equal (buffer-substring
10838 (max (point-min) (- (point) 4)) (point))
10839 " "))
10840 (insert " "))
10841 (goto-char p))
10842 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10843 " " (or org-ans1 org-ans2)))
10844 (org-end-time-was-given nil)
10845 (f (org-read-date-analyze ans def defdecode))
10846 (fmts (if org-dcst
10847 org-time-stamp-custom-formats
10848 org-time-stamp-formats))
10849 (fmt (if (or with-time
10850 (and (boundp 'org-time-was-given) org-time-was-given))
10851 (cdr fmts)
10852 (car fmts)))
10853 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10854 (when (and org-end-time-was-given
10855 (string-match org-plain-time-of-day-regexp txt))
10856 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10857 org-end-time-was-given
10858 (substring txt (match-end 0)))))
10859 (setq org-read-date-overlay
10860 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
10861 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10862
10863 (defun org-read-date-analyze (ans def defdecode)
10864 "Analyze the combined answer of the date prompt."
10865 ;; FIXME: cleanup and comment
10866 (let (delta deltan deltaw deltadef year month day
10867 hour minute second wday pm h2 m2 tl wday1
10868 iso-year iso-weekday iso-week iso-year iso-date)
10869
10870 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10871 (setq ans "+0"))
10872
10873 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10874 (setq ans (replace-match "" t t ans)
10875 deltan (car delta)
10876 deltaw (nth 1 delta)
10877 deltadef (nth 2 delta)))
10878
10879 ;; Check if there is an iso week date in there
10880 ;; If yes, sore the info and ostpone interpreting it until the rest
10881 ;; of the parsing is done
10882 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10883 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10884 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10885 iso-week (string-to-number (match-string 2 ans)))
10886 (setq ans (replace-match "" t t ans)))
10887
10888 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10889 (when (string-match
10890 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10891 (setq year (if (match-end 2)
10892 (string-to-number (match-string 2 ans))
10893 (string-to-number (format-time-string "%Y")))
10894 month (string-to-number (match-string 3 ans))
10895 day (string-to-number (match-string 4 ans)))
10896 (if (< year 100) (setq year (+ 2000 year)))
10897 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10898 t nil ans)))
10899 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10900 ;; If there is a time with am/pm, and *no* time without it, we convert
10901 ;; so that matching will be successful.
10902 (loop for i from 1 to 2 do ; twice, for end time as well
10903 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10904 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10905 (setq hour (string-to-number (match-string 1 ans))
10906 minute (if (match-end 3)
10907 (string-to-number (match-string 3 ans))
10908 0)
10909 pm (equal ?p
10910 (string-to-char (downcase (match-string 4 ans)))))
10911 (if (and (= hour 12) (not pm))
10912 (setq hour 0)
10913 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10914 (setq ans (replace-match (format "%02d:%02d" hour minute)
10915 t t ans))))
10916
10917 ;; Check if a time range is given as a duration
10918 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10919 (setq hour (string-to-number (match-string 1 ans))
10920 h2 (+ hour (string-to-number (match-string 3 ans)))
10921 minute (string-to-number (match-string 2 ans))
10922 m2 (+ minute (if (match-end 5) (string-to-number
10923 (match-string 5 ans))0)))
10924 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10925 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10926 t t ans)))
10927
10928 ;; Check if there is a time range
10929 (when (boundp 'org-end-time-was-given)
10930 (setq org-time-was-given nil)
10931 (when (and (string-match org-plain-time-of-day-regexp ans)
10932 (match-end 8))
10933 (setq org-end-time-was-given (match-string 8 ans))
10934 (setq ans (concat (substring ans 0 (match-beginning 7))
10935 (substring ans (match-end 7))))))
10936
10937 (setq tl (parse-time-string ans)
10938 day (or (nth 3 tl) (nth 3 defdecode))
10939 month (or (nth 4 tl)
10940 (if (and org-read-date-prefer-future
10941 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10942 (1+ (nth 4 defdecode))
10943 (nth 4 defdecode)))
10944 year (or (nth 5 tl)
10945 (if (and org-read-date-prefer-future
10946 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10947 (1+ (nth 5 defdecode))
10948 (nth 5 defdecode)))
10949 hour (or (nth 2 tl) (nth 2 defdecode))
10950 minute (or (nth 1 tl) (nth 1 defdecode))
10951 second (or (nth 0 tl) 0)
10952 wday (nth 6 tl))
10953
10954 ;; Special date definitions below
10955 (cond
10956 (iso-week
10957 ;; There was an iso week
10958 (setq year (or iso-year year)
10959 day (or iso-weekday wday 1)
10960 wday nil ; to make sure that the trigger below does not match
10961 iso-date (calendar-gregorian-from-absolute
10962 (calendar-absolute-from-iso
10963 (list iso-week day year))))
10964 ; FIXME: Should we also push ISO weeks into the future?
10965 ; (when (and org-read-date-prefer-future
10966 ; (not iso-year)
10967 ; (< (calendar-absolute-from-gregorian iso-date)
10968 ; (time-to-days (current-time))))
10969 ; (setq year (1+ year)
10970 ; iso-date (calendar-gregorian-from-absolute
10971 ; (calendar-absolute-from-iso
10972 ; (list iso-week day year)))))
10973 (setq month (car iso-date)
10974 year (nth 2 iso-date)
10975 day (nth 1 iso-date)))
10976 (deltan
10977 (unless deltadef
10978 (let ((now (decode-time (current-time))))
10979 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10980 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10981 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10982 ((equal deltaw "m") (setq month (+ month deltan)))
10983 ((equal deltaw "y") (setq year (+ year deltan)))))
10984 ((and wday (not (nth 3 tl)))
10985 ;; Weekday was given, but no day, so pick that day in the week
10986 ;; on or after the derived date.
10987 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10988 (unless (equal wday wday1)
10989 (setq day (+ day (% (- wday wday1 -7) 7))))))
10990 (if (and (boundp 'org-time-was-given)
10991 (nth 2 tl))
10992 (setq org-time-was-given t))
10993 (if (< year 100) (setq year (+ 2000 year)))
10994 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10995 (list second minute hour day month year)))
10996
10997 (defvar parse-time-weekdays)
10998
10999 (defun org-read-date-get-relative (s today default)
11000 "Check string S for special relative date string.
11001 TODAY and DEFAULT are internal times, for today and for a default.
11002 Return shift list (N what def-flag)
11003 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11004 N is the number of WHATs to shift.
11005 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11006 the DEFAULT date rather than TODAY."
11007 (when (and
11008 (string-match
11009 (concat
11010 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11011 "\\([0-9]+\\)?"
11012 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11013 "\\([ \t]\\|$\\)") s)
11014 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11015 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11016 (string-to-char (substring (match-string 1 s) -1))
11017 ?+))
11018 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11019 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11020 (what (if (match-end 3) (match-string 3 s) "d"))
11021 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11022 (date (if rel default today))
11023 (wday (nth 6 (decode-time date)))
11024 delta)
11025 (if wday1
11026 (progn
11027 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11028 (if (= dir ?-) (setq delta (- delta 7)))
11029 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11030 (list delta "d" rel))
11031 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11032
11033 (defun org-eval-in-calendar (form &optional keepdate)
11034 "Eval FORM in the calendar window and return to current window.
11035 Also, store the cursor date in variable org-ans2."
11036 (let ((sw (selected-window)))
11037 (select-window (get-buffer-window "*Calendar*"))
11038 (eval form)
11039 (when (and (not keepdate) (calendar-cursor-to-date))
11040 (let* ((date (calendar-cursor-to-date))
11041 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11042 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11043 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11044 (select-window sw)))
11045
11046 (defun org-calendar-select ()
11047 "Return to `org-read-date' with the date currently selected.
11048 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11049 (interactive)
11050 (when (calendar-cursor-to-date)
11051 (let* ((date (calendar-cursor-to-date))
11052 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11053 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11054 (if (active-minibuffer-window) (exit-minibuffer))))
11055
11056 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11057 "Insert a date stamp for the date given by the internal TIME.
11058 WITH-HM means, use the stamp format that includes the time of the day.
11059 INACTIVE means use square brackets instead of angular ones, so that the
11060 stamp will not contribute to the agenda.
11061 PRE and POST are optional strings to be inserted before and after the
11062 stamp.
11063 The command returns the inserted time stamp."
11064 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11065 stamp)
11066 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11067 (insert-before-markers (or pre ""))
11068 (insert-before-markers (setq stamp (format-time-string fmt time)))
11069 (when (listp extra)
11070 (setq extra (car extra))
11071 (if (and (stringp extra)
11072 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11073 (setq extra (format "-%02d:%02d"
11074 (string-to-number (match-string 1 extra))
11075 (string-to-number (match-string 2 extra))))
11076 (setq extra nil)))
11077 (when extra
11078 (backward-char 1)
11079 (insert-before-markers extra)
11080 (forward-char 1))
11081 (insert-before-markers (or post ""))
11082 (setq org-last-inserted-timestamp stamp)))
11083
11084 (defun org-toggle-time-stamp-overlays ()
11085 "Toggle the use of custom time stamp formats."
11086 (interactive)
11087 (setq org-display-custom-times (not org-display-custom-times))
11088 (unless org-display-custom-times
11089 (let ((p (point-min)) (bmp (buffer-modified-p)))
11090 (while (setq p (next-single-property-change p 'display))
11091 (if (and (get-text-property p 'display)
11092 (eq (get-text-property p 'face) 'org-date))
11093 (remove-text-properties
11094 p (setq p (next-single-property-change p 'display))
11095 '(display t))))
11096 (set-buffer-modified-p bmp)))
11097 (if (featurep 'xemacs)
11098 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11099 (org-restart-font-lock)
11100 (setq org-table-may-need-update t)
11101 (if org-display-custom-times
11102 (message "Time stamps are overlayed with custom format")
11103 (message "Time stamp overlays removed")))
11104
11105 (defun org-display-custom-time (beg end)
11106 "Overlay modified time stamp format over timestamp between BEG and END."
11107 (let* ((ts (buffer-substring beg end))
11108 t1 w1 with-hm tf time str w2 (off 0))
11109 (save-match-data
11110 (setq t1 (org-parse-time-string ts t))
11111 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11112 (setq off (- (match-end 0) (match-beginning 0)))))
11113 (setq end (- end off))
11114 (setq w1 (- end beg)
11115 with-hm (and (nth 1 t1) (nth 2 t1))
11116 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11117 time (org-fix-decoded-time t1)
11118 str (org-add-props
11119 (format-time-string
11120 (substring tf 1 -1) (apply 'encode-time time))
11121 nil 'mouse-face 'highlight)
11122 w2 (length str))
11123 (if (not (= w2 w1))
11124 (add-text-properties (1+ beg) (+ 2 beg)
11125 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11126 (if (featurep 'xemacs)
11127 (progn
11128 (put-text-property beg end 'invisible t)
11129 (put-text-property beg end 'end-glyph (make-glyph str)))
11130 (put-text-property beg end 'display str))))
11131
11132 (defun org-translate-time (string)
11133 "Translate all timestamps in STRING to custom format.
11134 But do this only if the variable `org-display-custom-times' is set."
11135 (when org-display-custom-times
11136 (save-match-data
11137 (let* ((start 0)
11138 (re org-ts-regexp-both)
11139 t1 with-hm inactive tf time str beg end)
11140 (while (setq start (string-match re string start))
11141 (setq beg (match-beginning 0)
11142 end (match-end 0)
11143 t1 (save-match-data
11144 (org-parse-time-string (substring string beg end) t))
11145 with-hm (and (nth 1 t1) (nth 2 t1))
11146 inactive (equal (substring string beg (1+ beg)) "[")
11147 tf (funcall (if with-hm 'cdr 'car)
11148 org-time-stamp-custom-formats)
11149 time (org-fix-decoded-time t1)
11150 str (format-time-string
11151 (concat
11152 (if inactive "[" "<") (substring tf 1 -1)
11153 (if inactive "]" ">"))
11154 (apply 'encode-time time))
11155 string (replace-match str t t string)
11156 start (+ start (length str)))))))
11157 string)
11158
11159 (defun org-fix-decoded-time (time)
11160 "Set 0 instead of nil for the first 6 elements of time.
11161 Don't touch the rest."
11162 (let ((n 0))
11163 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11164
11165 (defun org-days-to-time (timestamp-string)
11166 "Difference between TIMESTAMP-STRING and now in days."
11167 (- (time-to-days (org-time-string-to-time timestamp-string))
11168 (time-to-days (current-time))))
11169
11170 (defun org-deadline-close (timestamp-string &optional ndays)
11171 "Is the time in TIMESTAMP-STRING close to the current date?"
11172 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11173 (and (< (org-days-to-time timestamp-string) ndays)
11174 (not (org-entry-is-done-p))))
11175
11176 (defun org-get-wdays (ts)
11177 "Get the deadline lead time appropriate for timestring TS."
11178 (cond
11179 ((<= org-deadline-warning-days 0)
11180 ;; 0 or negative, enforce this value no matter what
11181 (- org-deadline-warning-days))
11182 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11183 ;; lead time is specified.
11184 (floor (* (string-to-number (match-string 1 ts))
11185 (cdr (assoc (match-string 2 ts)
11186 '(("d" . 1) ("w" . 7)
11187 ("m" . 30.4) ("y" . 365.25)))))))
11188 ;; go for the default.
11189 (t org-deadline-warning-days)))
11190
11191 (defun org-calendar-select-mouse (ev)
11192 "Return to `org-read-date' with the date currently selected.
11193 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11194 (interactive "e")
11195 (mouse-set-point ev)
11196 (when (calendar-cursor-to-date)
11197 (let* ((date (calendar-cursor-to-date))
11198 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11199 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11200 (if (active-minibuffer-window) (exit-minibuffer))))
11201
11202 (defun org-check-deadlines (ndays)
11203 "Check if there are any deadlines due or past due.
11204 A deadline is considered due if it happens within `org-deadline-warning-days'
11205 days from today's date. If the deadline appears in an entry marked DONE,
11206 it is not shown. The prefix arg NDAYS can be used to test that many
11207 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11208 (interactive "P")
11209 (let* ((org-warn-days
11210 (cond
11211 ((equal ndays '(4)) 100000)
11212 (ndays (prefix-numeric-value ndays))
11213 (t (abs org-deadline-warning-days))))
11214 (case-fold-search nil)
11215 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11216 (callback
11217 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11218
11219 (message "%d deadlines past-due or due within %d days"
11220 (org-occur regexp nil callback)
11221 org-warn-days)))
11222
11223 (defun org-check-before-date (date)
11224 "Check if there are deadlines or scheduled entries before DATE."
11225 (interactive (list (org-read-date)))
11226 (let ((case-fold-search nil)
11227 (regexp (concat "\\<\\(" org-deadline-string
11228 "\\|" org-scheduled-string
11229 "\\) *<\\([^>]+\\)>"))
11230 (callback
11231 (lambda () (time-less-p
11232 (org-time-string-to-time (match-string 2))
11233 (org-time-string-to-time date)))))
11234 (message "%d entries before %s"
11235 (org-occur regexp nil callback) date)))
11236
11237 (defun org-evaluate-time-range (&optional to-buffer)
11238 "Evaluate a time range by computing the difference between start and end.
11239 Normally the result is just printed in the echo area, but with prefix arg
11240 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11241 If the time range is actually in a table, the result is inserted into the
11242 next column.
11243 For time difference computation, a year is assumed to be exactly 365
11244 days in order to avoid rounding problems."
11245 (interactive "P")
11246 (or
11247 (org-clock-update-time-maybe)
11248 (save-excursion
11249 (unless (org-at-date-range-p t)
11250 (goto-char (point-at-bol))
11251 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11252 (if (not (org-at-date-range-p t))
11253 (error "Not at a time-stamp range, and none found in current line")))
11254 (let* ((ts1 (match-string 1))
11255 (ts2 (match-string 2))
11256 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11257 (match-end (match-end 0))
11258 (time1 (org-time-string-to-time ts1))
11259 (time2 (org-time-string-to-time ts2))
11260 (t1 (time-to-seconds time1))
11261 (t2 (time-to-seconds time2))
11262 (diff (abs (- t2 t1)))
11263 (negative (< (- t2 t1) 0))
11264 ;; (ys (floor (* 365 24 60 60)))
11265 (ds (* 24 60 60))
11266 (hs (* 60 60))
11267 (fy "%dy %dd %02d:%02d")
11268 (fy1 "%dy %dd")
11269 (fd "%dd %02d:%02d")
11270 (fd1 "%dd")
11271 (fh "%02d:%02d")
11272 y d h m align)
11273 (if havetime
11274 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11275 y 0
11276 d (floor (/ diff ds)) diff (mod diff ds)
11277 h (floor (/ diff hs)) diff (mod diff hs)
11278 m (floor (/ diff 60)))
11279 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11280 y 0
11281 d (floor (+ (/ diff ds) 0.5))
11282 h 0 m 0))
11283 (if (not to-buffer)
11284 (message "%s" (org-make-tdiff-string y d h m))
11285 (if (org-at-table-p)
11286 (progn
11287 (goto-char match-end)
11288 (setq align t)
11289 (and (looking-at " *|") (goto-char (match-end 0))))
11290 (goto-char match-end))
11291 (if (looking-at
11292 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11293 (replace-match ""))
11294 (if negative (insert " -"))
11295 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11296 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11297 (insert " " (format fh h m))))
11298 (if align (org-table-align))
11299 (message "Time difference inserted")))))
11300
11301 (defun org-make-tdiff-string (y d h m)
11302 (let ((fmt "")
11303 (l nil))
11304 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11305 l (push y l)))
11306 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11307 l (push d l)))
11308 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11309 l (push h l)))
11310 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11311 l (push m l)))
11312 (apply 'format fmt (nreverse l))))
11313
11314 (defun org-time-string-to-time (s)
11315 (apply 'encode-time (org-parse-time-string s)))
11316
11317 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11318 "Convert a time stamp to an absolute day number.
11319 If there is a specifyer for a cyclic time stamp, get the closest date to
11320 DAYNR.
11321 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11322 (cond
11323 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11324 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11325 daynr
11326 (+ daynr 1000)))
11327 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11328 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11329 (time-to-days (current-time))) (match-string 0 s)
11330 prefer show-all))
11331 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11332
11333 (defun org-days-to-iso-week (days)
11334 "Return the iso week number."
11335 (require 'cal-iso)
11336 (car (calendar-iso-from-absolute days)))
11337
11338 (defun org-small-year-to-year (year)
11339 "Convert 2-digit years into 4-digit years.
11340 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11341 The year 2000 cannot be abbreviated. Any year larger than 99
11342 is returned unchanged."
11343 (if (< year 38)
11344 (setq year (+ 2000 year))
11345 (if (< year 100)
11346 (setq year (+ 1900 year))))
11347 year)
11348
11349 (defun org-time-from-absolute (d)
11350 "Return the time corresponding to date D.
11351 D may be an absolute day number, or a calendar-type list (month day year)."
11352 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11353 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11354
11355 (defun org-calendar-holiday ()
11356 "List of holidays, for Diary display in Org-mode."
11357 (require 'holidays)
11358 (let ((hl (funcall
11359 (if (fboundp 'calendar-check-holidays)
11360 'calendar-check-holidays 'check-calendar-holidays) date)))
11361 (if hl (mapconcat 'identity hl "; "))))
11362
11363 (defun org-diary-sexp-entry (sexp entry date)
11364 "Process a SEXP diary ENTRY for DATE."
11365 (require 'diary-lib)
11366 (let ((result (if calendar-debug-sexp
11367 (let ((stack-trace-on-error t))
11368 (eval (car (read-from-string sexp))))
11369 (condition-case nil
11370 (eval (car (read-from-string sexp)))
11371 (error
11372 (beep)
11373 (message "Bad sexp at line %d in %s: %s"
11374 (org-current-line)
11375 (buffer-file-name) sexp)
11376 (sleep-for 2))))))
11377 (cond ((stringp result) result)
11378 ((and (consp result)
11379 (stringp (cdr result))) (cdr result))
11380 (result entry)
11381 (t nil))))
11382
11383 (defun org-diary-to-ical-string (frombuf)
11384 "Get iCalendar entries from diary entries in buffer FROMBUF.
11385 This uses the icalendar.el library."
11386 (let* ((tmpdir (if (featurep 'xemacs)
11387 (temp-directory)
11388 temporary-file-directory))
11389 (tmpfile (make-temp-name
11390 (expand-file-name "orgics" tmpdir)))
11391 buf rtn b e)
11392 (save-excursion
11393 (set-buffer frombuf)
11394 (icalendar-export-region (point-min) (point-max) tmpfile)
11395 (setq buf (find-buffer-visiting tmpfile))
11396 (set-buffer buf)
11397 (goto-char (point-min))
11398 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11399 (setq b (match-beginning 0)))
11400 (goto-char (point-max))
11401 (if (re-search-backward "^END:VEVENT" nil t)
11402 (setq e (match-end 0)))
11403 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11404 (kill-buffer buf)
11405 (delete-file tmpfile)
11406 rtn))
11407
11408 (defun org-closest-date (start current change prefer show-all)
11409 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11410 When PREFER is `past' return a date that is either CURRENT or past.
11411 When PREFER is `future', return a date that is either CURRENT or future.
11412 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11413 ;; Make the proper lists from the dates
11414 (catch 'exit
11415 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11416 dn dw sday cday n1 n2
11417 d m y y1 y2 date1 date2 nmonths nm ny m2)
11418
11419 (setq start (org-date-to-gregorian start)
11420 current (org-date-to-gregorian
11421 (if show-all
11422 current
11423 (time-to-days (current-time))))
11424 sday (calendar-absolute-from-gregorian start)
11425 cday (calendar-absolute-from-gregorian current))
11426
11427 (if (<= cday sday) (throw 'exit sday))
11428
11429 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11430 (setq dn (string-to-number (match-string 1 change))
11431 dw (cdr (assoc (match-string 2 change) a1)))
11432 (error "Invalid change specifyer: %s" change))
11433 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11434 (cond
11435 ((eq dw 'day)
11436 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11437 n2 (+ n1 dn)))
11438 ((eq dw 'year)
11439 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11440 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11441 (setq date1 (list m d y1)
11442 n1 (calendar-absolute-from-gregorian date1)
11443 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11444 n2 (calendar-absolute-from-gregorian date2)))
11445 ((eq dw 'month)
11446 ;; approx number of month between the two dates
11447 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11448 ;; How often does dn fit in there?
11449 (setq d (nth 1 start) m (car start) y (nth 2 start)
11450 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11451 m (+ m nm)
11452 ny (floor (/ m 12))
11453 y (+ y ny)
11454 m (- m (* ny 12)))
11455 (while (> m 12) (setq m (- m 12) y (1+ y)))
11456 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11457 (setq m2 (+ m dn) y2 y)
11458 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11459 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11460 (while (<= n2 cday)
11461 (setq n1 n2 m m2 y y2)
11462 (setq m2 (+ m dn) y2 y)
11463 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11464 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11465 (if show-all
11466 (cond
11467 ((eq prefer 'past) n1)
11468 ((eq prefer 'future) (if (= cday n1) n1 n2))
11469 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11470 (cond
11471 ((eq prefer 'past) n1)
11472 ((eq prefer 'future) (if (= cday n1) n1 n2))
11473 (t (if (= cday n1) n1 n2)))))))
11474
11475 (defun org-date-to-gregorian (date)
11476 "Turn any specification of DATE into a gregorian date for the calendar."
11477 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11478 ((and (listp date) (= (length date) 3)) date)
11479 ((stringp date)
11480 (setq date (org-parse-time-string date))
11481 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11482 ((listp date)
11483 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11484
11485 (defun org-parse-time-string (s &optional nodefault)
11486 "Parse the standard Org-mode time string.
11487 This should be a lot faster than the normal `parse-time-string'.
11488 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11489 hour and minute fields will be nil if not given."
11490 (if (string-match org-ts-regexp0 s)
11491 (list 0
11492 (if (or (match-beginning 8) (not nodefault))
11493 (string-to-number (or (match-string 8 s) "0")))
11494 (if (or (match-beginning 7) (not nodefault))
11495 (string-to-number (or (match-string 7 s) "0")))
11496 (string-to-number (match-string 4 s))
11497 (string-to-number (match-string 3 s))
11498 (string-to-number (match-string 2 s))
11499 nil nil nil)
11500 (make-list 9 0)))
11501
11502 (defun org-timestamp-up (&optional arg)
11503 "Increase the date item at the cursor by one.
11504 If the cursor is on the year, change the year. If it is on the month or
11505 the day, change that.
11506 With prefix ARG, change by that many units."
11507 (interactive "p")
11508 (org-timestamp-change (prefix-numeric-value arg)))
11509
11510 (defun org-timestamp-down (&optional arg)
11511 "Decrease the date item at the cursor by one.
11512 If the cursor is on the year, change the year. If it is on the month or
11513 the day, change that.
11514 With prefix ARG, change by that many units."
11515 (interactive "p")
11516 (org-timestamp-change (- (prefix-numeric-value arg))))
11517
11518 (defun org-timestamp-up-day (&optional arg)
11519 "Increase the date in the time stamp by one day.
11520 With prefix ARG, change that many days."
11521 (interactive "p")
11522 (if (and (not (org-at-timestamp-p t))
11523 (org-on-heading-p))
11524 (org-todo 'up)
11525 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11526
11527 (defun org-timestamp-down-day (&optional arg)
11528 "Decrease the date in the time stamp by one day.
11529 With prefix ARG, change that many days."
11530 (interactive "p")
11531 (if (and (not (org-at-timestamp-p t))
11532 (org-on-heading-p))
11533 (org-todo 'down)
11534 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11535
11536 (defun org-at-timestamp-p (&optional inactive-ok)
11537 "Determine if the cursor is in or at a timestamp."
11538 (interactive)
11539 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11540 (pos (point))
11541 (ans (or (looking-at tsr)
11542 (save-excursion
11543 (skip-chars-backward "^[<\n\r\t")
11544 (if (> (point) (point-min)) (backward-char 1))
11545 (and (looking-at tsr)
11546 (> (- (match-end 0) pos) -1))))))
11547 (and ans
11548 (boundp 'org-ts-what)
11549 (setq org-ts-what
11550 (cond
11551 ((= pos (match-beginning 0)) 'bracket)
11552 ((= pos (1- (match-end 0))) 'bracket)
11553 ((org-pos-in-match-range pos 2) 'year)
11554 ((org-pos-in-match-range pos 3) 'month)
11555 ((org-pos-in-match-range pos 7) 'hour)
11556 ((org-pos-in-match-range pos 8) 'minute)
11557 ((or (org-pos-in-match-range pos 4)
11558 (org-pos-in-match-range pos 5)) 'day)
11559 ((and (> pos (or (match-end 8) (match-end 5)))
11560 (< pos (match-end 0)))
11561 (- pos (or (match-end 8) (match-end 5))))
11562 (t 'day))))
11563 ans))
11564
11565 (defun org-toggle-timestamp-type ()
11566 "Toggle the type (<active> or [inactive]) of a time stamp."
11567 (interactive)
11568 (when (org-at-timestamp-p t)
11569 (let ((beg (match-beginning 0)) (end (match-end 0))
11570 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
11571 (save-excursion
11572 (goto-char beg)
11573 (while (re-search-forward "[][<>]" end t)
11574 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
11575 t t)))
11576 (message "Timestamp is now %sactive"
11577 (if (equal (char-after beg) ?<) "" "in")))))
11578
11579 (defun org-timestamp-change (n &optional what)
11580 "Change the date in the time stamp at point.
11581 The date will be changed by N times WHAT. WHAT can be `day', `month',
11582 `year', `minute', `second'. If WHAT is not given, the cursor position
11583 in the timestamp determines what will be changed."
11584 (let ((pos (point))
11585 with-hm inactive
11586 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11587 org-ts-what
11588 extra rem
11589 ts time time0)
11590 (if (not (org-at-timestamp-p t))
11591 (error "Not at a timestamp"))
11592 (if (and (not what) (eq org-ts-what 'bracket))
11593 (org-toggle-timestamp-type)
11594 (if (and (not what) (not (eq org-ts-what 'day))
11595 org-display-custom-times
11596 (get-text-property (point) 'display)
11597 (not (get-text-property (1- (point)) 'display)))
11598 (setq org-ts-what 'day))
11599 (setq org-ts-what (or what org-ts-what)
11600 inactive (= (char-after (match-beginning 0)) ?\[)
11601 ts (match-string 0))
11602 (replace-match "")
11603 (if (string-match
11604 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11605 ts)
11606 (setq extra (match-string 1 ts)))
11607 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11608 (setq with-hm t))
11609 (setq time0 (org-parse-time-string ts))
11610 (when (and (eq org-ts-what 'minute)
11611 (eq current-prefix-arg nil))
11612 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11613 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11614 (setcar (cdr time0) (+ (nth 1 time0)
11615 (if (> n 0) (- rem) (- dm rem))))))
11616 (setq time
11617 (encode-time (or (car time0) 0)
11618 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11619 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11620 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11621 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11622 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11623 (nthcdr 6 time0)))
11624 (when (integerp org-ts-what)
11625 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11626 (if (eq what 'calendar)
11627 (let ((cal-date (org-get-date-from-calendar)))
11628 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11629 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11630 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11631 (setcar time0 (or (car time0) 0))
11632 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11633 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11634 (setq time (apply 'encode-time time0))))
11635 (setq org-last-changed-timestamp
11636 (org-insert-time-stamp time with-hm inactive nil nil extra))
11637 (org-clock-update-time-maybe)
11638 (goto-char pos)
11639 ;; Try to recenter the calendar window, if any
11640 (if (and org-calendar-follow-timestamp-change
11641 (get-buffer-window "*Calendar*" t)
11642 (memq org-ts-what '(day month year)))
11643 (org-recenter-calendar (time-to-days time))))))
11644
11645 (defun org-modify-ts-extra (s pos n dm)
11646 "Change the different parts of the lead-time and repeat fields in timestamp."
11647 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11648 ng h m new rem)
11649 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11650 (cond
11651 ((or (org-pos-in-match-range pos 2)
11652 (org-pos-in-match-range pos 3))
11653 (setq m (string-to-number (match-string 3 s))
11654 h (string-to-number (match-string 2 s)))
11655 (if (org-pos-in-match-range pos 2)
11656 (setq h (+ h n))
11657 (setq n (* dm (org-no-warnings (signum n))))
11658 (when (not (= 0 (setq rem (% m dm))))
11659 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11660 (setq m (+ m n)))
11661 (if (< m 0) (setq m (+ m 60) h (1- h)))
11662 (if (> m 59) (setq m (- m 60) h (1+ h)))
11663 (setq h (min 24 (max 0 h)))
11664 (setq ng 1 new (format "-%02d:%02d" h m)))
11665 ((org-pos-in-match-range pos 6)
11666 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11667 ((org-pos-in-match-range pos 5)
11668 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11669
11670 ((org-pos-in-match-range pos 9)
11671 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11672 ((org-pos-in-match-range pos 8)
11673 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11674
11675 (when ng
11676 (setq s (concat
11677 (substring s 0 (match-beginning ng))
11678 new
11679 (substring s (match-end ng))))))
11680 s))
11681
11682 (defun org-recenter-calendar (date)
11683 "If the calendar is visible, recenter it to DATE."
11684 (let* ((win (selected-window))
11685 (cwin (get-buffer-window "*Calendar*" t))
11686 (calendar-move-hook nil))
11687 (when cwin
11688 (select-window cwin)
11689 (calendar-goto-date (if (listp date) date
11690 (calendar-gregorian-from-absolute date)))
11691 (select-window win))))
11692
11693 (defun org-goto-calendar (&optional arg)
11694 "Go to the Emacs calendar at the current date.
11695 If there is a time stamp in the current line, go to that date.
11696 A prefix ARG can be used to force the current date."
11697 (interactive "P")
11698 (let ((tsr org-ts-regexp) diff
11699 (calendar-move-hook nil)
11700 (calendar-view-holidays-initially-flag nil)
11701 (view-calendar-holidays-initially nil)
11702 (calendar-view-diary-initially-flag nil)
11703 (view-diary-entries-initially nil))
11704 (if (or (org-at-timestamp-p)
11705 (save-excursion
11706 (beginning-of-line 1)
11707 (looking-at (concat ".*" tsr))))
11708 (let ((d1 (time-to-days (current-time)))
11709 (d2 (time-to-days
11710 (org-time-string-to-time (match-string 1)))))
11711 (setq diff (- d2 d1))))
11712 (calendar)
11713 (calendar-goto-today)
11714 (if (and diff (not arg)) (calendar-forward-day diff))))
11715
11716 (defun org-get-date-from-calendar ()
11717 "Return a list (month day year) of date at point in calendar."
11718 (with-current-buffer "*Calendar*"
11719 (save-match-data
11720 (calendar-cursor-to-date))))
11721
11722 (defun org-date-from-calendar ()
11723 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11724 If there is already a time stamp at the cursor position, update it."
11725 (interactive)
11726 (if (org-at-timestamp-p t)
11727 (org-timestamp-change 0 'calendar)
11728 (let ((cal-date (org-get-date-from-calendar)))
11729 (org-insert-time-stamp
11730 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11731
11732 (defun org-minutes-to-hh:mm-string (m)
11733 "Compute H:MM from a number of minutes."
11734 (let ((h (/ m 60)))
11735 (setq m (- m (* 60 h)))
11736 (format org-time-clocksum-format h m)))
11737
11738 (defun org-hh:mm-string-to-minutes (s)
11739 "Convert a string H:MM to a number of minutes."
11740 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11741 (+ (* (string-to-number (match-string 1 s)) 60)
11742 (string-to-number (match-string 2 s)))
11743 0))
11744
11745 ;;;; Agenda files
11746
11747 ;;;###autoload
11748 (defun org-iswitchb (&optional arg)
11749 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11750 With a prefix argument, restrict available to files.
11751 With two prefix arguments, restrict available buffers to agenda files.
11752
11753 Due to some yet unresolved reason, the global function
11754 `iswitchb-mode' needs to be active for this function to work."
11755 (interactive "P")
11756 (require 'iswitchb)
11757 (let ((enabled iswitchb-mode) blist)
11758 (or enabled (iswitchb-mode 1))
11759 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11760 ((equal arg '(16)) (org-buffer-list 'agenda))
11761 (t (org-buffer-list))))
11762 (unwind-protect
11763 (let ((iswitchb-make-buflist-hook
11764 (lambda ()
11765 (setq iswitchb-temp-buflist
11766 (mapcar 'buffer-name blist)))))
11767 (switch-to-buffer
11768 (iswitchb-read-buffer
11769 "Switch-to: " nil t))
11770 (or enabled (iswitchb-mode -1))))))
11771
11772 (defun org-buffer-list (&optional predicate exclude-tmp)
11773 "Return a list of Org buffers.
11774 PREDICATE can be `export', `files' or `agenda'.
11775
11776 export restrict the list to Export buffers.
11777 files restrict the list to buffers visiting Org files.
11778 agenda restrict the list to buffers visiting agenda files.
11779
11780 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
11781 (let* ((bfn nil)
11782 (agenda-files (and (eq predicate 'agenda)
11783 (mapcar 'file-truename (org-agenda-files t))))
11784 (filter
11785 (cond
11786 ((eq predicate 'files)
11787 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
11788 ((eq predicate 'export)
11789 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
11790 ((eq predicate 'agenda)
11791 (lambda (b)
11792 (with-current-buffer b
11793 (and (eq major-mode 'org-mode)
11794 (setq bfn (buffer-file-name b))
11795 (member (file-truename bfn) agenda-files)))))
11796 (t (lambda (b) (with-current-buffer b
11797 (or (eq major-mode 'org-mode)
11798 (string-match "\*Org .*Export"
11799 (buffer-name b)))))))))
11800 (delq nil
11801 (mapcar
11802 (lambda(b)
11803 (if (and (funcall filter b)
11804 (or (not exclude-tmp)
11805 (not (string-match "tmp" (buffer-name b)))))
11806 b
11807 nil))
11808 (buffer-list)))))
11809
11810 (defun org-agenda-files (&optional unrestricted archives)
11811 "Get the list of agenda files.
11812 Optional UNRESTRICTED means return the full list even if a restriction
11813 is currently in place.
11814 When ARCHIVES is t, include all archive files hat are really being
11815 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11816 `org-agenda-archives-mode' is t."
11817 (let ((files
11818 (cond
11819 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11820 ((stringp org-agenda-files) (org-read-agenda-file-list))
11821 ((listp org-agenda-files) org-agenda-files)
11822 (t (error "Invalid value of `org-agenda-files'")))))
11823 (setq files (apply 'append
11824 (mapcar (lambda (f)
11825 (if (file-directory-p f)
11826 (directory-files
11827 f t org-agenda-file-regexp)
11828 (list f)))
11829 files)))
11830 (when org-agenda-skip-unavailable-files
11831 (setq files (delq nil
11832 (mapcar (function
11833 (lambda (file)
11834 (and (file-readable-p file) file)))
11835 files))))
11836 (when (or (eq archives t)
11837 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11838 (setq files (org-add-archive-files files)))
11839 files))
11840
11841 (defun org-edit-agenda-file-list ()
11842 "Edit the list of agenda files.
11843 Depending on setup, this either uses customize to edit the variable
11844 `org-agenda-files', or it visits the file that is holding the list. In the
11845 latter case, the buffer is set up in a way that saving it automatically kills
11846 the buffer and restores the previous window configuration."
11847 (interactive)
11848 (if (stringp org-agenda-files)
11849 (let ((cw (current-window-configuration)))
11850 (find-file org-agenda-files)
11851 (org-set-local 'org-window-configuration cw)
11852 (org-add-hook 'after-save-hook
11853 (lambda ()
11854 (set-window-configuration
11855 (prog1 org-window-configuration
11856 (kill-buffer (current-buffer))))
11857 (org-install-agenda-files-menu)
11858 (message "New agenda file list installed"))
11859 nil 'local)
11860 (message "%s" (substitute-command-keys
11861 "Edit list and finish with \\[save-buffer]")))
11862 (customize-variable 'org-agenda-files)))
11863
11864 (defun org-store-new-agenda-file-list (list)
11865 "Set new value for the agenda file list and save it correcly."
11866 (if (stringp org-agenda-files)
11867 (let ((f org-agenda-files) b)
11868 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11869 (with-temp-file f
11870 (insert (mapconcat 'identity list "\n") "\n")))
11871 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11872 (setq org-agenda-files list)
11873 (customize-save-variable 'org-agenda-files org-agenda-files))))
11874
11875 (defun org-read-agenda-file-list ()
11876 "Read the list of agenda files from a file."
11877 (when (file-directory-p org-agenda-files)
11878 (error "`org-agenda-files' cannot be a single directory"))
11879 (when (stringp org-agenda-files)
11880 (with-temp-buffer
11881 (insert-file-contents org-agenda-files)
11882 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11883
11884
11885 ;;;###autoload
11886 (defun org-cycle-agenda-files ()
11887 "Cycle through the files in `org-agenda-files'.
11888 If the current buffer visits an agenda file, find the next one in the list.
11889 If the current buffer does not, find the first agenda file."
11890 (interactive)
11891 (let* ((fs (org-agenda-files t))
11892 (files (append fs (list (car fs))))
11893 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11894 file)
11895 (unless files (error "No agenda files"))
11896 (catch 'exit
11897 (while (setq file (pop files))
11898 (if (equal (file-truename file) tcf)
11899 (when (car files)
11900 (find-file (car files))
11901 (throw 'exit t))))
11902 (find-file (car fs)))
11903 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11904
11905 (defun org-agenda-file-to-front (&optional to-end)
11906 "Move/add the current file to the top of the agenda file list.
11907 If the file is not present in the list, it is added to the front. If it is
11908 present, it is moved there. With optional argument TO-END, add/move to the
11909 end of the list."
11910 (interactive "P")
11911 (let ((org-agenda-skip-unavailable-files nil)
11912 (file-alist (mapcar (lambda (x)
11913 (cons (file-truename x) x))
11914 (org-agenda-files t)))
11915 (ctf (file-truename buffer-file-name))
11916 x had)
11917 (setq x (assoc ctf file-alist) had x)
11918
11919 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11920 (if to-end
11921 (setq file-alist (append (delq x file-alist) (list x)))
11922 (setq file-alist (cons x (delq x file-alist))))
11923 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11924 (org-install-agenda-files-menu)
11925 (message "File %s to %s of agenda file list"
11926 (if had "moved" "added") (if to-end "end" "front"))))
11927
11928 (defun org-remove-file (&optional file)
11929 "Remove current file from the list of files in variable `org-agenda-files'.
11930 These are the files which are being checked for agenda entries.
11931 Optional argument FILE means, use this file instead of the current."
11932 (interactive)
11933 (let* ((org-agenda-skip-unavailable-files nil)
11934 (file (or file buffer-file-name))
11935 (true-file (file-truename file))
11936 (afile (abbreviate-file-name file))
11937 (files (delq nil (mapcar
11938 (lambda (x)
11939 (if (equal true-file
11940 (file-truename x))
11941 nil x))
11942 (org-agenda-files t)))))
11943 (if (not (= (length files) (length (org-agenda-files t))))
11944 (progn
11945 (org-store-new-agenda-file-list files)
11946 (org-install-agenda-files-menu)
11947 (message "Removed file: %s" afile))
11948 (message "File was not in list: %s (not removed)" afile))))
11949
11950 (defun org-file-menu-entry (file)
11951 (vector file (list 'find-file file) t))
11952
11953 (defun org-check-agenda-file (file)
11954 "Make sure FILE exists. If not, ask user what to do."
11955 (when (not (file-exists-p file))
11956 (message "non-existent file %s. [R]emove from list or [A]bort?"
11957 (abbreviate-file-name file))
11958 (let ((r (downcase (read-char-exclusive))))
11959 (cond
11960 ((equal r ?r)
11961 (org-remove-file file)
11962 (throw 'nextfile t))
11963 (t (error "Abort"))))))
11964
11965 (defun org-get-agenda-file-buffer (file)
11966 "Get a buffer visiting FILE. If the buffer needs to be created, add
11967 it to the list of buffers which might be released later."
11968 (let ((buf (org-find-base-buffer-visiting file)))
11969 (if buf
11970 buf ; just return it
11971 ;; Make a new buffer and remember it
11972 (setq buf (find-file-noselect file))
11973 (if buf (push buf org-agenda-new-buffers))
11974 buf)))
11975
11976 (defun org-release-buffers (blist)
11977 "Release all buffers in list, asking the user for confirmation when needed.
11978 When a buffer is unmodified, it is just killed. When modified, it is saved
11979 \(if the user agrees) and then killed."
11980 (let (buf file)
11981 (while (setq buf (pop blist))
11982 (setq file (buffer-file-name buf))
11983 (when (and (buffer-modified-p buf)
11984 file
11985 (y-or-n-p (format "Save file %s? " file)))
11986 (with-current-buffer buf (save-buffer)))
11987 (kill-buffer buf))))
11988
11989 (defun org-prepare-agenda-buffers (files)
11990 "Create buffers for all agenda files, protect archived trees and comments."
11991 (interactive)
11992 (let ((pa '(:org-archived t))
11993 (pc '(:org-comment t))
11994 (pall '(:org-archived t :org-comment t))
11995 (inhibit-read-only t)
11996 (rea (concat ":" org-archive-tag ":"))
11997 bmp file re)
11998 (save-excursion
11999 (save-restriction
12000 (while (setq file (pop files))
12001 (if (bufferp file)
12002 (set-buffer file)
12003 (org-check-agenda-file file)
12004 (set-buffer (org-get-agenda-file-buffer file)))
12005 (widen)
12006 (setq bmp (buffer-modified-p))
12007 (org-refresh-category-properties)
12008 (setq org-todo-keywords-for-agenda
12009 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12010 (setq org-done-keywords-for-agenda
12011 (append org-done-keywords-for-agenda org-done-keywords))
12012 (setq org-todo-keyword-alist-for-agenda
12013 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12014 (setq org-tag-alist-for-agenda
12015 (append org-tag-alist-for-agenda org-tag-alist))
12016
12017 (save-excursion
12018 (remove-text-properties (point-min) (point-max) pall)
12019 (when org-agenda-skip-archived-trees
12020 (goto-char (point-min))
12021 (while (re-search-forward rea nil t)
12022 (if (org-on-heading-p t)
12023 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12024 (goto-char (point-min))
12025 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12026 (while (re-search-forward re nil t)
12027 (add-text-properties
12028 (match-beginning 0) (org-end-of-subtree t) pc)))
12029 (set-buffer-modified-p bmp))))
12030 (setq org-todo-keyword-alist-for-agenda
12031 (org-uniquify org-todo-keyword-alist-for-agenda)
12032 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12033
12034 ;;;; Embedded LaTeX
12035
12036 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12037 "Keymap for the minor `org-cdlatex-mode'.")
12038
12039 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12040 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12041 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12042 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12043 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12044
12045 (defvar org-cdlatex-texmathp-advice-is-done nil
12046 "Flag remembering if we have applied the advice to texmathp already.")
12047
12048 (define-minor-mode org-cdlatex-mode
12049 "Toggle the minor `org-cdlatex-mode'.
12050 This mode supports entering LaTeX environment and math in LaTeX fragments
12051 in Org-mode.
12052 \\{org-cdlatex-mode-map}"
12053 nil " OCDL" nil
12054 (when org-cdlatex-mode (require 'cdlatex))
12055 (unless org-cdlatex-texmathp-advice-is-done
12056 (setq org-cdlatex-texmathp-advice-is-done t)
12057 (defadvice texmathp (around org-math-always-on activate)
12058 "Always return t in org-mode buffers.
12059 This is because we want to insert math symbols without dollars even outside
12060 the LaTeX math segments. If Orgmode thinks that point is actually inside
12061 en embedded LaTeX fragement, let texmathp do its job.
12062 \\[org-cdlatex-mode-map]"
12063 (interactive)
12064 (let (p)
12065 (cond
12066 ((not (org-mode-p)) ad-do-it)
12067 ((eq this-command 'cdlatex-math-symbol)
12068 (setq ad-return-value t
12069 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12070 (t
12071 (let ((p (org-inside-LaTeX-fragment-p)))
12072 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12073 (setq ad-return-value t
12074 texmathp-why '("Org-mode embedded math" . 0))
12075 (if p ad-do-it)))))))))
12076
12077 (defun turn-on-org-cdlatex ()
12078 "Unconditionally turn on `org-cdlatex-mode'."
12079 (org-cdlatex-mode 1))
12080
12081 (defun org-inside-LaTeX-fragment-p ()
12082 "Test if point is inside a LaTeX fragment.
12083 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12084 sequence appearing also before point.
12085 Even though the matchers for math are configurable, this function assumes
12086 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12087 delimiters are skipped when they have been removed by customization.
12088 The return value is nil, or a cons cell with the delimiter and
12089 and the position of this delimiter.
12090
12091 This function does a reasonably good job, but can locally be fooled by
12092 for example currency specifications. For example it will assume being in
12093 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12094 fragments that are properly closed, but during editing, we have to live
12095 with the uncertainty caused by missing closing delimiters. This function
12096 looks only before point, not after."
12097 (catch 'exit
12098 (let ((pos (point))
12099 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12100 (lim (progn
12101 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12102 (point)))
12103 dd-on str (start 0) m re)
12104 (goto-char pos)
12105 (when dodollar
12106 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12107 re (nth 1 (assoc "$" org-latex-regexps)))
12108 (while (string-match re str start)
12109 (cond
12110 ((= (match-end 0) (length str))
12111 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12112 ((= (match-end 0) (- (length str) 5))
12113 (throw 'exit nil))
12114 (t (setq start (match-end 0))))))
12115 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12116 (goto-char pos)
12117 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12118 (and (match-beginning 2) (throw 'exit nil))
12119 ;; count $$
12120 (while (re-search-backward "\\$\\$" lim t)
12121 (setq dd-on (not dd-on)))
12122 (goto-char pos)
12123 (if dd-on (cons "$$" m))))))
12124
12125
12126 (defun org-try-cdlatex-tab ()
12127 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12128 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12129 - inside a LaTeX fragment, or
12130 - after the first word in a line, where an abbreviation expansion could
12131 insert a LaTeX environment."
12132 (when org-cdlatex-mode
12133 (cond
12134 ((save-excursion
12135 (skip-chars-backward "a-zA-Z0-9*")
12136 (skip-chars-backward " \t")
12137 (bolp))
12138 (cdlatex-tab) t)
12139 ((org-inside-LaTeX-fragment-p)
12140 (cdlatex-tab) t)
12141 (t nil))))
12142
12143 (defun org-cdlatex-underscore-caret (&optional arg)
12144 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12145 Revert to the normal definition outside of these fragments."
12146 (interactive "P")
12147 (if (org-inside-LaTeX-fragment-p)
12148 (call-interactively 'cdlatex-sub-superscript)
12149 (let (org-cdlatex-mode)
12150 (call-interactively (key-binding (vector last-input-event))))))
12151
12152 (defun org-cdlatex-math-modify (&optional arg)
12153 "Execute `cdlatex-math-modify' in LaTeX fragments.
12154 Revert to the normal definition outside of these fragments."
12155 (interactive "P")
12156 (if (org-inside-LaTeX-fragment-p)
12157 (call-interactively 'cdlatex-math-modify)
12158 (let (org-cdlatex-mode)
12159 (call-interactively (key-binding (vector last-input-event))))))
12160
12161 (defvar org-latex-fragment-image-overlays nil
12162 "List of overlays carrying the images of latex fragments.")
12163 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12164
12165 (defun org-remove-latex-fragment-image-overlays ()
12166 "Remove all overlays with LaTeX fragment images in current buffer."
12167 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12168 (setq org-latex-fragment-image-overlays nil))
12169
12170 (defun org-preview-latex-fragment (&optional subtree)
12171 "Preview the LaTeX fragment at point, or all locally or globally.
12172 If the cursor is in a LaTeX fragment, create the image and overlay
12173 it over the source code. If there is no fragment at point, display
12174 all fragments in the current text, from one headline to the next. With
12175 prefix SUBTREE, display all fragments in the current subtree. With a
12176 double prefix `C-u C-u', or when the cursor is before the first headline,
12177 display all fragments in the buffer.
12178 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12179 (interactive "P")
12180 (org-remove-latex-fragment-image-overlays)
12181 (save-excursion
12182 (save-restriction
12183 (let (beg end at msg)
12184 (cond
12185 ((or (equal subtree '(16))
12186 (not (save-excursion
12187 (re-search-backward (concat "^" outline-regexp) nil t))))
12188 (setq beg (point-min) end (point-max)
12189 msg "Creating images for buffer...%s"))
12190 ((equal subtree '(4))
12191 (org-back-to-heading)
12192 (setq beg (point) end (org-end-of-subtree t)
12193 msg "Creating images for subtree...%s"))
12194 (t
12195 (if (setq at (org-inside-LaTeX-fragment-p))
12196 (goto-char (max (point-min) (- (cdr at) 2)))
12197 (org-back-to-heading))
12198 (setq beg (point) end (progn (outline-next-heading) (point))
12199 msg (if at "Creating image...%s"
12200 "Creating images for entry...%s"))))
12201 (message msg "")
12202 (narrow-to-region beg end)
12203 (goto-char beg)
12204 (org-format-latex
12205 (concat "ltxpng/" (file-name-sans-extension
12206 (file-name-nondirectory
12207 buffer-file-name)))
12208 default-directory 'overlays msg at 'forbuffer)
12209 (message msg "done. Use `C-c C-c' to remove images.")))))
12210
12211 (defvar org-latex-regexps
12212 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12213 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12214 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12215 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12216 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12217 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12218 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12219 "Regular expressions for matching embedded LaTeX.")
12220
12221 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12222 "Replace LaTeX fragments with links to an image, and produce images."
12223 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12224 (let* ((prefixnodir (file-name-nondirectory prefix))
12225 (absprefix (expand-file-name prefix dir))
12226 (todir (file-name-directory absprefix))
12227 (opt org-format-latex-options)
12228 (matchers (plist-get opt :matchers))
12229 (re-list org-latex-regexps)
12230 (cnt 0) txt link beg end re e checkdir
12231 m n block linkfile movefile ov)
12232 ;; Check if there are old images files with this prefix, and remove them
12233 (when (file-directory-p todir)
12234 (mapc 'delete-file
12235 (directory-files
12236 todir 'full
12237 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12238 ;; Check the different regular expressions
12239 (while (setq e (pop re-list))
12240 (setq m (car e) re (nth 1 e) n (nth 2 e)
12241 block (if (nth 3 e) "\n\n" ""))
12242 (when (member m matchers)
12243 (goto-char (point-min))
12244 (while (re-search-forward re nil t)
12245 (when (or (not at) (equal (cdr at) (match-beginning n)))
12246 (setq txt (match-string n)
12247 beg (match-beginning n) end (match-end n)
12248 cnt (1+ cnt)
12249 linkfile (format "%s_%04d.png" prefix cnt)
12250 movefile (format "%s_%04d.png" absprefix cnt)
12251 link (concat block "[[file:" linkfile "]]" block))
12252 (if msg (message msg cnt))
12253 (goto-char beg)
12254 (unless checkdir ; make sure the directory exists
12255 (setq checkdir t)
12256 (or (file-directory-p todir) (make-directory todir)))
12257 (org-create-formula-image
12258 txt movefile opt forbuffer)
12259 (if overlays
12260 (progn
12261 (setq ov (org-make-overlay beg end))
12262 (if (featurep 'xemacs)
12263 (progn
12264 (org-overlay-put ov 'invisible t)
12265 (org-overlay-put
12266 ov 'end-glyph
12267 (make-glyph (vector 'png :file movefile))))
12268 (org-overlay-put
12269 ov 'display
12270 (list 'image :type 'png :file movefile :ascent 'center)))
12271 (push ov org-latex-fragment-image-overlays)
12272 (goto-char end))
12273 (delete-region beg end)
12274 (insert link))))))))
12275
12276 ;; This function borrows from Ganesh Swami's latex2png.el
12277 (defun org-create-formula-image (string tofile options buffer)
12278 (let* ((tmpdir (if (featurep 'xemacs)
12279 (temp-directory)
12280 temporary-file-directory))
12281 (texfilebase (make-temp-name
12282 (expand-file-name "orgtex" tmpdir)))
12283 (texfile (concat texfilebase ".tex"))
12284 (dvifile (concat texfilebase ".dvi"))
12285 (pngfile (concat texfilebase ".png"))
12286 (fnh (if (featurep 'xemacs)
12287 (font-height (get-face-font 'default))
12288 (face-attribute 'default :height nil)))
12289 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12290 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12291 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12292 "Black"))
12293 (bg (or (plist-get options (if buffer :background :html-background))
12294 "Transparent")))
12295 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12296 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12297 (with-temp-file texfile
12298 (insert org-format-latex-header
12299 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12300 (let ((dir default-directory))
12301 (condition-case nil
12302 (progn
12303 (cd tmpdir)
12304 (call-process "latex" nil nil nil texfile))
12305 (error nil))
12306 (cd dir))
12307 (if (not (file-exists-p dvifile))
12308 (progn (message "Failed to create dvi file from %s" texfile) nil)
12309 (condition-case nil
12310 (call-process "dvipng" nil nil nil
12311 "-E" "-fg" fg "-bg" bg
12312 "-D" dpi
12313 ;;"-x" scale "-y" scale
12314 "-T" "tight"
12315 "-o" pngfile
12316 dvifile)
12317 (error nil))
12318 (if (not (file-exists-p pngfile))
12319 (progn (message "Failed to create png file from %s" texfile) nil)
12320 ;; Use the requested file name and clean up
12321 (copy-file pngfile tofile 'replace)
12322 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12323 (delete-file (concat texfilebase e)))
12324 pngfile))))
12325
12326 (defun org-dvipng-color (attr)
12327 "Return an rgb color specification for dvipng."
12328 (apply 'format "rgb %s %s %s"
12329 (mapcar 'org-normalize-color
12330 (color-values (face-attribute 'default attr nil)))))
12331
12332 (defun org-normalize-color (value)
12333 "Return string to be used as color value for an RGB component."
12334 (format "%g" (/ value 65535.0)))
12335
12336
12337 ;;;; Key bindings
12338
12339 ;; Make `C-c C-x' a prefix key
12340 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12341
12342 ;; TAB key with modifiers
12343 (org-defkey org-mode-map "\C-i" 'org-cycle)
12344 (org-defkey org-mode-map [(tab)] 'org-cycle)
12345 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12346 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12347 (org-defkey org-mode-map "\M-\t" 'org-complete)
12348 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12349 ;; The following line is necessary under Suse GNU/Linux
12350 (unless (featurep 'xemacs)
12351 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12352 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12353 (define-key org-mode-map [backtab] 'org-shifttab)
12354
12355 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12356 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12357 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12358
12359 ;; Cursor keys with modifiers
12360 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12361 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12362 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12363 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12364
12365 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12366 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12367 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12368 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12369
12370 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12371 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12372 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12373 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12374
12375 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12376 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12377
12378 ;;; Extra keys for tty access.
12379 ;; We only set them when really needed because otherwise the
12380 ;; menus don't show the simple keys
12381
12382 (when (or org-use-extra-keys
12383 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12384 (not window-system))
12385 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12386 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12387 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12388 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12389 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12390 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12391 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12392 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12393 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12394 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12395 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12396 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12397 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12398 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12399 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12400 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12401 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12402 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12403 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12404 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12405 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12406 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12407
12408 ;; All the other keys
12409
12410 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12411 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12412 (if (boundp 'narrow-map)
12413 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12414 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12415 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12416 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12417 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12418 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12419 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12420 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12421 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12422 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12423 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12424 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12425 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12426 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12427 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12428 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12429 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12430 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12431 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12432 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12433 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12434 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12435 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12436 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12437 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12438 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12439 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12440 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12441 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12442 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12443 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12444 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12445 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12446 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12447 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12448 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12449 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12450 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12451 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12452 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12453 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12454 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12455 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12456 (org-defkey org-mode-map "\C-c^" 'org-sort)
12457 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12458 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12459 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12460 (org-defkey org-mode-map "\C-m" 'org-return)
12461 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12462 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12463 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12464 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12465 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12466 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12467 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12468 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12469 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12470 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12471 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12472 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12473 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12474 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12475 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12476 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12477
12478 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12479 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12480 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12481 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12482
12483 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12484 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12485 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12486 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12487 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12488 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12489 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12490 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12491 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12492 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12493 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12494 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12495
12496 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12497 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12498 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12499
12500 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12501
12502 (when (featurep 'xemacs)
12503 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12504
12505 (defvar org-table-auto-blank-field) ; defined in org-table.el
12506 (defun org-self-insert-command (N)
12507 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12508 If the cursor is in a table looking at whitespace, the whitespace is
12509 overwritten, and the table is not marked as requiring realignment."
12510 (interactive "p")
12511 (if (and (org-table-p)
12512 (progn
12513 ;; check if we blank the field, and if that triggers align
12514 (and (featurep 'org-table) org-table-auto-blank-field
12515 (member last-command
12516 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12517 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12518 ;; got extra space, this field does not determine column width
12519 (let (org-table-may-need-update) (org-table-blank-field))
12520 ;; no extra space, this field may determine column width
12521 (org-table-blank-field)))
12522 t)
12523 (eq N 1)
12524 (looking-at "[^|\n]* |"))
12525 (let (org-table-may-need-update)
12526 (goto-char (1- (match-end 0)))
12527 (delete-backward-char 1)
12528 (goto-char (match-beginning 0))
12529 (self-insert-command N))
12530 (setq org-table-may-need-update t)
12531 (self-insert-command N)
12532 (org-fix-tags-on-the-fly)))
12533
12534 (defun org-fix-tags-on-the-fly ()
12535 (when (and (equal (char-after (point-at-bol)) ?*)
12536 (org-on-heading-p))
12537 (org-align-tags-here org-tags-column)))
12538
12539 (defun org-delete-backward-char (N)
12540 "Like `delete-backward-char', insert whitespace at field end in tables.
12541 When deleting backwards, in tables this function will insert whitespace in
12542 front of the next \"|\" separator, to keep the table aligned. The table will
12543 still be marked for re-alignment if the field did fill the entire column,
12544 because, in this case the deletion might narrow the column."
12545 (interactive "p")
12546 (if (and (org-table-p)
12547 (eq N 1)
12548 (string-match "|" (buffer-substring (point-at-bol) (point)))
12549 (looking-at ".*?|"))
12550 (let ((pos (point))
12551 (noalign (looking-at "[^|\n\r]* |"))
12552 (c org-table-may-need-update))
12553 (backward-delete-char N)
12554 (skip-chars-forward "^|")
12555 (insert " ")
12556 (goto-char (1- pos))
12557 ;; noalign: if there were two spaces at the end, this field
12558 ;; does not determine the width of the column.
12559 (if noalign (setq org-table-may-need-update c)))
12560 (backward-delete-char N)
12561 (org-fix-tags-on-the-fly)))
12562
12563 (defun org-delete-char (N)
12564 "Like `delete-char', but insert whitespace at field end in tables.
12565 When deleting characters, in tables this function will insert whitespace in
12566 front of the next \"|\" separator, to keep the table aligned. The table will
12567 still be marked for re-alignment if the field did fill the entire column,
12568 because, in this case the deletion might narrow the column."
12569 (interactive "p")
12570 (if (and (org-table-p)
12571 (not (bolp))
12572 (not (= (char-after) ?|))
12573 (eq N 1))
12574 (if (looking-at ".*?|")
12575 (let ((pos (point))
12576 (noalign (looking-at "[^|\n\r]* |"))
12577 (c org-table-may-need-update))
12578 (replace-match (concat
12579 (substring (match-string 0) 1 -1)
12580 " |"))
12581 (goto-char pos)
12582 ;; noalign: if there were two spaces at the end, this field
12583 ;; does not determine the width of the column.
12584 (if noalign (setq org-table-may-need-update c)))
12585 (delete-char N))
12586 (delete-char N)
12587 (org-fix-tags-on-the-fly)))
12588
12589 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12590 (put 'org-self-insert-command 'delete-selection t)
12591 (put 'orgtbl-self-insert-command 'delete-selection t)
12592 (put 'org-delete-char 'delete-selection 'supersede)
12593 (put 'org-delete-backward-char 'delete-selection 'supersede)
12594
12595 ;; Make `flyspell-mode' delay after some commands
12596 (put 'org-self-insert-command 'flyspell-delayed t)
12597 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12598 (put 'org-delete-char 'flyspell-delayed t)
12599 (put 'org-delete-backward-char 'flyspell-delayed t)
12600
12601 ;; Make pabbrev-mode expand after org-mode commands
12602 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12603 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12604
12605 ;; How to do this: Measure non-white length of current string
12606 ;; If equal to column width, we should realign.
12607
12608 (defun org-remap (map &rest commands)
12609 "In MAP, remap the functions given in COMMANDS.
12610 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12611 (let (new old)
12612 (while commands
12613 (setq old (pop commands) new (pop commands))
12614 (if (fboundp 'command-remapping)
12615 (org-defkey map (vector 'remap old) new)
12616 (substitute-key-definition old new map global-map)))))
12617
12618 (when (eq org-enable-table-editor 'optimized)
12619 ;; If the user wants maximum table support, we need to hijack
12620 ;; some standard editing functions
12621 (org-remap org-mode-map
12622 'self-insert-command 'org-self-insert-command
12623 'delete-char 'org-delete-char
12624 'delete-backward-char 'org-delete-backward-char)
12625 (org-defkey org-mode-map "|" 'org-force-self-insert))
12626
12627 (defun org-shiftcursor-error ()
12628 "Throw an error because Shift-Cursor command was applied in wrong context."
12629 (error "This command is active in special context like tables, headlines or timestamps"))
12630
12631 (defun org-shifttab (&optional arg)
12632 "Global visibility cycling or move to previous table field.
12633 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12634 on context.
12635 See the individual commands for more information."
12636 (interactive "P")
12637 (cond
12638 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12639 ((integerp arg)
12640 (message "Content view to level: %d" arg)
12641 (org-content (prefix-numeric-value arg))
12642 (setq org-cycle-global-status 'overview))
12643 (t (call-interactively 'org-global-cycle))))
12644
12645 (defun org-shiftmetaleft ()
12646 "Promote subtree or delete table column.
12647 Calls `org-promote-subtree', `org-outdent-item',
12648 or `org-table-delete-column', depending on context.
12649 See the individual commands for more information."
12650 (interactive)
12651 (cond
12652 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12653 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12654 ((org-at-item-p) (call-interactively 'org-outdent-item))
12655 (t (org-shiftcursor-error))))
12656
12657 (defun org-shiftmetaright ()
12658 "Demote subtree or insert table column.
12659 Calls `org-demote-subtree', `org-indent-item',
12660 or `org-table-insert-column', depending on context.
12661 See the individual commands for more information."
12662 (interactive)
12663 (cond
12664 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12665 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12666 ((org-at-item-p) (call-interactively 'org-indent-item))
12667 (t (org-shiftcursor-error))))
12668
12669 (defun org-shiftmetaup (&optional arg)
12670 "Move subtree up or kill table row.
12671 Calls `org-move-subtree-up' or `org-table-kill-row' or
12672 `org-move-item-up' depending on context. See the individual commands
12673 for more information."
12674 (interactive "P")
12675 (cond
12676 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12677 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12678 ((org-at-item-p) (call-interactively 'org-move-item-up))
12679 (t (org-shiftcursor-error))))
12680 (defun org-shiftmetadown (&optional arg)
12681 "Move subtree down or insert table row.
12682 Calls `org-move-subtree-down' or `org-table-insert-row' or
12683 `org-move-item-down', depending on context. See the individual
12684 commands for more information."
12685 (interactive "P")
12686 (cond
12687 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12688 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12689 ((org-at-item-p) (call-interactively 'org-move-item-down))
12690 (t (org-shiftcursor-error))))
12691
12692 (defun org-metaleft (&optional arg)
12693 "Promote heading or move table column to left.
12694 Calls `org-do-promote' or `org-table-move-column', depending on context.
12695 With no specific context, calls the Emacs default `backward-word'.
12696 See the individual commands for more information."
12697 (interactive "P")
12698 (cond
12699 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12700 ((or (org-on-heading-p) (org-region-active-p))
12701 (call-interactively 'org-do-promote))
12702 ((org-at-item-p) (call-interactively 'org-outdent-item))
12703 (t (call-interactively 'backward-word))))
12704
12705 (defun org-metaright (&optional arg)
12706 "Demote subtree or move table column to right.
12707 Calls `org-do-demote' or `org-table-move-column', depending on context.
12708 With no specific context, calls the Emacs default `forward-word'.
12709 See the individual commands for more information."
12710 (interactive "P")
12711 (cond
12712 ((org-at-table-p) (call-interactively 'org-table-move-column))
12713 ((or (org-on-heading-p) (org-region-active-p))
12714 (call-interactively 'org-do-demote))
12715 ((org-at-item-p) (call-interactively 'org-indent-item))
12716 (t (call-interactively 'forward-word))))
12717
12718 (defun org-metaup (&optional arg)
12719 "Move subtree up or move table row up.
12720 Calls `org-move-subtree-up' or `org-table-move-row' or
12721 `org-move-item-up', depending on context. See the individual commands
12722 for more information."
12723 (interactive "P")
12724 (cond
12725 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12726 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12727 ((org-at-item-p) (call-interactively 'org-move-item-up))
12728 (t (transpose-lines 1) (beginning-of-line -1))))
12729
12730 (defun org-metadown (&optional arg)
12731 "Move subtree down or move table row down.
12732 Calls `org-move-subtree-down' or `org-table-move-row' or
12733 `org-move-item-down', depending on context. See the individual
12734 commands for more information."
12735 (interactive "P")
12736 (cond
12737 ((org-at-table-p) (call-interactively 'org-table-move-row))
12738 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12739 ((org-at-item-p) (call-interactively 'org-move-item-down))
12740 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12741
12742 (defun org-shiftup (&optional arg)
12743 "Increase item in timestamp or increase priority of current headline.
12744 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12745 depending on context. See the individual commands for more information."
12746 (interactive "P")
12747 (cond
12748 ((org-at-timestamp-p t)
12749 (call-interactively (if org-edit-timestamp-down-means-later
12750 'org-timestamp-down 'org-timestamp-up)))
12751 ((org-on-heading-p) (call-interactively 'org-priority-up))
12752 ((org-at-item-p) (call-interactively 'org-previous-item))
12753 ((org-clocktable-try-shift 'up arg))
12754 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12755
12756 (defun org-shiftdown (&optional arg)
12757 "Decrease item in timestamp or decrease priority of current headline.
12758 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12759 depending on context. See the individual commands for more information."
12760 (interactive "P")
12761 (cond
12762 ((org-at-timestamp-p t)
12763 (call-interactively (if org-edit-timestamp-down-means-later
12764 'org-timestamp-up 'org-timestamp-down)))
12765 ((org-on-heading-p) (call-interactively 'org-priority-down))
12766 ((org-clocktable-try-shift 'down arg))
12767 (t (call-interactively 'org-next-item))))
12768
12769 (defun org-shiftright (&optional arg)
12770 "Cycle the thing at point or in the current line, depending on context.
12771 Depending on context, this does one of the following:
12772
12773 - switch a timestamp at point one day into the future
12774 - on a headline, switch to the next TODO keyword.
12775 - on an item, switch entire list to the next bullet type
12776 - on a property line, switch to the next allowed value
12777 - on a clocktable definition line, move time block into the future"
12778 (interactive "P")
12779 (cond
12780 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12781 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12782 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12783 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12784 ((org-clocktable-try-shift 'right arg))
12785 (t (org-shiftcursor-error))))
12786
12787 (defun org-shiftleft (&optional arg)
12788 "Cycle the thing at point or in the current line, depending on context.
12789 Depending on context, this does one of the following:
12790
12791 - switch a timestamp at point one day into the past
12792 - on a headline, switch to the previous TODO keyword.
12793 - on an item, switch entire list to the previous bullet type
12794 - on a property line, switch to the previous allowed value
12795 - on a clocktable definition line, move time block into the past"
12796 (interactive "P")
12797 (cond
12798 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12799 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12800 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12801 ((org-at-property-p)
12802 (call-interactively 'org-property-previous-allowed-value))
12803 ((org-clocktable-try-shift 'left arg))
12804 (t (org-shiftcursor-error))))
12805
12806 (defun org-shiftcontrolright ()
12807 "Switch to next TODO set."
12808 (interactive)
12809 (cond
12810 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12811 (t (org-shiftcursor-error))))
12812
12813 (defun org-shiftcontrolleft ()
12814 "Switch to previous TODO set."
12815 (interactive)
12816 (cond
12817 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12818 (t (org-shiftcursor-error))))
12819
12820 (defun org-ctrl-c-ret ()
12821 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12822 (interactive)
12823 (cond
12824 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12825 (t (call-interactively 'org-insert-heading))))
12826
12827 (defun org-copy-special ()
12828 "Copy region in table or copy current subtree.
12829 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12830 See the individual commands for more information."
12831 (interactive)
12832 (call-interactively
12833 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12834
12835 (defun org-cut-special ()
12836 "Cut region in table or cut current subtree.
12837 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12838 See the individual commands for more information."
12839 (interactive)
12840 (call-interactively
12841 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12842
12843 (defun org-paste-special (arg)
12844 "Paste rectangular region into table, or past subtree relative to level.
12845 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12846 See the individual commands for more information."
12847 (interactive "P")
12848 (if (org-at-table-p)
12849 (org-table-paste-rectangle)
12850 (org-paste-subtree arg)))
12851
12852 (defun org-edit-special ()
12853 "Call a special editor for the stuff at point.
12854 When at a table, call the formula editor with `org-table-edit-formulas'.
12855 When at the first line of an src example, call `org-edit-src-code'.
12856 When in an #+include line, visit the include file. Otherwise call
12857 `ffap' to visit the file at point."
12858 (interactive)
12859 (cond
12860 ((org-at-table-p)
12861 (call-interactively 'org-table-edit-formulas))
12862 ((save-excursion
12863 (beginning-of-line 1)
12864 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12865 (find-file (org-trim (match-string 1))))
12866 ((org-edit-src-code))
12867 ((org-edit-fixed-width-region))
12868 (t (call-interactively 'ffap))))
12869
12870 (defun org-ctrl-c-ctrl-c (&optional arg)
12871 "Set tags in headline, or update according to changed information at point.
12872
12873 This command does many different things, depending on context:
12874
12875 - If the cursor is in a headline, prompt for tags and insert them
12876 into the current line, aligned to `org-tags-column'. When called
12877 with prefix arg, realign all tags in the current buffer.
12878
12879 - If the cursor is in one of the special #+KEYWORD lines, this
12880 triggers scanning the buffer for these lines and updating the
12881 information.
12882
12883 - If the cursor is inside a table, realign the table. This command
12884 works even if the automatic table editor has been turned off.
12885
12886 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12887 the entire table.
12888
12889 - If the cursor is a the beginning of a dynamic block, update it.
12890
12891 - If the cursor is inside a table created by the table.el package,
12892 activate that table.
12893
12894 - If the current buffer is a remember buffer, close note and file
12895 it. A prefix argument of 1 files to the default location
12896 without further interaction. A prefix argument of 2 files to
12897 the currently clocking task.
12898
12899 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12900 links in this buffer.
12901
12902 - If the cursor is on a numbered item in a plain list, renumber the
12903 ordered list.
12904
12905 - If the cursor is on a checkbox, toggle it."
12906 (interactive "P")
12907 (let ((org-enable-table-editor t))
12908 (cond
12909 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12910 org-occur-highlights
12911 org-latex-fragment-image-overlays)
12912 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12913 (org-remove-occur-highlights)
12914 (org-remove-latex-fragment-image-overlays)
12915 (message "Temporary highlights/overlays removed from current buffer"))
12916 ((and (local-variable-p 'org-finish-function (current-buffer))
12917 (fboundp org-finish-function))
12918 (funcall org-finish-function))
12919 ((org-at-property-p)
12920 (call-interactively 'org-property-action))
12921 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12922 ((org-on-heading-p) (call-interactively 'org-set-tags))
12923 ((org-at-table.el-p)
12924 (require 'table)
12925 (beginning-of-line 1)
12926 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12927 (call-interactively 'table-recognize-table))
12928 ((org-at-table-p)
12929 (org-table-maybe-eval-formula)
12930 (if arg
12931 (call-interactively 'org-table-recalculate)
12932 (org-table-maybe-recalculate-line))
12933 (call-interactively 'org-table-align))
12934 ((org-at-item-checkbox-p)
12935 (call-interactively 'org-toggle-checkbox))
12936 ((org-at-item-p)
12937 (call-interactively 'org-maybe-renumber-ordered-list))
12938 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12939 ;; Dynamic block
12940 (beginning-of-line 1)
12941 (save-excursion (org-update-dblock)))
12942 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12943 (cond
12944 ((equal (match-string 1) "TBLFM")
12945 ;; Recalculate the table before this line
12946 (save-excursion
12947 (beginning-of-line 1)
12948 (skip-chars-backward " \r\n\t")
12949 (if (org-at-table-p)
12950 (org-call-with-arg 'org-table-recalculate t))))
12951 (t
12952 ; (org-set-regexps-and-options)
12953 ; (org-restart-font-lock)
12954 (let ((org-inhibit-startup t)) (org-mode-restart))
12955 (message "Local setup has been refreshed"))))
12956 (t (error "C-c C-c can do nothing useful at this location.")))))
12957
12958 (defun org-mode-restart ()
12959 "Restart Org-mode, to scan again for special lines.
12960 Also updates the keyword regular expressions."
12961 (interactive)
12962 (org-mode)
12963 (message "Org-mode restarted"))
12964
12965 (defun org-kill-note-or-show-branches ()
12966 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12967 (interactive)
12968 (if (not org-finish-function)
12969 (call-interactively 'show-branches)
12970 (let ((org-note-abort t))
12971 (funcall org-finish-function))))
12972
12973 (defun org-return (&optional indent)
12974 "Goto next table row or insert a newline.
12975 Calls `org-table-next-row' or `newline', depending on context.
12976 See the individual commands for more information."
12977 (interactive)
12978 (cond
12979 ((bobp) (if indent (newline-and-indent) (newline)))
12980 ((and (org-at-heading-p)
12981 (looking-at
12982 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12983 (org-show-entry)
12984 (end-of-line 1)
12985 (newline))
12986 ((org-at-table-p)
12987 (org-table-justify-field-maybe)
12988 (call-interactively 'org-table-next-row))
12989 (t (if indent (newline-and-indent) (newline)))))
12990
12991 (defun org-return-indent ()
12992 "Goto next table row or insert a newline and indent.
12993 Calls `org-table-next-row' or `newline-and-indent', depending on
12994 context. See the individual commands for more information."
12995 (interactive)
12996 (org-return t))
12997
12998 (defun org-ctrl-c-star ()
12999 "Compute table, or change heading status of lines.
13000 Calls `org-table-recalculate' or `org-toggle-region-headings',
13001 depending on context. This will also turn a plain list item or a normal
13002 line into a subheading."
13003 (interactive)
13004 (cond
13005 ((org-at-table-p)
13006 (call-interactively 'org-table-recalculate))
13007 ((org-region-active-p)
13008 ;; Convert all lines in region to list items
13009 (call-interactively 'org-toggle-region-headings))
13010 ((org-on-heading-p)
13011 (org-toggle-region-headings (point-at-bol)
13012 (min (1+ (point-at-eol)) (point-max))))
13013 ((org-at-item-p)
13014 ;; Convert to heading
13015 (let ((level (save-match-data
13016 (save-excursion
13017 (condition-case nil
13018 (progn
13019 (org-back-to-heading t)
13020 (funcall outline-level))
13021 (error 0))))))
13022 (replace-match
13023 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13024 (t (org-toggle-region-headings (point-at-bol)
13025 (min (1+ (point-at-eol)) (point-max))))))
13026
13027 (defun org-ctrl-c-minus ()
13028 "Insert separator line in table or modify bullet status of line.
13029 Also turns a plain line or a region of lines into list items.
13030 Calls `org-table-insert-hline', `org-toggle-region-items', or
13031 `org-cycle-list-bullet', depending on context."
13032 (interactive)
13033 (cond
13034 ((org-at-table-p)
13035 (call-interactively 'org-table-insert-hline))
13036 ((org-on-heading-p)
13037 ;; Convert to item
13038 (save-excursion
13039 (beginning-of-line 1)
13040 (if (looking-at "\\*+ ")
13041 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
13042 ((org-region-active-p)
13043 ;; Convert all lines in region to list items
13044 (call-interactively 'org-toggle-region-items))
13045 ((org-in-item-p)
13046 (call-interactively 'org-cycle-list-bullet))
13047 (t (org-toggle-region-items (point-at-bol)
13048 (min (1+ (point-at-eol)) (point-max))))))
13049
13050 (defun org-toggle-region-items (beg end)
13051 "Convert all lines in region to list items.
13052 If the first line is already an item, convert all list items in the region
13053 to normal lines."
13054 (interactive "r")
13055 (let (l2 l)
13056 (save-excursion
13057 (goto-char end)
13058 (setq l2 (org-current-line))
13059 (goto-char beg)
13060 (beginning-of-line 1)
13061 (setq l (1- (org-current-line)))
13062 (if (org-at-item-p)
13063 ;; We already have items, de-itemize
13064 (while (< (setq l (1+ l)) l2)
13065 (when (org-at-item-p)
13066 (goto-char (match-beginning 2))
13067 (delete-region (match-beginning 2) (match-end 2))
13068 (and (looking-at "[ \t]+") (replace-match "")))
13069 (beginning-of-line 2))
13070 (while (< (setq l (1+ l)) l2)
13071 (unless (org-at-item-p)
13072 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13073 (replace-match "\\1- \\2")))
13074 (beginning-of-line 2))))))
13075
13076 (defun org-toggle-region-headings (beg end)
13077 "Convert all lines in region to list items.
13078 If the first line is already an item, convert all list items in the region
13079 to normal lines."
13080 (interactive "r")
13081 (let (l2 l)
13082 (save-excursion
13083 (goto-char end)
13084 (setq l2 (org-current-line))
13085 (goto-char beg)
13086 (beginning-of-line 1)
13087 (setq l (1- (org-current-line)))
13088 (if (org-on-heading-p)
13089 ;; We already have headlines, de-star them
13090 (while (< (setq l (1+ l)) l2)
13091 (when (org-on-heading-p t)
13092 (and (looking-at outline-regexp) (replace-match "")))
13093 (beginning-of-line 2))
13094 (let* ((stars (save-excursion
13095 (re-search-backward org-complex-heading-regexp nil t)
13096 (or (match-string 1) "*")))
13097 (add-stars (if org-odd-levels-only "**" "*"))
13098 (rpl (concat stars add-stars " \\2")))
13099 (while (< (setq l (1+ l)) l2)
13100 (unless (org-on-heading-p)
13101 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13102 (replace-match rpl)))
13103 (beginning-of-line 2)))))))
13104
13105 (defun org-meta-return (&optional arg)
13106 "Insert a new heading or wrap a region in a table.
13107 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13108 See the individual commands for more information."
13109 (interactive "P")
13110 (cond
13111 ((org-at-table-p)
13112 (call-interactively 'org-table-wrap-region))
13113 (t (call-interactively 'org-insert-heading))))
13114
13115 ;;; Menu entries
13116
13117 ;; Define the Org-mode menus
13118 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13119 '("Tbl"
13120 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13121 ["Next Field" org-cycle (org-at-table-p)]
13122 ["Previous Field" org-shifttab (org-at-table-p)]
13123 ["Next Row" org-return (org-at-table-p)]
13124 "--"
13125 ["Blank Field" org-table-blank-field (org-at-table-p)]
13126 ["Edit Field" org-table-edit-field (org-at-table-p)]
13127 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13128 "--"
13129 ("Column"
13130 ["Move Column Left" org-metaleft (org-at-table-p)]
13131 ["Move Column Right" org-metaright (org-at-table-p)]
13132 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13133 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13134 ("Row"
13135 ["Move Row Up" org-metaup (org-at-table-p)]
13136 ["Move Row Down" org-metadown (org-at-table-p)]
13137 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13138 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13139 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13140 "--"
13141 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13142 ("Rectangle"
13143 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13144 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13145 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13146 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13147 "--"
13148 ("Calculate"
13149 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13150 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13151 ["Edit Formulas" org-edit-special (org-at-table-p)]
13152 "--"
13153 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13154 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13155 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13156 "--"
13157 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13158 "--"
13159 ["Sum Column/Rectangle" org-table-sum
13160 (or (org-at-table-p) (org-region-active-p))]
13161 ["Which Column?" org-table-current-column (org-at-table-p)])
13162 ["Debug Formulas"
13163 org-table-toggle-formula-debugger
13164 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13165 ["Show Col/Row Numbers"
13166 org-table-toggle-coordinate-overlays
13167 :style toggle
13168 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13169 "--"
13170 ["Create" org-table-create (and (not (org-at-table-p))
13171 org-enable-table-editor)]
13172 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13173 ["Import from File" org-table-import (not (org-at-table-p))]
13174 ["Export to File" org-table-export (org-at-table-p)]
13175 "--"
13176 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13177
13178 (easy-menu-define org-org-menu org-mode-map "Org menu"
13179 '("Org"
13180 ("Show/Hide"
13181 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13182 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13183 ["Sparse Tree..." org-sparse-tree t]
13184 ["Reveal Context" org-reveal t]
13185 ["Show All" show-all t]
13186 "--"
13187 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13188 "--"
13189 ["New Heading" org-insert-heading t]
13190 ("Navigate Headings"
13191 ["Up" outline-up-heading t]
13192 ["Next" outline-next-visible-heading t]
13193 ["Previous" outline-previous-visible-heading t]
13194 ["Next Same Level" outline-forward-same-level t]
13195 ["Previous Same Level" outline-backward-same-level t]
13196 "--"
13197 ["Jump" org-goto t])
13198 ("Edit Structure"
13199 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13200 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13201 "--"
13202 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13203 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13204 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13205 "--"
13206 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13207 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13208 ["Demote Heading" org-metaright (not (org-at-table-p))]
13209 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13210 "--"
13211 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13212 "--"
13213 ["Convert to odd levels" org-convert-to-odd-levels t]
13214 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13215 ("Editing"
13216 ["Emphasis..." org-emphasize t]
13217 ["Edit Source Example" org-edit-special t])
13218 ("Archive"
13219 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13220 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13221 ; :active t :keys "C-u C-c C-x C-a"]
13222 ["Sparse trees open ARCHIVE trees"
13223 (setq org-sparse-tree-open-archived-trees
13224 (not org-sparse-tree-open-archived-trees))
13225 :style toggle :selected org-sparse-tree-open-archived-trees]
13226 ["Cycling opens ARCHIVE trees"
13227 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13228 :style toggle :selected org-cycle-open-archived-trees]
13229 "--"
13230 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13231 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13232 ; ["Check and Move Children" (org-archive-subtree '(4))
13233 ; :active t :keys "C-u C-c C-x C-s"]
13234 )
13235 "--"
13236 ("TODO Lists"
13237 ["TODO/DONE/-" org-todo t]
13238 ("Select keyword"
13239 ["Next keyword" org-shiftright (org-on-heading-p)]
13240 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13241 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13242 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13243 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13244 ["Show TODO Tree" org-show-todo-tree t]
13245 ["Global TODO list" org-todo-list t]
13246 "--"
13247 ["Set Priority" org-priority t]
13248 ["Priority Up" org-shiftup t]
13249 ["Priority Down" org-shiftdown t])
13250 ("TAGS and Properties"
13251 ["Set Tags" 'org-set-tags-command t]
13252 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13253 "--"
13254 ["Set property" 'org-set-property t]
13255 ["Column view of properties" org-columns t]
13256 ["Insert Column View DBlock" org-insert-columns-dblock t])
13257 ("Dates and Scheduling"
13258 ["Timestamp" org-time-stamp t]
13259 ["Timestamp (inactive)" org-time-stamp-inactive t]
13260 ("Change Date"
13261 ["1 Day Later" org-shiftright t]
13262 ["1 Day Earlier" org-shiftleft t]
13263 ["1 ... Later" org-shiftup t]
13264 ["1 ... Earlier" org-shiftdown t])
13265 ["Compute Time Range" org-evaluate-time-range t]
13266 ["Schedule Item" org-schedule t]
13267 ["Deadline" org-deadline t]
13268 "--"
13269 ["Custom time format" org-toggle-time-stamp-overlays
13270 :style radio :selected org-display-custom-times]
13271 "--"
13272 ["Goto Calendar" org-goto-calendar t]
13273 ["Date from Calendar" org-date-from-calendar t]
13274 "--"
13275 ["Start/restart timer" org-timer-start t]
13276 ["Insert timer string" org-timer t]
13277 ["Insert timer item" org-timer-item t])
13278 ("Logging work"
13279 ["Clock in" org-clock-in t]
13280 ["Clock out" org-clock-out t]
13281 ["Clock cancel" org-clock-cancel t]
13282 ["Goto running clock" org-clock-goto t]
13283 ["Display times" org-clock-display t]
13284 ["Create clock table" org-clock-report t]
13285 "--"
13286 ["Record DONE time"
13287 (progn (setq org-log-done (not org-log-done))
13288 (message "Switching to %s will %s record a timestamp"
13289 (car org-done-keywords)
13290 (if org-log-done "automatically" "not")))
13291 :style toggle :selected org-log-done])
13292 "--"
13293 ["Agenda Command..." org-agenda t]
13294 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13295 ("File List for Agenda")
13296 ("Special views current file"
13297 ["TODO Tree" org-show-todo-tree t]
13298 ["Check Deadlines" org-check-deadlines t]
13299 ["Timeline" org-timeline t]
13300 ["Tags Tree" org-tags-sparse-tree t])
13301 "--"
13302 ("Hyperlinks"
13303 ["Store Link (Global)" org-store-link t]
13304 ["Insert Link" org-insert-link t]
13305 ["Follow Link" org-open-at-point t]
13306 "--"
13307 ["Next link" org-next-link t]
13308 ["Previous link" org-previous-link t]
13309 "--"
13310 ["Descriptive Links"
13311 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13312 :style radio
13313 :selected (member '(org-link) buffer-invisibility-spec)]
13314 ["Literal Links"
13315 (progn
13316 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13317 :style radio
13318 :selected (not (member '(org-link) buffer-invisibility-spec))])
13319 "--"
13320 ["Export/Publish..." org-export t]
13321 ("LaTeX"
13322 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13323 :selected org-cdlatex-mode]
13324 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13325 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13326 ["Modify math symbol" org-cdlatex-math-modify
13327 (org-inside-LaTeX-fragment-p)]
13328 ["Export LaTeX fragments as images"
13329 (if (featurep 'org-exp)
13330 (setq org-export-with-LaTeX-fragments
13331 (not org-export-with-LaTeX-fragments))
13332 (require 'org-exp))
13333 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13334 org-export-with-LaTeX-fragments)])
13335 "--"
13336 ("Documentation"
13337 ["Show Version" org-version t]
13338 ["Info Documentation" org-info t])
13339 ("Customize"
13340 ["Browse Org Group" org-customize t]
13341 "--"
13342 ["Expand This Menu" org-create-customize-menu
13343 (fboundp 'customize-menu-create)])
13344 "--"
13345 ["Refresh setup" org-mode-restart t]
13346 ))
13347
13348 (defun org-info (&optional node)
13349 "Read documentation for Org-mode in the info system.
13350 With optional NODE, go directly to that node."
13351 (interactive)
13352 (info (format "(org)%s" (or node ""))))
13353
13354 (defun org-install-agenda-files-menu ()
13355 (let ((bl (buffer-list)))
13356 (save-excursion
13357 (while bl
13358 (set-buffer (pop bl))
13359 (if (org-mode-p) (setq bl nil)))
13360 (when (org-mode-p)
13361 (easy-menu-change
13362 '("Org") "File List for Agenda"
13363 (append
13364 (list
13365 ["Edit File List" (org-edit-agenda-file-list) t]
13366 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13367 ["Remove Current File from List" org-remove-file t]
13368 ["Cycle through agenda files" org-cycle-agenda-files t]
13369 ["Occur in all agenda files" org-occur-in-agenda-files t]
13370 "--")
13371 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13372
13373 ;;;; Documentation
13374
13375 ;;;###autoload
13376 (defun org-require-autoloaded-modules ()
13377 (interactive)
13378 (mapc 'require
13379 '(org-agenda org-archive org-clock org-colview
13380 org-exp org-id org-export-latex org-publish
13381 org-remember org-table)))
13382
13383 ;;;###autoload
13384 (defun org-customize ()
13385 "Call the customize function with org as argument."
13386 (interactive)
13387 (org-load-modules-maybe)
13388 (org-require-autoloaded-modules)
13389 (customize-browse 'org))
13390
13391 (defun org-create-customize-menu ()
13392 "Create a full customization menu for Org-mode, insert it into the menu."
13393 (interactive)
13394 (org-load-modules-maybe)
13395 (org-require-autoloaded-modules)
13396 (if (fboundp 'customize-menu-create)
13397 (progn
13398 (easy-menu-change
13399 '("Org") "Customize"
13400 `(["Browse Org group" org-customize t]
13401 "--"
13402 ,(customize-menu-create 'org)
13403 ["Set" Custom-set t]
13404 ["Save" Custom-save t]
13405 ["Reset to Current" Custom-reset-current t]
13406 ["Reset to Saved" Custom-reset-saved t]
13407 ["Reset to Standard Settings" Custom-reset-standard t]))
13408 (message "\"Org\"-menu now contains full customization menu"))
13409 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13410
13411 ;;;; Miscellaneous stuff
13412
13413 ;;; Generally useful functions
13414
13415 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13416 "Display the given MESSAGE as a warning."
13417 (if (fboundp 'display-warning)
13418 (display-warning 'org message
13419 (if (featurep 'xemacs)
13420 'warning
13421 :warning))
13422 (let ((buf (get-buffer-create "*Org warnings*")))
13423 (with-current-buffer buf
13424 (goto-char (point-max))
13425 (insert "Warning (Org): " message)
13426 (unless (bolp)
13427 (newline)))
13428 (display-buffer buf)
13429 (sit-for 0))))
13430
13431 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13432 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
13433 (if (and marker (marker-buffer marker)
13434 (buffer-live-p (marker-buffer marker)))
13435 (progn
13436 (switch-to-buffer (marker-buffer marker))
13437 (if (or (> marker (point-max)) (< marker (point-min)))
13438 (widen))
13439 (goto-char marker))
13440 (if bookmark
13441 (bookmark-jump bookmark)
13442 (error "Cannot find location"))))
13443
13444 (defun org-quote-csv-field (s)
13445 "Quote field for inclusion in CSV material."
13446 (if (string-match "[\",]" s)
13447 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13448 s))
13449
13450 (defun org-plist-delete (plist property)
13451 "Delete PROPERTY from PLIST.
13452 This is in contrast to merely setting it to 0."
13453 (let (p)
13454 (while plist
13455 (if (not (eq property (car plist)))
13456 (setq p (plist-put p (car plist) (nth 1 plist))))
13457 (setq plist (cddr plist)))
13458 p))
13459
13460 (defun org-force-self-insert (N)
13461 "Needed to enforce self-insert under remapping."
13462 (interactive "p")
13463 (self-insert-command N))
13464
13465 (defun org-string-width (s)
13466 "Compute width of string, ignoring invisible characters.
13467 This ignores character with invisibility property `org-link', and also
13468 characters with property `org-cwidth', because these will become invisible
13469 upon the next fontification round."
13470 (let (b l)
13471 (when (or (eq t buffer-invisibility-spec)
13472 (assq 'org-link buffer-invisibility-spec))
13473 (while (setq b (text-property-any 0 (length s)
13474 'invisible 'org-link s))
13475 (setq s (concat (substring s 0 b)
13476 (substring s (or (next-single-property-change
13477 b 'invisible s) (length s)))))))
13478 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13479 (setq s (concat (substring s 0 b)
13480 (substring s (or (next-single-property-change
13481 b 'org-cwidth s) (length s))))))
13482 (setq l (string-width s) b -1)
13483 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13484 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13485 l))
13486
13487 (defun org-get-indentation (&optional line)
13488 "Get the indentation of the current line, interpreting tabs.
13489 When LINE is given, assume it represents a line and compute its indentation."
13490 (if line
13491 (if (string-match "^ *" (org-remove-tabs line))
13492 (match-end 0))
13493 (save-excursion
13494 (beginning-of-line 1)
13495 (skip-chars-forward " \t")
13496 (current-column))))
13497
13498 (defun org-remove-tabs (s &optional width)
13499 "Replace tabulators in S with spaces.
13500 Assumes that s is a single line, starting in column 0."
13501 (setq width (or width tab-width))
13502 (while (string-match "\t" s)
13503 (setq s (replace-match
13504 (make-string
13505 (- (* width (/ (+ (match-beginning 0) width) width))
13506 (match-beginning 0)) ?\ )
13507 t t s)))
13508 s)
13509
13510 (defun org-fix-indentation (line ind)
13511 "Fix indentation in LINE.
13512 IND is a cons cell with target and minimum indentation.
13513 If the current indenation in LINE is smaller than the minimum,
13514 leave it alone. If it is larger than ind, set it to the target."
13515 (let* ((l (org-remove-tabs line))
13516 (i (org-get-indentation l))
13517 (i1 (car ind)) (i2 (cdr ind)))
13518 (if (>= i i2) (setq l (substring line i2)))
13519 (if (> i1 0)
13520 (concat (make-string i1 ?\ ) l)
13521 l)))
13522
13523 (defun org-base-buffer (buffer)
13524 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13525 (if (not buffer)
13526 buffer
13527 (or (buffer-base-buffer buffer)
13528 buffer)))
13529
13530 (defun org-trim (s)
13531 "Remove whitespace at beginning and end of string."
13532 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13533 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13534 s)
13535
13536 (defun org-wrap (string &optional width lines)
13537 "Wrap string to either a number of lines, or a width in characters.
13538 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13539 that costs. If there is a word longer than WIDTH, the text is actually
13540 wrapped to the length of that word.
13541 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13542 many lines, whatever width that takes.
13543 The return value is a list of lines, without newlines at the end."
13544 (let* ((words (org-split-string string "[ \t\n]+"))
13545 (maxword (apply 'max (mapcar 'org-string-width words)))
13546 w ll)
13547 (cond (width
13548 (org-do-wrap words (max maxword width)))
13549 (lines
13550 (setq w maxword)
13551 (setq ll (org-do-wrap words maxword))
13552 (if (<= (length ll) lines)
13553 ll
13554 (setq ll words)
13555 (while (> (length ll) lines)
13556 (setq w (1+ w))
13557 (setq ll (org-do-wrap words w)))
13558 ll))
13559 (t (error "Cannot wrap this")))))
13560
13561 (defun org-do-wrap (words width)
13562 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13563 (let (lines line)
13564 (while words
13565 (setq line (pop words))
13566 (while (and words (< (+ (length line) (length (car words))) width))
13567 (setq line (concat line " " (pop words))))
13568 (setq lines (push line lines)))
13569 (nreverse lines)))
13570
13571 (defun org-split-string (string &optional separators)
13572 "Splits STRING into substrings at SEPARATORS.
13573 No empty strings are returned if there are matches at the beginning
13574 and end of string."
13575 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13576 (start 0)
13577 notfirst
13578 (list nil))
13579 (while (and (string-match rexp string
13580 (if (and notfirst
13581 (= start (match-beginning 0))
13582 (< start (length string)))
13583 (1+ start) start))
13584 (< (match-beginning 0) (length string)))
13585 (setq notfirst t)
13586 (or (eq (match-beginning 0) 0)
13587 (and (eq (match-beginning 0) (match-end 0))
13588 (eq (match-beginning 0) start))
13589 (setq list
13590 (cons (substring string start (match-beginning 0))
13591 list)))
13592 (setq start (match-end 0)))
13593 (or (eq start (length string))
13594 (setq list
13595 (cons (substring string start)
13596 list)))
13597 (nreverse list)))
13598
13599 (defun org-context ()
13600 "Return a list of contexts of the current cursor position.
13601 If several contexts apply, all are returned.
13602 Each context entry is a list with a symbol naming the context, and
13603 two positions indicating start and end of the context. Possible
13604 contexts are:
13605
13606 :headline anywhere in a headline
13607 :headline-stars on the leading stars in a headline
13608 :todo-keyword on a TODO keyword (including DONE) in a headline
13609 :tags on the TAGS in a headline
13610 :priority on the priority cookie in a headline
13611 :item on the first line of a plain list item
13612 :item-bullet on the bullet/number of a plain list item
13613 :checkbox on the checkbox in a plain list item
13614 :table in an org-mode table
13615 :table-special on a special filed in a table
13616 :table-table in a table.el table
13617 :link on a hyperlink
13618 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13619 :target on a <<target>>
13620 :radio-target on a <<<radio-target>>>
13621 :latex-fragment on a LaTeX fragment
13622 :latex-preview on a LaTeX fragment with overlayed preview image
13623
13624 This function expects the position to be visible because it uses font-lock
13625 faces as a help to recognize the following contexts: :table-special, :link,
13626 and :keyword."
13627 (let* ((f (get-text-property (point) 'face))
13628 (faces (if (listp f) f (list f)))
13629 (p (point)) clist o)
13630 ;; First the large context
13631 (cond
13632 ((org-on-heading-p t)
13633 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13634 (when (progn
13635 (beginning-of-line 1)
13636 (looking-at org-todo-line-tags-regexp))
13637 (push (org-point-in-group p 1 :headline-stars) clist)
13638 (push (org-point-in-group p 2 :todo-keyword) clist)
13639 (push (org-point-in-group p 4 :tags) clist))
13640 (goto-char p)
13641 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13642 (if (looking-at "\\[#[A-Z0-9]\\]")
13643 (push (org-point-in-group p 0 :priority) clist)))
13644
13645 ((org-at-item-p)
13646 (push (org-point-in-group p 2 :item-bullet) clist)
13647 (push (list :item (point-at-bol)
13648 (save-excursion (org-end-of-item) (point)))
13649 clist)
13650 (and (org-at-item-checkbox-p)
13651 (push (org-point-in-group p 0 :checkbox) clist)))
13652
13653 ((org-at-table-p)
13654 (push (list :table (org-table-begin) (org-table-end)) clist)
13655 (if (memq 'org-formula faces)
13656 (push (list :table-special
13657 (previous-single-property-change p 'face)
13658 (next-single-property-change p 'face)) clist)))
13659 ((org-at-table-p 'any)
13660 (push (list :table-table) clist)))
13661 (goto-char p)
13662
13663 ;; Now the small context
13664 (cond
13665 ((org-at-timestamp-p)
13666 (push (org-point-in-group p 0 :timestamp) clist))
13667 ((memq 'org-link faces)
13668 (push (list :link
13669 (previous-single-property-change p 'face)
13670 (next-single-property-change p 'face)) clist))
13671 ((memq 'org-special-keyword faces)
13672 (push (list :keyword
13673 (previous-single-property-change p 'face)
13674 (next-single-property-change p 'face)) clist))
13675 ((org-on-target-p)
13676 (push (org-point-in-group p 0 :target) clist)
13677 (goto-char (1- (match-beginning 0)))
13678 (if (looking-at org-radio-target-regexp)
13679 (push (org-point-in-group p 0 :radio-target) clist))
13680 (goto-char p))
13681 ((setq o (car (delq nil
13682 (mapcar
13683 (lambda (x)
13684 (if (memq x org-latex-fragment-image-overlays) x))
13685 (org-overlays-at (point))))))
13686 (push (list :latex-fragment
13687 (org-overlay-start o) (org-overlay-end o)) clist)
13688 (push (list :latex-preview
13689 (org-overlay-start o) (org-overlay-end o)) clist))
13690 ((org-inside-LaTeX-fragment-p)
13691 ;; FIXME: positions wrong.
13692 (push (list :latex-fragment (point) (point)) clist)))
13693
13694 (setq clist (nreverse (delq nil clist)))
13695 clist))
13696
13697 ;; FIXME: Compare with at-regexp-p Do we need both?
13698 (defun org-in-regexp (re &optional nlines visually)
13699 "Check if point is inside a match of regexp.
13700 Normally only the current line is checked, but you can include NLINES extra
13701 lines both before and after point into the search.
13702 If VISUALLY is set, require that the cursor is not after the match but
13703 really on, so that the block visually is on the match."
13704 (catch 'exit
13705 (let ((pos (point))
13706 (eol (point-at-eol (+ 1 (or nlines 0))))
13707 (inc (if visually 1 0)))
13708 (save-excursion
13709 (beginning-of-line (- 1 (or nlines 0)))
13710 (while (re-search-forward re eol t)
13711 (if (and (<= (match-beginning 0) pos)
13712 (>= (+ inc (match-end 0)) pos))
13713 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13714
13715 (defun org-at-regexp-p (regexp)
13716 "Is point inside a match of REGEXP in the current line?"
13717 (catch 'exit
13718 (save-excursion
13719 (let ((pos (point)) (end (point-at-eol)))
13720 (beginning-of-line 1)
13721 (while (re-search-forward regexp end t)
13722 (if (and (<= (match-beginning 0) pos)
13723 (>= (match-end 0) pos))
13724 (throw 'exit t)))
13725 nil))))
13726
13727 (defun org-occur-in-agenda-files (regexp &optional nlines)
13728 "Call `multi-occur' with buffers for all agenda files."
13729 (interactive "sOrg-files matching: \np")
13730 (let* ((files (org-agenda-files))
13731 (tnames (mapcar 'file-truename files))
13732 (extra org-agenda-text-search-extra-files)
13733 f)
13734 (when (eq (car extra) 'agenda-archives)
13735 (setq extra (cdr extra))
13736 (setq files (org-add-archive-files files)))
13737 (while (setq f (pop extra))
13738 (unless (member (file-truename f) tnames)
13739 (add-to-list 'files f 'append)
13740 (add-to-list 'tnames (file-truename f) 'append)))
13741 (multi-occur
13742 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13743 regexp)))
13744
13745 (if (boundp 'occur-mode-find-occurrence-hook)
13746 ;; Emacs 23
13747 (add-hook 'occur-mode-find-occurrence-hook
13748 (lambda ()
13749 (when (org-mode-p)
13750 (org-reveal))))
13751 ;; Emacs 22
13752 (defadvice occur-mode-goto-occurrence
13753 (after org-occur-reveal activate)
13754 (and (org-mode-p) (org-reveal)))
13755 (defadvice occur-mode-goto-occurrence-other-window
13756 (after org-occur-reveal activate)
13757 (and (org-mode-p) (org-reveal)))
13758 (defadvice occur-mode-display-occurrence
13759 (after org-occur-reveal activate)
13760 (when (org-mode-p)
13761 (let ((pos (occur-mode-find-occurrence)))
13762 (with-current-buffer (marker-buffer pos)
13763 (save-excursion
13764 (goto-char pos)
13765 (org-reveal)))))))
13766
13767 (defun org-uniquify (list)
13768 "Remove duplicate elements from LIST."
13769 (let (res)
13770 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13771 res))
13772
13773 (defun org-delete-all (elts list)
13774 "Remove all elements in ELTS from LIST."
13775 (while elts
13776 (setq list (delete (pop elts) list)))
13777 list)
13778
13779 (defun org-back-over-empty-lines ()
13780 "Move backwards over witespace, to the beginning of the first empty line.
13781 Returns the number of empty lines passed."
13782 (let ((pos (point)))
13783 (skip-chars-backward " \t\n\r")
13784 (beginning-of-line 2)
13785 (goto-char (min (point) pos))
13786 (count-lines (point) pos)))
13787
13788 (defun org-skip-whitespace ()
13789 (skip-chars-forward " \t\n\r"))
13790
13791 (defun org-point-in-group (point group &optional context)
13792 "Check if POINT is in match-group GROUP.
13793 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13794 match. If the match group does ot exist or point is not inside it,
13795 return nil."
13796 (and (match-beginning group)
13797 (>= point (match-beginning group))
13798 (<= point (match-end group))
13799 (if context
13800 (list context (match-beginning group) (match-end group))
13801 t)))
13802
13803 (defun org-switch-to-buffer-other-window (&rest args)
13804 "Switch to buffer in a second window on the current frame.
13805 In particular, do not allow pop-up frames."
13806 (let (pop-up-frames special-display-buffer-names special-display-regexps
13807 special-display-function)
13808 (apply 'switch-to-buffer-other-window args)))
13809
13810 (defun org-combine-plists (&rest plists)
13811 "Create a single property list from all plists in PLISTS.
13812 The process starts by copying the first list, and then setting properties
13813 from the other lists. Settings in the last list are the most significant
13814 ones and overrule settings in the other lists."
13815 (let ((rtn (copy-sequence (pop plists)))
13816 p v ls)
13817 (while plists
13818 (setq ls (pop plists))
13819 (while ls
13820 (setq p (pop ls) v (pop ls))
13821 (setq rtn (plist-put rtn p v))))
13822 rtn))
13823
13824 (defun org-move-line-down (arg)
13825 "Move the current line down. With prefix argument, move it past ARG lines."
13826 (interactive "p")
13827 (let ((col (current-column))
13828 beg end pos)
13829 (beginning-of-line 1) (setq beg (point))
13830 (beginning-of-line 2) (setq end (point))
13831 (beginning-of-line (+ 1 arg))
13832 (setq pos (move-marker (make-marker) (point)))
13833 (insert (delete-and-extract-region beg end))
13834 (goto-char pos)
13835 (org-move-to-column col)))
13836
13837 (defun org-move-line-up (arg)
13838 "Move the current line up. With prefix argument, move it past ARG lines."
13839 (interactive "p")
13840 (let ((col (current-column))
13841 beg end pos)
13842 (beginning-of-line 1) (setq beg (point))
13843 (beginning-of-line 2) (setq end (point))
13844 (beginning-of-line (- arg))
13845 (setq pos (move-marker (make-marker) (point)))
13846 (insert (delete-and-extract-region beg end))
13847 (goto-char pos)
13848 (org-move-to-column col)))
13849
13850 (defun org-replace-escapes (string table)
13851 "Replace %-escapes in STRING with values in TABLE.
13852 TABLE is an association list with keys like \"%a\" and string values.
13853 The sequences in STRING may contain normal field width and padding information,
13854 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13855 so values can contain further %-escapes if they are define later in TABLE."
13856 (let ((case-fold-search nil)
13857 e re rpl)
13858 (while (setq e (pop table))
13859 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13860 (while (string-match re string)
13861 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13862 (cdr e)))
13863 (setq string (replace-match rpl t t string))))
13864 string))
13865
13866
13867 (defun org-sublist (list start end)
13868 "Return a section of LIST, from START to END.
13869 Counting starts at 1."
13870 (let (rtn (c start))
13871 (setq list (nthcdr (1- start) list))
13872 (while (and list (<= c end))
13873 (push (pop list) rtn)
13874 (setq c (1+ c)))
13875 (nreverse rtn)))
13876
13877 (defun org-find-base-buffer-visiting (file)
13878 "Like `find-buffer-visiting' but alway return the base buffer and
13879 not an indirect buffer."
13880 (let ((buf (find-buffer-visiting file)))
13881 (if buf
13882 (or (buffer-base-buffer buf) buf)
13883 nil)))
13884
13885 (defun org-image-file-name-regexp ()
13886 "Return regexp matching the file names of images."
13887 (if (fboundp 'image-file-name-regexp)
13888 (image-file-name-regexp)
13889 (let ((image-file-name-extensions
13890 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13891 "xbm" "xpm" "pbm" "pgm" "ppm")))
13892 (concat "\\."
13893 (regexp-opt (nconc (mapcar 'upcase
13894 image-file-name-extensions)
13895 image-file-name-extensions)
13896 t)
13897 "\\'"))))
13898
13899 (defun org-file-image-p (file)
13900 "Return non-nil if FILE is an image."
13901 (save-match-data
13902 (string-match (org-image-file-name-regexp) file)))
13903
13904 (defun org-get-cursor-date ()
13905 "Return the date at cursor in as a time.
13906 This works in the calendar and in the agenda, anywhere else it just
13907 returns the current time."
13908 (let (date day defd)
13909 (cond
13910 ((eq major-mode 'calendar-mode)
13911 (setq date (calendar-cursor-to-date)
13912 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13913 ((eq major-mode 'org-agenda-mode)
13914 (setq day (get-text-property (point) 'day))
13915 (if day
13916 (setq date (calendar-gregorian-from-absolute day)
13917 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13918 (nth 2 date))))))
13919 (or defd (current-time))))
13920
13921 (defvar org-agenda-action-marker (make-marker)
13922 "Marker pointing to the entry for the next agenda action.")
13923
13924 (defun org-mark-entry-for-agenda-action ()
13925 "Mark the current entry as target of an agenda action.
13926 Agenda actions are actions executed from the agenda with the key `k',
13927 which make use of the date at the cursor."
13928 (interactive)
13929 (move-marker org-agenda-action-marker
13930 (save-excursion (org-back-to-heading t) (point))
13931 (current-buffer))
13932 (message
13933 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13934
13935 ;;; Paragraph filling stuff.
13936 ;; We want this to be just right, so use the full arsenal.
13937
13938 (defun org-indent-line-function ()
13939 "Indent line like previous, but further if previous was headline or item."
13940 (interactive)
13941 (let* ((pos (point))
13942 (itemp (org-at-item-p))
13943 column bpos bcol tpos tcol bullet btype bullet-type)
13944 ;; Find the previous relevant line
13945 (beginning-of-line 1)
13946 (cond
13947 ((looking-at "#") (setq column 0))
13948 ((looking-at "\\*+ ") (setq column 0))
13949 (t
13950 (beginning-of-line 0)
13951 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13952 (beginning-of-line 0))
13953 (cond
13954 ((looking-at "\\*+[ \t]+")
13955 (if (not org-adapt-indentation)
13956 (setq column 0)
13957 (goto-char (match-end 0))
13958 (setq column (current-column))))
13959 ((org-in-item-p)
13960 (org-beginning-of-item)
13961 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13962 (setq bpos (match-beginning 1) tpos (match-end 0)
13963 bcol (progn (goto-char bpos) (current-column))
13964 tcol (progn (goto-char tpos) (current-column))
13965 bullet (match-string 1)
13966 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13967 (if (> tcol (+ bcol org-description-max-indent))
13968 (setq tcol (+ bcol 5)))
13969 (if (not itemp)
13970 (setq column tcol)
13971 (goto-char pos)
13972 (beginning-of-line 1)
13973 (if (looking-at "\\S-")
13974 (progn
13975 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13976 (setq bullet (match-string 1)
13977 btype (if (string-match "[0-9]" bullet) "n" bullet))
13978 (setq column (if (equal btype bullet-type) bcol tcol)))
13979 (setq column (org-get-indentation)))))
13980 (t (setq column (org-get-indentation))))))
13981 (goto-char pos)
13982 (if (<= (current-column) (current-indentation))
13983 (org-indent-line-to column)
13984 (save-excursion (org-indent-line-to column)))
13985 (setq column (current-column))
13986 (beginning-of-line 1)
13987 (if (looking-at
13988 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13989 (replace-match (concat "\\1" (format org-property-format
13990 (match-string 2) (match-string 3)))
13991 t nil))
13992 (org-move-to-column column)))
13993
13994 (defun org-set-autofill-regexps ()
13995 (interactive)
13996 ;; In the paragraph separator we include headlines, because filling
13997 ;; text in a line directly attached to a headline would otherwise
13998 ;; fill the headline as well.
13999 (org-set-local 'comment-start-skip "^#+[ \t]*")
14000 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14001 ;; The paragraph starter includes hand-formatted lists.
14002 (org-set-local 'paragraph-start
14003 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14004 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14005 ;; But only if the user has not turned off tables or fixed-width regions
14006 (org-set-local
14007 'auto-fill-inhibit-regexp
14008 (concat "\\*+ \\|#\\+"
14009 "\\|[ \t]*" org-keyword-time-regexp
14010 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14011 (concat
14012 "\\|[ \t]*["
14013 (if org-enable-table-editor "|" "")
14014 (if org-enable-fixed-width-editor ":" "")
14015 "]"))))
14016 ;; We use our own fill-paragraph function, to make sure that tables
14017 ;; and fixed-width regions are not wrapped. That function will pass
14018 ;; through to `fill-paragraph' when appropriate.
14019 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14020 ; Adaptive filling: To get full control, first make sure that
14021 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14022 (org-set-local 'adaptive-fill-regexp "\000")
14023 (org-set-local 'adaptive-fill-function
14024 'org-adaptive-fill-function)
14025 (org-set-local
14026 'align-mode-rules-list
14027 '((org-in-buffer-settings
14028 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14029 (modes . '(org-mode))))))
14030
14031 (defun org-fill-paragraph (&optional justify)
14032 "Re-align a table, pass through to fill-paragraph if no table."
14033 (let ((table-p (org-at-table-p))
14034 (table.el-p (org-at-table.el-p)))
14035 (cond ((and (equal (char-after (point-at-bol)) ?*)
14036 (save-excursion (goto-char (point-at-bol))
14037 (looking-at outline-regexp)))
14038 t) ; skip headlines
14039 (table.el-p t) ; skip table.el tables
14040 (table-p (org-table-align) t) ; align org-mode tables
14041 (t nil)))) ; call paragraph-fill
14042
14043 ;; For reference, this is the default value of adaptive-fill-regexp
14044 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14045
14046 (defun org-adaptive-fill-function ()
14047 "Return a fill prefix for org-mode files.
14048 In particular, this makes sure hanging paragraphs for hand-formatted lists
14049 work correctly."
14050 (cond ((looking-at "#[ \t]+")
14051 (match-string 0))
14052 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14053 (save-excursion
14054 (if (> (match-end 1) (+ (match-beginning 1)
14055 org-description-max-indent))
14056 (goto-char (+ (match-beginning 1) 5))
14057 (goto-char (match-end 0)))
14058 (make-string (current-column) ?\ )))
14059 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14060 (save-excursion
14061 (goto-char (match-end 0))
14062 (make-string (current-column) ?\ )))
14063 (t nil)))
14064
14065 ;;; Other stuff.
14066
14067 (defun org-toggle-fixed-width-section (arg)
14068 "Toggle the fixed-width export.
14069 If there is no active region, the QUOTE keyword at the current headline is
14070 inserted or removed. When present, it causes the text between this headline
14071 and the next to be exported as fixed-width text, and unmodified.
14072 If there is an active region, this command adds or removes a colon as the
14073 first character of this line. If the first character of a line is a colon,
14074 this line is also exported in fixed-width font."
14075 (interactive "P")
14076 (let* ((cc 0)
14077 (regionp (org-region-active-p))
14078 (beg (if regionp (region-beginning) (point)))
14079 (end (if regionp (region-end)))
14080 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14081 (case-fold-search nil)
14082 (re "[ \t]*\\(:\\)")
14083 off)
14084 (if regionp
14085 (save-excursion
14086 (goto-char beg)
14087 (setq cc (current-column))
14088 (beginning-of-line 1)
14089 (setq off (looking-at re))
14090 (while (> nlines 0)
14091 (setq nlines (1- nlines))
14092 (beginning-of-line 1)
14093 (cond
14094 (arg
14095 (org-move-to-column cc t)
14096 (insert ":\n")
14097 (forward-line -1))
14098 ((and off (looking-at re))
14099 (replace-match "" t t nil 1))
14100 ((not off) (org-move-to-column cc t) (insert ":")))
14101 (forward-line 1)))
14102 (save-excursion
14103 (org-back-to-heading)
14104 (if (looking-at (concat outline-regexp
14105 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14106 (replace-match "" t t nil 1)
14107 (if (looking-at outline-regexp)
14108 (progn
14109 (goto-char (match-end 0))
14110 (insert org-quote-string " "))))))))
14111
14112 ;;;; Functions extending outline functionality
14113
14114 (defun org-beginning-of-line (&optional arg)
14115 "Go to the beginning of the current line. If that is invisible, continue
14116 to a visible line beginning. This makes the function of C-a more intuitive.
14117 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14118 first attempt, and only move to after the tags when the cursor is already
14119 beyond the end of the headline."
14120 (interactive "P")
14121 (let ((pos (point)) refpos)
14122 (beginning-of-line 1)
14123 (if (bobp)
14124 nil
14125 (backward-char 1)
14126 (if (org-invisible-p)
14127 (while (and (not (bobp)) (org-invisible-p))
14128 (backward-char 1)
14129 (beginning-of-line 1))
14130 (forward-char 1)))
14131 (when org-special-ctrl-a/e
14132 (cond
14133 ((and (looking-at org-complex-heading-regexp)
14134 (= (char-after (match-end 1)) ?\ ))
14135 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14136 (point-at-eol)))
14137 (goto-char
14138 (if (eq org-special-ctrl-a/e t)
14139 (cond ((> pos refpos) refpos)
14140 ((= pos (point)) refpos)
14141 (t (point)))
14142 (cond ((> pos (point)) (point))
14143 ((not (eq last-command this-command)) (point))
14144 (t refpos)))))
14145 ((org-at-item-p)
14146 (goto-char
14147 (if (eq org-special-ctrl-a/e t)
14148 (cond ((> pos (match-end 4)) (match-end 4))
14149 ((= pos (point)) (match-end 4))
14150 (t (point)))
14151 (cond ((> pos (point)) (point))
14152 ((not (eq last-command this-command)) (point))
14153 (t (match-end 4))))))))
14154 (org-no-warnings
14155 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14156
14157 (defun org-end-of-line (&optional arg)
14158 "Go to the end of the line.
14159 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14160 first attempt, and only move to after the tags when the cursor is already
14161 beyond the end of the headline."
14162 (interactive "P")
14163 (if (or (not org-special-ctrl-a/e)
14164 (not (org-on-heading-p)))
14165 (end-of-line arg)
14166 (let ((pos (point)))
14167 (beginning-of-line 1)
14168 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14169 (if (eq org-special-ctrl-a/e t)
14170 (if (or (< pos (match-beginning 1))
14171 (= pos (match-end 0)))
14172 (goto-char (match-beginning 1))
14173 (goto-char (match-end 0)))
14174 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14175 (goto-char (match-end 0))
14176 (goto-char (match-beginning 1))))
14177 (end-of-line arg))))
14178 (org-no-warnings
14179 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14180
14181
14182 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14183 (define-key org-mode-map "\C-e" 'org-end-of-line)
14184
14185 (defun org-kill-line (&optional arg)
14186 "Kill line, to tags or end of line."
14187 (interactive "P")
14188 (cond
14189 ((or (not org-special-ctrl-k)
14190 (bolp)
14191 (not (org-on-heading-p)))
14192 (call-interactively 'kill-line))
14193 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14194 (kill-region (point) (match-beginning 1))
14195 (org-set-tags nil t))
14196 (t (kill-region (point) (point-at-eol)))))
14197
14198 (define-key org-mode-map "\C-k" 'org-kill-line)
14199
14200 (defun org-yank (&optional arg)
14201 "Yank. If the kill is a subtree, treat it specially.
14202 This command will look at the current kill and check if is a single
14203 subtree, or a series of subtrees[1]. If it passes the test, and if the
14204 cursor is at the beginning of a line or after the stars of a currently
14205 empty headline, then the yank is handeled specially. How exactly depends
14206 on the value of the following variables, both set by default.
14207
14208 org-yank-folded-subtrees
14209 When set, the subree(s) will be folded after insertion, but only
14210 if doing so would now swallow text after the yanked text.
14211
14212 org-yank-adjusted-subtrees
14213 When set, the subtree will be promoted or demoted in order to
14214 fit into the local outline tree structure, which means that the level
14215 will be adjusted so that it becomes the smaller one of the two
14216 *visible* surrounding headings.
14217
14218 Any prefix to this command will cause `yank' to be called directly with
14219 no special treatment. In particular, a simple `C-u' prefix will just
14220 plainly yank the text as it is.
14221
14222 \[1] Basically, the test checks if the first non-white line is a heading
14223 and if there are no other headings with fewer stars."
14224 (interactive "P")
14225 (setq this-command 'yank)
14226 (if arg
14227 (call-interactively 'yank)
14228 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14229 (and (org-kill-is-subtree-p)
14230 (or (bolp)
14231 (and (looking-at "[ \t]*$")
14232 (string-match
14233 "\\`\\*+\\'"
14234 (buffer-substring (point-at-bol) (point)))))))
14235 swallowp)
14236 (cond
14237 ((and subtreep org-yank-folded-subtrees)
14238 (let ((beg (point))
14239 end)
14240 (if (and subtreep org-yank-adjusted-subtrees)
14241 (org-paste-subtree nil nil 'for-yank)
14242 (call-interactively 'yank))
14243 (setq end (point))
14244 (goto-char beg)
14245 (when (and (bolp) subtreep
14246 (not (setq swallowp
14247 (org-yank-folding-would-swallow-text beg end))))
14248 (or (looking-at outline-regexp)
14249 (re-search-forward (concat "^" outline-regexp) end t))
14250 (while (and (< (point) end) (looking-at outline-regexp))
14251 (hide-subtree)
14252 (org-cycle-show-empty-lines 'folded)
14253 (condition-case nil
14254 (outline-forward-same-level 1)
14255 (error (goto-char end)))))
14256 (when swallowp
14257 (message
14258 "Yanked text not folded because that would swallow text"))
14259 (goto-char end)
14260 (skip-chars-forward " \t\n\r")
14261 (beginning-of-line 1)
14262 (push-mark beg 'nomsg)))
14263 ((and subtreep org-yank-adjusted-subtrees)
14264 (let ((beg (point-at-bol)))
14265 (org-paste-subtree nil nil 'for-yank)
14266 (push-mark beg 'nomsg)))
14267 (t
14268 (call-interactively 'yank))))))
14269
14270 (defun org-yank-folding-would-swallow-text (beg end)
14271 "Would hide-subtree at BEG swallow any text after END?"
14272 (let (level)
14273 (save-excursion
14274 (goto-char beg)
14275 (when (or (looking-at outline-regexp)
14276 (re-search-forward (concat "^" outline-regexp) end t))
14277 (setq level (org-outline-level)))
14278 (goto-char end)
14279 (skip-chars-forward " \t\r\n\v\f")
14280 (if (or (eobp)
14281 (and (bolp) (looking-at org-outline-regexp)
14282 (<= (org-outline-level) level)))
14283 nil ; Nothing would be swallowed
14284 t)))) ; something would swallow
14285
14286 (define-key org-mode-map "\C-y" 'org-yank)
14287
14288 (defun org-invisible-p ()
14289 "Check if point is at a character currently not visible."
14290 ;; Early versions of noutline don't have `outline-invisible-p'.
14291 (if (fboundp 'outline-invisible-p)
14292 (outline-invisible-p)
14293 (get-char-property (point) 'invisible)))
14294
14295 (defun org-invisible-p2 ()
14296 "Check if point is at a character currently not visible."
14297 (save-excursion
14298 (if (and (eolp) (not (bobp))) (backward-char 1))
14299 ;; Early versions of noutline don't have `outline-invisible-p'.
14300 (if (fboundp 'outline-invisible-p)
14301 (outline-invisible-p)
14302 (get-char-property (point) 'invisible))))
14303
14304 (defun org-back-to-heading (&optional invisible-ok)
14305 "Call `outline-back-to-heading', but provide a better error message."
14306 (condition-case nil
14307 (outline-back-to-heading invisible-ok)
14308 (error (error "Before first headline at position %d in buffer %s"
14309 (point) (current-buffer)))))
14310
14311 (defalias 'org-on-heading-p 'outline-on-heading-p)
14312 (defalias 'org-at-heading-p 'outline-on-heading-p)
14313 (defun org-at-heading-or-item-p ()
14314 (or (org-on-heading-p) (org-at-item-p)))
14315
14316 (defun org-on-target-p ()
14317 (or (org-in-regexp org-radio-target-regexp)
14318 (org-in-regexp org-target-regexp)))
14319
14320 (defun org-up-heading-all (arg)
14321 "Move to the heading line of which the present line is a subheading.
14322 This function considers both visible and invisible heading lines.
14323 With argument, move up ARG levels."
14324 (if (fboundp 'outline-up-heading-all)
14325 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14326 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14327
14328 (defun org-up-heading-safe ()
14329 "Move to the heading line of which the present line is a subheading.
14330 This version will not throw an error. It will return the level of the
14331 headline found, or nil if no higher level is found."
14332 (let ((pos (point)) start-level level
14333 (re (concat "^" outline-regexp)))
14334 (catch 'exit
14335 (org-back-to-heading t)
14336 (setq start-level (funcall outline-level))
14337 (if (equal start-level 1) (throw 'exit nil))
14338 (while (re-search-backward re nil t)
14339 (setq level (funcall outline-level))
14340 (if (< level start-level) (throw 'exit level)))
14341 nil)))
14342
14343 (defun org-first-sibling-p ()
14344 "Is this heading the first child of its parents?"
14345 (interactive)
14346 (let ((re (concat "^" outline-regexp))
14347 level l)
14348 (unless (org-at-heading-p t)
14349 (error "Not at a heading"))
14350 (setq level (funcall outline-level))
14351 (save-excursion
14352 (if (not (re-search-backward re nil t))
14353 t
14354 (setq l (funcall outline-level))
14355 (< l level)))))
14356
14357 (defun org-goto-sibling (&optional previous)
14358 "Goto the next sibling, even if it is invisible.
14359 When PREVIOUS is set, go to the previous sibling instead. Returns t
14360 when a sibling was found. When none is found, return nil and don't
14361 move point."
14362 (let ((fun (if previous 're-search-backward 're-search-forward))
14363 (pos (point))
14364 (re (concat "^" outline-regexp))
14365 level l)
14366 (when (condition-case nil (org-back-to-heading t) (error nil))
14367 (setq level (funcall outline-level))
14368 (catch 'exit
14369 (or previous (forward-char 1))
14370 (while (funcall fun re nil t)
14371 (setq l (funcall outline-level))
14372 (when (< l level) (goto-char pos) (throw 'exit nil))
14373 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14374 (goto-char pos)
14375 nil))))
14376
14377 (defun org-show-siblings ()
14378 "Show all siblings of the current headline."
14379 (save-excursion
14380 (while (org-goto-sibling) (org-flag-heading nil)))
14381 (save-excursion
14382 (while (org-goto-sibling 'previous)
14383 (org-flag-heading nil))))
14384
14385 (defun org-show-hidden-entry ()
14386 "Show an entry where even the heading is hidden."
14387 (save-excursion
14388 (org-show-entry)))
14389
14390 (defun org-flag-heading (flag &optional entry)
14391 "Flag the current heading. FLAG non-nil means make invisible.
14392 When ENTRY is non-nil, show the entire entry."
14393 (save-excursion
14394 (org-back-to-heading t)
14395 ;; Check if we should show the entire entry
14396 (if entry
14397 (progn
14398 (org-show-entry)
14399 (save-excursion
14400 (and (outline-next-heading)
14401 (org-flag-heading nil))))
14402 (outline-flag-region (max (point-min) (1- (point)))
14403 (save-excursion (outline-end-of-heading) (point))
14404 flag))))
14405
14406 (defun org-forward-same-level (arg)
14407 "Move forward to the ARG'th subheading at same level as this one.
14408 Stop at the first and last subheadings of a superior heading.
14409 This is like outline-forward-same-level, but invisible headings are ok."
14410 (interactive "p")
14411 (org-back-to-heading t)
14412 (while (> arg 0)
14413 (let ((point-to-move-to (save-excursion
14414 (org-get-next-sibling))))
14415 (if point-to-move-to
14416 (progn
14417 (goto-char point-to-move-to)
14418 (setq arg (1- arg)))
14419 (progn
14420 (setq arg 0)
14421 (error "No following same-level heading"))))))
14422
14423 (defun org-get-next-sibling ()
14424 "Move to next heading of the same level, and return point.
14425 If there is no such heading, return nil.
14426 This is like outline-next-sibling, but invisible headings are ok."
14427 (let ((level (funcall outline-level)))
14428 (outline-next-heading)
14429 (while (and (not (eobp)) (> (funcall outline-level) level))
14430 (outline-next-heading))
14431 (if (or (eobp) (< (funcall outline-level) level))
14432 nil
14433 (point))))
14434
14435 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14436 ;; This is an exact copy of the original function, but it uses
14437 ;; `org-back-to-heading', to make it work also in invisible
14438 ;; trees. And is uses an invisible-OK argument.
14439 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14440 (org-back-to-heading invisible-OK)
14441 (let ((first t)
14442 (level (funcall outline-level)))
14443 (while (and (not (eobp))
14444 (or first (> (funcall outline-level) level)))
14445 (setq first nil)
14446 (outline-next-heading))
14447 (unless to-heading
14448 (if (memq (preceding-char) '(?\n ?\^M))
14449 (progn
14450 ;; Go to end of line before heading
14451 (forward-char -1)
14452 (if (memq (preceding-char) '(?\n ?\^M))
14453 ;; leave blank line before heading
14454 (forward-char -1))))))
14455 (point))
14456
14457 (defun org-show-subtree ()
14458 "Show everything after this heading at deeper levels."
14459 (outline-flag-region
14460 (point)
14461 (save-excursion
14462 (outline-end-of-subtree) (outline-next-heading) (point))
14463 nil))
14464
14465 (defun org-show-entry ()
14466 "Show the body directly following this heading.
14467 Show the heading too, if it is currently invisible."
14468 (interactive)
14469 (save-excursion
14470 (condition-case nil
14471 (progn
14472 (org-back-to-heading t)
14473 (outline-flag-region
14474 (max (point-min) (1- (point)))
14475 (save-excursion
14476 (re-search-forward
14477 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14478 (or (match-beginning 1) (point-max)))
14479 nil))
14480 (error nil))))
14481
14482 (defun org-make-options-regexp (kwds)
14483 "Make a regular expression for keyword lines."
14484 (concat
14485 "^"
14486 "#?[ \t]*\\+\\("
14487 (mapconcat 'regexp-quote kwds "\\|")
14488 "\\):[ \t]*"
14489 "\\(.+\\)"))
14490
14491 ;; Make isearch reveal the necessary context
14492 (defun org-isearch-end ()
14493 "Reveal context after isearch exits."
14494 (when isearch-success ; only if search was successful
14495 (if (featurep 'xemacs)
14496 ;; Under XEmacs, the hook is run in the correct place,
14497 ;; we directly show the context.
14498 (org-show-context 'isearch)
14499 ;; In Emacs the hook runs *before* restoring the overlays.
14500 ;; So we have to use a one-time post-command-hook to do this.
14501 ;; (Emacs 22 has a special variable, see function `org-mode')
14502 (unless (and (boundp 'isearch-mode-end-hook-quit)
14503 isearch-mode-end-hook-quit)
14504 ;; Only when the isearch was not quitted.
14505 (org-add-hook 'post-command-hook 'org-isearch-post-command
14506 'append 'local)))))
14507
14508 (defun org-isearch-post-command ()
14509 "Remove self from hook, and show context."
14510 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14511 (org-show-context 'isearch))
14512
14513
14514 ;;;; Integration with and fixes for other packages
14515
14516 ;;; Imenu support
14517
14518 (defvar org-imenu-markers nil
14519 "All markers currently used by Imenu.")
14520 (make-variable-buffer-local 'org-imenu-markers)
14521
14522 (defun org-imenu-new-marker (&optional pos)
14523 "Return a new marker for use by Imenu, and remember the marker."
14524 (let ((m (make-marker)))
14525 (move-marker m (or pos (point)))
14526 (push m org-imenu-markers)
14527 m))
14528
14529 (defun org-imenu-get-tree ()
14530 "Produce the index for Imenu."
14531 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14532 (setq org-imenu-markers nil)
14533 (let* ((n org-imenu-depth)
14534 (re (concat "^" outline-regexp))
14535 (subs (make-vector (1+ n) nil))
14536 (last-level 0)
14537 m tree level head)
14538 (save-excursion
14539 (save-restriction
14540 (widen)
14541 (goto-char (point-max))
14542 (while (re-search-backward re nil t)
14543 (setq level (org-reduced-level (funcall outline-level)))
14544 (when (<= level n)
14545 (looking-at org-complex-heading-regexp)
14546 (setq head (org-link-display-format
14547 (org-match-string-no-properties 4))
14548 m (org-imenu-new-marker))
14549 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14550 (if (>= level last-level)
14551 (push (cons head m) (aref subs level))
14552 (push (cons head (aref subs (1+ level))) (aref subs level))
14553 (loop for i from (1+ level) to n do (aset subs i nil)))
14554 (setq last-level level)))))
14555 (aref subs 1)))
14556
14557 (eval-after-load "imenu"
14558 '(progn
14559 (add-hook 'imenu-after-jump-hook
14560 (lambda ()
14561 (if (eq major-mode 'org-mode)
14562 (org-show-context 'org-goto))))))
14563
14564 (defun org-link-display-format (link)
14565 "Replace a link with either the description, or the link target
14566 if no description is present"
14567 (save-match-data
14568 (if (string-match org-bracket-link-analytic-regexp link)
14569 (replace-match (or (match-string 5 link)
14570 (concat (match-string 1 link)
14571 (match-string 3 link)))
14572 nil nil link)
14573 link)))
14574
14575 ;; Speedbar support
14576
14577 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14578 "Overlay marking the agenda restriction line in speedbar.")
14579 (org-overlay-put org-speedbar-restriction-lock-overlay
14580 'face 'org-agenda-restriction-lock)
14581 (org-overlay-put org-speedbar-restriction-lock-overlay
14582 'help-echo "Agendas are currently limited to this item.")
14583 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14584
14585 (defun org-speedbar-set-agenda-restriction ()
14586 "Restrict future agenda commands to the location at point in speedbar.
14587 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14588 (interactive)
14589 (require 'org-agenda)
14590 (let (p m tp np dir txt w)
14591 (cond
14592 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14593 'org-imenu t))
14594 (setq m (get-text-property p 'org-imenu-marker))
14595 (save-excursion
14596 (save-restriction
14597 (set-buffer (marker-buffer m))
14598 (goto-char m)
14599 (org-agenda-set-restriction-lock 'subtree))))
14600 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14601 'speedbar-function 'speedbar-find-file))
14602 (setq tp (previous-single-property-change
14603 (1+ p) 'speedbar-function)
14604 np (next-single-property-change
14605 tp 'speedbar-function)
14606 dir (speedbar-line-directory)
14607 txt (buffer-substring-no-properties (or tp (point-min))
14608 (or np (point-max))))
14609 (save-excursion
14610 (save-restriction
14611 (set-buffer (find-file-noselect
14612 (let ((default-directory dir))
14613 (expand-file-name txt))))
14614 (unless (org-mode-p)
14615 (error "Cannot restrict to non-Org-mode file"))
14616 (org-agenda-set-restriction-lock 'file))))
14617 (t (error "Don't know how to restrict Org-mode's agenda")))
14618 (org-move-overlay org-speedbar-restriction-lock-overlay
14619 (point-at-bol) (point-at-eol))
14620 (setq current-prefix-arg nil)
14621 (org-agenda-maybe-redo)))
14622
14623 (eval-after-load "speedbar"
14624 '(progn
14625 (speedbar-add-supported-extension ".org")
14626 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14627 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14628 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14629 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14630 (add-hook 'speedbar-visiting-tag-hook
14631 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
14632
14633
14634 ;;; Fixes and Hacks for problems with other packages
14635
14636 ;; Make flyspell not check words in links, to not mess up our keymap
14637 (defun org-mode-flyspell-verify ()
14638 "Don't let flyspell put overlays at active buttons."
14639 (not (get-text-property (point) 'keymap)))
14640
14641 ;; Make `bookmark-jump' show the jump location if it was hidden.
14642 (eval-after-load "bookmark"
14643 '(if (boundp 'bookmark-after-jump-hook)
14644 ;; We can use the hook
14645 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14646 ;; Hook not available, use advice
14647 (defadvice bookmark-jump (after org-make-visible activate)
14648 "Make the position visible."
14649 (org-bookmark-jump-unhide))))
14650
14651 ;; Make sure saveplace show the location if it was hidden
14652 (eval-after-load "saveplace"
14653 '(defadvice save-place-find-file-hook (after org-make-visible activate)
14654 "Make the position visible."
14655 (org-bookmark-jump-unhide)))
14656
14657 (defun org-bookmark-jump-unhide ()
14658 "Unhide the current position, to show the bookmark location."
14659 (and (org-mode-p)
14660 (or (org-invisible-p)
14661 (save-excursion (goto-char (max (point-min) (1- (point))))
14662 (org-invisible-p)))
14663 (org-show-context 'bookmark-jump)))
14664
14665 ;; Make session.el ignore our circular variable
14666 (eval-after-load "session"
14667 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14668
14669 ;;;; Experimental code
14670
14671 (defun org-closed-in-range ()
14672 "Sparse tree of items closed in a certain time range.
14673 Still experimental, may disappear in the future."
14674 (interactive)
14675 ;; Get the time interval from the user.
14676 (let* ((time1 (time-to-seconds
14677 (org-read-date nil 'to-time nil "Starting date: ")))
14678 (time2 (time-to-seconds
14679 (org-read-date nil 'to-time nil "End date:")))
14680 ;; callback function
14681 (callback (lambda ()
14682 (let ((time
14683 (time-to-seconds
14684 (apply 'encode-time
14685 (org-parse-time-string
14686 (match-string 1))))))
14687 ;; check if time in interval
14688 (and (>= time time1) (<= time time2))))))
14689 ;; make tree, check each match with the callback
14690 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14691
14692
14693 ;;;; Finish up
14694
14695 (provide 'org)
14696
14697 (run-hooks 'org-load-hook)
14698
14699 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14700
14701 ;;; org.el ends here