Fix stack overflow in string creation (Bug#6214).
[bpt/emacs.git] / lisp / org / org.el
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.35i
10 ;;
11 ;; This file is part of GNU Emacs.
12 ;;
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;
27 ;;; Commentary:
28 ;;
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
31 ;;
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
46 ;;
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
50 ;;
51 ;; http://orgmode.org/org.html#Installation
52 ;;
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
60 ;;
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
63 ;;
64 ;;; Code:
65
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
70
71 ;;;; Require other packages
72
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
86
87 (require 'org-macs)
88 (require 'org-entities)
89 (require 'org-compat)
90 (require 'org-faces)
91 (require 'org-list)
92 (require 'org-src)
93 (require 'org-footnote)
94
95 ;;;; Customization variables
96
97 ;;; Version
98
99 (defconst org-version "6.35i"
100 "The version number of the file org.el.")
101
102 (defun org-version (&optional here)
103 "Show the org-mode version in the echo area.
104 With prefix arg HERE, insert it at point."
105 (interactive "P")
106 (let* ((origin default-directory)
107 (version org-version)
108 (git-version)
109 (dir (concat (file-name-directory (locate-library "org")) "../" )))
110 (when (and (file-exists-p (expand-file-name ".git" dir))
111 (executable-find "git"))
112 (unwind-protect
113 (progn
114 (cd dir)
115 (when (eql 0 (shell-command "git describe --abbrev=4 HEAD"))
116 (with-current-buffer "*Shell Command Output*"
117 (goto-char (point-min))
118 (setq git-version (buffer-substring (point) (point-at-eol))))
119 (subst-char-in-string ?- ?. git-version t)
120 (when (string-match "\\S-"
121 (shell-command-to-string
122 "git diff-index --name-only HEAD --"))
123 (setq git-version (concat git-version ".dirty")))
124 (setq version (concat version " (" git-version ")"))))
125 (cd origin)))
126 (setq version (format "Org-mode version %s" version))
127 (if here (insert version))
128 (message version)))
129
130 ;;; Compatibility constants
131
132 ;;; The custom variables
133
134 (defgroup org nil
135 "Outline-based notes management and organizer."
136 :tag "Org"
137 :group 'outlines
138 :group 'calendar)
139
140 (defcustom org-mode-hook nil
141 "Mode hook for Org-mode, run after the mode was turned on."
142 :group 'org
143 :type 'hook)
144
145 (defcustom org-load-hook nil
146 "Hook that is run after org.el has been loaded."
147 :group 'org
148 :type 'hook)
149
150 (defvar org-modules) ; defined below
151 (defvar org-modules-loaded nil
152 "Have the modules been loaded already?")
153
154 (defun org-load-modules-maybe (&optional force)
155 "Load all extensions listed in `org-modules'."
156 (when (or force (not org-modules-loaded))
157 (mapc (lambda (ext)
158 (condition-case nil (require ext)
159 (error (message "Problems while trying to load feature `%s'" ext))))
160 org-modules)
161 (setq org-modules-loaded t)))
162
163 (defun org-set-modules (var value)
164 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
165 (set var value)
166 (when (featurep 'org)
167 (org-load-modules-maybe 'force)))
168
169 (when (org-bound-and-true-p org-modules)
170 (let ((a (member 'org-infojs org-modules)))
171 (and a (setcar a 'org-jsinfo))))
172
173 (defcustom org-modules '(org-bbdb org-bibtex org-docview org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
174 "Modules that should always be loaded together with org.el.
175 If a description starts with <C>, the file is not part of Emacs
176 and loading it will require that you have downloaded and properly installed
177 the org-mode distribution.
178
179 You can also use this system to load external packages (i.e. neither Org
180 core modules, nor modules from the CONTRIB directory). Just add symbols
181 to the end of the list. If the package is called org-xyz.el, then you need
182 to add the symbol `xyz', and the package must have a call to
183
184 (provide 'org-xyz)"
185 :group 'org
186 :set 'org-set-modules
187 :type
188 '(set :greedy t
189 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
190 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
191 (const :tag " crypt: Encryption of subtrees" org-crypt)
192 (const :tag " ctags: Access to Emacs tags with links" org-ctags)
193 (const :tag " docview: Links to doc-view buffers" org-docview)
194 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
195 (const :tag " id: Global IDs for identifying entries" org-id)
196 (const :tag " info: Links to Info nodes" org-info)
197 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
198 (const :tag " habit: Track your consistency with habits" org-habit)
199 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
200 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
201 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
202 (const :tag " mew Links to Mew folders/messages" org-mew)
203 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
204 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
205 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
206 (const :tag " vm: Links to VM folders/messages" org-vm)
207 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
208 (const :tag " w3m: Special cut/paste from w3m to Org-mode." org-w3m)
209 (const :tag " mouse: Additional mouse support" org-mouse)
210
211 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
212 (const :tag "C bookmark: Org-mode links to bookmarks" org-bookmark)
213 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
214 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
215 (const :tag "C collector: Collect properties into tables" org-collector)
216 (const :tag "C depend: TODO dependencies for Org-mode\n\t\t\t(PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
217 (const :tag "C elisp-symbol: Org-mode links to emacs-lisp symbols" org-elisp-symbol)
218 (const :tag "C eval: Include command output as text" org-eval)
219 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
220 (const :tag "C expiry: Expiry mechanism for Org-mode entries" org-expiry)
221 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
222 (const :tag "C git-link: Provide org links to specific file version" org-git-link)
223 (const :tag "C interactive-query: Interactive modification of tags query\n\t\t\t(PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
224
225 (const :tag "C invoice: Help manage client invoices in Org-mode" org-invoice)
226
227 (const :tag "C jira: Add a jira:ticket protocol to Org-mode" org-jira)
228 (const :tag "C learn: SuperMemo's incremental learning algorithm" org-learn)
229 (const :tag "C mairix: Hook mairix search into Org-mode for different MUAs" org-mairix)
230 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
231 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
232 (const :tag "C mtags: Support for muse-like tags" org-mtags)
233 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
234 (const :tag "C registry: A registry for Org-mode links" org-registry)
235 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
236 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
237 (const :tag "C secretary: Team management with org-mode" org-secretary)
238 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
239 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
240 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
241 (const :tag "C track: Keep up with Org-mode development" org-track)
242 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
243
244 (defcustom org-support-shift-select nil
245 "Non-nil means make shift-cursor commands select text when possible.
246
247 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
248 selecting a region, or enlarge thusly regions started in this way.
249 In Org-mode, in special contexts, these same keys are used for other
250 purposes, important enough to compete with shift selection. Org tries
251 to balance these needs by supporting `shift-select-mode' outside these
252 special contexts, under control of this variable.
253
254 The default of this variable is nil, to avoid confusing behavior. Shifted
255 cursor keys will then execute Org commands in the following contexts:
256 - on a headline, changing TODO state (left/right) and priority (up/down)
257 - on a time stamp, changing the time
258 - in a plain list item, changing the bullet type
259 - in a property definition line, switching between allowed values
260 - in the BEGIN line of a clock table (changing the time block).
261 Outside these contexts, the commands will throw an error.
262
263 When this variable is t and the cursor is not in a special context,
264 Org-mode will support shift-selection for making and enlarging regions.
265 To make this more effective, the bullet cycling will no longer happen
266 anywhere in an item line, but only if the cursor is exactly on the bullet.
267
268 If you set this variable to the symbol `always', then the keys
269 will not be special in headlines, property lines, and item lines, to make
270 shift selection work there as well. If this is what you want, you can
271 use the following alternative commands: `C-c C-t' and `C-c ,' to
272 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
273 TODO sets, `C-c -' to cycle item bullet types, and properties can be
274 edited by hand or in column view.
275
276 However, when the cursor is on a timestamp, shift-cursor commands
277 will still edit the time stamp - this is just too good to give up.
278
279 XEmacs user should have this variable set to nil, because shift-select-mode
280 is Emacs 23 only."
281 :group 'org
282 :type '(choice
283 (const :tag "Never" nil)
284 (const :tag "When outside special context" t)
285 (const :tag "Everywhere except timestamps" always)))
286
287 (defgroup org-startup nil
288 "Options concerning startup of Org-mode."
289 :tag "Org Startup"
290 :group 'org)
291
292 (defcustom org-startup-folded t
293 "Non-nil means entering Org-mode will switch to OVERVIEW.
294 This can also be configured on a per-file basis by adding one of
295 the following lines anywhere in the buffer:
296
297 #+STARTUP: fold (or `overview', this is equivalent)
298 #+STARTUP: nofold (or `showall', this is equivalent)
299 #+STARTUP: content
300 #+STARTUP: showeverything"
301 :group 'org-startup
302 :type '(choice
303 (const :tag "nofold: show all" nil)
304 (const :tag "fold: overview" t)
305 (const :tag "content: all headlines" content)
306 (const :tag "show everything, even drawers" showeverything)))
307
308 (defcustom org-startup-truncated t
309 "Non-nil means entering Org-mode will set `truncate-lines'.
310 This is useful since some lines containing links can be very long and
311 uninteresting. Also tables look terrible when wrapped."
312 :group 'org-startup
313 :type 'boolean)
314
315 (defcustom org-startup-indented nil
316 "Non-nil means turn on `org-indent-mode' on startup.
317 This can also be configured on a per-file basis by adding one of
318 the following lines anywhere in the buffer:
319
320 #+STARTUP: indent
321 #+STARTUP: noindent"
322 :group 'org-structure
323 :type '(choice
324 (const :tag "Not" nil)
325 (const :tag "Globally (slow on startup in large files)" t)))
326
327 (defcustom org-startup-with-beamer-mode nil
328 "Non-nil means turn on `org-beamer-mode' on startup.
329 This can also be configured on a per-file basis by adding one of
330 the following lines anywhere in the buffer:
331
332 #+STARTUP: beamer"
333 :group 'org-startup
334 :type 'boolean)
335
336 (defcustom org-startup-align-all-tables nil
337 "Non-nil means align all tables when visiting a file.
338 This is useful when the column width in tables is forced with <N> cookies
339 in table fields. Such tables will look correct only after the first re-align.
340 This can also be configured on a per-file basis by adding one of
341 the following lines anywhere in the buffer:
342 #+STARTUP: align
343 #+STARTUP: noalign"
344 :group 'org-startup
345 :type 'boolean)
346
347 (defcustom org-insert-mode-line-in-empty-file nil
348 "Non-nil means insert the first line setting Org-mode in empty files.
349 When the function `org-mode' is called interactively in an empty file, this
350 normally means that the file name does not automatically trigger Org-mode.
351 To ensure that the file will always be in Org-mode in the future, a
352 line enforcing Org-mode will be inserted into the buffer, if this option
353 has been set."
354 :group 'org-startup
355 :type 'boolean)
356
357 (defcustom org-replace-disputed-keys nil
358 "Non-nil means use alternative key bindings for some keys.
359 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
360 These keys are also used by other packages like shift-selection-mode'
361 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
362 If you want to use Org-mode together with one of these other modes,
363 or more generally if you would like to move some Org-mode commands to
364 other keys, set this variable and configure the keys with the variable
365 `org-disputed-keys'.
366
367 This option is only relevant at load-time of Org-mode, and must be set
368 *before* org.el is loaded. Changing it requires a restart of Emacs to
369 become effective."
370 :group 'org-startup
371 :type 'boolean)
372
373 (defcustom org-use-extra-keys nil
374 "Non-nil means use extra key sequence definitions for certain
375 commands. This happens automatically if you run XEmacs or if
376 window-system is nil. This variable lets you do the same
377 manually. You must set it before loading org.
378
379 Example: on Carbon Emacs 22 running graphically, with an external
380 keyboard on a Powerbook, the default way of setting M-left might
381 not work for either Alt or ESC. Setting this variable will make
382 it work for ESC."
383 :group 'org-startup
384 :type 'boolean)
385
386 (if (fboundp 'defvaralias)
387 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
388
389 (defcustom org-disputed-keys
390 '(([(shift up)] . [(meta p)])
391 ([(shift down)] . [(meta n)])
392 ([(shift left)] . [(meta -)])
393 ([(shift right)] . [(meta +)])
394 ([(control shift right)] . [(meta shift +)])
395 ([(control shift left)] . [(meta shift -)]))
396 "Keys for which Org-mode and other modes compete.
397 This is an alist, cars are the default keys, second element specifies
398 the alternative to use when `org-replace-disputed-keys' is t.
399
400 Keys can be specified in any syntax supported by `define-key'.
401 The value of this option takes effect only at Org-mode's startup,
402 therefore you'll have to restart Emacs to apply it after changing."
403 :group 'org-startup
404 :type 'alist)
405
406 (defun org-key (key)
407 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
408 Or return the original if not disputed."
409 (if org-replace-disputed-keys
410 (let* ((nkey (key-description key))
411 (x (org-find-if (lambda (x)
412 (equal (key-description (car x)) nkey))
413 org-disputed-keys)))
414 (if x (cdr x) key))
415 key))
416
417 (defun org-find-if (predicate seq)
418 (catch 'exit
419 (while seq
420 (if (funcall predicate (car seq))
421 (throw 'exit (car seq))
422 (pop seq)))))
423
424 (defun org-defkey (keymap key def)
425 "Define a key, possibly translated, as returned by `org-key'."
426 (define-key keymap (org-key key) def))
427
428 (defcustom org-ellipsis nil
429 "The ellipsis to use in the Org-mode outline.
430 When nil, just use the standard three dots. When a string, use that instead,
431 When a face, use the standard 3 dots, but with the specified face.
432 The change affects only Org-mode (which will then use its own display table).
433 Changing this requires executing `M-x org-mode' in a buffer to become
434 effective."
435 :group 'org-startup
436 :type '(choice (const :tag "Default" nil)
437 (face :tag "Face" :value org-warning)
438 (string :tag "String" :value "...#")))
439
440 (defvar org-display-table nil
441 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
442
443 (defgroup org-keywords nil
444 "Keywords in Org-mode."
445 :tag "Org Keywords"
446 :group 'org)
447
448 (defcustom org-deadline-string "DEADLINE:"
449 "String to mark deadline entries.
450 A deadline is this string, followed by a time stamp. Should be a word,
451 terminated by a colon. You can insert a schedule keyword and
452 a timestamp with \\[org-deadline].
453 Changes become only effective after restarting Emacs."
454 :group 'org-keywords
455 :type 'string)
456
457 (defcustom org-scheduled-string "SCHEDULED:"
458 "String to mark scheduled TODO entries.
459 A schedule is this string, followed by a time stamp. Should be a word,
460 terminated by a colon. You can insert a schedule keyword and
461 a timestamp with \\[org-schedule].
462 Changes become only effective after restarting Emacs."
463 :group 'org-keywords
464 :type 'string)
465
466 (defcustom org-closed-string "CLOSED:"
467 "String used as the prefix for timestamps logging closing a TODO entry."
468 :group 'org-keywords
469 :type 'string)
470
471 (defcustom org-clock-string "CLOCK:"
472 "String used as prefix for timestamps clocking work hours on an item."
473 :group 'org-keywords
474 :type 'string)
475
476 (defcustom org-comment-string "COMMENT"
477 "Entries starting with this keyword will never be exported.
478 An entry can be toggled between COMMENT and normal with
479 \\[org-toggle-comment].
480 Changes become only effective after restarting Emacs."
481 :group 'org-keywords
482 :type 'string)
483
484 (defcustom org-quote-string "QUOTE"
485 "Entries starting with this keyword will be exported in fixed-width font.
486 Quoting applies only to the text in the entry following the headline, and does
487 not extend beyond the next headline, even if that is lower level.
488 An entry can be toggled between QUOTE and normal with
489 \\[org-toggle-fixed-width-section]."
490 :group 'org-keywords
491 :type 'string)
492
493 (defconst org-repeat-re
494 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*?\\([.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)"
495 "Regular expression for specifying repeated events.
496 After a match, group 1 contains the repeat expression.")
497
498 (defgroup org-structure nil
499 "Options concerning the general structure of Org-mode files."
500 :tag "Org Structure"
501 :group 'org)
502
503 (defgroup org-reveal-location nil
504 "Options about how to make context of a location visible."
505 :tag "Org Reveal Location"
506 :group 'org-structure)
507
508 (defconst org-context-choice
509 '(choice
510 (const :tag "Always" t)
511 (const :tag "Never" nil)
512 (repeat :greedy t :tag "Individual contexts"
513 (cons
514 (choice :tag "Context"
515 (const agenda)
516 (const org-goto)
517 (const occur-tree)
518 (const tags-tree)
519 (const link-search)
520 (const mark-goto)
521 (const bookmark-jump)
522 (const isearch)
523 (const default))
524 (boolean))))
525 "Contexts for the reveal options.")
526
527 (defcustom org-show-hierarchy-above '((default . t))
528 "Non-nil means show full hierarchy when revealing a location.
529 Org-mode often shows locations in an org-mode file which might have
530 been invisible before. When this is set, the hierarchy of headings
531 above the exposed location is shown.
532 Turning this off for example for sparse trees makes them very compact.
533 Instead of t, this can also be an alist specifying this option for different
534 contexts. Valid contexts are
535 agenda when exposing an entry from the agenda
536 org-goto when using the command `org-goto' on key C-c C-j
537 occur-tree when using the command `org-occur' on key C-c /
538 tags-tree when constructing a sparse tree based on tags matches
539 link-search when exposing search matches associated with a link
540 mark-goto when exposing the jump goal of a mark
541 bookmark-jump when exposing a bookmark location
542 isearch when exiting from an incremental search
543 default default for all contexts not set explicitly"
544 :group 'org-reveal-location
545 :type org-context-choice)
546
547 (defcustom org-show-following-heading '((default . nil))
548 "Non-nil means show following heading when revealing a location.
549 Org-mode often shows locations in an org-mode file which might have
550 been invisible before. When this is set, the heading following the
551 match is shown.
552 Turning this off for example for sparse trees makes them very compact,
553 but makes it harder to edit the location of the match. In such a case,
554 use the command \\[org-reveal] to show more context.
555 Instead of t, this can also be an alist specifying this option for different
556 contexts. See `org-show-hierarchy-above' for valid contexts."
557 :group 'org-reveal-location
558 :type org-context-choice)
559
560 (defcustom org-show-siblings '((default . nil) (isearch t))
561 "Non-nil means show all sibling heading when revealing a location.
562 Org-mode often shows locations in an org-mode file which might have
563 been invisible before. When this is set, the sibling of the current entry
564 heading are all made visible. If `org-show-hierarchy-above' is t,
565 the same happens on each level of the hierarchy above the current entry.
566
567 By default this is on for the isearch context, off for all other contexts.
568 Turning this off for example for sparse trees makes them very compact,
569 but makes it harder to edit the location of the match. In such a case,
570 use the command \\[org-reveal] to show more context.
571 Instead of t, this can also be an alist specifying this option for different
572 contexts. See `org-show-hierarchy-above' for valid contexts."
573 :group 'org-reveal-location
574 :type org-context-choice)
575
576 (defcustom org-show-entry-below '((default . nil))
577 "Non-nil means show the entry below a headline when revealing a location.
578 Org-mode often shows locations in an org-mode file which might have
579 been invisible before. When this is set, the text below the headline that is
580 exposed is also shown.
581
582 By default this is off for all contexts.
583 Instead of t, this can also be an alist specifying this option for different
584 contexts. See `org-show-hierarchy-above' for valid contexts."
585 :group 'org-reveal-location
586 :type org-context-choice)
587
588 (defcustom org-indirect-buffer-display 'other-window
589 "How should indirect tree buffers be displayed?
590 This applies to indirect buffers created with the commands
591 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
592 Valid values are:
593 current-window Display in the current window
594 other-window Just display in another window.
595 dedicated-frame Create one new frame, and re-use it each time.
596 new-frame Make a new frame each time. Note that in this case
597 previously-made indirect buffers are kept, and you need to
598 kill these buffers yourself."
599 :group 'org-structure
600 :group 'org-agenda-windows
601 :type '(choice
602 (const :tag "In current window" current-window)
603 (const :tag "In current frame, other window" other-window)
604 (const :tag "Each time a new frame" new-frame)
605 (const :tag "One dedicated frame" dedicated-frame)))
606
607 (defcustom org-use-speed-commands nil
608 "Non-nil means activate single letter commands at beginning of a headline.
609 This may also be a function to test for appropriate locations where speed
610 commands should be active."
611 :group 'org-structure
612 :type '(choice
613 (const :tag "Never" nil)
614 (const :tag "At beginning of headline stars" t)
615 (function)))
616
617 (defcustom org-speed-commands-user nil
618 "Alist of additional speed commands.
619 This list will be checked before `org-speed-commands-default'
620 when the variable `org-use-speed-commands' is non-nil
621 and when the cursor is at the beginning of a headline.
622 The car if each entry is a string with a single letter, which must
623 be assigned to `self-insert-command' in the global map.
624 The cdr is either a command to be called interactively, a function
625 to be called, or a form to be evaluated.
626 An entry that is just a list with a single string will be interpreted
627 as a descriptive headline that will be added when listing the speed
628 copmmands in the Help buffer using the `?' speed command."
629 :group 'org-structure
630 :type '(repeat :value ("k" . ignore)
631 (choice :value ("k" . ignore)
632 (list :tag "Descriptive Headline" (string :tag "Headline"))
633 (cons :tag "Letter and Command"
634 (string :tag "Command letter")
635 (choice
636 (function)
637 (sexp))))))
638
639 (defgroup org-cycle nil
640 "Options concerning visibility cycling in Org-mode."
641 :tag "Org Cycle"
642 :group 'org-structure)
643
644 (defcustom org-cycle-skip-children-state-if-no-children t
645 "Non-nil means skip CHILDREN state in entries that don't have any."
646 :group 'org-cycle
647 :type 'boolean)
648
649 (defcustom org-cycle-max-level nil
650 "Maximum level which should still be subject to visibility cycling.
651 Levels higher than this will, for cycling, be treated as text, not a headline.
652 When `org-odd-levels-only' is set, a value of N in this variable actually
653 means 2N-1 stars as the limiting headline.
654 When nil, cycle all levels.
655 Note that the limiting level of cycling is also influenced by
656 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
657 `org-inlinetask-min-level' is, cycling will be limited to levels one less
658 than its value."
659 :group 'org-cycle
660 :type '(choice
661 (const :tag "No limit" nil)
662 (integer :tag "Maximum level")))
663
664 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
665 "Names of drawers. Drawers are not opened by cycling on the headline above.
666 Drawers only open with a TAB on the drawer line itself. A drawer looks like
667 this:
668 :DRAWERNAME:
669 .....
670 :END:
671 The drawer \"PROPERTIES\" is special for capturing properties through
672 the property API.
673
674 Drawers can be defined on the per-file basis with a line like:
675
676 #+DRAWERS: HIDDEN STATE PROPERTIES"
677 :group 'org-structure
678 :group 'org-cycle
679 :type '(repeat (string :tag "Drawer Name")))
680
681 (defcustom org-hide-block-startup nil
682 "Non-nil means entering Org-mode will fold all blocks.
683 This can also be set in on a per-file basis with
684
685 #+STARTUP: hideblocks
686 #+STARTUP: showblocks"
687 :group 'org-startup
688 :group 'org-cycle
689 :type 'boolean)
690
691 (defcustom org-cycle-global-at-bob nil
692 "Cycle globally if cursor is at beginning of buffer and not at a headline.
693 This makes it possible to do global cycling without having to use S-TAB or
694 C-u TAB. For this special case to work, the first line of the buffer
695 must not be a headline - it may be empty or some other text. When used in
696 this way, `org-cycle-hook' is disables temporarily, to make sure the
697 cursor stays at the beginning of the buffer.
698 When this option is nil, don't do anything special at the beginning
699 of the buffer."
700 :group 'org-cycle
701 :type 'boolean)
702
703 (defcustom org-cycle-level-after-item/entry-creation t
704 "Non-nil means cycle entry level or item indentation in new empty entries.
705
706 When the cursor is at the end of an empty headline, i.e with only stars
707 and maybe a TODO keyword, TAB will then switch the entry to become a child,
708 and then all possible anchestor states, before returning to the original state.
709 This makes data entry extremely fast: M-RET to create a new headline,
710 on TAB to make it a child, two or more tabs to make it a (grand-)uncle.
711
712 When the cursor is at the end of an empty plain list item, one TAB will
713 make it a subitem, two or more tabs will back up to make this an item
714 higher up in the item hierarchy."
715 :group 'org-cycle
716 :type 'boolean)
717
718 (defcustom org-cycle-emulate-tab t
719 "Where should `org-cycle' emulate TAB.
720 nil Never
721 white Only in completely white lines
722 whitestart Only at the beginning of lines, before the first non-white char
723 t Everywhere except in headlines
724 exc-hl-bol Everywhere except at the start of a headline
725 If TAB is used in a place where it does not emulate TAB, the current subtree
726 visibility is cycled."
727 :group 'org-cycle
728 :type '(choice (const :tag "Never" nil)
729 (const :tag "Only in completely white lines" white)
730 (const :tag "Before first char in a line" whitestart)
731 (const :tag "Everywhere except in headlines" t)
732 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
733 ))
734
735 (defcustom org-cycle-separator-lines 2
736 "Number of empty lines needed to keep an empty line between collapsed trees.
737 If you leave an empty line between the end of a subtree and the following
738 headline, this empty line is hidden when the subtree is folded.
739 Org-mode will leave (exactly) one empty line visible if the number of
740 empty lines is equal or larger to the number given in this variable.
741 So the default 2 means at least 2 empty lines after the end of a subtree
742 are needed to produce free space between a collapsed subtree and the
743 following headline.
744
745 If the number is negative, and the number of empty lines is at least -N,
746 all empty lines are shown.
747
748 Special case: when 0, never leave empty lines in collapsed view."
749 :group 'org-cycle
750 :type 'integer)
751 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
752
753 (defcustom org-pre-cycle-hook nil
754 "Hook that is run before visibility cycling is happening.
755 The function(s) in this hook must accept a single argument which indicates
756 the new state that will be set right after running this hook. The
757 argument is a symbol. Before a global state change, it can have the values
758 `overview', `content', or `all'. Before a local state change, it can have
759 the values `folded', `children', or `subtree'."
760 :group 'org-cycle
761 :type 'hook)
762
763 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
764 org-cycle-hide-drawers
765 org-cycle-show-empty-lines
766 org-optimize-window-after-visibility-change)
767 "Hook that is run after `org-cycle' has changed the buffer visibility.
768 The function(s) in this hook must accept a single argument which indicates
769 the new state that was set by the most recent `org-cycle' command. The
770 argument is a symbol. After a global state change, it can have the values
771 `overview', `content', or `all'. After a local state change, it can have
772 the values `folded', `children', or `subtree'."
773 :group 'org-cycle
774 :type 'hook)
775
776 (defgroup org-edit-structure nil
777 "Options concerning structure editing in Org-mode."
778 :tag "Org Edit Structure"
779 :group 'org-structure)
780
781 (defcustom org-odd-levels-only nil
782 "Non-nil means skip even levels and only use odd levels for the outline.
783 This has the effect that two stars are being added/taken away in
784 promotion/demotion commands. It also influences how levels are
785 handled by the exporters.
786 Changing it requires restart of `font-lock-mode' to become effective
787 for fontification also in regions already fontified.
788 You may also set this on a per-file basis by adding one of the following
789 lines to the buffer:
790
791 #+STARTUP: odd
792 #+STARTUP: oddeven"
793 :group 'org-edit-structure
794 :group 'org-appearance
795 :type 'boolean)
796
797 (defcustom org-adapt-indentation t
798 "Non-nil means adapt indentation to outline node level.
799
800 When this variable is set, Org assumes that you write outlines by
801 indenting text in each node to align with the headline (after the stars).
802 The following issues are influenced by this variable:
803
804 - When this is set and the *entire* text in an entry is indented, the
805 indentation is increased by one space in a demotion command, and
806 decreased by one in a promotion command. If any line in the entry
807 body starts with text at column 0, indentation is not changed at all.
808
809 - Property drawers and planning information is inserted indented when
810 this variable s set. When nil, they will not be indented.
811
812 - TAB indents a line relative to context. The lines below a headline
813 will be indented when this variable is set.
814
815 Note that this is all about true indentation, by adding and removing
816 space characters. See also `org-indent.el' which does level-dependent
817 indentation in a virtual way, i.e. at display time in Emacs."
818 :group 'org-edit-structure
819 :type 'boolean)
820
821 (defcustom org-special-ctrl-a/e nil
822 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
823
824 When t, `C-a' will bring back the cursor to the beginning of the
825 headline text, i.e. after the stars and after a possible TODO keyword.
826 In an item, this will be the position after the bullet.
827 When the cursor is already at that position, another `C-a' will bring
828 it to the beginning of the line.
829
830 `C-e' will jump to the end of the headline, ignoring the presence of tags
831 in the headline. A second `C-e' will then jump to the true end of the
832 line, after any tags. This also means that, when this variable is
833 non-nil, `C-e' also will never jump beyond the end of the heading of a
834 folded section, i.e. not after the ellipses.
835
836 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
837 going to the true line boundary first. Only a directly following, identical
838 keypress will bring the cursor to the special positions.
839
840 This may also be a cons cell where the behavior for `C-a' and `C-e' is
841 set separately."
842 :group 'org-edit-structure
843 :type '(choice
844 (const :tag "off" nil)
845 (const :tag "on: after stars/bullet and before tags first" t)
846 (const :tag "reversed: true line boundary first" reversed)
847 (cons :tag "Set C-a and C-e separately"
848 (choice :tag "Special C-a"
849 (const :tag "off" nil)
850 (const :tag "on: after stars/bullet first" t)
851 (const :tag "reversed: before stars/bullet first" reversed))
852 (choice :tag "Special C-e"
853 (const :tag "off" nil)
854 (const :tag "on: before tags first" t)
855 (const :tag "reversed: after tags first" reversed)))))
856 (if (fboundp 'defvaralias)
857 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
858
859 (defcustom org-special-ctrl-k nil
860 "Non-nil means `C-k' will behave specially in headlines.
861 When nil, `C-k' will call the default `kill-line' command.
862 When t, the following will happen while the cursor is in the headline:
863
864 - When the cursor is at the beginning of a headline, kill the entire
865 line and possible the folded subtree below the line.
866 - When in the middle of the headline text, kill the headline up to the tags.
867 - When after the headline text, kill the tags."
868 :group 'org-edit-structure
869 :type 'boolean)
870
871 (defcustom org-yank-folded-subtrees t
872 "Non-nil means when yanking subtrees, fold them.
873 If the kill is a single subtree, or a sequence of subtrees, i.e. if
874 it starts with a heading and all other headings in it are either children
875 or siblings, then fold all the subtrees. However, do this only if no
876 text after the yank would be swallowed into a folded tree by this action."
877 :group 'org-edit-structure
878 :type 'boolean)
879
880 (defcustom org-yank-adjusted-subtrees nil
881 "Non-nil means when yanking subtrees, adjust the level.
882 With this setting, `org-paste-subtree' is used to insert the subtree, see
883 this function for details."
884 :group 'org-edit-structure
885 :type 'boolean)
886
887 (defcustom org-M-RET-may-split-line '((default . t))
888 "Non-nil means M-RET will split the line at the cursor position.
889 When nil, it will go to the end of the line before making a
890 new line.
891 You may also set this option in a different way for different
892 contexts. Valid contexts are:
893
894 headline when creating a new headline
895 item when creating a new item
896 table in a table field
897 default the value to be used for all contexts not explicitly
898 customized"
899 :group 'org-structure
900 :group 'org-table
901 :type '(choice
902 (const :tag "Always" t)
903 (const :tag "Never" nil)
904 (repeat :greedy t :tag "Individual contexts"
905 (cons
906 (choice :tag "Context"
907 (const headline)
908 (const item)
909 (const table)
910 (const default))
911 (boolean)))))
912
913
914 (defcustom org-insert-heading-respect-content nil
915 "Non-nil means insert new headings after the current subtree.
916 When nil, the new heading is created directly after the current line.
917 The commands \\[org-insert-heading-respect-content] and
918 \\[org-insert-todo-heading-respect-content] turn this variable on
919 for the duration of the command."
920 :group 'org-structure
921 :type 'boolean)
922
923 (defcustom org-blank-before-new-entry '((heading . auto)
924 (plain-list-item . auto))
925 "Should `org-insert-heading' leave a blank line before new heading/item?
926 The value is an alist, with `heading' and `plain-list-item' as car,
927 and a boolean flag as cdr. For plain lists, if the variable
928 `org-empty-line-terminates-plain-lists' is set, the setting here
929 is ignored and no empty line is inserted, to keep the list in tact."
930 :group 'org-edit-structure
931 :type '(list
932 (cons (const heading)
933 (choice (const :tag "Never" nil)
934 (const :tag "Always" t)
935 (const :tag "Auto" auto)))
936 (cons (const plain-list-item)
937 (choice (const :tag "Never" nil)
938 (const :tag "Always" t)
939 (const :tag "Auto" auto)))))
940
941 (defcustom org-insert-heading-hook nil
942 "Hook being run after inserting a new heading."
943 :group 'org-edit-structure
944 :type 'hook)
945
946 (defcustom org-enable-fixed-width-editor t
947 "Non-nil means lines starting with \":\" are treated as fixed-width.
948 This currently only means they are never auto-wrapped.
949 When nil, such lines will be treated like ordinary lines.
950 See also the QUOTE keyword."
951 :group 'org-edit-structure
952 :type 'boolean)
953
954
955 (defcustom org-goto-auto-isearch t
956 "Non-nil means typing characters in org-goto starts incremental search."
957 :group 'org-edit-structure
958 :type 'boolean)
959
960 (defgroup org-sparse-trees nil
961 "Options concerning sparse trees in Org-mode."
962 :tag "Org Sparse Trees"
963 :group 'org-structure)
964
965 (defcustom org-highlight-sparse-tree-matches t
966 "Non-nil means highlight all matches that define a sparse tree.
967 The highlights will automatically disappear the next time the buffer is
968 changed by an edit command."
969 :group 'org-sparse-trees
970 :type 'boolean)
971
972 (defcustom org-remove-highlights-with-change t
973 "Non-nil means any change to the buffer will remove temporary highlights.
974 Such highlights are created by `org-occur' and `org-clock-display'.
975 When nil, `C-c C-c needs to be used to get rid of the highlights.
976 The highlights created by `org-preview-latex-fragment' always need
977 `C-c C-c' to be removed."
978 :group 'org-sparse-trees
979 :group 'org-time
980 :type 'boolean)
981
982
983 (defcustom org-occur-hook '(org-first-headline-recenter)
984 "Hook that is run after `org-occur' has constructed a sparse tree.
985 This can be used to recenter the window to show as much of the structure
986 as possible."
987 :group 'org-sparse-trees
988 :type 'hook)
989
990 (defgroup org-imenu-and-speedbar nil
991 "Options concerning imenu and speedbar in Org-mode."
992 :tag "Org Imenu and Speedbar"
993 :group 'org-structure)
994
995 (defcustom org-imenu-depth 2
996 "The maximum level for Imenu access to Org-mode headlines.
997 This also applied for speedbar access."
998 :group 'org-imenu-and-speedbar
999 :type 'integer)
1000
1001 (defgroup org-table nil
1002 "Options concerning tables in Org-mode."
1003 :tag "Org Table"
1004 :group 'org)
1005
1006 (defcustom org-enable-table-editor 'optimized
1007 "Non-nil means lines starting with \"|\" are handled by the table editor.
1008 When nil, such lines will be treated like ordinary lines.
1009
1010 When equal to the symbol `optimized', the table editor will be optimized to
1011 do the following:
1012 - Automatic overwrite mode in front of whitespace in table fields.
1013 This makes the structure of the table stay in tact as long as the edited
1014 field does not exceed the column width.
1015 - Minimize the number of realigns. Normally, the table is aligned each time
1016 TAB or RET are pressed to move to another field. With optimization this
1017 happens only if changes to a field might have changed the column width.
1018 Optimization requires replacing the functions `self-insert-command',
1019 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
1020 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
1021 very good at guessing when a re-align will be necessary, but you can always
1022 force one with \\[org-ctrl-c-ctrl-c].
1023
1024 If you would like to use the optimized version in Org-mode, but the
1025 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
1026
1027 This variable can be used to turn on and off the table editor during a session,
1028 but in order to toggle optimization, a restart is required.
1029
1030 See also the variable `org-table-auto-blank-field'."
1031 :group 'org-table
1032 :type '(choice
1033 (const :tag "off" nil)
1034 (const :tag "on" t)
1035 (const :tag "on, optimized" optimized)))
1036
1037 (defcustom org-self-insert-cluster-for-undo t
1038 "Non-nil means cluster self-insert commands for undo when possible.
1039 If this is set, then, like in the Emacs command loop, 20 consecutive
1040 characters will be undone together.
1041 This is configurable, because there is some impact on typing performance."
1042 :group 'org-table
1043 :type 'boolean)
1044
1045 (defcustom org-table-tab-recognizes-table.el t
1046 "Non-nil means TAB will automatically notice a table.el table.
1047 When it sees such a table, it moves point into it and - if necessary -
1048 calls `table-recognize-table'."
1049 :group 'org-table-editing
1050 :type 'boolean)
1051
1052 (defgroup org-link nil
1053 "Options concerning links in Org-mode."
1054 :tag "Org Link"
1055 :group 'org)
1056
1057 (defvar org-link-abbrev-alist-local nil
1058 "Buffer-local version of `org-link-abbrev-alist', which see.
1059 The value of this is taken from the #+LINK lines.")
1060 (make-variable-buffer-local 'org-link-abbrev-alist-local)
1061
1062 (defcustom org-link-abbrev-alist nil
1063 "Alist of link abbreviations.
1064 The car of each element is a string, to be replaced at the start of a link.
1065 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
1066 links in Org-mode buffers can have an optional tag after a double colon, e.g.
1067
1068 [[linkkey:tag][description]]
1069
1070 The 'linkkey' must be a word word, starting with a letter, followed
1071 by letters, numbers, '-' or '_'.
1072
1073 If REPLACE is a string, the tag will simply be appended to create the link.
1074 If the string contains \"%s\", the tag will be inserted there. Alternatively,
1075 the placeholder \"%h\" will cause a url-encoded version of the tag to
1076 be inserted at that point (see the function `url-hexify-string').
1077
1078 REPLACE may also be a function that will be called with the tag as the
1079 only argument to create the link, which should be returned as a string.
1080
1081 See the manual for examples."
1082 :group 'org-link
1083 :type '(repeat
1084 (cons
1085 (string :tag "Protocol")
1086 (choice
1087 (string :tag "Format")
1088 (function)))))
1089
1090 (defcustom org-descriptive-links t
1091 "Non-nil means hide link part and only show description of bracket links.
1092 Bracket links are like [[link][description]]. This variable sets the initial
1093 state in new org-mode buffers. The setting can then be toggled on a
1094 per-buffer basis from the Org->Hyperlinks menu."
1095 :group 'org-link
1096 :type 'boolean)
1097
1098 (defcustom org-link-file-path-type 'adaptive
1099 "How the path name in file links should be stored.
1100 Valid values are:
1101
1102 relative Relative to the current directory, i.e. the directory of the file
1103 into which the link is being inserted.
1104 absolute Absolute path, if possible with ~ for home directory.
1105 noabbrev Absolute path, no abbreviation of home directory.
1106 adaptive Use relative path for files in the current directory and sub-
1107 directories of it. For other files, use an absolute path."
1108 :group 'org-link
1109 :type '(choice
1110 (const relative)
1111 (const absolute)
1112 (const noabbrev)
1113 (const adaptive)))
1114
1115 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1116 "Types of links that should be activated in Org-mode files.
1117 This is a list of symbols, each leading to the activation of a certain link
1118 type. In principle, it does not hurt to turn on most link types - there may
1119 be a small gain when turning off unused link types. The types are:
1120
1121 bracket The recommended [[link][description]] or [[link]] links with hiding.
1122 angular Links in angular brackets that may contain whitespace like
1123 <bbdb:Carsten Dominik>.
1124 plain Plain links in normal text, no whitespace, like http://google.com.
1125 radio Text that is matched by a radio target, see manual for details.
1126 tag Tag settings in a headline (link to tag search).
1127 date Time stamps (link to calendar).
1128 footnote Footnote labels.
1129
1130 Changing this variable requires a restart of Emacs to become effective."
1131 :group 'org-link
1132 :type '(set :greedy t
1133 (const :tag "Double bracket links (new style)" bracket)
1134 (const :tag "Angular bracket links (old style)" angular)
1135 (const :tag "Plain text links" plain)
1136 (const :tag "Radio target matches" radio)
1137 (const :tag "Tags" tag)
1138 (const :tag "Timestamps" date)
1139 (const :tag "Footnotes" footnote)))
1140
1141 (defcustom org-make-link-description-function nil
1142 "Function to use to generate link descriptions from links. If
1143 nil the link location will be used. This function must take two
1144 parameters; the first is the link and the second the description
1145 org-insert-link has generated, and should return the description
1146 to use."
1147 :group 'org-link
1148 :type 'function)
1149
1150 (defgroup org-link-store nil
1151 "Options concerning storing links in Org-mode."
1152 :tag "Org Store Link"
1153 :group 'org-link)
1154
1155 (defcustom org-email-link-description-format "Email %c: %.30s"
1156 "Format of the description part of a link to an email or usenet message.
1157 The following %-escapes will be replaced by corresponding information:
1158
1159 %F full \"From\" field
1160 %f name, taken from \"From\" field, address if no name
1161 %T full \"To\" field
1162 %t first name in \"To\" field, address if no name
1163 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1164 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1165 %s subject
1166 %m message-id.
1167
1168 You may use normal field width specification between the % and the letter.
1169 This is for example useful to limit the length of the subject.
1170
1171 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1172 :group 'org-link-store
1173 :type 'string)
1174
1175 (defcustom org-from-is-user-regexp
1176 (let (r1 r2)
1177 (when (and user-mail-address (not (string= user-mail-address "")))
1178 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1179 (when (and user-full-name (not (string= user-full-name "")))
1180 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1181 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1182 "Regexp matched against the \"From:\" header of an email or usenet message.
1183 It should match if the message is from the user him/herself."
1184 :group 'org-link-store
1185 :type 'regexp)
1186
1187 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1188 "Non-nil means storing a link to an Org file will use entry IDs.
1189
1190 Note that before this variable is even considered, org-id must be loaded,
1191 so please customize `org-modules' and turn it on.
1192
1193 The variable can have the following values:
1194
1195 t Create an ID if needed to make a link to the current entry.
1196
1197 create-if-interactive
1198 If `org-store-link' is called directly (interactively, as a user
1199 command), do create an ID to support the link. But when doing the
1200 job for remember, only use the ID if it already exists. The
1201 purpose of this setting is to avoid proliferation of unwanted
1202 IDs, just because you happen to be in an Org file when you
1203 call `org-remember' that automatically and preemptively
1204 creates a link. If you do want to get an ID link in a remember
1205 template to an entry not having an ID, create it first by
1206 explicitly creating a link to it, using `C-c C-l' first.
1207
1208 create-if-interactive-and-no-custom-id
1209 Like create-if-interactive, but do not create an ID if there is
1210 a CUSTOM_ID property defined in the entry. This is the default.
1211
1212 use-existing
1213 Use existing ID, do not create one.
1214
1215 nil Never use an ID to make a link, instead link using a text search for
1216 the headline text."
1217 :group 'org-link-store
1218 :type '(choice
1219 (const :tag "Create ID to make link" t)
1220 (const :tag "Create if storing link interactively"
1221 create-if-interactive)
1222 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1223 create-if-interactive-and-no-custom-id)
1224 (const :tag "Only use existing" use-existing)
1225 (const :tag "Do not use ID to create link" nil)))
1226
1227 (defcustom org-context-in-file-links t
1228 "Non-nil means file links from `org-store-link' contain context.
1229 A search string will be added to the file name with :: as separator and
1230 used to find the context when the link is activated by the command
1231 `org-open-at-point'.
1232 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1233 negates this setting for the duration of the command."
1234 :group 'org-link-store
1235 :type 'boolean)
1236
1237 (defcustom org-keep-stored-link-after-insertion nil
1238 "Non-nil means keep link in list for entire session.
1239
1240 The command `org-store-link' adds a link pointing to the current
1241 location to an internal list. These links accumulate during a session.
1242 The command `org-insert-link' can be used to insert links into any
1243 Org-mode file (offering completion for all stored links). When this
1244 option is nil, every link which has been inserted once using \\[org-insert-link]
1245 will be removed from the list, to make completing the unused links
1246 more efficient."
1247 :group 'org-link-store
1248 :type 'boolean)
1249
1250 (defgroup org-link-follow nil
1251 "Options concerning following links in Org-mode."
1252 :tag "Org Follow Link"
1253 :group 'org-link)
1254
1255 (defcustom org-link-translation-function nil
1256 "Function to translate links with different syntax to Org syntax.
1257 This can be used to translate links created for example by the Planner
1258 or emacs-wiki packages to Org syntax.
1259 The function must accept two parameters, a TYPE containing the link
1260 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1261 which is everything after the link protocol. It should return a cons
1262 with possibly modified values of type and path.
1263 Org contains a function for this, so if you set this variable to
1264 `org-translate-link-from-planner', you should be able follow many
1265 links created by planner."
1266 :group 'org-link-follow
1267 :type 'function)
1268
1269 (defcustom org-follow-link-hook nil
1270 "Hook that is run after a link has been followed."
1271 :group 'org-link-follow
1272 :type 'hook)
1273
1274 (defcustom org-tab-follows-link nil
1275 "Non-nil means on links TAB will follow the link.
1276 Needs to be set before org.el is loaded.
1277 This really should not be used, it does not make sense, and the
1278 implementation is bad."
1279 :group 'org-link-follow
1280 :type 'boolean)
1281
1282 (defcustom org-return-follows-link nil
1283 "Non-nil means on links RET will follow the link.
1284 Needs to be set before org.el is loaded."
1285 :group 'org-link-follow
1286 :type 'boolean)
1287
1288 (defcustom org-mouse-1-follows-link
1289 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1290 "Non-nil means mouse-1 on a link will follow the link.
1291 A longer mouse click will still set point. Does not work on XEmacs.
1292 Needs to be set before org.el is loaded."
1293 :group 'org-link-follow
1294 :type 'boolean)
1295
1296 (defcustom org-mark-ring-length 4
1297 "Number of different positions to be recorded in the ring
1298 Changing this requires a restart of Emacs to work correctly."
1299 :group 'org-link-follow
1300 :type 'integer)
1301
1302 (defcustom org-link-frame-setup
1303 '((vm . vm-visit-folder-other-frame)
1304 (gnus . gnus-other-frame)
1305 (file . find-file-other-window))
1306 "Setup the frame configuration for following links.
1307 When following a link with Emacs, it may often be useful to display
1308 this link in another window or frame. This variable can be used to
1309 set this up for the different types of links.
1310 For VM, use any of
1311 `vm-visit-folder'
1312 `vm-visit-folder-other-frame'
1313 For Gnus, use any of
1314 `gnus'
1315 `gnus-other-frame'
1316 `org-gnus-no-new-news'
1317 For FILE, use any of
1318 `find-file'
1319 `find-file-other-window'
1320 `find-file-other-frame'
1321 For the calendar, use the variable `calendar-setup'.
1322 For BBDB, it is currently only possible to display the matches in
1323 another window."
1324 :group 'org-link-follow
1325 :type '(list
1326 (cons (const vm)
1327 (choice
1328 (const vm-visit-folder)
1329 (const vm-visit-folder-other-window)
1330 (const vm-visit-folder-other-frame)))
1331 (cons (const gnus)
1332 (choice
1333 (const gnus)
1334 (const gnus-other-frame)
1335 (const org-gnus-no-new-news)))
1336 (cons (const file)
1337 (choice
1338 (const find-file)
1339 (const find-file-other-window)
1340 (const find-file-other-frame)))))
1341
1342 (defcustom org-display-internal-link-with-indirect-buffer nil
1343 "Non-nil means use indirect buffer to display infile links.
1344 Activating internal links (from one location in a file to another location
1345 in the same file) normally just jumps to the location. When the link is
1346 activated with a C-u prefix (or with mouse-3), the link is displayed in
1347 another window. When this option is set, the other window actually displays
1348 an indirect buffer clone of the current buffer, to avoid any visibility
1349 changes to the current buffer."
1350 :group 'org-link-follow
1351 :type 'boolean)
1352
1353 (defcustom org-open-non-existing-files nil
1354 "Non-nil means `org-open-file' will open non-existing files.
1355 When nil, an error will be generated.
1356 This variable applies only to external applications because they
1357 might choke on non-existing files. If the link is to a file that
1358 will be opened in Emacs, the variable is ignored."
1359 :group 'org-link-follow
1360 :type 'boolean)
1361
1362 (defcustom org-open-directory-means-index-dot-org nil
1363 "Non-nil means a link to a directory really means to index.org.
1364 When nil, following a directory link will run dired or open a finder/explorer
1365 window on that directory."
1366 :group 'org-link-follow
1367 :type 'boolean)
1368
1369 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1370 "Function and arguments to call for following mailto links.
1371 This is a list with the first element being a lisp function, and the
1372 remaining elements being arguments to the function. In string arguments,
1373 %a will be replaced by the address, and %s will be replaced by the subject
1374 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1375 :group 'org-link-follow
1376 :type '(choice
1377 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1378 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1379 (const :tag "message-mail" (message-mail "%a" "%s"))
1380 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1381
1382 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1383 "Non-nil means ask for confirmation before executing shell links.
1384 Shell links can be dangerous: just think about a link
1385
1386 [[shell:rm -rf ~/*][Google Search]]
1387
1388 This link would show up in your Org-mode document as \"Google Search\",
1389 but really it would remove your entire home directory.
1390 Therefore we advise against setting this variable to nil.
1391 Just change it to `y-or-n-p' if you want to confirm with a
1392 single keystroke rather than having to type \"yes\"."
1393 :group 'org-link-follow
1394 :type '(choice
1395 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1396 (const :tag "with y-or-n (faster)" y-or-n-p)
1397 (const :tag "no confirmation (dangerous)" nil)))
1398
1399 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1400 "Non-nil means ask for confirmation before executing Emacs Lisp links.
1401 Elisp links can be dangerous: just think about a link
1402
1403 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1404
1405 This link would show up in your Org-mode document as \"Google Search\",
1406 but really it would remove your entire home directory.
1407 Therefore we advise against setting this variable to nil.
1408 Just change it to `y-or-n-p' if you want to confirm with a
1409 single keystroke rather than having to type \"yes\"."
1410 :group 'org-link-follow
1411 :type '(choice
1412 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1413 (const :tag "with y-or-n (faster)" y-or-n-p)
1414 (const :tag "no confirmation (dangerous)" nil)))
1415
1416 (defconst org-file-apps-defaults-gnu
1417 '((remote . emacs)
1418 (system . mailcap)
1419 (t . mailcap))
1420 "Default file applications on a UNIX or GNU/Linux system.
1421 See `org-file-apps'.")
1422
1423 (defconst org-file-apps-defaults-macosx
1424 '((remote . emacs)
1425 (t . "open %s")
1426 (system . "open %s")
1427 ("ps.gz" . "gv %s")
1428 ("eps.gz" . "gv %s")
1429 ("dvi" . "xdvi %s")
1430 ("fig" . "xfig %s"))
1431 "Default file applications on a MacOS X system.
1432 The system \"open\" is known as a default, but we use X11 applications
1433 for some files for which the OS does not have a good default.
1434 See `org-file-apps'.")
1435
1436 (defconst org-file-apps-defaults-windowsnt
1437 (list
1438 '(remote . emacs)
1439 (cons t
1440 (list (if (featurep 'xemacs)
1441 'mswindows-shell-execute
1442 'w32-shell-execute)
1443 "open" 'file))
1444 (cons 'system
1445 (list (if (featurep 'xemacs)
1446 'mswindows-shell-execute
1447 'w32-shell-execute)
1448 "open" 'file)))
1449 "Default file applications on a Windows NT system.
1450 The system \"open\" is used for most files.
1451 See `org-file-apps'.")
1452
1453 (defcustom org-file-apps
1454 '(
1455 (auto-mode . emacs)
1456 ("\\.mm\\'" . default)
1457 ("\\.x?html?\\'" . default)
1458 ("\\.pdf\\'" . default)
1459 )
1460 "External applications for opening `file:path' items in a document.
1461 Org-mode uses system defaults for different file types, but
1462 you can use this variable to set the application for a given file
1463 extension. The entries in this list are cons cells where the car identifies
1464 files and the cdr the corresponding command. Possible values for the
1465 file identifier are
1466 \"regex\" Regular expression matched against the file: link. For
1467 backward compatibility, this can also be a string with only
1468 alphanumeric characters, which is then interpreted as an
1469 extension.
1470 `directory' Matches a directory
1471 `remote' Matches a remote file, accessible through tramp or efs.
1472 Remote files most likely should be visited through Emacs
1473 because external applications cannot handle such paths.
1474 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1475 so all files Emacs knows how to handle. Using this with
1476 command `emacs' will open most files in Emacs. Beware that this
1477 will also open html files inside Emacs, unless you add
1478 (\"html\" . default) to the list as well.
1479 t Default for files not matched by any of the other options.
1480 `system' The system command to open files, like `open' on Windows
1481 and Mac OS X, and mailcap under GNU/Linux. This is the command
1482 that will be selected if you call `C-c C-o' with a double
1483 `C-u C-u' prefix.
1484
1485 Possible values for the command are:
1486 `emacs' The file will be visited by the current Emacs process.
1487 `default' Use the default application for this file type, which is the
1488 association for t in the list, most likely in the system-specific
1489 part.
1490 This can be used to overrule an unwanted setting in the
1491 system-specific variable.
1492 `system' Use the system command for opening files, like \"open\".
1493 This command is specified by the entry whose car is `system'.
1494 Most likely, the system-specific version of this variable
1495 does define this command, but you can overrule/replace it
1496 here.
1497 string A command to be executed by a shell; %s will be replaced
1498 by the path to the file. If the file identifier is a regex,
1499 %n will be replaced by the match of the nth match group.
1500 sexp A Lisp form which will be evaluated. The file path will
1501 be available in the Lisp variable `file', the link itself
1502 in the Lisp variable `link'. If the file identifier is a regex,
1503 the original match data will be restored, so subexpression
1504 matches are accessible using (match-string n link).
1505 For more examples, see the system specific constants
1506 `org-file-apps-defaults-macosx'
1507 `org-file-apps-defaults-windowsnt'
1508 `org-file-apps-defaults-gnu'."
1509 :group 'org-link-follow
1510 :type '(repeat
1511 (cons (choice :value ""
1512 (string :tag "Extension")
1513 (const :tag "System command to open files" system)
1514 (const :tag "Default for unrecognized files" t)
1515 (const :tag "Remote file" remote)
1516 (const :tag "Links to a directory" directory)
1517 (const :tag "Any files that have Emacs modes"
1518 auto-mode))
1519 (choice :value ""
1520 (const :tag "Visit with Emacs" emacs)
1521 (const :tag "Use default" default)
1522 (const :tag "Use the system command" system)
1523 (string :tag "Command")
1524 (sexp :tag "Lisp form")))))
1525
1526 (defgroup org-refile nil
1527 "Options concerning refiling entries in Org-mode."
1528 :tag "Org Refile"
1529 :group 'org)
1530
1531 (defcustom org-directory "~/org"
1532 "Directory with org files.
1533 This is just a default location to look for Org files. There is no need
1534 at all to put your files into this directory. It is only used in the
1535 following situations:
1536
1537 1. When a remember template specifies a target file that is not an
1538 absolute path. The path will then be interpreted relative to
1539 `org-directory'
1540 2. When a remember note is filed away in an interactive way (when exiting the
1541 note buffer with `C-1 C-c C-c'. The user is prompted for an org file,
1542 with `org-directory' as the default path."
1543 :group 'org-refile
1544 :group 'org-remember
1545 :type 'directory)
1546
1547 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1548 "Default target for storing notes.
1549 Used by the hooks for remember.el. This can be a string, or nil to mean
1550 the value of `remember-data-file'.
1551 You can set this on a per-template basis with the variable
1552 `org-remember-templates'."
1553 :group 'org-refile
1554 :group 'org-remember
1555 :type '(choice
1556 (const :tag "Default from remember-data-file" nil)
1557 file))
1558
1559 (defcustom org-goto-interface 'outline
1560 "The default interface to be used for `org-goto'.
1561 Allowed values are:
1562 outline The interface shows an outline of the relevant file
1563 and the correct heading is found by moving through
1564 the outline or by searching with incremental search.
1565 outline-path-completion Headlines in the current buffer are offered via
1566 completion. This is the interface also used by
1567 the refile command."
1568 :group 'org-refile
1569 :type '(choice
1570 (const :tag "Outline" outline)
1571 (const :tag "Outline-path-completion" outline-path-completion)))
1572
1573 (defcustom org-goto-max-level 5
1574 "Maximum level to be considered when running org-goto with refile interface."
1575 :group 'org-refile
1576 :type 'integer)
1577
1578 (defcustom org-reverse-note-order nil
1579 "Non-nil means store new notes at the beginning of a file or entry.
1580 When nil, new notes will be filed to the end of a file or entry.
1581 This can also be a list with cons cells of regular expressions that
1582 are matched against file names, and values."
1583 :group 'org-remember
1584 :group 'org-refile
1585 :type '(choice
1586 (const :tag "Reverse always" t)
1587 (const :tag "Reverse never" nil)
1588 (repeat :tag "By file name regexp"
1589 (cons regexp boolean))))
1590
1591 (defcustom org-log-refile nil
1592 "Information to record when a task is refiled.
1593
1594 Possible values are:
1595
1596 nil Don't add anything
1597 time Add a time stamp to the task
1598 note Prompt for a note and add it with template `org-log-note-headings'
1599
1600 This option can also be set with on a per-file-basis with
1601
1602 #+STARTUP: nologrefile
1603 #+STARTUP: logrefile
1604 #+STARTUP: lognoterefile
1605
1606 You can have local logging settings for a subtree by setting the LOGGING
1607 property to one or more of these keywords.
1608
1609 When bulk-refiling from the agenda, the value `note' is forbidden and
1610 will temporarily be changed to `time'."
1611 :group 'org-refile
1612 :group 'org-progress
1613 :type '(choice
1614 (const :tag "No logging" nil)
1615 (const :tag "Record timestamp" time)
1616 (const :tag "Record timestamp with note." note)))
1617
1618 (defcustom org-refile-targets nil
1619 "Targets for refiling entries with \\[org-refile].
1620 This is list of cons cells. Each cell contains:
1621 - a specification of the files to be considered, either a list of files,
1622 or a symbol whose function or variable value will be used to retrieve
1623 a file name or a list of file names. If you use `org-agenda-files' for
1624 that, all agenda files will be scanned for targets. Nil means consider
1625 headings in the current buffer.
1626 - A specification of how to find candidate refile targets. This may be
1627 any of:
1628 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1629 This tag has to be present in all target headlines, inheritance will
1630 not be considered.
1631 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1632 todo keyword.
1633 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1634 headlines that are refiling targets.
1635 - a cons cell (:level . N). Any headline of level N is considered a target.
1636 Note that, when `org-odd-levels-only' is set, level corresponds to
1637 order in hierarchy, not to the number of stars.
1638 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1639 Note that, when `org-odd-levels-only' is set, level corresponds to
1640 order in hierarchy, not to the number of stars.
1641
1642 You can set the variable `org-refile-target-verify-function' to a function
1643 to verify each headline found by the simple critery above.
1644
1645 When this variable is nil, all top-level headlines in the current buffer
1646 are used, equivalent to the value `((nil . (:level . 1))'."
1647 :group 'org-refile
1648 :type '(repeat
1649 (cons
1650 (choice :value org-agenda-files
1651 (const :tag "All agenda files" org-agenda-files)
1652 (const :tag "Current buffer" nil)
1653 (function) (variable) (file))
1654 (choice :tag "Identify target headline by"
1655 (cons :tag "Specific tag" (const :value :tag) (string))
1656 (cons :tag "TODO keyword" (const :value :todo) (string))
1657 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1658 (cons :tag "Level number" (const :value :level) (integer))
1659 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1660
1661 (defcustom org-refile-target-verify-function nil
1662 "Function to verify if the headline at point should be a refile target.
1663 The function will be called without arguments, with point at the
1664 beginning of the headline. It should return t and leave point
1665 where it is if the headline is a valid target for refiling.
1666
1667 If the target should not be selected, the function must return nil.
1668 In addition to this, it may move point to a place from where the search
1669 should be continued. For example, the function may decide that the entire
1670 subtree of the current entry should be excluded and move point to the end
1671 of the subtree."
1672 :group 'org-refile
1673 :type 'function)
1674
1675 (defcustom org-refile-use-outline-path nil
1676 "Non-nil means provide refile targets as paths.
1677 So a level 3 headline will be available as level1/level2/level3.
1678
1679 When the value is `file', also include the file name (without directory)
1680 into the path. In this case, you can also stop the completion after
1681 the file name, to get entries inserted as top level in the file.
1682
1683 When `full-file-path', include the full file path."
1684 :group 'org-refile
1685 :type '(choice
1686 (const :tag "Not" nil)
1687 (const :tag "Yes" t)
1688 (const :tag "Start with file name" file)
1689 (const :tag "Start with full file path" full-file-path)))
1690
1691 (defcustom org-outline-path-complete-in-steps t
1692 "Non-nil means complete the outline path in hierarchical steps.
1693 When Org-mode uses the refile interface to select an outline path
1694 \(see variable `org-refile-use-outline-path'), the completion of
1695 the path can be done is a single go, or if can be done in steps down
1696 the headline hierarchy. Going in steps is probably the best if you
1697 do not use a special completion package like `ido' or `icicles'.
1698 However, when using these packages, going in one step can be very
1699 fast, while still showing the whole path to the entry."
1700 :group 'org-refile
1701 :type 'boolean)
1702
1703 (defcustom org-refile-allow-creating-parent-nodes nil
1704 "Non-nil means allow to create new nodes as refile targets.
1705 New nodes are then created by adding \"/new node name\" to the completion
1706 of an existing node. When the value of this variable is `confirm',
1707 new node creation must be confirmed by the user (recommended)
1708 When nil, the completion must match an existing entry.
1709
1710 Note that, if the new heading is not seen by the criteria
1711 listed in `org-refile-targets', multiple instances of the same
1712 heading would be created by trying again to file under the new
1713 heading."
1714 :group 'org-refile
1715 :type '(choice
1716 (const :tag "Never" nil)
1717 (const :tag "Always" t)
1718 (const :tag "Prompt for confirmation" confirm)))
1719
1720 (defgroup org-todo nil
1721 "Options concerning TODO items in Org-mode."
1722 :tag "Org TODO"
1723 :group 'org)
1724
1725 (defgroup org-progress nil
1726 "Options concerning Progress logging in Org-mode."
1727 :tag "Org Progress"
1728 :group 'org-time)
1729
1730 (defvar org-todo-interpretation-widgets
1731 '(
1732 (:tag "Sequence (cycling hits every state)" sequence)
1733 (:tag "Type (cycling directly to DONE)" type))
1734 "The available interpretation symbols for customizing
1735 `org-todo-keywords'.
1736 Interested libraries should add to this list.")
1737
1738 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1739 "List of TODO entry keyword sequences and their interpretation.
1740 \\<org-mode-map>This is a list of sequences.
1741
1742 Each sequence starts with a symbol, either `sequence' or `type',
1743 indicating if the keywords should be interpreted as a sequence of
1744 action steps, or as different types of TODO items. The first
1745 keywords are states requiring action - these states will select a headline
1746 for inclusion into the global TODO list Org-mode produces. If one of
1747 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1748 signify that no further action is necessary. If \"|\" is not found,
1749 the last keyword is treated as the only DONE state of the sequence.
1750
1751 The command \\[org-todo] cycles an entry through these states, and one
1752 additional state where no keyword is present. For details about this
1753 cycling, see the manual.
1754
1755 TODO keywords and interpretation can also be set on a per-file basis with
1756 the special #+SEQ_TODO and #+TYP_TODO lines.
1757
1758 Each keyword can optionally specify a character for fast state selection
1759 \(in combination with the variable `org-use-fast-todo-selection')
1760 and specifiers for state change logging, using the same syntax
1761 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1762 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1763 indicates to record a time stamp each time this state is selected.
1764
1765 Each keyword may also specify if a timestamp or a note should be
1766 recorded when entering or leaving the state, by adding additional
1767 characters in the parenthesis after the keyword. This looks like this:
1768 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1769 record only the time of the state change. With X and Y being either
1770 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1771 Y when leaving the state if and only if the *target* state does not
1772 define X. You may omit any of the fast-selection key or X or /Y,
1773 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1774
1775 For backward compatibility, this variable may also be just a list
1776 of keywords - in this case the interpretation (sequence or type) will be
1777 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1778 :group 'org-todo
1779 :group 'org-keywords
1780 :type '(choice
1781 (repeat :tag "Old syntax, just keywords"
1782 (string :tag "Keyword"))
1783 (repeat :tag "New syntax"
1784 (cons
1785 (choice
1786 :tag "Interpretation"
1787 ;;Quick and dirty way to see
1788 ;;`org-todo-interpretations'. This takes the
1789 ;;place of item arguments
1790 :convert-widget
1791 (lambda (widget)
1792 (widget-put widget
1793 :args (mapcar
1794 #'(lambda (x)
1795 (widget-convert
1796 (cons 'const x)))
1797 org-todo-interpretation-widgets))
1798 widget))
1799 (repeat
1800 (string :tag "Keyword"))))))
1801
1802 (defvar org-todo-keywords-1 nil
1803 "All TODO and DONE keywords active in a buffer.")
1804 (make-variable-buffer-local 'org-todo-keywords-1)
1805 (defvar org-todo-keywords-for-agenda nil)
1806 (defvar org-done-keywords-for-agenda nil)
1807 (defvar org-drawers-for-agenda nil)
1808 (defvar org-todo-keyword-alist-for-agenda nil)
1809 (defvar org-tag-alist-for-agenda nil)
1810 (defvar org-agenda-contributing-files nil)
1811 (defvar org-not-done-keywords nil)
1812 (make-variable-buffer-local 'org-not-done-keywords)
1813 (defvar org-done-keywords nil)
1814 (make-variable-buffer-local 'org-done-keywords)
1815 (defvar org-todo-heads nil)
1816 (make-variable-buffer-local 'org-todo-heads)
1817 (defvar org-todo-sets nil)
1818 (make-variable-buffer-local 'org-todo-sets)
1819 (defvar org-todo-log-states nil)
1820 (make-variable-buffer-local 'org-todo-log-states)
1821 (defvar org-todo-kwd-alist nil)
1822 (make-variable-buffer-local 'org-todo-kwd-alist)
1823 (defvar org-todo-key-alist nil)
1824 (make-variable-buffer-local 'org-todo-key-alist)
1825 (defvar org-todo-key-trigger nil)
1826 (make-variable-buffer-local 'org-todo-key-trigger)
1827
1828 (defcustom org-todo-interpretation 'sequence
1829 "Controls how TODO keywords are interpreted.
1830 This variable is in principle obsolete and is only used for
1831 backward compatibility, if the interpretation of todo keywords is
1832 not given already in `org-todo-keywords'. See that variable for
1833 more information."
1834 :group 'org-todo
1835 :group 'org-keywords
1836 :type '(choice (const sequence)
1837 (const type)))
1838
1839 (defcustom org-use-fast-todo-selection t
1840 "Non-nil means use the fast todo selection scheme with C-c C-t.
1841 This variable describes if and under what circumstances the cycling
1842 mechanism for TODO keywords will be replaced by a single-key, direct
1843 selection scheme.
1844
1845 When nil, fast selection is never used.
1846
1847 When the symbol `prefix', it will be used when `org-todo' is called with
1848 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1849 in an agenda buffer.
1850
1851 When t, fast selection is used by default. In this case, the prefix
1852 argument forces cycling instead.
1853
1854 In all cases, the special interface is only used if access keys have actually
1855 been assigned by the user, i.e. if keywords in the configuration are followed
1856 by a letter in parenthesis, like TODO(t)."
1857 :group 'org-todo
1858 :type '(choice
1859 (const :tag "Never" nil)
1860 (const :tag "By default" t)
1861 (const :tag "Only with C-u C-c C-t" prefix)))
1862
1863 (defcustom org-provide-todo-statistics t
1864 "Non-nil means update todo statistics after insert and toggle.
1865 ALL-HEADLINES means update todo statistics by including headlines
1866 with no TODO keyword as well, counting them as not done.
1867 A list of TODO keywords means the same, but skip keywords that are
1868 not in this list.
1869
1870 When this is set, todo statistics is updated in the parent of the
1871 current entry each time a todo state is changed."
1872 :group 'org-todo
1873 :type '(choice
1874 (const :tag "Yes, only for TODO entries" t)
1875 (const :tag "Yes, including all entries" 'all-headlines)
1876 (repeat :tag "Yes, for TODOs in this list"
1877 (string :tag "TODO keyword"))
1878 (other :tag "No TODO statistics" nil)))
1879
1880 (defcustom org-hierarchical-todo-statistics t
1881 "Non-nil means TODO statistics covers just direct children.
1882 When nil, all entries in the subtree are considered.
1883 This has only an effect if `org-provide-todo-statistics' is set.
1884 To set this to nil for only a single subtree, use a COOKIE_DATA
1885 property and include the word \"recursive\" into the value."
1886 :group 'org-todo
1887 :type 'boolean)
1888
1889 (defcustom org-after-todo-state-change-hook nil
1890 "Hook which is run after the state of a TODO item was changed.
1891 The new state (a string with a TODO keyword, or nil) is available in the
1892 Lisp variable `state'."
1893 :group 'org-todo
1894 :type 'hook)
1895
1896 (defvar org-blocker-hook nil
1897 "Hook for functions that are allowed to block a state change.
1898
1899 Each function gets as its single argument a property list, see
1900 `org-trigger-hook' for more information about this list.
1901
1902 If any of the functions in this hook returns nil, the state change
1903 is blocked.")
1904
1905 (defvar org-trigger-hook nil
1906 "Hook for functions that are triggered by a state change.
1907
1908 Each function gets as its single argument a property list with at least
1909 the following elements:
1910
1911 (:type type-of-change :position pos-at-entry-start
1912 :from old-state :to new-state)
1913
1914 Depending on the type, more properties may be present.
1915
1916 This mechanism is currently implemented for:
1917
1918 TODO state changes
1919 ------------------
1920 :type todo-state-change
1921 :from previous state (keyword as a string), or nil, or a symbol
1922 'todo' or 'done', to indicate the general type of state.
1923 :to new state, like in :from")
1924
1925 (defcustom org-enforce-todo-dependencies nil
1926 "Non-nil means undone TODO entries will block switching the parent to DONE.
1927 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1928 be blocked if any prior sibling is not yet done.
1929 Finally, if the parent is blocked because of ordered siblings of its own,
1930 the child will also be blocked.
1931 This variable needs to be set before org.el is loaded, and you need to
1932 restart Emacs after a change to make the change effective. The only way
1933 to change is while Emacs is running is through the customize interface."
1934 :set (lambda (var val)
1935 (set var val)
1936 (if val
1937 (add-hook 'org-blocker-hook
1938 'org-block-todo-from-children-or-siblings-or-parent)
1939 (remove-hook 'org-blocker-hook
1940 'org-block-todo-from-children-or-siblings-or-parent)))
1941 :group 'org-todo
1942 :type 'boolean)
1943
1944 (defcustom org-enforce-todo-checkbox-dependencies nil
1945 "Non-nil means unchecked boxes will block switching the parent to DONE.
1946 When this is nil, checkboxes have no influence on switching TODO states.
1947 When non-nil, you first need to check off all check boxes before the TODO
1948 entry can be switched to DONE.
1949 This variable needs to be set before org.el is loaded, and you need to
1950 restart Emacs after a change to make the change effective. The only way
1951 to change is while Emacs is running is through the customize interface."
1952 :set (lambda (var val)
1953 (set var val)
1954 (if val
1955 (add-hook 'org-blocker-hook
1956 'org-block-todo-from-checkboxes)
1957 (remove-hook 'org-blocker-hook
1958 'org-block-todo-from-checkboxes)))
1959 :group 'org-todo
1960 :type 'boolean)
1961
1962 (defcustom org-treat-insert-todo-heading-as-state-change nil
1963 "Non-nil means inserting a TODO heading is treated as state change.
1964 So when the command \\[org-insert-todo-heading] is used, state change
1965 logging will apply if appropriate. When nil, the new TODO item will
1966 be inserted directly, and no logging will take place."
1967 :group 'org-todo
1968 :type 'boolean)
1969
1970 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1971 "Non-nil means switching TODO states with S-cursor counts as state change.
1972 This is the default behavior. However, setting this to nil allows a
1973 convenient way to select a TODO state and bypass any logging associated
1974 with that."
1975 :group 'org-todo
1976 :type 'boolean)
1977
1978 (defcustom org-todo-state-tags-triggers nil
1979 "Tag changes that should be triggered by TODO state changes.
1980 This is a list. Each entry is
1981
1982 (state-change (tag . flag) .......)
1983
1984 State-change can be a string with a state, and empty string to indicate the
1985 state that has no TODO keyword, or it can be one of the symbols `todo'
1986 or `done', meaning any not-done or done state, respectively."
1987 :group 'org-todo
1988 :group 'org-tags
1989 :type '(repeat
1990 (cons (choice :tag "When changing to"
1991 (const :tag "Not-done state" todo)
1992 (const :tag "Done state" done)
1993 (string :tag "State"))
1994 (repeat
1995 (cons :tag "Tag action"
1996 (string :tag "Tag")
1997 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1998
1999 (defcustom org-log-done nil
2000 "Information to record when a task moves to the DONE state.
2001
2002 Possible values are:
2003
2004 nil Don't add anything, just change the keyword
2005 time Add a time stamp to the task
2006 note Prompt for a note and add it with template `org-log-note-headings'
2007
2008 This option can also be set with on a per-file-basis with
2009
2010 #+STARTUP: nologdone
2011 #+STARTUP: logdone
2012 #+STARTUP: lognotedone
2013
2014 You can have local logging settings for a subtree by setting the LOGGING
2015 property to one or more of these keywords."
2016 :group 'org-todo
2017 :group 'org-progress
2018 :type '(choice
2019 (const :tag "No logging" nil)
2020 (const :tag "Record CLOSED timestamp" time)
2021 (const :tag "Record CLOSED timestamp with note." note)))
2022
2023 ;; Normalize old uses of org-log-done.
2024 (cond
2025 ((eq org-log-done t) (setq org-log-done 'time))
2026 ((and (listp org-log-done) (memq 'done org-log-done))
2027 (setq org-log-done 'note)))
2028
2029 (defcustom org-log-reschedule nil
2030 "Information to record when the scheduling date of a tasks is modified.
2031
2032 Possible values are:
2033
2034 nil Don't add anything, just change the date
2035 time Add a time stamp to the task
2036 note Prompt for a note and add it with template `org-log-note-headings'
2037
2038 This option can also be set with on a per-file-basis with
2039
2040 #+STARTUP: nologreschedule
2041 #+STARTUP: logreschedule
2042 #+STARTUP: lognotereschedule"
2043 :group 'org-todo
2044 :group 'org-progress
2045 :type '(choice
2046 (const :tag "No logging" nil)
2047 (const :tag "Record timestamp" time)
2048 (const :tag "Record timestamp with note." note)))
2049
2050 (defcustom org-log-redeadline nil
2051 "Information to record when the deadline date of a tasks is modified.
2052
2053 Possible values are:
2054
2055 nil Don't add anything, just change the date
2056 time Add a time stamp to the task
2057 note Prompt for a note and add it with template `org-log-note-headings'
2058
2059 This option can also be set with on a per-file-basis with
2060
2061 #+STARTUP: nologredeadline
2062 #+STARTUP: logredeadline
2063 #+STARTUP: lognoteredeadline
2064
2065 You can have local logging settings for a subtree by setting the LOGGING
2066 property to one or more of these keywords."
2067 :group 'org-todo
2068 :group 'org-progress
2069 :type '(choice
2070 (const :tag "No logging" nil)
2071 (const :tag "Record timestamp" time)
2072 (const :tag "Record timestamp with note." note)))
2073
2074 (defcustom org-log-note-clock-out nil
2075 "Non-nil means record a note when clocking out of an item.
2076 This can also be configured on a per-file basis by adding one of
2077 the following lines anywhere in the buffer:
2078
2079 #+STARTUP: lognoteclock-out
2080 #+STARTUP: nolognoteclock-out"
2081 :group 'org-todo
2082 :group 'org-progress
2083 :type 'boolean)
2084
2085 (defcustom org-log-done-with-time t
2086 "Non-nil means the CLOSED time stamp will contain date and time.
2087 When nil, only the date will be recorded."
2088 :group 'org-progress
2089 :type 'boolean)
2090
2091 (defcustom org-log-note-headings
2092 '((done . "CLOSING NOTE %t")
2093 (state . "State %-12s from %-12S %t")
2094 (note . "Note taken on %t")
2095 (reschedule . "Rescheduled from %S on %t")
2096 (delschedule . "Not scheduled, was %S on %t")
2097 (redeadline . "New deadline from %S on %t")
2098 (deldeadline . "Removed deadline, was %S on %t")
2099 (refile . "Refiled on %t")
2100 (clock-out . ""))
2101 "Headings for notes added to entries.
2102 The value is an alist, with the car being a symbol indicating the note
2103 context, and the cdr is the heading to be used. The heading may also be the
2104 empty string.
2105 %t in the heading will be replaced by a time stamp.
2106 %s will be replaced by the new TODO state, in double quotes.
2107 %S will be replaced by the old TODO state, in double quotes.
2108 %u will be replaced by the user name.
2109 %U will be replaced by the full user name.
2110
2111 In fact, it is not a good idea to change the `state' entry, because
2112 agenda log mode depends on the format of these entries."
2113 :group 'org-todo
2114 :group 'org-progress
2115 :type '(list :greedy t
2116 (cons (const :tag "Heading when closing an item" done) string)
2117 (cons (const :tag
2118 "Heading when changing todo state (todo sequence only)"
2119 state) string)
2120 (cons (const :tag "Heading when just taking a note" note) string)
2121 (cons (const :tag "Heading when clocking out" clock-out) string)
2122 (cons (const :tag "Heading when an item is no longer scheduled" delschedule) string)
2123 (cons (const :tag "Heading when rescheduling" reschedule) string)
2124 (cons (const :tag "Heading when changing deadline" redeadline) string)
2125 (cons (const :tag "Heading when deleting a deadline" deldeadline) string)
2126 (cons (const :tag "Heading when refiling" refile) string)))
2127
2128 (unless (assq 'note org-log-note-headings)
2129 (push '(note . "%t") org-log-note-headings))
2130
2131 (defcustom org-log-into-drawer nil
2132 "Non-nil means insert state change notes and time stamps into a drawer.
2133 When nil, state changes notes will be inserted after the headline and
2134 any scheduling and clock lines, but not inside a drawer.
2135
2136 The value of this variable should be the name of the drawer to use.
2137 LOGBOOK is proposed at the default drawer for this purpose, you can
2138 also set this to a string to define the drawer of your choice.
2139
2140 A value of t is also allowed, representing \"LOGBOOK\".
2141
2142 If this variable is set, `org-log-state-notes-insert-after-drawers'
2143 will be ignored.
2144
2145 You can set the property LOG_INTO_DRAWER to overrule this setting for
2146 a subtree."
2147 :group 'org-todo
2148 :group 'org-progress
2149 :type '(choice
2150 (const :tag "Not into a drawer" nil)
2151 (const :tag "LOGBOOK" t)
2152 (string :tag "Other")))
2153
2154 (if (fboundp 'defvaralias)
2155 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
2156
2157 (defun org-log-into-drawer ()
2158 "Return the value of `org-log-into-drawer', but let properties overrule.
2159 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
2160 used instead of the default value."
2161 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
2162 (cond
2163 ((or (not p) (equal p "nil")) org-log-into-drawer)
2164 ((equal p "t") "LOGBOOK")
2165 (t p))))
2166
2167 (defcustom org-log-state-notes-insert-after-drawers nil
2168 "Non-nil means insert state change notes after any drawers in entry.
2169 Only the drawers that *immediately* follow the headline and the
2170 deadline/scheduled line are skipped.
2171 When nil, insert notes right after the heading and perhaps the line
2172 with deadline/scheduling if present.
2173
2174 This variable will have no effect if `org-log-into-drawer' is
2175 set."
2176 :group 'org-todo
2177 :group 'org-progress
2178 :type 'boolean)
2179
2180 (defcustom org-log-states-order-reversed t
2181 "Non-nil means the latest state note will be directly after heading.
2182 When nil, the state change notes will be ordered according to time."
2183 :group 'org-todo
2184 :group 'org-progress
2185 :type 'boolean)
2186
2187 (defcustom org-log-repeat 'time
2188 "Non-nil means record moving through the DONE state when triggering repeat.
2189 An auto-repeating task is immediately switched back to TODO when
2190 marked DONE. If you are not logging state changes (by adding \"@\"
2191 or \"!\" to the TODO keyword definition), or set `org-log-done' to
2192 record a closing note, there will be no record of the task moving
2193 through DONE. This variable forces taking a note anyway.
2194
2195 nil Don't force a record
2196 time Record a time stamp
2197 note Record a note
2198
2199 This option can also be set with on a per-file-basis with
2200
2201 #+STARTUP: logrepeat
2202 #+STARTUP: lognoterepeat
2203 #+STARTUP: nologrepeat
2204
2205 You can have local logging settings for a subtree by setting the LOGGING
2206 property to one or more of these keywords."
2207 :group 'org-todo
2208 :group 'org-progress
2209 :type '(choice
2210 (const :tag "Don't force a record" nil)
2211 (const :tag "Force recording the DONE state" time)
2212 (const :tag "Force recording a note with the DONE state" note)))
2213
2214
2215 (defgroup org-priorities nil
2216 "Priorities in Org-mode."
2217 :tag "Org Priorities"
2218 :group 'org-todo)
2219
2220 (defcustom org-enable-priority-commands t
2221 "Non-nil means priority commands are active.
2222 When nil, these commands will be disabled, so that you never accidentally
2223 set a priority."
2224 :group 'org-priorities
2225 :type 'boolean)
2226
2227 (defcustom org-highest-priority ?A
2228 "The highest priority of TODO items. A character like ?A, ?B etc.
2229 Must have a smaller ASCII number than `org-lowest-priority'."
2230 :group 'org-priorities
2231 :type 'character)
2232
2233 (defcustom org-lowest-priority ?C
2234 "The lowest priority of TODO items. A character like ?A, ?B etc.
2235 Must have a larger ASCII number than `org-highest-priority'."
2236 :group 'org-priorities
2237 :type 'character)
2238
2239 (defcustom org-default-priority ?B
2240 "The default priority of TODO items.
2241 This is the priority an item get if no explicit priority is given."
2242 :group 'org-priorities
2243 :type 'character)
2244
2245 (defcustom org-priority-start-cycle-with-default t
2246 "Non-nil means start with default priority when starting to cycle.
2247 When this is nil, the first step in the cycle will be (depending on the
2248 command used) one higher or lower that the default priority."
2249 :group 'org-priorities
2250 :type 'boolean)
2251
2252 (defgroup org-time nil
2253 "Options concerning time stamps and deadlines in Org-mode."
2254 :tag "Org Time"
2255 :group 'org)
2256
2257 (defcustom org-insert-labeled-timestamps-at-point nil
2258 "Non-nil means SCHEDULED and DEADLINE timestamps are inserted at point.
2259 When nil, these labeled time stamps are forces into the second line of an
2260 entry, just after the headline. When scheduling from the global TODO list,
2261 the time stamp will always be forced into the second line."
2262 :group 'org-time
2263 :type 'boolean)
2264
2265 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2266 "Formats for `format-time-string' which are used for time stamps.
2267 It is not recommended to change this constant.")
2268
2269 (defcustom org-time-stamp-rounding-minutes '(0 5)
2270 "Number of minutes to round time stamps to.
2271 These are two values, the first applies when first creating a time stamp.
2272 The second applies when changing it with the commands `S-up' and `S-down'.
2273 When changing the time stamp, this means that it will change in steps
2274 of N minutes, as given by the second value.
2275
2276 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2277 numbers should be factors of 60, so for example 5, 10, 15.
2278
2279 When this is larger than 1, you can still force an exact time-stamp by using
2280 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2281 and by using a prefix arg to `S-up/down' to specify the exact number
2282 of minutes to shift."
2283 :group 'org-time
2284 :get '(lambda (var) ; Make sure all entries have 5 elements
2285 (if (integerp (default-value var))
2286 (list (default-value var) 5)
2287 (default-value var)))
2288 :type '(list
2289 (integer :tag "when inserting times")
2290 (integer :tag "when modifying times")))
2291
2292 ;; Normalize old customizations of this variable.
2293 (when (integerp org-time-stamp-rounding-minutes)
2294 (setq org-time-stamp-rounding-minutes
2295 (list org-time-stamp-rounding-minutes
2296 org-time-stamp-rounding-minutes)))
2297
2298 (defcustom org-display-custom-times nil
2299 "Non-nil means overlay custom formats over all time stamps.
2300 The formats are defined through the variable `org-time-stamp-custom-formats'.
2301 To turn this on on a per-file basis, insert anywhere in the file:
2302 #+STARTUP: customtime"
2303 :group 'org-time
2304 :set 'set-default
2305 :type 'sexp)
2306 (make-variable-buffer-local 'org-display-custom-times)
2307
2308 (defcustom org-time-stamp-custom-formats
2309 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2310 "Custom formats for time stamps. See `format-time-string' for the syntax.
2311 These are overlayed over the default ISO format if the variable
2312 `org-display-custom-times' is set. Time like %H:%M should be at the
2313 end of the second format. The custom formats are also honored by export
2314 commands, if custom time display is turned on at the time of export."
2315 :group 'org-time
2316 :type 'sexp)
2317
2318 (defun org-time-stamp-format (&optional long inactive)
2319 "Get the right format for a time string."
2320 (let ((f (if long (cdr org-time-stamp-formats)
2321 (car org-time-stamp-formats))))
2322 (if inactive
2323 (concat "[" (substring f 1 -1) "]")
2324 f)))
2325
2326 (defcustom org-time-clocksum-format "%d:%02d"
2327 "The format string used when creating CLOCKSUM lines, or when
2328 org-mode generates a time duration."
2329 :group 'org-time
2330 :type 'string)
2331
2332 (defcustom org-time-clocksum-use-fractional nil
2333 "If non-nil, \\[org-clock-display] uses fractional times.
2334 org-mode generates a time duration."
2335 :group 'org-time
2336 :type 'boolean)
2337
2338 (defcustom org-time-clocksum-fractional-format "%.2f"
2339 "The format string used when creating CLOCKSUM lines, or when
2340 org-mode generates a time duration."
2341 :group 'org-time
2342 :type 'string)
2343
2344 (defcustom org-deadline-warning-days 14
2345 "No. of days before expiration during which a deadline becomes active.
2346 This variable governs the display in sparse trees and in the agenda.
2347 When 0 or negative, it means use this number (the absolute value of it)
2348 even if a deadline has a different individual lead time specified.
2349
2350 Custom commands can set this variable in the options section."
2351 :group 'org-time
2352 :group 'org-agenda-daily/weekly
2353 :type 'integer)
2354
2355 (defcustom org-read-date-prefer-future t
2356 "Non-nil means assume future for incomplete date input from user.
2357 This affects the following situations:
2358 1. The user gives a month but not a year.
2359 For example, if it is april and you enter \"feb 2\", this will be read
2360 as feb 2, *next* year. \"May 5\", however, will be this year.
2361 2. The user gives a day, but no month.
2362 For example, if today is the 15th, and you enter \"3\", Org-mode will
2363 read this as the third of *next* month. However, if you enter \"17\",
2364 it will be considered as *this* month.
2365
2366 If you set this variable to the symbol `time', then also the following
2367 will work:
2368
2369 3. If the user gives a time, but no day. If the time is before now,
2370 to will be interpreted as tomorrow.
2371
2372 Currently none of this works for ISO week specifications.
2373
2374 When this option is nil, the current day, month and year will always be
2375 used as defaults."
2376 :group 'org-time
2377 :type '(choice
2378 (const :tag "Never" nil)
2379 (const :tag "Check month and day" t)
2380 (const :tag "Check month, day, and time" time)))
2381
2382 (defcustom org-read-date-display-live t
2383 "Non-nil means display current interpretation of date prompt live.
2384 This display will be in an overlay, in the minibuffer."
2385 :group 'org-time
2386 :type 'boolean)
2387
2388 (defcustom org-read-date-popup-calendar t
2389 "Non-nil means pop up a calendar when prompting for a date.
2390 In the calendar, the date can be selected with mouse-1. However, the
2391 minibuffer will also be active, and you can simply enter the date as well.
2392 When nil, only the minibuffer will be available."
2393 :group 'org-time
2394 :type 'boolean)
2395 (if (fboundp 'defvaralias)
2396 (defvaralias 'org-popup-calendar-for-date-prompt
2397 'org-read-date-popup-calendar))
2398
2399 (defcustom org-read-date-minibuffer-setup-hook nil
2400 "Hook to be used to set up keys for the date/time interface.
2401 Add key definitions to `minibuffer-local-map', which will be a temporary
2402 copy."
2403 :group 'org-time
2404 :type 'hook)
2405
2406 (defcustom org-extend-today-until 0
2407 "The hour when your day really ends. Must be an integer.
2408 This has influence for the following applications:
2409 - When switching the agenda to \"today\". It it is still earlier than
2410 the time given here, the day recognized as TODAY is actually yesterday.
2411 - When a date is read from the user and it is still before the time given
2412 here, the current date and time will be assumed to be yesterday, 23:59.
2413 Also, timestamps inserted in remember templates follow this rule.
2414
2415 IMPORTANT: This is a feature whose implementation is and likely will
2416 remain incomplete. Really, it is only here because past midnight seems to
2417 be the favorite working time of John Wiegley :-)"
2418 :group 'org-time
2419 :type 'integer)
2420
2421 (defcustom org-edit-timestamp-down-means-later nil
2422 "Non-nil means S-down will increase the time in a time stamp.
2423 When nil, S-up will increase."
2424 :group 'org-time
2425 :type 'boolean)
2426
2427 (defcustom org-calendar-follow-timestamp-change t
2428 "Non-nil means make the calendar window follow timestamp changes.
2429 When a timestamp is modified and the calendar window is visible, it will be
2430 moved to the new date."
2431 :group 'org-time
2432 :type 'boolean)
2433
2434 (defgroup org-tags nil
2435 "Options concerning tags in Org-mode."
2436 :tag "Org Tags"
2437 :group 'org)
2438
2439 (defcustom org-tag-alist nil
2440 "List of tags allowed in Org-mode files.
2441 When this list is nil, Org-mode will base TAG input on what is already in the
2442 buffer.
2443 The value of this variable is an alist, the car of each entry must be a
2444 keyword as a string, the cdr may be a character that is used to select
2445 that tag through the fast-tag-selection interface.
2446 See the manual for details."
2447 :group 'org-tags
2448 :type '(repeat
2449 (choice
2450 (cons (string :tag "Tag name")
2451 (character :tag "Access char"))
2452 (list :tag "Start radio group"
2453 (const :startgroup)
2454 (option (string :tag "Group description")))
2455 (list :tag "End radio group"
2456 (const :endgroup)
2457 (option (string :tag "Group description")))
2458 (const :tag "New line" (:newline)))))
2459
2460 (defcustom org-tag-persistent-alist nil
2461 "List of tags that will always appear in all Org-mode files.
2462 This is in addition to any in buffer settings or customizations
2463 of `org-tag-alist'.
2464 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2465 The value of this variable is an alist, the car of each entry must be a
2466 keyword as a string, the cdr may be a character that is used to select
2467 that tag through the fast-tag-selection interface.
2468 See the manual for details.
2469 To disable these tags on a per-file basis, insert anywhere in the file:
2470 #+STARTUP: noptag"
2471 :group 'org-tags
2472 :type '(repeat
2473 (choice
2474 (cons (string :tag "Tag name")
2475 (character :tag "Access char"))
2476 (const :tag "Start radio group" (:startgroup))
2477 (const :tag "End radio group" (:endgroup))
2478 (const :tag "New line" (:newline)))))
2479
2480 (defcustom org-complete-tags-always-offer-all-agenda-tags nil
2481 "If non-nil, always offer completion for all tags of all agenda files.
2482 Instead of customizing this variable directly, you might want to
2483 set it locally for remember buffers, because there no list of
2484 tags in that file can be created dynamically (there are none).
2485
2486 (add-hook 'org-remember-mode-hook
2487 (lambda ()
2488 (set (make-local-variable
2489 'org-complete-tags-always-offer-all-agenda-tags)
2490 t)))"
2491 :group 'org-tags
2492 :type 'boolean)
2493
2494 (defvar org-file-tags nil
2495 "List of tags that can be inherited by all entries in the file.
2496 The tags will be inherited if the variable `org-use-tag-inheritance'
2497 says they should be.
2498 This variable is populated from #+FILETAGS lines.")
2499
2500 (defcustom org-use-fast-tag-selection 'auto
2501 "Non-nil means use fast tag selection scheme.
2502 This is a special interface to select and deselect tags with single keys.
2503 When nil, fast selection is never used.
2504 When the symbol `auto', fast selection is used if and only if selection
2505 characters for tags have been configured, either through the variable
2506 `org-tag-alist' or through a #+TAGS line in the buffer.
2507 When t, fast selection is always used and selection keys are assigned
2508 automatically if necessary."
2509 :group 'org-tags
2510 :type '(choice
2511 (const :tag "Always" t)
2512 (const :tag "Never" nil)
2513 (const :tag "When selection characters are configured" 'auto)))
2514
2515 (defcustom org-fast-tag-selection-single-key nil
2516 "Non-nil means fast tag selection exits after first change.
2517 When nil, you have to press RET to exit it.
2518 During fast tag selection, you can toggle this flag with `C-c'.
2519 This variable can also have the value `expert'. In this case, the window
2520 displaying the tags menu is not even shown, until you press C-c again."
2521 :group 'org-tags
2522 :type '(choice
2523 (const :tag "No" nil)
2524 (const :tag "Yes" t)
2525 (const :tag "Expert" expert)))
2526
2527 (defvar org-fast-tag-selection-include-todo nil
2528 "Non-nil means fast tags selection interface will also offer TODO states.
2529 This is an undocumented feature, you should not rely on it.")
2530
2531 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2532 "The column to which tags should be indented in a headline.
2533 If this number is positive, it specifies the column. If it is negative,
2534 it means that the tags should be flushright to that column. For example,
2535 -80 works well for a normal 80 character screen."
2536 :group 'org-tags
2537 :type 'integer)
2538
2539 (defcustom org-auto-align-tags t
2540 "Non-nil means realign tags after pro/demotion of TODO state change.
2541 These operations change the length of a headline and therefore shift
2542 the tags around. With this options turned on, after each such operation
2543 the tags are again aligned to `org-tags-column'."
2544 :group 'org-tags
2545 :type 'boolean)
2546
2547 (defcustom org-use-tag-inheritance t
2548 "Non-nil means tags in levels apply also for sublevels.
2549 When nil, only the tags directly given in a specific line apply there.
2550 This may also be a list of tags that should be inherited, or a regexp that
2551 matches tags that should be inherited. Additional control is possible
2552 with the variable `org-tags-exclude-from-inheritance' which gives an
2553 explicit list of tags to be excluded from inheritance., even if the value of
2554 `org-use-tag-inheritance' would select it for inheritance.
2555
2556 If this option is t, a match early-on in a tree can lead to a large
2557 number of matches in the subtree when constructing the agenda or creating
2558 a sparse tree. If you only want to see the first match in a tree during
2559 a search, check out the variable `org-tags-match-list-sublevels'."
2560 :group 'org-tags
2561 :type '(choice
2562 (const :tag "Not" nil)
2563 (const :tag "Always" t)
2564 (repeat :tag "Specific tags" (string :tag "Tag"))
2565 (regexp :tag "Tags matched by regexp")))
2566
2567 (defcustom org-tags-exclude-from-inheritance nil
2568 "List of tags that should never be inherited.
2569 This is a way to exclude a few tags from inheritance. For way to do
2570 the opposite, to actively allow inheritance for selected tags,
2571 see the variable `org-use-tag-inheritance'."
2572 :group 'org-tags
2573 :type '(repeat (string :tag "Tag")))
2574
2575 (defun org-tag-inherit-p (tag)
2576 "Check if TAG is one that should be inherited."
2577 (cond
2578 ((member tag org-tags-exclude-from-inheritance) nil)
2579 ((eq org-use-tag-inheritance t) t)
2580 ((not org-use-tag-inheritance) nil)
2581 ((stringp org-use-tag-inheritance)
2582 (string-match org-use-tag-inheritance tag))
2583 ((listp org-use-tag-inheritance)
2584 (member tag org-use-tag-inheritance))
2585 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2586
2587 (defcustom org-tags-match-list-sublevels t
2588 "Non-nil means list also sublevels of headlines matching a search.
2589 This variable applies to tags/property searches, and also to stuck
2590 projects because this search is based on a tags match as well.
2591
2592 When set to the symbol `indented', sublevels are indented with
2593 leading dots.
2594
2595 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2596 the sublevels of a headline matching a tag search often also match
2597 the same search. Listing all of them can create very long lists.
2598 Setting this variable to nil causes subtrees of a match to be skipped.
2599
2600 This variable is semi-obsolete and probably should always be true. It
2601 is better to limit inheritance to certain tags using the variables
2602 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2603 :group 'org-tags
2604 :type '(choice
2605 (const :tag "No, don't list them" nil)
2606 (const :tag "Yes, do list them" t)
2607 (const :tag "List them, indented with leading dots" indented)))
2608
2609 (defcustom org-tags-sort-function nil
2610 "When set, tags are sorted using this function as a comparator"
2611 :group 'org-tags
2612 :type '(choice
2613 (const :tag "No sorting" nil)
2614 (const :tag "Alphabetical" string<)
2615 (const :tag "Reverse alphabetical" string>)
2616 (function :tag "Custom function" nil)))
2617
2618 (defvar org-tags-history nil
2619 "History of minibuffer reads for tags.")
2620 (defvar org-last-tags-completion-table nil
2621 "The last used completion table for tags.")
2622 (defvar org-after-tags-change-hook nil
2623 "Hook that is run after the tags in a line have changed.")
2624
2625 (defgroup org-properties nil
2626 "Options concerning properties in Org-mode."
2627 :tag "Org Properties"
2628 :group 'org)
2629
2630 (defcustom org-property-format "%-10s %s"
2631 "How property key/value pairs should be formatted by `indent-line'.
2632 When `indent-line' hits a property definition, it will format the line
2633 according to this format, mainly to make sure that the values are
2634 lined-up with respect to each other."
2635 :group 'org-properties
2636 :type 'string)
2637
2638 (defcustom org-use-property-inheritance nil
2639 "Non-nil means properties apply also for sublevels.
2640
2641 This setting is chiefly used during property searches. Turning it on can
2642 cause significant overhead when doing a search, which is why it is not
2643 on by default.
2644
2645 When nil, only the properties directly given in the current entry count.
2646 When t, every property is inherited. The value may also be a list of
2647 properties that should have inheritance, or a regular expression matching
2648 properties that should be inherited.
2649
2650 However, note that some special properties use inheritance under special
2651 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2652 and the properties ending in \"_ALL\" when they are used as descriptor
2653 for valid values of a property.
2654
2655 Note for programmers:
2656 When querying an entry with `org-entry-get', you can control if inheritance
2657 should be used. By default, `org-entry-get' looks only at the local
2658 properties. You can request inheritance by setting the inherit argument
2659 to t (to force inheritance) or to `selective' (to respect the setting
2660 in this variable)."
2661 :group 'org-properties
2662 :type '(choice
2663 (const :tag "Not" nil)
2664 (const :tag "Always" t)
2665 (repeat :tag "Specific properties" (string :tag "Property"))
2666 (regexp :tag "Properties matched by regexp")))
2667
2668 (defun org-property-inherit-p (property)
2669 "Check if PROPERTY is one that should be inherited."
2670 (cond
2671 ((eq org-use-property-inheritance t) t)
2672 ((not org-use-property-inheritance) nil)
2673 ((stringp org-use-property-inheritance)
2674 (string-match org-use-property-inheritance property))
2675 ((listp org-use-property-inheritance)
2676 (member property org-use-property-inheritance))
2677 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2678
2679 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2680 "The default column format, if no other format has been defined.
2681 This variable can be set on the per-file basis by inserting a line
2682
2683 #+COLUMNS: %25ITEM ....."
2684 :group 'org-properties
2685 :type 'string)
2686
2687 (defcustom org-columns-ellipses ".."
2688 "The ellipses to be used when a field in column view is truncated.
2689 When this is the empty string, as many characters as possible are shown,
2690 but then there will be no visual indication that the field has been truncated.
2691 When this is a string of length N, the last N characters of a truncated
2692 field are replaced by this string. If the column is narrower than the
2693 ellipses string, only part of the ellipses string will be shown."
2694 :group 'org-properties
2695 :type 'string)
2696
2697 (defcustom org-columns-modify-value-for-display-function nil
2698 "Function that modifies values for display in column view.
2699 For example, it can be used to cut out a certain part from a time stamp.
2700 The function must take 2 arguments:
2701
2702 column-title The title of the column (*not* the property name)
2703 value The value that should be modified.
2704
2705 The function should return the value that should be displayed,
2706 or nil if the normal value should be used."
2707 :group 'org-properties
2708 :type 'function)
2709
2710 (defcustom org-effort-property "Effort"
2711 "The property that is being used to keep track of effort estimates.
2712 Effort estimates given in this property need to have the format H:MM."
2713 :group 'org-properties
2714 :group 'org-progress
2715 :type '(string :tag "Property"))
2716
2717 (defconst org-global-properties-fixed
2718 '(("VISIBILITY_ALL" . "folded children content all")
2719 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2720 "List of property/value pairs that can be inherited by any entry.
2721
2722 These are fixed values, for the preset properties. The user variable
2723 that can be used to add to this list is `org-global-properties'.
2724
2725 The entries in this list are cons cells where the car is a property
2726 name and cdr is a string with the value. If the value represents
2727 multiple items like an \"_ALL\" property, separate the items by
2728 spaces.")
2729
2730 (defcustom org-global-properties nil
2731 "List of property/value pairs that can be inherited by any entry.
2732
2733 This list will be combined with the constant `org-global-properties-fixed'.
2734
2735 The entries in this list are cons cells where the car is a property
2736 name and cdr is a string with the value.
2737
2738 You can set buffer-local values for the same purpose in the variable
2739 `org-file-properties' this by adding lines like
2740
2741 #+PROPERTY: NAME VALUE"
2742 :group 'org-properties
2743 :type '(repeat
2744 (cons (string :tag "Property")
2745 (string :tag "Value"))))
2746
2747 (defvar org-file-properties nil
2748 "List of property/value pairs that can be inherited by any entry.
2749 Valid for the current buffer.
2750 This variable is populated from #+PROPERTY lines.")
2751 (make-variable-buffer-local 'org-file-properties)
2752
2753 (defgroup org-agenda nil
2754 "Options concerning agenda views in Org-mode."
2755 :tag "Org Agenda"
2756 :group 'org)
2757
2758 (defvar org-category nil
2759 "Variable used by org files to set a category for agenda display.
2760 Such files should use a file variable to set it, for example
2761
2762 # -*- mode: org; org-category: \"ELisp\"
2763
2764 or contain a special line
2765
2766 #+CATEGORY: ELisp
2767
2768 If the file does not specify a category, then file's base name
2769 is used instead.")
2770 (make-variable-buffer-local 'org-category)
2771 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2772
2773 (defcustom org-agenda-files nil
2774 "The files to be used for agenda display.
2775 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2776 \\[org-remove-file]. You can also use customize to edit the list.
2777
2778 If an entry is a directory, all files in that directory that are matched by
2779 `org-agenda-file-regexp' will be part of the file list.
2780
2781 If the value of the variable is not a list but a single file name, then
2782 the list of agenda files is actually stored and maintained in that file, one
2783 agenda file per line. In this file paths can be given relative to
2784 `org-directory'. Tilde expansion and environment variable substitution
2785 are also made."
2786 :group 'org-agenda
2787 :type '(choice
2788 (repeat :tag "List of files and directories" file)
2789 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2790
2791 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2792 "Regular expression to match files for `org-agenda-files'.
2793 If any element in the list in that variable contains a directory instead
2794 of a normal file, all files in that directory that are matched by this
2795 regular expression will be included."
2796 :group 'org-agenda
2797 :type 'regexp)
2798
2799 (defcustom org-agenda-text-search-extra-files nil
2800 "List of extra files to be searched by text search commands.
2801 These files will be search in addition to the agenda files by the
2802 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2803 Note that these files will only be searched for text search commands,
2804 not for the other agenda views like todo lists, tag searches or the weekly
2805 agenda. This variable is intended to list notes and possibly archive files
2806 that should also be searched by these two commands.
2807 In fact, if the first element in the list is the symbol `agenda-archives',
2808 than all archive files of all agenda files will be added to the search
2809 scope."
2810 :group 'org-agenda
2811 :type '(set :greedy t
2812 (const :tag "Agenda Archives" agenda-archives)
2813 (repeat :inline t (file))))
2814
2815 (if (fboundp 'defvaralias)
2816 (defvaralias 'org-agenda-multi-occur-extra-files
2817 'org-agenda-text-search-extra-files))
2818
2819 (defcustom org-agenda-skip-unavailable-files nil
2820 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2821 A nil value means to remove them, after a query, from the list."
2822 :group 'org-agenda
2823 :type 'boolean)
2824
2825 (defcustom org-calendar-to-agenda-key [?c]
2826 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2827 The command `org-calendar-goto-agenda' will be bound to this key. The
2828 default is the character `c' because then `c' can be used to switch back and
2829 forth between agenda and calendar."
2830 :group 'org-agenda
2831 :type 'sexp)
2832
2833 (defcustom org-calendar-agenda-action-key [?k]
2834 "The key to be installed in `calendar-mode-map' for agenda-action.
2835 The command `org-agenda-action' will be bound to this key. The
2836 default is the character `k' because we use the same key in the agenda."
2837 :group 'org-agenda
2838 :type 'sexp)
2839
2840 (defcustom org-calendar-insert-diary-entry-key [?i]
2841 "The key to be installed in `calendar-mode-map' for adding diary entries.
2842 This option is irrelevant until `org-agenda-diary-file' has been configured
2843 to point to an Org-mode file. When that is the case, the command
2844 `org-agenda-diary-entry' will be bound to the key given here, by default
2845 `i'. In the calendar, `i' normally adds entries to `diary-file'. So
2846 if you want to continue doing this, you need to change this to a different
2847 key."
2848 :group 'org-agenda
2849 :type 'sexp)
2850
2851 (defcustom org-agenda-diary-file 'diary-file
2852 "File to which to add new entries with the `i' key in agenda and calendar.
2853 When this is the symbol `diary-file', the functionality in the Emacs
2854 calendar will be used to add entries to the `diary-file'. But when this
2855 points to a file, `org-agenda-diary-entry' will be used instead."
2856 :group 'org-agenda
2857 :type '(choice
2858 (const :tag "The standard Emacs diary file" diary-file)
2859 (file :tag "Special Org file diary entries")))
2860
2861 (eval-after-load "calendar"
2862 '(progn
2863 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2864 'org-calendar-goto-agenda)
2865 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2866 'org-agenda-action)
2867 (add-hook 'calendar-mode-hook
2868 (lambda ()
2869 (unless (eq org-agenda-diary-file 'diary-file)
2870 (define-key calendar-mode-map
2871 org-calendar-insert-diary-entry-key
2872 'org-agenda-diary-entry))))))
2873
2874 (defgroup org-latex nil
2875 "Options for embedding LaTeX code into Org-mode."
2876 :tag "Org LaTeX"
2877 :group 'org)
2878
2879 (defcustom org-format-latex-options
2880 '(:foreground default :background default :scale 1.0
2881 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2882 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2883 "Options for creating images from LaTeX fragments.
2884 This is a property list with the following properties:
2885 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2886 `default' means use the foreground of the default face.
2887 :background the background color, or \"Transparent\".
2888 `default' means use the background of the default face.
2889 :scale a scaling factor for the size of the images.
2890 :html-foreground, :html-background, :html-scale
2891 the same numbers for HTML export.
2892 :matchers a list indicating which matchers should be used to
2893 find LaTeX fragments. Valid members of this list are:
2894 \"begin\" find environments
2895 \"$1\" find single characters surrounded by $.$
2896 \"$\" find math expressions surrounded by $...$
2897 \"$$\" find math expressions surrounded by $$....$$
2898 \"\\(\" find math expressions surrounded by \\(...\\)
2899 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2900 :group 'org-latex
2901 :type 'plist)
2902
2903 (defcustom org-format-latex-signal-error t
2904 "Non-nil means signal an error when image creation of LaTeX snippets fails.
2905 When nil, just push out a message."
2906 :group 'org-latex
2907 :type 'boolean)
2908
2909 (defcustom org-format-latex-header "\\documentclass{article}
2910 \\usepackage[usenames]{color}
2911 \\usepackage{amsmath}
2912 \\usepackage[mathscr]{eucal}
2913 \\pagestyle{empty} % do not remove
2914 \[PACKAGES]
2915 \[DEFAULT-PACKAGES]
2916 % The settings below are copied from fullpage.sty
2917 \\setlength{\\textwidth}{\\paperwidth}
2918 \\addtolength{\\textwidth}{-3cm}
2919 \\setlength{\\oddsidemargin}{1.5cm}
2920 \\addtolength{\\oddsidemargin}{-2.54cm}
2921 \\setlength{\\evensidemargin}{\\oddsidemargin}
2922 \\setlength{\\textheight}{\\paperheight}
2923 \\addtolength{\\textheight}{-\\headheight}
2924 \\addtolength{\\textheight}{-\\headsep}
2925 \\addtolength{\\textheight}{-\\footskip}
2926 \\addtolength{\\textheight}{-3cm}
2927 \\setlength{\\topmargin}{1.5cm}
2928 \\addtolength{\\topmargin}{-2.54cm}"
2929 "The document header used for processing LaTeX fragments.
2930 It is imperative that this header make sure that no page number
2931 appears on the page. The package defined in the variables
2932 `org-export-latex-default-packages-alist' and `org-export-latex-packages-alist'
2933 will either replace the placeholder \"[PACKAGES]\" in this header, or they
2934 will be appended."
2935 :group 'org-latex
2936 :type 'string)
2937
2938 (defvar org-format-latex-header-extra nil)
2939
2940 ;; The following variables are defined here because is it also used
2941 ;; when formatting latex fragments. Originally it was part of the
2942 ;; LaTeX exporter, which is why the name includes "export".
2943 (defcustom org-export-latex-default-packages-alist
2944 '(("AUTO" "inputenc")
2945 ("T1" "fontenc")
2946 ("" "fixltx2e")
2947 ("" "graphicx")
2948 ("" "longtable")
2949 ("" "float")
2950 ("" "wrapfig")
2951 ("" "soul")
2952 ("" "t1enc")
2953 ("" "textcomp")
2954 ("" "marvosym")
2955 ("" "wasysym")
2956 ("" "latexsym")
2957 ("" "amssymb")
2958 ("" "hyperref")
2959 "\\tolerance=1000"
2960 )
2961 "Alist of default packages to be inserted in the header.
2962 Change this only if one of the packages here causes an incompatibility
2963 with another package you are using.
2964 The packages in this list are needed by one part or another of Org-mode
2965 to function properly.
2966
2967 - inputenc, fontenc, t1enc: for basic font and character selection
2968 - textcomp, marvosymb, wasysym, latexsym, amssym: for various symbols used
2969 for interpreting the entities in `org-entities'. You can skip some of these
2970 packages if you don't use any of the symbols in it.
2971 - graphicx: for including images
2972 - float, wrapfig: for figure placement
2973 - longtable: for long tables
2974 - hyperref: for cross references
2975
2976 Therefore you should not modify this variable unless you know what you
2977 are doing. The one reason to change it anyway is that you might be loading
2978 some other package that conflicts with one of the default packages.
2979 Each cell is of the format \( \"options\" \"package\" \)."
2980 :group 'org-export-latex
2981 :type '(repeat
2982 (choice
2983 (string :tag "A line of LaTeX")
2984 (list :tag "options/package pair"
2985 (string :tag "options")
2986 (string :tag "package")))))
2987
2988 (defcustom org-export-latex-packages-alist nil
2989 "Alist of packages to be inserted in every LaTeX the header.
2990 These will be inserted after `org-export-latex-default-packages-alist'.
2991 Each cell is of the format \( \"options\" \"package\" \).
2992 Make sure that you only lis packages here which:
2993 - you want in every file
2994 - do not conflict with the default packages in
2995 `org-export-latex-default-packages-alist'
2996 - do not conflict with the setup in `org-format-latex-header'."
2997 :group 'org-export-latex
2998 :type '(repeat
2999 (choice
3000 (string :tag "A line of LaTeX")
3001 (list :tag "options/package pair"
3002 (string :tag "options")
3003 (string :tag "package")))))
3004
3005 (defgroup org-appearance nil
3006 "Settings for Org-mode appearance."
3007 :tag "Org Appearance"
3008 :group 'org)
3009
3010 (defcustom org-level-color-stars-only nil
3011 "Non-nil means fontify only the stars in each headline.
3012 When nil, the entire headline is fontified.
3013 Changing it requires restart of `font-lock-mode' to become effective
3014 also in regions already fontified."
3015 :group 'org-appearance
3016 :type 'boolean)
3017
3018 (defcustom org-hide-leading-stars nil
3019 "Non-nil means hide the first N-1 stars in a headline.
3020 This works by using the face `org-hide' for these stars. This
3021 face is white for a light background, and black for a dark
3022 background. You may have to customize the face `org-hide' to
3023 make this work.
3024 Changing it requires restart of `font-lock-mode' to become effective
3025 also in regions already fontified.
3026 You may also set this on a per-file basis by adding one of the following
3027 lines to the buffer:
3028
3029 #+STARTUP: hidestars
3030 #+STARTUP: showstars"
3031 :group 'org-appearance
3032 :type 'boolean)
3033
3034 (defcustom org-hidden-keywords nil
3035 "List of keywords that should be hidden when typed in the org buffer.
3036 For example, add #+TITLE to this list in order to make the
3037 document title appear in the buffer without the initial #+TITLE:
3038 keyword."
3039 :group 'org-appearance
3040 :type '(set (const :tag "#+AUTHOR" author)
3041 (const :tag "#+DATE" date)
3042 (const :tag "#+EMAIL" email)
3043 (const :tag "#+TITLE" title)))
3044
3045 (defcustom org-fontify-done-headline nil
3046 "Non-nil means change the face of a headline if it is marked DONE.
3047 Normally, only the TODO/DONE keyword indicates the state of a headline.
3048 When this is non-nil, the headline after the keyword is set to the
3049 `org-headline-done' as an additional indication."
3050 :group 'org-appearance
3051 :type 'boolean)
3052
3053 (defcustom org-fontify-emphasized-text t
3054 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
3055 Changing this variable requires a restart of Emacs to take effect."
3056 :group 'org-appearance
3057 :type 'boolean)
3058
3059 (defcustom org-fontify-whole-heading-line nil
3060 "Non-nil means fontify the whole line for headings.
3061 This is useful when setting a background color for the
3062 org-level-* faces."
3063 :group 'org-appearance
3064 :type 'boolean)
3065
3066 (defcustom org-highlight-latex-fragments-and-specials nil
3067 "Non-nil means fontify what is treated specially by the exporters."
3068 :group 'org-appearance
3069 :type 'boolean)
3070
3071 (defcustom org-hide-emphasis-markers nil
3072 "Non-nil mean font-lock should hide the emphasis marker characters."
3073 :group 'org-appearance
3074 :type 'boolean)
3075
3076 (defvar org-emph-re nil
3077 "Regular expression for matching emphasis.")
3078 (defvar org-verbatim-re nil
3079 "Regular expression for matching verbatim text.")
3080 (defvar org-emphasis-regexp-components) ; defined just below
3081 (defvar org-emphasis-alist) ; defined just below
3082 (defun org-set-emph-re (var val)
3083 "Set variable and compute the emphasis regular expression."
3084 (set var val)
3085 (when (and (boundp 'org-emphasis-alist)
3086 (boundp 'org-emphasis-regexp-components)
3087 org-emphasis-alist org-emphasis-regexp-components)
3088 (let* ((e org-emphasis-regexp-components)
3089 (pre (car e))
3090 (post (nth 1 e))
3091 (border (nth 2 e))
3092 (body (nth 3 e))
3093 (nl (nth 4 e))
3094 (body1 (concat body "*?"))
3095 (markers (mapconcat 'car org-emphasis-alist ""))
3096 (vmarkers (mapconcat
3097 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
3098 org-emphasis-alist "")))
3099 ;; make sure special characters appear at the right position in the class
3100 (if (string-match "\\^" markers)
3101 (setq markers (concat (replace-match "" t t markers) "^")))
3102 (if (string-match "-" markers)
3103 (setq markers (concat (replace-match "" t t markers) "-")))
3104 (if (string-match "\\^" vmarkers)
3105 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
3106 (if (string-match "-" vmarkers)
3107 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
3108 (if (> nl 0)
3109 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
3110 (int-to-string nl) "\\}")))
3111 ;; Make the regexp
3112 (setq org-emph-re
3113 (concat "\\([" pre "]\\|^\\)"
3114 "\\("
3115 "\\([" markers "]\\)"
3116 "\\("
3117 "[^" border "]\\|"
3118 "[^" border "]"
3119 body1
3120 "[^" border "]"
3121 "\\)"
3122 "\\3\\)"
3123 "\\([" post "]\\|$\\)"))
3124 (setq org-verbatim-re
3125 (concat "\\([" pre "]\\|^\\)"
3126 "\\("
3127 "\\([" vmarkers "]\\)"
3128 "\\("
3129 "[^" border "]\\|"
3130 "[^" border "]"
3131 body1
3132 "[^" border "]"
3133 "\\)"
3134 "\\3\\)"
3135 "\\([" post "]\\|$\\)")))))
3136
3137 (defcustom org-emphasis-regexp-components
3138 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
3139 "Components used to build the regular expression for emphasis.
3140 This is a list with 6 entries. Terminology: In an emphasis string
3141 like \" *strong word* \", we call the initial space PREMATCH, the final
3142 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
3143 and \"trong wor\" is the body. The different components in this variable
3144 specify what is allowed/forbidden in each part:
3145
3146 pre Chars allowed as prematch. Beginning of line will be allowed too.
3147 post Chars allowed as postmatch. End of line will be allowed too.
3148 border The chars *forbidden* as border characters.
3149 body-regexp A regexp like \".\" to match a body character. Don't use
3150 non-shy groups here, and don't allow newline here.
3151 newline The maximum number of newlines allowed in an emphasis exp.
3152
3153 Use customize to modify this, or restart Emacs after changing it."
3154 :group 'org-appearance
3155 :set 'org-set-emph-re
3156 :type '(list
3157 (sexp :tag "Allowed chars in pre ")
3158 (sexp :tag "Allowed chars in post ")
3159 (sexp :tag "Forbidden chars in border ")
3160 (sexp :tag "Regexp for body ")
3161 (integer :tag "number of newlines allowed")
3162 (option (boolean :tag "Please ignore this button"))))
3163
3164 (defcustom org-emphasis-alist
3165 `(("*" bold "<b>" "</b>")
3166 ("/" italic "<i>" "</i>")
3167 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
3168 ("=" org-code "<code>" "</code>" verbatim)
3169 ("~" org-verbatim "<code>" "</code>" verbatim)
3170 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
3171 "<del>" "</del>")
3172 )
3173 "Special syntax for emphasized text.
3174 Text starting and ending with a special character will be emphasized, for
3175 example *bold*, _underlined_ and /italic/. This variable sets the marker
3176 characters, the face to be used by font-lock for highlighting in Org-mode
3177 Emacs buffers, and the HTML tags to be used for this.
3178 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
3179 Use customize to modify this, or restart Emacs after changing it."
3180 :group 'org-appearance
3181 :set 'org-set-emph-re
3182 :type '(repeat
3183 (list
3184 (string :tag "Marker character")
3185 (choice
3186 (face :tag "Font-lock-face")
3187 (plist :tag "Face property list"))
3188 (string :tag "HTML start tag")
3189 (string :tag "HTML end tag")
3190 (option (const verbatim)))))
3191
3192 (defvar org-protecting-blocks
3193 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
3194 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
3195 This is needed for font-lock setup.")
3196
3197 ;;; Miscellaneous options
3198
3199 (defgroup org-completion nil
3200 "Completion in Org-mode."
3201 :tag "Org Completion"
3202 :group 'org)
3203
3204 (defcustom org-completion-use-ido nil
3205 "Non-nil means use ido completion wherever possible.
3206 Note that `ido-mode' must be active for this variable to be relevant.
3207 If you decide to turn this variable on, you might well want to turn off
3208 `org-outline-path-complete-in-steps'.
3209 See also `org-completion-use-iswitchb'."
3210 :group 'org-completion
3211 :type 'boolean)
3212
3213 (defcustom org-completion-use-iswitchb nil
3214 "Non-nil means use iswitchb completion wherever possible.
3215 Note that `iswitchb-mode' must be active for this variable to be relevant.
3216 If you decide to turn this variable on, you might well want to turn off
3217 `org-outline-path-complete-in-steps'.
3218 Note that this variable has only an effect if `org-completion-use-ido' is nil."
3219 :group 'org-completion
3220 :type 'boolean)
3221
3222 (defcustom org-completion-fallback-command 'hippie-expand
3223 "The expansion command called by \\[org-complete] in normal context.
3224 Normal means no org-mode-specific context."
3225 :group 'org-completion
3226 :type 'function)
3227
3228 ;;; Functions and variables from their packages
3229 ;; Declared here to avoid compiler warnings
3230
3231 ;; XEmacs only
3232 (defvar outline-mode-menu-heading)
3233 (defvar outline-mode-menu-show)
3234 (defvar outline-mode-menu-hide)
3235 (defvar zmacs-regions) ; XEmacs regions
3236
3237 ;; Emacs only
3238 (defvar mark-active)
3239
3240 ;; Various packages
3241 (declare-function calendar-absolute-from-iso "cal-iso" (date))
3242 (declare-function calendar-forward-day "cal-move" (arg))
3243 (declare-function calendar-goto-date "cal-move" (date))
3244 (declare-function calendar-goto-today "cal-move" ())
3245 (declare-function calendar-iso-from-absolute "cal-iso" (date))
3246 (defvar calc-embedded-close-formula)
3247 (defvar calc-embedded-open-formula)
3248 (declare-function cdlatex-tab "ext:cdlatex" ())
3249 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
3250 (defvar font-lock-unfontify-region-function)
3251 (declare-function iswitchb-read-buffer "iswitchb"
3252 (prompt &optional default require-match start matches-set))
3253 (defvar iswitchb-temp-buflist)
3254 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
3255 (defvar org-agenda-tags-todo-honor-ignore-options)
3256 (declare-function org-agenda-skip "org-agenda" ())
3257 (declare-function
3258 org-format-agenda-item "org-agenda"
3259 (extra txt &optional category tags dotime noprefix remove-re habitp))
3260 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
3261 (declare-function org-agenda-change-all-lines "org-agenda"
3262 (newhead hdmarker &optional fixface just-this))
3263 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
3264 (declare-function org-agenda-maybe-redo "org-agenda" ())
3265 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
3266 (beg end))
3267 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
3268 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
3269 "org-agenda" (&optional end))
3270 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
3271 (declare-function org-indent-mode "org-indent" (&optional arg))
3272 (declare-function parse-time-string "parse-time" (string))
3273 (declare-function org-attach-reveal "org-attach" (&optional if-exists))
3274 (defvar remember-data-file)
3275 (defvar texmathp-why)
3276 (declare-function speedbar-line-directory "speedbar" (&optional depth))
3277 (declare-function table--at-cell-p "table" (position &optional object at-column))
3278
3279 (defvar w3m-current-url)
3280 (defvar w3m-current-title)
3281
3282 (defvar org-latex-regexps)
3283
3284 ;;; Autoload and prepare some org modules
3285
3286 ;; Some table stuff that needs to be defined here, because it is used
3287 ;; by the functions setting up org-mode or checking for table context.
3288
3289 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
3290 "Detects an org-type or table-type table.")
3291 (defconst org-table-line-regexp "^[ \t]*|"
3292 "Detects an org-type table line.")
3293 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
3294 "Detects an org-type table line.")
3295 (defconst org-table-hline-regexp "^[ \t]*|-"
3296 "Detects an org-type table hline.")
3297 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
3298 "Detects a table-type table hline.")
3299 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
3300 "Searching from within a table (any type) this finds the first line
3301 outside the table.")
3302
3303 ;; Autoload the functions in org-table.el that are needed by functions here.
3304
3305 (eval-and-compile
3306 (org-autoload "org-table"
3307 '(org-table-align org-table-begin org-table-blank-field
3308 org-table-convert org-table-convert-region org-table-copy-down
3309 org-table-copy-region org-table-create
3310 org-table-create-or-convert-from-region
3311 org-table-create-with-table.el org-table-current-dline
3312 org-table-cut-region org-table-delete-column org-table-edit-field
3313 org-table-edit-formulas org-table-end org-table-eval-formula
3314 org-table-export org-table-field-info
3315 org-table-get-stored-formulas org-table-goto-column
3316 org-table-hline-and-move org-table-import org-table-insert-column
3317 org-table-insert-hline org-table-insert-row org-table-iterate
3318 org-table-justify-field-maybe org-table-kill-row
3319 org-table-maybe-eval-formula org-table-maybe-recalculate-line
3320 org-table-move-column org-table-move-column-left
3321 org-table-move-column-right org-table-move-row
3322 org-table-move-row-down org-table-move-row-up
3323 org-table-next-field org-table-next-row org-table-paste-rectangle
3324 org-table-previous-field org-table-recalculate
3325 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
3326 org-table-toggle-coordinate-overlays
3327 org-table-toggle-formula-debugger org-table-wrap-region
3328 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
3329
3330 (defun org-at-table-p (&optional table-type)
3331 "Return t if the cursor is inside an org-type table.
3332 If TABLE-TYPE is non-nil, also check for table.el-type tables."
3333 (if org-enable-table-editor
3334 (save-excursion
3335 (beginning-of-line 1)
3336 (looking-at (if table-type org-table-any-line-regexp
3337 org-table-line-regexp)))
3338 nil))
3339 (defsubst org-table-p () (org-at-table-p))
3340
3341 (defun org-at-table.el-p ()
3342 "Return t if and only if we are at a table.el table."
3343 (and (org-at-table-p 'any)
3344 (save-excursion
3345 (goto-char (org-table-begin 'any))
3346 (looking-at org-table1-hline-regexp))))
3347 (defun org-table-recognize-table.el ()
3348 "If there is a table.el table nearby, recognize it and move into it."
3349 (if org-table-tab-recognizes-table.el
3350 (if (org-at-table.el-p)
3351 (progn
3352 (beginning-of-line 1)
3353 (if (looking-at org-table-dataline-regexp)
3354 nil
3355 (if (looking-at org-table1-hline-regexp)
3356 (progn
3357 (beginning-of-line 2)
3358 (if (looking-at org-table-any-border-regexp)
3359 (beginning-of-line -1)))))
3360 (if (re-search-forward "|" (org-table-end t) t)
3361 (progn
3362 (require 'table)
3363 (if (table--at-cell-p (point))
3364 t
3365 (message "recognizing table.el table...")
3366 (table-recognize-table)
3367 (message "recognizing table.el table...done")))
3368 (error "This should not happen..."))
3369 t)
3370 nil)
3371 nil))
3372
3373 (defun org-at-table-hline-p ()
3374 "Return t if the cursor is inside a hline in a table."
3375 (if org-enable-table-editor
3376 (save-excursion
3377 (beginning-of-line 1)
3378 (looking-at org-table-hline-regexp))
3379 nil))
3380
3381 (defvar org-table-clean-did-remove-column nil)
3382
3383 (defun org-table-map-tables (function)
3384 "Apply FUNCTION to the start of all tables in the buffer."
3385 (save-excursion
3386 (save-restriction
3387 (widen)
3388 (goto-char (point-min))
3389 (while (re-search-forward org-table-any-line-regexp nil t)
3390 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3391 (beginning-of-line 1)
3392 (when (looking-at org-table-line-regexp)
3393 (save-excursion (funcall function))
3394 (or (looking-at org-table-line-regexp)
3395 (forward-char 1)))
3396 (re-search-forward org-table-any-border-regexp nil 1))))
3397 (message "Mapping tables: done"))
3398
3399 ;; Declare and autoload functions from org-exp.el & Co
3400
3401 (declare-function org-default-export-plist "org-exp")
3402 (declare-function org-infile-export-plist "org-exp")
3403 (declare-function org-get-current-options "org-exp")
3404 (eval-and-compile
3405 (org-autoload "org-exp"
3406 '(org-export org-export-visible
3407 org-insert-export-options-template
3408 org-table-clean-before-export))
3409 (org-autoload "org-ascii"
3410 '(org-export-as-ascii org-export-ascii-preprocess
3411 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3412 org-export-region-as-ascii))
3413 (org-autoload "org-latex"
3414 '(org-export-as-latex-batch org-export-as-latex-to-buffer
3415 org-replace-region-by-latex org-export-region-as-latex
3416 org-export-as-latex org-export-as-pdf
3417 org-export-as-pdf-and-open))
3418 (org-autoload "org-html"
3419 '(org-export-as-html-and-open
3420 org-export-as-html-batch org-export-as-html-to-buffer
3421 org-replace-region-by-html org-export-region-as-html
3422 org-export-as-html))
3423 (org-autoload "org-docbook"
3424 '(org-export-as-docbook-batch org-export-as-docbook-to-buffer
3425 org-replace-region-by-docbook org-export-region-as-docbook
3426 org-export-as-docbook-pdf org-export-as-docbook-pdf-and-open
3427 org-export-as-docbook))
3428 (org-autoload "org-icalendar"
3429 '(org-export-icalendar-this-file
3430 org-export-icalendar-all-agenda-files
3431 org-export-icalendar-combine-agenda-files))
3432 (org-autoload "org-xoxo" '(org-export-as-xoxo))
3433 (org-autoload "org-beamer" '(org-beamer-mode org-beamer-sectioning)))
3434
3435 ;; Declare and autoload functions from org-agenda.el
3436
3437 (eval-and-compile
3438 (org-autoload "org-agenda"
3439 '(org-agenda org-agenda-list org-search-view
3440 org-todo-list org-tags-view org-agenda-list-stuck-projects
3441 org-diary org-agenda-to-appt
3442 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3443
3444 ;; Autoload org-remember
3445
3446 (eval-and-compile
3447 (org-autoload "org-remember"
3448 '(org-remember-insinuate org-remember-annotation
3449 org-remember-apply-template org-remember org-remember-handler)))
3450
3451 ;; Autoload org-clock.el
3452
3453
3454 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3455 (beg end))
3456 (declare-function org-clock-update-mode-line "org-clock" ())
3457 (declare-function org-resolve-clocks "org-clock"
3458 (&optional also-non-dangling-p prompt last-valid))
3459 (defvar org-clock-start-time)
3460 (defvar org-clock-marker (make-marker)
3461 "Marker recording the last clock-in.")
3462 (defvar org-clock-hd-marker (make-marker)
3463 "Marker recording the last clock-in, but the headline position.")
3464 (defvar org-clock-heading ""
3465 "The heading of the current clock entry.")
3466 (defun org-clock-is-active ()
3467 "Return non-nil if clock is currently running.
3468 The return value is actually the clock marker."
3469 (marker-buffer org-clock-marker))
3470
3471 (eval-and-compile
3472 (org-autoload
3473 "org-clock"
3474 '(org-clock-in org-clock-out org-clock-cancel
3475 org-clock-goto org-clock-sum org-clock-display
3476 org-clock-remove-overlays org-clock-report
3477 org-clocktable-shift org-dblock-write:clocktable
3478 org-get-clocktable org-resolve-clocks)))
3479
3480 (defun org-clock-update-time-maybe ()
3481 "If this is a CLOCK line, update it and return t.
3482 Otherwise, return nil."
3483 (interactive)
3484 (save-excursion
3485 (beginning-of-line 1)
3486 (skip-chars-forward " \t")
3487 (when (looking-at org-clock-string)
3488 (let ((re (concat "[ \t]*" org-clock-string
3489 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3490 "\\([ \t]*=>.*\\)?\\)?"))
3491 ts te h m s neg)
3492 (cond
3493 ((not (looking-at re))
3494 nil)
3495 ((not (match-end 2))
3496 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3497 (> org-clock-marker (point))
3498 (<= org-clock-marker (point-at-eol)))
3499 ;; The clock is running here
3500 (setq org-clock-start-time
3501 (apply 'encode-time
3502 (org-parse-time-string (match-string 1))))
3503 (org-clock-update-mode-line)))
3504 (t
3505 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3506 (end-of-line 1)
3507 (setq ts (match-string 1)
3508 te (match-string 3))
3509 (setq s (- (org-float-time
3510 (apply 'encode-time (org-parse-time-string te)))
3511 (org-float-time
3512 (apply 'encode-time (org-parse-time-string ts))))
3513 neg (< s 0)
3514 s (abs s)
3515 h (floor (/ s 3600))
3516 s (- s (* 3600 h))
3517 m (floor (/ s 60))
3518 s (- s (* 60 s)))
3519 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3520 t))))))
3521
3522 (defun org-check-running-clock ()
3523 "Check if the current buffer contains the running clock.
3524 If yes, offer to stop it and to save the buffer with the changes."
3525 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3526 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3527 (buffer-name))))
3528 (org-clock-out)
3529 (when (y-or-n-p "Save changed buffer?")
3530 (save-buffer))))
3531
3532 (defun org-clocktable-try-shift (dir n)
3533 "Check if this line starts a clock table, if yes, shift the time block."
3534 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3535 (org-clocktable-shift dir n)))
3536
3537 ;; Autoload org-timer.el
3538
3539 (eval-and-compile
3540 (org-autoload
3541 "org-timer"
3542 '(org-timer-start org-timer org-timer-item
3543 org-timer-change-times-in-region
3544 org-timer-set-timer
3545 org-timer-reset-timers
3546 org-timer-show-remaining-time)))
3547
3548 ;; Autoload org-feed.el
3549
3550 (eval-and-compile
3551 (org-autoload
3552 "org-feed"
3553 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3554
3555
3556 ;; Autoload org-indent.el
3557
3558 ;; Define the variable already here, to make sure we have it.
3559 (defvar org-indent-mode nil
3560 "Non-nil if Org-Indent mode is enabled.
3561 Use the command `org-indent-mode' to change this variable.")
3562
3563 (eval-and-compile
3564 (org-autoload
3565 "org-indent"
3566 '(org-indent-mode)))
3567
3568 ;; Autoload org-mobile.el
3569
3570 (eval-and-compile
3571 (org-autoload
3572 "org-mobile"
3573 '(org-mobile-push org-mobile-pull org-mobile-create-sumo-agenda)))
3574
3575 ;; Autoload archiving code
3576 ;; The stuff that is needed for cycling and tags has to be defined here.
3577
3578 (defgroup org-archive nil
3579 "Options concerning archiving in Org-mode."
3580 :tag "Org Archive"
3581 :group 'org-structure)
3582
3583 (defcustom org-archive-location "%s_archive::"
3584 "The location where subtrees should be archived.
3585
3586 The value of this variable is a string, consisting of two parts,
3587 separated by a double-colon. The first part is a filename and
3588 the second part is a headline.
3589
3590 When the filename is omitted, archiving happens in the same file.
3591 %s in the filename will be replaced by the current file
3592 name (without the directory part). Archiving to a different file
3593 is useful to keep archived entries from contributing to the
3594 Org-mode Agenda.
3595
3596 The archived entries will be filed as subtrees of the specified
3597 headline. When the headline is omitted, the subtrees are simply
3598 filed away at the end of the file, as top-level entries. Also in
3599 the heading you can use %s to represent the file name, this can be
3600 useful when using the same archive for a number of different files.
3601
3602 Here are a few examples:
3603 \"%s_archive::\"
3604 If the current file is Projects.org, archive in file
3605 Projects.org_archive, as top-level trees. This is the default.
3606
3607 \"::* Archived Tasks\"
3608 Archive in the current file, under the top-level headline
3609 \"* Archived Tasks\".
3610
3611 \"~/org/archive.org::\"
3612 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3613
3614 \"~/org/archive.org::From %s\"
3615 Archive in file ~/org/archive.org (absolute path), under headlines
3616 \"From FILENAME\" where file name is the current file name.
3617
3618 \"basement::** Finished Tasks\"
3619 Archive in file ./basement (relative path), as level 3 trees
3620 below the level 2 heading \"** Finished Tasks\".
3621
3622 You may set this option on a per-file basis by adding to the buffer a
3623 line like
3624
3625 #+ARCHIVE: basement::** Finished Tasks
3626
3627 You may also define it locally for a subtree by setting an ARCHIVE property
3628 in the entry. If such a property is found in an entry, or anywhere up
3629 the hierarchy, it will be used."
3630 :group 'org-archive
3631 :type 'string)
3632
3633 (defcustom org-archive-tag "ARCHIVE"
3634 "The tag that marks a subtree as archived.
3635 An archived subtree does not open during visibility cycling, and does
3636 not contribute to the agenda listings.
3637 After changing this, font-lock must be restarted in the relevant buffers to
3638 get the proper fontification."
3639 :group 'org-archive
3640 :group 'org-keywords
3641 :type 'string)
3642
3643 (defcustom org-agenda-skip-archived-trees t
3644 "Non-nil means the agenda will skip any items located in archived trees.
3645 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3646 variable is no longer recommended, you should leave it at the value t.
3647 Instead, use the key `v' to cycle the archives-mode in the agenda."
3648 :group 'org-archive
3649 :group 'org-agenda-skip
3650 :type 'boolean)
3651
3652 (defcustom org-columns-skip-archived-trees t
3653 "Non-nil means ignore archived trees when creating column view."
3654 :group 'org-archive
3655 :group 'org-properties
3656 :type 'boolean)
3657
3658 (defcustom org-cycle-open-archived-trees nil
3659 "Non-nil means `org-cycle' will open archived trees.
3660 An archived tree is a tree marked with the tag ARCHIVE.
3661 When nil, archived trees will stay folded. You can still open them with
3662 normal outline commands like `show-all', but not with the cycling commands."
3663 :group 'org-archive
3664 :group 'org-cycle
3665 :type 'boolean)
3666
3667 (defcustom org-sparse-tree-open-archived-trees nil
3668 "Non-nil means sparse tree construction shows matches in archived trees.
3669 When nil, matches in these trees are highlighted, but the trees are kept in
3670 collapsed state."
3671 :group 'org-archive
3672 :group 'org-sparse-trees
3673 :type 'boolean)
3674
3675 (defun org-cycle-hide-archived-subtrees (state)
3676 "Re-hide all archived subtrees after a visibility state change."
3677 (when (and (not org-cycle-open-archived-trees)
3678 (not (memq state '(overview folded))))
3679 (save-excursion
3680 (let* ((globalp (memq state '(contents all)))
3681 (beg (if globalp (point-min) (point)))
3682 (end (if globalp (point-max) (org-end-of-subtree t))))
3683 (org-hide-archived-subtrees beg end)
3684 (goto-char beg)
3685 (if (looking-at (concat ".*:" org-archive-tag ":"))
3686 (message "%s" (substitute-command-keys
3687 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3688
3689 (defun org-force-cycle-archived ()
3690 "Cycle subtree even if it is archived."
3691 (interactive)
3692 (setq this-command 'org-cycle)
3693 (let ((org-cycle-open-archived-trees t))
3694 (call-interactively 'org-cycle)))
3695
3696 (defun org-hide-archived-subtrees (beg end)
3697 "Re-hide all archived subtrees after a visibility state change."
3698 (save-excursion
3699 (let* ((re (concat ":" org-archive-tag ":")))
3700 (goto-char beg)
3701 (while (re-search-forward re end t)
3702 (when (org-on-heading-p)
3703 (org-flag-subtree t)
3704 (org-end-of-subtree t))))))
3705
3706 (defun org-flag-subtree (flag)
3707 (save-excursion
3708 (org-back-to-heading t)
3709 (outline-end-of-heading)
3710 (outline-flag-region (point)
3711 (progn (org-end-of-subtree t) (point))
3712 flag)))
3713
3714 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3715
3716 (eval-and-compile
3717 (org-autoload "org-archive"
3718 '(org-add-archive-files org-archive-subtree
3719 org-archive-to-archive-sibling org-toggle-archive-tag
3720 org-archive-subtree-default
3721 org-archive-subtree-default-with-confirmation)))
3722
3723 ;; Autoload Column View Code
3724
3725 (declare-function org-columns-number-to-string "org-colview")
3726 (declare-function org-columns-get-format-and-top-level "org-colview")
3727 (declare-function org-columns-compute "org-colview")
3728
3729 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3730 '(org-columns-number-to-string org-columns-get-format-and-top-level
3731 org-columns-compute org-agenda-columns org-columns-remove-overlays
3732 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3733
3734 ;; Autoload ID code
3735
3736 (declare-function org-id-store-link "org-id")
3737 (declare-function org-id-locations-load "org-id")
3738 (declare-function org-id-locations-save "org-id")
3739 (defvar org-id-track-globally)
3740 (org-autoload "org-id"
3741 '(org-id-get-create org-id-new org-id-copy org-id-get
3742 org-id-get-with-outline-path-completion
3743 org-id-get-with-outline-drilling
3744 org-id-goto org-id-find org-id-store-link))
3745
3746 ;; Autoload Plotting Code
3747
3748 (org-autoload "org-plot"
3749 '(org-plot/gnuplot))
3750
3751 ;;; Variables for pre-computed regular expressions, all buffer local
3752
3753 (defvar org-drawer-regexp nil
3754 "Matches first line of a hidden block.")
3755 (make-variable-buffer-local 'org-drawer-regexp)
3756 (defvar org-todo-regexp nil
3757 "Matches any of the TODO state keywords.")
3758 (make-variable-buffer-local 'org-todo-regexp)
3759 (defvar org-not-done-regexp nil
3760 "Matches any of the TODO state keywords except the last one.")
3761 (make-variable-buffer-local 'org-not-done-regexp)
3762 (defvar org-not-done-heading-regexp nil
3763 "Matches a TODO headline that is not done.")
3764 (make-variable-buffer-local 'org-not-done-regexp)
3765 (defvar org-todo-line-regexp nil
3766 "Matches a headline and puts TODO state into group 2 if present.")
3767 (make-variable-buffer-local 'org-todo-line-regexp)
3768 (defvar org-complex-heading-regexp nil
3769 "Matches a headline and puts everything into groups:
3770 group 1: the stars
3771 group 2: The todo keyword, maybe
3772 group 3: Priority cookie
3773 group 4: True headline
3774 group 5: Tags")
3775 (make-variable-buffer-local 'org-complex-heading-regexp)
3776 (defvar org-complex-heading-regexp-format nil)
3777 (make-variable-buffer-local 'org-complex-heading-regexp-format)
3778 (defvar org-todo-line-tags-regexp nil
3779 "Matches a headline and puts TODO state into group 2 if present.
3780 Also put tags into group 4 if tags are present.")
3781 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3782 (defvar org-nl-done-regexp nil
3783 "Matches newline followed by a headline with the DONE keyword.")
3784 (make-variable-buffer-local 'org-nl-done-regexp)
3785 (defvar org-looking-at-done-regexp nil
3786 "Matches the DONE keyword a point.")
3787 (make-variable-buffer-local 'org-looking-at-done-regexp)
3788 (defvar org-ds-keyword-length 12
3789 "Maximum length of the Deadline and SCHEDULED keywords.")
3790 (make-variable-buffer-local 'org-ds-keyword-length)
3791 (defvar org-deadline-regexp nil
3792 "Matches the DEADLINE keyword.")
3793 (make-variable-buffer-local 'org-deadline-regexp)
3794 (defvar org-deadline-time-regexp nil
3795 "Matches the DEADLINE keyword together with a time stamp.")
3796 (make-variable-buffer-local 'org-deadline-time-regexp)
3797 (defvar org-deadline-line-regexp nil
3798 "Matches the DEADLINE keyword and the rest of the line.")
3799 (make-variable-buffer-local 'org-deadline-line-regexp)
3800 (defvar org-scheduled-regexp nil
3801 "Matches the SCHEDULED keyword.")
3802 (make-variable-buffer-local 'org-scheduled-regexp)
3803 (defvar org-scheduled-time-regexp nil
3804 "Matches the SCHEDULED keyword together with a time stamp.")
3805 (make-variable-buffer-local 'org-scheduled-time-regexp)
3806 (defvar org-closed-time-regexp nil
3807 "Matches the CLOSED keyword together with a time stamp.")
3808 (make-variable-buffer-local 'org-closed-time-regexp)
3809
3810 (defvar org-keyword-time-regexp nil
3811 "Matches any of the 4 keywords, together with the time stamp.")
3812 (make-variable-buffer-local 'org-keyword-time-regexp)
3813 (defvar org-keyword-time-not-clock-regexp nil
3814 "Matches any of the 3 keywords, together with the time stamp.")
3815 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3816 (defvar org-maybe-keyword-time-regexp nil
3817 "Matches a timestamp, possibly preceeded by a keyword.")
3818 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3819 (defvar org-planning-or-clock-line-re nil
3820 "Matches a line with planning or clock info.")
3821 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3822 (defvar org-all-time-keywords nil
3823 "List of time keywords.")
3824 (make-variable-buffer-local 'org-all-time-keywords)
3825
3826 (defconst org-plain-time-of-day-regexp
3827 (concat
3828 "\\(\\<[012]?[0-9]"
3829 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3830 "\\(--?"
3831 "\\(\\<[012]?[0-9]"
3832 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3833 "\\)?")
3834 "Regular expression to match a plain time or time range.
3835 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3836 groups carry important information:
3837 0 the full match
3838 1 the first time, range or not
3839 8 the second time, if it is a range.")
3840
3841 (defconst org-plain-time-extension-regexp
3842 (concat
3843 "\\(\\<[012]?[0-9]"
3844 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3845 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3846 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3847 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3848 groups carry important information:
3849 0 the full match
3850 7 hours of duration
3851 9 minutes of duration")
3852
3853 (defconst org-stamp-time-of-day-regexp
3854 (concat
3855 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3856 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3857 "\\(--?"
3858 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3859 "Regular expression to match a timestamp time or time range.
3860 After a match, the following groups carry important information:
3861 0 the full match
3862 1 date plus weekday, for back referencing to make sure both times are on the same day
3863 2 the first time, range or not
3864 4 the second time, if it is a range.")
3865
3866 (defconst org-startup-options
3867 '(("fold" org-startup-folded t)
3868 ("overview" org-startup-folded t)
3869 ("nofold" org-startup-folded nil)
3870 ("showall" org-startup-folded nil)
3871 ("showeverything" org-startup-folded showeverything)
3872 ("content" org-startup-folded content)
3873 ("indent" org-startup-indented t)
3874 ("noindent" org-startup-indented nil)
3875 ("hidestars" org-hide-leading-stars t)
3876 ("showstars" org-hide-leading-stars nil)
3877 ("odd" org-odd-levels-only t)
3878 ("oddeven" org-odd-levels-only nil)
3879 ("align" org-startup-align-all-tables t)
3880 ("noalign" org-startup-align-all-tables nil)
3881 ("customtime" org-display-custom-times t)
3882 ("logdone" org-log-done time)
3883 ("lognotedone" org-log-done note)
3884 ("nologdone" org-log-done nil)
3885 ("lognoteclock-out" org-log-note-clock-out t)
3886 ("nolognoteclock-out" org-log-note-clock-out nil)
3887 ("logrepeat" org-log-repeat state)
3888 ("lognoterepeat" org-log-repeat note)
3889 ("nologrepeat" org-log-repeat nil)
3890 ("logreschedule" org-log-reschedule time)
3891 ("lognotereschedule" org-log-reschedule note)
3892 ("nologreschedule" org-log-reschedule nil)
3893 ("logredeadline" org-log-redeadline time)
3894 ("lognoteredeadline" org-log-redeadline note)
3895 ("nologredeadline" org-log-redeadline nil)
3896 ("logrefile" org-log-refile time)
3897 ("lognoterefile" org-log-refile note)
3898 ("nologrefile" org-log-refile nil)
3899 ("fninline" org-footnote-define-inline t)
3900 ("nofninline" org-footnote-define-inline nil)
3901 ("fnlocal" org-footnote-section nil)
3902 ("fnauto" org-footnote-auto-label t)
3903 ("fnprompt" org-footnote-auto-label nil)
3904 ("fnconfirm" org-footnote-auto-label confirm)
3905 ("fnplain" org-footnote-auto-label plain)
3906 ("fnadjust" org-footnote-auto-adjust t)
3907 ("nofnadjust" org-footnote-auto-adjust nil)
3908 ("constcgs" constants-unit-system cgs)
3909 ("constSI" constants-unit-system SI)
3910 ("noptag" org-tag-persistent-alist nil)
3911 ("hideblocks" org-hide-block-startup t)
3912 ("nohideblocks" org-hide-block-startup nil)
3913 ("beamer" org-startup-with-beamer-mode t))
3914 "Variable associated with STARTUP options for org-mode.
3915 Each element is a list of three items: The startup options as written
3916 in the #+STARTUP line, the corresponding variable, and the value to
3917 set this variable to if the option is found. An optional forth element PUSH
3918 means to push this value onto the list in the variable.")
3919
3920 (defun org-set-regexps-and-options ()
3921 "Precompute regular expressions for current buffer."
3922 (when (org-mode-p)
3923 (org-set-local 'org-todo-kwd-alist nil)
3924 (org-set-local 'org-todo-key-alist nil)
3925 (org-set-local 'org-todo-key-trigger nil)
3926 (org-set-local 'org-todo-keywords-1 nil)
3927 (org-set-local 'org-done-keywords nil)
3928 (org-set-local 'org-todo-heads nil)
3929 (org-set-local 'org-todo-sets nil)
3930 (org-set-local 'org-todo-log-states nil)
3931 (org-set-local 'org-file-properties nil)
3932 (org-set-local 'org-file-tags nil)
3933 (let ((re (org-make-options-regexp
3934 '("CATEGORY" "TODO" "COLUMNS"
3935 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3936 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE" "LATEX_CLASS")
3937 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3938 (splitre "[ \t]+")
3939 kwds kws0 kwsa key log value cat arch tags const links hw dws
3940 tail sep kws1 prio props ftags drawers beamer-p
3941 ext-setup-or-nil setup-contents (start 0))
3942 (save-excursion
3943 (save-restriction
3944 (widen)
3945 (goto-char (point-min))
3946 (while (or (and ext-setup-or-nil
3947 (string-match re ext-setup-or-nil start)
3948 (setq start (match-end 0)))
3949 (and (setq ext-setup-or-nil nil start 0)
3950 (re-search-forward re nil t)))
3951 (setq key (upcase (match-string 1 ext-setup-or-nil))
3952 value (org-match-string-no-properties 2 ext-setup-or-nil))
3953 (cond
3954 ((equal key "CATEGORY")
3955 (if (string-match "[ \t]+$" value)
3956 (setq value (replace-match "" t t value)))
3957 (setq cat value))
3958 ((member key '("SEQ_TODO" "TODO"))
3959 (push (cons 'sequence (org-split-string value splitre)) kwds))
3960 ((equal key "TYP_TODO")
3961 (push (cons 'type (org-split-string value splitre)) kwds))
3962 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3963 ;; general TODO-like setup
3964 (push (cons (intern (downcase (match-string 1 key)))
3965 (org-split-string value splitre)) kwds))
3966 ((equal key "TAGS")
3967 (setq tags (append tags (if tags '("\\n") nil)
3968 (org-split-string value splitre))))
3969 ((equal key "COLUMNS")
3970 (org-set-local 'org-columns-default-format value))
3971 ((equal key "LINK")
3972 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3973 (push (cons (match-string 1 value)
3974 (org-trim (match-string 2 value)))
3975 links)))
3976 ((equal key "PRIORITIES")
3977 (setq prio (org-split-string value " +")))
3978 ((equal key "PROPERTY")
3979 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3980 (push (cons (match-string 1 value) (match-string 2 value))
3981 props)))
3982 ((equal key "FILETAGS")
3983 (when (string-match "\\S-" value)
3984 (setq ftags
3985 (append
3986 ftags
3987 (apply 'append
3988 (mapcar (lambda (x) (org-split-string x ":"))
3989 (org-split-string value)))))))
3990 ((equal key "DRAWERS")
3991 (setq drawers (org-split-string value splitre)))
3992 ((equal key "CONSTANTS")
3993 (setq const (append const (org-split-string value splitre))))
3994 ((equal key "STARTUP")
3995 (let ((opts (org-split-string value splitre))
3996 l var val)
3997 (while (setq l (pop opts))
3998 (when (setq l (assoc l org-startup-options))
3999 (setq var (nth 1 l) val (nth 2 l))
4000 (if (not (nth 3 l))
4001 (set (make-local-variable var) val)
4002 (if (not (listp (symbol-value var)))
4003 (set (make-local-variable var) nil))
4004 (set (make-local-variable var) (symbol-value var))
4005 (add-to-list var val))))))
4006 ((equal key "ARCHIVE")
4007 (string-match " *$" value)
4008 (setq arch (replace-match "" t t value))
4009 (remove-text-properties 0 (length arch)
4010 '(face t fontified t) arch))
4011 ((equal key "LATEX_CLASS")
4012 (setq beamer-p (equal value "beamer")))
4013 ((equal key "SETUPFILE")
4014 (setq setup-contents (org-file-contents
4015 (expand-file-name
4016 (org-remove-double-quotes value))
4017 'noerror))
4018 (if (not ext-setup-or-nil)
4019 (setq ext-setup-or-nil setup-contents start 0)
4020 (setq ext-setup-or-nil
4021 (concat (substring ext-setup-or-nil 0 start)
4022 "\n" setup-contents "\n"
4023 (substring ext-setup-or-nil start)))))
4024 ))))
4025 (when cat
4026 (org-set-local 'org-category (intern cat))
4027 (push (cons "CATEGORY" cat) props))
4028 (when prio
4029 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
4030 (setq prio (mapcar 'string-to-char prio))
4031 (org-set-local 'org-highest-priority (nth 0 prio))
4032 (org-set-local 'org-lowest-priority (nth 1 prio))
4033 (org-set-local 'org-default-priority (nth 2 prio)))
4034 (and props (org-set-local 'org-file-properties (nreverse props)))
4035 (and ftags (org-set-local 'org-file-tags
4036 (mapcar 'org-add-prop-inherited ftags)))
4037 (and drawers (org-set-local 'org-drawers drawers))
4038 (and arch (org-set-local 'org-archive-location arch))
4039 (and links (setq org-link-abbrev-alist-local (nreverse links)))
4040 ;; Process the TODO keywords
4041 (unless kwds
4042 ;; Use the global values as if they had been given locally.
4043 (setq kwds (default-value 'org-todo-keywords))
4044 (if (stringp (car kwds))
4045 (setq kwds (list (cons org-todo-interpretation
4046 (default-value 'org-todo-keywords)))))
4047 (setq kwds (reverse kwds)))
4048 (setq kwds (nreverse kwds))
4049 (let (inter kws kw)
4050 (while (setq kws (pop kwds))
4051 (let ((kws (or
4052 (run-hook-with-args-until-success
4053 'org-todo-setup-filter-hook kws)
4054 kws)))
4055 (setq inter (pop kws) sep (member "|" kws)
4056 kws0 (delete "|" (copy-sequence kws))
4057 kwsa nil
4058 kws1 (mapcar
4059 (lambda (x)
4060 ;; 1 2
4061 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
4062 (progn
4063 (setq kw (match-string 1 x)
4064 key (and (match-end 2) (match-string 2 x))
4065 log (org-extract-log-state-settings x))
4066 (push (cons kw (and key (string-to-char key))) kwsa)
4067 (and log (push log org-todo-log-states))
4068 kw)
4069 (error "Invalid TODO keyword %s" x)))
4070 kws0)
4071 kwsa (if kwsa (append '((:startgroup))
4072 (nreverse kwsa)
4073 '((:endgroup))))
4074 hw (car kws1)
4075 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
4076 tail (list inter hw (car dws) (org-last dws))))
4077 (add-to-list 'org-todo-heads hw 'append)
4078 (push kws1 org-todo-sets)
4079 (setq org-done-keywords (append org-done-keywords dws nil))
4080 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
4081 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
4082 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
4083 (setq org-todo-sets (nreverse org-todo-sets)
4084 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
4085 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
4086 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
4087 ;; Process the constants
4088 (when const
4089 (let (e cst)
4090 (while (setq e (pop const))
4091 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
4092 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
4093 (setq org-table-formula-constants-local cst)))
4094
4095 ;; Process the tags.
4096 (when tags
4097 (let (e tgs)
4098 (while (setq e (pop tags))
4099 (cond
4100 ((equal e "{") (push '(:startgroup) tgs))
4101 ((equal e "}") (push '(:endgroup) tgs))
4102 ((equal e "\\n") (push '(:newline) tgs))
4103 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
4104 (push (cons (match-string 1 e)
4105 (string-to-char (match-string 2 e)))
4106 tgs))
4107 (t (push (list e) tgs))))
4108 (org-set-local 'org-tag-alist nil)
4109 (while (setq e (pop tgs))
4110 (or (and (stringp (car e))
4111 (assoc (car e) org-tag-alist))
4112 (push e org-tag-alist)))))
4113
4114 ;; Compute the regular expressions and other local variables
4115 (if (not org-done-keywords)
4116 (setq org-done-keywords (and org-todo-keywords-1
4117 (list (org-last org-todo-keywords-1)))))
4118 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
4119 (length org-scheduled-string)
4120 (length org-clock-string)
4121 (length org-closed-string)))
4122 org-drawer-regexp
4123 (concat "^[ \t]*:\\("
4124 (mapconcat 'regexp-quote org-drawers "\\|")
4125 "\\):[ \t]*$")
4126 org-not-done-keywords
4127 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
4128 org-todo-regexp
4129 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
4130 "\\|") "\\)\\>")
4131 org-not-done-regexp
4132 (concat "\\<\\("
4133 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4134 "\\)\\>")
4135 org-not-done-heading-regexp
4136 (concat "^\\(\\*+\\)[ \t]+\\("
4137 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
4138 "\\)\\>")
4139 org-todo-line-regexp
4140 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4141 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4142 "\\)\\>\\)?[ \t]*\\(.*\\)")
4143 org-complex-heading-regexp
4144 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4145 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4146 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
4147 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4148 org-complex-heading-regexp-format
4149 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4150 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4151 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(%s\\)"
4152 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4153 org-nl-done-regexp
4154 (concat "\n\\*+[ \t]+"
4155 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
4156 "\\)" "\\>")
4157 org-todo-line-tags-regexp
4158 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
4159 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
4160 (org-re
4161 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
4162 org-looking-at-done-regexp
4163 (concat "^" "\\(?:"
4164 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
4165 "\\>")
4166 org-deadline-regexp (concat "\\<" org-deadline-string)
4167 org-deadline-time-regexp
4168 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
4169 org-deadline-line-regexp
4170 (concat "\\<\\(" org-deadline-string "\\).*")
4171 org-scheduled-regexp
4172 (concat "\\<" org-scheduled-string)
4173 org-scheduled-time-regexp
4174 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
4175 org-closed-time-regexp
4176 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
4177 org-keyword-time-regexp
4178 (concat "\\<\\(" org-scheduled-string
4179 "\\|" org-deadline-string
4180 "\\|" org-closed-string
4181 "\\|" org-clock-string "\\)"
4182 " *[[<]\\([^]>]+\\)[]>]")
4183 org-keyword-time-not-clock-regexp
4184 (concat "\\<\\(" org-scheduled-string
4185 "\\|" org-deadline-string
4186 "\\|" org-closed-string
4187 "\\)"
4188 " *[[<]\\([^]>]+\\)[]>]")
4189 org-maybe-keyword-time-regexp
4190 (concat "\\(\\<\\(" org-scheduled-string
4191 "\\|" org-deadline-string
4192 "\\|" org-closed-string
4193 "\\|" org-clock-string "\\)\\)?"
4194 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
4195 org-planning-or-clock-line-re
4196 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
4197 "\\|" org-deadline-string
4198 "\\|" org-closed-string "\\|" org-clock-string
4199 "\\)\\>\\)")
4200 org-all-time-keywords
4201 (mapcar (lambda (w) (substring w 0 -1))
4202 (list org-scheduled-string org-deadline-string
4203 org-clock-string org-closed-string))
4204 )
4205 (org-compute-latex-and-specials-regexp)
4206 (org-set-font-lock-defaults))))
4207
4208 (defun org-file-contents (file &optional noerror)
4209 "Return the contents of FILE, as a string."
4210 (if (or (not file)
4211 (not (file-readable-p file)))
4212 (if noerror
4213 (progn
4214 (message "Cannot read file %s" file)
4215 (ding) (sit-for 2)
4216 "")
4217 (error "Cannot read file %s" file))
4218 (with-temp-buffer
4219 (insert-file-contents file)
4220 (buffer-string))))
4221
4222 (defun org-extract-log-state-settings (x)
4223 "Extract the log state setting from a TODO keyword string.
4224 This will extract info from a string like \"WAIT(w@/!)\"."
4225 (let (kw key log1 log2)
4226 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
4227 (setq kw (match-string 1 x)
4228 key (and (match-end 2) (match-string 2 x))
4229 log1 (and (match-end 3) (match-string 3 x))
4230 log2 (and (match-end 4) (match-string 4 x)))
4231 (and (or log1 log2)
4232 (list kw
4233 (and log1 (if (equal log1 "!") 'time 'note))
4234 (and log2 (if (equal log2 "!") 'time 'note)))))))
4235
4236 (defun org-remove-keyword-keys (list)
4237 "Remove a pair of parenthesis at the end of each string in LIST."
4238 (mapcar (lambda (x)
4239 (if (string-match "(.*)$" x)
4240 (substring x 0 (match-beginning 0))
4241 x))
4242 list))
4243
4244 (defun org-assign-fast-keys (alist)
4245 "Assign fast keys to a keyword-key alist.
4246 Respect keys that are already there."
4247 (let (new e (alt ?0))
4248 (while (setq e (pop alist))
4249 (if (or (memq (car e) '(:newline :endgroup :startgroup))
4250 (cdr e)) ;; Key already assigned.
4251 (push e new)
4252 (let ((clist (string-to-list (downcase (car e))))
4253 (used (append new alist)))
4254 (when (= (car clist) ?@)
4255 (pop clist))
4256 (while (and clist (rassoc (car clist) used))
4257 (pop clist))
4258 (unless clist
4259 (while (rassoc alt used)
4260 (incf alt)))
4261 (push (cons (car e) (or (car clist) alt)) new))))
4262 (nreverse new)))
4263
4264 ;;; Some variables used in various places
4265
4266 (defvar org-window-configuration nil
4267 "Used in various places to store a window configuration.")
4268 (defvar org-selected-window nil
4269 "Used in various places to store a window configuration.")
4270 (defvar org-finish-function nil
4271 "Function to be called when `C-c C-c' is used.
4272 This is for getting out of special buffers like remember.")
4273
4274
4275 ;; FIXME: Occasionally check by commenting these, to make sure
4276 ;; no other functions uses these, forgetting to let-bind them.
4277 (defvar entry)
4278 (defvar last-state)
4279 (defvar date)
4280
4281 ;; Defined somewhere in this file, but used before definition.
4282 (defvar org-entities) ;; defined in org-entities.el
4283 (defvar org-struct-menu)
4284 (defvar org-org-menu)
4285 (defvar org-tbl-menu)
4286
4287 ;;;; Define the Org-mode
4288
4289 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
4290 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or upgrade to newer allout, for example by switching to Emacs 22."))
4291
4292
4293 ;; We use a before-change function to check if a table might need
4294 ;; an update.
4295 (defvar org-table-may-need-update t
4296 "Indicates that a table might need an update.
4297 This variable is set by `org-before-change-function'.
4298 `org-table-align' sets it back to nil.")
4299 (defun org-before-change-function (beg end)
4300 "Every change indicates that a table might need an update."
4301 (setq org-table-may-need-update t))
4302 (defvar org-mode-map)
4303 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
4304 (defvar org-inhibit-startup-visibility-stuff nil) ; Dynamically-scoped param.
4305 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
4306 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
4307 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
4308 (defvar org-table-buffer-is-an nil)
4309 (defconst org-outline-regexp "\\*+ ")
4310
4311 ;;;###autoload
4312 (define-derived-mode org-mode outline-mode "Org"
4313 "Outline-based notes management and organizer, alias
4314 \"Carsten's outline-mode for keeping track of everything.\"
4315
4316 Org-mode develops organizational tasks around a NOTES file which
4317 contains information about projects as plain text. Org-mode is
4318 implemented on top of outline-mode, which is ideal to keep the content
4319 of large files well structured. It supports ToDo items, deadlines and
4320 time stamps, which magically appear in the diary listing of the Emacs
4321 calendar. Tables are easily created with a built-in table editor.
4322 Plain text URL-like links connect to websites, emails (VM), Usenet
4323 messages (Gnus), BBDB entries, and any files related to the project.
4324 For printing and sharing of notes, an Org-mode file (or a part of it)
4325 can be exported as a structured ASCII or HTML file.
4326
4327 The following commands are available:
4328
4329 \\{org-mode-map}"
4330
4331 ;; Get rid of Outline menus, they are not needed
4332 ;; Need to do this here because define-derived-mode sets up
4333 ;; the keymap so late. Still, it is a waste to call this each time
4334 ;; we switch another buffer into org-mode.
4335 (if (featurep 'xemacs)
4336 (when (boundp 'outline-mode-menu-heading)
4337 ;; Assume this is Greg's port, it used easymenu
4338 (easy-menu-remove outline-mode-menu-heading)
4339 (easy-menu-remove outline-mode-menu-show)
4340 (easy-menu-remove outline-mode-menu-hide))
4341 (define-key org-mode-map [menu-bar headings] 'undefined)
4342 (define-key org-mode-map [menu-bar hide] 'undefined)
4343 (define-key org-mode-map [menu-bar show] 'undefined))
4344
4345 (org-load-modules-maybe)
4346 (easy-menu-add org-org-menu)
4347 (easy-menu-add org-tbl-menu)
4348 (org-install-agenda-files-menu)
4349 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
4350 (org-add-to-invisibility-spec '(org-cwidth))
4351 (org-add-to-invisibility-spec '(org-hide-block . t))
4352 (when (featurep 'xemacs)
4353 (org-set-local 'line-move-ignore-invisible t))
4354 (org-set-local 'outline-regexp org-outline-regexp)
4355 (org-set-local 'outline-level 'org-outline-level)
4356 (when (and org-ellipsis
4357 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
4358 (fboundp 'make-glyph-code))
4359 (unless org-display-table
4360 (setq org-display-table (make-display-table)))
4361 (set-display-table-slot
4362 org-display-table 4
4363 (vconcat (mapcar
4364 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
4365 org-ellipsis)))
4366 (if (stringp org-ellipsis) org-ellipsis "..."))))
4367 (setq buffer-display-table org-display-table))
4368 (org-set-regexps-and-options)
4369 (when (and org-tag-faces (not org-tags-special-faces-re))
4370 ;; tag faces set outside customize.... force initialization.
4371 (org-set-tag-faces 'org-tag-faces org-tag-faces))
4372 ;; Calc embedded
4373 (org-set-local 'calc-embedded-open-mode "# ")
4374 (modify-syntax-entry ?# "<")
4375 (modify-syntax-entry ?@ "w")
4376 (if org-startup-truncated (setq truncate-lines t))
4377 (org-set-local 'font-lock-unfontify-region-function
4378 'org-unfontify-region)
4379 ;; Activate before-change-function
4380 (org-set-local 'org-table-may-need-update t)
4381 (org-add-hook 'before-change-functions 'org-before-change-function nil
4382 'local)
4383 ;; Check for running clock before killing a buffer
4384 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
4385 ;; Paragraphs and auto-filling
4386 (org-set-autofill-regexps)
4387 (setq indent-line-function 'org-indent-line-function)
4388 (org-update-radio-target-regexp)
4389 ;; Make sure dependence stuff works reliably, even for users who set it
4390 ;; too late :-(
4391 (if org-enforce-todo-dependencies
4392 (add-hook 'org-blocker-hook
4393 'org-block-todo-from-children-or-siblings-or-parent)
4394 (remove-hook 'org-blocker-hook
4395 'org-block-todo-from-children-or-siblings-or-parent))
4396 (if org-enforce-todo-checkbox-dependencies
4397 (add-hook 'org-blocker-hook
4398 'org-block-todo-from-checkboxes)
4399 (remove-hook 'org-blocker-hook
4400 'org-block-todo-from-checkboxes))
4401
4402 ;; Comment characters
4403 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
4404 (org-set-local 'comment-padding " ")
4405
4406 ;; Align options lines
4407 (org-set-local
4408 'align-mode-rules-list
4409 '((org-in-buffer-settings
4410 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
4411 (modes . '(org-mode)))))
4412
4413 ;; Imenu
4414 (org-set-local 'imenu-create-index-function
4415 'org-imenu-get-tree)
4416
4417 ;; Make isearch reveal context
4418 (if (or (featurep 'xemacs)
4419 (not (boundp 'outline-isearch-open-invisible-function)))
4420 ;; Emacs 21 and XEmacs make use of the hook
4421 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
4422 ;; Emacs 22 deals with this through a special variable
4423 (org-set-local 'outline-isearch-open-invisible-function
4424 (lambda (&rest ignore) (org-show-context 'isearch))))
4425
4426 ;; Turn on org-beamer-mode?
4427 (and org-startup-with-beamer-mode (org-beamer-mode 1))
4428
4429 ;; If empty file that did not turn on org-mode automatically, make it to.
4430 (if (and org-insert-mode-line-in-empty-file
4431 (interactive-p)
4432 (= (point-min) (point-max)))
4433 (insert "# -*- mode: org -*-\n\n"))
4434 (unless org-inhibit-startup
4435 (when org-startup-align-all-tables
4436 (let ((bmp (buffer-modified-p)))
4437 (org-table-map-tables 'org-table-align)
4438 (set-buffer-modified-p bmp)))
4439 (when org-startup-indented
4440 (require 'org-indent)
4441 (org-indent-mode 1))
4442 (unless org-inhibit-startup-visibility-stuff
4443 (org-set-startup-visibility))))
4444
4445 (when (fboundp 'abbrev-table-put)
4446 (abbrev-table-put org-mode-abbrev-table
4447 :parents (list text-mode-abbrev-table)))
4448
4449 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4450
4451 (defun org-current-time ()
4452 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4453 (if (> (car org-time-stamp-rounding-minutes) 1)
4454 (let ((r (car org-time-stamp-rounding-minutes))
4455 (time (decode-time)))
4456 (apply 'encode-time
4457 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4458 (nthcdr 2 time))))
4459 (current-time)))
4460
4461 ;;;; Font-Lock stuff, including the activators
4462
4463 (defvar org-mouse-map (make-sparse-keymap))
4464 (org-defkey org-mouse-map
4465 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4466 (org-defkey org-mouse-map
4467 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4468 (when org-mouse-1-follows-link
4469 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4470 (when org-tab-follows-link
4471 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4472 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4473
4474 (require 'font-lock)
4475
4476 (defconst org-non-link-chars "]\t\n\r<>")
4477 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4478 "shell" "elisp"))
4479 (defvar org-link-types-re nil
4480 "Matches a link that has a url-like prefix like \"http:\"")
4481 (defvar org-link-re-with-space nil
4482 "Matches a link with spaces, optional angular brackets around it.")
4483 (defvar org-link-re-with-space2 nil
4484 "Matches a link with spaces, optional angular brackets around it.")
4485 (defvar org-link-re-with-space3 nil
4486 "Matches a link with spaces, only for internal part in bracket links.")
4487 (defvar org-angle-link-re nil
4488 "Matches link with angular brackets, spaces are allowed.")
4489 (defvar org-plain-link-re nil
4490 "Matches plain link, without spaces.")
4491 (defvar org-bracket-link-regexp nil
4492 "Matches a link in double brackets.")
4493 (defvar org-bracket-link-analytic-regexp nil
4494 "Regular expression used to analyze links.
4495 Here is what the match groups contain after a match:
4496 1: http:
4497 2: http
4498 3: path
4499 4: [desc]
4500 5: desc")
4501 (defvar org-bracket-link-analytic-regexp++ nil
4502 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4503 (defvar org-any-link-re nil
4504 "Regular expression matching any link.")
4505
4506 (defun org-make-link-regexps ()
4507 "Update the link regular expressions.
4508 This should be called after the variable `org-link-types' has changed."
4509 (setq org-link-types-re
4510 (concat
4511 "\\`\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):")
4512 org-link-re-with-space
4513 (concat
4514 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4515 "\\([^" org-non-link-chars " ]"
4516 "[^" org-non-link-chars "]*"
4517 "[^" org-non-link-chars " ]\\)>?")
4518 org-link-re-with-space2
4519 (concat
4520 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4521 "\\([^" org-non-link-chars " ]"
4522 "[^\t\n\r]*"
4523 "[^" org-non-link-chars " ]\\)>?")
4524 org-link-re-with-space3
4525 (concat
4526 "<?\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4527 "\\([^" org-non-link-chars " ]"
4528 "[^\t\n\r]*\\)")
4529 org-angle-link-re
4530 (concat
4531 "<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4532 "\\([^" org-non-link-chars " ]"
4533 "[^" org-non-link-chars "]*"
4534 "\\)>")
4535 org-plain-link-re
4536 (concat
4537 "\\<\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):"
4538 (org-re "\\([^ \t\n()<>]+\\(?:([[:word:]0-9]+)\\|\\([^[:punct:] \t\n]\\|/\\)\\)\\)"))
4539 ;; "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4540 org-bracket-link-regexp
4541 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4542 org-bracket-link-analytic-regexp
4543 (concat
4544 "\\[\\["
4545 "\\(\\(" (mapconcat 'regexp-quote org-link-types "\\|") "\\):\\)?"
4546 "\\([^]]+\\)"
4547 "\\]"
4548 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4549 "\\]")
4550 org-bracket-link-analytic-regexp++
4551 (concat
4552 "\\[\\["
4553 "\\(\\(" (mapconcat 'regexp-quote (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4554 "\\([^]]+\\)"
4555 "\\]"
4556 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4557 "\\]")
4558 org-any-link-re
4559 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4560 org-angle-link-re "\\)\\|\\("
4561 org-plain-link-re "\\)")))
4562
4563 (org-make-link-regexps)
4564
4565 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4566 "Regular expression for fast time stamp matching.")
4567 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4568 "Regular expression for fast time stamp matching.")
4569 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4570 "Regular expression matching time strings for analysis.
4571 This one does not require the space after the date, so it can be used
4572 on a string that terminates immediately after the date.")
4573 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4574 "Regular expression matching time strings for analysis.")
4575 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4576 "Regular expression matching time stamps, with groups.")
4577 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4578 "Regular expression matching time stamps (also [..]), with groups.")
4579 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4580 "Regular expression matching a time stamp range.")
4581 (defconst org-tr-regexp-both
4582 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4583 "Regular expression matching a time stamp range.")
4584 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4585 org-ts-regexp "\\)?")
4586 "Regular expression matching a time stamp or time stamp range.")
4587 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4588 org-ts-regexp-both "\\)?")
4589 "Regular expression matching a time stamp or time stamp range.
4590 The time stamps may be either active or inactive.")
4591
4592 (defvar org-emph-face nil)
4593
4594 (defun org-do-emphasis-faces (limit)
4595 "Run through the buffer and add overlays to links."
4596 (let (rtn a)
4597 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4598 (if (not (= (char-after (match-beginning 3))
4599 (char-after (match-beginning 4))))
4600 (progn
4601 (setq rtn t)
4602 (setq a (assoc (match-string 3) org-emphasis-alist))
4603 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4604 'face
4605 (nth 1 a))
4606 (and (nth 4 a)
4607 (org-remove-flyspell-overlays-in
4608 (match-beginning 0) (match-end 0)))
4609 (add-text-properties (match-beginning 2) (match-end 2)
4610 '(font-lock-multiline t))
4611 (when org-hide-emphasis-markers
4612 (add-text-properties (match-end 4) (match-beginning 5)
4613 '(invisible org-link))
4614 (add-text-properties (match-beginning 3) (match-end 3)
4615 '(invisible org-link)))))
4616 (backward-char 1))
4617 rtn))
4618
4619 (defun org-emphasize (&optional char)
4620 "Insert or change an emphasis, i.e. a font like bold or italic.
4621 If there is an active region, change that region to a new emphasis.
4622 If there is no region, just insert the marker characters and position
4623 the cursor between them.
4624 CHAR should be either the marker character, or the first character of the
4625 HTML tag associated with that emphasis. If CHAR is a space, the means
4626 to remove the emphasis of the selected region.
4627 If char is not given (for example in an interactive call) it
4628 will be prompted for."
4629 (interactive)
4630 (let ((eal org-emphasis-alist) e det
4631 (erc org-emphasis-regexp-components)
4632 (prompt "")
4633 (string "") beg end move tag c s)
4634 (if (org-region-active-p)
4635 (setq beg (region-beginning) end (region-end)
4636 string (buffer-substring beg end))
4637 (setq move t))
4638
4639 (while (setq e (pop eal))
4640 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4641 c (aref tag 0))
4642 (push (cons c (string-to-char (car e))) det)
4643 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4644 (substring tag 1)))))
4645 (setq det (nreverse det))
4646 (unless char
4647 (message "%s" (concat "Emphasis marker or tag:" prompt))
4648 (setq char (read-char-exclusive)))
4649 (setq char (or (cdr (assoc char det)) char))
4650 (if (equal char ?\ )
4651 (setq s "" move nil)
4652 (unless (assoc (char-to-string char) org-emphasis-alist)
4653 (error "No such emphasis marker: \"%c\"" char))
4654 (setq s (char-to-string char)))
4655 (while (and (> (length string) 1)
4656 (equal (substring string 0 1) (substring string -1))
4657 (assoc (substring string 0 1) org-emphasis-alist))
4658 (setq string (substring string 1 -1)))
4659 (setq string (concat s string s))
4660 (if beg (delete-region beg end))
4661 (unless (or (bolp)
4662 (string-match (concat "[" (nth 0 erc) "\n]")
4663 (char-to-string (char-before (point)))))
4664 (insert " "))
4665 (unless (or (eobp)
4666 (string-match (concat "[" (nth 1 erc) "\n]")
4667 (char-to-string (char-after (point)))))
4668 (insert " ") (backward-char 1))
4669 (insert string)
4670 (and move (backward-char 1))))
4671
4672 (defconst org-nonsticky-props
4673 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4674
4675 (defsubst org-rear-nonsticky-at (pos)
4676 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4677
4678 (defun org-activate-plain-links (limit)
4679 "Run through the buffer and add overlays to links."
4680 (catch 'exit
4681 (let (f)
4682 (if (re-search-forward org-plain-link-re limit t)
4683 (progn
4684 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4685 (setq f (get-text-property (match-beginning 0) 'face))
4686 (if (or (eq f 'org-tag)
4687 (and (listp f) (memq 'org-tag f)))
4688 nil
4689 (add-text-properties (match-beginning 0) (match-end 0)
4690 (list 'mouse-face 'highlight
4691 'face 'org-link
4692 'keymap org-mouse-map))
4693 (org-rear-nonsticky-at (match-end 0)))
4694 t)))))
4695
4696 (defun org-activate-code (limit)
4697 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4698 (progn
4699 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4700 (remove-text-properties (match-beginning 0) (match-end 0)
4701 '(display t invisible t intangible t))
4702 t)))
4703
4704 (defun org-fontify-meta-lines-and-blocks (limit)
4705 "Fontify #+ lines and blocks, in the correct ways."
4706 (let ((case-fold-search t))
4707 (if (re-search-forward
4708 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\| \\|$\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4709 limit t)
4710 (let ((beg (match-beginning 0))
4711 (beg1 (line-beginning-position 2))
4712 (dc1 (downcase (match-string 2)))
4713 (dc3 (downcase (match-string 3)))
4714 end end1 quoting block-type)
4715 (cond
4716 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4717 ;; a single line of backend-specific content
4718 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4719 (remove-text-properties (match-beginning 0) (match-end 0)
4720 '(display t invisible t intangible t))
4721 (add-text-properties (match-beginning 1) (match-end 3)
4722 '(font-lock-fontified t face org-meta-line))
4723 (add-text-properties (match-beginning 6) (match-end 6)
4724 '(font-lock-fontified t face org-block))
4725 t)
4726 ((and (match-end 4) (equal dc3 "begin"))
4727 ;; Truely a block
4728 (setq block-type (downcase (match-string 5))
4729 quoting (member block-type org-protecting-blocks))
4730 (when (re-search-forward
4731 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4732 nil t) ;; on purpose, we look further than LIMIT
4733 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4734 (when quoting
4735 (remove-text-properties beg end
4736 '(display t invisible t intangible t)))
4737 (add-text-properties
4738 beg end
4739 '(font-lock-fontified t font-lock-multiline t))
4740 (add-text-properties beg beg1 '(face org-meta-line))
4741 (add-text-properties end1 end '(face org-meta-line))
4742 (cond
4743 (quoting
4744 (add-text-properties beg1 end1 '(face org-block)))
4745 ((not org-fontify-quote-and-verse-blocks))
4746 ((string= block-type "quote")
4747 (add-text-properties beg1 end1 '(face org-quote)))
4748 ((string= block-type "verse")
4749 (add-text-properties beg1 end1 '(face org-verse))))
4750 t))
4751 ((member dc1 '("title:" "author:" "email:" "date:"))
4752 (add-text-properties
4753 beg (match-end 3)
4754 (if (member (intern (substring dc1 0 -1)) org-hidden-keywords)
4755 '(font-lock-fontified t invisible t)
4756 '(font-lock-fontified t face org-document-info-keyword)))
4757 (add-text-properties
4758 (match-beginning 6) (match-end 6)
4759 (if (string-equal dc1 "title:")
4760 '(font-lock-fontified t face org-document-title)
4761 '(font-lock-fontified t face org-document-info))))
4762 ((not (member (char-after beg) '(?\ ?\t)))
4763 ;; just any other in-buffer setting, but not indented
4764 (add-text-properties
4765 beg (match-end 0)
4766 '(font-lock-fontified t face org-meta-line))
4767 t)
4768 ((or (member dc1 '("begin:" "end:" "caption:" "label:"
4769 "orgtbl:" "tblfm:" "tblname:"))
4770 (and (match-end 4) (equal dc3 "attr")))
4771 (add-text-properties
4772 beg (match-end 0)
4773 '(font-lock-fontified t face org-meta-line))
4774 t)
4775 ((member dc3 '(" " ""))
4776 (add-text-properties
4777 beg (match-end 0)
4778 '(font-lock-fontified t face font-lock-comment-face)))
4779 (t nil))))))
4780
4781 (defun org-activate-angle-links (limit)
4782 "Run through the buffer and add overlays to links."
4783 (if (re-search-forward org-angle-link-re limit t)
4784 (progn
4785 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4786 (add-text-properties (match-beginning 0) (match-end 0)
4787 (list 'mouse-face 'highlight
4788 'keymap org-mouse-map))
4789 (org-rear-nonsticky-at (match-end 0))
4790 t)))
4791
4792 (defun org-activate-footnote-links (limit)
4793 "Run through the buffer and add overlays to links."
4794 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4795 limit t)
4796 (progn
4797 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4798 (add-text-properties (match-beginning 2) (match-end 2)
4799 (list 'mouse-face 'highlight
4800 'keymap org-mouse-map
4801 'help-echo
4802 (if (= (point-at-bol) (match-beginning 2))
4803 "Footnote definition"
4804 "Footnote reference")
4805 ))
4806 (org-rear-nonsticky-at (match-end 2))
4807 t)))
4808
4809 (defun org-activate-bracket-links (limit)
4810 "Run through the buffer and add overlays to bracketed links."
4811 (if (re-search-forward org-bracket-link-regexp limit t)
4812 (let* ((help (concat "LINK: "
4813 (org-match-string-no-properties 1)))
4814 ;; FIXME: above we should remove the escapes.
4815 ;; but that requires another match, protecting match data,
4816 ;; a lot of overhead for font-lock.
4817 (ip (org-maybe-intangible
4818 (list 'invisible 'org-link
4819 'keymap org-mouse-map 'mouse-face 'highlight
4820 'font-lock-multiline t 'help-echo help)))
4821 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4822 'font-lock-multiline t 'help-echo help)))
4823 ;; We need to remove the invisible property here. Table narrowing
4824 ;; may have made some of this invisible.
4825 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4826 (remove-text-properties (match-beginning 0) (match-end 0)
4827 '(invisible nil))
4828 (if (match-end 3)
4829 (progn
4830 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4831 (org-rear-nonsticky-at (match-beginning 3))
4832 (add-text-properties (match-beginning 3) (match-end 3) vp)
4833 (org-rear-nonsticky-at (match-end 3))
4834 (add-text-properties (match-end 3) (match-end 0) ip)
4835 (org-rear-nonsticky-at (match-end 0)))
4836 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4837 (org-rear-nonsticky-at (match-beginning 1))
4838 (add-text-properties (match-beginning 1) (match-end 1) vp)
4839 (org-rear-nonsticky-at (match-end 1))
4840 (add-text-properties (match-end 1) (match-end 0) ip)
4841 (org-rear-nonsticky-at (match-end 0)))
4842 t)))
4843
4844 (defun org-activate-dates (limit)
4845 "Run through the buffer and add overlays to dates."
4846 (if (re-search-forward org-tsr-regexp-both limit t)
4847 (progn
4848 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4849 (add-text-properties (match-beginning 0) (match-end 0)
4850 (list 'mouse-face 'highlight
4851 'keymap org-mouse-map))
4852 (org-rear-nonsticky-at (match-end 0))
4853 (when org-display-custom-times
4854 (if (match-end 3)
4855 (org-display-custom-time (match-beginning 3) (match-end 3)))
4856 (org-display-custom-time (match-beginning 1) (match-end 1)))
4857 t)))
4858
4859 (defvar org-target-link-regexp nil
4860 "Regular expression matching radio targets in plain text.")
4861 (make-variable-buffer-local 'org-target-link-regexp)
4862 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4863 "Regular expression matching a link target.")
4864 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4865 "Regular expression matching a radio target.")
4866 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4867 "Regular expression matching any target.")
4868
4869 (defun org-activate-target-links (limit)
4870 "Run through the buffer and add overlays to target matches."
4871 (when org-target-link-regexp
4872 (let ((case-fold-search t))
4873 (if (re-search-forward org-target-link-regexp limit t)
4874 (progn
4875 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4876 (add-text-properties (match-beginning 0) (match-end 0)
4877 (list 'mouse-face 'highlight
4878 'keymap org-mouse-map
4879 'help-echo "Radio target link"
4880 'org-linked-text t))
4881 (org-rear-nonsticky-at (match-end 0))
4882 t)))))
4883
4884 (defun org-update-radio-target-regexp ()
4885 "Find all radio targets in this file and update the regular expression."
4886 (interactive)
4887 (when (memq 'radio org-activate-links)
4888 (setq org-target-link-regexp
4889 (org-make-target-link-regexp (org-all-targets 'radio)))
4890 (org-restart-font-lock)))
4891
4892 (defun org-hide-wide-columns (limit)
4893 (let (s e)
4894 (setq s (text-property-any (point) (or limit (point-max))
4895 'org-cwidth t))
4896 (when s
4897 (setq e (next-single-property-change s 'org-cwidth))
4898 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4899 (goto-char e)
4900 t)))
4901
4902 (defvar org-latex-and-specials-regexp nil
4903 "Regular expression for highlighting export special stuff.")
4904 (defvar org-match-substring-regexp)
4905 (defvar org-match-substring-with-braces-regexp)
4906
4907 ;; This should be with the exporter code, but we also use if for font-locking
4908 (defconst org-export-html-special-string-regexps
4909 '(("\\\\-" . "&shy;")
4910 ("---\\([^-]\\)" . "&mdash;\\1")
4911 ("--\\([^-]\\)" . "&ndash;\\1")
4912 ("\\.\\.\\." . "&hellip;"))
4913 "Regular expressions for special string conversion.")
4914
4915
4916 (defun org-compute-latex-and-specials-regexp ()
4917 "Compute regular expression for stuff treated specially by exporters."
4918 (if (not org-highlight-latex-fragments-and-specials)
4919 (org-set-local 'org-latex-and-specials-regexp nil)
4920 (require 'org-exp)
4921 (let*
4922 ((matchers (plist-get org-format-latex-options :matchers))
4923 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4924 org-latex-regexps)))
4925 (org-export-allow-BIND nil)
4926 (options (org-combine-plists (org-default-export-plist)
4927 (org-infile-export-plist)))
4928 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4929 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4930 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4931 (org-export-html-expand (plist-get options :expand-quoted-html))
4932 (org-export-with-special-strings (plist-get options :special-strings))
4933 (re-sub
4934 (cond
4935 ((equal org-export-with-sub-superscripts '{})
4936 (list org-match-substring-with-braces-regexp))
4937 (org-export-with-sub-superscripts
4938 (list org-match-substring-regexp))
4939 (t nil)))
4940 (re-latex
4941 (if org-export-with-LaTeX-fragments
4942 (mapcar (lambda (x) (nth 1 x)) latexs)))
4943 (re-macros
4944 (if org-export-with-TeX-macros
4945 (list (concat "\\\\"
4946 (regexp-opt
4947 (append (mapcar 'car (append org-entities-user
4948 org-entities))
4949 (if (boundp 'org-latex-entities)
4950 (mapcar (lambda (x)
4951 (or (car-safe x) x))
4952 org-latex-entities)
4953 nil))
4954 'words))) ; FIXME
4955 ))
4956 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4957 (re-special (if org-export-with-special-strings
4958 (mapcar (lambda (x) (car x))
4959 org-export-html-special-string-regexps)))
4960 (re-rest
4961 (delq nil
4962 (list
4963 (if org-export-html-expand "@<[^>\n]+>")
4964 ))))
4965 (org-set-local
4966 'org-latex-and-specials-regexp
4967 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4968 re-rest) "\\|")))))
4969
4970 (defun org-do-latex-and-special-faces (limit)
4971 "Run through the buffer and add overlays to links."
4972 (when org-latex-and-specials-regexp
4973 (let (rtn d)
4974 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4975 limit t))
4976 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4977 'face))
4978 '(org-code org-verbatim underline)))
4979 (progn
4980 (setq rtn t
4981 d (cond ((member (char-after (1+ (match-beginning 0)))
4982 '(?_ ?^)) 1)
4983 (t 0)))
4984 (font-lock-prepend-text-property
4985 (+ d (match-beginning 0)) (match-end 0)
4986 'face 'org-latex-and-export-specials)
4987 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4988 '(font-lock-multiline t)))))
4989 rtn)))
4990
4991 (defun org-restart-font-lock ()
4992 "Restart font-lock-mode, to force refontification."
4993 (when (and (boundp 'font-lock-mode) font-lock-mode)
4994 (font-lock-mode -1)
4995 (font-lock-mode 1)))
4996
4997 (defun org-all-targets (&optional radio)
4998 "Return a list of all targets in this file.
4999 With optional argument RADIO, only find radio targets."
5000 (let ((re (if radio org-radio-target-regexp org-target-regexp))
5001 rtn)
5002 (save-excursion
5003 (goto-char (point-min))
5004 (while (re-search-forward re nil t)
5005 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
5006 rtn)))
5007
5008 (defun org-make-target-link-regexp (targets)
5009 "Make regular expression matching all strings in TARGETS.
5010 The regular expression finds the targets also if there is a line break
5011 between words."
5012 (and targets
5013 (concat
5014 "\\<\\("
5015 (mapconcat
5016 (lambda (x)
5017 (while (string-match " +" x)
5018 (setq x (replace-match "\\s-+" t t x)))
5019 x)
5020 targets
5021 "\\|")
5022 "\\)\\>")))
5023
5024 (defun org-activate-tags (limit)
5025 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
5026 (progn
5027 (org-remove-flyspell-overlays-in (match-beginning 1) (match-end 1))
5028 (add-text-properties (match-beginning 1) (match-end 1)
5029 (list 'mouse-face 'highlight
5030 'keymap org-mouse-map))
5031 (org-rear-nonsticky-at (match-end 1))
5032 t)))
5033
5034 (defun org-outline-level ()
5035 "Compute the outline level of the heading at point.
5036 This function assumes that the cursor is at the beginning of a line matched
5037 by outline-regexp. Otherwise it returns garbage.
5038 If this is called at a normal headline, the level is the number of stars.
5039 Use `org-reduced-level' to remove the effect of `org-odd-levels'.
5040 For plain list items, if they are matched by `outline-regexp', this returns
5041 1000 plus the line indentation."
5042 (save-excursion
5043 (looking-at outline-regexp)
5044 (if (match-beginning 1)
5045 (+ (org-get-string-indentation (match-string 1)) 1000)
5046 (1- (- (match-end 0) (match-beginning 0))))))
5047
5048 (defvar org-font-lock-keywords nil)
5049
5050 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
5051 "Regular expression matching a property line.")
5052
5053 (defvar org-font-lock-hook nil
5054 "Functions to be called for special font lock stuff.")
5055
5056 (defun org-font-lock-hook (limit)
5057 (run-hook-with-args 'org-font-lock-hook limit))
5058
5059 (defun org-set-font-lock-defaults ()
5060 (let* ((em org-fontify-emphasized-text)
5061 (lk org-activate-links)
5062 (org-font-lock-extra-keywords
5063 (list
5064 ;; Call the hook
5065 '(org-font-lock-hook)
5066 ;; Headlines
5067 `(,(if org-fontify-whole-heading-line
5068 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
5069 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
5070 (1 (org-get-level-face 1))
5071 (2 (org-get-level-face 2))
5072 (3 (org-get-level-face 3)))
5073 ;; Table lines
5074 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
5075 (1 'org-table t))
5076 ;; Table internals
5077 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
5078 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
5079 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
5080 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
5081 ;; Drawers
5082 (list org-drawer-regexp '(0 'org-special-keyword t))
5083 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
5084 ;; Properties
5085 (list org-property-re
5086 '(1 'org-special-keyword t)
5087 '(3 'org-property-value t))
5088 ;; Links
5089 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
5090 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
5091 (if (memq 'plain lk) '(org-activate-plain-links))
5092 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
5093 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
5094 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
5095 (if (memq 'footnote lk) '(org-activate-footnote-links
5096 (2 'org-footnote t)))
5097 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
5098 '(org-hide-wide-columns (0 nil append))
5099 ;; TODO lines
5100 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
5101 '(1 (org-get-todo-face 1) t))
5102 ;; DONE
5103 (if org-fontify-done-headline
5104 (list (concat "^[*]+ +\\<\\("
5105 (mapconcat 'regexp-quote org-done-keywords "\\|")
5106 "\\)\\(.*\\)")
5107 '(2 'org-headline-done t))
5108 nil)
5109 ;; Priorities
5110 '(org-font-lock-add-priority-faces)
5111 ;; Tags
5112 '(org-font-lock-add-tag-faces)
5113 ;; Special keywords
5114 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
5115 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
5116 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
5117 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
5118 ;; Emphasis
5119 (if em
5120 (if (featurep 'xemacs)
5121 '(org-do-emphasis-faces (0 nil append))
5122 '(org-do-emphasis-faces)))
5123 ;; Checkboxes
5124 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
5125 2 'org-checkbox prepend)
5126 (if org-provide-checkbox-statistics
5127 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
5128 (0 (org-get-checkbox-statistics-face) t)))
5129 ;; Description list items
5130 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
5131 2 'bold prepend)
5132 ;; ARCHIVEd headings
5133 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
5134 '(1 'org-archived prepend))
5135 ;; Specials
5136 '(org-do-latex-and-special-faces)
5137 ;; Code
5138 '(org-activate-code (1 'org-code t))
5139 ;; COMMENT
5140 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
5141 "\\|" org-quote-string "\\)\\>")
5142 '(1 'org-special-keyword t))
5143 '("^#.*" (0 'font-lock-comment-face t))
5144 ;; Blocks and meta lines
5145 '(org-fontify-meta-lines-and-blocks)
5146 )))
5147 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
5148 ;; Now set the full font-lock-keywords
5149 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
5150 (org-set-local 'font-lock-defaults
5151 '(org-font-lock-keywords t nil nil backward-paragraph))
5152 (kill-local-variable 'font-lock-keywords) nil))
5153
5154 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
5155 "Fontify string S like in Org-mode"
5156 (with-temp-buffer
5157 (insert s)
5158 (let ((org-odd-levels-only odd-levels))
5159 (org-mode)
5160 (font-lock-fontify-buffer)
5161 (buffer-string))))
5162
5163 (defvar org-m nil)
5164 (defvar org-l nil)
5165 (defvar org-f nil)
5166 (defun org-get-level-face (n)
5167 "Get the right face for match N in font-lock matching of headlines."
5168 (setq org-l (- (match-end 2) (match-beginning 1) 1))
5169 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
5170 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
5171 (cond
5172 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
5173 ((eq n 2) org-f)
5174 (t (if org-level-color-stars-only nil org-f))))
5175
5176 (defun org-get-todo-face (kwd)
5177 "Get the right face for a TODO keyword KWD.
5178 If KWD is a number, get the corresponding match group."
5179 (if (numberp kwd) (setq kwd (match-string kwd)))
5180 (or (org-face-from-face-or-color
5181 'todo 'org-todo (cdr (assoc kwd org-todo-keyword-faces)))
5182 (and (member kwd org-done-keywords) 'org-done)
5183 'org-todo))
5184
5185 (defun org-face-from-face-or-color (context inherit face-or-color)
5186 "Create a face list that inherits INHERIT, but sets the foreground color.
5187 When FACE-OR-COLOR is not a string, just return it."
5188 (if (stringp face-or-color)
5189 (list :inherit inherit
5190 (cdr (assoc context org-faces-easy-properties))
5191 face-or-color)
5192 face-or-color))
5193
5194 (defun org-font-lock-add-tag-faces (limit)
5195 "Add the special tag faces."
5196 (when (and org-tag-faces org-tags-special-faces-re)
5197 (while (re-search-forward org-tags-special-faces-re limit t)
5198 (add-text-properties (match-beginning 1) (match-end 1)
5199 (list 'face (org-get-tag-face 1)
5200 'font-lock-fontified t))
5201 (backward-char 1))))
5202
5203 (defun org-font-lock-add-priority-faces (limit)
5204 "Add the special priority faces."
5205 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
5206 (add-text-properties
5207 (match-beginning 0) (match-end 0)
5208 (list 'face (or (org-face-from-face-or-color
5209 'priority 'org-special-keyword
5210 (cdr (assoc (char-after (match-beginning 1))
5211 org-priority-faces)))
5212 'org-special-keyword)
5213 'font-lock-fontified t))))
5214
5215 (defun org-get-tag-face (kwd)
5216 "Get the right face for a TODO keyword KWD.
5217 If KWD is a number, get the corresponding match group."
5218 (if (numberp kwd) (setq kwd (match-string kwd)))
5219 (or (org-face-from-face-or-color
5220 'tag 'org-tag (cdr (assoc kwd org-tag-faces)))
5221 'org-tag))
5222
5223 (defun org-unfontify-region (beg end &optional maybe_loudly)
5224 "Remove fontification and activation overlays from links."
5225 (font-lock-default-unfontify-region beg end)
5226 (let* ((buffer-undo-list t)
5227 (inhibit-read-only t) (inhibit-point-motion-hooks t)
5228 (inhibit-modification-hooks t)
5229 deactivate-mark buffer-file-name buffer-file-truename)
5230 (remove-text-properties
5231 beg end
5232 (if org-indent-mode
5233 ;; also remove line-prefix and wrap-prefix properties
5234 '(mouse-face t keymap t org-linked-text t
5235 invisible t intangible t
5236 line-prefix t wrap-prefix t
5237 org-no-flyspell t)
5238 '(mouse-face t keymap t org-linked-text t
5239 invisible t intangible t
5240 org-no-flyspell t)))))
5241
5242 ;;;; Visibility cycling, including org-goto and indirect buffer
5243
5244 ;;; Cycling
5245
5246 (defvar org-cycle-global-status nil)
5247 (make-variable-buffer-local 'org-cycle-global-status)
5248 (defvar org-cycle-subtree-status nil)
5249 (make-variable-buffer-local 'org-cycle-subtree-status)
5250
5251 ;;;###autoload
5252
5253 (defvar org-inlinetask-min-level)
5254
5255 (defun org-cycle (&optional arg)
5256 "TAB-action and visibility cycling for Org-mode.
5257
5258 This is the command invoked in Org-mode by the TAB key. Its main purpose
5259 is outline visibility cycling, but it also invokes other actions
5260 in special contexts.
5261
5262 - When this function is called with a prefix argument, rotate the entire
5263 buffer through 3 states (global cycling)
5264 1. OVERVIEW: Show only top-level headlines.
5265 2. CONTENTS: Show all headlines of all levels, but no body text.
5266 3. SHOW ALL: Show everything.
5267 When called with two `C-u C-u' prefixes, switch to the startup visibility,
5268 determined by the variable `org-startup-folded', and by any VISIBILITY
5269 properties in the buffer.
5270 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
5271 including any drawers.
5272
5273 - When inside a table, re-align the table and move to the next field.
5274
5275 - When point is at the beginning of a headline, rotate the subtree started
5276 by this line through 3 different states (local cycling)
5277 1. FOLDED: Only the main headline is shown.
5278 2. CHILDREN: The main headline and the direct children are shown.
5279 From this state, you can move to one of the children
5280 and zoom in further.
5281 3. SUBTREE: Show the entire subtree, including body text.
5282 If there is no subtree, switch directly from CHILDREN to FOLDED.
5283
5284 - When point is at the beginning of an empty headline and the variable
5285 `org-cycle-level-after-item/entry-creation' is set, cycle the level
5286 of the headline by demoting and promoting it to likely levels. This
5287 speeds up creation document structure by presing TAB once or several
5288 times right after creating a new headline.
5289
5290 - When there is a numeric prefix, go up to a heading with level ARG, do
5291 a `show-subtree' and return to the previous cursor position. If ARG
5292 is negative, go up that many levels.
5293
5294 - When point is not at the beginning of a headline, execute the global
5295 binding for TAB, which is re-indenting the line. See the option
5296 `org-cycle-emulate-tab' for details.
5297
5298 - Special case: if point is at the beginning of the buffer and there is
5299 no headline in line 1, this function will act as if called with prefix arg.
5300 But only if also the variable `org-cycle-global-at-bob' is t."
5301 (interactive "P")
5302 (org-load-modules-maybe)
5303 (unless (or (run-hook-with-args-until-success 'org-tab-first-hook)
5304 (and org-cycle-level-after-item/entry-creation
5305 (or (org-cycle-level)
5306 (org-cycle-item-indentation))))
5307 (let* ((limit-level
5308 (or org-cycle-max-level
5309 (and (boundp 'org-inlinetask-min-level)
5310 org-inlinetask-min-level
5311 (1- org-inlinetask-min-level))))
5312 (nstars (and limit-level
5313 (if org-odd-levels-only
5314 (and limit-level (1- (* limit-level 2)))
5315 limit-level)))
5316 (outline-regexp
5317 (cond
5318 ((not (org-mode-p)) outline-regexp)
5319 ((or (eq org-cycle-include-plain-lists 'integrate)
5320 (and org-cycle-include-plain-lists (org-at-item-p)))
5321 (concat "\\(?:\\*"
5322 (if nstars (format "\\{1,%d\\}" nstars) "+")
5323 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
5324 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
5325 (bob-special (and org-cycle-global-at-bob (bobp)
5326 (not (looking-at outline-regexp))))
5327 (org-cycle-hook
5328 (if bob-special
5329 (delq 'org-optimize-window-after-visibility-change
5330 (copy-sequence org-cycle-hook))
5331 org-cycle-hook))
5332 (pos (point)))
5333
5334 (if (or bob-special (equal arg '(4)))
5335 ;; special case: use global cycling
5336 (setq arg t))
5337
5338 (cond
5339
5340 ((equal arg '(16))
5341 (org-set-startup-visibility)
5342 (message "Startup visibility, plus VISIBILITY properties"))
5343
5344 ((equal arg '(64))
5345 (show-all)
5346 (message "Entire buffer visible, including drawers"))
5347
5348 ((org-at-table-p 'any)
5349 ;; Enter the table or move to the next field in the table
5350 (if (org-at-table.el-p)
5351 (message "Use C-c ' to edit table.el tables")
5352 (if arg (org-table-edit-field t)
5353 (org-table-justify-field-maybe)
5354 (call-interactively 'org-table-next-field))))
5355
5356 ((run-hook-with-args-until-success
5357 'org-tab-after-check-for-table-hook))
5358
5359 ((eq arg t) ;; Global cycling
5360 (org-cycle-internal-global))
5361
5362 ((and org-drawers org-drawer-regexp
5363 (save-excursion
5364 (beginning-of-line 1)
5365 (looking-at org-drawer-regexp)))
5366 ;; Toggle block visibility
5367 (org-flag-drawer
5368 (not (get-char-property (match-end 0) 'invisible))))
5369
5370 ((integerp arg)
5371 ;; Show-subtree, ARG levels up from here.
5372 (save-excursion
5373 (org-back-to-heading)
5374 (outline-up-heading (if (< arg 0) (- arg)
5375 (- (funcall outline-level) arg)))
5376 (org-show-subtree)))
5377
5378 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
5379 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
5380
5381 (org-cycle-internal-local))
5382
5383 ;; TAB emulation and template completion
5384 (buffer-read-only (org-back-to-heading))
5385
5386 ((run-hook-with-args-until-success
5387 'org-tab-after-check-for-cycling-hook))
5388
5389 ((org-try-structure-completion))
5390
5391 ((org-try-cdlatex-tab))
5392
5393 ((run-hook-with-args-until-success
5394 'org-tab-before-tab-emulation-hook))
5395
5396 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
5397 (or (not (bolp))
5398 (not (looking-at outline-regexp))))
5399 (call-interactively (global-key-binding "\t")))
5400
5401 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
5402 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
5403 (or (and (eq org-cycle-emulate-tab 'white)
5404 (= (match-end 0) (point-at-eol)))
5405 (and (eq org-cycle-emulate-tab 'whitestart)
5406 (>= (match-end 0) pos))))
5407 t
5408 (eq org-cycle-emulate-tab t))
5409 (call-interactively (global-key-binding "\t")))
5410
5411 (t (save-excursion
5412 (org-back-to-heading)
5413 (org-cycle)))))))
5414
5415 (defun org-cycle-internal-global ()
5416 "Do the global cycling action."
5417 (cond
5418 ((and (eq last-command this-command)
5419 (eq org-cycle-global-status 'overview))
5420 ;; We just created the overview - now do table of contents
5421 ;; This can be slow in very large buffers, so indicate action
5422 (run-hook-with-args 'org-pre-cycle-hook 'contents)
5423 (message "CONTENTS...")
5424 (org-content)
5425 (message "CONTENTS...done")
5426 (setq org-cycle-global-status 'contents)
5427 (run-hook-with-args 'org-cycle-hook 'contents))
5428
5429 ((and (eq last-command this-command)
5430 (eq org-cycle-global-status 'contents))
5431 ;; We just showed the table of contents - now show everything
5432 (run-hook-with-args 'org-pre-cycle-hook 'all)
5433 (show-all)
5434 (message "SHOW ALL")
5435 (setq org-cycle-global-status 'all)
5436 (run-hook-with-args 'org-cycle-hook 'all))
5437
5438 (t
5439 ;; Default action: go to overview
5440 (run-hook-with-args 'org-pre-cycle-hook 'overview)
5441 (org-overview)
5442 (message "OVERVIEW")
5443 (setq org-cycle-global-status 'overview)
5444 (run-hook-with-args 'org-cycle-hook 'overview))))
5445
5446 (defun org-cycle-internal-local ()
5447 "Do the local cycling action."
5448 (org-back-to-heading)
5449 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
5450 ;; First, some boundaries
5451 (save-excursion
5452 (org-back-to-heading)
5453 (setq level (funcall outline-level))
5454 (save-excursion
5455 (beginning-of-line 2)
5456 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
5457 ; XEmacs does not have `next-single-char-property-change'
5458 ; I'm not sure about Emacs 21.
5459 (while (and (not (eobp)) ;; this is like `next-line'
5460 (get-char-property (1- (point)) 'invisible))
5461 (beginning-of-line 2))
5462 (while (and (not (eobp)) ;; this is like `next-line'
5463 (get-char-property (1- (point)) 'invisible))
5464 (goto-char (next-single-char-property-change (point) 'invisible))
5465 ;;;??? (or (bolp) (beginning-of-line 2))))
5466 (and (eolp) (beginning-of-line 2))))
5467 (setq eol (point)))
5468 (outline-end-of-heading) (setq eoh (point))
5469 (save-excursion
5470 (outline-next-heading)
5471 (setq has-children (and (org-at-heading-p t)
5472 (> (funcall outline-level) level))))
5473 (org-end-of-subtree t)
5474 (unless (eobp)
5475 (skip-chars-forward " \t\n")
5476 (beginning-of-line 1) ; in case this is an item
5477 )
5478 (setq eos (if (eobp) (point) (1- (point)))))
5479 ;; Find out what to do next and set `this-command'
5480 (cond
5481 ((= eos eoh)
5482 ;; Nothing is hidden behind this heading
5483 (run-hook-with-args 'org-pre-cycle-hook 'empty)
5484 (message "EMPTY ENTRY")
5485 (setq org-cycle-subtree-status nil)
5486 (save-excursion
5487 (goto-char eos)
5488 (outline-next-heading)
5489 (if (org-invisible-p) (org-flag-heading nil))))
5490 ((and (or (>= eol eos)
5491 (not (string-match "\\S-" (buffer-substring eol eos))))
5492 (or has-children
5493 (not (setq children-skipped
5494 org-cycle-skip-children-state-if-no-children))))
5495 ;; Entire subtree is hidden in one line: children view
5496 (run-hook-with-args 'org-pre-cycle-hook 'children)
5497 (org-show-entry)
5498 (show-children)
5499 (message "CHILDREN")
5500 (save-excursion
5501 (goto-char eos)
5502 (outline-next-heading)
5503 (if (org-invisible-p) (org-flag-heading nil)))
5504 (setq org-cycle-subtree-status 'children)
5505 (run-hook-with-args 'org-cycle-hook 'children))
5506 ((or children-skipped
5507 (and (eq last-command this-command)
5508 (eq org-cycle-subtree-status 'children)))
5509 ;; We just showed the children, or no children are there,
5510 ;; now show everything.
5511 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5512 (org-show-subtree)
5513 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5514 (setq org-cycle-subtree-status 'subtree)
5515 (run-hook-with-args 'org-cycle-hook 'subtree))
5516 (t
5517 ;; Default action: hide the subtree.
5518 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5519 (hide-subtree)
5520 (message "FOLDED")
5521 (setq org-cycle-subtree-status 'folded)
5522 (run-hook-with-args 'org-cycle-hook 'folded)))))
5523
5524 ;;;###autoload
5525 (defun org-global-cycle (&optional arg)
5526 "Cycle the global visibility. For details see `org-cycle'.
5527 With C-u prefix arg, switch to startup visibility.
5528 With a numeric prefix, show all headlines up to that level."
5529 (interactive "P")
5530 (let ((org-cycle-include-plain-lists
5531 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5532 (cond
5533 ((integerp arg)
5534 (show-all)
5535 (hide-sublevels arg)
5536 (setq org-cycle-global-status 'contents))
5537 ((equal arg '(4))
5538 (org-set-startup-visibility)
5539 (message "Startup visibility, plus VISIBILITY properties."))
5540 (t
5541 (org-cycle '(4))))))
5542
5543 (defun org-set-startup-visibility ()
5544 "Set the visibility required by startup options and properties."
5545 (cond
5546 ((eq org-startup-folded t)
5547 (org-cycle '(4)))
5548 ((eq org-startup-folded 'content)
5549 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5550 (org-cycle '(4)) (org-cycle '(4)))))
5551 (unless (eq org-startup-folded 'showeverything)
5552 (if org-hide-block-startup (org-hide-block-all))
5553 (org-set-visibility-according-to-property 'no-cleanup)
5554 (org-cycle-hide-archived-subtrees 'all)
5555 (org-cycle-hide-drawers 'all)
5556 (org-cycle-show-empty-lines 'all)))
5557
5558 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5559 "Switch subtree visibilities according to :VISIBILITY: property."
5560 (interactive)
5561 (let (org-show-entry-below state)
5562 (save-excursion
5563 (goto-char (point-min))
5564 (while (re-search-forward
5565 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5566 nil t)
5567 (setq state (match-string 1))
5568 (save-excursion
5569 (org-back-to-heading t)
5570 (hide-subtree)
5571 (org-reveal)
5572 (cond
5573 ((equal state '("fold" "folded"))
5574 (hide-subtree))
5575 ((equal state "children")
5576 (org-show-hidden-entry)
5577 (show-children))
5578 ((equal state "content")
5579 (save-excursion
5580 (save-restriction
5581 (org-narrow-to-subtree)
5582 (org-content))))
5583 ((member state '("all" "showall"))
5584 (show-subtree)))))
5585 (unless no-cleanup
5586 (org-cycle-hide-archived-subtrees 'all)
5587 (org-cycle-hide-drawers 'all)
5588 (org-cycle-show-empty-lines 'all)))))
5589
5590 (defun org-overview ()
5591 "Switch to overview mode, showing only top-level headlines.
5592 Really, this shows all headlines with level equal or greater than the level
5593 of the first headline in the buffer. This is important, because if the
5594 first headline is not level one, then (hide-sublevels 1) gives confusing
5595 results."
5596 (interactive)
5597 (let ((level (save-excursion
5598 (goto-char (point-min))
5599 (if (re-search-forward (concat "^" outline-regexp) nil t)
5600 (progn
5601 (goto-char (match-beginning 0))
5602 (funcall outline-level))))))
5603 (and level (hide-sublevels level))))
5604
5605 (defun org-content (&optional arg)
5606 "Show all headlines in the buffer, like a table of contents.
5607 With numerical argument N, show content up to level N."
5608 (interactive "P")
5609 (save-excursion
5610 ;; Visit all headings and show their offspring
5611 (and (integerp arg) (org-overview))
5612 (goto-char (point-max))
5613 (catch 'exit
5614 (while (and (progn (condition-case nil
5615 (outline-previous-visible-heading 1)
5616 (error (goto-char (point-min))))
5617 t)
5618 (looking-at outline-regexp))
5619 (if (integerp arg)
5620 (show-children (1- arg))
5621 (show-branches))
5622 (if (bobp) (throw 'exit nil))))))
5623
5624
5625 (defun org-optimize-window-after-visibility-change (state)
5626 "Adjust the window after a change in outline visibility.
5627 This function is the default value of the hook `org-cycle-hook'."
5628 (when (get-buffer-window (current-buffer))
5629 (cond
5630 ((eq state 'content) nil)
5631 ((eq state 'all) nil)
5632 ((eq state 'folded) nil)
5633 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5634 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5635
5636 (defun org-remove-empty-overlays-at (pos)
5637 "Remove outline overlays that do not contain non-white stuff."
5638 (mapc
5639 (lambda (o)
5640 (and (eq 'outline (org-overlay-get o 'invisible))
5641 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5642 (org-overlay-end o))))
5643 (org-delete-overlay o)))
5644 (org-overlays-at pos)))
5645
5646 (defun org-clean-visibility-after-subtree-move ()
5647 "Fix visibility issues after moving a subtree."
5648 ;; First, find a reasonable region to look at:
5649 ;; Start two siblings above, end three below
5650 (let* ((beg (save-excursion
5651 (and (org-get-last-sibling)
5652 (org-get-last-sibling))
5653 (point)))
5654 (end (save-excursion
5655 (and (org-get-next-sibling)
5656 (org-get-next-sibling)
5657 (org-get-next-sibling))
5658 (if (org-at-heading-p)
5659 (point-at-eol)
5660 (point))))
5661 (level (looking-at "\\*+"))
5662 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5663 (save-excursion
5664 (save-restriction
5665 (narrow-to-region beg end)
5666 (when re
5667 ;; Properly fold already folded siblings
5668 (goto-char (point-min))
5669 (while (re-search-forward re nil t)
5670 (if (and (not (org-invisible-p))
5671 (save-excursion
5672 (goto-char (point-at-eol)) (org-invisible-p)))
5673 (hide-entry))))
5674 (org-cycle-show-empty-lines 'overview)
5675 (org-cycle-hide-drawers 'overview)))))
5676
5677 (defun org-cycle-show-empty-lines (state)
5678 "Show empty lines above all visible headlines.
5679 The region to be covered depends on STATE when called through
5680 `org-cycle-hook'. Lisp program can use t for STATE to get the
5681 entire buffer covered. Note that an empty line is only shown if there
5682 are at least `org-cycle-separator-lines' empty lines before the headline."
5683 (when (not (= org-cycle-separator-lines 0))
5684 (save-excursion
5685 (let* ((n (abs org-cycle-separator-lines))
5686 (re (cond
5687 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5688 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5689 (t (let ((ns (number-to-string (- n 2))))
5690 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5691 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5692 beg end b e)
5693 (cond
5694 ((memq state '(overview contents t))
5695 (setq beg (point-min) end (point-max)))
5696 ((memq state '(children folded))
5697 (setq beg (point) end (progn (org-end-of-subtree t t)
5698 (beginning-of-line 2)
5699 (point)))))
5700 (when beg
5701 (goto-char beg)
5702 (while (re-search-forward re end t)
5703 (unless (get-char-property (match-end 1) 'invisible)
5704 (setq e (match-end 1))
5705 (if (< org-cycle-separator-lines 0)
5706 (setq b (save-excursion
5707 (goto-char (match-beginning 0))
5708 (org-back-over-empty-lines)
5709 (if (save-excursion
5710 (goto-char (max (point-min) (1- (point))))
5711 (org-on-heading-p))
5712 (1- (point))
5713 (point))))
5714 (setq b (match-beginning 1)))
5715 (outline-flag-region b e nil)))))))
5716 ;; Never hide empty lines at the end of the file.
5717 (save-excursion
5718 (goto-char (point-max))
5719 (outline-previous-heading)
5720 (outline-end-of-heading)
5721 (if (and (looking-at "[ \t\n]+")
5722 (= (match-end 0) (point-max)))
5723 (outline-flag-region (point) (match-end 0) nil))))
5724
5725 (defun org-show-empty-lines-in-parent ()
5726 "Move to the parent and re-show empty lines before visible headlines."
5727 (save-excursion
5728 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5729 (org-cycle-show-empty-lines context))))
5730
5731 (defun org-files-list ()
5732 "Return `org-agenda-files' list, plus all open org-mode files.
5733 This is useful for operations that need to scan all of a user's
5734 open and agenda-wise Org files."
5735 (let ((files (mapcar 'expand-file-name (org-agenda-files))))
5736 (dolist (buf (buffer-list))
5737 (with-current-buffer buf
5738 (if (and (eq major-mode 'org-mode) (buffer-file-name))
5739 (let ((file (expand-file-name (buffer-file-name))))
5740 (unless (member file files)
5741 (push file files))))))
5742 files))
5743
5744 (defsubst org-entry-beginning-position ()
5745 "Return the beginning position of the current entry."
5746 (save-excursion (outline-back-to-heading t) (point)))
5747
5748 (defsubst org-entry-end-position ()
5749 "Return the end position of the current entry."
5750 (save-excursion (outline-next-heading) (point)))
5751
5752 (defun org-cycle-hide-drawers (state)
5753 "Re-hide all drawers after a visibility state change."
5754 (when (and (org-mode-p)
5755 (not (memq state '(overview folded contents))))
5756 (save-excursion
5757 (let* ((globalp (memq state '(contents all)))
5758 (beg (if globalp (point-min) (point)))
5759 (end (if globalp (point-max)
5760 (if (eq state 'children)
5761 (save-excursion (outline-next-heading) (point))
5762 (org-end-of-subtree t)))))
5763 (goto-char beg)
5764 (while (re-search-forward org-drawer-regexp end t)
5765 (org-flag-drawer t))))))
5766
5767 (defun org-flag-drawer (flag)
5768 (save-excursion
5769 (beginning-of-line 1)
5770 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5771 (let ((b (match-end 0))
5772 (outline-regexp org-outline-regexp))
5773 (if (re-search-forward
5774 "^[ \t]*:END:"
5775 (save-excursion (outline-next-heading) (point)) t)
5776 (outline-flag-region b (point-at-eol) flag)
5777 (error ":END: line missing at position %s" b))))))
5778
5779 (defun org-subtree-end-visible-p ()
5780 "Is the end of the current subtree visible?"
5781 (pos-visible-in-window-p
5782 (save-excursion (org-end-of-subtree t) (point))))
5783
5784 (defun org-first-headline-recenter (&optional N)
5785 "Move cursor to the first headline and recenter the headline.
5786 Optional argument N means put the headline into the Nth line of the window."
5787 (goto-char (point-min))
5788 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5789 (beginning-of-line)
5790 (recenter (prefix-numeric-value N))))
5791
5792 ;;; Saving and restoring visibility
5793
5794 (defun org-outline-overlay-data (&optional use-markers)
5795 "Return a list of the locations of all outline overlays.
5796 The are overlays with the `invisible' property value `outline'.
5797 The return valus is a list of cons cells, with start and stop
5798 positions for each overlay.
5799 If USE-MARKERS is set, return the positions as markers."
5800 (let (beg end)
5801 (save-excursion
5802 (save-restriction
5803 (widen)
5804 (delq nil
5805 (mapcar (lambda (o)
5806 (when (eq (org-overlay-get o 'invisible) 'outline)
5807 (setq beg (org-overlay-start o)
5808 end (org-overlay-end o))
5809 (and beg end (> end beg)
5810 (if use-markers
5811 (cons (move-marker (make-marker) beg)
5812 (move-marker (make-marker) end))
5813 (cons beg end)))))
5814 (org-overlays-in (point-min) (point-max))))))))
5815
5816 (defun org-set-outline-overlay-data (data)
5817 "Create visibility overlays for all positions in DATA.
5818 DATA should have been made by `org-outline-overlay-data'."
5819 (let (o)
5820 (save-excursion
5821 (save-restriction
5822 (widen)
5823 (show-all)
5824 (mapc (lambda (c)
5825 (setq o (org-make-overlay (car c) (cdr c)))
5826 (org-overlay-put o 'invisible 'outline))
5827 data)))))
5828
5829 (defmacro org-save-outline-visibility (use-markers &rest body)
5830 "Save and restore outline visibility around BODY.
5831 If USE-MARKERS is non-nil, use markers for the positions.
5832 This means that the buffer may change while running BODY,
5833 but it also means that the buffer should stay alive
5834 during the operation, because otherwise all these markers will
5835 point nowhere."
5836 `(let ((data (org-outline-overlay-data ,use-markers)))
5837 (unwind-protect
5838 (progn
5839 ,@body
5840 (org-set-outline-overlay-data data))
5841 (when ,use-markers
5842 (mapc (lambda (c)
5843 (and (markerp (car c)) (move-marker (car c) nil))
5844 (and (markerp (cdr c)) (move-marker (cdr c) nil)))
5845 data)))))
5846
5847
5848 ;;; Folding of blocks
5849
5850 (defconst org-block-regexp
5851
5852 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5853 "Regular expression for hiding blocks.")
5854
5855 (defvar org-hide-block-overlays nil
5856 "Overlays hiding blocks.")
5857 (make-variable-buffer-local 'org-hide-block-overlays)
5858
5859 (defun org-block-map (function &optional start end)
5860 "Call func at the head of all source blocks in the current
5861 buffer. Optional arguments START and END can be used to limit
5862 the range."
5863 (let ((start (or start (point-min)))
5864 (end (or end (point-max))))
5865 (save-excursion
5866 (goto-char start)
5867 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5868 (save-excursion
5869 (save-match-data
5870 (goto-char (match-beginning 0))
5871 (funcall function)))))))
5872
5873 (defun org-hide-block-toggle-all ()
5874 "Toggle the visibility of all blocks in the current buffer."
5875 (org-block-map #'org-hide-block-toggle))
5876
5877 (defun org-hide-block-all ()
5878 "Fold all blocks in the current buffer."
5879 (interactive)
5880 (org-show-block-all)
5881 (org-block-map #'org-hide-block-toggle-maybe))
5882
5883 (defun org-show-block-all ()
5884 "Unfold all blocks in the current buffer."
5885 (mapc 'org-delete-overlay org-hide-block-overlays)
5886 (setq org-hide-block-overlays nil))
5887
5888 (defun org-hide-block-toggle-maybe ()
5889 "Toggle visibility of block at point."
5890 (interactive)
5891 (let ((case-fold-search t))
5892 (if (save-excursion
5893 (beginning-of-line 1)
5894 (looking-at org-block-regexp))
5895 (progn (org-hide-block-toggle)
5896 t) ;; to signal that we took action
5897 nil))) ;; to signal that we did not
5898
5899 (defun org-hide-block-toggle (&optional force)
5900 "Toggle the visibility of the current block."
5901 (interactive)
5902 (save-excursion
5903 (beginning-of-line)
5904 (if (re-search-forward org-block-regexp nil t)
5905 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5906 (end (match-end 0)) ;; end of entire body
5907 ov)
5908 (if (memq t (mapcar (lambda (overlay)
5909 (eq (org-overlay-get overlay 'invisible)
5910 'org-hide-block))
5911 (org-overlays-at start)))
5912 (if (or (not force) (eq force 'off))
5913 (mapc (lambda (ov)
5914 (when (member ov org-hide-block-overlays)
5915 (setq org-hide-block-overlays
5916 (delq ov org-hide-block-overlays)))
5917 (when (eq (org-overlay-get ov 'invisible)
5918 'org-hide-block)
5919 (org-delete-overlay ov)))
5920 (org-overlays-at start)))
5921 (setq ov (org-make-overlay start end))
5922 (org-overlay-put ov 'invisible 'org-hide-block)
5923 ;; make the block accessible to isearch
5924 (org-overlay-put
5925 ov 'isearch-open-invisible
5926 (lambda (ov)
5927 (when (member ov org-hide-block-overlays)
5928 (setq org-hide-block-overlays
5929 (delq ov org-hide-block-overlays)))
5930 (when (eq (org-overlay-get ov 'invisible)
5931 'org-hide-block)
5932 (org-delete-overlay ov))))
5933 (push ov org-hide-block-overlays)))
5934 (error "Not looking at a source block"))))
5935
5936 ;; org-tab-after-check-for-cycling-hook
5937 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5938 ;; Remove overlays when changing major mode
5939 (add-hook 'org-mode-hook
5940 (lambda () (org-add-hook 'change-major-mode-hook
5941 'org-show-block-all 'append 'local)))
5942
5943 ;;; Org-goto
5944
5945 (defvar org-goto-window-configuration nil)
5946 (defvar org-goto-marker nil)
5947 (defvar org-goto-map
5948 (let ((map (make-sparse-keymap)))
5949 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5950 (while (setq cmd (pop cmds))
5951 (substitute-key-definition cmd cmd map global-map)))
5952 (suppress-keymap map)
5953 (org-defkey map "\C-m" 'org-goto-ret)
5954 (org-defkey map [(return)] 'org-goto-ret)
5955 (org-defkey map [(left)] 'org-goto-left)
5956 (org-defkey map [(right)] 'org-goto-right)
5957 (org-defkey map [(control ?g)] 'org-goto-quit)
5958 (org-defkey map "\C-i" 'org-cycle)
5959 (org-defkey map [(tab)] 'org-cycle)
5960 (org-defkey map [(down)] 'outline-next-visible-heading)
5961 (org-defkey map [(up)] 'outline-previous-visible-heading)
5962 (if org-goto-auto-isearch
5963 (if (fboundp 'define-key-after)
5964 (define-key-after map [t] 'org-goto-local-auto-isearch)
5965 nil)
5966 (org-defkey map "q" 'org-goto-quit)
5967 (org-defkey map "n" 'outline-next-visible-heading)
5968 (org-defkey map "p" 'outline-previous-visible-heading)
5969 (org-defkey map "f" 'outline-forward-same-level)
5970 (org-defkey map "b" 'outline-backward-same-level)
5971 (org-defkey map "u" 'outline-up-heading))
5972 (org-defkey map "/" 'org-occur)
5973 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5974 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5975 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5976 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5977 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5978 map))
5979
5980 (defconst org-goto-help
5981 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5982 RET=jump to location [Q]uit and return to previous location
5983 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5984
5985 (defvar org-goto-start-pos) ; dynamically scoped parameter
5986
5987 ;; FIXME: Docstring does not mention both interfaces
5988 (defun org-goto (&optional alternative-interface)
5989 "Look up a different location in the current file, keeping current visibility.
5990
5991 When you want look-up or go to a different location in a document, the
5992 fastest way is often to fold the entire buffer and then dive into the tree.
5993 This method has the disadvantage, that the previous location will be folded,
5994 which may not be what you want.
5995
5996 This command works around this by showing a copy of the current buffer
5997 in an indirect buffer, in overview mode. You can dive into the tree in
5998 that copy, use org-occur and incremental search to find a location.
5999 When pressing RET or `Q', the command returns to the original buffer in
6000 which the visibility is still unchanged. After RET is will also jump to
6001 the location selected in the indirect buffer and expose the
6002 the headline hierarchy above."
6003 (interactive "P")
6004 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
6005 (org-refile-use-outline-path t)
6006 (org-refile-target-verify-function nil)
6007 (interface
6008 (if (not alternative-interface)
6009 org-goto-interface
6010 (if (eq org-goto-interface 'outline)
6011 'outline-path-completion
6012 'outline)))
6013 (org-goto-start-pos (point))
6014 (selected-point
6015 (if (eq interface 'outline)
6016 (car (org-get-location (current-buffer) org-goto-help))
6017 (nth 3 (org-refile-get-location "Goto: ")))))
6018 (if selected-point
6019 (progn
6020 (org-mark-ring-push org-goto-start-pos)
6021 (goto-char selected-point)
6022 (if (or (org-invisible-p) (org-invisible-p2))
6023 (org-show-context 'org-goto)))
6024 (message "Quit"))))
6025
6026 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
6027 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
6028 (defvar org-goto-local-auto-isearch-map) ; defined below
6029
6030 (defun org-get-location (buf help)
6031 "Let the user select a location in the Org-mode buffer BUF.
6032 This function uses a recursive edit. It returns the selected position
6033 or nil."
6034 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
6035 (isearch-hide-immediately nil)
6036 (isearch-search-fun-function
6037 (lambda () 'org-goto-local-search-headings))
6038 (org-goto-selected-point org-goto-exit-command)
6039 (pop-up-frames nil)
6040 (special-display-buffer-names nil)
6041 (special-display-regexps nil)
6042 (special-display-function nil))
6043 (save-excursion
6044 (save-window-excursion
6045 (delete-other-windows)
6046 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
6047 (switch-to-buffer
6048 (condition-case nil
6049 (make-indirect-buffer (current-buffer) "*org-goto*")
6050 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
6051 (with-output-to-temp-buffer "*Help*"
6052 (princ help))
6053 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
6054 (setq buffer-read-only nil)
6055 (let ((org-startup-truncated t)
6056 (org-startup-folded nil)
6057 (org-startup-align-all-tables nil))
6058 (org-mode)
6059 (org-overview))
6060 (setq buffer-read-only t)
6061 (if (and (boundp 'org-goto-start-pos)
6062 (integer-or-marker-p org-goto-start-pos))
6063 (let ((org-show-hierarchy-above t)
6064 (org-show-siblings t)
6065 (org-show-following-heading t))
6066 (goto-char org-goto-start-pos)
6067 (and (org-invisible-p) (org-show-context)))
6068 (goto-char (point-min)))
6069 (let (org-special-ctrl-a/e) (org-beginning-of-line))
6070 (message "Select location and press RET")
6071 (use-local-map org-goto-map)
6072 (recursive-edit)
6073 ))
6074 (kill-buffer "*org-goto*")
6075 (cons org-goto-selected-point org-goto-exit-command)))
6076
6077 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
6078 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
6079 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
6080 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
6081
6082 (defun org-goto-local-search-headings (string bound noerror)
6083 "Search and make sure that any matches are in headlines."
6084 (catch 'return
6085 (while (if isearch-forward
6086 (search-forward string bound noerror)
6087 (search-backward string bound noerror))
6088 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
6089 (and (member :headline context)
6090 (not (member :tags context))))
6091 (throw 'return (point))))))
6092
6093 (defun org-goto-local-auto-isearch ()
6094 "Start isearch."
6095 (interactive)
6096 (goto-char (point-min))
6097 (let ((keys (this-command-keys)))
6098 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
6099 (isearch-mode t)
6100 (isearch-process-search-char (string-to-char keys)))))
6101
6102 (defun org-goto-ret (&optional arg)
6103 "Finish `org-goto' by going to the new location."
6104 (interactive "P")
6105 (setq org-goto-selected-point (point)
6106 org-goto-exit-command 'return)
6107 (throw 'exit nil))
6108
6109 (defun org-goto-left ()
6110 "Finish `org-goto' by going to the new location."
6111 (interactive)
6112 (if (org-on-heading-p)
6113 (progn
6114 (beginning-of-line 1)
6115 (setq org-goto-selected-point (point)
6116 org-goto-exit-command 'left)
6117 (throw 'exit nil))
6118 (error "Not on a heading")))
6119
6120 (defun org-goto-right ()
6121 "Finish `org-goto' by going to the new location."
6122 (interactive)
6123 (if (org-on-heading-p)
6124 (progn
6125 (setq org-goto-selected-point (point)
6126 org-goto-exit-command 'right)
6127 (throw 'exit nil))
6128 (error "Not on a heading")))
6129
6130 (defun org-goto-quit ()
6131 "Finish `org-goto' without cursor motion."
6132 (interactive)
6133 (setq org-goto-selected-point nil)
6134 (setq org-goto-exit-command 'quit)
6135 (throw 'exit nil))
6136
6137 ;;; Indirect buffer display of subtrees
6138
6139 (defvar org-indirect-dedicated-frame nil
6140 "This is the frame being used for indirect tree display.")
6141 (defvar org-last-indirect-buffer nil)
6142
6143 (defun org-tree-to-indirect-buffer (&optional arg)
6144 "Create indirect buffer and narrow it to current subtree.
6145 With numerical prefix ARG, go up to this level and then take that tree.
6146 If ARG is negative, go up that many levels.
6147 If `org-indirect-buffer-display' is not `new-frame', the command removes the
6148 indirect buffer previously made with this command, to avoid proliferation of
6149 indirect buffers. However, when you call the command with a `C-u' prefix, or
6150 when `org-indirect-buffer-display' is `new-frame', the last buffer
6151 is kept so that you can work with several indirect buffers at the same time.
6152 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
6153 requests that a new frame be made for the new buffer, so that the dedicated
6154 frame is not changed."
6155 (interactive "P")
6156 (let ((cbuf (current-buffer))
6157 (cwin (selected-window))
6158 (pos (point))
6159 beg end level heading ibuf)
6160 (save-excursion
6161 (org-back-to-heading t)
6162 (when (numberp arg)
6163 (setq level (org-outline-level))
6164 (if (< arg 0) (setq arg (+ level arg)))
6165 (while (> (setq level (org-outline-level)) arg)
6166 (outline-up-heading 1 t)))
6167 (setq beg (point)
6168 heading (org-get-heading))
6169 (org-end-of-subtree t t)
6170 (if (org-on-heading-p) (backward-char 1))
6171 (setq end (point)))
6172 (if (and (buffer-live-p org-last-indirect-buffer)
6173 (not (eq org-indirect-buffer-display 'new-frame))
6174 (not arg))
6175 (kill-buffer org-last-indirect-buffer))
6176 (setq ibuf (org-get-indirect-buffer cbuf)
6177 org-last-indirect-buffer ibuf)
6178 (cond
6179 ((or (eq org-indirect-buffer-display 'new-frame)
6180 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
6181 (select-frame (make-frame))
6182 (delete-other-windows)
6183 (switch-to-buffer ibuf)
6184 (org-set-frame-title heading))
6185 ((eq org-indirect-buffer-display 'dedicated-frame)
6186 (raise-frame
6187 (select-frame (or (and org-indirect-dedicated-frame
6188 (frame-live-p org-indirect-dedicated-frame)
6189 org-indirect-dedicated-frame)
6190 (setq org-indirect-dedicated-frame (make-frame)))))
6191 (delete-other-windows)
6192 (switch-to-buffer ibuf)
6193 (org-set-frame-title (concat "Indirect: " heading)))
6194 ((eq org-indirect-buffer-display 'current-window)
6195 (switch-to-buffer ibuf))
6196 ((eq org-indirect-buffer-display 'other-window)
6197 (pop-to-buffer ibuf))
6198 (t (error "Invalid value")))
6199 (if (featurep 'xemacs)
6200 (save-excursion (org-mode) (turn-on-font-lock)))
6201 (narrow-to-region beg end)
6202 (show-all)
6203 (goto-char pos)
6204 (and (window-live-p cwin) (select-window cwin))))
6205
6206 (defun org-get-indirect-buffer (&optional buffer)
6207 (setq buffer (or buffer (current-buffer)))
6208 (let ((n 1) (base (buffer-name buffer)) bname)
6209 (while (buffer-live-p
6210 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
6211 (setq n (1+ n)))
6212 (condition-case nil
6213 (make-indirect-buffer buffer bname 'clone)
6214 (error (make-indirect-buffer buffer bname)))))
6215
6216 (defun org-set-frame-title (title)
6217 "Set the title of the current frame to the string TITLE."
6218 ;; FIXME: how to name a single frame in XEmacs???
6219 (unless (featurep 'xemacs)
6220 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
6221
6222 ;;;; Structure editing
6223
6224 ;;; Inserting headlines
6225
6226 (defun org-previous-line-empty-p ()
6227 (save-excursion
6228 (and (not (bobp))
6229 (or (beginning-of-line 0) t)
6230 (save-match-data
6231 (looking-at "[ \t]*$")))))
6232
6233 (defun org-insert-heading (&optional force-heading invisible-ok)
6234 "Insert a new heading or item with same depth at point.
6235 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
6236 If point is at the beginning of a headline, insert a sibling before the
6237 current headline. If point is not at the beginning, do not split the line,
6238 but create the new headline after the current line.
6239 When INVISIBLE-OK is set, stop at invisible headlines when going back.
6240 This is important for non-interactive uses of the command."
6241 (interactive "P")
6242 (if (or (= (buffer-size) 0)
6243 (and (not (save-excursion (and (ignore-errors (org-back-to-heading invisible-ok))
6244 (org-on-heading-p))))
6245 (not (org-in-item-p))))
6246 (insert "\n* ")
6247 (when (or force-heading (not (org-insert-item)))
6248 (let* ((empty-line-p nil)
6249 (head (save-excursion
6250 (condition-case nil
6251 (progn
6252 (org-back-to-heading invisible-ok)
6253 (setq empty-line-p (org-previous-line-empty-p))
6254 (match-string 0))
6255 (error "*"))))
6256 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
6257 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
6258 pos hide-previous previous-pos)
6259 (cond
6260 ((and (org-on-heading-p) (bolp)
6261 (or (bobp)
6262 (save-excursion (backward-char 1) (not (org-invisible-p)))))
6263 ;; insert before the current line
6264 (open-line (if blank 2 1)))
6265 ((and (bolp)
6266 (not org-insert-heading-respect-content)
6267 (or (bobp)
6268 (save-excursion
6269 (backward-char 1) (not (org-invisible-p)))))
6270 ;; insert right here
6271 nil)
6272 (t
6273 ;; somewhere in the line
6274 (save-excursion
6275 (setq previous-pos (point-at-bol))
6276 (end-of-line)
6277 (setq hide-previous (org-invisible-p)))
6278 (and org-insert-heading-respect-content (org-show-subtree))
6279 (let ((split
6280 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
6281 (save-excursion
6282 (let ((p (point)))
6283 (goto-char (point-at-bol))
6284 (and (looking-at org-complex-heading-regexp)
6285 (> p (match-beginning 4)))))))
6286 tags pos)
6287 (cond
6288 (org-insert-heading-respect-content
6289 (org-end-of-subtree nil t)
6290 (or (bolp) (newline))
6291 (or (org-previous-line-empty-p)
6292 (and blank (newline)))
6293 (open-line 1))
6294 ((org-on-heading-p)
6295 (when hide-previous
6296 (show-children)
6297 (org-show-entry))
6298 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
6299 (setq tags (and (match-end 2) (match-string 2)))
6300 (and (match-end 1)
6301 (delete-region (match-beginning 1) (match-end 1)))
6302 (setq pos (point-at-bol))
6303 (or split (end-of-line 1))
6304 (delete-horizontal-space)
6305 (if (string-match "\\`\\*+\\'"
6306 (buffer-substring (point-at-bol) (point)))
6307 (insert " "))
6308 (newline (if blank 2 1))
6309 (when tags
6310 (save-excursion
6311 (goto-char pos)
6312 (end-of-line 1)
6313 (insert " " tags)
6314 (org-set-tags nil 'align))))
6315 (t
6316 (or split (end-of-line 1))
6317 (newline (if blank 2 1)))))))
6318 (insert head) (just-one-space)
6319 (setq pos (point))
6320 (end-of-line 1)
6321 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
6322 (when (and org-insert-heading-respect-content hide-previous)
6323 (save-excursion
6324 (goto-char previous-pos)
6325 (hide-subtree)))
6326 (run-hooks 'org-insert-heading-hook)))))
6327
6328 (defun org-get-heading (&optional no-tags)
6329 "Return the heading of the current entry, without the stars."
6330 (save-excursion
6331 (org-back-to-heading t)
6332 (if (looking-at
6333 (if no-tags
6334 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
6335 "\\*+[ \t]+\\([^\r\n]*\\)"))
6336 (match-string 1) "")))
6337
6338 (defun org-heading-components ()
6339 "Return the components of the current heading.
6340 This is a list with the following elements:
6341 - the level as an integer
6342 - the reduced level, different if `org-odd-levels-only' is set.
6343 - the TODO keyword, or nil
6344 - the priority character, like ?A, or nil if no priority is given
6345 - the headline text itself, or the tags string if no headline text
6346 - the tags string, or nil."
6347 (save-excursion
6348 (org-back-to-heading t)
6349 (if (let (case-fold-search) (looking-at org-complex-heading-regexp))
6350 (list (length (match-string 1))
6351 (org-reduced-level (length (match-string 1)))
6352 (org-match-string-no-properties 2)
6353 (and (match-end 3) (aref (match-string 3) 2))
6354 (org-match-string-no-properties 4)
6355 (org-match-string-no-properties 5)))))
6356
6357 (defun org-get-entry ()
6358 "Get the entry text, after heading, entire subtree."
6359 (save-excursion
6360 (org-back-to-heading t)
6361 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
6362
6363 (defun org-insert-heading-after-current ()
6364 "Insert a new heading with same level as current, after current subtree."
6365 (interactive)
6366 (org-back-to-heading)
6367 (org-insert-heading)
6368 (org-move-subtree-down)
6369 (end-of-line 1))
6370
6371 (defun org-insert-heading-respect-content ()
6372 (interactive)
6373 (let ((org-insert-heading-respect-content t))
6374 (org-insert-heading t)))
6375
6376 (defun org-insert-todo-heading-respect-content (&optional force-state)
6377 (interactive "P")
6378 (let ((org-insert-heading-respect-content t))
6379 (org-insert-todo-heading force-state t)))
6380
6381 (defun org-insert-todo-heading (arg &optional force-heading)
6382 "Insert a new heading with the same level and TODO state as current heading.
6383 If the heading has no TODO state, or if the state is DONE, use the first
6384 state (TODO by default). Also with prefix arg, force first state."
6385 (interactive "P")
6386 (when (or force-heading (not (org-insert-item 'checkbox)))
6387 (org-insert-heading force-heading)
6388 (save-excursion
6389 (org-back-to-heading)
6390 (outline-previous-heading)
6391 (looking-at org-todo-line-regexp))
6392 (let*
6393 ((new-mark-x
6394 (if (or arg
6395 (not (match-beginning 2))
6396 (member (match-string 2) org-done-keywords))
6397 (car org-todo-keywords-1)
6398 (match-string 2)))
6399 (new-mark
6400 (or
6401 (run-hook-with-args-until-success
6402 'org-todo-get-default-hook new-mark-x nil)
6403 new-mark-x)))
6404 (beginning-of-line 1)
6405 (and (looking-at "\\*+ ") (goto-char (match-end 0))
6406 (if org-treat-insert-todo-heading-as-state-change
6407 (org-todo new-mark)
6408 (insert new-mark " "))))
6409 (when org-provide-todo-statistics
6410 (org-update-parent-todo-statistics))))
6411
6412 (defun org-insert-subheading (arg)
6413 "Insert a new subheading and demote it.
6414 Works for outline headings and for plain lists alike."
6415 (interactive "P")
6416 (org-insert-heading arg)
6417 (cond
6418 ((org-on-heading-p) (org-do-demote))
6419 ((org-at-item-p) (org-indent-item 1))))
6420
6421 (defun org-insert-todo-subheading (arg)
6422 "Insert a new subheading with TODO keyword or checkbox and demote it.
6423 Works for outline headings and for plain lists alike."
6424 (interactive "P")
6425 (org-insert-todo-heading arg)
6426 (cond
6427 ((org-on-heading-p) (org-do-demote))
6428 ((org-at-item-p) (org-indent-item 1))))
6429
6430 ;;; Promotion and Demotion
6431
6432 (defvar org-after-demote-entry-hook nil
6433 "Hook run after an entry has been demoted.
6434 The cursor will be at the beginning of the entry.
6435 When a subtree is being demoted, the hook will be called for each node.")
6436
6437 (defvar org-after-promote-entry-hook nil
6438 "Hook run after an entry has been promoted.
6439 The cursor will be at the beginning of the entry.
6440 When a subtree is being promoted, the hook will be called for each node.")
6441
6442 (defun org-promote-subtree ()
6443 "Promote the entire subtree.
6444 See also `org-promote'."
6445 (interactive)
6446 (save-excursion
6447 (org-map-tree 'org-promote))
6448 (org-fix-position-after-promote))
6449
6450 (defun org-demote-subtree ()
6451 "Demote the entire subtree. See `org-demote'.
6452 See also `org-promote'."
6453 (interactive)
6454 (save-excursion
6455 (org-map-tree 'org-demote))
6456 (org-fix-position-after-promote))
6457
6458
6459 (defun org-do-promote ()
6460 "Promote the current heading higher up the tree.
6461 If the region is active in `transient-mark-mode', promote all headings
6462 in the region."
6463 (interactive)
6464 (save-excursion
6465 (if (org-region-active-p)
6466 (org-map-region 'org-promote (region-beginning) (region-end))
6467 (org-promote)))
6468 (org-fix-position-after-promote))
6469
6470 (defun org-do-demote ()
6471 "Demote the current heading lower down the tree.
6472 If the region is active in `transient-mark-mode', demote all headings
6473 in the region."
6474 (interactive)
6475 (save-excursion
6476 (if (org-region-active-p)
6477 (org-map-region 'org-demote (region-beginning) (region-end))
6478 (org-demote)))
6479 (org-fix-position-after-promote))
6480
6481 (defun org-fix-position-after-promote ()
6482 "Make sure that after pro/demotion cursor position is right."
6483 (let ((pos (point)))
6484 (when (save-excursion
6485 (beginning-of-line 1)
6486 (looking-at org-todo-line-regexp)
6487 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
6488 (cond ((eobp) (insert " "))
6489 ((eolp) (insert " "))
6490 ((equal (char-after) ?\ ) (forward-char 1))))))
6491
6492 (defun org-current-level ()
6493 "Return the level of the current entry, or nil if before the first headline.
6494 The level is the number of stars at the beginning of the headline."
6495 (save-excursion
6496 (condition-case nil
6497 (progn
6498 (org-back-to-heading t)
6499 (funcall outline-level))
6500 (error nil))))
6501
6502 (defun org-get-previous-line-level ()
6503 "Return the outline depth of the last headline before the current line.
6504 Returns 0 for the first headline in the buffer, and nil if before the
6505 first headline."
6506 (let ((current-level (org-current-level))
6507 (prev-level (when (> (line-number-at-pos) 1)
6508 (save-excursion
6509 (beginning-of-line 0)
6510 (org-current-level)))))
6511 (cond ((null current-level) nil) ; Before first headline
6512 ((null prev-level) 0) ; At first headline
6513 (prev-level))))
6514
6515 (defun org-reduced-level (l)
6516 "Compute the effective level of a heading.
6517 This takes into account the setting of `org-odd-levels-only'."
6518 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
6519
6520 (defun org-level-increment ()
6521 "Return the number of stars that will be added or removed at a
6522 time to headlines when structure editing, based on the value of
6523 `org-odd-levels-only'."
6524 (if org-odd-levels-only 2 1))
6525
6526 (defun org-get-valid-level (level &optional change)
6527 "Rectify a level change under the influence of `org-odd-levels-only'
6528 LEVEL is a current level, CHANGE is by how much the level should be
6529 modified. Even if CHANGE is nil, LEVEL may be returned modified because
6530 even level numbers will become the next higher odd number."
6531 (if org-odd-levels-only
6532 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
6533 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
6534 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
6535 (max 1 (+ level (or change 0)))))
6536
6537 (if (boundp 'define-obsolete-function-alias)
6538 (if (or (featurep 'xemacs) (< emacs-major-version 23))
6539 (define-obsolete-function-alias 'org-get-legal-level
6540 'org-get-valid-level)
6541 (define-obsolete-function-alias 'org-get-legal-level
6542 'org-get-valid-level "23.1")))
6543
6544 (defun org-promote ()
6545 "Promote the current heading higher up the tree.
6546 If the region is active in `transient-mark-mode', promote all headings
6547 in the region."
6548 (org-back-to-heading t)
6549 (let* ((level (save-match-data (funcall outline-level)))
6550 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
6551 (diff (abs (- level (length up-head) -1))))
6552 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
6553 (replace-match up-head nil t)
6554 ;; Fixup tag positioning
6555 (and org-auto-align-tags (org-set-tags nil t))
6556 (if org-adapt-indentation (org-fixup-indentation (- diff)))
6557 (run-hooks 'org-after-promote-entry-hook)))
6558
6559 (defun org-demote ()
6560 "Demote the current heading lower down the tree.
6561 If the region is active in `transient-mark-mode', demote all headings
6562 in the region."
6563 (org-back-to-heading t)
6564 (let* ((level (save-match-data (funcall outline-level)))
6565 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
6566 (diff (abs (- level (length down-head) -1))))
6567 (replace-match down-head nil t)
6568 ;; Fixup tag positioning
6569 (and org-auto-align-tags (org-set-tags nil t))
6570 (if org-adapt-indentation (org-fixup-indentation diff))
6571 (run-hooks 'org-after-demote-entry-hook)))
6572
6573 (defun org-cycle-level ()
6574 "Cycle the level of an empty headline through possible states.
6575 This goes first to child, then to parent, level, then up the hierarchy.
6576 After top level, it switches back to sibling level."
6577 (interactive)
6578 (let ((org-adapt-indentation nil))
6579 (when (org-point-at-end-of-empty-headline)
6580 (setq this-command 'org-cycle-level) ; Only needed for caching
6581 (let ((cur-level (org-current-level))
6582 (prev-level (org-get-previous-line-level)))
6583 (cond
6584 ;; If first headline in file, promote to top-level.
6585 ((= prev-level 0)
6586 (loop repeat (/ (- cur-level 1) (org-level-increment))
6587 do (org-do-promote)))
6588 ;; If same level as prev, demote one.
6589 ((= prev-level cur-level)
6590 (org-do-demote))
6591 ;; If parent is top-level, promote to top level if not already.
6592 ((= prev-level 1)
6593 (loop repeat (/ (- cur-level 1) (org-level-increment))
6594 do (org-do-promote)))
6595 ;; If top-level, return to prev-level.
6596 ((= cur-level 1)
6597 (loop repeat (/ (- prev-level 1) (org-level-increment))
6598 do (org-do-demote)))
6599 ;; If less than prev-level, promote one.
6600 ((< cur-level prev-level)
6601 (org-do-promote))
6602 ;; If deeper than prev-level, promote until higher than
6603 ;; prev-level.
6604 ((> cur-level prev-level)
6605 (loop repeat (+ 1 (/ (- cur-level prev-level) (org-level-increment)))
6606 do (org-do-promote))))
6607 t))))
6608
6609 (defun org-map-tree (fun)
6610 "Call FUN for every heading underneath the current one."
6611 (org-back-to-heading)
6612 (let ((level (funcall outline-level)))
6613 (save-excursion
6614 (funcall fun)
6615 (while (and (progn
6616 (outline-next-heading)
6617 (> (funcall outline-level) level))
6618 (not (eobp)))
6619 (funcall fun)))))
6620
6621 (defun org-map-region (fun beg end)
6622 "Call FUN for every heading between BEG and END."
6623 (let ((org-ignore-region t))
6624 (save-excursion
6625 (setq end (copy-marker end))
6626 (goto-char beg)
6627 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
6628 (< (point) end))
6629 (funcall fun))
6630 (while (and (progn
6631 (outline-next-heading)
6632 (< (point) end))
6633 (not (eobp)))
6634 (funcall fun)))))
6635
6636 (defun org-fixup-indentation (diff)
6637 "Change the indentation in the current entry by DIFF
6638 However, if any line in the current entry has no indentation, or if it
6639 would end up with no indentation after the change, nothing at all is done."
6640 (save-excursion
6641 (let ((end (save-excursion (outline-next-heading)
6642 (point-marker)))
6643 (prohibit (if (> diff 0)
6644 "^\\S-"
6645 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
6646 col)
6647 (unless (save-excursion (end-of-line 1)
6648 (re-search-forward prohibit end t))
6649 (while (and (< (point) end)
6650 (re-search-forward "^[ \t]+" end t))
6651 (goto-char (match-end 0))
6652 (setq col (current-column))
6653 (if (< diff 0) (replace-match ""))
6654 (org-indent-to-column (+ diff col))))
6655 (move-marker end nil))))
6656
6657 (defun org-convert-to-odd-levels ()
6658 "Convert an org-mode file with all levels allowed to one with odd levels.
6659 This will leave level 1 alone, convert level 2 to level 3, level 3 to
6660 level 5 etc."
6661 (interactive)
6662 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
6663 (let ((outline-regexp org-outline-regexp)
6664 (outline-level 'org-outline-level)
6665 (org-odd-levels-only nil) n)
6666 (save-excursion
6667 (goto-char (point-min))
6668 (while (re-search-forward "^\\*\\*+ " nil t)
6669 (setq n (- (length (match-string 0)) 2))
6670 (while (>= (setq n (1- n)) 0)
6671 (org-demote))
6672 (end-of-line 1))))))
6673
6674 (defun org-convert-to-oddeven-levels ()
6675 "Convert an org-mode file with only odd levels to one with odd and even levels.
6676 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6677 section with an even level, conversion would destroy the structure of the file. An error
6678 is signaled in this case."
6679 (interactive)
6680 (goto-char (point-min))
6681 ;; First check if there are no even levels
6682 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6683 (org-show-context t)
6684 (error "Not all levels are odd in this file. Conversion not possible"))
6685 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6686 (let ((outline-regexp org-outline-regexp)
6687 (outline-level 'org-outline-level)
6688 (org-odd-levels-only nil) n)
6689 (save-excursion
6690 (goto-char (point-min))
6691 (while (re-search-forward "^\\*\\*+ " nil t)
6692 (setq n (/ (1- (length (match-string 0))) 2))
6693 (while (>= (setq n (1- n)) 0)
6694 (org-promote))
6695 (end-of-line 1))))))
6696
6697 (defun org-tr-level (n)
6698 "Make N odd if required."
6699 (if org-odd-levels-only (1+ (/ n 2)) n))
6700
6701 ;;; Vertical tree motion, cutting and pasting of subtrees
6702
6703 (defun org-move-subtree-up (&optional arg)
6704 "Move the current subtree up past ARG headlines of the same level."
6705 (interactive "p")
6706 (org-move-subtree-down (- (prefix-numeric-value arg))))
6707
6708 (defun org-move-subtree-down (&optional arg)
6709 "Move the current subtree down past ARG headlines of the same level."
6710 (interactive "p")
6711 (setq arg (prefix-numeric-value arg))
6712 (let ((movfunc (if (> arg 0) 'org-get-next-sibling
6713 'org-get-last-sibling))
6714 (ins-point (make-marker))
6715 (cnt (abs arg))
6716 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6717 ;; Select the tree
6718 (org-back-to-heading)
6719 (setq beg0 (point))
6720 (save-excursion
6721 (setq ne-beg (org-back-over-empty-lines))
6722 (setq beg (point)))
6723 (save-match-data
6724 (save-excursion (outline-end-of-heading)
6725 (setq folded (org-invisible-p)))
6726 (outline-end-of-subtree))
6727 (outline-next-heading)
6728 (setq ne-end (org-back-over-empty-lines))
6729 (setq end (point))
6730 (goto-char beg0)
6731 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6732 ;; include less whitespace
6733 (save-excursion
6734 (goto-char beg)
6735 (forward-line (- ne-beg ne-end))
6736 (setq beg (point))))
6737 ;; Find insertion point, with error handling
6738 (while (> cnt 0)
6739 (or (and (funcall movfunc) (looking-at outline-regexp))
6740 (progn (goto-char beg0)
6741 (error "Cannot move past superior level or buffer limit")))
6742 (setq cnt (1- cnt)))
6743 (if (> arg 0)
6744 ;; Moving forward - still need to move over subtree
6745 (progn (org-end-of-subtree t t)
6746 (save-excursion
6747 (org-back-over-empty-lines)
6748 (or (bolp) (newline)))))
6749 (setq ne-ins (org-back-over-empty-lines))
6750 (move-marker ins-point (point))
6751 (setq txt (buffer-substring beg end))
6752 (org-save-markers-in-region beg end)
6753 (delete-region beg end)
6754 (org-remove-empty-overlays-at beg)
6755 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6756 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6757 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6758 (let ((bbb (point)))
6759 (insert-before-markers txt)
6760 (org-reinstall-markers-in-region bbb)
6761 (move-marker ins-point bbb))
6762 (or (bolp) (insert "\n"))
6763 (setq ins-end (point))
6764 (goto-char ins-point)
6765 (org-skip-whitespace)
6766 (when (and (< arg 0)
6767 (org-first-sibling-p)
6768 (> ne-ins ne-beg))
6769 ;; Move whitespace back to beginning
6770 (save-excursion
6771 (goto-char ins-end)
6772 (let ((kill-whole-line t))
6773 (kill-line (- ne-ins ne-beg)) (point)))
6774 (insert (make-string (- ne-ins ne-beg) ?\n)))
6775 (move-marker ins-point nil)
6776 (if folded
6777 (hide-subtree)
6778 (org-show-entry)
6779 (show-children)
6780 (org-cycle-hide-drawers 'children))
6781 (org-clean-visibility-after-subtree-move)))
6782
6783 (defvar org-subtree-clip ""
6784 "Clipboard for cut and paste of subtrees.
6785 This is actually only a copy of the kill, because we use the normal kill
6786 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6787
6788 (defvar org-subtree-clip-folded nil
6789 "Was the last copied subtree folded?
6790 This is used to fold the tree back after pasting.")
6791
6792 (defun org-cut-subtree (&optional n)
6793 "Cut the current subtree into the clipboard.
6794 With prefix arg N, cut this many sequential subtrees.
6795 This is a short-hand for marking the subtree and then cutting it."
6796 (interactive "p")
6797 (org-copy-subtree n 'cut))
6798
6799 (defun org-copy-subtree (&optional n cut force-store-markers)
6800 "Cut the current subtree into the clipboard.
6801 With prefix arg N, cut this many sequential subtrees.
6802 This is a short-hand for marking the subtree and then copying it.
6803 If CUT is non-nil, actually cut the subtree.
6804 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6805 of some markers in the region, even if CUT is non-nil. This is
6806 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6807 (interactive "p")
6808 (let (beg end folded (beg0 (point)))
6809 (if (interactive-p)
6810 (org-back-to-heading nil) ; take what looks like a subtree
6811 (org-back-to-heading t)) ; take what is really there
6812 (org-back-over-empty-lines)
6813 (setq beg (point))
6814 (skip-chars-forward " \t\r\n")
6815 (save-match-data
6816 (save-excursion (outline-end-of-heading)
6817 (setq folded (org-invisible-p)))
6818 (condition-case nil
6819 (org-forward-same-level (1- n) t)
6820 (error nil))
6821 (org-end-of-subtree t t))
6822 (org-back-over-empty-lines)
6823 (setq end (point))
6824 (goto-char beg0)
6825 (when (> end beg)
6826 (setq org-subtree-clip-folded folded)
6827 (when (or cut force-store-markers)
6828 (org-save-markers-in-region beg end))
6829 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6830 (setq org-subtree-clip (current-kill 0))
6831 (message "%s: Subtree(s) with %d characters"
6832 (if cut "Cut" "Copied")
6833 (length org-subtree-clip)))))
6834
6835 (defun org-paste-subtree (&optional level tree for-yank)
6836 "Paste the clipboard as a subtree, with modification of headline level.
6837 The entire subtree is promoted or demoted in order to match a new headline
6838 level.
6839
6840 If the cursor is at the beginning of a headline, the same level as
6841 that headline is used to paste the tree
6842
6843 If not, the new level is derived from the *visible* headings
6844 before and after the insertion point, and taken to be the inferior headline
6845 level of the two. So if the previous visible heading is level 3 and the
6846 next is level 4 (or vice versa), level 4 will be used for insertion.
6847 This makes sure that the subtree remains an independent subtree and does
6848 not swallow low level entries.
6849
6850 You can also force a different level, either by using a numeric prefix
6851 argument, or by inserting the heading marker by hand. For example, if the
6852 cursor is after \"*****\", then the tree will be shifted to level 5.
6853
6854 If optional TREE is given, use this text instead of the kill ring.
6855
6856 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6857 move back over whitespace before inserting, and move point to the end of
6858 the inserted text when done."
6859 (interactive "P")
6860 (setq tree (or tree (and kill-ring (current-kill 0))))
6861 (unless (org-kill-is-subtree-p tree)
6862 (error "%s"
6863 (substitute-command-keys
6864 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6865 (let* ((visp (not (org-invisible-p)))
6866 (txt tree)
6867 (^re (concat "^\\(" outline-regexp "\\)"))
6868 (re (concat "\\(" outline-regexp "\\)"))
6869 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6870
6871 (old-level (if (string-match ^re txt)
6872 (- (match-end 0) (match-beginning 0) 1)
6873 -1))
6874 (force-level (cond (level (prefix-numeric-value level))
6875 ((and (looking-at "[ \t]*$")
6876 (string-match
6877 ^re_ (buffer-substring
6878 (point-at-bol) (point))))
6879 (- (match-end 1) (match-beginning 1)))
6880 ((and (bolp)
6881 (looking-at org-outline-regexp))
6882 (- (match-end 0) (point) 1))
6883 (t nil)))
6884 (previous-level (save-excursion
6885 (condition-case nil
6886 (progn
6887 (outline-previous-visible-heading 1)
6888 (if (looking-at re)
6889 (- (match-end 0) (match-beginning 0) 1)
6890 1))
6891 (error 1))))
6892 (next-level (save-excursion
6893 (condition-case nil
6894 (progn
6895 (or (looking-at outline-regexp)
6896 (outline-next-visible-heading 1))
6897 (if (looking-at re)
6898 (- (match-end 0) (match-beginning 0) 1)
6899 1))
6900 (error 1))))
6901 (new-level (or force-level (max previous-level next-level)))
6902 (shift (if (or (= old-level -1)
6903 (= new-level -1)
6904 (= old-level new-level))
6905 0
6906 (- new-level old-level)))
6907 (delta (if (> shift 0) -1 1))
6908 (func (if (> shift 0) 'org-demote 'org-promote))
6909 (org-odd-levels-only nil)
6910 beg end newend)
6911 ;; Remove the forced level indicator
6912 (if force-level
6913 (delete-region (point-at-bol) (point)))
6914 ;; Paste
6915 (beginning-of-line 1)
6916 (unless for-yank (org-back-over-empty-lines))
6917 (setq beg (point))
6918 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6919 (insert-before-markers txt)
6920 (unless (string-match "\n\\'" txt) (insert "\n"))
6921 (setq newend (point))
6922 (org-reinstall-markers-in-region beg)
6923 (setq end (point))
6924 (goto-char beg)
6925 (skip-chars-forward " \t\n\r")
6926 (setq beg (point))
6927 (if (and (org-invisible-p) visp)
6928 (save-excursion (outline-show-heading)))
6929 ;; Shift if necessary
6930 (unless (= shift 0)
6931 (save-restriction
6932 (narrow-to-region beg end)
6933 (while (not (= shift 0))
6934 (org-map-region func (point-min) (point-max))
6935 (setq shift (+ delta shift)))
6936 (goto-char (point-min))
6937 (setq newend (point-max))))
6938 (when (or (interactive-p) for-yank)
6939 (message "Clipboard pasted as level %d subtree" new-level))
6940 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6941 kill-ring
6942 (eq org-subtree-clip (current-kill 0))
6943 org-subtree-clip-folded)
6944 ;; The tree was folded before it was killed/copied
6945 (hide-subtree))
6946 (and for-yank (goto-char newend))))
6947
6948 (defun org-kill-is-subtree-p (&optional txt)
6949 "Check if the current kill is an outline subtree, or a set of trees.
6950 Returns nil if kill does not start with a headline, or if the first
6951 headline level is not the largest headline level in the tree.
6952 So this will actually accept several entries of equal levels as well,
6953 which is OK for `org-paste-subtree'.
6954 If optional TXT is given, check this string instead of the current kill."
6955 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6956 (start-level (and kill
6957 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6958 org-outline-regexp "\\)")
6959 kill)
6960 (- (match-end 2) (match-beginning 2) 1)))
6961 (re (concat "^" org-outline-regexp))
6962 (start (1+ (or (match-beginning 2) -1))))
6963 (if (not start-level)
6964 (progn
6965 nil) ;; does not even start with a heading
6966 (catch 'exit
6967 (while (setq start (string-match re kill (1+ start)))
6968 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6969 (throw 'exit nil)))
6970 t))))
6971
6972 (defvar org-markers-to-move nil
6973 "Markers that should be moved with a cut-and-paste operation.
6974 Those markers are stored together with their positions relative to
6975 the start of the region.")
6976
6977 (defun org-save-markers-in-region (beg end)
6978 "Check markers in region.
6979 If these markers are between BEG and END, record their position relative
6980 to BEG, so that after moving the block of text, we can put the markers back
6981 into place.
6982 This function gets called just before an entry or tree gets cut from the
6983 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6984 called immediately, to move the markers with the entries."
6985 (setq org-markers-to-move nil)
6986 (when (featurep 'org-clock)
6987 (org-clock-save-markers-for-cut-and-paste beg end))
6988 (when (featurep 'org-agenda)
6989 (org-agenda-save-markers-for-cut-and-paste beg end)))
6990
6991 (defun org-check-and-save-marker (marker beg end)
6992 "Check if MARKER is between BEG and END.
6993 If yes, remember the marker and the distance to BEG."
6994 (when (and (marker-buffer marker)
6995 (equal (marker-buffer marker) (current-buffer)))
6996 (if (and (>= marker beg) (< marker end))
6997 (push (cons marker (- marker beg)) org-markers-to-move))))
6998
6999 (defun org-reinstall-markers-in-region (beg)
7000 "Move all remembered markers to their position relative to BEG."
7001 (mapc (lambda (x)
7002 (move-marker (car x) (+ beg (cdr x))))
7003 org-markers-to-move)
7004 (setq org-markers-to-move nil))
7005
7006 (defun org-narrow-to-subtree ()
7007 "Narrow buffer to the current subtree."
7008 (interactive)
7009 (save-excursion
7010 (save-match-data
7011 (narrow-to-region
7012 (progn (org-back-to-heading t) (point))
7013 (progn (org-end-of-subtree t t)
7014 (if (org-on-heading-p) (backward-char 1))
7015 (point))))))
7016
7017 (defun org-clone-subtree-with-time-shift (n &optional shift)
7018 "Clone the task (subtree) at point N times.
7019 The clones will be inserted as siblings.
7020
7021 In interactive use, the user will be prompted for the number of clones
7022 to be produced, and for a time SHIFT, which may be a repeater as used
7023 in time stamps, for example `+3d'.
7024
7025 When a valid repeater is given and the entry contains any time stamps,
7026 the clones will become a sequence in time, with time stamps in the
7027 subtree shifted for each clone produced. If SHIFT is nil or the
7028 empty string, time stamps will be left alone.
7029
7030 If the original subtree did contain time stamps with a repeater,
7031 the following will happen:
7032 - the repeater will be removed in each clone
7033 - an additional clone will be produced, with the current, unshifted
7034 date(s) in the entry.
7035 - the original entry will be placed *after* all the clones, with
7036 repeater intact.
7037 - the start days in the repeater in the original entry will be shifted
7038 to past the last clone.
7039 I this way you can spell out a number of instances of a repeating task,
7040 and still retain the repeater to cover future instances of the task."
7041 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
7042 (let (beg end template task
7043 shift-n shift-what doshift nmin nmax (n-no-remove -1))
7044 (if (not (and (integerp n) (> n 0)))
7045 (error "Invalid number of replications %s" n))
7046 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
7047 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
7048 shift)))
7049 (error "Invalid shift specification %s" shift))
7050 (when doshift
7051 (setq shift-n (string-to-number (match-string 1 shift))
7052 shift-what (cdr (assoc (match-string 2 shift)
7053 '(("d" . day) ("w" . week)
7054 ("m" . month) ("y" . year))))))
7055 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
7056 (setq nmin 1 nmax n)
7057 (org-back-to-heading t)
7058 (setq beg (point))
7059 (org-end-of-subtree t t)
7060 (or (bolp) (insert "\n"))
7061 (setq end (point))
7062 (setq template (buffer-substring beg end))
7063 (when (and doshift
7064 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
7065 (delete-region beg end)
7066 (setq end beg)
7067 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
7068 (goto-char end)
7069 (loop for n from nmin to nmax do
7070 (if (not doshift)
7071 (setq task template)
7072 (with-temp-buffer
7073 (insert template)
7074 (org-mode)
7075 (goto-char (point-min))
7076 (while (re-search-forward org-ts-regexp-both nil t)
7077 (org-timestamp-change (* n shift-n) shift-what))
7078 (unless (= n n-no-remove)
7079 (goto-char (point-min))
7080 (while (re-search-forward org-ts-regexp nil t)
7081 (save-excursion
7082 (goto-char (match-beginning 0))
7083 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
7084 (delete-region (match-beginning 1) (match-end 1))))))
7085 (setq task (buffer-string))))
7086 (insert task))
7087 (goto-char beg)))
7088
7089 ;;; Outline Sorting
7090
7091 (defun org-sort (with-case)
7092 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
7093 Optional argument WITH-CASE means sort case-sensitively.
7094 With a double prefix argument, also remove duplicate entries."
7095 (interactive "P")
7096 (if (org-at-table-p)
7097 (org-call-with-arg 'org-table-sort-lines with-case)
7098 (org-call-with-arg 'org-sort-entries-or-items with-case)))
7099
7100 (defun org-sort-remove-invisible (s)
7101 (remove-text-properties 0 (length s) org-rm-props s)
7102 (while (string-match org-bracket-link-regexp s)
7103 (setq s (replace-match (if (match-end 2)
7104 (match-string 3 s)
7105 (match-string 1 s)) t t s)))
7106 s)
7107
7108 (defvar org-priority-regexp) ; defined later in the file
7109
7110 (defvar org-after-sorting-entries-or-items-hook nil
7111 "Hook that is run after a bunch of entries or items have been sorted.
7112 When children are sorted, the cursor is in the parent line when this
7113 hook gets called. When a region or a plain list is sorted, the cursor
7114 will be in the first entry of the sorted region/list.")
7115
7116 (defun org-sort-entries-or-items
7117 (&optional with-case sorting-type getkey-func compare-func property)
7118 "Sort entries on a certain level of an outline tree, or plain list items.
7119 If there is an active region, the entries in the region are sorted.
7120 Else, if the cursor is before the first entry, sort the top-level items.
7121 Else, the children of the entry at point are sorted.
7122 If the cursor is at the first item in a plain list, the list items will be
7123 sorted.
7124
7125 Sorting can be alphabetically, numerically, by date/time as given by
7126 a time stamp, by a property or by priority.
7127
7128 The command prompts for the sorting type unless it has been given to the
7129 function through the SORTING-TYPE argument, which needs to a character,
7130 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
7131 precise meaning of each character:
7132
7133 n Numerically, by converting the beginning of the entry/item to a number.
7134 a Alphabetically, ignoring the TODO keyword and the priority, if any.
7135 t By date/time, either the first active time stamp in the entry, or, if
7136 none exist, by the first inactive one.
7137 In items, only the first line will be checked.
7138 s By the scheduled date/time.
7139 d By deadline date/time.
7140 c By creation time, which is assumed to be the first inactive time stamp
7141 at the beginning of a line.
7142 p By priority according to the cookie.
7143 r By the value of a property.
7144
7145 Capital letters will reverse the sort order.
7146
7147 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
7148 called with point at the beginning of the record. It must return either
7149 a string or a number that should serve as the sorting key for that record.
7150
7151 Comparing entries ignores case by default. However, with an optional argument
7152 WITH-CASE, the sorting considers case as well."
7153 (interactive "P")
7154 (let ((case-func (if with-case 'identity 'downcase))
7155 start beg end stars re re2
7156 txt what tmp plain-list-p)
7157 ;; Find beginning and end of region to sort
7158 (cond
7159 ((org-region-active-p)
7160 ;; we will sort the region
7161 (setq end (region-end)
7162 what "region")
7163 (goto-char (region-beginning))
7164 (if (not (org-on-heading-p)) (outline-next-heading))
7165 (setq start (point)))
7166 ((org-at-item-p)
7167 ;; we will sort this plain list
7168 (org-beginning-of-item-list) (setq start (point))
7169 (org-end-of-item-list)
7170 (or (bolp) (insert "\n"))
7171 (setq end (point))
7172 (goto-char start)
7173 (setq plain-list-p t
7174 what "plain list"))
7175 ((or (org-on-heading-p)
7176 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
7177 ;; we will sort the children of the current headline
7178 (org-back-to-heading)
7179 (setq start (point)
7180 end (progn (org-end-of-subtree t t)
7181 (or (bolp) (insert "\n"))
7182 (org-back-over-empty-lines)
7183 (point))
7184 what "children")
7185 (goto-char start)
7186 (show-subtree)
7187 (outline-next-heading))
7188 (t
7189 ;; we will sort the top-level entries in this file
7190 (goto-char (point-min))
7191 (or (org-on-heading-p) (outline-next-heading))
7192 (setq start (point))
7193 (goto-char (point-max))
7194 (beginning-of-line 1)
7195 (when (looking-at ".*?\\S-")
7196 ;; File ends in a non-white line
7197 (end-of-line 1)
7198 (insert "\n"))
7199 (setq end (point-max))
7200 (setq what "top-level")
7201 (goto-char start)
7202 (show-all)))
7203
7204 (setq beg (point))
7205 (if (>= beg end) (error "Nothing to sort"))
7206
7207 (unless plain-list-p
7208 (looking-at "\\(\\*+\\)")
7209 (setq stars (match-string 1)
7210 re (concat "^" (regexp-quote stars) " +")
7211 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
7212 txt (buffer-substring beg end))
7213 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
7214 (if (and (not (equal stars "*")) (string-match re2 txt))
7215 (error "Region to sort contains a level above the first entry")))
7216
7217 (unless sorting-type
7218 (message
7219 (if plain-list-p
7220 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
7221 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
7222 [t]ime [s]cheduled [d]eadline [c]reated
7223 A/N/T/S/D/C/P/O/F means reversed:")
7224 what)
7225 (setq sorting-type (read-char-exclusive))
7226
7227 (and (= (downcase sorting-type) ?f)
7228 (setq getkey-func
7229 (org-icompleting-read "Sort using function: "
7230 obarray 'fboundp t nil nil))
7231 (setq getkey-func (intern getkey-func)))
7232
7233 (and (= (downcase sorting-type) ?r)
7234 (setq property
7235 (org-icompleting-read "Property: "
7236 (mapcar 'list (org-buffer-property-keys t))
7237 nil t))))
7238
7239 (message "Sorting entries...")
7240
7241 (save-restriction
7242 (narrow-to-region start end)
7243
7244 (let ((dcst (downcase sorting-type))
7245 (case-fold-search nil)
7246 (now (current-time)))
7247 (sort-subr
7248 (/= dcst sorting-type)
7249 ;; This function moves to the beginning character of the "record" to
7250 ;; be sorted.
7251 (if plain-list-p
7252 (lambda nil
7253 (if (org-at-item-p) t (goto-char (point-max))))
7254 (lambda nil
7255 (if (re-search-forward re nil t)
7256 (goto-char (match-beginning 0))
7257 (goto-char (point-max)))))
7258 ;; This function moves to the last character of the "record" being
7259 ;; sorted.
7260 (if plain-list-p
7261 'org-end-of-item
7262 (lambda nil
7263 (save-match-data
7264 (condition-case nil
7265 (outline-forward-same-level 1)
7266 (error
7267 (goto-char (point-max)))))))
7268
7269 ;; This function returns the value that gets sorted against.
7270 (if plain-list-p
7271 (lambda nil
7272 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
7273 (cond
7274 ((= dcst ?n)
7275 (string-to-number (buffer-substring (match-end 0)
7276 (point-at-eol))))
7277 ((= dcst ?a)
7278 (buffer-substring (match-end 0) (point-at-eol)))
7279 ((= dcst ?t)
7280 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
7281 (re-search-forward org-ts-regexp-both
7282 (point-at-eol) t))
7283 (org-time-string-to-seconds (match-string 0))
7284 (org-float-time now)))
7285 ((= dcst ?f)
7286 (if getkey-func
7287 (progn
7288 (setq tmp (funcall getkey-func))
7289 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7290 tmp)
7291 (error "Invalid key function `%s'" getkey-func)))
7292 (t (error "Invalid sorting type `%c'" sorting-type)))))
7293 (lambda nil
7294 (cond
7295 ((= dcst ?n)
7296 (if (looking-at org-complex-heading-regexp)
7297 (string-to-number (match-string 4))
7298 nil))
7299 ((= dcst ?a)
7300 (if (looking-at org-complex-heading-regexp)
7301 (funcall case-func (match-string 4))
7302 nil))
7303 ((= dcst ?t)
7304 (let ((end (save-excursion (outline-next-heading) (point))))
7305 (if (or (re-search-forward org-ts-regexp end t)
7306 (re-search-forward org-ts-regexp-both end t))
7307 (org-time-string-to-seconds (match-string 0))
7308 (org-float-time now))))
7309 ((= dcst ?c)
7310 (let ((end (save-excursion (outline-next-heading) (point))))
7311 (if (re-search-forward
7312 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
7313 end t)
7314 (org-time-string-to-seconds (match-string 0))
7315 (org-float-time now))))
7316 ((= dcst ?s)
7317 (let ((end (save-excursion (outline-next-heading) (point))))
7318 (if (re-search-forward org-scheduled-time-regexp end t)
7319 (org-time-string-to-seconds (match-string 1))
7320 (org-float-time now))))
7321 ((= dcst ?d)
7322 (let ((end (save-excursion (outline-next-heading) (point))))
7323 (if (re-search-forward org-deadline-time-regexp end t)
7324 (org-time-string-to-seconds (match-string 1))
7325 (org-float-time now))))
7326 ((= dcst ?p)
7327 (if (re-search-forward org-priority-regexp (point-at-eol) t)
7328 (string-to-char (match-string 2))
7329 org-default-priority))
7330 ((= dcst ?r)
7331 (or (org-entry-get nil property) ""))
7332 ((= dcst ?o)
7333 (if (looking-at org-complex-heading-regexp)
7334 (- 9999 (length (member (match-string 2)
7335 org-todo-keywords-1)))))
7336 ((= dcst ?f)
7337 (if getkey-func
7338 (progn
7339 (setq tmp (funcall getkey-func))
7340 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
7341 tmp)
7342 (error "Invalid key function `%s'" getkey-func)))
7343 (t (error "Invalid sorting type `%c'" sorting-type)))))
7344 nil
7345 (cond
7346 ((= dcst ?a) 'string<)
7347 ((= dcst ?f) compare-func)
7348 ((member dcst '(?p ?t ?s ?d ?c)) '<)
7349 (t nil)))))
7350 (run-hooks 'org-after-sorting-entries-or-items-hook)
7351 (message "Sorting entries...done")))
7352
7353 (defun org-do-sort (table what &optional with-case sorting-type)
7354 "Sort TABLE of WHAT according to SORTING-TYPE.
7355 The user will be prompted for the SORTING-TYPE if the call to this
7356 function does not specify it. WHAT is only for the prompt, to indicate
7357 what is being sorted. The sorting key will be extracted from
7358 the car of the elements of the table.
7359 If WITH-CASE is non-nil, the sorting will be case-sensitive."
7360 (unless sorting-type
7361 (message
7362 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
7363 what)
7364 (setq sorting-type (read-char-exclusive)))
7365 (let ((dcst (downcase sorting-type))
7366 extractfun comparefun)
7367 ;; Define the appropriate functions
7368 (cond
7369 ((= dcst ?n)
7370 (setq extractfun 'string-to-number
7371 comparefun (if (= dcst sorting-type) '< '>)))
7372 ((= dcst ?a)
7373 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
7374 (lambda(x) (downcase (org-sort-remove-invisible x))))
7375 comparefun (if (= dcst sorting-type)
7376 'string<
7377 (lambda (a b) (and (not (string< a b))
7378 (not (string= a b)))))))
7379 ((= dcst ?t)
7380 (setq extractfun
7381 (lambda (x)
7382 (if (or (string-match org-ts-regexp x)
7383 (string-match org-ts-regexp-both x))
7384 (org-float-time
7385 (org-time-string-to-time (match-string 0 x)))
7386 0))
7387 comparefun (if (= dcst sorting-type) '< '>)))
7388 (t (error "Invalid sorting type `%c'" sorting-type)))
7389
7390 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
7391 table)
7392 (lambda (a b) (funcall comparefun (car a) (car b))))))
7393
7394
7395 ;;; The orgstruct minor mode
7396
7397 ;; Define a minor mode which can be used in other modes in order to
7398 ;; integrate the org-mode structure editing commands.
7399
7400 ;; This is really a hack, because the org-mode structure commands use
7401 ;; keys which normally belong to the major mode. Here is how it
7402 ;; works: The minor mode defines all the keys necessary to operate the
7403 ;; structure commands, but wraps the commands into a function which
7404 ;; tests if the cursor is currently at a headline or a plain list
7405 ;; item. If that is the case, the structure command is used,
7406 ;; temporarily setting many Org-mode variables like regular
7407 ;; expressions for filling etc. However, when any of those keys is
7408 ;; used at a different location, function uses `key-binding' to look
7409 ;; up if the key has an associated command in another currently active
7410 ;; keymap (minor modes, major mode, global), and executes that
7411 ;; command. There might be problems if any of the keys is otherwise
7412 ;; used as a prefix key.
7413
7414 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
7415 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
7416 ;; addresses this by checking explicitly for both bindings.
7417
7418 (defvar orgstruct-mode-map (make-sparse-keymap)
7419 "Keymap for the minor `orgstruct-mode'.")
7420
7421 (defvar org-local-vars nil
7422 "List of local variables, for use by `orgstruct-mode'")
7423
7424 ;;;###autoload
7425 (define-minor-mode orgstruct-mode
7426 "Toggle the minor more `orgstruct-mode'.
7427 This mode is for using Org-mode structure commands in other modes.
7428 The following key behave as if Org-mode was active, if the cursor
7429 is on a headline, or on a plain list item (both in the definition
7430 of Org-mode).
7431
7432 M-up Move entry/item up
7433 M-down Move entry/item down
7434 M-left Promote
7435 M-right Demote
7436 M-S-up Move entry/item up
7437 M-S-down Move entry/item down
7438 M-S-left Promote subtree
7439 M-S-right Demote subtree
7440 M-q Fill paragraph and items like in Org-mode
7441 C-c ^ Sort entries
7442 C-c - Cycle list bullet
7443 TAB Cycle item visibility
7444 M-RET Insert new heading/item
7445 S-M-RET Insert new TODO heading / Checkbox item
7446 C-c C-c Set tags / toggle checkbox"
7447 nil " OrgStruct" nil
7448 (org-load-modules-maybe)
7449 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
7450
7451 ;;;###autoload
7452 (defun turn-on-orgstruct ()
7453 "Unconditionally turn on `orgstruct-mode'."
7454 (orgstruct-mode 1))
7455
7456 (defun orgstruct++-mode (&optional arg)
7457 "Toggle `orgstruct-mode', the enhanced version of it.
7458 In addition to setting orgstruct-mode, this also exports all indentation
7459 and autofilling variables from org-mode into the buffer. It will also
7460 recognize item context in multiline items.
7461 Note that turning off orgstruct-mode will *not* remove the
7462 indentation/paragraph settings. This can only be done by refreshing the
7463 major mode, for example with \\[normal-mode]."
7464 (interactive "P")
7465 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
7466 (if (< arg 1)
7467 (orgstruct-mode -1)
7468 (orgstruct-mode 1)
7469 (let (var val)
7470 (mapc
7471 (lambda (x)
7472 (when (string-match
7473 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7474 (symbol-name (car x)))
7475 (setq var (car x) val (nth 1 x))
7476 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
7477 org-local-vars)
7478 (org-set-local 'orgstruct-is-++ t))))
7479
7480 (defvar orgstruct-is-++ nil
7481 "Is orgstruct-mode in ++ version in the current-buffer?")
7482 (make-variable-buffer-local 'orgstruct-is-++)
7483
7484 ;;;###autoload
7485 (defun turn-on-orgstruct++ ()
7486 "Unconditionally turn on `orgstruct++-mode'."
7487 (orgstruct++-mode 1))
7488
7489 (defun orgstruct-error ()
7490 "Error when there is no default binding for a structure key."
7491 (interactive)
7492 (error "This key has no function outside structure elements"))
7493
7494 (defun orgstruct-setup ()
7495 "Setup orgstruct keymaps."
7496 (let ((nfunc 0)
7497 (bindings
7498 (list
7499 '([(meta up)] org-metaup)
7500 '([(meta down)] org-metadown)
7501 '([(meta left)] org-metaleft)
7502 '([(meta right)] org-metaright)
7503 '([(meta shift up)] org-shiftmetaup)
7504 '([(meta shift down)] org-shiftmetadown)
7505 '([(meta shift left)] org-shiftmetaleft)
7506 '([(meta shift right)] org-shiftmetaright)
7507 '([?\e (up)] org-metaup)
7508 '([?\e (down)] org-metadown)
7509 '([?\e (left)] org-metaleft)
7510 '([?\e (right)] org-metaright)
7511 '([?\e (shift up)] org-shiftmetaup)
7512 '([?\e (shift down)] org-shiftmetadown)
7513 '([?\e (shift left)] org-shiftmetaleft)
7514 '([?\e (shift right)] org-shiftmetaright)
7515 '([(shift up)] org-shiftup)
7516 '([(shift down)] org-shiftdown)
7517 '([(shift left)] org-shiftleft)
7518 '([(shift right)] org-shiftright)
7519 '("\C-c\C-c" org-ctrl-c-ctrl-c)
7520 '("\M-q" fill-paragraph)
7521 '("\C-c^" org-sort)
7522 '("\C-c-" org-cycle-list-bullet)))
7523 elt key fun cmd)
7524 (while (setq elt (pop bindings))
7525 (setq nfunc (1+ nfunc))
7526 (setq key (org-key (car elt))
7527 fun (nth 1 elt)
7528 cmd (orgstruct-make-binding fun nfunc key))
7529 (org-defkey orgstruct-mode-map key cmd))
7530
7531 ;; Special treatment needed for TAB and RET
7532 (org-defkey orgstruct-mode-map [(tab)]
7533 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
7534 (org-defkey orgstruct-mode-map "\C-i"
7535 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
7536
7537 (org-defkey orgstruct-mode-map "\M-\C-m"
7538 (orgstruct-make-binding 'org-insert-heading 105
7539 "\M-\C-m" [(meta return)]))
7540 (org-defkey orgstruct-mode-map [(meta return)]
7541 (orgstruct-make-binding 'org-insert-heading 106
7542 [(meta return)] "\M-\C-m"))
7543
7544 (org-defkey orgstruct-mode-map [(shift meta return)]
7545 (orgstruct-make-binding 'org-insert-todo-heading 107
7546 [(meta return)] "\M-\C-m"))
7547
7548 (org-defkey orgstruct-mode-map "\e\C-m"
7549 (orgstruct-make-binding 'org-insert-heading 108
7550 "\e\C-m" [?\e (return)]))
7551 (org-defkey orgstruct-mode-map [?\e (return)]
7552 (orgstruct-make-binding 'org-insert-heading 109
7553 [?\e (return)] "\e\C-m"))
7554 (org-defkey orgstruct-mode-map [?\e (shift return)]
7555 (orgstruct-make-binding 'org-insert-todo-heading 110
7556 [?\e (return)] "\e\C-m"))
7557
7558 (unless org-local-vars
7559 (setq org-local-vars (org-get-local-variables)))
7560
7561 t))
7562
7563 (defun orgstruct-make-binding (fun n &rest keys)
7564 "Create a function for binding in the structure minor mode.
7565 FUN is the command to call inside a table. N is used to create a unique
7566 command name. KEYS are keys that should be checked in for a command
7567 to execute outside of tables."
7568 (eval
7569 (list 'defun
7570 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
7571 '(arg)
7572 (concat "In Structure, run `" (symbol-name fun) "'.\n"
7573 "Outside of structure, run the binding of `"
7574 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
7575 "'.")
7576 '(interactive "p")
7577 (list 'if
7578 `(org-context-p 'headline 'item
7579 (and orgstruct-is-++
7580 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
7581 'item-body))
7582 (list 'org-run-like-in-org-mode (list 'quote fun))
7583 (list 'let '(orgstruct-mode)
7584 (list 'call-interactively
7585 (append '(or)
7586 (mapcar (lambda (k)
7587 (list 'key-binding k))
7588 keys)
7589 '('orgstruct-error))))))))
7590
7591 (defun org-context-p (&rest contexts)
7592 "Check if local context is any of CONTEXTS.
7593 Possible values in the list of contexts are `table', `headline', and `item'."
7594 (let ((pos (point)))
7595 (goto-char (point-at-bol))
7596 (prog1 (or (and (memq 'table contexts)
7597 (looking-at "[ \t]*|"))
7598 (and (memq 'headline contexts)
7599 ;;????????? (looking-at "\\*+"))
7600 (looking-at outline-regexp))
7601 (and (memq 'item contexts)
7602 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
7603 (and (memq 'item-body contexts)
7604 (org-in-item-p)))
7605 (goto-char pos))))
7606
7607 (defun org-get-local-variables ()
7608 "Return a list of all local variables in an org-mode buffer."
7609 (let (varlist)
7610 (with-current-buffer (get-buffer-create "*Org tmp*")
7611 (erase-buffer)
7612 (org-mode)
7613 (setq varlist (buffer-local-variables)))
7614 (kill-buffer "*Org tmp*")
7615 (delq nil
7616 (mapcar
7617 (lambda (x)
7618 (setq x
7619 (if (symbolp x)
7620 (list x)
7621 (list (car x) (list 'quote (cdr x)))))
7622 (if (string-match
7623 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
7624 (symbol-name (car x)))
7625 x nil))
7626 varlist))))
7627
7628 ;;;###autoload
7629 (defun org-run-like-in-org-mode (cmd)
7630 "Run a command, pretending that the current buffer is in Org-mode.
7631 This will temporarily bind local variables that are typically bound in
7632 Org-mode to the values they have in Org-mode, and then interactively
7633 call CMD."
7634 (org-load-modules-maybe)
7635 (unless org-local-vars
7636 (setq org-local-vars (org-get-local-variables)))
7637 (eval (list 'let org-local-vars
7638 (list 'call-interactively (list 'quote cmd)))))
7639
7640 ;;;; Archiving
7641
7642 (defun org-get-category (&optional pos)
7643 "Get the category applying to position POS."
7644 (get-text-property (or pos (point)) 'org-category))
7645
7646 (defun org-refresh-category-properties ()
7647 "Refresh category text properties in the buffer."
7648 (let ((def-cat (cond
7649 ((null org-category)
7650 (if buffer-file-name
7651 (file-name-sans-extension
7652 (file-name-nondirectory buffer-file-name))
7653 "???"))
7654 ((symbolp org-category) (symbol-name org-category))
7655 (t org-category)))
7656 beg end cat pos optionp)
7657 (org-unmodified
7658 (save-excursion
7659 (save-restriction
7660 (widen)
7661 (goto-char (point-min))
7662 (put-text-property (point) (point-max) 'org-category def-cat)
7663 (while (re-search-forward
7664 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
7665 (setq pos (match-end 0)
7666 optionp (equal (char-after (match-beginning 0)) ?#)
7667 cat (org-trim (match-string 2)))
7668 (if optionp
7669 (setq beg (point-at-bol) end (point-max))
7670 (org-back-to-heading t)
7671 (setq beg (point) end (org-end-of-subtree t t)))
7672 (put-text-property beg end 'org-category cat)
7673 (goto-char pos)))))))
7674
7675
7676 ;;;; Link Stuff
7677
7678 ;;; Link abbreviations
7679
7680 (defun org-link-expand-abbrev (link)
7681 "Apply replacements as defined in `org-link-abbrev-alist."
7682 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
7683 (let* ((key (match-string 1 link))
7684 (as (or (assoc key org-link-abbrev-alist-local)
7685 (assoc key org-link-abbrev-alist)))
7686 (tag (and (match-end 2) (match-string 3 link)))
7687 rpl)
7688 (if (not as)
7689 link
7690 (setq rpl (cdr as))
7691 (cond
7692 ((symbolp rpl) (funcall rpl tag))
7693 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7694 ((string-match "%h" rpl)
7695 (replace-match (url-hexify-string (or tag "")) t t rpl))
7696 (t (concat rpl tag)))))
7697 link))
7698
7699 ;;; Storing and inserting links
7700
7701 (defvar org-insert-link-history nil
7702 "Minibuffer history for links inserted with `org-insert-link'.")
7703
7704 (defvar org-stored-links nil
7705 "Contains the links stored with `org-store-link'.")
7706
7707 (defvar org-store-link-plist nil
7708 "Plist with info about the most recently link created with `org-store-link'.")
7709
7710 (defvar org-link-protocols nil
7711 "Link protocols added to Org-mode using `org-add-link-type'.")
7712
7713 (defvar org-store-link-functions nil
7714 "List of functions that are called to create and store a link.
7715 Each function will be called in turn until one returns a non-nil
7716 value. Each function should check if it is responsible for creating
7717 this link (for example by looking at the major mode).
7718 If not, it must exit and return nil.
7719 If yes, it should return a non-nil value after a calling
7720 `org-store-link-props' with a list of properties and values.
7721 Special properties are:
7722
7723 :type The link prefix. like \"http\". This must be given.
7724 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7725 This is obligatory as well.
7726 :description Optional default description for the second pair
7727 of brackets in an Org-mode link. The user can still change
7728 this when inserting this link into an Org-mode buffer.
7729
7730 In addition to these, any additional properties can be specified
7731 and then used in remember templates.")
7732
7733 (defun org-add-link-type (type &optional follow export)
7734 "Add TYPE to the list of `org-link-types'.
7735 Re-compute all regular expressions depending on `org-link-types'
7736
7737 FOLLOW and EXPORT are two functions.
7738
7739 FOLLOW should take the link path as the single argument and do whatever
7740 is necessary to follow the link, for example find a file or display
7741 a mail message.
7742
7743 EXPORT should format the link path for export to one of the export formats.
7744 It should be a function accepting three arguments:
7745
7746 path the path of the link, the text after the prefix (like \"http:\")
7747 desc the description of the link, if any, nil if there was no description
7748 format the export format, a symbol like `html' or `latex'.
7749
7750 The function may use the FORMAT information to return different values
7751 depending on the format. The return value will be put literally into
7752 the exported file.
7753 Org-mode has a built-in default for exporting links. If you are happy with
7754 this default, there is no need to define an export function for the link
7755 type. For a simple example of an export function, see `org-bbdb.el'."
7756 (add-to-list 'org-link-types type t)
7757 (org-make-link-regexps)
7758 (if (assoc type org-link-protocols)
7759 (setcdr (assoc type org-link-protocols) (list follow export))
7760 (push (list type follow export) org-link-protocols)))
7761
7762 (defvar org-agenda-buffer-name)
7763
7764 ;;;###autoload
7765 (defun org-store-link (arg)
7766 "\\<org-mode-map>Store an org-link to the current location.
7767 This link is added to `org-stored-links' and can later be inserted
7768 into an org-buffer with \\[org-insert-link].
7769
7770 For some link types, a prefix arg is interpreted:
7771 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7772 For file links, arg negates `org-context-in-file-links'."
7773 (interactive "P")
7774 (org-load-modules-maybe)
7775 (setq org-store-link-plist nil) ; reset
7776 (let ((outline-regexp (org-get-limited-outline-regexp))
7777 link cpltxt desc description search txt custom-id)
7778 (cond
7779
7780 ((run-hook-with-args-until-success 'org-store-link-functions)
7781 (setq link (plist-get org-store-link-plist :link)
7782 desc (or (plist-get org-store-link-plist :description) link)))
7783
7784 ((equal (buffer-name) "*Org Edit Src Example*")
7785 (let (label gc)
7786 (while (or (not label)
7787 (save-excursion
7788 (save-restriction
7789 (widen)
7790 (goto-char (point-min))
7791 (re-search-forward
7792 (regexp-quote (format org-coderef-label-format label))
7793 nil t))))
7794 (when label (message "Label exists already") (sit-for 2))
7795 (setq label (read-string "Code line label: " label)))
7796 (end-of-line 1)
7797 (setq link (format org-coderef-label-format label))
7798 (setq gc (- 79 (length link)))
7799 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7800 (insert link)
7801 (setq link (concat "(" label ")") desc nil)))
7802
7803 ((equal (org-bound-and-true-p org-agenda-buffer-name) (buffer-name))
7804 ;; We are in the agenda, link to referenced location
7805 (let ((m (or (get-text-property (point) 'org-hd-marker)
7806 (get-text-property (point) 'org-marker))))
7807 (when m
7808 (org-with-point-at m
7809 (call-interactively 'org-store-link)))))
7810
7811 ((eq major-mode 'calendar-mode)
7812 (let ((cd (calendar-cursor-to-date)))
7813 (setq link
7814 (format-time-string
7815 (car org-time-stamp-formats)
7816 (apply 'encode-time
7817 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7818 nil nil nil))))
7819 (org-store-link-props :type "calendar" :date cd)))
7820
7821 ((eq major-mode 'w3-mode)
7822 (setq cpltxt (if (and (buffer-name)
7823 (not (string-match "Untitled" (buffer-name))))
7824 (buffer-name)
7825 (url-view-url t))
7826 link (org-make-link (url-view-url t)))
7827 (org-store-link-props :type "w3" :url (url-view-url t)))
7828
7829 ((eq major-mode 'w3m-mode)
7830 (setq cpltxt (or w3m-current-title w3m-current-url)
7831 link (org-make-link w3m-current-url))
7832 (org-store-link-props :type "w3m" :url (url-view-url t)))
7833
7834 ((setq search (run-hook-with-args-until-success
7835 'org-create-file-search-functions))
7836 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7837 "::" search))
7838 (setq cpltxt (or description link)))
7839
7840 ((eq major-mode 'image-mode)
7841 (setq cpltxt (concat "file:"
7842 (abbreviate-file-name buffer-file-name))
7843 link (org-make-link cpltxt))
7844 (org-store-link-props :type "image" :file buffer-file-name))
7845
7846 ((eq major-mode 'dired-mode)
7847 ;; link to the file in the current line
7848 (let ((file (dired-get-filename nil t)))
7849 (setq file (if file
7850 (abbreviate-file-name
7851 (expand-file-name (dired-get-filename nil t)))
7852 ;; otherwise, no file so use current directory.
7853 default-directory))
7854 (setq cpltxt (concat "file:" file)
7855 link (org-make-link cpltxt))))
7856
7857 ((and buffer-file-name (org-mode-p))
7858 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7859 (cond
7860 ((org-in-regexp "<<\\(.*?\\)>>")
7861 (setq cpltxt
7862 (concat "file:"
7863 (abbreviate-file-name buffer-file-name)
7864 "::" (match-string 1))
7865 link (org-make-link cpltxt)))
7866 ((and (featurep 'org-id)
7867 (or (eq org-link-to-org-use-id t)
7868 (and (eq org-link-to-org-use-id 'create-if-interactive)
7869 (interactive-p))
7870 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7871 (interactive-p)
7872 (not custom-id))
7873 (and org-link-to-org-use-id
7874 (condition-case nil
7875 (org-entry-get nil "ID")
7876 (error nil)))))
7877 ;; We can make a link using the ID.
7878 (setq link (condition-case nil
7879 (prog1 (org-id-store-link)
7880 (setq desc (plist-get org-store-link-plist
7881 :description)))
7882 (error
7883 ;; probably before first headline, link to file only
7884 (concat "file:"
7885 (abbreviate-file-name buffer-file-name))))))
7886 (t
7887 ;; Just link to current headline
7888 (setq cpltxt (concat "file:"
7889 (abbreviate-file-name buffer-file-name)))
7890 ;; Add a context search string
7891 (when (org-xor org-context-in-file-links arg)
7892 (setq txt (cond
7893 ((org-on-heading-p) nil)
7894 ((org-region-active-p)
7895 (buffer-substring (region-beginning) (region-end)))
7896 (t nil)))
7897 (when (or (null txt) (string-match "\\S-" txt))
7898 (setq cpltxt
7899 (concat cpltxt "::"
7900 (condition-case nil
7901 (org-make-org-heading-search-string txt)
7902 (error "")))
7903 desc (or (nth 4 (ignore-errors
7904 (org-heading-components))) "NONE"))))
7905 (if (string-match "::\\'" cpltxt)
7906 (setq cpltxt (substring cpltxt 0 -2)))
7907 (setq link (org-make-link cpltxt)))))
7908
7909 ((buffer-file-name (buffer-base-buffer))
7910 ;; Just link to this file here.
7911 (setq cpltxt (concat "file:"
7912 (abbreviate-file-name
7913 (buffer-file-name (buffer-base-buffer)))))
7914 ;; Add a context string
7915 (when (org-xor org-context-in-file-links arg)
7916 (setq txt (if (org-region-active-p)
7917 (buffer-substring (region-beginning) (region-end))
7918 (buffer-substring (point-at-bol) (point-at-eol))))
7919 ;; Only use search option if there is some text.
7920 (when (string-match "\\S-" txt)
7921 (setq cpltxt
7922 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7923 desc "NONE")))
7924 (setq link (org-make-link cpltxt)))
7925
7926 ((interactive-p)
7927 (error "Cannot link to a buffer which is not visiting a file"))
7928
7929 (t (setq link nil)))
7930
7931 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7932 (setq link (or link cpltxt)
7933 desc (or desc cpltxt))
7934 (if (equal desc "NONE") (setq desc nil))
7935
7936 (if (and (or (interactive-p) executing-kbd-macro) link)
7937 (progn
7938 (setq org-stored-links
7939 (cons (list link desc) org-stored-links))
7940 (message "Stored: %s" (or desc link))
7941 (when custom-id
7942 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7943 "::#" custom-id))
7944 (setq org-stored-links
7945 (cons (list link desc) org-stored-links))))
7946 (and link (org-make-link-string link desc)))))
7947
7948 (defun org-store-link-props (&rest plist)
7949 "Store link properties, extract names and addresses."
7950 (let (x adr)
7951 (when (setq x (plist-get plist :from))
7952 (setq adr (mail-extract-address-components x))
7953 (setq plist (plist-put plist :fromname (car adr)))
7954 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7955 (when (setq x (plist-get plist :to))
7956 (setq adr (mail-extract-address-components x))
7957 (setq plist (plist-put plist :toname (car adr)))
7958 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7959 (let ((from (plist-get plist :from))
7960 (to (plist-get plist :to)))
7961 (when (and from to org-from-is-user-regexp)
7962 (setq plist
7963 (plist-put plist :fromto
7964 (if (string-match org-from-is-user-regexp from)
7965 (concat "to %t")
7966 (concat "from %f"))))))
7967 (setq org-store-link-plist plist))
7968
7969 (defun org-add-link-props (&rest plist)
7970 "Add these properties to the link property list."
7971 (let (key value)
7972 (while plist
7973 (setq key (pop plist) value (pop plist))
7974 (setq org-store-link-plist
7975 (plist-put org-store-link-plist key value)))))
7976
7977 (defun org-email-link-description (&optional fmt)
7978 "Return the description part of an email link.
7979 This takes information from `org-store-link-plist' and formats it
7980 according to FMT (default from `org-email-link-description-format')."
7981 (setq fmt (or fmt org-email-link-description-format))
7982 (let* ((p org-store-link-plist)
7983 (to (plist-get p :toaddress))
7984 (from (plist-get p :fromaddress))
7985 (table
7986 (list
7987 (cons "%c" (plist-get p :fromto))
7988 (cons "%F" (plist-get p :from))
7989 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7990 (cons "%T" (plist-get p :to))
7991 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7992 (cons "%s" (plist-get p :subject))
7993 (cons "%m" (plist-get p :message-id)))))
7994 (when (string-match "%c" fmt)
7995 ;; Check if the user wrote this message
7996 (if (and org-from-is-user-regexp from to
7997 (save-match-data (string-match org-from-is-user-regexp from)))
7998 (setq fmt (replace-match "to %t" t t fmt))
7999 (setq fmt (replace-match "from %f" t t fmt))))
8000 (org-replace-escapes fmt table)))
8001
8002 (defun org-make-org-heading-search-string (&optional string heading)
8003 "Make search string for STRING or current headline."
8004 (interactive)
8005 (let ((s (or string (org-get-heading))))
8006 (unless (and string (not heading))
8007 ;; We are using a headline, clean up garbage in there.
8008 (if (string-match org-todo-regexp s)
8009 (setq s (replace-match "" t t s)))
8010 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
8011 (setq s (replace-match "" t t s)))
8012 (setq s (org-trim s))
8013 (if (string-match (concat "^\\(" org-quote-string "\\|"
8014 org-comment-string "\\)") s)
8015 (setq s (replace-match "" t t s)))
8016 (while (string-match org-ts-regexp s)
8017 (setq s (replace-match "" t t s))))
8018 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
8019 (setq s (replace-match " " t t s)))
8020 (or string (setq s (concat "*" s))) ; Add * for headlines
8021 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
8022
8023 (defun org-make-link (&rest strings)
8024 "Concatenate STRINGS."
8025 (apply 'concat strings))
8026
8027 (defun org-make-link-string (link &optional description)
8028 "Make a link with brackets, consisting of LINK and DESCRIPTION."
8029 (unless (string-match "\\S-" link)
8030 (error "Empty link"))
8031 (when (and description
8032 (stringp description)
8033 (not (string-match "\\S-" description)))
8034 (setq description nil))
8035 (when (stringp description)
8036 ;; Remove brackets from the description, they are fatal.
8037 (while (string-match "\\[" description)
8038 (setq description (replace-match "{" t t description)))
8039 (while (string-match "\\]" description)
8040 (setq description (replace-match "}" t t description))))
8041 (when (equal (org-link-escape link) description)
8042 ;; No description needed, it is identical
8043 (setq description nil))
8044 (when (and (not description)
8045 (not (equal link (org-link-escape link))))
8046 (setq description (org-extract-attributes link)))
8047 (concat "[[" (org-link-escape link) "]"
8048 (if description (concat "[" description "]") "")
8049 "]"))
8050
8051 (defconst org-link-escape-chars
8052 '((?\ . "%20")
8053 (?\[ . "%5B")
8054 (?\] . "%5D")
8055 (?\340 . "%E0") ; `a
8056 (?\342 . "%E2") ; ^a
8057 (?\347 . "%E7") ; ,c
8058 (?\350 . "%E8") ; `e
8059 (?\351 . "%E9") ; 'e
8060 (?\352 . "%EA") ; ^e
8061 (?\356 . "%EE") ; ^i
8062 (?\364 . "%F4") ; ^o
8063 (?\371 . "%F9") ; `u
8064 (?\373 . "%FB") ; ^u
8065 (?\; . "%3B")
8066 ;; (?? . "%3F")
8067 (?= . "%3D")
8068 (?+ . "%2B")
8069 )
8070 "Association list of escapes for some characters problematic in links.
8071 This is the list that is used for internal purposes.")
8072
8073 (defvar org-url-encoding-use-url-hexify nil)
8074
8075 (defconst org-link-escape-chars-browser
8076 '((?\ . "%20")) ; 32 for the SPC char
8077 "Association list of escapes for some characters problematic in links.
8078 This is the list that is used before handing over to the browser.")
8079
8080 (defun org-link-escape (text &optional table)
8081 "Escape characters in TEXT that are problematic for links."
8082 (if (and org-url-encoding-use-url-hexify (not table))
8083 (url-hexify-string text)
8084 (setq table (or table org-link-escape-chars))
8085 (when text
8086 (let ((re (mapconcat (lambda (x) (regexp-quote
8087 (char-to-string (car x))))
8088 table "\\|")))
8089 (while (string-match re text)
8090 (setq text
8091 (replace-match
8092 (cdr (assoc (string-to-char (match-string 0 text))
8093 table))
8094 t t text)))
8095 text))))
8096
8097 (defun org-link-unescape (text &optional table)
8098 "Reverse the action of `org-link-escape'."
8099 (if (and org-url-encoding-use-url-hexify (not table))
8100 (url-unhex-string text)
8101 (setq table (or table org-link-escape-chars))
8102 (when text
8103 (let ((case-fold-search t)
8104 (re (mapconcat (lambda (x) (regexp-quote (downcase (cdr x))))
8105 table "\\|")))
8106 (while (string-match re text)
8107 (setq text
8108 (replace-match
8109 (char-to-string (car (rassoc (upcase (match-string 0 text))
8110 table)))
8111 t t text)))
8112 text))))
8113
8114 (defun org-xor (a b)
8115 "Exclusive or."
8116 (if a (not b) b))
8117
8118 (defun org-fixup-message-id-for-http (s)
8119 "Replace special characters in a message id, so it can be used in an http query."
8120 (while (string-match "<" s)
8121 (setq s (replace-match "%3C" t t s)))
8122 (while (string-match ">" s)
8123 (setq s (replace-match "%3E" t t s)))
8124 (while (string-match "@" s)
8125 (setq s (replace-match "%40" t t s)))
8126 s)
8127
8128 ;;;###autoload
8129 (defun org-insert-link-global ()
8130 "Insert a link like Org-mode does.
8131 This command can be called in any mode to insert a link in Org-mode syntax."
8132 (interactive)
8133 (org-load-modules-maybe)
8134 (org-run-like-in-org-mode 'org-insert-link))
8135
8136 (defun org-insert-link (&optional complete-file link-location)
8137 "Insert a link. At the prompt, enter the link.
8138
8139 Completion can be used to insert any of the link protocol prefixes like
8140 http or ftp in use.
8141
8142 The history can be used to select a link previously stored with
8143 `org-store-link'. When the empty string is entered (i.e. if you just
8144 press RET at the prompt), the link defaults to the most recently
8145 stored link. As SPC triggers completion in the minibuffer, you need to
8146 use M-SPC or C-q SPC to force the insertion of a space character.
8147
8148 You will also be prompted for a description, and if one is given, it will
8149 be displayed in the buffer instead of the link.
8150
8151 If there is already a link at point, this command will allow you to edit link
8152 and description parts.
8153
8154 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
8155 be selected using completion. The path to the file will be relative to the
8156 current directory if the file is in the current directory or a subdirectory.
8157 Otherwise, the link will be the absolute path as completed in the minibuffer
8158 \(i.e. normally ~/path/to/file). You can configure this behavior using the
8159 option `org-link-file-path-type'.
8160
8161 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
8162 the current directory or below.
8163
8164 With three \\[universal-argument] prefixes, negate the meaning of
8165 `org-keep-stored-link-after-insertion'.
8166
8167 If `org-make-link-description-function' is non-nil, this function will be
8168 called with the link target, and the result will be the default
8169 link description.
8170
8171 If the LINK-LOCATION parameter is non-nil, this value will be
8172 used as the link location instead of reading one interactively."
8173 (interactive "P")
8174 (let* ((wcf (current-window-configuration))
8175 (region (if (org-region-active-p)
8176 (buffer-substring (region-beginning) (region-end))))
8177 (remove (and region (list (region-beginning) (region-end))))
8178 (desc region)
8179 tmphist ; byte-compile incorrectly complains about this
8180 (link link-location)
8181 entry file all-prefixes)
8182 (cond
8183 (link-location) ; specified by arg, just use it.
8184 ((org-in-regexp org-bracket-link-regexp 1)
8185 ;; We do have a link at point, and we are going to edit it.
8186 (setq remove (list (match-beginning 0) (match-end 0)))
8187 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
8188 (setq link (read-string "Link: "
8189 (org-link-unescape
8190 (org-match-string-no-properties 1)))))
8191 ((or (org-in-regexp org-angle-link-re)
8192 (org-in-regexp org-plain-link-re))
8193 ;; Convert to bracket link
8194 (setq remove (list (match-beginning 0) (match-end 0))
8195 link (read-string "Link: "
8196 (org-remove-angle-brackets (match-string 0)))))
8197 ((member complete-file '((4) (16)))
8198 ;; Completing read for file names.
8199 (setq link (org-file-complete-link complete-file)))
8200 (t
8201 ;; Read link, with completion for stored links.
8202 (with-output-to-temp-buffer "*Org Links*"
8203 (princ "Insert a link.
8204 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
8205 (when org-stored-links
8206 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
8207 (princ (mapconcat
8208 (lambda (x)
8209 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
8210 (reverse org-stored-links) "\n"))))
8211 (let ((cw (selected-window)))
8212 (select-window (get-buffer-window "*Org Links*" 'visible))
8213 (setq truncate-lines t)
8214 (unless (pos-visible-in-window-p (point-max))
8215 (org-fit-window-to-buffer))
8216 (and (window-live-p cw) (select-window cw)))
8217 ;; Fake a link history, containing the stored links.
8218 (setq tmphist (append (mapcar 'car org-stored-links)
8219 org-insert-link-history))
8220 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
8221 (mapcar 'car org-link-abbrev-alist)
8222 org-link-types))
8223 (unwind-protect
8224 (progn
8225 (setq link
8226 (let ((org-completion-use-ido nil)
8227 (org-completion-use-iswitchb nil))
8228 (org-completing-read
8229 "Link: "
8230 (append
8231 (mapcar (lambda (x) (list (concat x ":")))
8232 all-prefixes)
8233 (mapcar 'car org-stored-links))
8234 nil nil nil
8235 'tmphist
8236 (car (car org-stored-links)))))
8237 (if (not (string-match "\\S-" link))
8238 (error "No link selected"))
8239 (if (or (member link all-prefixes)
8240 (and (equal ":" (substring link -1))
8241 (member (substring link 0 -1) all-prefixes)
8242 (setq link (substring link 0 -1))))
8243 (setq link (org-link-try-special-completion link))))
8244 (set-window-configuration wcf)
8245 (kill-buffer "*Org Links*"))
8246 (setq entry (assoc link org-stored-links))
8247 (or entry (push link org-insert-link-history))
8248 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
8249 (not org-keep-stored-link-after-insertion))
8250 (setq org-stored-links (delq (assoc link org-stored-links)
8251 org-stored-links)))
8252 (setq desc (or desc (nth 1 entry)))))
8253
8254 (if (string-match org-plain-link-re link)
8255 ;; URL-like link, normalize the use of angular brackets.
8256 (setq link (org-make-link (org-remove-angle-brackets link))))
8257
8258 ;; Check if we are linking to the current file with a search option
8259 ;; If yes, simplify the link by using only the search option.
8260 (when (and buffer-file-name
8261 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
8262 (let* ((path (match-string 1 link))
8263 (case-fold-search nil)
8264 (search (match-string 2 link)))
8265 (save-match-data
8266 (if (equal (file-truename buffer-file-name) (file-truename path))
8267 ;; We are linking to this same file, with a search option
8268 (setq link search)))))
8269
8270 ;; Check if we can/should use a relative path. If yes, simplify the link
8271 (when (string-match "^\\(file:\\|docview:\\)\\(.*\\)" link)
8272 (let* ((type (match-string 1 link))
8273 (path (match-string 2 link))
8274 (origpath path)
8275 (case-fold-search nil))
8276 (cond
8277 ((or (eq org-link-file-path-type 'absolute)
8278 (equal complete-file '(16)))
8279 (setq path (abbreviate-file-name (expand-file-name path))))
8280 ((eq org-link-file-path-type 'noabbrev)
8281 (setq path (expand-file-name path)))
8282 ((eq org-link-file-path-type 'relative)
8283 (setq path (file-relative-name path)))
8284 (t
8285 (save-match-data
8286 (if (string-match (concat "^" (regexp-quote
8287 (file-name-as-directory
8288 (expand-file-name "."))))
8289 (expand-file-name path))
8290 ;; We are linking a file with relative path name.
8291 (setq path (substring (expand-file-name path)
8292 (match-end 0)))
8293 (setq path (abbreviate-file-name (expand-file-name path)))))))
8294 (setq link (concat type path))
8295 (if (equal desc origpath)
8296 (setq desc path))))
8297
8298 (if org-make-link-description-function
8299 (setq desc (funcall org-make-link-description-function link desc)))
8300
8301 (setq desc (read-string "Description: " desc))
8302 (unless (string-match "\\S-" desc) (setq desc nil))
8303 (if remove (apply 'delete-region remove))
8304 (insert (org-make-link-string link desc))))
8305
8306 (defun org-link-try-special-completion (type)
8307 "If there is completion support for link type TYPE, offer it."
8308 (let ((fun (intern (concat "org-" type "-complete-link"))))
8309 (if (functionp fun)
8310 (funcall fun)
8311 (read-string "Link (no completion support): " (concat type ":")))))
8312
8313 (defun org-file-complete-link (&optional arg)
8314 "Create a file link using completion."
8315 (let (file link)
8316 (setq file (read-file-name "File: "))
8317 (let ((pwd (file-name-as-directory (expand-file-name ".")))
8318 (pwd1 (file-name-as-directory (abbreviate-file-name
8319 (expand-file-name ".")))))
8320 (cond
8321 ((equal arg '(16))
8322 (setq link (org-make-link
8323 "file:"
8324 (abbreviate-file-name (expand-file-name file)))))
8325 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
8326 (setq link (org-make-link "file:" (match-string 1 file))))
8327 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
8328 (expand-file-name file))
8329 (setq link (org-make-link
8330 "file:" (match-string 1 (expand-file-name file)))))
8331 (t (setq link (org-make-link "file:" file)))))
8332 link))
8333
8334 (defun org-completing-read (&rest args)
8335 "Completing-read with SPACE being a normal character."
8336 (let ((minibuffer-local-completion-map
8337 (copy-keymap minibuffer-local-completion-map)))
8338 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
8339 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
8340 (apply 'org-icompleting-read args)))
8341
8342 (defun org-completing-read-no-i (&rest args)
8343 (let (org-completion-use-ido org-completion-use-iswitchb)
8344 (apply 'org-completing-read args)))
8345
8346 (defun org-iswitchb-completing-read (prompt choices &rest args)
8347 "Use iswitch as a completing-read replacement to choose from choices.
8348 PROMPT is a string to prompt with. CHOICES is a list of strings to choose
8349 from."
8350 (let* ((iswitchb-use-virtual-buffers nil)
8351 (iswitchb-make-buflist-hook
8352 (lambda ()
8353 (setq iswitchb-temp-buflist choices))))
8354 (iswitchb-read-buffer prompt)))
8355
8356 (defun org-icompleting-read (&rest args)
8357 "Completing-read using `ido-mode' or `iswitchb' speedups if available."
8358 (org-without-partial-completion
8359 (if (and org-completion-use-ido
8360 (fboundp 'ido-completing-read)
8361 (boundp 'ido-mode) ido-mode
8362 (listp (second args)))
8363 (let ((ido-enter-matching-directory nil))
8364 (apply 'ido-completing-read (concat (car args))
8365 (if (consp (car (nth 1 args)))
8366 (mapcar (lambda (x) (car x)) (nth 1 args))
8367 (nth 1 args))
8368 (cddr args)))
8369 (if (and org-completion-use-iswitchb
8370 (boundp 'iswitchb-mode) iswitchb-mode
8371 (listp (second args)))
8372 (apply 'org-iswitchb-completing-read (concat (car args))
8373 (if (consp (car (nth 1 args)))
8374 (mapcar (lambda (x) (car x)) (nth 1 args))
8375 (nth 1 args))
8376 (cddr args))
8377 (apply 'completing-read args)))))
8378
8379 (defun org-extract-attributes (s)
8380 "Extract the attributes cookie from a string and set as text property."
8381 (let (a attr (start 0) key value)
8382 (save-match-data
8383 (when (string-match "{{\\([^}]+\\)}}$" s)
8384 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
8385 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
8386 (setq key (match-string 1 a) value (match-string 2 a)
8387 start (match-end 0)
8388 attr (plist-put attr (intern key) value))))
8389 (org-add-props s nil 'org-attr attr))
8390 s))
8391
8392 (defun org-extract-attributes-from-string (tag)
8393 (let (key value attr)
8394 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
8395 (setq key (match-string 1 tag) value (match-string 2 tag)
8396 tag (replace-match "" t t tag)
8397 attr (plist-put attr (intern key) value)))
8398 (cons tag attr)))
8399
8400 (defun org-attributes-to-string (plist)
8401 "Format a property list into an HTML attribute list."
8402 (let ((s "") key value)
8403 (while plist
8404 (setq key (pop plist) value (pop plist))
8405 (and value
8406 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
8407 s))
8408
8409 ;;; Opening/following a link
8410
8411 (defvar org-link-search-failed nil)
8412
8413 (defvar org-open-link-functions nil
8414 "Hook for functions finding a plain text link.
8415 These functions must take a single argument, the link content.
8416 They will be called for links that look like [[link text][description]]
8417 when LINK TEXT does not have a protocol like \"http:\" and does not look
8418 like a filename (e.g. \"./blue.png\").
8419
8420 These functions will be called *before* Org attempts to resolve the
8421 link by doing text searches in the current buffer - so if you want a
8422 link \"[[target]]\" to still find \"<<target>>\", your function should
8423 handle this as a special case.
8424
8425 When the function does handle the link, it must return a non-nil value.
8426 If it decides that it is not responsible for this link, it must return
8427 nil to indicate that that Org-mode can continue with other options
8428 like exact and fuzzy text search.")
8429
8430 (defun org-next-link ()
8431 "Move forward to the next link.
8432 If the link is in hidden text, expose it."
8433 (interactive)
8434 (when (and org-link-search-failed (eq this-command last-command))
8435 (goto-char (point-min))
8436 (message "Link search wrapped back to beginning of buffer"))
8437 (setq org-link-search-failed nil)
8438 (let* ((pos (point))
8439 (ct (org-context))
8440 (a (assoc :link ct)))
8441 (if a (goto-char (nth 2 a)))
8442 (if (re-search-forward org-any-link-re nil t)
8443 (progn
8444 (goto-char (match-beginning 0))
8445 (if (org-invisible-p) (org-show-context)))
8446 (goto-char pos)
8447 (setq org-link-search-failed t)
8448 (error "No further link found"))))
8449
8450 (defun org-previous-link ()
8451 "Move backward to the previous link.
8452 If the link is in hidden text, expose it."
8453 (interactive)
8454 (when (and org-link-search-failed (eq this-command last-command))
8455 (goto-char (point-max))
8456 (message "Link search wrapped back to end of buffer"))
8457 (setq org-link-search-failed nil)
8458 (let* ((pos (point))
8459 (ct (org-context))
8460 (a (assoc :link ct)))
8461 (if a (goto-char (nth 1 a)))
8462 (if (re-search-backward org-any-link-re nil t)
8463 (progn
8464 (goto-char (match-beginning 0))
8465 (if (org-invisible-p) (org-show-context)))
8466 (goto-char pos)
8467 (setq org-link-search-failed t)
8468 (error "No further link found"))))
8469
8470 (defun org-translate-link (s)
8471 "Translate a link string if a translation function has been defined."
8472 (if (and org-link-translation-function
8473 (fboundp org-link-translation-function)
8474 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
8475 (progn
8476 (setq s (funcall org-link-translation-function
8477 (match-string 1) (match-string 2)))
8478 (concat (car s) ":" (cdr s)))
8479 s))
8480
8481 (defun org-translate-link-from-planner (type path)
8482 "Translate a link from Emacs Planner syntax so that Org can follow it.
8483 This is still an experimental function, your mileage may vary."
8484 (cond
8485 ((member type '("http" "https" "news" "ftp"))
8486 ;; standard Internet links are the same.
8487 nil)
8488 ((and (equal type "irc") (string-match "^//" path))
8489 ;; Planner has two / at the beginning of an irc link, we have 1.
8490 ;; We should have zero, actually....
8491 (setq path (substring path 1)))
8492 ((and (equal type "lisp") (string-match "^/" path))
8493 ;; Planner has a slash, we do not.
8494 (setq type "elisp" path (substring path 1)))
8495 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
8496 ;; A typical message link. Planner has the id after the final slash,
8497 ;; we separate it with a hash mark
8498 (setq path (concat (match-string 1 path) "#"
8499 (org-remove-angle-brackets (match-string 2 path)))))
8500 )
8501 (cons type path))
8502
8503 (defun org-find-file-at-mouse (ev)
8504 "Open file link or URL at mouse."
8505 (interactive "e")
8506 (mouse-set-point ev)
8507 (org-open-at-point 'in-emacs))
8508
8509 (defun org-open-at-mouse (ev)
8510 "Open file link or URL at mouse."
8511 (interactive "e")
8512 (mouse-set-point ev)
8513 (if (eq major-mode 'org-agenda-mode)
8514 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
8515 (org-open-at-point))
8516
8517 (defvar org-window-config-before-follow-link nil
8518 "The window configuration before following a link.
8519 This is saved in case the need arises to restore it.")
8520
8521 (defvar org-open-link-marker (make-marker)
8522 "Marker pointing to the location where `org-open-at-point; was called.")
8523
8524 ;;;###autoload
8525 (defun org-open-at-point-global ()
8526 "Follow a link like Org-mode does.
8527 This command can be called in any mode to follow a link that has
8528 Org-mode syntax."
8529 (interactive)
8530 (org-run-like-in-org-mode 'org-open-at-point))
8531
8532 ;;;###autoload
8533 (defun org-open-link-from-string (s &optional arg reference-buffer)
8534 "Open a link in the string S, as if it was in Org-mode."
8535 (interactive "sLink: \nP")
8536 (let ((reference-buffer (or reference-buffer (current-buffer))))
8537 (with-temp-buffer
8538 (let ((org-inhibit-startup t))
8539 (org-mode)
8540 (insert s)
8541 (goto-char (point-min))
8542 (when reference-buffer
8543 (setq org-link-abbrev-alist-local
8544 (with-current-buffer reference-buffer
8545 org-link-abbrev-alist-local)))
8546 (org-open-at-point arg reference-buffer)))))
8547
8548 (defun org-open-at-point (&optional in-emacs reference-buffer)
8549 "Open link at or after point.
8550 If there is no link at point, this function will search forward up to
8551 the end of the current line.
8552 Normally, files will be opened by an appropriate application. If the
8553 optional argument IN-EMACS is non-nil, Emacs will visit the file.
8554 With a double prefix argument, try to open outside of Emacs, in the
8555 application the system uses for this file type."
8556 (interactive "P")
8557 (org-load-modules-maybe)
8558 (move-marker org-open-link-marker (point))
8559 (setq org-window-config-before-follow-link (current-window-configuration))
8560 (org-remove-occur-highlights nil nil t)
8561 (cond
8562 ((and (org-on-heading-p)
8563 (not (org-in-regexp
8564 (concat org-plain-link-re "\\|"
8565 org-bracket-link-regexp "\\|"
8566 org-angle-link-re "\\|"
8567 "[ \t]:[^ \t\n]+:[ \t]*$")))
8568 (not (get-text-property (point) 'org-linked-text)))
8569 (or (org-offer-links-in-entry in-emacs)
8570 (progn (require 'org-attach) (org-attach-reveal 'if-exists))))
8571 ((org-at-timestamp-p t) (org-follow-timestamp-link))
8572 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
8573 (org-footnote-action))
8574 (t
8575 (let (type path link line search (pos (point)))
8576 (catch 'match
8577 (save-excursion
8578 (skip-chars-forward "^]\n\r")
8579 (when (org-in-regexp org-bracket-link-regexp 1)
8580 (setq link (org-extract-attributes
8581 (org-link-unescape (org-match-string-no-properties 1))))
8582 (while (string-match " *\n *" link)
8583 (setq link (replace-match " " t t link)))
8584 (setq link (org-link-expand-abbrev link))
8585 (cond
8586 ((or (file-name-absolute-p link)
8587 (string-match "^\\.\\.?/" link))
8588 (setq type "file" path link))
8589 ((string-match org-link-re-with-space3 link)
8590 (setq type (match-string 1 link) path (match-string 2 link)))
8591 (t (setq type "thisfile" path link)))
8592 (throw 'match t)))
8593
8594 (when (get-text-property (point) 'org-linked-text)
8595 (setq type "thisfile"
8596 pos (if (get-text-property (1+ (point)) 'org-linked-text)
8597 (1+ (point)) (point))
8598 path (buffer-substring
8599 (previous-single-property-change pos 'org-linked-text)
8600 (next-single-property-change pos 'org-linked-text)))
8601 (throw 'match t))
8602
8603 (save-excursion
8604 (when (or (org-in-regexp org-angle-link-re)
8605 (org-in-regexp org-plain-link-re))
8606 (setq type (match-string 1) path (match-string 2))
8607 (throw 'match t)))
8608 (save-excursion
8609 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
8610 (setq type "tags"
8611 path (match-string 1))
8612 (while (string-match ":" path)
8613 (setq path (replace-match "+" t t path)))
8614 (throw 'match t)))
8615 (when (org-in-regexp "<\\([^><\n]+\\)>")
8616 (setq type "tree-match"
8617 path (match-string 1))
8618 (throw 'match t)))
8619 (unless path
8620 (error "No link found"))
8621
8622 ;; switch back to reference buffer
8623 ;; needed when if called in a temporary buffer through
8624 ;; org-open-link-from-string
8625 (with-current-buffer (or reference-buffer (current-buffer))
8626
8627 ;; Remove any trailing spaces in path
8628 (if (string-match " +\\'" path)
8629 (setq path (replace-match "" t t path)))
8630 (if (and org-link-translation-function
8631 (fboundp org-link-translation-function))
8632 ;; Check if we need to translate the link
8633 (let ((tmp (funcall org-link-translation-function type path)))
8634 (setq type (car tmp) path (cdr tmp))))
8635
8636 (cond
8637
8638 ((assoc type org-link-protocols)
8639 (funcall (nth 1 (assoc type org-link-protocols)) path))
8640
8641 ((equal type "mailto")
8642 (let ((cmd (car org-link-mailto-program))
8643 (args (cdr org-link-mailto-program)) args1
8644 (address path) (subject "") a)
8645 (if (string-match "\\(.*\\)::\\(.*\\)" path)
8646 (setq address (match-string 1 path)
8647 subject (org-link-escape (match-string 2 path))))
8648 (while args
8649 (cond
8650 ((not (stringp (car args))) (push (pop args) args1))
8651 (t (setq a (pop args))
8652 (if (string-match "%a" a)
8653 (setq a (replace-match address t t a)))
8654 (if (string-match "%s" a)
8655 (setq a (replace-match subject t t a)))
8656 (push a args1))))
8657 (apply cmd (nreverse args1))))
8658
8659 ((member type '("http" "https" "ftp" "news"))
8660 (browse-url (concat type ":" (org-link-escape
8661 path org-link-escape-chars-browser))))
8662
8663 ((member type '("message"))
8664 (browse-url (concat type ":" path)))
8665
8666 ((string= type "tags")
8667 (org-tags-view in-emacs path))
8668
8669 ((string= type "tree-match")
8670 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
8671
8672 ((string= type "file")
8673 (if (string-match "::\\([0-9]+\\)\\'" path)
8674 (setq line (string-to-number (match-string 1 path))
8675 path (substring path 0 (match-beginning 0)))
8676 (if (string-match "::\\(.+\\)\\'" path)
8677 (setq search (match-string 1 path)
8678 path (substring path 0 (match-beginning 0)))))
8679 (if (string-match "[*?{]" (file-name-nondirectory path))
8680 (dired path)
8681 (org-open-file path in-emacs line search)))
8682
8683 ((string= type "news")
8684 (require 'org-gnus)
8685 (org-gnus-follow-link path))
8686
8687 ((string= type "shell")
8688 (let ((cmd path))
8689 (if (or (not org-confirm-shell-link-function)
8690 (funcall org-confirm-shell-link-function
8691 (format "Execute \"%s\" in shell? "
8692 (org-add-props cmd nil
8693 'face 'org-warning))))
8694 (progn
8695 (message "Executing %s" cmd)
8696 (shell-command cmd))
8697 (error "Abort"))))
8698
8699 ((string= type "elisp")
8700 (let ((cmd path))
8701 (if (or (not org-confirm-elisp-link-function)
8702 (funcall org-confirm-elisp-link-function
8703 (format "Execute \"%s\" as elisp? "
8704 (org-add-props cmd nil
8705 'face 'org-warning))))
8706 (message "%s => %s" cmd
8707 (if (equal (string-to-char cmd) ?\()
8708 (eval (read cmd))
8709 (call-interactively (read cmd))))
8710 (error "Abort"))))
8711
8712 ((and (string= type "thisfile")
8713 (run-hook-with-args-until-success
8714 'org-open-link-functions path)))
8715
8716 ((string= type "thisfile")
8717 (if in-emacs
8718 (switch-to-buffer-other-window
8719 (org-get-buffer-for-internal-link (current-buffer)))
8720 (org-mark-ring-push))
8721 (let ((cmd `(org-link-search
8722 ,path
8723 ,(cond ((equal in-emacs '(4)) 'occur)
8724 ((equal in-emacs '(16)) 'org-occur)
8725 (t nil))
8726 ,pos)))
8727 (condition-case nil (eval cmd)
8728 (error (progn (widen) (eval cmd))))))
8729
8730 (t
8731 (browse-url-at-point)))))))
8732 (move-marker org-open-link-marker nil)
8733 (run-hook-with-args 'org-follow-link-hook))
8734
8735 (defun org-offer-links-in-entry (&optional nth zero)
8736 "Offer links in the current entry and follow the selected link.
8737 If there is only one link, follow it immediately as well.
8738 If NTH is an integer, immediately pick the NTH link found.
8739 If ZERO is a string, check also this string for a link, and if
8740 there is one, offer it as link number zero."
8741 (let ((re (concat "\\(" org-bracket-link-regexp "\\)\\|"
8742 "\\(" org-angle-link-re "\\)\\|"
8743 "\\(" org-plain-link-re "\\)"))
8744 (cnt ?0)
8745 (in-emacs (if (integerp nth) nil nth))
8746 have-zero end links link c)
8747 (when (and (stringp zero) (string-match org-bracket-link-regexp zero))
8748 (push (match-string 0 zero) links)
8749 (setq cnt (1- cnt) have-zero t))
8750 (save-excursion
8751 (org-back-to-heading t)
8752 (setq end (save-excursion (outline-next-heading) (point)))
8753 (while (re-search-forward re end t)
8754 (push (match-string 0) links))
8755 (setq links (org-uniquify (reverse links))))
8756
8757 (cond
8758 ((null links)
8759 (message "No links"))
8760 ((equal (length links) 1)
8761 (setq link (list (car links))))
8762 ((and (integerp nth) (>= (length links) (if have-zero (1+ nth) nth)))
8763 (setq link (nth (if have-zero nth (1- nth)) links)))
8764 (t ; we have to select a link
8765 (save-excursion
8766 (save-window-excursion
8767 (delete-other-windows)
8768 (with-output-to-temp-buffer "*Select Link*"
8769 (mapc (lambda (l)
8770 (if (not (string-match org-bracket-link-regexp l))
8771 (princ (format "[%c] %s\n" (incf cnt)
8772 (org-remove-angle-brackets l)))
8773 (if (match-end 3)
8774 (princ (format "[%c] %s (%s)\n" (incf cnt)
8775 (match-string 3 l) (match-string 1 l)))
8776 (princ (format "[%c] %s\n" (incf cnt)
8777 (match-string 1 l))))))
8778 links))
8779 (org-fit-window-to-buffer (get-buffer-window "*Select Link*"))
8780 (message "Select link to open, RET to open all:")
8781 (setq c (read-char-exclusive))
8782 (and (get-buffer "*Select Link*") (kill-buffer "*Select Link*"))))
8783 (when (equal c ?q) (error "Abort"))
8784 (if (equal c ?\C-m)
8785 (setq link links)
8786 (setq nth (- c ?0))
8787 (if have-zero (setq nth (1+ nth)))
8788 (unless (and (integerp nth) (>= (length links) nth))
8789 (error "Invalid link selection"))
8790 (setq link (list (nth (1- nth) links))))))
8791 (if link
8792 (let ((buf (current-buffer)))
8793 (dolist (l link)
8794 (org-open-link-from-string l in-emacs buf))
8795 t)
8796 nil)))
8797
8798 ;; Add special file links that specify the way of opening
8799
8800 (org-add-link-type "file+sys" 'org-open-file-with-system)
8801 (org-add-link-type "file+emacs" 'org-open-file-with-emacs)
8802 (defun org-open-file-with-system (path)
8803 "Open file at PATH using the system way of opeing it."
8804 (org-open-file path 'system))
8805 (defun org-open-file-with-emacs (path)
8806 "Open file at PATH in emacs."
8807 (org-open-file path 'emacs))
8808 (defun org-remove-file-link-modifiers ()
8809 "Remove the file link modifiers in `file+sys:' and `file+emacs:' links."
8810 (goto-char (point-min))
8811 (while (re-search-forward "\\<file\\+\\(sys\\|emacs\\):" nil t)
8812 (org-if-unprotected
8813 (replace-match "file:" t t))))
8814 (eval-after-load "org-exp"
8815 '(add-hook 'org-export-preprocess-before-normalizing-links-hook
8816 'org-remove-file-link-modifiers))
8817
8818 ;;;; Time estimates
8819
8820 (defun org-get-effort (&optional pom)
8821 "Get the effort estimate for the current entry."
8822 (org-entry-get pom org-effort-property))
8823
8824 ;;; File search
8825
8826 (defvar org-create-file-search-functions nil
8827 "List of functions to construct the right search string for a file link.
8828 These functions are called in turn with point at the location to
8829 which the link should point.
8830
8831 A function in the hook should first test if it would like to
8832 handle this file type, for example by checking the major-mode or
8833 the file extension. If it decides not to handle this file, it
8834 should just return nil to give other functions a chance. If it
8835 does handle the file, it must return the search string to be used
8836 when following the link. The search string will be part of the
8837 file link, given after a double colon, and `org-open-at-point'
8838 will automatically search for it. If special measures must be
8839 taken to make the search successful, another function should be
8840 added to the companion hook `org-execute-file-search-functions',
8841 which see.
8842
8843 A function in this hook may also use `setq' to set the variable
8844 `description' to provide a suggestion for the descriptive text to
8845 be used for this link when it gets inserted into an Org-mode
8846 buffer with \\[org-insert-link].")
8847
8848 (defvar org-execute-file-search-functions nil
8849 "List of functions to execute a file search triggered by a link.
8850
8851 Functions added to this hook must accept a single argument, the
8852 search string that was part of the file link, the part after the
8853 double colon. The function must first check if it would like to
8854 handle this search, for example by checking the major-mode or the
8855 file extension. If it decides not to handle this search, it
8856 should just return nil to give other functions a chance. If it
8857 does handle the search, it must return a non-nil value to keep
8858 other functions from trying.
8859
8860 Each function can access the current prefix argument through the
8861 variable `current-prefix-argument'. Note that a single prefix is
8862 used to force opening a link in Emacs, so it may be good to only
8863 use a numeric or double prefix to guide the search function.
8864
8865 In case this is needed, a function in this hook can also restore
8866 the window configuration before `org-open-at-point' was called using:
8867
8868 (set-window-configuration org-window-config-before-follow-link)")
8869
8870 (defun org-link-search (s &optional type avoid-pos)
8871 "Search for a link search option.
8872 If S is surrounded by forward slashes, it is interpreted as a
8873 regular expression. In org-mode files, this will create an `org-occur'
8874 sparse tree. In ordinary files, `occur' will be used to list matches.
8875 If the current buffer is in `dired-mode', grep will be used to search
8876 in all files. If AVOID-POS is given, ignore matches near that position."
8877 (let ((case-fold-search t)
8878 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8879 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8880 (append '(("") (" ") ("\t") ("\n"))
8881 org-emphasis-alist)
8882 "\\|") "\\)"))
8883 (pos (point))
8884 (pre nil) (post nil)
8885 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8886 (cond
8887 ;; First check if there are any special
8888 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8889 ;; Now try the builtin stuff
8890 ((and (equal (string-to-char s0) ?#)
8891 (> (length s0) 1)
8892 (save-excursion
8893 (goto-char (point-min))
8894 (and
8895 (re-search-forward
8896 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8897 (setq type 'dedicated
8898 pos (match-beginning 0))))
8899 ;; There is an exact target for this
8900 (goto-char pos)
8901 (org-back-to-heading t)))
8902 ((save-excursion
8903 (goto-char (point-min))
8904 (and
8905 (re-search-forward
8906 (concat "<<" (regexp-quote s0) ">>") nil t)
8907 (setq type 'dedicated
8908 pos (match-beginning 0))))
8909 ;; There is an exact target for this
8910 (goto-char pos))
8911 ((and (string-match "^(\\(.*\\))$" s0)
8912 (save-excursion
8913 (goto-char (point-min))
8914 (and
8915 (re-search-forward
8916 (concat "[^[]" (regexp-quote
8917 (format org-coderef-label-format
8918 (match-string 1 s0))))
8919 nil t)
8920 (setq type 'dedicated
8921 pos (1+ (match-beginning 0))))))
8922 ;; There is a coderef target for this
8923 (goto-char pos))
8924 ((string-match "^/\\(.*\\)/$" s)
8925 ;; A regular expression
8926 (cond
8927 ((org-mode-p)
8928 (org-occur (match-string 1 s)))
8929 ;;((eq major-mode 'dired-mode)
8930 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8931 (t (org-do-occur (match-string 1 s)))))
8932 (t
8933 ;; A normal search strings
8934 (when (equal (string-to-char s) ?*)
8935 ;; Anchor on headlines, post may include tags.
8936 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8937 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8938 s (substring s 1)))
8939 (remove-text-properties
8940 0 (length s)
8941 '(face nil mouse-face nil keymap nil fontified nil) s)
8942 ;; Make a series of regular expressions to find a match
8943 (setq words (org-split-string s "[ \n\r\t]+")
8944
8945 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8946 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8947 "\\)" markers)
8948 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8949 re2a (concat "[ \t\r\n]" re2a_)
8950 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8951 re4 (concat "[^a-zA-Z_]" re4_)
8952
8953 re1 (concat pre re2 post)
8954 re3 (concat pre (if pre re4_ re4) post)
8955 re5 (concat pre ".*" re4)
8956 re2 (concat pre re2)
8957 re2a (concat pre (if pre re2a_ re2a))
8958 re4 (concat pre (if pre re4_ re4))
8959 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8960 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8961 re5 "\\)"
8962 ))
8963 (cond
8964 ((eq type 'org-occur) (org-occur reall))
8965 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8966 (t (goto-char (point-min))
8967 (setq type 'fuzzy)
8968 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8969 (org-search-not-self 1 re1 nil t)
8970 (org-search-not-self 1 re2 nil t)
8971 (org-search-not-self 1 re2a nil t)
8972 (org-search-not-self 1 re3 nil t)
8973 (org-search-not-self 1 re4 nil t)
8974 (org-search-not-self 1 re5 nil t)
8975 )
8976 (goto-char (match-beginning 1))
8977 (goto-char pos)
8978 (error "No match")))))
8979 (t
8980 ;; Normal string-search
8981 (goto-char (point-min))
8982 (if (search-forward s nil t)
8983 (goto-char (match-beginning 0))
8984 (error "No match"))))
8985 (and (org-mode-p) (org-show-context 'link-search))
8986 type))
8987
8988 (defun org-search-not-self (group &rest args)
8989 "Execute `re-search-forward', but only accept matches that do not
8990 enclose the position of `org-open-link-marker'."
8991 (let ((m org-open-link-marker))
8992 (catch 'exit
8993 (while (apply 're-search-forward args)
8994 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8995 (goto-char (match-end group))
8996 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8997 (> (match-beginning 0) (marker-position m))
8998 (< (match-end 0) (marker-position m)))
8999 (save-match-data
9000 (or (not (org-in-regexp
9001 org-bracket-link-analytic-regexp 1))
9002 (not (match-end 4)) ; no description
9003 (and (<= (match-beginning 4) (point))
9004 (>= (match-end 4) (point))))))
9005 (throw 'exit (point))))))))
9006
9007 (defun org-get-buffer-for-internal-link (buffer)
9008 "Return a buffer to be used for displaying the link target of internal links."
9009 (cond
9010 ((not org-display-internal-link-with-indirect-buffer)
9011 buffer)
9012 ((string-match "(Clone)$" (buffer-name buffer))
9013 (message "Buffer is already a clone, not making another one")
9014 ;; we also do not modify visibility in this case
9015 buffer)
9016 (t ; make a new indirect buffer for displaying the link
9017 (let* ((bn (buffer-name buffer))
9018 (ibn (concat bn "(Clone)"))
9019 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
9020 (with-current-buffer ib (org-overview))
9021 ib))))
9022
9023 (defun org-do-occur (regexp &optional cleanup)
9024 "Call the Emacs command `occur'.
9025 If CLEANUP is non-nil, remove the printout of the regular expression
9026 in the *Occur* buffer. This is useful if the regex is long and not useful
9027 to read."
9028 (occur regexp)
9029 (when cleanup
9030 (let ((cwin (selected-window)) win beg end)
9031 (when (setq win (get-buffer-window "*Occur*"))
9032 (select-window win))
9033 (goto-char (point-min))
9034 (when (re-search-forward "match[a-z]+" nil t)
9035 (setq beg (match-end 0))
9036 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
9037 (setq end (1- (match-beginning 0)))))
9038 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
9039 (goto-char (point-min))
9040 (select-window cwin))))
9041
9042 ;;; The mark ring for links jumps
9043
9044 (defvar org-mark-ring nil
9045 "Mark ring for positions before jumps in Org-mode.")
9046 (defvar org-mark-ring-last-goto nil
9047 "Last position in the mark ring used to go back.")
9048 ;; Fill and close the ring
9049 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
9050 (loop for i from 1 to org-mark-ring-length do
9051 (push (make-marker) org-mark-ring))
9052 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
9053 org-mark-ring)
9054
9055 (defun org-mark-ring-push (&optional pos buffer)
9056 "Put the current position or POS into the mark ring and rotate it."
9057 (interactive)
9058 (setq pos (or pos (point)))
9059 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
9060 (move-marker (car org-mark-ring)
9061 (or pos (point))
9062 (or buffer (current-buffer)))
9063 (message "%s"
9064 (substitute-command-keys
9065 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
9066
9067 (defun org-mark-ring-goto (&optional n)
9068 "Jump to the previous position in the mark ring.
9069 With prefix arg N, jump back that many stored positions. When
9070 called several times in succession, walk through the entire ring.
9071 Org-mode commands jumping to a different position in the current file,
9072 or to another Org-mode file, automatically push the old position
9073 onto the ring."
9074 (interactive "p")
9075 (let (p m)
9076 (if (eq last-command this-command)
9077 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
9078 (setq p org-mark-ring))
9079 (setq org-mark-ring-last-goto p)
9080 (setq m (car p))
9081 (switch-to-buffer (marker-buffer m))
9082 (goto-char m)
9083 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
9084
9085 (defun org-remove-angle-brackets (s)
9086 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
9087 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
9088 s)
9089 (defun org-add-angle-brackets (s)
9090 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
9091 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
9092 s)
9093 (defun org-remove-double-quotes (s)
9094 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
9095 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
9096 s)
9097
9098 ;;; Following specific links
9099
9100 (defun org-follow-timestamp-link ()
9101 (cond
9102 ((org-at-date-range-p t)
9103 (let ((org-agenda-start-on-weekday)
9104 (t1 (match-string 1))
9105 (t2 (match-string 2)))
9106 (setq t1 (time-to-days (org-time-string-to-time t1))
9107 t2 (time-to-days (org-time-string-to-time t2)))
9108 (org-agenda-list nil t1 (1+ (- t2 t1)))))
9109 ((org-at-timestamp-p t)
9110 (org-agenda-list nil (time-to-days (org-time-string-to-time
9111 (substring (match-string 1) 0 10)))
9112 1))
9113 (t (error "This should not happen"))))
9114
9115
9116 ;;; Following file links
9117 (defvar org-wait nil)
9118 (defun org-open-file (path &optional in-emacs line search)
9119 "Open the file at PATH.
9120 First, this expands any special file name abbreviations. Then the
9121 configuration variable `org-file-apps' is checked if it contains an
9122 entry for this file type, and if yes, the corresponding command is launched.
9123
9124 If no application is found, Emacs simply visits the file.
9125
9126 With optional prefix argument IN-EMACS, Emacs will visit the file.
9127 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
9128 and to use an external application to visit the file.
9129
9130 Optional LINE specifies a line to go to, optional SEARCH a string to
9131 search for. If LINE or SEARCH is given, but IN-EMACS is nil, it will
9132 be assumed that org-open-file was called to open a file: link, and the
9133 original link to match against org-file-apps will be reconstructed
9134 from PATH and whichever of LINE or SEARCH is given.
9135
9136 If the file does not exist, an error is thrown."
9137 (let* ((file (if (equal path "")
9138 buffer-file-name
9139 (substitute-in-file-name (expand-file-name path))))
9140 (apps (append org-file-apps (org-default-apps)))
9141 (remp (and (assq 'remote apps) (org-file-remote-p file)))
9142 (dirp (if remp nil (file-directory-p file)))
9143 (file (if (and dirp org-open-directory-means-index-dot-org)
9144 (concat (file-name-as-directory file) "index.org")
9145 file))
9146 (a-m-a-p (assq 'auto-mode apps))
9147 (dfile (downcase file))
9148 ;; reconstruct the original file: link from the PATH, LINE and SEARCH args
9149 (link (cond ((and (eq line nil)
9150 (eq search nil))
9151 file)
9152 (line
9153 (concat file "::" (number-to-string line)))
9154 (search
9155 (concat file "::" search))))
9156 (dlink (downcase link))
9157 (old-buffer (current-buffer))
9158 (old-pos (point))
9159 (old-mode major-mode)
9160 ext cmd link-match-data)
9161 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
9162 (setq ext (match-string 1 dfile))
9163 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
9164 (setq ext (match-string 1 dfile))))
9165 (cond
9166 ((member in-emacs '((16) system))
9167 (setq cmd (cdr (assoc 'system apps))))
9168 (in-emacs (setq cmd 'emacs))
9169 (t
9170 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
9171 (and dirp (cdr (assoc 'directory apps)))
9172 ;; if we find a match in org-file-apps, store the match
9173 ;; data for later
9174 (let* ((re-list1 (org-apps-regexp-alist apps nil))
9175 (re-list2
9176 (if a-m-a-p
9177 (org-apps-regexp-alist apps a-m-a-p)
9178 re-list1))
9179 (private-match
9180 (assoc-default dlink re-list1 'string-match))
9181 (general-match
9182 (assoc-default dfile re-list2 'string-match)))
9183 (if private-match
9184 (progn (setq link-match-data (match-data))
9185 private-match)
9186 general-match))
9187 (cdr (assoc ext apps))
9188 (cdr (assoc t apps))))))
9189 (when (eq cmd 'system)
9190 (setq cmd (cdr (assoc 'system apps))))
9191 (when (eq cmd 'default)
9192 (setq cmd (cdr (assoc t apps))))
9193 (when (eq cmd 'mailcap)
9194 (require 'mailcap)
9195 (mailcap-parse-mailcaps)
9196 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
9197 (command (mailcap-mime-info mime-type)))
9198 (if (stringp command)
9199 (setq cmd command)
9200 (setq cmd 'emacs))))
9201 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
9202 (not (file-exists-p file))
9203 (not org-open-non-existing-files))
9204 (error "No such file: %s" file))
9205 (cond
9206 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
9207 ;; Remove quotes around the file name - we'll use shell-quote-argument.
9208 (while (string-match "['\"]%s['\"]" cmd)
9209 (setq cmd (replace-match "%s" t t cmd)))
9210 (while (string-match "%s" cmd)
9211 (setq cmd (replace-match
9212 (save-match-data
9213 (shell-quote-argument
9214 (convert-standard-filename file)))
9215 t t cmd)))
9216 ;; Replace "%1", "%2" etc. in command with group matches from regex
9217 (save-match-data
9218 (let ((match-index 1)
9219 (number-of-groups (- (/ (length link-match-data) 2) 1)))
9220 (set-match-data link-match-data)
9221 (while (<= match-index number-of-groups)
9222 (let ((regex (concat "%" (number-to-string match-index)))
9223 (replace-with (match-string match-index dlink)))
9224 (while (string-match regex cmd)
9225 (setq cmd (replace-match replace-with t t cmd))))
9226 (setq match-index (+ match-index 1)))))
9227
9228 (save-window-excursion
9229 (start-process-shell-command cmd nil cmd)
9230 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
9231 ))
9232 ((or (stringp cmd)
9233 (eq cmd 'emacs))
9234 (funcall (cdr (assq 'file org-link-frame-setup)) file)
9235 (widen)
9236 (if line (org-goto-line line)
9237 (if search (org-link-search search))))
9238 ((consp cmd)
9239 (let ((file (convert-standard-filename file)))
9240 (save-match-data
9241 (set-match-data link-match-data)
9242 (eval cmd))))
9243 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
9244 (and (org-mode-p) (eq old-mode 'org-mode)
9245 (or (not (equal old-buffer (current-buffer)))
9246 (not (equal old-pos (point))))
9247 (org-mark-ring-push old-pos old-buffer))))
9248
9249 (defun org-default-apps ()
9250 "Return the default applications for this operating system."
9251 (cond
9252 ((eq system-type 'darwin)
9253 org-file-apps-defaults-macosx)
9254 ((eq system-type 'windows-nt)
9255 org-file-apps-defaults-windowsnt)
9256 (t org-file-apps-defaults-gnu)))
9257
9258 (defun org-apps-regexp-alist (list &optional add-auto-mode)
9259 "Convert extensions to regular expressions in the cars of LIST.
9260 Also, weed out any non-string entries, because the return value is used
9261 only for regexp matching.
9262 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
9263 point to the symbol `emacs', indicating that the file should
9264 be opened in Emacs."
9265 (append
9266 (delq nil
9267 (mapcar (lambda (x)
9268 (if (not (stringp (car x)))
9269 nil
9270 (if (string-match "\\W" (car x))
9271 x
9272 (cons (concat "\\." (car x) "\\(::.*\\)?\\'")
9273 (cdr x)))))
9274 list))
9275 (if add-auto-mode
9276 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
9277
9278 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
9279 (defun org-file-remote-p (file)
9280 "Test whether FILE specifies a location on a remote system.
9281 Return non-nil if the location is indeed remote.
9282
9283 For example, the filename \"/user@host:/foo\" specifies a location
9284 on the system \"/user@host:\"."
9285 (cond ((fboundp 'file-remote-p)
9286 (file-remote-p file))
9287 ((fboundp 'tramp-handle-file-remote-p)
9288 (tramp-handle-file-remote-p file))
9289 ((and (boundp 'ange-ftp-name-format)
9290 (string-match (car ange-ftp-name-format) file))
9291 t)
9292 (t nil)))
9293
9294
9295 ;;;; Refiling
9296
9297 (defun org-get-org-file ()
9298 "Read a filename, with default directory `org-directory'."
9299 (let ((default (or org-default-notes-file remember-data-file)))
9300 (read-file-name (format "File name [%s]: " default)
9301 (file-name-as-directory org-directory)
9302 default)))
9303
9304 (defun org-notes-order-reversed-p ()
9305 "Check if the current file should receive notes in reversed order."
9306 (cond
9307 ((not org-reverse-note-order) nil)
9308 ((eq t org-reverse-note-order) t)
9309 ((not (listp org-reverse-note-order)) nil)
9310 (t (catch 'exit
9311 (let ((all org-reverse-note-order)
9312 entry)
9313 (while (setq entry (pop all))
9314 (if (string-match (car entry) buffer-file-name)
9315 (throw 'exit (cdr entry))))
9316 nil)))))
9317
9318 (defvar org-refile-target-table nil
9319 "The list of refile targets, created by `org-refile'.")
9320
9321 (defvar org-agenda-new-buffers nil
9322 "Buffers created to visit agenda files.")
9323
9324 (defun org-get-refile-targets (&optional default-buffer)
9325 "Produce a table with refile targets."
9326 (let ((case-fold-search nil)
9327 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
9328 (entries (or org-refile-targets '((nil . (:level . 1)))))
9329 targets txt re files f desc descre fast-path-p level pos0)
9330 (message "Getting targets...")
9331 (with-current-buffer (or default-buffer (current-buffer))
9332 (while (setq entry (pop entries))
9333 (setq files (car entry) desc (cdr entry))
9334 (setq fast-path-p nil)
9335 (cond
9336 ((null files) (setq files (list (current-buffer))))
9337 ((eq files 'org-agenda-files)
9338 (setq files (org-agenda-files 'unrestricted)))
9339 ((and (symbolp files) (fboundp files))
9340 (setq files (funcall files)))
9341 ((and (symbolp files) (boundp files))
9342 (setq files (symbol-value files))))
9343 (if (stringp files) (setq files (list files)))
9344 (cond
9345 ((eq (car desc) :tag)
9346 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
9347 ((eq (car desc) :todo)
9348 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
9349 ((eq (car desc) :regexp)
9350 (setq descre (cdr desc)))
9351 ((eq (car desc) :level)
9352 (setq descre (concat "^\\*\\{" (number-to-string
9353 (if org-odd-levels-only
9354 (1- (* 2 (cdr desc)))
9355 (cdr desc)))
9356 "\\}[ \t]")))
9357 ((eq (car desc) :maxlevel)
9358 (setq fast-path-p t)
9359 (setq descre (concat "^\\*\\{1," (number-to-string
9360 (if org-odd-levels-only
9361 (1- (* 2 (cdr desc)))
9362 (cdr desc)))
9363 "\\}[ \t]")))
9364 (t (error "Bad refiling target description %s" desc)))
9365 (while (setq f (pop files))
9366 (with-current-buffer
9367 (if (bufferp f) f (org-get-agenda-file-buffer f))
9368 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
9369 (setq f (and f (expand-file-name f)))
9370 (if (eq org-refile-use-outline-path 'file)
9371 (push (list (file-name-nondirectory f) f nil nil) targets))
9372 (save-excursion
9373 (save-restriction
9374 (widen)
9375 (goto-char (point-min))
9376 (while (re-search-forward descre nil t)
9377 (goto-char (setq pos0 (point-at-bol)))
9378 (catch 'next
9379 (when org-refile-target-verify-function
9380 (save-match-data
9381 (or (funcall org-refile-target-verify-function)
9382 (throw 'next t))))
9383 (when (looking-at org-complex-heading-regexp)
9384 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
9385 txt (org-link-display-format (match-string 4))
9386 re (concat "^" (regexp-quote
9387 (buffer-substring (match-beginning 1)
9388 (match-end 4)))))
9389 (if (match-end 5) (setq re (concat re "[ \t]+"
9390 (regexp-quote
9391 (match-string 5)))))
9392 (setq re (concat re "[ \t]*$"))
9393 (when org-refile-use-outline-path
9394 (setq txt (mapconcat 'org-protect-slash
9395 (append
9396 (if (eq org-refile-use-outline-path 'file)
9397 (list (file-name-nondirectory
9398 (buffer-file-name (buffer-base-buffer))))
9399 (if (eq org-refile-use-outline-path 'full-file-path)
9400 (list (buffer-file-name (buffer-base-buffer)))))
9401 (org-get-outline-path fast-path-p level txt)
9402 (list txt))
9403 "/")))
9404 (push (list txt f re (point)) targets)))
9405 (when (= (point) pos0)
9406 ;; verification function has not moved point
9407 (goto-char (point-at-eol))))))))))
9408 (message "Getting targets...done")
9409 (nreverse targets)))
9410
9411 (defun org-protect-slash (s)
9412 (while (string-match "/" s)
9413 (setq s (replace-match "\\" t t s)))
9414 s)
9415
9416 (defvar org-olpa (make-vector 20 nil))
9417
9418 (defun org-get-outline-path (&optional fastp level heading)
9419 "Return the outline path to the current entry, as a list.
9420 The parameters FASTP, LEVEL, and HEADING are for use be a scanner
9421 routine which makes outline path derivations for an entire file,
9422 avoiding backtracing."
9423 (if fastp
9424 (progn
9425 (if (> level 19)
9426 (error "Outline path failure, more than 19 levels."))
9427 (loop for i from level upto 19 do
9428 (aset org-olpa i nil))
9429 (prog1
9430 (delq nil (append org-olpa nil))
9431 (aset org-olpa level heading)))
9432 (let (rtn case-fold-search)
9433 (save-excursion
9434 (save-restriction
9435 (widen)
9436 (while (org-up-heading-safe)
9437 (when (looking-at org-complex-heading-regexp)
9438 (push (org-match-string-no-properties 4) rtn)))
9439 rtn)))))
9440
9441 (defun org-format-outline-path (path &optional width prefix)
9442 "Format the outlie path PATH for display.
9443 Width is the maximum number of characters that is available.
9444 Prefix is a prefix to be included in the returned string,
9445 such as the file name."
9446 (setq width (or width 79))
9447 (if prefix (setq width (- width (length prefix))))
9448 (if (not path)
9449 (or prefix "")
9450 (let* ((nsteps (length path))
9451 (total-width (+ nsteps (apply '+ (mapcar 'length path))))
9452 (maxwidth (if (<= total-width width)
9453 10000 ;; everything fits
9454 ;; we need to shorten the level headings
9455 (/ (- width nsteps) nsteps)))
9456 (org-odd-levels-only nil)
9457 (n 0)
9458 (total (1+ (length prefix))))
9459 (setq maxwidth (max maxwidth 10))
9460 (concat prefix
9461 (mapconcat
9462 (lambda (h)
9463 (setq n (1+ n))
9464 (if (and (= n nsteps) (< maxwidth 10000))
9465 (setq maxwidth (- total-width total)))
9466 (if (< (length h) maxwidth)
9467 (progn (setq total (+ total (length h) 1)) h)
9468 (setq h (substring h 0 (- maxwidth 2))
9469 total (+ total maxwidth 1))
9470 (if (string-match "[ \t]+\\'" h)
9471 (setq h (substring h 0 (match-beginning 0))))
9472 (setq h (concat h "..")))
9473 (org-add-props h nil 'face
9474 (nth (% (1- n) org-n-level-faces)
9475 org-level-faces))
9476 h)
9477 path "/")))))
9478
9479 (defun org-display-outline-path (&optional file current)
9480 "Display the current outline path in the echo area."
9481 (interactive "P")
9482 (let* ((bfn (buffer-file-name (buffer-base-buffer)))
9483 (case-fold-search nil)
9484 (path (and (org-mode-p) (org-get-outline-path))))
9485 (if current (setq path (append path
9486 (save-excursion
9487 (org-back-to-heading t)
9488 (if (looking-at org-complex-heading-regexp)
9489 (list (match-string 4)))))))
9490 (message "%s"
9491 (org-format-outline-path
9492 path
9493 (1- (frame-width))
9494 (and file bfn (concat (file-name-nondirectory bfn) "/"))))))
9495
9496 (defvar org-refile-history nil
9497 "History for refiling operations.")
9498
9499 (defvar org-after-refile-insert-hook nil
9500 "Hook run after `org-refile' has inserted its stuff at the new location.
9501 Note that this is still *before* the stuff will be removed from
9502 the *old* location.")
9503
9504 (defun org-refile (&optional goto default-buffer rfloc)
9505 "Move the entry at point to another heading.
9506 The list of target headings is compiled using the information in
9507 `org-refile-targets', which see. This list is created before each use
9508 and will therefore always be up-to-date.
9509
9510 At the target location, the entry is filed as a subitem of the target heading.
9511 Depending on `org-reverse-note-order', the new subitem will either be the
9512 first or the last subitem.
9513
9514 If there is an active region, all entries in that region will be moved.
9515 However, the region must fulfil the requirement that the first heading
9516 is the first one sets the top-level of the moved text - at most siblings
9517 below it are allowed.
9518
9519 With prefix arg GOTO, the command will only visit the target location,
9520 not actually move anything.
9521 With a double prefix `C-u C-u', go to the location where the last refiling
9522 operation has put the subtree.
9523 With a prefix argument of `2', refile to the running clock.
9524
9525 RFLOC can be a refile location obtained in a different way.
9526
9527 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
9528 (interactive "P")
9529 (let* ((cbuf (current-buffer))
9530 (regionp (org-region-active-p))
9531 (region-start (and regionp (region-beginning)))
9532 (region-end (and regionp (region-end)))
9533 (region-length (and regionp (- region-end region-start)))
9534 (filename (buffer-file-name (buffer-base-buffer cbuf)))
9535 pos it nbuf file re level reversed)
9536 (setq last-command nil)
9537 (when regionp
9538 (goto-char region-start)
9539 (or (bolp) (goto-char (point-at-bol)))
9540 (setq region-start (point))
9541 (unless (org-kill-is-subtree-p
9542 (buffer-substring region-start region-end))
9543 (error "The region is not a (sequence of) subtree(s)")))
9544 (if (equal goto '(16))
9545 (org-refile-goto-last-stored)
9546 (when (or
9547 (and (equal goto 2)
9548 org-clock-hd-marker (marker-buffer org-clock-hd-marker)
9549 (prog1
9550 (setq it (list (or org-clock-heading "running clock")
9551 (buffer-file-name
9552 (marker-buffer org-clock-hd-marker))
9553 ""
9554 (marker-position org-clock-hd-marker)))
9555 (setq goto nil)))
9556 (setq it (or rfloc
9557 (save-excursion
9558 (org-refile-get-location
9559 (if goto "Goto: " "Refile to: ") default-buffer
9560 org-refile-allow-creating-parent-nodes)))))
9561 (setq file (nth 1 it)
9562 re (nth 2 it)
9563 pos (nth 3 it))
9564 (if (and (not goto)
9565 pos
9566 (equal (buffer-file-name) file)
9567 (if regionp
9568 (and (>= pos region-start)
9569 (<= pos region-end))
9570 (and (>= pos (point))
9571 (< pos (save-excursion
9572 (org-end-of-subtree t t))))))
9573 (error "Cannot refile to position inside the tree or region"))
9574
9575 (setq nbuf (or (find-buffer-visiting file)
9576 (find-file-noselect file)))
9577 (if goto
9578 (progn
9579 (switch-to-buffer nbuf)
9580 (goto-char pos)
9581 (org-show-context 'org-goto))
9582 (if regionp
9583 (progn
9584 (org-kill-new (buffer-substring region-start region-end))
9585 (org-save-markers-in-region region-start region-end))
9586 (org-copy-subtree 1 nil t))
9587 (with-current-buffer (setq nbuf (or (find-buffer-visiting file)
9588 (find-file-noselect file)))
9589 (setq reversed (org-notes-order-reversed-p))
9590 (save-excursion
9591 (save-restriction
9592 (widen)
9593 (if pos
9594 (progn
9595 (goto-char pos)
9596 (looking-at outline-regexp)
9597 (setq level (org-get-valid-level (funcall outline-level) 1))
9598 (goto-char
9599 (if reversed
9600 (or (outline-next-heading) (point-max))
9601 (or (save-excursion (org-get-next-sibling))
9602 (org-end-of-subtree t t)
9603 (point-max)))))
9604 (setq level 1)
9605 (if (not reversed)
9606 (goto-char (point-max))
9607 (goto-char (point-min))
9608 (or (outline-next-heading) (goto-char (point-max)))))
9609 (if (not (bolp)) (newline))
9610 (org-paste-subtree level)
9611 (when org-log-refile
9612 (org-add-log-setup 'refile nil nil 'findpos
9613 org-log-refile)
9614 (unless (eq org-log-refile 'note)
9615 (save-excursion (org-add-log-note))))
9616 (and org-auto-align-tags (org-set-tags nil t))
9617 (bookmark-set "org-refile-last-stored")
9618 (if (fboundp 'deactivate-mark) (deactivate-mark))
9619 (run-hooks 'org-after-refile-insert-hook))))
9620 (if regionp
9621 (delete-region (point) (+ (point) region-length))
9622 (org-cut-subtree))
9623 (when (featurep 'org-inlinetask)
9624 (org-inlinetask-remove-END-maybe))
9625 (setq org-markers-to-move nil)
9626 (message "Refiled to \"%s\"" (car it))))))
9627 (org-reveal))
9628
9629 (defun org-refile-goto-last-stored ()
9630 "Go to the location where the last refile was stored."
9631 (interactive)
9632 (bookmark-jump "org-refile-last-stored")
9633 (message "This is the location of the last refile"))
9634
9635 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
9636 "Prompt the user for a refile location, using PROMPT."
9637 (let ((org-refile-targets org-refile-targets)
9638 (org-refile-use-outline-path org-refile-use-outline-path))
9639 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
9640 (unless org-refile-target-table
9641 (error "No refile targets"))
9642 (let* ((cbuf (current-buffer))
9643 (partial-completion-mode nil)
9644 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
9645 (cfunc (if (and org-refile-use-outline-path
9646 org-outline-path-complete-in-steps)
9647 'org-olpath-completing-read
9648 'org-icompleting-read))
9649 (extra (if org-refile-use-outline-path "/" ""))
9650 (filename (and cfn (expand-file-name cfn)))
9651 (tbl (mapcar
9652 (lambda (x)
9653 (if (and (not (member org-refile-use-outline-path
9654 '(file full-file-path)))
9655 (not (equal filename (nth 1 x))))
9656 (cons (concat (car x) extra " ("
9657 (file-name-nondirectory (nth 1 x)) ")")
9658 (cdr x))
9659 (cons (concat (car x) extra) (cdr x))))
9660 org-refile-target-table))
9661 (completion-ignore-case t)
9662 pa answ parent-target child parent old-hist)
9663 (setq old-hist org-refile-history)
9664 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
9665 nil 'org-refile-history))
9666 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
9667 (if pa
9668 (progn
9669 (when (or (not org-refile-history)
9670 (not (eq old-hist org-refile-history))
9671 (not (equal (car pa) (car org-refile-history))))
9672 (setq org-refile-history
9673 (cons (car pa) (if (assoc (car org-refile-history) tbl)
9674 org-refile-history
9675 (cdr org-refile-history))))
9676 (if (equal (car org-refile-history) (nth 1 org-refile-history))
9677 (pop org-refile-history)))
9678 pa)
9679 (if (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
9680 (progn
9681 (setq parent (match-string 1 answ)
9682 child (match-string 2 answ))
9683 (setq parent-target (or (assoc parent tbl)
9684 (assoc (concat parent "/") tbl)))
9685 (when (and parent-target
9686 (or (eq new-nodes t)
9687 (and (eq new-nodes 'confirm)
9688 (y-or-n-p (format "Create new node \"%s\"? "
9689 child)))))
9690 (org-refile-new-child parent-target child)))
9691 (error "Invalid target location")))))
9692
9693 (defun org-refile-new-child (parent-target child)
9694 "Use refile target PARENT-TARGET to add new CHILD below it."
9695 (unless parent-target
9696 (error "Cannot find parent for new node"))
9697 (let ((file (nth 1 parent-target))
9698 (pos (nth 3 parent-target))
9699 level)
9700 (with-current-buffer (or (find-buffer-visiting file)
9701 (find-file-noselect file))
9702 (save-excursion
9703 (save-restriction
9704 (widen)
9705 (if pos
9706 (goto-char pos)
9707 (goto-char (point-max))
9708 (if (not (bolp)) (newline)))
9709 (when (looking-at outline-regexp)
9710 (setq level (funcall outline-level))
9711 (org-end-of-subtree t t))
9712 (org-back-over-empty-lines)
9713 (insert "\n" (make-string
9714 (if pos (org-get-valid-level level 1) 1) ?*)
9715 " " child "\n")
9716 (beginning-of-line 0)
9717 (list (concat (car parent-target) "/" child) file "" (point)))))))
9718
9719 (defun org-olpath-completing-read (prompt collection &rest args)
9720 "Read an outline path like a file name."
9721 (let ((thetable collection)
9722 (org-completion-use-ido nil) ; does not work with ido.
9723 (org-completion-use-iswitchb nil)) ; or iswitchb
9724 (apply
9725 'org-icompleting-read prompt
9726 (lambda (string predicate &optional flag)
9727 (let (rtn r f (l (length string)))
9728 (cond
9729 ((eq flag nil)
9730 ;; try completion
9731 (try-completion string thetable))
9732 ((eq flag t)
9733 ;; all-completions
9734 (setq rtn (all-completions string thetable predicate))
9735 (mapcar
9736 (lambda (x)
9737 (setq r (substring x l))
9738 (if (string-match " ([^)]*)$" x)
9739 (setq f (match-string 0 x))
9740 (setq f ""))
9741 (if (string-match "/" r)
9742 (concat string (substring r 0 (match-end 0)) f)
9743 x))
9744 rtn))
9745 ((eq flag 'lambda)
9746 ;; exact match?
9747 (assoc string thetable)))
9748 ))
9749 args)))
9750
9751 ;;;; Dynamic blocks
9752
9753 (defun org-find-dblock (name)
9754 "Find the first dynamic block with name NAME in the buffer.
9755 If not found, stay at current position and return nil."
9756 (let (pos)
9757 (save-excursion
9758 (goto-char (point-min))
9759 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
9760 nil t)
9761 (match-beginning 0))))
9762 (if pos (goto-char pos))
9763 pos))
9764
9765 (defconst org-dblock-start-re
9766 "^[ \t]*#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
9767 "Matches the start line of a dynamic block, with parameters.")
9768
9769 (defconst org-dblock-end-re "^[ \t]*#\\+END\\([: \t\r\n]\\|$\\)"
9770 "Matches the end of a dynamic block.")
9771
9772 (defun org-create-dblock (plist)
9773 "Create a dynamic block section, with parameters taken from PLIST.
9774 PLIST must contain a :name entry which is used as name of the block."
9775 (when (string-match "\\S-" (buffer-substring (point-at-bol) (point-at-eol)))
9776 (end-of-line 1)
9777 (newline))
9778 (let ((col (current-column))
9779 (name (plist-get plist :name)))
9780 (insert "#+BEGIN: " name)
9781 (while plist
9782 (if (eq (car plist) :name)
9783 (setq plist (cddr plist))
9784 (insert " " (prin1-to-string (pop plist)))))
9785 (insert "\n\n" (make-string col ?\ ) "#+END:\n")
9786 (beginning-of-line -2)))
9787
9788 (defun org-prepare-dblock ()
9789 "Prepare dynamic block for refresh.
9790 This empties the block, puts the cursor at the insert position and returns
9791 the property list including an extra property :name with the block name."
9792 (unless (looking-at org-dblock-start-re)
9793 (error "Not at a dynamic block"))
9794 (let* ((begdel (1+ (match-end 0)))
9795 (name (org-no-properties (match-string 1)))
9796 (params (append (list :name name)
9797 (read (concat "(" (match-string 3) ")")))))
9798 (save-excursion
9799 (beginning-of-line 1)
9800 (skip-chars-forward " \t")
9801 (setq params (plist-put params :indentation-column (current-column))))
9802 (unless (re-search-forward org-dblock-end-re nil t)
9803 (error "Dynamic block not terminated"))
9804 (setq params
9805 (append params
9806 (list :content (buffer-substring
9807 begdel (match-beginning 0)))))
9808 (delete-region begdel (match-beginning 0))
9809 (goto-char begdel)
9810 (open-line 1)
9811 params))
9812
9813 (defun org-map-dblocks (&optional command)
9814 "Apply COMMAND to all dynamic blocks in the current buffer.
9815 If COMMAND is not given, use `org-update-dblock'."
9816 (let ((cmd (or command 'org-update-dblock)))
9817 (save-excursion
9818 (goto-char (point-min))
9819 (while (re-search-forward org-dblock-start-re nil t)
9820 (goto-char (match-beginning 0))
9821 (save-excursion
9822 (condition-case nil
9823 (funcall cmd)
9824 (error (message "Error during update of dynamic block"))))
9825 (unless (re-search-forward org-dblock-end-re nil t)
9826 (error "Dynamic block not terminated"))))))
9827
9828 (defun org-dblock-update (&optional arg)
9829 "User command for updating dynamic blocks.
9830 Update the dynamic block at point. With prefix ARG, update all dynamic
9831 blocks in the buffer."
9832 (interactive "P")
9833 (if arg
9834 (org-update-all-dblocks)
9835 (or (looking-at org-dblock-start-re)
9836 (org-beginning-of-dblock))
9837 (org-update-dblock)))
9838
9839 (defun org-update-dblock ()
9840 "Update the dynamic block at point
9841 This means to empty the block, parse for parameters and then call
9842 the correct writing function."
9843 (save-window-excursion
9844 (let* ((pos (point))
9845 (line (org-current-line))
9846 (params (org-prepare-dblock))
9847 (name (plist-get params :name))
9848 (indent (plist-get params :indentation-column))
9849 (cmd (intern (concat "org-dblock-write:" name))))
9850 (message "Updating dynamic block `%s' at line %d..." name line)
9851 (funcall cmd params)
9852 (message "Updating dynamic block `%s' at line %d...done" name line)
9853 (goto-char pos)
9854 (when (and indent (> indent 0))
9855 (setq indent (make-string indent ?\ ))
9856 (save-excursion
9857 (org-beginning-of-dblock)
9858 (forward-line 1)
9859 (while (not (looking-at org-dblock-end-re))
9860 (insert indent)
9861 (beginning-of-line 2))
9862 (when (looking-at org-dblock-end-re)
9863 (and (looking-at "[ \t]+")
9864 (replace-match ""))
9865 (insert indent)))))))
9866
9867 (defun org-beginning-of-dblock ()
9868 "Find the beginning of the dynamic block at point.
9869 Error if there is no such block at point."
9870 (let ((pos (point))
9871 beg)
9872 (end-of-line 1)
9873 (if (and (re-search-backward org-dblock-start-re nil t)
9874 (setq beg (match-beginning 0))
9875 (re-search-forward org-dblock-end-re nil t)
9876 (> (match-end 0) pos))
9877 (goto-char beg)
9878 (goto-char pos)
9879 (error "Not in a dynamic block"))))
9880
9881 (defun org-update-all-dblocks ()
9882 "Update all dynamic blocks in the buffer.
9883 This function can be used in a hook."
9884 (when (org-mode-p)
9885 (org-map-dblocks 'org-update-dblock)))
9886
9887
9888 ;;;; Completion
9889
9890 (defconst org-additional-option-like-keywords
9891 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
9892 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
9893 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:"
9894 "LATEX_CLASS:" "LATEX_CLASS_OPTIONS:" "ATTR_LaTeX"
9895 "BEGIN:" "END:"
9896 "ORGTBL" "TBLFM:" "TBLNAME:"
9897 "BEGIN_EXAMPLE" "END_EXAMPLE"
9898 "BEGIN_QUOTE" "END_QUOTE"
9899 "BEGIN_VERSE" "END_VERSE"
9900 "BEGIN_CENTER" "END_CENTER"
9901 "BEGIN_SRC" "END_SRC"
9902 "CATEGORY" "COLUMNS"
9903 "CAPTION" "LABEL"
9904 "SETUPFILE"
9905 "BIND"
9906 "MACRO"))
9907
9908 (defcustom org-structure-template-alist
9909 '(
9910 ("s" "#+begin_src ?\n\n#+end_src"
9911 "<src lang=\"?\">\n\n</src>")
9912 ("e" "#+begin_example\n?\n#+end_example"
9913 "<example>\n?\n</example>")
9914 ("q" "#+begin_quote\n?\n#+end_quote"
9915 "<quote>\n?\n</quote>")
9916 ("v" "#+begin_verse\n?\n#+end_verse"
9917 "<verse>\n?\n/verse>")
9918 ("c" "#+begin_center\n?\n#+end_center"
9919 "<center>\n?\n/center>")
9920 ("l" "#+begin_latex\n?\n#+end_latex"
9921 "<literal style=\"latex\">\n?\n</literal>")
9922 ("L" "#+latex: "
9923 "<literal style=\"latex\">?</literal>")
9924 ("h" "#+begin_html\n?\n#+end_html"
9925 "<literal style=\"html\">\n?\n</literal>")
9926 ("H" "#+html: "
9927 "<literal style=\"html\">?</literal>")
9928 ("a" "#+begin_ascii\n?\n#+end_ascii")
9929 ("A" "#+ascii: ")
9930 ("i" "#+include %file ?"
9931 "<include file=%file markup=\"?\">")
9932 )
9933 "Structure completion elements.
9934 This is a list of abbreviation keys and values. The value gets inserted
9935 it you type @samp{.} followed by the key and then the completion key,
9936 usually `M-TAB'. %file will be replaced by a file name after prompting
9937 for the file using completion.
9938 There are two templates for each key, the first uses the original Org syntax,
9939 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
9940 the default when the /org-mtags.el/ module has been loaded. See also the
9941 variable `org-mtags-prefer-muse-templates'.
9942 This is an experimental feature, it is undecided if it is going to stay in."
9943 :group 'org-completion
9944 :type '(repeat
9945 (string :tag "Key")
9946 (string :tag "Template")
9947 (string :tag "Muse Template")))
9948
9949 (defun org-try-structure-completion ()
9950 "Try to complete a structure template before point.
9951 This looks for strings like \"<e\" on an otherwise empty line and
9952 expands them."
9953 (let ((l (buffer-substring (point-at-bol) (point)))
9954 a)
9955 (when (and (looking-at "[ \t]*$")
9956 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
9957 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
9958 (org-complete-expand-structure-template (+ -1 (point-at-bol)
9959 (match-beginning 1)) a)
9960 t)))
9961
9962 (defun org-complete-expand-structure-template (start cell)
9963 "Expand a structure template."
9964 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
9965 (rpl (nth (if musep 2 1) cell))
9966 (ind ""))
9967 (delete-region start (point))
9968 (when (string-match "\\`#\\+" rpl)
9969 (cond
9970 ((bolp))
9971 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
9972 (setq ind (buffer-substring (point-at-bol) (point))))
9973 (t (newline))))
9974 (setq start (point))
9975 (if (string-match "%file" rpl)
9976 (setq rpl (replace-match
9977 (concat
9978 "\""
9979 (save-match-data
9980 (abbreviate-file-name (read-file-name "Include file: ")))
9981 "\"")
9982 t t rpl)))
9983 (setq rpl (mapconcat 'identity (split-string rpl "\n")
9984 (concat "\n" ind)))
9985 (insert rpl)
9986 (if (re-search-backward "\\?" start t) (delete-char 1))))
9987
9988
9989 (defun org-complete (&optional arg)
9990 "Perform completion on word at point.
9991 At the beginning of a headline, this completes TODO keywords as given in
9992 `org-todo-keywords'.
9993 If the current word is preceded by a backslash, completes the TeX symbols
9994 that are supported for HTML support.
9995 If the current word is preceded by \"#+\", completes special words for
9996 setting file options.
9997 In the line after \"#+STARTUP:, complete valid keywords.\"
9998 At all other locations, this simply calls the value of
9999 `org-completion-fallback-command'."
10000 (interactive "P")
10001 (org-without-partial-completion
10002 (catch 'exit
10003 (let* ((a nil)
10004 (end (point))
10005 (beg1 (save-excursion
10006 (skip-chars-backward (org-re "[:alnum:]_@"))
10007 (point)))
10008 (beg (save-excursion
10009 (skip-chars-backward "a-zA-Z0-9_:$")
10010 (point)))
10011 (confirm (lambda (x) (stringp (car x))))
10012 (searchhead (equal (char-before beg) ?*))
10013 (struct
10014 (when (and (member (char-before beg1) '(?. ?<))
10015 (setq a (assoc (buffer-substring beg1 (point))
10016 org-structure-template-alist)))
10017 (org-complete-expand-structure-template (1- beg1) a)
10018 (throw 'exit t)))
10019 (tag (and (equal (char-before beg1) ?:)
10020 (equal (char-after (point-at-bol)) ?*)))
10021 (prop (and (equal (char-before beg1) ?:)
10022 (not (equal (char-after (point-at-bol)) ?*))))
10023 (texp (equal (char-before beg) ?\\))
10024 (link (equal (char-before beg) ?\[))
10025 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
10026 beg)
10027 "#+"))
10028 (startup (string-match "^#\\+STARTUP:.*"
10029 (buffer-substring (point-at-bol) (point))))
10030 (completion-ignore-case opt)
10031 (type nil)
10032 (tbl nil)
10033 (table (cond
10034 (opt
10035 (setq type :opt)
10036 (require 'org-exp)
10037 (append
10038 (delq nil
10039 (mapcar
10040 (lambda (x)
10041 (if (string-match
10042 "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
10043 (cons (match-string 2 x)
10044 (match-string 1 x))))
10045 (org-split-string (org-get-current-options) "\n")))
10046 (mapcar 'list org-additional-option-like-keywords)))
10047 (startup
10048 (setq type :startup)
10049 org-startup-options)
10050 (link (append org-link-abbrev-alist-local
10051 org-link-abbrev-alist))
10052 (texp
10053 (setq type :tex)
10054 (append org-entities-user org-entities))
10055 ((string-match "\\`\\*+[ \t]+\\'"
10056 (buffer-substring (point-at-bol) beg))
10057 (setq type :todo)
10058 (mapcar 'list org-todo-keywords-1))
10059 (searchhead
10060 (setq type :searchhead)
10061 (save-excursion
10062 (goto-char (point-min))
10063 (while (re-search-forward org-todo-line-regexp nil t)
10064 (push (list
10065 (org-make-org-heading-search-string
10066 (match-string 3) t))
10067 tbl)))
10068 tbl)
10069 (tag (setq type :tag beg beg1)
10070 (or org-tag-alist (org-get-buffer-tags)))
10071 (prop (setq type :prop beg beg1)
10072 (mapcar 'list (org-buffer-property-keys nil t t)))
10073 (t (progn
10074 (call-interactively org-completion-fallback-command)
10075 (throw 'exit nil)))))
10076 (pattern (buffer-substring-no-properties beg end))
10077 (completion (try-completion pattern table confirm)))
10078 (cond ((eq completion t)
10079 (if (not (assoc (upcase pattern) table))
10080 (message "Already complete")
10081 (if (and (equal type :opt)
10082 (not (member (car (assoc (upcase pattern) table))
10083 org-additional-option-like-keywords)))
10084 (insert (substring (cdr (assoc (upcase pattern) table))
10085 (length pattern)))
10086 (if (memq type '(:tag :prop)) (insert ":")))))
10087 ((null completion)
10088 (message "Can't find completion for \"%s\"" pattern)
10089 (ding))
10090 ((not (string= pattern completion))
10091 (delete-region beg end)
10092 (if (string-match " +$" completion)
10093 (setq completion (replace-match "" t t completion)))
10094 (insert completion)
10095 (if (get-buffer-window "*Completions*")
10096 (delete-window (get-buffer-window "*Completions*")))
10097 (if (assoc completion table)
10098 (if (eq type :todo) (insert " ")
10099 (if (memq type '(:tag :prop)) (insert ":"))))
10100 (if (and (equal type :opt) (assoc completion table))
10101 (message "%s" (substitute-command-keys
10102 "Press \\[org-complete] again to insert example settings"))))
10103 (t
10104 (message "Making completion list...")
10105 (let ((list (sort (all-completions pattern table confirm)
10106 'string<)))
10107 (with-output-to-temp-buffer "*Completions*"
10108 (condition-case nil
10109 ;; Protection needed for XEmacs and emacs 21
10110 (display-completion-list list pattern)
10111 (error (display-completion-list list)))))
10112 (message "Making completion list...%s" "done")))))))
10113
10114 ;;;; TODO, DEADLINE, Comments
10115
10116 (defun org-toggle-comment ()
10117 "Change the COMMENT state of an entry."
10118 (interactive)
10119 (save-excursion
10120 (org-back-to-heading)
10121 (let (case-fold-search)
10122 (if (looking-at (concat outline-regexp
10123 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
10124 (replace-match "" t t nil 1)
10125 (if (looking-at outline-regexp)
10126 (progn
10127 (goto-char (match-end 0))
10128 (insert org-comment-string " ")))))))
10129
10130 (defvar org-last-todo-state-is-todo nil
10131 "This is non-nil when the last TODO state change led to a TODO state.
10132 If the last change removed the TODO tag or switched to DONE, then
10133 this is nil.")
10134
10135 (defvar org-setting-tags nil) ; dynamically skipped
10136
10137 (defun org-parse-local-options (string var)
10138 "Parse STRING for startup setting relevant for variable VAR."
10139 (let ((rtn (symbol-value var))
10140 e opts)
10141 (save-match-data
10142 (if (or (not string) (not (string-match "\\S-" string)))
10143 rtn
10144 (setq opts (delq nil (mapcar (lambda (x)
10145 (setq e (assoc x org-startup-options))
10146 (if (eq (nth 1 e) var) e nil))
10147 (org-split-string string "[ \t]+"))))
10148 (if (not opts)
10149 rtn
10150 (setq rtn nil)
10151 (while (setq e (pop opts))
10152 (if (not (nth 3 e))
10153 (setq rtn (nth 2 e))
10154 (if (not (listp rtn)) (setq rtn nil))
10155 (push (nth 2 e) rtn)))
10156 rtn)))))
10157
10158 (defvar org-todo-setup-filter-hook nil
10159 "Hook for functions that pre-filter todo specs.
10160
10161 Each function takes a todo spec and returns either `nil' or the spec
10162 transformed into canonical form." )
10163
10164 (defvar org-todo-get-default-hook nil
10165 "Hook for functions that get a default item for todo.
10166
10167 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
10168 `nil' or a string to be used for the todo mark." )
10169
10170 (defvar org-agenda-headline-snapshot-before-repeat)
10171
10172 (defun org-todo (&optional arg)
10173 "Change the TODO state of an item.
10174 The state of an item is given by a keyword at the start of the heading,
10175 like
10176 *** TODO Write paper
10177 *** DONE Call mom
10178
10179 The different keywords are specified in the variable `org-todo-keywords'.
10180 By default the available states are \"TODO\" and \"DONE\".
10181 So for this example: when the item starts with TODO, it is changed to DONE.
10182 When it starts with DONE, the DONE is removed. And when neither TODO nor
10183 DONE are present, add TODO at the beginning of the heading.
10184
10185 With C-u prefix arg, use completion to determine the new state.
10186 With numeric prefix arg, switch to that state.
10187 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
10188 With a triple C-u prefix, circumvent any state blocking.
10189
10190 For calling through lisp, arg is also interpreted in the following way:
10191 'none -> empty state
10192 \"\"(empty string) -> switch to empty state
10193 'done -> switch to DONE
10194 'nextset -> switch to the next set of keywords
10195 'previousset -> switch to the previous set of keywords
10196 \"WAITING\" -> switch to the specified keyword, but only if it
10197 really is a member of `org-todo-keywords'."
10198 (interactive "P")
10199 (if (equal arg '(16)) (setq arg 'nextset))
10200 (let ((org-blocker-hook org-blocker-hook)
10201 (case-fold-search nil))
10202 (when (equal arg '(64))
10203 (setq arg nil org-blocker-hook nil))
10204 (when (and org-blocker-hook
10205 (or org-inhibit-blocking
10206 (org-entry-get nil "NOBLOCKING")))
10207 (setq org-blocker-hook nil))
10208 (save-excursion
10209 (catch 'exit
10210 (org-back-to-heading t)
10211 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
10212 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
10213 (looking-at " *"))
10214 (let* ((match-data (match-data))
10215 (startpos (point-at-bol))
10216 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
10217 (org-log-done org-log-done)
10218 (org-log-repeat org-log-repeat)
10219 (org-todo-log-states org-todo-log-states)
10220 (this (match-string 1))
10221 (hl-pos (match-beginning 0))
10222 (head (org-get-todo-sequence-head this))
10223 (ass (assoc head org-todo-kwd-alist))
10224 (interpret (nth 1 ass))
10225 (done-word (nth 3 ass))
10226 (final-done-word (nth 4 ass))
10227 (last-state (or this ""))
10228 (completion-ignore-case t)
10229 (member (member this org-todo-keywords-1))
10230 (tail (cdr member))
10231 (state (cond
10232 ((and org-todo-key-trigger
10233 (or (and (equal arg '(4))
10234 (eq org-use-fast-todo-selection 'prefix))
10235 (and (not arg) org-use-fast-todo-selection
10236 (not (eq org-use-fast-todo-selection
10237 'prefix)))))
10238 ;; Use fast selection
10239 (org-fast-todo-selection))
10240 ((and (equal arg '(4))
10241 (or (not org-use-fast-todo-selection)
10242 (not org-todo-key-trigger)))
10243 ;; Read a state with completion
10244 (org-icompleting-read
10245 "State: " (mapcar (lambda(x) (list x))
10246 org-todo-keywords-1)
10247 nil t))
10248 ((eq arg 'right)
10249 (if this
10250 (if tail (car tail) nil)
10251 (car org-todo-keywords-1)))
10252 ((eq arg 'left)
10253 (if (equal member org-todo-keywords-1)
10254 nil
10255 (if this
10256 (nth (- (length org-todo-keywords-1)
10257 (length tail) 2)
10258 org-todo-keywords-1)
10259 (org-last org-todo-keywords-1))))
10260 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
10261 (setq arg nil))) ; hack to fall back to cycling
10262 (arg
10263 ;; user or caller requests a specific state
10264 (cond
10265 ((equal arg "") nil)
10266 ((eq arg 'none) nil)
10267 ((eq arg 'done) (or done-word (car org-done-keywords)))
10268 ((eq arg 'nextset)
10269 (or (car (cdr (member head org-todo-heads)))
10270 (car org-todo-heads)))
10271 ((eq arg 'previousset)
10272 (let ((org-todo-heads (reverse org-todo-heads)))
10273 (or (car (cdr (member head org-todo-heads)))
10274 (car org-todo-heads))))
10275 ((car (member arg org-todo-keywords-1)))
10276 ((stringp arg)
10277 (error "State `%s' not valid in this file" arg))
10278 ((nth (1- (prefix-numeric-value arg))
10279 org-todo-keywords-1))))
10280 ((null member) (or head (car org-todo-keywords-1)))
10281 ((equal this final-done-word) nil) ;; -> make empty
10282 ((null tail) nil) ;; -> first entry
10283 ((memq interpret '(type priority))
10284 (if (eq this-command last-command)
10285 (car tail)
10286 (if (> (length tail) 0)
10287 (or done-word (car org-done-keywords))
10288 nil)))
10289 (t
10290 (car tail))))
10291 (state (or
10292 (run-hook-with-args-until-success
10293 'org-todo-get-default-hook state last-state)
10294 state))
10295 (next (if state (concat " " state " ") " "))
10296 (change-plist (list :type 'todo-state-change :from this :to state
10297 :position startpos))
10298 dolog now-done-p)
10299 (when org-blocker-hook
10300 (setq org-last-todo-state-is-todo
10301 (not (member this org-done-keywords)))
10302 (unless (save-excursion
10303 (save-match-data
10304 (run-hook-with-args-until-failure
10305 'org-blocker-hook change-plist)))
10306 (if (interactive-p)
10307 (error "TODO state change from %s to %s blocked" this state)
10308 ;; fail silently
10309 (message "TODO state change from %s to %s blocked" this state)
10310 (throw 'exit nil))))
10311 (store-match-data match-data)
10312 (replace-match next t t)
10313 (unless (pos-visible-in-window-p hl-pos)
10314 (message "TODO state changed to %s" (org-trim next)))
10315 (unless head
10316 (setq head (org-get-todo-sequence-head state)
10317 ass (assoc head org-todo-kwd-alist)
10318 interpret (nth 1 ass)
10319 done-word (nth 3 ass)
10320 final-done-word (nth 4 ass)))
10321 (when (memq arg '(nextset previousset))
10322 (message "Keyword-Set %d/%d: %s"
10323 (- (length org-todo-sets) -1
10324 (length (memq (assoc state org-todo-sets) org-todo-sets)))
10325 (length org-todo-sets)
10326 (mapconcat 'identity (assoc state org-todo-sets) " ")))
10327 (setq org-last-todo-state-is-todo
10328 (not (member state org-done-keywords)))
10329 (setq now-done-p (and (member state org-done-keywords)
10330 (not (member this org-done-keywords))))
10331 (and logging (org-local-logging logging))
10332 (when (and (or org-todo-log-states org-log-done)
10333 (not (eq org-inhibit-logging t))
10334 (not (memq arg '(nextset previousset))))
10335 ;; we need to look at recording a time and note
10336 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
10337 (nth 2 (assoc this org-todo-log-states))))
10338 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
10339 (setq dolog 'time))
10340 (when (and state
10341 (member state org-not-done-keywords)
10342 (not (member this org-not-done-keywords)))
10343 ;; This is now a todo state and was not one before
10344 ;; If there was a CLOSED time stamp, get rid of it.
10345 (org-add-planning-info nil nil 'closed))
10346 (when (and now-done-p org-log-done)
10347 ;; It is now done, and it was not done before
10348 (org-add-planning-info 'closed (org-current-time))
10349 (if (and (not dolog) (eq 'note org-log-done))
10350 (org-add-log-setup 'done state this 'findpos 'note)))
10351 (when (and state dolog)
10352 ;; This is a non-nil state, and we need to log it
10353 (org-add-log-setup 'state state this 'findpos dolog)))
10354 ;; Fixup tag positioning
10355 (org-todo-trigger-tag-changes state)
10356 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
10357 (when org-provide-todo-statistics
10358 (org-update-parent-todo-statistics))
10359 (run-hooks 'org-after-todo-state-change-hook)
10360 (if (and arg (not (member state org-done-keywords)))
10361 (setq head (org-get-todo-sequence-head state)))
10362 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
10363 ;; Do we need to trigger a repeat?
10364 (when now-done-p
10365 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
10366 ;; This is for the agenda, take a snapshot of the headline.
10367 (save-match-data
10368 (setq org-agenda-headline-snapshot-before-repeat
10369 (org-get-heading))))
10370 (org-auto-repeat-maybe state))
10371 ;; Fixup cursor location if close to the keyword
10372 (if (and (outline-on-heading-p)
10373 (not (bolp))
10374 (save-excursion (beginning-of-line 1)
10375 (looking-at org-todo-line-regexp))
10376 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
10377 (progn
10378 (goto-char (or (match-end 2) (match-end 1)))
10379 (and (looking-at " ") (just-one-space))))
10380 (when org-trigger-hook
10381 (save-excursion
10382 (run-hook-with-args 'org-trigger-hook change-plist))))))))
10383
10384 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
10385 "Block turning an entry into a TODO, using the hierarchy.
10386 This checks whether the current task should be blocked from state
10387 changes. Such blocking occurs when:
10388
10389 1. The task has children which are not all in a completed state.
10390
10391 2. A task has a parent with the property :ORDERED:, and there
10392 are siblings prior to the current task with incomplete
10393 status.
10394
10395 3. The parent of the task is blocked because it has siblings that should
10396 be done first, or is child of a block grandparent TODO entry."
10397
10398 (if (not org-enforce-todo-dependencies)
10399 t ; if locally turned off don't block
10400 (catch 'dont-block
10401 ;; If this is not a todo state change, or if this entry is already DONE,
10402 ;; do not block
10403 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10404 (member (plist-get change-plist :from)
10405 (cons 'done org-done-keywords))
10406 (member (plist-get change-plist :to)
10407 (cons 'todo org-not-done-keywords))
10408 (not (plist-get change-plist :to)))
10409 (throw 'dont-block t))
10410 ;; If this task has children, and any are undone, it's blocked
10411 (save-excursion
10412 (org-back-to-heading t)
10413 (let ((this-level (funcall outline-level)))
10414 (outline-next-heading)
10415 (let ((child-level (funcall outline-level)))
10416 (while (and (not (eobp))
10417 (> child-level this-level))
10418 ;; this todo has children, check whether they are all
10419 ;; completed
10420 (if (and (not (org-entry-is-done-p))
10421 (org-entry-is-todo-p))
10422 (throw 'dont-block nil))
10423 (outline-next-heading)
10424 (setq child-level (funcall outline-level))))))
10425 ;; Otherwise, if the task's parent has the :ORDERED: property, and
10426 ;; any previous siblings are undone, it's blocked
10427 (save-excursion
10428 (org-back-to-heading t)
10429 (let* ((pos (point))
10430 (parent-pos (and (org-up-heading-safe) (point))))
10431 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10432 (when (and (org-entry-get (point) "ORDERED")
10433 (forward-line 1)
10434 (re-search-forward org-not-done-heading-regexp pos t))
10435 (throw 'dont-block nil)) ; block, there is an older sibling not done.
10436 ;; Search further up the hierarchy, to see if an anchestor is blocked
10437 (while t
10438 (goto-char parent-pos)
10439 (if (not (looking-at org-not-done-heading-regexp))
10440 (throw 'dont-block t)) ; do not block, parent is not a TODO
10441 (setq pos (point))
10442 (setq parent-pos (and (org-up-heading-safe) (point)))
10443 (if (not parent-pos) (throw 'dont-block t)) ; no parent
10444 (when (and (org-entry-get (point) "ORDERED")
10445 (forward-line 1)
10446 (re-search-forward org-not-done-heading-regexp pos t))
10447 (throw 'dont-block nil)))))))) ; block, older sibling not done.
10448
10449 (defcustom org-track-ordered-property-with-tag nil
10450 "Should the ORDERED property also be shown as a tag?
10451 The ORDERED property decides if an entry should require subtasks to be
10452 completed in sequence. Since a property is not very visible, setting
10453 this option means that toggling the ORDERED property with the command
10454 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
10455 not relevant for the behavior, but it makes things more visible.
10456
10457 Note that toggling the tag with tags commands will not change the property
10458 and therefore not influence behavior!
10459
10460 This can be t, meaning the tag ORDERED should be used, It can also be a
10461 string to select a different tag for this task."
10462 :group 'org-todo
10463 :type '(choice
10464 (const :tag "No tracking" nil)
10465 (const :tag "Track with ORDERED tag" t)
10466 (string :tag "Use other tag")))
10467
10468 (defun org-toggle-ordered-property ()
10469 "Toggle the ORDERED property of the current entry.
10470 For better visibility, you can track the value of this property with a tag.
10471 See variable `org-track-ordered-property-with-tag'."
10472 (interactive)
10473 (let* ((t1 org-track-ordered-property-with-tag)
10474 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
10475 (save-excursion
10476 (org-back-to-heading)
10477 (if (org-entry-get nil "ORDERED")
10478 (progn
10479 (org-delete-property "ORDERED")
10480 (and tag (org-toggle-tag tag 'off))
10481 (message "Subtasks can be completed in arbitrary order"))
10482 (org-entry-put nil "ORDERED" "t")
10483 (and tag (org-toggle-tag tag 'on))
10484 (message "Subtasks must be completed in sequence")))))
10485
10486 (defvar org-blocked-by-checkboxes) ; dynamically scoped
10487 (defun org-block-todo-from-checkboxes (change-plist)
10488 "Block turning an entry into a TODO, using checkboxes.
10489 This checks whether the current task should be blocked from state
10490 changes because there are unchecked boxes in this entry."
10491 (if (not org-enforce-todo-checkbox-dependencies)
10492 t ; if locally turned off don't block
10493 (catch 'dont-block
10494 ;; If this is not a todo state change, or if this entry is already DONE,
10495 ;; do not block
10496 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
10497 (member (plist-get change-plist :from)
10498 (cons 'done org-done-keywords))
10499 (member (plist-get change-plist :to)
10500 (cons 'todo org-not-done-keywords))
10501 (not (plist-get change-plist :to)))
10502 (throw 'dont-block t))
10503 ;; If this task has checkboxes that are not checked, it's blocked
10504 (save-excursion
10505 (org-back-to-heading t)
10506 (let ((beg (point)) end)
10507 (outline-next-heading)
10508 (setq end (point))
10509 (goto-char beg)
10510 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
10511 end t)
10512 (progn
10513 (if (boundp 'org-blocked-by-checkboxes)
10514 (setq org-blocked-by-checkboxes t))
10515 (throw 'dont-block nil)))))
10516 t))) ; do not block
10517
10518 (defun org-entry-blocked-p ()
10519 "Is the current entry blocked?"
10520 (if (org-entry-get nil "NOBLOCKING")
10521 nil ;; Never block this entry
10522 (not
10523 (run-hook-with-args-until-failure
10524 'org-blocker-hook
10525 (list :type 'todo-state-change
10526 :position (point)
10527 :from 'todo
10528 :to 'done)))))
10529
10530 (defun org-update-statistics-cookies (all)
10531 "Update the statistics cookie, either from TODO or from checkboxes.
10532 This should be called with the cursor in a line with a statistics cookie."
10533 (interactive "P")
10534 (if all
10535 (progn
10536 (org-update-checkbox-count 'all)
10537 (org-map-entries 'org-update-parent-todo-statistics))
10538 (if (not (org-on-heading-p))
10539 (org-update-checkbox-count)
10540 (let ((pos (move-marker (make-marker) (point)))
10541 end l1 l2)
10542 (ignore-errors (org-back-to-heading t))
10543 (if (not (org-on-heading-p))
10544 (org-update-checkbox-count)
10545 (setq l1 (org-outline-level))
10546 (setq end (save-excursion
10547 (outline-next-heading)
10548 (if (org-on-heading-p) (setq l2 (org-outline-level)))
10549 (point)))
10550 (if (and (save-excursion
10551 (re-search-forward
10552 "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) \\[[- X]\\]" end t))
10553 (not (save-excursion (re-search-forward
10554 ":COOKIE_DATA:.*\\<todo\\>" end t))))
10555 (org-update-checkbox-count)
10556 (if (and l2 (> l2 l1))
10557 (progn
10558 (goto-char end)
10559 (org-update-parent-todo-statistics))
10560 (goto-char pos)
10561 (beginning-of-line 1)
10562 (while (re-search-forward
10563 "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)"
10564 (point-at-eol) t)
10565 (replace-match (if (match-end 2) "[100%]" "[0/0]") t t)))))
10566 (goto-char pos)
10567 (move-marker pos nil)))))
10568
10569 (defvar org-entry-property-inherited-from) ;; defined below
10570 (defun org-update-parent-todo-statistics ()
10571 "Update any statistics cookie in the parent of the current headline.
10572 When `org-hierarchical-todo-statistics' is nil, statistics will cover
10573 the entire subtree and this will travel up the hierarchy and update
10574 statistics everywhere."
10575 (interactive)
10576 (let* ((lim 0) prop
10577 (recursive (or (not org-hierarchical-todo-statistics)
10578 (string-match
10579 "\\<recursive\\>"
10580 (or (setq prop (org-entry-get
10581 nil "COOKIE_DATA" 'inherit)) ""))))
10582 (lim (or (and prop (marker-position
10583 org-entry-property-inherited-from))
10584 lim))
10585 (first t)
10586 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
10587 level ltoggle l1 new ndel
10588 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
10589 (catch 'exit
10590 (save-excursion
10591 (beginning-of-line 1)
10592 (if (org-at-heading-p)
10593 (setq ltoggle (funcall outline-level))
10594 (error "This should not happen"))
10595 (while (and (setq level (org-up-heading-safe))
10596 (or recursive first)
10597 (>= (point) lim))
10598 (setq first nil cookie-present nil)
10599 (unless (and level
10600 (not (string-match
10601 "\\<checkbox\\>"
10602 (downcase
10603 (or (org-entry-get
10604 nil "COOKIE_DATA")
10605 "")))))
10606 (throw 'exit nil))
10607 (while (re-search-forward box-re (point-at-eol) t)
10608 (setq cnt-all 0 cnt-done 0 cookie-present t)
10609 (setq is-percent (match-end 2))
10610 (save-match-data
10611 (unless (outline-next-heading) (throw 'exit nil))
10612 (while (and (looking-at org-complex-heading-regexp)
10613 (> (setq l1 (length (match-string 1))) level))
10614 (setq kwd (and (or recursive (= l1 ltoggle))
10615 (match-string 2)))
10616 (if (or (eq org-provide-todo-statistics 'all-headlines)
10617 (and (listp org-provide-todo-statistics)
10618 (or (member kwd org-provide-todo-statistics)
10619 (member kwd org-done-keywords))))
10620 (setq cnt-all (1+ cnt-all))
10621 (if (eq org-provide-todo-statistics t)
10622 (and kwd (setq cnt-all (1+ cnt-all)))))
10623 (and (member kwd org-done-keywords)
10624 (setq cnt-done (1+ cnt-done)))
10625 (outline-next-heading)))
10626 (setq new
10627 (if is-percent
10628 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
10629 (format "[%d/%d]" cnt-done cnt-all))
10630 ndel (- (match-end 0) (match-beginning 0)))
10631 (goto-char (match-beginning 0))
10632 (insert new)
10633 (delete-region (point) (+ (point) ndel)))
10634 (when cookie-present
10635 (run-hook-with-args 'org-after-todo-statistics-hook
10636 cnt-done (- cnt-all cnt-done))))))
10637 (run-hooks 'org-todo-statistics-hook)))
10638
10639 (defvar org-after-todo-statistics-hook nil
10640 "Hook that is called after a TODO statistics cookie has been updated.
10641 Each function is called with two arguments: the number of not-done entries
10642 and the number of done entries.
10643
10644 For example, the following function, when added to this hook, will switch
10645 an entry to DONE when all children are done, and back to TODO when new
10646 entries are set to a TODO status. Note that this hook is only called
10647 when there is a statistics cookie in the headline!
10648
10649 (defun org-summary-todo (n-done n-not-done)
10650 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
10651 (let (org-log-done org-log-states) ; turn off logging
10652 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
10653 ")
10654
10655 (defvar org-todo-statistics-hook nil
10656 "Hook that is run whenever Org thinks TODO statistics should be updated.
10657 This hook runs even if there is no statistics cookie present, in which case
10658 `org-after-todo-statistics-hook' would not run.")
10659
10660 (defun org-todo-trigger-tag-changes (state)
10661 "Apply the changes defined in `org-todo-state-tags-triggers'."
10662 (let ((l org-todo-state-tags-triggers)
10663 changes)
10664 (when (or (not state) (equal state ""))
10665 (setq changes (append changes (cdr (assoc "" l)))))
10666 (when (and (stringp state) (> (length state) 0))
10667 (setq changes (append changes (cdr (assoc state l)))))
10668 (when (member state org-not-done-keywords)
10669 (setq changes (append changes (cdr (assoc 'todo l)))))
10670 (when (member state org-done-keywords)
10671 (setq changes (append changes (cdr (assoc 'done l)))))
10672 (dolist (c changes)
10673 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
10674
10675 (defun org-local-logging (value)
10676 "Get logging settings from a property VALUE."
10677 (let* (words w a)
10678 ;; directly set the variables, they are already local.
10679 (setq org-log-done nil
10680 org-log-repeat nil
10681 org-todo-log-states nil)
10682 (setq words (org-split-string value))
10683 (while (setq w (pop words))
10684 (cond
10685 ((setq a (assoc w org-startup-options))
10686 (and (member (nth 1 a) '(org-log-done org-log-repeat))
10687 (set (nth 1 a) (nth 2 a))))
10688 ((setq a (org-extract-log-state-settings w))
10689 (and (member (car a) org-todo-keywords-1)
10690 (push a org-todo-log-states)))))))
10691
10692 (defun org-get-todo-sequence-head (kwd)
10693 "Return the head of the TODO sequence to which KWD belongs.
10694 If KWD is not set, check if there is a text property remembering the
10695 right sequence."
10696 (let (p)
10697 (cond
10698 ((not kwd)
10699 (or (get-text-property (point-at-bol) 'org-todo-head)
10700 (progn
10701 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
10702 nil (point-at-eol)))
10703 (get-text-property p 'org-todo-head))))
10704 ((not (member kwd org-todo-keywords-1))
10705 (car org-todo-keywords-1))
10706 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
10707
10708 (defun org-fast-todo-selection ()
10709 "Fast TODO keyword selection with single keys.
10710 Returns the new TODO keyword, or nil if no state change should occur."
10711 (let* ((fulltable org-todo-key-alist)
10712 (done-keywords org-done-keywords) ;; needed for the faces.
10713 (maxlen (apply 'max (mapcar
10714 (lambda (x)
10715 (if (stringp (car x)) (string-width (car x)) 0))
10716 fulltable)))
10717 (expert nil)
10718 (fwidth (+ maxlen 3 1 3))
10719 (ncol (/ (- (window-width) 4) fwidth))
10720 tg cnt e c tbl
10721 groups ingroup)
10722 (save-excursion
10723 (save-window-excursion
10724 (if expert
10725 (set-buffer (get-buffer-create " *Org todo*"))
10726 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
10727 (erase-buffer)
10728 (org-set-local 'org-done-keywords done-keywords)
10729 (setq tbl fulltable cnt 0)
10730 (while (setq e (pop tbl))
10731 (cond
10732 ((equal e '(:startgroup))
10733 (push '() groups) (setq ingroup t)
10734 (when (not (= cnt 0))
10735 (setq cnt 0)
10736 (insert "\n"))
10737 (insert "{ "))
10738 ((equal e '(:endgroup))
10739 (setq ingroup nil cnt 0)
10740 (insert "}\n"))
10741 ((equal e '(:newline))
10742 (when (not (= cnt 0))
10743 (setq cnt 0)
10744 (insert "\n")
10745 (setq e (car tbl))
10746 (while (equal (car tbl) '(:newline))
10747 (insert "\n")
10748 (setq tbl (cdr tbl)))))
10749 (t
10750 (setq tg (car e) c (cdr e))
10751 (if ingroup (push tg (car groups)))
10752 (setq tg (org-add-props tg nil 'face
10753 (org-get-todo-face tg)))
10754 (if (and (= cnt 0) (not ingroup)) (insert " "))
10755 (insert "[" c "] " tg (make-string
10756 (- fwidth 4 (length tg)) ?\ ))
10757 (when (= (setq cnt (1+ cnt)) ncol)
10758 (insert "\n")
10759 (if ingroup (insert " "))
10760 (setq cnt 0)))))
10761 (insert "\n")
10762 (goto-char (point-min))
10763 (if (not expert) (org-fit-window-to-buffer))
10764 (message "[a-z..]:Set [SPC]:clear")
10765 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10766 (cond
10767 ((or (= c ?\C-g)
10768 (and (= c ?q) (not (rassoc c fulltable))))
10769 (setq quit-flag t))
10770 ((= c ?\ ) nil)
10771 ((setq e (rassoc c fulltable) tg (car e))
10772 tg)
10773 (t (setq quit-flag t)))))))
10774
10775 (defun org-entry-is-todo-p ()
10776 (member (org-get-todo-state) org-not-done-keywords))
10777
10778 (defun org-entry-is-done-p ()
10779 (member (org-get-todo-state) org-done-keywords))
10780
10781 (defun org-get-todo-state ()
10782 (save-excursion
10783 (org-back-to-heading t)
10784 (and (looking-at org-todo-line-regexp)
10785 (match-end 2)
10786 (match-string 2))))
10787
10788 (defun org-at-date-range-p (&optional inactive-ok)
10789 "Is the cursor inside a date range?"
10790 (interactive)
10791 (save-excursion
10792 (catch 'exit
10793 (let ((pos (point)))
10794 (skip-chars-backward "^[<\r\n")
10795 (skip-chars-backward "<[")
10796 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10797 (>= (match-end 0) pos)
10798 (throw 'exit t))
10799 (skip-chars-backward "^<[\r\n")
10800 (skip-chars-backward "<[")
10801 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
10802 (>= (match-end 0) pos)
10803 (throw 'exit t)))
10804 nil)))
10805
10806 (defun org-get-repeat (&optional tagline)
10807 "Check if there is a deadline/schedule with repeater in this entry."
10808 (save-match-data
10809 (save-excursion
10810 (org-back-to-heading t)
10811 (and (re-search-forward (if tagline
10812 (concat tagline "\\s-*" org-repeat-re)
10813 org-repeat-re)
10814 (org-entry-end-position) t)
10815 (match-string-no-properties 1)))))
10816
10817 (defvar org-last-changed-timestamp)
10818 (defvar org-last-inserted-timestamp)
10819 (defvar org-log-post-message)
10820 (defvar org-log-note-purpose)
10821 (defvar org-log-note-how)
10822 (defvar org-log-note-extra)
10823 (defun org-auto-repeat-maybe (done-word)
10824 "Check if the current headline contains a repeated deadline/schedule.
10825 If yes, set TODO state back to what it was and change the base date
10826 of repeating deadline/scheduled time stamps to new date.
10827 This function is run automatically after each state change to a DONE state."
10828 ;; last-state is dynamically scoped into this function
10829 (let* ((repeat (org-get-repeat))
10830 (aa (assoc last-state org-todo-kwd-alist))
10831 (interpret (nth 1 aa))
10832 (head (nth 2 aa))
10833 (whata '(("d" . day) ("m" . month) ("y" . year)))
10834 (msg "Entry repeats: ")
10835 (org-log-done nil)
10836 (org-todo-log-states nil)
10837 (nshiftmax 10) (nshift 0)
10838 re type n what ts time)
10839 (when repeat
10840 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
10841 (org-todo (if (eq interpret 'type) last-state head))
10842 (org-entry-put nil "LAST_REPEAT" (format-time-string
10843 (org-time-stamp-format t t)))
10844 (when org-log-repeat
10845 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
10846 (memq 'org-add-log-note post-command-hook))
10847 ;; OK, we are already setup for some record
10848 (if (eq org-log-repeat 'note)
10849 ;; make sure we take a note, not only a time stamp
10850 (setq org-log-note-how 'note))
10851 ;; Set up for taking a record
10852 (org-add-log-setup 'state (or done-word (car org-done-keywords))
10853 last-state
10854 'findpos org-log-repeat)))
10855 (org-back-to-heading t)
10856 (org-add-planning-info nil nil 'closed)
10857 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
10858 org-deadline-time-regexp "\\)\\|\\("
10859 org-ts-regexp "\\)"))
10860 (while (re-search-forward
10861 re (save-excursion (outline-next-heading) (point)) t)
10862 (setq type (if (match-end 1) org-scheduled-string
10863 (if (match-end 3) org-deadline-string "Plain:"))
10864 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
10865 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
10866 (setq n (string-to-number (match-string 2 ts))
10867 what (match-string 3 ts))
10868 (if (equal what "w") (setq n (* n 7) what "d"))
10869 ;; Preparation, see if we need to modify the start date for the change
10870 (when (match-end 1)
10871 (setq time (save-match-data (org-time-string-to-time ts)))
10872 (cond
10873 ((equal (match-string 1 ts) ".")
10874 ;; Shift starting date to today
10875 (org-timestamp-change
10876 (- (time-to-days (current-time)) (time-to-days time))
10877 'day))
10878 ((equal (match-string 1 ts) "+")
10879 (while (or (= nshift 0)
10880 (<= (time-to-days time) (time-to-days (current-time))))
10881 (when (= (incf nshift) nshiftmax)
10882 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
10883 (error "Abort")))
10884 (org-timestamp-change n (cdr (assoc what whata)))
10885 (org-at-timestamp-p t)
10886 (setq ts (match-string 1))
10887 (setq time (save-match-data (org-time-string-to-time ts))))
10888 (org-timestamp-change (- n) (cdr (assoc what whata)))
10889 ;; rematch, so that we have everything in place for the real shift
10890 (org-at-timestamp-p t)
10891 (setq ts (match-string 1))
10892 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
10893 (org-timestamp-change n (cdr (assoc what whata)))
10894 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
10895 (setq org-log-post-message msg)
10896 (message "%s" msg))))
10897
10898 (defun org-show-todo-tree (arg)
10899 "Make a compact tree which shows all headlines marked with TODO.
10900 The tree will show the lines where the regexp matches, and all higher
10901 headlines above the match.
10902 With a \\[universal-argument] prefix, prompt for a regexp to match.
10903 With a numeric prefix N, construct a sparse tree for the Nth element
10904 of `org-todo-keywords-1'."
10905 (interactive "P")
10906 (let ((case-fold-search nil)
10907 (kwd-re
10908 (cond ((null arg) org-not-done-regexp)
10909 ((equal arg '(4))
10910 (let ((kwd (org-icompleting-read "Keyword (or KWD1|KWD2|...): "
10911 (mapcar 'list org-todo-keywords-1))))
10912 (concat "\\("
10913 (mapconcat 'identity (org-split-string kwd "|") "\\|")
10914 "\\)\\>")))
10915 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
10916 (regexp-quote (nth (1- (prefix-numeric-value arg))
10917 org-todo-keywords-1)))
10918 (t (error "Invalid prefix argument: %s" arg)))))
10919 (message "%d TODO entries found"
10920 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
10921
10922 (defun org-deadline (&optional remove time)
10923 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
10924 With argument REMOVE, remove any deadline from the item.
10925 When TIME is set, it should be an internal time specification, and the
10926 scheduling will use the corresponding date."
10927 (interactive "P")
10928 (let* ((old-date (org-entry-get nil "DEADLINE"))
10929 (repeater (and old-date
10930 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
10931 (match-string 1 old-date))))
10932 (if remove
10933 (progn
10934 (when (and old-date org-log-redeadline)
10935 (org-add-log-setup 'deldeadline nil old-date 'findpos
10936 org-log-redeadline))
10937 (org-remove-timestamp-with-keyword org-deadline-string)
10938 (message "Item no longer has a deadline."))
10939 (org-add-planning-info 'deadline time 'closed)
10940 (when (and old-date org-log-redeadline
10941 (not (equal old-date
10942 (substring org-last-inserted-timestamp 1 -1))))
10943 (org-add-log-setup 'redeadline nil old-date 'findpos
10944 org-log-redeadline))
10945 (when repeater
10946 (save-excursion
10947 (org-back-to-heading t)
10948 (when (re-search-forward (concat org-deadline-string " "
10949 org-last-inserted-timestamp)
10950 (save-excursion
10951 (outline-next-heading) (point)) t)
10952 (goto-char (1- (match-end 0)))
10953 (insert " " repeater)
10954 (setq org-last-inserted-timestamp
10955 (concat (substring org-last-inserted-timestamp 0 -1)
10956 " " repeater
10957 (substring org-last-inserted-timestamp -1))))))
10958 (message "Deadline on %s" org-last-inserted-timestamp))))
10959
10960 (defun org-schedule (&optional remove time)
10961 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
10962 With argument REMOVE, remove any scheduling date from the item.
10963 When TIME is set, it should be an internal time specification, and the
10964 scheduling will use the corresponding date."
10965 (interactive "P")
10966 (let* ((old-date (org-entry-get nil "SCHEDULED"))
10967 (repeater (and old-date
10968 (string-match "\\([.+]+[0-9]+[dwmy]\\) ?" old-date)
10969 (match-string 1 old-date))))
10970 (if remove
10971 (progn
10972 (when (and old-date org-log-reschedule)
10973 (org-add-log-setup 'delschedule nil old-date 'findpos
10974 org-log-reschedule))
10975 (org-remove-timestamp-with-keyword org-scheduled-string)
10976 (message "Item is no longer scheduled."))
10977 (org-add-planning-info 'scheduled time 'closed)
10978 (when (and old-date org-log-reschedule
10979 (not (equal old-date
10980 (substring org-last-inserted-timestamp 1 -1))))
10981 (org-add-log-setup 'reschedule nil old-date 'findpos
10982 org-log-reschedule))
10983 (when repeater
10984 (save-excursion
10985 (org-back-to-heading t)
10986 (when (re-search-forward (concat org-scheduled-string " "
10987 org-last-inserted-timestamp)
10988 (save-excursion
10989 (outline-next-heading) (point)) t)
10990 (goto-char (1- (match-end 0)))
10991 (insert " " repeater)
10992 (setq org-last-inserted-timestamp
10993 (concat (substring org-last-inserted-timestamp 0 -1)
10994 " " repeater
10995 (substring org-last-inserted-timestamp -1))))))
10996 (message "Scheduled to %s" org-last-inserted-timestamp))))
10997
10998 (defun org-get-scheduled-time (pom &optional inherit)
10999 "Get the scheduled time as a time tuple, of a format suitable
11000 for calling org-schedule with, or if there is no scheduling,
11001 returns nil."
11002 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
11003 (when time
11004 (apply 'encode-time (org-parse-time-string time)))))
11005
11006 (defun org-get-deadline-time (pom &optional inherit)
11007 "Get the deadine as a time tuple, of a format suitable for
11008 calling org-deadline with, or if there is no scheduling, returns
11009 nil."
11010 (let ((time (org-entry-get pom "DEADLINE" inherit)))
11011 (when time
11012 (apply 'encode-time (org-parse-time-string time)))))
11013
11014 (defun org-remove-timestamp-with-keyword (keyword)
11015 "Remove all time stamps with KEYWORD in the current entry."
11016 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
11017 beg)
11018 (save-excursion
11019 (org-back-to-heading t)
11020 (setq beg (point))
11021 (outline-next-heading)
11022 (while (re-search-backward re beg t)
11023 (replace-match "")
11024 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
11025 (equal (char-before) ?\ ))
11026 (backward-delete-char 1)
11027 (if (string-match "^[ \t]*$" (buffer-substring
11028 (point-at-bol) (point-at-eol)))
11029 (delete-region (point-at-bol)
11030 (min (point-max) (1+ (point-at-eol))))))))))
11031
11032 (defun org-add-planning-info (what &optional time &rest remove)
11033 "Insert new timestamp with keyword in the line directly after the headline.
11034 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
11035 If non is given, the user is prompted for a date.
11036 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
11037 be removed."
11038 (interactive)
11039 (let (org-time-was-given org-end-time-was-given ts
11040 end default-time default-input)
11041
11042 (catch 'exit
11043 (when (and (not time) (memq what '(scheduled deadline)))
11044 ;; Try to get a default date/time from existing timestamp
11045 (save-excursion
11046 (org-back-to-heading t)
11047 (setq end (save-excursion (outline-next-heading) (point)))
11048 (when (re-search-forward (if (eq what 'scheduled)
11049 org-scheduled-time-regexp
11050 org-deadline-time-regexp)
11051 end t)
11052 (setq ts (match-string 1)
11053 default-time
11054 (apply 'encode-time (org-parse-time-string ts))
11055 default-input (and ts (org-get-compact-tod ts))))))
11056 (when what
11057 ;; If necessary, get the time from the user
11058 (setq time (or time (org-read-date nil 'to-time nil nil
11059 default-time default-input))))
11060
11061 (when (and org-insert-labeled-timestamps-at-point
11062 (member what '(scheduled deadline)))
11063 (insert
11064 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
11065 (org-insert-time-stamp time org-time-was-given
11066 nil nil nil (list org-end-time-was-given))
11067 (setq what nil))
11068 (save-excursion
11069 (save-restriction
11070 (let (col list elt ts buffer-invisibility-spec)
11071 (org-back-to-heading t)
11072 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
11073 (goto-char (match-end 1))
11074 (setq col (current-column))
11075 (goto-char (match-end 0))
11076 (if (eobp) (insert "\n") (forward-char 1))
11077 (when (and (not what)
11078 (not (looking-at
11079 (concat "[ \t]*"
11080 org-keyword-time-not-clock-regexp))))
11081 ;; Nothing to add, nothing to remove...... :-)
11082 (throw 'exit nil))
11083 (if (and (not (looking-at outline-regexp))
11084 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
11085 "[^\r\n]*"))
11086 (not (equal (match-string 1) org-clock-string)))
11087 (narrow-to-region (match-beginning 0) (match-end 0))
11088 (insert-before-markers "\n")
11089 (backward-char 1)
11090 (narrow-to-region (point) (point))
11091 (and org-adapt-indentation (org-indent-to-column col)))
11092 ;; Check if we have to remove something.
11093 (setq list (cons what remove))
11094 (while list
11095 (setq elt (pop list))
11096 (goto-char (point-min))
11097 (when (or (and (eq elt 'scheduled)
11098 (re-search-forward org-scheduled-time-regexp nil t))
11099 (and (eq elt 'deadline)
11100 (re-search-forward org-deadline-time-regexp nil t))
11101 (and (eq elt 'closed)
11102 (re-search-forward org-closed-time-regexp nil t)))
11103 (replace-match "")
11104 (if (looking-at "--+<[^>]+>") (replace-match ""))
11105 (skip-chars-backward " ")
11106 (if (looking-at " +") (replace-match ""))))
11107 (goto-char (point-max))
11108 (and org-adapt-indentation (bolp) (org-indent-to-column col))
11109 (when what
11110 (insert
11111 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
11112 (cond ((eq what 'scheduled) org-scheduled-string)
11113 ((eq what 'deadline) org-deadline-string)
11114 ((eq what 'closed) org-closed-string))
11115 " ")
11116 (setq ts (org-insert-time-stamp
11117 time
11118 (or org-time-was-given
11119 (and (eq what 'closed) org-log-done-with-time))
11120 (eq what 'closed)
11121 nil nil (list org-end-time-was-given)))
11122 (end-of-line 1))
11123 (goto-char (point-min))
11124 (widen)
11125 (if (and (looking-at "[ \t]+\n")
11126 (equal (char-before) ?\n))
11127 (delete-region (1- (point)) (point-at-eol)))
11128 ts))))))
11129
11130 (defvar org-log-note-marker (make-marker))
11131 (defvar org-log-note-purpose nil)
11132 (defvar org-log-note-state nil)
11133 (defvar org-log-note-previous-state nil)
11134 (defvar org-log-note-how nil)
11135 (defvar org-log-note-extra nil)
11136 (defvar org-log-note-window-configuration nil)
11137 (defvar org-log-note-return-to (make-marker))
11138 (defvar org-log-post-message nil
11139 "Message to be displayed after a log note has been stored.
11140 The auto-repeater uses this.")
11141
11142 (defun org-add-note ()
11143 "Add a note to the current entry.
11144 This is done in the same way as adding a state change note."
11145 (interactive)
11146 (org-add-log-setup 'note nil nil 'findpos nil))
11147
11148 (defvar org-property-end-re)
11149 (defun org-add-log-setup (&optional purpose state prev-state
11150 findpos how &optional extra)
11151 "Set up the post command hook to take a note.
11152 If this is about to TODO state change, the new state is expected in STATE.
11153 When FINDPOS is non-nil, find the correct position for the note in
11154 the current entry. If not, assume that it can be inserted at point.
11155 HOW is an indicator what kind of note should be created.
11156 EXTRA is additional text that will be inserted into the notes buffer."
11157 (let* ((org-log-into-drawer (org-log-into-drawer))
11158 (drawer (cond ((stringp org-log-into-drawer)
11159 org-log-into-drawer)
11160 (org-log-into-drawer "LOGBOOK")
11161 (t nil))))
11162 (save-restriction
11163 (save-excursion
11164 (when findpos
11165 (org-back-to-heading t)
11166 (narrow-to-region (point) (save-excursion
11167 (outline-next-heading) (point)))
11168 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
11169 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
11170 "[^\r\n]*\\)?"))
11171 (goto-char (match-end 0))
11172 (cond
11173 (drawer
11174 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
11175 nil t)
11176 (progn
11177 (goto-char (match-end 0))
11178 (or org-log-states-order-reversed
11179 (and (re-search-forward org-property-end-re nil t)
11180 (goto-char (1- (match-beginning 0))))))
11181 (insert "\n:" drawer ":\n:END:")
11182 (beginning-of-line 0)
11183 (org-indent-line-function)
11184 (beginning-of-line 2)
11185 (org-indent-line-function)
11186 (end-of-line 0)))
11187 ((and org-log-state-notes-insert-after-drawers
11188 (save-excursion
11189 (forward-line) (looking-at org-drawer-regexp)))
11190 (forward-line)
11191 (while (looking-at org-drawer-regexp)
11192 (goto-char (match-end 0))
11193 (re-search-forward org-property-end-re (point-max) t)
11194 (forward-line))
11195 (forward-line -1)))
11196 (unless org-log-states-order-reversed
11197 (and (= (char-after) ?\n) (forward-char 1))
11198 (org-skip-over-state-notes)
11199 (skip-chars-backward " \t\n\r")))
11200 (move-marker org-log-note-marker (point))
11201 (setq org-log-note-purpose purpose
11202 org-log-note-state state
11203 org-log-note-previous-state prev-state
11204 org-log-note-how how
11205 org-log-note-extra extra)
11206 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
11207
11208 (defun org-skip-over-state-notes ()
11209 "Skip past the list of State notes in an entry."
11210 (if (looking-at "\n[ \t]*- State") (forward-char 1))
11211 (while (looking-at "[ \t]*- State")
11212 (condition-case nil
11213 (org-next-item)
11214 (error (org-end-of-item)))))
11215
11216 (defun org-add-log-note (&optional purpose)
11217 "Pop up a window for taking a note, and add this note later at point."
11218 (remove-hook 'post-command-hook 'org-add-log-note)
11219 (setq org-log-note-window-configuration (current-window-configuration))
11220 (delete-other-windows)
11221 (move-marker org-log-note-return-to (point))
11222 (switch-to-buffer (marker-buffer org-log-note-marker))
11223 (goto-char org-log-note-marker)
11224 (org-switch-to-buffer-other-window "*Org Note*")
11225 (erase-buffer)
11226 (if (memq org-log-note-how '(time state))
11227 (let (current-prefix-arg) (org-store-log-note))
11228 (let ((org-inhibit-startup t)) (org-mode))
11229 (insert (format "# Insert note for %s.
11230 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
11231 (cond
11232 ((eq org-log-note-purpose 'clock-out) "stopped clock")
11233 ((eq org-log-note-purpose 'done) "closed todo item")
11234 ((eq org-log-note-purpose 'state)
11235 (format "state change from \"%s\" to \"%s\""
11236 (or org-log-note-previous-state "")
11237 (or org-log-note-state "")))
11238 ((eq org-log-note-purpose 'reschedule)
11239 "rescheduling")
11240 ((eq org-log-note-purpose 'delschedule)
11241 "no longer scheduled")
11242 ((eq org-log-note-purpose 'redeadline)
11243 "changing deadline")
11244 ((eq org-log-note-purpose 'deldeadline)
11245 "removing deadline")
11246 ((eq org-log-note-purpose 'refile)
11247 "refiling")
11248 ((eq org-log-note-purpose 'note)
11249 "this entry")
11250 (t (error "This should not happen")))))
11251 (if org-log-note-extra (insert org-log-note-extra))
11252 (org-set-local 'org-finish-function 'org-store-log-note)))
11253
11254 (defvar org-note-abort nil) ; dynamically scoped
11255 (defun org-store-log-note ()
11256 "Finish taking a log note, and insert it to where it belongs."
11257 (let ((txt (buffer-string))
11258 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
11259 lines ind)
11260 (kill-buffer (current-buffer))
11261 (while (string-match "\\`#.*\n[ \t\n]*" txt)
11262 (setq txt (replace-match "" t t txt)))
11263 (if (string-match "\\s-+\\'" txt)
11264 (setq txt (replace-match "" t t txt)))
11265 (setq lines (org-split-string txt "\n"))
11266 (when (and note (string-match "\\S-" note))
11267 (setq note
11268 (org-replace-escapes
11269 note
11270 (list (cons "%u" (user-login-name))
11271 (cons "%U" user-full-name)
11272 (cons "%t" (format-time-string
11273 (org-time-stamp-format 'long 'inactive)
11274 (current-time)))
11275 (cons "%s" (if org-log-note-state
11276 (concat "\"" org-log-note-state "\"")
11277 ""))
11278 (cons "%S" (if org-log-note-previous-state
11279 (concat "\"" org-log-note-previous-state "\"")
11280 "\"\"")))))
11281 (if lines (setq note (concat note " \\\\")))
11282 (push note lines))
11283 (when (or current-prefix-arg org-note-abort)
11284 (when org-log-into-drawer
11285 (org-remove-empty-drawer-at
11286 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
11287 org-log-note-marker))
11288 (setq lines nil))
11289 (when lines
11290 (with-current-buffer (marker-buffer org-log-note-marker)
11291 (save-excursion
11292 (goto-char org-log-note-marker)
11293 (move-marker org-log-note-marker nil)
11294 (end-of-line 1)
11295 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
11296 (insert "- " (pop lines))
11297 (org-indent-line-function)
11298 (beginning-of-line 1)
11299 (looking-at "[ \t]*")
11300 (setq ind (concat (match-string 0) " "))
11301 (end-of-line 1)
11302 (while lines (insert "\n" ind (pop lines)))
11303 (message "Note stored")
11304 (org-back-to-heading t)
11305 (org-cycle-hide-drawers 'children)))))
11306 (set-window-configuration org-log-note-window-configuration)
11307 (with-current-buffer (marker-buffer org-log-note-return-to)
11308 (goto-char org-log-note-return-to))
11309 (move-marker org-log-note-return-to nil)
11310 (and org-log-post-message (message "%s" org-log-post-message)))
11311
11312 (defun org-remove-empty-drawer-at (drawer pos)
11313 "Remove an empty drawer DRAWER at position POS.
11314 POS may also be a marker."
11315 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
11316 (save-excursion
11317 (save-restriction
11318 (widen)
11319 (goto-char pos)
11320 (if (org-in-regexp
11321 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
11322 (replace-match ""))))))
11323
11324 (defun org-sparse-tree (&optional arg)
11325 "Create a sparse tree, prompt for the details.
11326 This command can create sparse trees. You first need to select the type
11327 of match used to create the tree:
11328
11329 t Show entries with a specific TODO keyword.
11330 m Show entries selected by a tags/property match.
11331 p Enter a property name and its value (both with completion on existing
11332 names/values) and show entries with that property.
11333 / Show entries matching a regular expression (`r' can be used as well)
11334 d Show deadlines due within `org-deadline-warning-days'.
11335 b Show deadlines and scheduled items before a date.
11336 a Show deadlines and scheduled items after a date."
11337 (interactive "P")
11338 (let (ans kwd value)
11339 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
11340 (setq ans (read-char-exclusive))
11341 (cond
11342 ((equal ans ?d)
11343 (call-interactively 'org-check-deadlines))
11344 ((equal ans ?b)
11345 (call-interactively 'org-check-before-date))
11346 ((equal ans ?a)
11347 (call-interactively 'org-check-after-date))
11348 ((equal ans ?t)
11349 (org-show-todo-tree '(4)))
11350 ((member ans '(?T ?m))
11351 (call-interactively 'org-match-sparse-tree))
11352 ((member ans '(?p ?P))
11353 (setq kwd (org-icompleting-read "Property: "
11354 (mapcar 'list (org-buffer-property-keys))))
11355 (setq value (org-icompleting-read "Value: "
11356 (mapcar 'list (org-property-values kwd))))
11357 (unless (string-match "\\`{.*}\\'" value)
11358 (setq value (concat "\"" value "\"")))
11359 (org-match-sparse-tree arg (concat kwd "=" value)))
11360 ((member ans '(?r ?R ?/))
11361 (call-interactively 'org-occur))
11362 (t (error "No such sparse tree command \"%c\"" ans)))))
11363
11364 (defvar org-occur-highlights nil
11365 "List of overlays used for occur matches.")
11366 (make-variable-buffer-local 'org-occur-highlights)
11367 (defvar org-occur-parameters nil
11368 "Parameters of the active org-occur calls.
11369 This is a list, each call to org-occur pushes as cons cell,
11370 containing the regular expression and the callback, onto the list.
11371 The list can contain several entries if `org-occur' has been called
11372 several time with the KEEP-PREVIOUS argument. Otherwise, this list
11373 will only contain one set of parameters. When the highlights are
11374 removed (for example with `C-c C-c', or with the next edit (depending
11375 on `org-remove-highlights-with-change'), this variable is emptied
11376 as well.")
11377 (make-variable-buffer-local 'org-occur-parameters)
11378
11379 (defun org-occur (regexp &optional keep-previous callback)
11380 "Make a compact tree which shows all matches of REGEXP.
11381 The tree will show the lines where the regexp matches, and all higher
11382 headlines above the match. It will also show the heading after the match,
11383 to make sure editing the matching entry is easy.
11384 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
11385 call to `org-occur' will be kept, to allow stacking of calls to this
11386 command.
11387 If CALLBACK is non-nil, it is a function which is called to confirm
11388 that the match should indeed be shown."
11389 (interactive "sRegexp: \nP")
11390 (when (equal regexp "")
11391 (error "Regexp cannot be empty"))
11392 (unless keep-previous
11393 (org-remove-occur-highlights nil nil t))
11394 (push (cons regexp callback) org-occur-parameters)
11395 (let ((cnt 0))
11396 (save-excursion
11397 (goto-char (point-min))
11398 (if (or (not keep-previous) ; do not want to keep
11399 (not org-occur-highlights)) ; no previous matches
11400 ;; hide everything
11401 (org-overview))
11402 (while (re-search-forward regexp nil t)
11403 (when (or (not callback)
11404 (save-match-data (funcall callback)))
11405 (setq cnt (1+ cnt))
11406 (when org-highlight-sparse-tree-matches
11407 (org-highlight-new-match (match-beginning 0) (match-end 0)))
11408 (org-show-context 'occur-tree))))
11409 (when org-remove-highlights-with-change
11410 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
11411 nil 'local))
11412 (unless org-sparse-tree-open-archived-trees
11413 (org-hide-archived-subtrees (point-min) (point-max)))
11414 (run-hooks 'org-occur-hook)
11415 (if (interactive-p)
11416 (message "%d match(es) for regexp %s" cnt regexp))
11417 cnt))
11418
11419 (defun org-show-context (&optional key)
11420 "Make sure point and context and visible.
11421 How much context is shown depends upon the variables
11422 `org-show-hierarchy-above', `org-show-following-heading'. and
11423 `org-show-siblings'."
11424 (let ((heading-p (org-on-heading-p t))
11425 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
11426 (following-p (org-get-alist-option org-show-following-heading key))
11427 (entry-p (org-get-alist-option org-show-entry-below key))
11428 (siblings-p (org-get-alist-option org-show-siblings key)))
11429 (catch 'exit
11430 ;; Show heading or entry text
11431 (if (and heading-p (not entry-p))
11432 (org-flag-heading nil) ; only show the heading
11433 (and (or entry-p (org-invisible-p) (org-invisible-p2))
11434 (org-show-hidden-entry))) ; show entire entry
11435 (when following-p
11436 ;; Show next sibling, or heading below text
11437 (save-excursion
11438 (and (if heading-p (org-goto-sibling) (outline-next-heading))
11439 (org-flag-heading nil))))
11440 (when siblings-p (org-show-siblings))
11441 (when hierarchy-p
11442 ;; show all higher headings, possibly with siblings
11443 (save-excursion
11444 (while (and (condition-case nil
11445 (progn (org-up-heading-all 1) t)
11446 (error nil))
11447 (not (bobp)))
11448 (org-flag-heading nil)
11449 (when siblings-p (org-show-siblings))))))))
11450
11451 (defvar org-reveal-start-hook nil
11452 "Hook run before revealing a location.")
11453
11454 (defun org-reveal (&optional siblings)
11455 "Show current entry, hierarchy above it, and the following headline.
11456 This can be used to show a consistent set of context around locations
11457 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
11458 not t for the search context.
11459
11460 With optional argument SIBLINGS, on each level of the hierarchy all
11461 siblings are shown. This repairs the tree structure to what it would
11462 look like when opened with hierarchical calls to `org-cycle'.
11463 With double optional argument `C-u C-u', go to the parent and show the
11464 entire tree."
11465 (interactive "P")
11466 (run-hooks 'org-reveal-start-hook)
11467 (let ((org-show-hierarchy-above t)
11468 (org-show-following-heading t)
11469 (org-show-siblings (if siblings t org-show-siblings)))
11470 (org-show-context nil))
11471 (when (equal siblings '(16))
11472 (save-excursion
11473 (when (org-up-heading-safe)
11474 (org-show-subtree)
11475 (run-hook-with-args 'org-cycle-hook 'subtree)))))
11476
11477 (defun org-highlight-new-match (beg end)
11478 "Highlight from BEG to END and mark the highlight is an occur headline."
11479 (let ((ov (org-make-overlay beg end)))
11480 (org-overlay-put ov 'face 'secondary-selection)
11481 (push ov org-occur-highlights)))
11482
11483 (defun org-remove-occur-highlights (&optional beg end noremove)
11484 "Remove the occur highlights from the buffer.
11485 BEG and END are ignored. If NOREMOVE is nil, remove this function
11486 from the `before-change-functions' in the current buffer."
11487 (interactive)
11488 (unless org-inhibit-highlight-removal
11489 (mapc 'org-delete-overlay org-occur-highlights)
11490 (setq org-occur-highlights nil)
11491 (setq org-occur-parameters nil)
11492 (unless noremove
11493 (remove-hook 'before-change-functions
11494 'org-remove-occur-highlights 'local))))
11495
11496 ;;;; Priorities
11497
11498 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
11499 "Regular expression matching the priority indicator.")
11500
11501 (defvar org-remove-priority-next-time nil)
11502
11503 (defun org-priority-up ()
11504 "Increase the priority of the current item."
11505 (interactive)
11506 (org-priority 'up))
11507
11508 (defun org-priority-down ()
11509 "Decrease the priority of the current item."
11510 (interactive)
11511 (org-priority 'down))
11512
11513 (defun org-priority (&optional action)
11514 "Change the priority of an item by ARG.
11515 ACTION can be `set', `up', `down', or a character."
11516 (interactive)
11517 (unless org-enable-priority-commands
11518 (error "Priority commands are disabled"))
11519 (setq action (or action 'set))
11520 (let (current new news have remove)
11521 (save-excursion
11522 (org-back-to-heading t)
11523 (if (looking-at org-priority-regexp)
11524 (setq current (string-to-char (match-string 2))
11525 have t)
11526 (setq current org-default-priority))
11527 (cond
11528 ((eq action 'remove)
11529 (setq remove t new ?\ ))
11530 ((or (eq action 'set)
11531 (if (featurep 'xemacs) (characterp action) (integerp action)))
11532 (if (not (eq action 'set))
11533 (setq new action)
11534 (message "Priority %c-%c, SPC to remove: "
11535 org-highest-priority org-lowest-priority)
11536 (setq new (read-char-exclusive)))
11537 (if (and (= (upcase org-highest-priority) org-highest-priority)
11538 (= (upcase org-lowest-priority) org-lowest-priority))
11539 (setq new (upcase new)))
11540 (cond ((equal new ?\ ) (setq remove t))
11541 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
11542 (error "Priority must be between `%c' and `%c'"
11543 org-highest-priority org-lowest-priority))))
11544 ((eq action 'up)
11545 (if (and (not have) (eq last-command this-command))
11546 (setq new org-lowest-priority)
11547 (setq new (if (and org-priority-start-cycle-with-default (not have))
11548 org-default-priority (1- current)))))
11549 ((eq action 'down)
11550 (if (and (not have) (eq last-command this-command))
11551 (setq new org-highest-priority)
11552 (setq new (if (and org-priority-start-cycle-with-default (not have))
11553 org-default-priority (1+ current)))))
11554 (t (error "Invalid action")))
11555 (if (or (< (upcase new) org-highest-priority)
11556 (> (upcase new) org-lowest-priority))
11557 (setq remove t))
11558 (setq news (format "%c" new))
11559 (if have
11560 (if remove
11561 (replace-match "" t t nil 1)
11562 (replace-match news t t nil 2))
11563 (if remove
11564 (error "No priority cookie found in line")
11565 (let ((case-fold-search nil))
11566 (looking-at org-todo-line-regexp))
11567 (if (match-end 2)
11568 (progn
11569 (goto-char (match-end 2))
11570 (insert " [#" news "]"))
11571 (goto-char (match-beginning 3))
11572 (insert "[#" news "] "))))
11573 (org-preserve-lc (org-set-tags nil 'align)))
11574 (if remove
11575 (message "Priority removed")
11576 (message "Priority of current item set to %s" news))))
11577
11578 (defun org-get-priority (s)
11579 "Find priority cookie and return priority."
11580 (save-match-data
11581 (if (not (string-match org-priority-regexp s))
11582 (* 1000 (- org-lowest-priority org-default-priority))
11583 (* 1000 (- org-lowest-priority
11584 (string-to-char (match-string 2 s)))))))
11585
11586 ;;;; Tags
11587
11588 (defvar org-agenda-archives-mode)
11589 (defvar org-map-continue-from nil
11590 "Position from where mapping should continue.
11591 Can be set by the action argument to `org-scan-tag's and `org-map-entries'.")
11592
11593 (defvar org-scanner-tags nil
11594 "The current tag list while the tags scanner is running.")
11595 (defvar org-trust-scanner-tags nil
11596 "Should `org-get-tags-at' use the tags fro the scanner.
11597 This is for internal dynamical scoping only.
11598 When this is non-nil, the function `org-get-tags-at' will return the value
11599 of `org-scanner-tags' instead of building the list by itself. This
11600 can lead to large speed-ups when the tags scanner is used in a file with
11601 many entries, and when the list of tags is retrieved, for example to
11602 obtain a list of properties. Building the tags list for each entry in such
11603 a file becomes an N^2 operation - but with this variable set, it scales
11604 as N.")
11605
11606 (defun org-scan-tags (action matcher &optional todo-only)
11607 "Scan headline tags with inheritance and produce output ACTION.
11608
11609 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
11610 or `agenda' to produce an entry list for an agenda view. It can also be
11611 a Lisp form or a function that should be called at each matched headline, in
11612 this case the return value is a list of all return values from these calls.
11613
11614 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
11615 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
11616 only lines with a TODO keyword are included in the output."
11617 (require 'org-agenda)
11618 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
11619 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
11620 (org-re
11621 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
11622 (props (list 'face 'default
11623 'done-face 'org-agenda-done
11624 'undone-face 'default
11625 'mouse-face 'highlight
11626 'org-not-done-regexp org-not-done-regexp
11627 'org-todo-regexp org-todo-regexp
11628 'help-echo
11629 (format "mouse-2 or RET jump to org file %s"
11630 (abbreviate-file-name
11631 (or (buffer-file-name (buffer-base-buffer))
11632 (buffer-name (buffer-base-buffer)))))))
11633 (case-fold-search nil)
11634 (org-map-continue-from nil)
11635 lspos tags tags-list
11636 (tags-alist (list (cons 0 org-file-tags)))
11637 (llast 0) rtn rtn1 level category i txt
11638 todo marker entry priority)
11639 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
11640 (setq action (list 'lambda nil action)))
11641 (save-excursion
11642 (goto-char (point-min))
11643 (when (eq action 'sparse-tree)
11644 (org-overview)
11645 (org-remove-occur-highlights))
11646 (while (re-search-forward re nil t)
11647 (catch :skip
11648 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
11649 tags (if (match-end 4) (org-match-string-no-properties 4)))
11650 (goto-char (setq lspos (match-beginning 0)))
11651 (setq level (org-reduced-level (funcall outline-level))
11652 category (org-get-category))
11653 (setq i llast llast level)
11654 ;; remove tag lists from same and sublevels
11655 (while (>= i level)
11656 (when (setq entry (assoc i tags-alist))
11657 (setq tags-alist (delete entry tags-alist)))
11658 (setq i (1- i)))
11659 ;; add the next tags
11660 (when tags
11661 (setq tags (org-split-string tags ":")
11662 tags-alist
11663 (cons (cons level tags) tags-alist)))
11664 ;; compile tags for current headline
11665 (setq tags-list
11666 (if org-use-tag-inheritance
11667 (apply 'append (mapcar 'cdr (reverse tags-alist)))
11668 tags)
11669 org-scanner-tags tags-list)
11670 (when org-use-tag-inheritance
11671 (setcdr (car tags-alist)
11672 (mapcar (lambda (x)
11673 (setq x (copy-sequence x))
11674 (org-add-prop-inherited x))
11675 (cdar tags-alist))))
11676 (when (and tags org-use-tag-inheritance
11677 (or (not (eq t org-use-tag-inheritance))
11678 org-tags-exclude-from-inheritance))
11679 ;; selective inheritance, remove uninherited ones
11680 (setcdr (car tags-alist)
11681 (org-remove-uniherited-tags (cdar tags-alist))))
11682 (when (and (or (not todo-only)
11683 (and (member todo org-not-done-keywords)
11684 (or (not org-agenda-tags-todo-honor-ignore-options)
11685 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
11686 (let ((case-fold-search t)) (eval matcher))
11687 (or
11688 (not (member org-archive-tag tags-list))
11689 ;; we have an archive tag, should we use this anyway?
11690 (or (not org-agenda-skip-archived-trees)
11691 (and (eq action 'agenda) org-agenda-archives-mode))))
11692 (unless (eq action 'sparse-tree) (org-agenda-skip))
11693
11694 ;; select this headline
11695
11696 (cond
11697 ((eq action 'sparse-tree)
11698 (and org-highlight-sparse-tree-matches
11699 (org-get-heading) (match-end 0)
11700 (org-highlight-new-match
11701 (match-beginning 0) (match-beginning 1)))
11702 (org-show-context 'tags-tree))
11703 ((eq action 'agenda)
11704 (setq txt (org-format-agenda-item
11705 ""
11706 (concat
11707 (if (eq org-tags-match-list-sublevels 'indented)
11708 (make-string (1- level) ?.) "")
11709 (org-get-heading))
11710 category
11711 tags-list
11712 )
11713 priority (org-get-priority txt))
11714 (goto-char lspos)
11715 (setq marker (org-agenda-new-marker))
11716 (org-add-props txt props
11717 'org-marker marker 'org-hd-marker marker 'org-category category
11718 'todo-state todo
11719 'priority priority 'type "tagsmatch")
11720 (push txt rtn))
11721 ((functionp action)
11722 (setq org-map-continue-from nil)
11723 (save-excursion
11724 (setq rtn1 (funcall action))
11725 (push rtn1 rtn)))
11726 (t (error "Invalid action")))
11727
11728 ;; if we are to skip sublevels, jump to end of subtree
11729 (unless org-tags-match-list-sublevels
11730 (org-end-of-subtree t)
11731 (backward-char 1))))
11732 ;; Get the correct position from where to continue
11733 (if org-map-continue-from
11734 (goto-char org-map-continue-from)
11735 (and (= (point) lspos) (end-of-line 1)))))
11736 (when (and (eq action 'sparse-tree)
11737 (not org-sparse-tree-open-archived-trees))
11738 (org-hide-archived-subtrees (point-min) (point-max)))
11739 (nreverse rtn)))
11740
11741 (defun org-remove-uniherited-tags (tags)
11742 "Remove all tags that are not inherited from the list TAGS."
11743 (cond
11744 ((eq org-use-tag-inheritance t)
11745 (if org-tags-exclude-from-inheritance
11746 (org-delete-all org-tags-exclude-from-inheritance tags)
11747 tags))
11748 ((not org-use-tag-inheritance) nil)
11749 ((stringp org-use-tag-inheritance)
11750 (delq nil (mapcar
11751 (lambda (x)
11752 (if (and (string-match org-use-tag-inheritance x)
11753 (not (member x org-tags-exclude-from-inheritance)))
11754 x nil))
11755 tags)))
11756 ((listp org-use-tag-inheritance)
11757 (delq nil (mapcar
11758 (lambda (x)
11759 (if (member x org-use-tag-inheritance) x nil))
11760 tags)))))
11761
11762 (defvar todo-only) ;; dynamically scoped
11763
11764 (defun org-match-sparse-tree (&optional todo-only match)
11765 "Create a sparse tree according to tags string MATCH.
11766 MATCH can contain positive and negative selection of tags, like
11767 \"+WORK+URGENT-WITHBOSS\".
11768 If optional argument TODO-ONLY is non-nil, only select lines that are
11769 also TODO lines."
11770 (interactive "P")
11771 (org-prepare-agenda-buffers (list (current-buffer)))
11772 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
11773
11774 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
11775
11776 (defvar org-cached-props nil)
11777 (defun org-cached-entry-get (pom property)
11778 (if (or (eq t org-use-property-inheritance)
11779 (and (stringp org-use-property-inheritance)
11780 (string-match org-use-property-inheritance property))
11781 (and (listp org-use-property-inheritance)
11782 (member property org-use-property-inheritance)))
11783 ;; Caching is not possible, check it directly
11784 (org-entry-get pom property 'inherit)
11785 ;; Get all properties, so that we can do complicated checks easily
11786 (cdr (assoc property (or org-cached-props
11787 (setq org-cached-props
11788 (org-entry-properties pom)))))))
11789
11790 (defun org-global-tags-completion-table (&optional files)
11791 "Return the list of all tags in all agenda buffer/files."
11792 (save-excursion
11793 (org-uniquify
11794 (delq nil
11795 (apply 'append
11796 (mapcar
11797 (lambda (file)
11798 (set-buffer (find-file-noselect file))
11799 (append (org-get-buffer-tags)
11800 (mapcar (lambda (x) (if (stringp (car-safe x))
11801 (list (car-safe x)) nil))
11802 org-tag-alist)))
11803 (if (and files (car files))
11804 files
11805 (org-agenda-files))))))))
11806
11807 (defun org-make-tags-matcher (match)
11808 "Create the TAGS//TODO matcher form for the selection string MATCH."
11809 ;; todo-only is scoped dynamically into this function, and the function
11810 ;; may change it if the matcher asks for it.
11811 (unless match
11812 ;; Get a new match request, with completion
11813 (let ((org-last-tags-completion-table
11814 (org-global-tags-completion-table)))
11815 (setq match (org-completing-read-no-i
11816 "Match: " 'org-tags-completion-function nil nil nil
11817 'org-tags-history))))
11818
11819 ;; Parse the string and create a lisp form
11820 (let ((match0 match)
11821 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
11822 minus tag mm
11823 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
11824 orterms term orlist re-p str-p level-p level-op time-p
11825 prop-p pn pv po cat-p gv rest)
11826 (if (string-match "/+" match)
11827 ;; match contains also a todo-matching request
11828 (progn
11829 (setq tagsmatch (substring match 0 (match-beginning 0))
11830 todomatch (substring match (match-end 0)))
11831 (if (string-match "^!" todomatch)
11832 (setq todo-only t todomatch (substring todomatch 1)))
11833 (if (string-match "^\\s-*$" todomatch)
11834 (setq todomatch nil)))
11835 ;; only matching tags
11836 (setq tagsmatch match todomatch nil))
11837
11838 ;; Make the tags matcher
11839 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
11840 (setq tagsmatcher t)
11841 (setq orterms (org-split-string tagsmatch "|") orlist nil)
11842 (while (setq term (pop orterms))
11843 (while (and (equal (substring term -1) "\\") orterms)
11844 (setq term (concat term "|" (pop orterms)))) ; repair bad split
11845 (while (string-match re term)
11846 (setq rest (substring term (match-end 0))
11847 minus (and (match-end 1)
11848 (equal (match-string 1 term) "-"))
11849 tag (match-string 2 term)
11850 re-p (equal (string-to-char tag) ?{)
11851 level-p (match-end 4)
11852 prop-p (match-end 5)
11853 mm (cond
11854 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
11855 (level-p
11856 (setq level-op (org-op-to-function (match-string 3 term)))
11857 `(,level-op level ,(string-to-number
11858 (match-string 4 term))))
11859 (prop-p
11860 (setq pn (match-string 5 term)
11861 po (match-string 6 term)
11862 pv (match-string 7 term)
11863 cat-p (equal pn "CATEGORY")
11864 re-p (equal (string-to-char pv) ?{)
11865 str-p (equal (string-to-char pv) ?\")
11866 time-p (save-match-data
11867 (string-match "^\"[[<].*[]>]\"$" pv))
11868 pv (if (or re-p str-p) (substring pv 1 -1) pv))
11869 (if time-p (setq pv (org-matcher-time pv)))
11870 (setq po (org-op-to-function po (if time-p 'time str-p)))
11871 (cond
11872 ((equal pn "CATEGORY")
11873 (setq gv '(get-text-property (point) 'org-category)))
11874 ((equal pn "TODO")
11875 (setq gv 'todo))
11876 (t
11877 (setq gv `(org-cached-entry-get nil ,pn))))
11878 (if re-p
11879 (if (eq po 'org<>)
11880 `(not (string-match ,pv (or ,gv "")))
11881 `(string-match ,pv (or ,gv "")))
11882 (if str-p
11883 `(,po (or ,gv "") ,pv)
11884 `(,po (string-to-number (or ,gv ""))
11885 ,(string-to-number pv) ))))
11886 (t `(member ,tag tags-list)))
11887 mm (if minus (list 'not mm) mm)
11888 term rest)
11889 (push mm tagsmatcher))
11890 (push (if (> (length tagsmatcher) 1)
11891 (cons 'and tagsmatcher)
11892 (car tagsmatcher))
11893 orlist)
11894 (setq tagsmatcher nil))
11895 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
11896 (setq tagsmatcher
11897 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
11898 ;; Make the todo matcher
11899 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
11900 (setq todomatcher t)
11901 (setq orterms (org-split-string todomatch "|") orlist nil)
11902 (while (setq term (pop orterms))
11903 (while (string-match re term)
11904 (setq minus (and (match-end 1)
11905 (equal (match-string 1 term) "-"))
11906 kwd (match-string 2 term)
11907 re-p (equal (string-to-char kwd) ?{)
11908 term (substring term (match-end 0))
11909 mm (if re-p
11910 `(string-match ,(substring kwd 1 -1) todo)
11911 (list 'equal 'todo kwd))
11912 mm (if minus (list 'not mm) mm))
11913 (push mm todomatcher))
11914 (push (if (> (length todomatcher) 1)
11915 (cons 'and todomatcher)
11916 (car todomatcher))
11917 orlist)
11918 (setq todomatcher nil))
11919 (setq todomatcher (if (> (length orlist) 1)
11920 (cons 'or orlist) (car orlist))))
11921
11922 ;; Return the string and lisp forms of the matcher
11923 (setq matcher (if todomatcher
11924 (list 'and tagsmatcher todomatcher)
11925 tagsmatcher))
11926 (cons match0 matcher)))
11927
11928 (defun org-op-to-function (op &optional stringp)
11929 "Turn an operator into the appropriate function."
11930 (setq op
11931 (cond
11932 ((equal op "<" ) '(< string< org-time<))
11933 ((equal op ">" ) '(> org-string> org-time>))
11934 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
11935 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
11936 ((member op '("=" "==")) '(= string= org-time=))
11937 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
11938 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
11939
11940 (defun org<> (a b) (not (= a b)))
11941 (defun org-string<= (a b) (or (string= a b) (string< a b)))
11942 (defun org-string>= (a b) (not (string< a b)))
11943 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
11944 (defun org-string<> (a b) (not (string= a b)))
11945 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
11946 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
11947 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
11948 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
11949 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
11950 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
11951 (defun org-2ft (s)
11952 "Convert S to a floating point time.
11953 If S is already a number, just return it. If it is a string, parse
11954 it as a time string and apply `float-time' to it. If S is nil, just return 0."
11955 (cond
11956 ((numberp s) s)
11957 ((stringp s)
11958 (condition-case nil
11959 (float-time (apply 'encode-time (org-parse-time-string s)))
11960 (error 0.)))
11961 (t 0.)))
11962
11963 (defun org-time-today ()
11964 "Time in seconds today at 0:00.
11965 Returns the float number of seconds since the beginning of the
11966 epoch to the beginning of today (00:00)."
11967 (float-time (apply 'encode-time
11968 (append '(0 0 0) (nthcdr 3 (decode-time))))))
11969
11970 (defun org-matcher-time (s)
11971 "Interpret a time comparison value."
11972 (save-match-data
11973 (cond
11974 ((string= s "<now>") (float-time))
11975 ((string= s "<today>") (org-time-today))
11976 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
11977 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
11978 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
11979 (+ (org-time-today)
11980 (* (string-to-number (match-string 1 s))
11981 (cdr (assoc (match-string 2 s)
11982 '(("d" . 86400.0) ("w" . 604800.0)
11983 ("m" . 2678400.0) ("y" . 31557600.0)))))))
11984 (t (org-2ft s)))))
11985
11986 (defun org-match-any-p (re list)
11987 "Does re match any element of list?"
11988 (setq list (mapcar (lambda (x) (string-match re x)) list))
11989 (delq nil list))
11990
11991 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
11992 (defvar org-tags-overlay (org-make-overlay 1 1))
11993 (org-detach-overlay org-tags-overlay)
11994
11995 (defun org-get-local-tags-at (&optional pos)
11996 "Get a list of tags defined in the current headline."
11997 (org-get-tags-at pos 'local))
11998
11999 (defun org-get-local-tags ()
12000 "Get a list of tags defined in the current headline."
12001 (org-get-tags-at nil 'local))
12002
12003 (defun org-get-tags-at (&optional pos local)
12004 "Get a list of all headline tags applicable at POS.
12005 POS defaults to point. If tags are inherited, the list contains
12006 the targets in the same sequence as the headlines appear, i.e.
12007 the tags of the current headline come last.
12008 When LOCAL is non-nil, only return tags from the current headline,
12009 ignore inherited ones."
12010 (interactive)
12011 (if (and org-trust-scanner-tags
12012 (or (not pos) (equal pos (point)))
12013 (not local))
12014 org-scanner-tags
12015 (let (tags ltags lastpos parent)
12016 (save-excursion
12017 (save-restriction
12018 (widen)
12019 (goto-char (or pos (point)))
12020 (save-match-data
12021 (catch 'done
12022 (condition-case nil
12023 (progn
12024 (org-back-to-heading t)
12025 (while (not (equal lastpos (point)))
12026 (setq lastpos (point))
12027 (when (looking-at
12028 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
12029 (setq ltags (org-split-string
12030 (org-match-string-no-properties 1) ":"))
12031 (when parent
12032 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
12033 (setq tags (append
12034 (if parent
12035 (org-remove-uniherited-tags ltags)
12036 ltags)
12037 tags)))
12038 (or org-use-tag-inheritance (throw 'done t))
12039 (if local (throw 'done t))
12040 (or (org-up-heading-safe) (error nil))
12041 (setq parent t)))
12042 (error nil)))))
12043 (append (org-remove-uniherited-tags org-file-tags) tags)))))
12044
12045 (defun org-add-prop-inherited (s)
12046 (add-text-properties 0 (length s) '(inherited t) s)
12047 s)
12048
12049 (defun org-toggle-tag (tag &optional onoff)
12050 "Toggle the tag TAG for the current line.
12051 If ONOFF is `on' or `off', don't toggle but set to this state."
12052 (let (res current)
12053 (save-excursion
12054 (org-back-to-heading t)
12055 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
12056 (point-at-eol) t)
12057 (progn
12058 (setq current (match-string 1))
12059 (replace-match ""))
12060 (setq current ""))
12061 (setq current (nreverse (org-split-string current ":")))
12062 (cond
12063 ((eq onoff 'on)
12064 (setq res t)
12065 (or (member tag current) (push tag current)))
12066 ((eq onoff 'off)
12067 (or (not (member tag current)) (setq current (delete tag current))))
12068 (t (if (member tag current)
12069 (setq current (delete tag current))
12070 (setq res t)
12071 (push tag current))))
12072 (end-of-line 1)
12073 (if current
12074 (progn
12075 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
12076 (org-set-tags nil t))
12077 (delete-horizontal-space))
12078 (run-hooks 'org-after-tags-change-hook))
12079 res))
12080
12081 (defun org-align-tags-here (to-col)
12082 ;; Assumes that this is a headline
12083 (let ((pos (point)) (col (current-column)) ncol tags-l p)
12084 (beginning-of-line 1)
12085 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12086 (< pos (match-beginning 2)))
12087 (progn
12088 (setq tags-l (- (match-end 2) (match-beginning 2)))
12089 (goto-char (match-beginning 1))
12090 (insert " ")
12091 (delete-region (point) (1+ (match-beginning 2)))
12092 (setq ncol (max (1+ (current-column))
12093 (1+ col)
12094 (if (> to-col 0)
12095 to-col
12096 (- (abs to-col) tags-l))))
12097 (setq p (point))
12098 (insert (make-string (- ncol (current-column)) ?\ ))
12099 (setq ncol (current-column))
12100 (when indent-tabs-mode (tabify p (point-at-eol)))
12101 (org-move-to-column (min ncol col) t))
12102 (goto-char pos))))
12103
12104 (defun org-set-tags-command (&optional arg just-align)
12105 "Call the set-tags command for the current entry."
12106 (interactive "P")
12107 (if (org-on-heading-p)
12108 (org-set-tags arg just-align)
12109 (save-excursion
12110 (org-back-to-heading t)
12111 (org-set-tags arg just-align))))
12112
12113 (defun org-set-tags-to (data)
12114 "Set the tags of the current entry to DATA, replacing the current tags.
12115 DATA may be a tags string like :aa:bb:cc:, or a list of tags.
12116 If DATA is nil or the empty string, any tags will be removed."
12117 (interactive "sTags: ")
12118 (setq data
12119 (cond
12120 ((eq data nil) "")
12121 ((equal data "") "")
12122 ((stringp data)
12123 (concat ":" (mapconcat 'identity (org-split-string data ":+") ":")
12124 ":"))
12125 ((listp data)
12126 (concat ":" (mapconcat 'identity data ":") ":"))
12127 (t nil)))
12128 (when data
12129 (save-excursion
12130 (org-back-to-heading t)
12131 (when (looking-at org-complex-heading-regexp)
12132 (if (match-end 5)
12133 (progn
12134 (goto-char (match-beginning 5))
12135 (insert data)
12136 (delete-region (point) (point-at-eol))
12137 (org-set-tags nil 'align))
12138 (goto-char (point-at-eol))
12139 (insert " " data)
12140 (org-set-tags nil 'align)))
12141 (beginning-of-line 1)
12142 (if (looking-at ".*?\\([ \t]+\\)$")
12143 (delete-region (match-beginning 1) (match-end 1))))))
12144
12145 (defun org-set-tags (&optional arg just-align)
12146 "Set the tags for the current headline.
12147 With prefix ARG, realign all tags in headings in the current buffer."
12148 (interactive "P")
12149 (let* ((re (concat "^" outline-regexp))
12150 (current (org-get-tags-string))
12151 (col (current-column))
12152 (org-setting-tags t)
12153 table current-tags inherited-tags ; computed below when needed
12154 tags p0 c0 c1 rpl)
12155 (if arg
12156 (save-excursion
12157 (goto-char (point-min))
12158 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
12159 (while (re-search-forward re nil t)
12160 (org-set-tags nil t)
12161 (end-of-line 1)))
12162 (message "All tags realigned to column %d" org-tags-column))
12163 (if just-align
12164 (setq tags current)
12165 ;; Get a new set of tags from the user
12166 (save-excursion
12167 (setq table (append org-tag-persistent-alist
12168 (or org-tag-alist (org-get-buffer-tags))
12169 (and org-complete-tags-always-offer-all-agenda-tags
12170 (org-global-tags-completion-table (org-agenda-files))))
12171 org-last-tags-completion-table table
12172 current-tags (org-split-string current ":")
12173 inherited-tags (nreverse
12174 (nthcdr (length current-tags)
12175 (nreverse (org-get-tags-at))))
12176 tags
12177 (if (or (eq t org-use-fast-tag-selection)
12178 (and org-use-fast-tag-selection
12179 (delq nil (mapcar 'cdr table))))
12180 (org-fast-tag-selection
12181 current-tags inherited-tags table
12182 (if org-fast-tag-selection-include-todo org-todo-key-alist))
12183 (let ((org-add-colon-after-tag-completion t))
12184 (org-trim
12185 (org-without-partial-completion
12186 (org-icompleting-read "Tags: " 'org-tags-completion-function
12187 nil nil current 'org-tags-history)))))))
12188 (while (string-match "[-+&]+" tags)
12189 ;; No boolean logic, just a list
12190 (setq tags (replace-match ":" t t tags))))
12191
12192 (if org-tags-sort-function
12193 (setq tags (mapconcat 'identity
12194 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
12195 org-tags-sort-function) ":")))
12196
12197 (if (string-match "\\`[\t ]*\\'" tags)
12198 (setq tags "")
12199 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
12200 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
12201
12202 ;; Insert new tags at the correct column
12203 (beginning-of-line 1)
12204 (cond
12205 ((and (equal current "") (equal tags "")))
12206 ((re-search-forward
12207 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
12208 (point-at-eol) t)
12209 (if (equal tags "")
12210 (setq rpl "")
12211 (goto-char (match-beginning 0))
12212 (setq c0 (current-column) p0 (if (equal (char-before) ?*)
12213 (1+ (point)) (point))
12214 c1 (max (1+ c0) (if (> org-tags-column 0)
12215 org-tags-column
12216 (- (- org-tags-column) (length tags))))
12217 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
12218 (replace-match rpl t t)
12219 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
12220 tags)
12221 (t (error "Tags alignment failed")))
12222 (org-move-to-column col)
12223 (unless just-align
12224 (run-hooks 'org-after-tags-change-hook)))))
12225
12226 (defun org-change-tag-in-region (beg end tag off)
12227 "Add or remove TAG for each entry in the region.
12228 This works in the agenda, and also in an org-mode buffer."
12229 (interactive
12230 (list (region-beginning) (region-end)
12231 (let ((org-last-tags-completion-table
12232 (if (org-mode-p)
12233 (org-get-buffer-tags)
12234 (org-global-tags-completion-table))))
12235 (org-icompleting-read
12236 "Tag: " 'org-tags-completion-function nil nil nil
12237 'org-tags-history))
12238 (progn
12239 (message "[s]et or [r]emove? ")
12240 (equal (read-char-exclusive) ?r))))
12241 (if (fboundp 'deactivate-mark) (deactivate-mark))
12242 (let ((agendap (equal major-mode 'org-agenda-mode))
12243 l1 l2 m buf pos newhead (cnt 0))
12244 (goto-char end)
12245 (setq l2 (1- (org-current-line)))
12246 (goto-char beg)
12247 (setq l1 (org-current-line))
12248 (loop for l from l1 to l2 do
12249 (org-goto-line l)
12250 (setq m (get-text-property (point) 'org-hd-marker))
12251 (when (or (and (org-mode-p) (org-on-heading-p))
12252 (and agendap m))
12253 (setq buf (if agendap (marker-buffer m) (current-buffer))
12254 pos (if agendap m (point)))
12255 (with-current-buffer buf
12256 (save-excursion
12257 (save-restriction
12258 (goto-char pos)
12259 (setq cnt (1+ cnt))
12260 (org-toggle-tag tag (if off 'off 'on))
12261 (setq newhead (org-get-heading)))))
12262 (and agendap (org-agenda-change-all-lines newhead m))))
12263 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
12264
12265 (defun org-tags-completion-function (string predicate &optional flag)
12266 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
12267 (confirm (lambda (x) (stringp (car x)))))
12268 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
12269 (setq s1 (match-string 1 string)
12270 s2 (match-string 2 string))
12271 (setq s1 "" s2 string))
12272 (cond
12273 ((eq flag nil)
12274 ;; try completion
12275 (setq rtn (try-completion s2 ctable confirm))
12276 (if (stringp rtn)
12277 (setq rtn
12278 (concat s1 s2 (substring rtn (length s2))
12279 (if (and org-add-colon-after-tag-completion
12280 (assoc rtn ctable))
12281 ":" ""))))
12282 rtn)
12283 ((eq flag t)
12284 ;; all-completions
12285 (all-completions s2 ctable confirm)
12286 )
12287 ((eq flag 'lambda)
12288 ;; exact match?
12289 (assoc s2 ctable)))
12290 ))
12291
12292 (defun org-fast-tag-insert (kwd tags face &optional end)
12293 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
12294 (insert (format "%-12s" (concat kwd ":"))
12295 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
12296 (or end "")))
12297
12298 (defun org-fast-tag-show-exit (flag)
12299 (save-excursion
12300 (org-goto-line 3)
12301 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
12302 (replace-match ""))
12303 (when flag
12304 (end-of-line 1)
12305 (org-move-to-column (- (window-width) 19) t)
12306 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
12307
12308 (defun org-set-current-tags-overlay (current prefix)
12309 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
12310 (if (featurep 'xemacs)
12311 (org-overlay-display org-tags-overlay (concat prefix s)
12312 'secondary-selection)
12313 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
12314 (org-overlay-display org-tags-overlay (concat prefix s)))))
12315
12316 (defvar org-last-tag-selection-key nil)
12317 (defun org-fast-tag-selection (current inherited table &optional todo-table)
12318 "Fast tag selection with single keys.
12319 CURRENT is the current list of tags in the headline, INHERITED is the
12320 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
12321 possibly with grouping information. TODO-TABLE is a similar table with
12322 TODO keywords, should these have keys assigned to them.
12323 If the keys are nil, a-z are automatically assigned.
12324 Returns the new tags string, or nil to not change the current settings."
12325 (let* ((fulltable (append table todo-table))
12326 (maxlen (apply 'max (mapcar
12327 (lambda (x)
12328 (if (stringp (car x)) (string-width (car x)) 0))
12329 fulltable)))
12330 (buf (current-buffer))
12331 (expert (eq org-fast-tag-selection-single-key 'expert))
12332 (buffer-tags nil)
12333 (fwidth (+ maxlen 3 1 3))
12334 (ncol (/ (- (window-width) 4) fwidth))
12335 (i-face 'org-done)
12336 (c-face 'org-todo)
12337 tg cnt e c char c1 c2 ntable tbl rtn
12338 ov-start ov-end ov-prefix
12339 (exit-after-next org-fast-tag-selection-single-key)
12340 (done-keywords org-done-keywords)
12341 groups ingroup)
12342 (save-excursion
12343 (beginning-of-line 1)
12344 (if (looking-at
12345 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12346 (setq ov-start (match-beginning 1)
12347 ov-end (match-end 1)
12348 ov-prefix "")
12349 (setq ov-start (1- (point-at-eol))
12350 ov-end (1+ ov-start))
12351 (skip-chars-forward "^\n\r")
12352 (setq ov-prefix
12353 (concat
12354 (buffer-substring (1- (point)) (point))
12355 (if (> (current-column) org-tags-column)
12356 " "
12357 (make-string (- org-tags-column (current-column)) ?\ ))))))
12358 (org-move-overlay org-tags-overlay ov-start ov-end)
12359 (save-window-excursion
12360 (if expert
12361 (set-buffer (get-buffer-create " *Org tags*"))
12362 (delete-other-windows)
12363 (split-window-vertically)
12364 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
12365 (erase-buffer)
12366 (org-set-local 'org-done-keywords done-keywords)
12367 (org-fast-tag-insert "Inherited" inherited i-face "\n")
12368 (org-fast-tag-insert "Current" current c-face "\n\n")
12369 (org-fast-tag-show-exit exit-after-next)
12370 (org-set-current-tags-overlay current ov-prefix)
12371 (setq tbl fulltable char ?a cnt 0)
12372 (while (setq e (pop tbl))
12373 (cond
12374 ((equal (car e) :startgroup)
12375 (push '() groups) (setq ingroup t)
12376 (when (not (= cnt 0))
12377 (setq cnt 0)
12378 (insert "\n"))
12379 (insert (if (cdr e) (format "%s: " (cdr e)) "") "{ "))
12380 ((equal (car e) :endgroup)
12381 (setq ingroup nil cnt 0)
12382 (insert "}" (if (cdr e) (format " (%s) " (cdr e)) "") "\n"))
12383 ((equal e '(:newline))
12384 (when (not (= cnt 0))
12385 (setq cnt 0)
12386 (insert "\n")
12387 (setq e (car tbl))
12388 (while (equal (car tbl) '(:newline))
12389 (insert "\n")
12390 (setq tbl (cdr tbl)))))
12391 (t
12392 (setq tg (copy-sequence (car e)) c2 nil)
12393 (if (cdr e)
12394 (setq c (cdr e))
12395 ;; automatically assign a character.
12396 (setq c1 (string-to-char
12397 (downcase (substring
12398 tg (if (= (string-to-char tg) ?@) 1 0)))))
12399 (if (or (rassoc c1 ntable) (rassoc c1 table))
12400 (while (or (rassoc char ntable) (rassoc char table))
12401 (setq char (1+ char)))
12402 (setq c2 c1))
12403 (setq c (or c2 char)))
12404 (if ingroup (push tg (car groups)))
12405 (setq tg (org-add-props tg nil 'face
12406 (cond
12407 ((not (assoc tg table))
12408 (org-get-todo-face tg))
12409 ((member tg current) c-face)
12410 ((member tg inherited) i-face)
12411 (t nil))))
12412 (if (and (= cnt 0) (not ingroup)) (insert " "))
12413 (insert "[" c "] " tg (make-string
12414 (- fwidth 4 (length tg)) ?\ ))
12415 (push (cons tg c) ntable)
12416 (when (= (setq cnt (1+ cnt)) ncol)
12417 (insert "\n")
12418 (if ingroup (insert " "))
12419 (setq cnt 0)))))
12420 (setq ntable (nreverse ntable))
12421 (insert "\n")
12422 (goto-char (point-min))
12423 (if (not expert) (org-fit-window-to-buffer))
12424 (setq rtn
12425 (catch 'exit
12426 (while t
12427 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free [!] %sgroups%s"
12428 (if (not groups) "no " "")
12429 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
12430 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
12431 (setq org-last-tag-selection-key c)
12432 (cond
12433 ((= c ?\r) (throw 'exit t))
12434 ((= c ?!)
12435 (setq groups (not groups))
12436 (goto-char (point-min))
12437 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
12438 ((= c ?\C-c)
12439 (if (not expert)
12440 (org-fast-tag-show-exit
12441 (setq exit-after-next (not exit-after-next)))
12442 (setq expert nil)
12443 (delete-other-windows)
12444 (split-window-vertically)
12445 (org-switch-to-buffer-other-window " *Org tags*")
12446 (org-fit-window-to-buffer)))
12447 ((or (= c ?\C-g)
12448 (and (= c ?q) (not (rassoc c ntable))))
12449 (org-detach-overlay org-tags-overlay)
12450 (setq quit-flag t))
12451 ((= c ?\ )
12452 (setq current nil)
12453 (if exit-after-next (setq exit-after-next 'now)))
12454 ((= c ?\t)
12455 (condition-case nil
12456 (setq tg (org-icompleting-read
12457 "Tag: "
12458 (or buffer-tags
12459 (with-current-buffer buf
12460 (org-get-buffer-tags)))))
12461 (quit (setq tg "")))
12462 (when (string-match "\\S-" tg)
12463 (add-to-list 'buffer-tags (list tg))
12464 (if (member tg current)
12465 (setq current (delete tg current))
12466 (push tg current)))
12467 (if exit-after-next (setq exit-after-next 'now)))
12468 ((setq e (rassoc c todo-table) tg (car e))
12469 (with-current-buffer buf
12470 (save-excursion (org-todo tg)))
12471 (if exit-after-next (setq exit-after-next 'now)))
12472 ((setq e (rassoc c ntable) tg (car e))
12473 (if (member tg current)
12474 (setq current (delete tg current))
12475 (loop for g in groups do
12476 (if (member tg g)
12477 (mapc (lambda (x)
12478 (setq current (delete x current)))
12479 g)))
12480 (push tg current))
12481 (if exit-after-next (setq exit-after-next 'now))))
12482
12483 ;; Create a sorted list
12484 (setq current
12485 (sort current
12486 (lambda (a b)
12487 (assoc b (cdr (memq (assoc a ntable) ntable))))))
12488 (if (eq exit-after-next 'now) (throw 'exit t))
12489 (goto-char (point-min))
12490 (beginning-of-line 2)
12491 (delete-region (point) (point-at-eol))
12492 (org-fast-tag-insert "Current" current c-face)
12493 (org-set-current-tags-overlay current ov-prefix)
12494 (while (re-search-forward
12495 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
12496 (setq tg (match-string 1))
12497 (add-text-properties
12498 (match-beginning 1) (match-end 1)
12499 (list 'face
12500 (cond
12501 ((member tg current) c-face)
12502 ((member tg inherited) i-face)
12503 (t (get-text-property (match-beginning 1) 'face))))))
12504 (goto-char (point-min)))))
12505 (org-detach-overlay org-tags-overlay)
12506 (if rtn
12507 (mapconcat 'identity current ":")
12508 nil))))
12509
12510 (defun org-get-tags-string ()
12511 "Get the TAGS string in the current headline."
12512 (unless (org-on-heading-p t)
12513 (error "Not on a heading"))
12514 (save-excursion
12515 (beginning-of-line 1)
12516 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
12517 (org-match-string-no-properties 1)
12518 "")))
12519
12520 (defun org-get-tags ()
12521 "Get the list of tags specified in the current headline."
12522 (org-split-string (org-get-tags-string) ":"))
12523
12524 (defun org-get-buffer-tags ()
12525 "Get a table of all tags used in the buffer, for completion."
12526 (let (tags)
12527 (save-excursion
12528 (goto-char (point-min))
12529 (while (re-search-forward
12530 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
12531 (when (equal (char-after (point-at-bol 0)) ?*)
12532 (mapc (lambda (x) (add-to-list 'tags x))
12533 (org-split-string (org-match-string-no-properties 1) ":")))))
12534 (mapc (lambda (s) (add-to-list 'tags s)) org-file-tags)
12535 (mapcar 'list tags)))
12536
12537 ;;;; The mapping API
12538
12539 ;;;###autoload
12540 (defun org-map-entries (func &optional match scope &rest skip)
12541 "Call FUNC at each headline selected by MATCH in SCOPE.
12542
12543 FUNC is a function or a lisp form. The function will be called without
12544 arguments, with the cursor positioned at the beginning of the headline.
12545 The return values of all calls to the function will be collected and
12546 returned as a list.
12547
12548 The call to FUNC will be wrapped into a save-excursion form, so FUNC
12549 does not need to preserve point. After evaluation, the cursor will be
12550 moved to the end of the line (presumably of the headline of the
12551 processed entry) and search continues from there. Under some
12552 circumstances, this may not produce the wanted results. For example,
12553 if you have removed (e.g. archived) the current (sub)tree it could
12554 mean that the next entry will be skipped entirely. In such cases, you
12555 can specify the position from where search should continue by making
12556 FUNC set the variable `org-map-continue-from' to the desired buffer
12557 position.
12558
12559 MATCH is a tags/property/todo match as it is used in the agenda tags view.
12560 Only headlines that are matched by this query will be considered during
12561 the iteration. When MATCH is nil or t, all headlines will be
12562 visited by the iteration.
12563
12564 SCOPE determines the scope of this command. It can be any of:
12565
12566 nil The current buffer, respecting the restriction if any
12567 tree The subtree started with the entry at point
12568 file The current buffer, without restriction
12569 file-with-archives
12570 The current buffer, and any archives associated with it
12571 agenda All agenda files
12572 agenda-with-archives
12573 All agenda files with any archive files associated with them
12574 \(file1 file2 ...)
12575 If this is a list, all files in the list will be scanned
12576
12577 The remaining args are treated as settings for the skipping facilities of
12578 the scanner. The following items can be given here:
12579
12580 archive skip trees with the archive tag.
12581 comment skip trees with the COMMENT keyword
12582 function or Emacs Lisp form:
12583 will be used as value for `org-agenda-skip-function', so whenever
12584 the function returns t, FUNC will not be called for that
12585 entry and search will continue from the point where the
12586 function leaves it.
12587
12588 If your function needs to retrieve the tags including inherited tags
12589 at the *current* entry, you can use the value of the variable
12590 `org-scanner-tags' which will be much faster than getting the value
12591 with `org-get-tags-at'. If your function gets properties with
12592 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
12593 to t around the call to `org-entry-properties' to get the same speedup.
12594 Note that if your function moves around to retrieve tags and properties at
12595 a *different* entry, you cannot use these techniques."
12596 (let* ((org-agenda-archives-mode nil) ; just to make sure
12597 (org-agenda-skip-archived-trees (memq 'archive skip))
12598 (org-agenda-skip-comment-trees (memq 'comment skip))
12599 (org-agenda-skip-function
12600 (car (org-delete-all '(comment archive) skip)))
12601 (org-tags-match-list-sublevels t)
12602 matcher file res
12603 org-todo-keywords-for-agenda
12604 org-done-keywords-for-agenda
12605 org-todo-keyword-alist-for-agenda
12606 org-drawers-for-agenda
12607 org-tag-alist-for-agenda)
12608
12609 (cond
12610 ((eq match t) (setq matcher t))
12611 ((eq match nil) (setq matcher t))
12612 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
12613
12614 (save-excursion
12615 (save-restriction
12616 (when (eq scope 'tree)
12617 (org-back-to-heading t)
12618 (org-narrow-to-subtree)
12619 (setq scope nil))
12620
12621 (if (not scope)
12622 (progn
12623 (org-prepare-agenda-buffers
12624 (list (buffer-file-name (current-buffer))))
12625 (setq res (org-scan-tags func matcher)))
12626 ;; Get the right scope
12627 (cond
12628 ((and scope (listp scope) (symbolp (car scope)))
12629 (setq scope (eval scope)))
12630 ((eq scope 'agenda)
12631 (setq scope (org-agenda-files t)))
12632 ((eq scope 'agenda-with-archives)
12633 (setq scope (org-agenda-files t))
12634 (setq scope (org-add-archive-files scope)))
12635 ((eq scope 'file)
12636 (setq scope (list (buffer-file-name))))
12637 ((eq scope 'file-with-archives)
12638 (setq scope (org-add-archive-files (list (buffer-file-name))))))
12639 (org-prepare-agenda-buffers scope)
12640 (while (setq file (pop scope))
12641 (with-current-buffer (org-find-base-buffer-visiting file)
12642 (save-excursion
12643 (save-restriction
12644 (widen)
12645 (goto-char (point-min))
12646 (setq res (append res (org-scan-tags func matcher))))))))))
12647 res))
12648
12649 ;;;; Properties
12650
12651 ;;; Setting and retrieving properties
12652
12653 (defconst org-special-properties
12654 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
12655 "TIMESTAMP" "TIMESTAMP_IA" "BLOCKED")
12656 "The special properties valid in Org-mode.
12657
12658 These are properties that are not defined in the property drawer,
12659 but in some other way.")
12660
12661 (defconst org-default-properties
12662 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
12663 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
12664 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
12665 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
12666 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
12667 "CLOCK_MODELINE_TOTAL" "STYLE" "HTML_CONTAINER_CLASS")
12668 "Some properties that are used by Org-mode for various purposes.
12669 Being in this list makes sure that they are offered for completion.")
12670
12671 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
12672 "Regular expression matching the first line of a property drawer.")
12673
12674 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
12675 "Regular expression matching the last line of a property drawer.")
12676
12677 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
12678 "Regular expression matching the first line of a property drawer.")
12679
12680 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
12681 "Regular expression matching the first line of a property drawer.")
12682
12683 (defconst org-property-drawer-re
12684 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
12685 org-property-end-re "\\)\n?")
12686 "Matches an entire property drawer.")
12687
12688 (defconst org-clock-drawer-re
12689 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
12690 org-property-end-re "\\)\n?")
12691 "Matches an entire clock drawer.")
12692
12693 (defun org-property-action ()
12694 "Do an action on properties."
12695 (interactive)
12696 (let (c)
12697 (org-at-property-p)
12698 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
12699 (setq c (read-char-exclusive))
12700 (cond
12701 ((equal c ?s)
12702 (call-interactively 'org-set-property))
12703 ((equal c ?d)
12704 (call-interactively 'org-delete-property))
12705 ((equal c ?D)
12706 (call-interactively 'org-delete-property-globally))
12707 ((equal c ?c)
12708 (call-interactively 'org-compute-property-at-point))
12709 (t (error "No such property action %c" c)))))
12710
12711 (defun org-set-effort (&optional value)
12712 "Set the effort property of the current entry.
12713 With numerical prefix arg, use the nth allowed value, 0 stands for the 10th
12714 allowed value."
12715 (interactive "P")
12716 (if (equal value 0) (setq value 10))
12717 (let* ((completion-ignore-case t)
12718 (prop org-effort-property)
12719 (cur (org-entry-get nil prop))
12720 (allowed (org-property-get-allowed-values nil prop 'table))
12721 (existing (mapcar 'list (org-property-values prop)))
12722 rpl
12723 (val (cond
12724 ((stringp value) value)
12725 ((and allowed (integerp value))
12726 (or (car (nth (1- value) allowed))
12727 (car (org-last allowed))))
12728 (allowed
12729 (message "Select 1-9,0, [RET%s]: %s"
12730 (if cur (concat "=" cur) "")
12731 (mapconcat 'car allowed " "))
12732 (setq rpl (read-char-exclusive))
12733 (if (equal rpl ?\r)
12734 cur
12735 (setq rpl (- rpl ?0))
12736 (if (equal rpl 0) (setq rpl 10))
12737 (if (and (> rpl 0) (<= rpl (length allowed)))
12738 (car (nth (1- rpl) allowed))
12739 (org-completing-read "Effort: " allowed nil))))
12740 (t
12741 (let (org-completion-use-ido org-completion-use-iswitchb)
12742 (org-completing-read
12743 (concat "Effort " (if (and cur (string-match "\\S-" cur))
12744 (concat "[" cur "]") "")
12745 ": ")
12746 existing nil nil "" nil cur))))))
12747 (unless (equal (org-entry-get nil prop) val)
12748 (org-entry-put nil prop val))
12749 (message "%s is now %s" prop val)))
12750
12751 (defun org-at-property-p ()
12752 "Is cursor inside a property drawer?"
12753 (save-excursion
12754 (beginning-of-line 1)
12755 (when (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))
12756 (let ((match (match-data)) ;; Keep match-data for use by calling
12757 (p (point)) ;; procedures.
12758 (range (unless (org-before-first-heading-p)
12759 (org-get-property-block))))
12760 (prog1 (and range (<= (car range) p) (< p (cdr range)))
12761 (set-match-data match))))))
12762
12763 (defun org-get-property-block (&optional beg end force)
12764 "Return the (beg . end) range of the body of the property drawer.
12765 BEG and END can be beginning and end of subtree, if not given
12766 they will be found.
12767 If the drawer does not exist and FORCE is non-nil, create the drawer."
12768 (catch 'exit
12769 (save-excursion
12770 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
12771 (end (or end (progn (outline-next-heading) (point)))))
12772 (goto-char beg)
12773 (if (re-search-forward org-property-start-re end t)
12774 (setq beg (1+ (match-end 0)))
12775 (if force
12776 (save-excursion
12777 (org-insert-property-drawer)
12778 (setq end (progn (outline-next-heading) (point))))
12779 (throw 'exit nil))
12780 (goto-char beg)
12781 (if (re-search-forward org-property-start-re end t)
12782 (setq beg (1+ (match-end 0)))))
12783 (if (re-search-forward org-property-end-re end t)
12784 (setq end (match-beginning 0))
12785 (or force (throw 'exit nil))
12786 (goto-char beg)
12787 (setq end beg)
12788 (org-indent-line-function)
12789 (insert ":END:\n"))
12790 (cons beg end)))))
12791
12792 (defun org-entry-properties (&optional pom which specific)
12793 "Get all properties of the entry at point-or-marker POM.
12794 This includes the TODO keyword, the tags, time strings for deadline,
12795 scheduled, and clocking, and any additional properties defined in the
12796 entry. The return value is an alist, keys may occur multiple times
12797 if the property key was used several times.
12798 POM may also be nil, in which case the current entry is used.
12799 If WHICH is nil or `all', get all properties. If WHICH is
12800 `special' or `standard', only get that subclass. If WHICH
12801 is a string only get exactly this property. Specific can be a string, the
12802 specific property we are interested in. Specifying it can speed
12803 things up because then unnecessary parsing is avoided."
12804 (setq which (or which 'all))
12805 (org-with-point-at pom
12806 (let ((clockstr (substring org-clock-string 0 -1))
12807 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY" "BLOCKED"))
12808 (case-fold-search nil)
12809 beg end range props sum-props key value string clocksum)
12810 (save-excursion
12811 (when (condition-case nil
12812 (and (org-mode-p) (org-back-to-heading t))
12813 (error nil))
12814 (setq beg (point))
12815 (setq sum-props (get-text-property (point) 'org-summaries))
12816 (setq clocksum (get-text-property (point) :org-clock-minutes))
12817 (outline-next-heading)
12818 (setq end (point))
12819 (when (memq which '(all special))
12820 ;; Get the special properties, like TODO and tags
12821 (goto-char beg)
12822 (when (and (or (not specific) (string= specific "TODO"))
12823 (looking-at org-todo-line-regexp) (match-end 2))
12824 (push (cons "TODO" (org-match-string-no-properties 2)) props))
12825 (when (and (or (not specific) (string= specific "PRIORITY"))
12826 (looking-at org-priority-regexp))
12827 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
12828 (when (and (or (not specific) (string= specific "TAGS"))
12829 (setq value (org-get-tags-string))
12830 (string-match "\\S-" value))
12831 (push (cons "TAGS" value) props))
12832 (when (and (or (not specific) (string= specific "ALLTAGS"))
12833 (setq value (org-get-tags-at)))
12834 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":")
12835 ":"))
12836 props))
12837 (when (or (not specific) (string= specific "BLOCKED"))
12838 (push (cons "BLOCKED" (if (org-entry-blocked-p) "t" "")) props))
12839 (when (or (not specific)
12840 (member specific org-all-time-keywords)
12841 (member specific '("TIMESTAMP" "TIMESTAMP_IA")))
12842 (while (re-search-forward org-maybe-keyword-time-regexp end t)
12843 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
12844 string (if (equal key clockstr)
12845 (org-no-properties
12846 (org-trim
12847 (buffer-substring
12848 (match-beginning 3) (goto-char (point-at-eol)))))
12849 (substring (org-match-string-no-properties 3) 1 -1)))
12850 (unless key
12851 (if (= (char-after (match-beginning 3)) ?\[)
12852 (setq key "TIMESTAMP_IA")
12853 (setq key "TIMESTAMP")))
12854 (when (or (equal key clockstr) (not (assoc key props)))
12855 (push (cons key string) props))))
12856
12857 )
12858
12859 (when (memq which '(all standard))
12860 ;; Get the standard properties, like :PROP: ...
12861 (setq range (org-get-property-block beg end))
12862 (when range
12863 (goto-char (car range))
12864 (while (re-search-forward
12865 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
12866 (cdr range) t)
12867 (setq key (org-match-string-no-properties 1)
12868 value (org-trim (or (org-match-string-no-properties 2) "")))
12869 (unless (member key excluded)
12870 (push (cons key (or value "")) props)))))
12871 (if clocksum
12872 (push (cons "CLOCKSUM"
12873 (org-columns-number-to-string (/ (float clocksum) 60.)
12874 'add_times))
12875 props))
12876 (unless (assoc "CATEGORY" props)
12877 (setq value (or (org-get-category)
12878 (progn (org-refresh-category-properties)
12879 (org-get-category))))
12880 (push (cons "CATEGORY" value) props))
12881 (append sum-props (nreverse props)))))))
12882
12883 (defun org-entry-get (pom property &optional inherit)
12884 "Get value of PROPERTY for entry at point-or-marker POM.
12885 If INHERIT is non-nil and the entry does not have the property,
12886 then also check higher levels of the hierarchy.
12887 If INHERIT is the symbol `selective', use inheritance only if the setting
12888 in `org-use-property-inheritance' selects PROPERTY for inheritance.
12889 If the property is present but empty, the return value is the empty string.
12890 If the property is not present at all, nil is returned."
12891 (org-with-point-at pom
12892 (if (and inherit (if (eq inherit 'selective)
12893 (org-property-inherit-p property)
12894 t))
12895 (org-entry-get-with-inheritance property)
12896 (if (member property org-special-properties)
12897 ;; We need a special property. Use `org-entry-properties' to
12898 ;; retrieve it, but specify the wanted property
12899 (cdr (assoc property (org-entry-properties nil 'special property)))
12900 (let ((range (org-get-property-block)))
12901 (if (and range
12902 (goto-char (car range))
12903 (re-search-forward
12904 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
12905 (cdr range) t))
12906 ;; Found the property, return it.
12907 (if (match-end 1)
12908 (org-match-string-no-properties 1)
12909 "")))))))
12910
12911 (defun org-property-or-variable-value (var &optional inherit)
12912 "Check if there is a property fixing the value of VAR.
12913 If yes, return this value. If not, return the current value of the variable."
12914 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
12915 (if (and prop (stringp prop) (string-match "\\S-" prop))
12916 (read prop)
12917 (symbol-value var))))
12918
12919 (defun org-entry-delete (pom property)
12920 "Delete the property PROPERTY from entry at point-or-marker POM."
12921 (org-with-point-at pom
12922 (if (member property org-special-properties)
12923 nil ; cannot delete these properties.
12924 (let ((range (org-get-property-block)))
12925 (if (and range
12926 (goto-char (car range))
12927 (re-search-forward
12928 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
12929 (cdr range) t))
12930 (progn
12931 (delete-region (match-beginning 0) (1+ (point-at-eol)))
12932 t)
12933 nil)))))
12934
12935 ;; Multi-values properties are properties that contain multiple values
12936 ;; These values are assumed to be single words, separated by whitespace.
12937 (defun org-entry-add-to-multivalued-property (pom property value)
12938 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
12939 (let* ((old (org-entry-get pom property))
12940 (values (and old (org-split-string old "[ \t]"))))
12941 (setq value (org-entry-protect-space value))
12942 (unless (member value values)
12943 (setq values (cons value values))
12944 (org-entry-put pom property
12945 (mapconcat 'identity values " ")))))
12946
12947 (defun org-entry-remove-from-multivalued-property (pom property value)
12948 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
12949 (let* ((old (org-entry-get pom property))
12950 (values (and old (org-split-string old "[ \t]"))))
12951 (setq value (org-entry-protect-space value))
12952 (when (member value values)
12953 (setq values (delete value values))
12954 (org-entry-put pom property
12955 (mapconcat 'identity values " ")))))
12956
12957 (defun org-entry-member-in-multivalued-property (pom property value)
12958 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
12959 (let* ((old (org-entry-get pom property))
12960 (values (and old (org-split-string old "[ \t]"))))
12961 (setq value (org-entry-protect-space value))
12962 (member value values)))
12963
12964 (defun org-entry-get-multivalued-property (pom property)
12965 "Return a list of values in a multivalued property."
12966 (let* ((value (org-entry-get pom property))
12967 (values (and value (org-split-string value "[ \t]"))))
12968 (mapcar 'org-entry-restore-space values)))
12969
12970 (defun org-entry-put-multivalued-property (pom property &rest values)
12971 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
12972 VALUES should be a list of strings. Spaces will be protected."
12973 (org-entry-put pom property
12974 (mapconcat 'org-entry-protect-space values " "))
12975 (let* ((value (org-entry-get pom property))
12976 (values (and value (org-split-string value "[ \t]"))))
12977 (mapcar 'org-entry-restore-space values)))
12978
12979 (defun org-entry-protect-space (s)
12980 "Protect spaces and newline in string S."
12981 (while (string-match " " s)
12982 (setq s (replace-match "%20" t t s)))
12983 (while (string-match "\n" s)
12984 (setq s (replace-match "%0A" t t s)))
12985 s)
12986
12987 (defun org-entry-restore-space (s)
12988 "Restore spaces and newline in string S."
12989 (while (string-match "%20" s)
12990 (setq s (replace-match " " t t s)))
12991 (while (string-match "%0A" s)
12992 (setq s (replace-match "\n" t t s)))
12993 s)
12994
12995 (defvar org-entry-property-inherited-from (make-marker)
12996 "Marker pointing to the entry from where a property was inherited.
12997 Each call to `org-entry-get-with-inheritance' will set this marker to the
12998 location of the entry where the inheritance search matched. If there was
12999 no match, the marker will point nowhere.
13000 Note that also `org-entry-get' calls this function, if the INHERIT flag
13001 is set.")
13002
13003 (defun org-entry-get-with-inheritance (property)
13004 "Get entry property, and search higher levels if not present."
13005 (move-marker org-entry-property-inherited-from nil)
13006 (let (tmp)
13007 (save-excursion
13008 (save-restriction
13009 (widen)
13010 (catch 'ex
13011 (while t
13012 (when (setq tmp (org-entry-get nil property))
13013 (org-back-to-heading t)
13014 (move-marker org-entry-property-inherited-from (point))
13015 (throw 'ex tmp))
13016 (or (org-up-heading-safe) (throw 'ex nil)))))
13017 (or tmp
13018 (cdr (assoc property org-file-properties))
13019 (cdr (assoc property org-global-properties))
13020 (cdr (assoc property org-global-properties-fixed))))))
13021
13022 (defvar org-property-changed-functions nil
13023 "Hook called when the value of a property has changed.
13024 Each hook function should accept two arguments, the name of the property
13025 and the new value.")
13026
13027 (defun org-entry-put (pom property value)
13028 "Set PROPERTY to VALUE for entry at point-or-marker POM."
13029 (org-with-point-at pom
13030 (org-back-to-heading t)
13031 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
13032 range)
13033 (cond
13034 ((equal property "TODO")
13035 (when (and (stringp value) (string-match "\\S-" value)
13036 (not (member value org-todo-keywords-1)))
13037 (error "\"%s\" is not a valid TODO state" value))
13038 (if (or (not value)
13039 (not (string-match "\\S-" value)))
13040 (setq value 'none))
13041 (org-todo value)
13042 (org-set-tags nil 'align))
13043 ((equal property "PRIORITY")
13044 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
13045 (string-to-char value) ?\ ))
13046 (org-set-tags nil 'align))
13047 ((equal property "SCHEDULED")
13048 (if (re-search-forward org-scheduled-time-regexp end t)
13049 (cond
13050 ((eq value 'earlier) (org-timestamp-change -1 'day))
13051 ((eq value 'later) (org-timestamp-change 1 'day))
13052 (t (call-interactively 'org-schedule)))
13053 (call-interactively 'org-schedule)))
13054 ((equal property "DEADLINE")
13055 (if (re-search-forward org-deadline-time-regexp end t)
13056 (cond
13057 ((eq value 'earlier) (org-timestamp-change -1 'day))
13058 ((eq value 'later) (org-timestamp-change 1 'day))
13059 (t (call-interactively 'org-deadline)))
13060 (call-interactively 'org-deadline)))
13061 ((member property org-special-properties)
13062 (error "The %s property can not yet be set with `org-entry-put'"
13063 property))
13064 (t ; a non-special property
13065 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
13066 (setq range (org-get-property-block beg end 'force))
13067 (goto-char (car range))
13068 (if (re-search-forward
13069 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
13070 (progn
13071 (delete-region (match-beginning 1) (match-end 1))
13072 (goto-char (match-beginning 1)))
13073 (goto-char (cdr range))
13074 (insert "\n")
13075 (backward-char 1)
13076 (org-indent-line-function)
13077 (insert ":" property ":"))
13078 (and value (insert " " value))
13079 (org-indent-line-function)))))
13080 (run-hook-with-args 'org-property-changed-functions property value)))
13081
13082 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
13083 "Get all property keys in the current buffer.
13084 With INCLUDE-SPECIALS, also list the special properties that reflect things
13085 like tags and TODO state.
13086 With INCLUDE-DEFAULTS, also include properties that has special meaning
13087 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
13088 With INCLUDE-COLUMNS, also include property names given in COLUMN
13089 formats in the current buffer."
13090 (let (rtn range cfmt s p)
13091 (save-excursion
13092 (save-restriction
13093 (widen)
13094 (goto-char (point-min))
13095 (while (re-search-forward org-property-start-re nil t)
13096 (setq range (org-get-property-block))
13097 (goto-char (car range))
13098 (while (re-search-forward
13099 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
13100 (cdr range) t)
13101 (add-to-list 'rtn (org-match-string-no-properties 1)))
13102 (outline-next-heading))))
13103
13104 (when include-specials
13105 (setq rtn (append org-special-properties rtn)))
13106
13107 (when include-defaults
13108 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
13109 (add-to-list 'rtn org-effort-property))
13110
13111 (when include-columns
13112 (save-excursion
13113 (save-restriction
13114 (widen)
13115 (goto-char (point-min))
13116 (while (re-search-forward
13117 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
13118 nil t)
13119 (setq cfmt (match-string 2) s 0)
13120 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
13121 cfmt s)
13122 (setq s (match-end 0)
13123 p (match-string 1 cfmt))
13124 (unless (or (equal p "ITEM")
13125 (member p org-special-properties))
13126 (add-to-list 'rtn (match-string 1 cfmt))))))))
13127
13128 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
13129
13130 (defun org-property-values (key)
13131 "Return a list of all values of property KEY."
13132 (save-excursion
13133 (save-restriction
13134 (widen)
13135 (goto-char (point-min))
13136 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
13137 values)
13138 (while (re-search-forward re nil t)
13139 (add-to-list 'values (org-trim (match-string 1))))
13140 (delete "" values)))))
13141
13142 (defun org-insert-property-drawer ()
13143 "Insert a property drawer into the current entry."
13144 (interactive)
13145 (org-back-to-heading t)
13146 (looking-at outline-regexp)
13147 (let ((indent (if org-adapt-indentation
13148 (- (match-end 0)(match-beginning 0))
13149 0))
13150 (beg (point))
13151 (re (concat "^[ \t]*" org-keyword-time-regexp))
13152 end hiddenp)
13153 (outline-next-heading)
13154 (setq end (point))
13155 (goto-char beg)
13156 (while (re-search-forward re end t))
13157 (setq hiddenp (org-invisible-p))
13158 (end-of-line 1)
13159 (and (equal (char-after) ?\n) (forward-char 1))
13160 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
13161 (if (member (match-string 1) '("CLOCK:" ":END:"))
13162 ;; just skip this line
13163 (beginning-of-line 2)
13164 ;; Drawer start, find the end
13165 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
13166 (beginning-of-line 1)))
13167 (org-skip-over-state-notes)
13168 (skip-chars-backward " \t\n\r")
13169 (if (eq (char-before) ?*) (forward-char 1))
13170 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
13171 (beginning-of-line 0)
13172 (org-indent-to-column indent)
13173 (beginning-of-line 2)
13174 (org-indent-to-column indent)
13175 (beginning-of-line 0)
13176 (if hiddenp
13177 (save-excursion
13178 (org-back-to-heading t)
13179 (hide-entry))
13180 (org-flag-drawer t))))
13181
13182 (defun org-set-property (property value)
13183 "In the current entry, set PROPERTY to VALUE.
13184 When called interactively, this will prompt for a property name, offering
13185 completion on existing and default properties. And then it will prompt
13186 for a value, offering completion either on allowed values (via an inherited
13187 xxx_ALL property) or on existing values in other instances of this property
13188 in the current file."
13189 (interactive
13190 (let* ((completion-ignore-case t)
13191 (keys (org-buffer-property-keys nil t t))
13192 (prop0 (org-icompleting-read "Property: " (mapcar 'list keys)))
13193 (prop (if (member prop0 keys)
13194 prop0
13195 (or (cdr (assoc (downcase prop0)
13196 (mapcar (lambda (x) (cons (downcase x) x))
13197 keys)))
13198 prop0)))
13199 (cur (org-entry-get nil prop))
13200 (prompt (concat prop " value"
13201 (if (and cur (string-match "\\S-" cur))
13202 (concat " [" cur "]") "") ": "))
13203 (allowed (org-property-get-allowed-values nil prop 'table))
13204 (existing (mapcar 'list (org-property-values prop)))
13205 (val (if allowed
13206 (org-completing-read prompt allowed nil
13207 (not (get-text-property 0 'org-unrestricted
13208 (caar allowed))))
13209 (let (org-completion-use-ido org-completion-use-iswitchb)
13210 (org-completing-read prompt existing nil nil "" nil cur)))))
13211 (list prop (if (equal val "") cur val))))
13212 (unless (equal (org-entry-get nil property) value)
13213 (org-entry-put nil property value)))
13214
13215 (defun org-delete-property (property)
13216 "In the current entry, delete PROPERTY."
13217 (interactive
13218 (let* ((completion-ignore-case t)
13219 (prop (org-icompleting-read "Property: " (org-entry-properties nil 'standard))))
13220 (list prop)))
13221 (message "Property %s %s" property
13222 (if (org-entry-delete nil property)
13223 "deleted"
13224 "was not present in the entry")))
13225
13226 (defun org-delete-property-globally (property)
13227 "Remove PROPERTY globally, from all entries."
13228 (interactive
13229 (let* ((completion-ignore-case t)
13230 (prop (org-icompleting-read
13231 "Globally remove property: "
13232 (mapcar 'list (org-buffer-property-keys)))))
13233 (list prop)))
13234 (save-excursion
13235 (save-restriction
13236 (widen)
13237 (goto-char (point-min))
13238 (let ((cnt 0))
13239 (while (re-search-forward
13240 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
13241 nil t)
13242 (setq cnt (1+ cnt))
13243 (replace-match ""))
13244 (message "Property \"%s\" removed from %d entries" property cnt)))))
13245
13246 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
13247
13248 (defun org-compute-property-at-point ()
13249 "Compute the property at point.
13250 This looks for an enclosing column format, extracts the operator and
13251 then applies it to the property in the column format's scope."
13252 (interactive)
13253 (unless (org-at-property-p)
13254 (error "Not at a property"))
13255 (let ((prop (org-match-string-no-properties 2)))
13256 (org-columns-get-format-and-top-level)
13257 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
13258 (error "No operator defined for property %s" prop))
13259 (org-columns-compute prop)))
13260
13261 (defvar org-property-allowed-value-functions nil
13262 "Hook for functions supplying allowed values for a specific property.
13263 The functions must take a single argument, the name of the property, and
13264 return a flat list of allowed values. If \":ETC\" is one of
13265 the values, this means that these values are intended as defaults for
13266 completion, but that other values should be allowed too.
13267 The functions must return nil if they are not responsible for this
13268 property.")
13269
13270 (defun org-property-get-allowed-values (pom property &optional table)
13271 "Get allowed values for the property PROPERTY.
13272 When TABLE is non-nil, return an alist that can directly be used for
13273 completion."
13274 (let (vals)
13275 (cond
13276 ((equal property "TODO")
13277 (setq vals (org-with-point-at pom
13278 (append org-todo-keywords-1 '("")))))
13279 ((equal property "PRIORITY")
13280 (let ((n org-lowest-priority))
13281 (while (>= n org-highest-priority)
13282 (push (char-to-string n) vals)
13283 (setq n (1- n)))))
13284 ((member property org-special-properties))
13285 ((setq vals (run-hook-with-args-until-success
13286 'org-property-allowed-value-functions property)))
13287 (t
13288 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
13289 (when (and vals (string-match "\\S-" vals))
13290 (setq vals (car (read-from-string (concat "(" vals ")"))))
13291 (setq vals (mapcar (lambda (x)
13292 (cond ((stringp x) x)
13293 ((numberp x) (number-to-string x))
13294 ((symbolp x) (symbol-name x))
13295 (t "???")))
13296 vals)))))
13297 (when (member ":ETC" vals)
13298 (setq vals (remove ":ETC" vals))
13299 (org-add-props (car vals) '(org-unrestricted t)))
13300 (if table (mapcar 'list vals) vals)))
13301
13302 (defun org-property-previous-allowed-value (&optional previous)
13303 "Switch to the next allowed value for this property."
13304 (interactive)
13305 (org-property-next-allowed-value t))
13306
13307 (defun org-property-next-allowed-value (&optional previous)
13308 "Switch to the next allowed value for this property."
13309 (interactive)
13310 (unless (org-at-property-p)
13311 (error "Not at a property"))
13312 (let* ((key (match-string 2))
13313 (value (match-string 3))
13314 (allowed (or (org-property-get-allowed-values (point) key)
13315 (and (member value '("[ ]" "[-]" "[X]"))
13316 '("[ ]" "[X]"))))
13317 nval)
13318 (unless allowed
13319 (error "Allowed values for this property have not been defined"))
13320 (if previous (setq allowed (reverse allowed)))
13321 (if (member value allowed)
13322 (setq nval (car (cdr (member value allowed)))))
13323 (setq nval (or nval (car allowed)))
13324 (if (equal nval value)
13325 (error "Only one allowed value for this property"))
13326 (org-at-property-p)
13327 (replace-match (concat " :" key ": " nval) t t)
13328 (org-indent-line-function)
13329 (beginning-of-line 1)
13330 (skip-chars-forward " \t")
13331 (run-hook-with-args 'org-property-changed-functions key nval)))
13332
13333 (defun org-find-entry-with-id (ident)
13334 "Locate the entry that contains the ID property with exact value IDENT.
13335 IDENT can be a string, a symbol or a number, this function will search for
13336 the string representation of it.
13337 Return the position where this entry starts, or nil if there is no such entry."
13338 (interactive "sID: ")
13339 (let ((id (cond
13340 ((stringp ident) ident)
13341 ((symbol-name ident) (symbol-name ident))
13342 ((numberp ident) (number-to-string ident))
13343 (t (error "IDENT %s must be a string, symbol or number" ident))))
13344 (case-fold-search nil))
13345 (save-excursion
13346 (save-restriction
13347 (widen)
13348 (goto-char (point-min))
13349 (when (re-search-forward
13350 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
13351 nil t)
13352 (org-back-to-heading t)
13353 (point))))))
13354
13355 ;;;; Timestamps
13356
13357 (defvar org-last-changed-timestamp nil)
13358 (defvar org-last-inserted-timestamp nil
13359 "The last time stamp inserted with `org-insert-time-stamp'.")
13360 (defvar org-time-was-given) ; dynamically scoped parameter
13361 (defvar org-end-time-was-given) ; dynamically scoped parameter
13362 (defvar org-ts-what) ; dynamically scoped parameter
13363
13364 (defun org-time-stamp (arg &optional inactive)
13365 "Prompt for a date/time and insert a time stamp.
13366 If the user specifies a time like HH:MM, or if this command is called
13367 with a prefix argument, the time stamp will contain date and time.
13368 Otherwise, only the date will be included. All parts of a date not
13369 specified by the user will be filled in from the current date/time.
13370 So if you press just return without typing anything, the time stamp
13371 will represent the current date/time. If there is already a timestamp
13372 at the cursor, it will be modified."
13373 (interactive "P")
13374 (let* ((ts nil)
13375 (default-time
13376 ;; Default time is either today, or, when entering a range,
13377 ;; the range start.
13378 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
13379 (save-excursion
13380 (re-search-backward
13381 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
13382 (- (point) 20) t)))
13383 (apply 'encode-time (org-parse-time-string (match-string 1)))
13384 (current-time)))
13385 (default-input (and ts (org-get-compact-tod ts)))
13386 org-time-was-given org-end-time-was-given time)
13387 (cond
13388 ((and (org-at-timestamp-p t)
13389 (memq last-command '(org-time-stamp org-time-stamp-inactive))
13390 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
13391 (insert "--")
13392 (setq time (let ((this-command this-command))
13393 (org-read-date arg 'totime nil nil
13394 default-time default-input)))
13395 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
13396 ((org-at-timestamp-p t)
13397 (setq time (let ((this-command this-command))
13398 (org-read-date arg 'totime nil nil default-time default-input)))
13399 (when (org-at-timestamp-p t) ; just to get the match data
13400 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
13401 (replace-match "")
13402 (setq org-last-changed-timestamp
13403 (org-insert-time-stamp
13404 time (or org-time-was-given arg)
13405 inactive nil nil (list org-end-time-was-given))))
13406 (message "Timestamp updated"))
13407 (t
13408 (setq time (let ((this-command this-command))
13409 (org-read-date arg 'totime nil nil default-time default-input)))
13410 (org-insert-time-stamp time (or org-time-was-given arg) inactive
13411 nil nil (list org-end-time-was-given))))))
13412
13413 ;; FIXME: can we use this for something else, like computing time differences?
13414 (defun org-get-compact-tod (s)
13415 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
13416 (let* ((t1 (match-string 1 s))
13417 (h1 (string-to-number (match-string 2 s)))
13418 (m1 (string-to-number (match-string 3 s)))
13419 (t2 (and (match-end 4) (match-string 5 s)))
13420 (h2 (and t2 (string-to-number (match-string 6 s))))
13421 (m2 (and t2 (string-to-number (match-string 7 s))))
13422 dh dm)
13423 (if (not t2)
13424 t1
13425 (setq dh (- h2 h1) dm (- m2 m1))
13426 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
13427 (concat t1 "+" (number-to-string dh)
13428 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
13429
13430 (defun org-time-stamp-inactive (&optional arg)
13431 "Insert an inactive time stamp.
13432 An inactive time stamp is enclosed in square brackets instead of angle
13433 brackets. It is inactive in the sense that it does not trigger agenda entries,
13434 does not link to the calendar and cannot be changed with the S-cursor keys.
13435 So these are more for recording a certain time/date."
13436 (interactive "P")
13437 (org-time-stamp arg 'inactive))
13438
13439 (defvar org-date-ovl (org-make-overlay 1 1))
13440 (org-overlay-put org-date-ovl 'face 'org-warning)
13441 (org-detach-overlay org-date-ovl)
13442
13443 (defvar org-ans1) ; dynamically scoped parameter
13444 (defvar org-ans2) ; dynamically scoped parameter
13445
13446 (defvar org-plain-time-of-day-regexp) ; defined below
13447
13448 (defvar org-overriding-default-time nil) ; dynamically scoped
13449 (defvar org-read-date-overlay nil)
13450 (defvar org-dcst nil) ; dynamically scoped
13451 (defvar org-read-date-history nil)
13452 (defvar org-read-date-final-answer nil)
13453
13454 (defun org-read-date (&optional with-time to-time from-string prompt
13455 default-time default-input)
13456 "Read a date, possibly a time, and make things smooth for the user.
13457 The prompt will suggest to enter an ISO date, but you can also enter anything
13458 which will at least partially be understood by `parse-time-string'.
13459 Unrecognized parts of the date will default to the current day, month, year,
13460 hour and minute. If this command is called to replace a timestamp at point,
13461 of to enter the second timestamp of a range, the default time is taken from the
13462 existing stamp. For example,
13463 3-2-5 --> 2003-02-05
13464 feb 15 --> currentyear-02-15
13465 sep 12 9 --> 2009-09-12
13466 12:45 --> today 12:45
13467 22 sept 0:34 --> currentyear-09-22 0:34
13468 12 --> currentyear-currentmonth-12
13469 Fri --> nearest Friday (today or later)
13470 etc.
13471
13472 Furthermore you can specify a relative date by giving, as the *first* thing
13473 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
13474 change in days weeks, months, years.
13475 With a single plus or minus, the date is relative to today. With a double
13476 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
13477 +4d --> four days from today
13478 +4 --> same as above
13479 +2w --> two weeks from today
13480 ++5 --> five days from default date
13481
13482 The function understands only English month and weekday abbreviations,
13483 but this can be configured with the variables `parse-time-months' and
13484 `parse-time-weekdays'.
13485
13486 While prompting, a calendar is popped up - you can also select the
13487 date with the mouse (button 1). The calendar shows a period of three
13488 months. To scroll it to other months, use the keys `>' and `<'.
13489 If you don't like the calendar, turn it off with
13490 \(setq org-read-date-popup-calendar nil)
13491
13492 With optional argument TO-TIME, the date will immediately be converted
13493 to an internal time.
13494 With an optional argument WITH-TIME, the prompt will suggest to also
13495 insert a time. Note that when WITH-TIME is not set, you can still
13496 enter a time, and this function will inform the calling routine about
13497 this change. The calling routine may then choose to change the format
13498 used to insert the time stamp into the buffer to include the time.
13499 With optional argument FROM-STRING, read from this string instead from
13500 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
13501 the time/date that is used for everything that is not specified by the
13502 user."
13503 (require 'parse-time)
13504 (let* ((org-time-stamp-rounding-minutes
13505 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
13506 (org-dcst org-display-custom-times)
13507 (ct (org-current-time))
13508 (def (or org-overriding-default-time default-time ct))
13509 (defdecode (decode-time def))
13510 (dummy (progn
13511 (when (< (nth 2 defdecode) org-extend-today-until)
13512 (setcar (nthcdr 2 defdecode) -1)
13513 (setcar (nthcdr 1 defdecode) 59)
13514 (setq def (apply 'encode-time defdecode)
13515 defdecode (decode-time def)))))
13516 (calendar-frame-setup nil)
13517 (calendar-move-hook nil)
13518 (calendar-view-diary-initially-flag nil)
13519 (view-diary-entries-initially nil)
13520 (calendar-view-holidays-initially-flag nil)
13521 (view-calendar-holidays-initially nil)
13522 (timestr (format-time-string
13523 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
13524 (prompt (concat (if prompt (concat prompt " ") "")
13525 (format "Date+time [%s]: " timestr)))
13526 ans (org-ans0 "") org-ans1 org-ans2 final)
13527
13528 (cond
13529 (from-string (setq ans from-string))
13530 (org-read-date-popup-calendar
13531 (save-excursion
13532 (save-window-excursion
13533 (calendar)
13534 (calendar-forward-day (- (time-to-days def)
13535 (calendar-absolute-from-gregorian
13536 (calendar-current-date))))
13537 (org-eval-in-calendar nil t)
13538 (let* ((old-map (current-local-map))
13539 (map (copy-keymap calendar-mode-map))
13540 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
13541 (org-defkey map (kbd "RET") 'org-calendar-select)
13542 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
13543 'org-calendar-select-mouse)
13544 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
13545 'org-calendar-select-mouse)
13546 (org-defkey minibuffer-local-map [(meta shift left)]
13547 (lambda () (interactive)
13548 (org-eval-in-calendar '(calendar-backward-month 1))))
13549 (org-defkey minibuffer-local-map [(meta shift right)]
13550 (lambda () (interactive)
13551 (org-eval-in-calendar '(calendar-forward-month 1))))
13552 (org-defkey minibuffer-local-map [(meta shift up)]
13553 (lambda () (interactive)
13554 (org-eval-in-calendar '(calendar-backward-year 1))))
13555 (org-defkey minibuffer-local-map [(meta shift down)]
13556 (lambda () (interactive)
13557 (org-eval-in-calendar '(calendar-forward-year 1))))
13558 (org-defkey minibuffer-local-map [?\e (shift left)]
13559 (lambda () (interactive)
13560 (org-eval-in-calendar '(calendar-backward-month 1))))
13561 (org-defkey minibuffer-local-map [?\e (shift right)]
13562 (lambda () (interactive)
13563 (org-eval-in-calendar '(calendar-forward-month 1))))
13564 (org-defkey minibuffer-local-map [?\e (shift up)]
13565 (lambda () (interactive)
13566 (org-eval-in-calendar '(calendar-backward-year 1))))
13567 (org-defkey minibuffer-local-map [?\e (shift down)]
13568 (lambda () (interactive)
13569 (org-eval-in-calendar '(calendar-forward-year 1))))
13570 (org-defkey minibuffer-local-map [(shift up)]
13571 (lambda () (interactive)
13572 (org-eval-in-calendar '(calendar-backward-week 1))))
13573 (org-defkey minibuffer-local-map [(shift down)]
13574 (lambda () (interactive)
13575 (org-eval-in-calendar '(calendar-forward-week 1))))
13576 (org-defkey minibuffer-local-map [(shift left)]
13577 (lambda () (interactive)
13578 (org-eval-in-calendar '(calendar-backward-day 1))))
13579 (org-defkey minibuffer-local-map [(shift right)]
13580 (lambda () (interactive)
13581 (org-eval-in-calendar '(calendar-forward-day 1))))
13582 (org-defkey minibuffer-local-map ">"
13583 (lambda () (interactive)
13584 (org-eval-in-calendar '(scroll-calendar-left 1))))
13585 (org-defkey minibuffer-local-map "<"
13586 (lambda () (interactive)
13587 (org-eval-in-calendar '(scroll-calendar-right 1))))
13588 (run-hooks 'org-read-date-minibuffer-setup-hook)
13589 (unwind-protect
13590 (progn
13591 (use-local-map map)
13592 (add-hook 'post-command-hook 'org-read-date-display)
13593 (setq org-ans0 (read-string prompt default-input
13594 'org-read-date-history nil))
13595 ;; org-ans0: from prompt
13596 ;; org-ans1: from mouse click
13597 ;; org-ans2: from calendar motion
13598 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
13599 (remove-hook 'post-command-hook 'org-read-date-display)
13600 (use-local-map old-map)
13601 (when org-read-date-overlay
13602 (org-delete-overlay org-read-date-overlay)
13603 (setq org-read-date-overlay nil)))))))
13604
13605 (t ; Naked prompt only
13606 (unwind-protect
13607 (setq ans (read-string prompt default-input
13608 'org-read-date-history timestr))
13609 (when org-read-date-overlay
13610 (org-delete-overlay org-read-date-overlay)
13611 (setq org-read-date-overlay nil)))))
13612
13613 (setq final (org-read-date-analyze ans def defdecode))
13614 (setq org-read-date-final-answer ans)
13615
13616 (if to-time
13617 (apply 'encode-time final)
13618 (if (and (boundp 'org-time-was-given) org-time-was-given)
13619 (format "%04d-%02d-%02d %02d:%02d"
13620 (nth 5 final) (nth 4 final) (nth 3 final)
13621 (nth 2 final) (nth 1 final))
13622 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
13623
13624 (defvar def)
13625 (defvar defdecode)
13626 (defvar with-time)
13627 (defvar org-read-date-analyze-futurep nil)
13628 (defun org-read-date-display ()
13629 "Display the current date prompt interpretation in the minibuffer."
13630 (when org-read-date-display-live
13631 (when org-read-date-overlay
13632 (org-delete-overlay org-read-date-overlay))
13633 (let ((p (point)))
13634 (end-of-line 1)
13635 (while (not (equal (buffer-substring
13636 (max (point-min) (- (point) 4)) (point))
13637 " "))
13638 (insert " "))
13639 (goto-char p))
13640 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
13641 " " (or org-ans1 org-ans2)))
13642 (org-end-time-was-given nil)
13643 (f (org-read-date-analyze ans def defdecode))
13644 (fmts (if org-dcst
13645 org-time-stamp-custom-formats
13646 org-time-stamp-formats))
13647 (fmt (if (or with-time
13648 (and (boundp 'org-time-was-given) org-time-was-given))
13649 (cdr fmts)
13650 (car fmts)))
13651 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
13652 (when (and org-end-time-was-given
13653 (string-match org-plain-time-of-day-regexp txt))
13654 (setq txt (concat (substring txt 0 (match-end 0)) "-"
13655 org-end-time-was-given
13656 (substring txt (match-end 0)))))
13657 (when org-read-date-analyze-futurep
13658 (setq txt (concat txt " (=>F)")))
13659 (setq org-read-date-overlay
13660 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
13661 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
13662
13663 (defun org-read-date-analyze (ans def defdecode)
13664 "Analyse the combined answer of the date prompt."
13665 ;; FIXME: cleanup and comment
13666 (let ((nowdecode (decode-time (current-time)))
13667 delta deltan deltaw deltadef year month day
13668 hour minute second wday pm h2 m2 tl wday1
13669 iso-year iso-weekday iso-week iso-year iso-date futurep kill-year)
13670 (setq org-read-date-analyze-futurep nil)
13671 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
13672 (setq ans "+0"))
13673
13674 (when (setq delta (org-read-date-get-relative ans (current-time) def))
13675 (setq ans (replace-match "" t t ans)
13676 deltan (car delta)
13677 deltaw (nth 1 delta)
13678 deltadef (nth 2 delta)))
13679
13680 ;; Check if there is an iso week date in there
13681 ;; If yes, store the info and postpone interpreting it until the rest
13682 ;; of the parsing is done
13683 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
13684 (setq iso-year (if (match-end 1)
13685 (org-small-year-to-year
13686 (string-to-number (match-string 1 ans))))
13687 iso-weekday (if (match-end 3)
13688 (string-to-number (match-string 3 ans)))
13689 iso-week (string-to-number (match-string 2 ans)))
13690 (setq ans (replace-match "" t t ans)))
13691
13692 ;; Help matching ISO dates with single digit month or day, like 2006-8-11.
13693 (when (string-match
13694 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
13695 (setq year (if (match-end 2)
13696 (string-to-number (match-string 2 ans))
13697 (progn (setq kill-year t)
13698 (string-to-number (format-time-string "%Y"))))
13699 month (string-to-number (match-string 3 ans))
13700 day (string-to-number (match-string 4 ans)))
13701 (if (< year 100) (setq year (+ 2000 year)))
13702 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13703 t nil ans)))
13704 ;; Help matching american dates, like 5/30 or 5/30/7
13705 (when (string-match
13706 "^ *\\([0-3]?[0-9]\\)/\\([0-1]?[0-9]\\)\\(/\\([0-9]+\\)\\)?\\([^/0-9]\\|$\\)" ans)
13707 (setq year (if (match-end 4)
13708 (string-to-number (match-string 4 ans))
13709 (progn (setq kill-year t)
13710 (string-to-number (format-time-string "%Y"))))
13711 month (string-to-number (match-string 1 ans))
13712 day (string-to-number (match-string 2 ans)))
13713 (if (< year 100) (setq year (+ 2000 year)))
13714 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
13715 t nil ans)))
13716 ;; Help matching am/pm times, because `parse-time-string' does not do that.
13717 ;; If there is a time with am/pm, and *no* time without it, we convert
13718 ;; so that matching will be successful.
13719 (loop for i from 1 to 2 do ; twice, for end time as well
13720 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
13721 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
13722 (setq hour (string-to-number (match-string 1 ans))
13723 minute (if (match-end 3)
13724 (string-to-number (match-string 3 ans))
13725 0)
13726 pm (equal ?p
13727 (string-to-char (downcase (match-string 4 ans)))))
13728 (if (and (= hour 12) (not pm))
13729 (setq hour 0)
13730 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
13731 (setq ans (replace-match (format "%02d:%02d" hour minute)
13732 t t ans))))
13733
13734 ;; Check if a time range is given as a duration
13735 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
13736 (setq hour (string-to-number (match-string 1 ans))
13737 h2 (+ hour (string-to-number (match-string 3 ans)))
13738 minute (string-to-number (match-string 2 ans))
13739 m2 (+ minute (if (match-end 5) (string-to-number
13740 (match-string 5 ans))0)))
13741 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
13742 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
13743 t t ans)))
13744
13745 ;; Check if there is a time range
13746 (when (boundp 'org-end-time-was-given)
13747 (setq org-time-was-given nil)
13748 (when (and (string-match org-plain-time-of-day-regexp ans)
13749 (match-end 8))
13750 (setq org-end-time-was-given (match-string 8 ans))
13751 (setq ans (concat (substring ans 0 (match-beginning 7))
13752 (substring ans (match-end 7))))))
13753
13754 (setq tl (parse-time-string ans)
13755 day (or (nth 3 tl) (nth 3 defdecode))
13756 month (or (nth 4 tl)
13757 (if (and org-read-date-prefer-future
13758 (nth 3 tl) (< (nth 3 tl) (nth 3 nowdecode)))
13759 (prog1 (1+ (nth 4 nowdecode)) (setq futurep t))
13760 (nth 4 defdecode)))
13761 year (or (and (not kill-year) (nth 5 tl))
13762 (if (and org-read-date-prefer-future
13763 (nth 4 tl) (< (nth 4 tl) (nth 4 nowdecode)))
13764 (prog1 (1+ (nth 5 nowdecode)) (setq futurep t))
13765 (nth 5 defdecode)))
13766 hour (or (nth 2 tl) (nth 2 defdecode))
13767 minute (or (nth 1 tl) (nth 1 defdecode))
13768 second (or (nth 0 tl) 0)
13769 wday (nth 6 tl))
13770
13771 (when (and (eq org-read-date-prefer-future 'time)
13772 (not (nth 3 tl)) (not (nth 4 tl)) (not (nth 5 tl))
13773 (equal day (nth 3 nowdecode))
13774 (equal month (nth 4 nowdecode))
13775 (equal year (nth 5 nowdecode))
13776 (nth 2 tl)
13777 (or (< (nth 2 tl) (nth 2 nowdecode))
13778 (and (= (nth 2 tl) (nth 2 nowdecode))
13779 (nth 1 tl)
13780 (< (nth 1 tl) (nth 1 nowdecode)))))
13781 (setq day (1+ day)
13782 futurep t))
13783
13784 ;; Special date definitions below
13785 (cond
13786 (iso-week
13787 ;; There was an iso week
13788 (require 'cal-iso)
13789 (setq futurep nil)
13790 (setq year (or iso-year year)
13791 day (or iso-weekday wday 1)
13792 wday nil ; to make sure that the trigger below does not match
13793 iso-date (calendar-gregorian-from-absolute
13794 (calendar-absolute-from-iso
13795 (list iso-week day year))))
13796 ; FIXME: Should we also push ISO weeks into the future?
13797 ; (when (and org-read-date-prefer-future
13798 ; (not iso-year)
13799 ; (< (calendar-absolute-from-gregorian iso-date)
13800 ; (time-to-days (current-time))))
13801 ; (setq year (1+ year)
13802 ; iso-date (calendar-gregorian-from-absolute
13803 ; (calendar-absolute-from-iso
13804 ; (list iso-week day year)))))
13805 (setq month (car iso-date)
13806 year (nth 2 iso-date)
13807 day (nth 1 iso-date)))
13808 (deltan
13809 (setq futurep nil)
13810 (unless deltadef
13811 (let ((now (decode-time (current-time))))
13812 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
13813 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
13814 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
13815 ((equal deltaw "m") (setq month (+ month deltan)))
13816 ((equal deltaw "y") (setq year (+ year deltan)))))
13817 ((and wday (not (nth 3 tl)))
13818 (setq futurep nil)
13819 ;; Weekday was given, but no day, so pick that day in the week
13820 ;; on or after the derived date.
13821 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
13822 (unless (equal wday wday1)
13823 (setq day (+ day (% (- wday wday1 -7) 7))))))
13824 (if (and (boundp 'org-time-was-given)
13825 (nth 2 tl))
13826 (setq org-time-was-given t))
13827 (if (< year 100) (setq year (+ 2000 year)))
13828 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
13829 (setq org-read-date-analyze-futurep futurep)
13830 (list second minute hour day month year)))
13831
13832 (defvar parse-time-weekdays)
13833
13834 (defun org-read-date-get-relative (s today default)
13835 "Check string S for special relative date string.
13836 TODAY and DEFAULT are internal times, for today and for a default.
13837 Return shift list (N what def-flag)
13838 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
13839 N is the number of WHATs to shift.
13840 DEF-FLAG is t when a double ++ or -- indicates shift relative to
13841 the DEFAULT date rather than TODAY."
13842 (when (and
13843 (string-match
13844 (concat
13845 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
13846 "\\([0-9]+\\)?"
13847 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
13848 "\\([ \t]\\|$\\)") s)
13849 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
13850 (let* ((dir (if (> (match-end 1) (match-beginning 1))
13851 (string-to-char (substring (match-string 1 s) -1))
13852 ?+))
13853 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
13854 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
13855 (what (if (match-end 3) (match-string 3 s) "d"))
13856 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
13857 (date (if rel default today))
13858 (wday (nth 6 (decode-time date)))
13859 delta)
13860 (if wday1
13861 (progn
13862 (setq delta (mod (+ 7 (- wday1 wday)) 7))
13863 (if (= dir ?-) (setq delta (- delta 7)))
13864 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
13865 (list delta "d" rel))
13866 (list (* n (if (= dir ?-) -1 1)) what rel)))))
13867
13868 (defun org-order-calendar-date-args (arg1 arg2 arg3)
13869 "Turn a user-specified date into the internal representation.
13870 The internal representation needed by the calendar is (month day year).
13871 This is a wrapper to handle the brain-dead convention in calendar that
13872 user function argument order change dependent on argument order."
13873 (if (boundp 'calendar-date-style)
13874 (cond
13875 ((eq calendar-date-style 'american)
13876 (list arg1 arg2 arg3))
13877 ((eq calendar-date-style 'european)
13878 (list arg2 arg1 arg3))
13879 ((eq calendar-date-style 'iso)
13880 (list arg2 arg3 arg1)))
13881 (if (org-bound-and-true-p european-calendar-style)
13882 (list arg2 arg1 arg3)
13883 (list arg1 arg2 arg3))))
13884
13885 (defun org-eval-in-calendar (form &optional keepdate)
13886 "Eval FORM in the calendar window and return to current window.
13887 Also, store the cursor date in variable org-ans2."
13888 (let ((sf (selected-frame))
13889 (sw (selected-window)))
13890 (select-window (get-buffer-window "*Calendar*" t))
13891 (eval form)
13892 (when (and (not keepdate) (calendar-cursor-to-date))
13893 (let* ((date (calendar-cursor-to-date))
13894 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13895 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
13896 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
13897 (select-window sw)
13898 (org-select-frame-set-input-focus sf)))
13899
13900 (defun org-calendar-select ()
13901 "Return to `org-read-date' with the date currently selected.
13902 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
13903 (interactive)
13904 (when (calendar-cursor-to-date)
13905 (let* ((date (calendar-cursor-to-date))
13906 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13907 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
13908 (if (active-minibuffer-window) (exit-minibuffer))))
13909
13910 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
13911 "Insert a date stamp for the date given by the internal TIME.
13912 WITH-HM means use the stamp format that includes the time of the day.
13913 INACTIVE means use square brackets instead of angular ones, so that the
13914 stamp will not contribute to the agenda.
13915 PRE and POST are optional strings to be inserted before and after the
13916 stamp.
13917 The command returns the inserted time stamp."
13918 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
13919 stamp)
13920 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
13921 (insert-before-markers (or pre ""))
13922 (insert-before-markers (setq stamp (format-time-string fmt time)))
13923 (when (listp extra)
13924 (setq extra (car extra))
13925 (if (and (stringp extra)
13926 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
13927 (setq extra (format "-%02d:%02d"
13928 (string-to-number (match-string 1 extra))
13929 (string-to-number (match-string 2 extra))))
13930 (setq extra nil)))
13931 (when extra
13932 (backward-char 1)
13933 (insert-before-markers extra)
13934 (forward-char 1))
13935 (insert-before-markers (or post ""))
13936 (setq org-last-inserted-timestamp stamp)))
13937
13938 (defun org-toggle-time-stamp-overlays ()
13939 "Toggle the use of custom time stamp formats."
13940 (interactive)
13941 (setq org-display-custom-times (not org-display-custom-times))
13942 (unless org-display-custom-times
13943 (let ((p (point-min)) (bmp (buffer-modified-p)))
13944 (while (setq p (next-single-property-change p 'display))
13945 (if (and (get-text-property p 'display)
13946 (eq (get-text-property p 'face) 'org-date))
13947 (remove-text-properties
13948 p (setq p (next-single-property-change p 'display))
13949 '(display t))))
13950 (set-buffer-modified-p bmp)))
13951 (if (featurep 'xemacs)
13952 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
13953 (org-restart-font-lock)
13954 (setq org-table-may-need-update t)
13955 (if org-display-custom-times
13956 (message "Time stamps are overlayed with custom format")
13957 (message "Time stamp overlays removed")))
13958
13959 (defun org-display-custom-time (beg end)
13960 "Overlay modified time stamp format over timestamp between BEG and END."
13961 (let* ((ts (buffer-substring beg end))
13962 t1 w1 with-hm tf time str w2 (off 0))
13963 (save-match-data
13964 (setq t1 (org-parse-time-string ts t))
13965 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)?\\'" ts)
13966 (setq off (- (match-end 0) (match-beginning 0)))))
13967 (setq end (- end off))
13968 (setq w1 (- end beg)
13969 with-hm (and (nth 1 t1) (nth 2 t1))
13970 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
13971 time (org-fix-decoded-time t1)
13972 str (org-add-props
13973 (format-time-string
13974 (substring tf 1 -1) (apply 'encode-time time))
13975 nil 'mouse-face 'highlight)
13976 w2 (length str))
13977 (if (not (= w2 w1))
13978 (add-text-properties (1+ beg) (+ 2 beg)
13979 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
13980 (if (featurep 'xemacs)
13981 (progn
13982 (put-text-property beg end 'invisible t)
13983 (put-text-property beg end 'end-glyph (make-glyph str)))
13984 (put-text-property beg end 'display str))))
13985
13986 (defun org-translate-time (string)
13987 "Translate all timestamps in STRING to custom format.
13988 But do this only if the variable `org-display-custom-times' is set."
13989 (when org-display-custom-times
13990 (save-match-data
13991 (let* ((start 0)
13992 (re org-ts-regexp-both)
13993 t1 with-hm inactive tf time str beg end)
13994 (while (setq start (string-match re string start))
13995 (setq beg (match-beginning 0)
13996 end (match-end 0)
13997 t1 (save-match-data
13998 (org-parse-time-string (substring string beg end) t))
13999 with-hm (and (nth 1 t1) (nth 2 t1))
14000 inactive (equal (substring string beg (1+ beg)) "[")
14001 tf (funcall (if with-hm 'cdr 'car)
14002 org-time-stamp-custom-formats)
14003 time (org-fix-decoded-time t1)
14004 str (format-time-string
14005 (concat
14006 (if inactive "[" "<") (substring tf 1 -1)
14007 (if inactive "]" ">"))
14008 (apply 'encode-time time))
14009 string (replace-match str t t string)
14010 start (+ start (length str)))))))
14011 string)
14012
14013 (defun org-fix-decoded-time (time)
14014 "Set 0 instead of nil for the first 6 elements of time.
14015 Don't touch the rest."
14016 (let ((n 0))
14017 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
14018
14019 (defun org-days-to-time (timestamp-string)
14020 "Difference between TIMESTAMP-STRING and now in days."
14021 (- (time-to-days (org-time-string-to-time timestamp-string))
14022 (time-to-days (current-time))))
14023
14024 (defun org-deadline-close (timestamp-string &optional ndays)
14025 "Is the time in TIMESTAMP-STRING close to the current date?"
14026 (setq ndays (or ndays (org-get-wdays timestamp-string)))
14027 (and (< (org-days-to-time timestamp-string) ndays)
14028 (not (org-entry-is-done-p))))
14029
14030 (defun org-get-wdays (ts)
14031 "Get the deadline lead time appropriate for timestring TS."
14032 (cond
14033 ((<= org-deadline-warning-days 0)
14034 ;; 0 or negative, enforce this value no matter what
14035 (- org-deadline-warning-days))
14036 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
14037 ;; lead time is specified.
14038 (floor (* (string-to-number (match-string 1 ts))
14039 (cdr (assoc (match-string 2 ts)
14040 '(("d" . 1) ("w" . 7)
14041 ("m" . 30.4) ("y" . 365.25)))))))
14042 ;; go for the default.
14043 (t org-deadline-warning-days)))
14044
14045 (defun org-calendar-select-mouse (ev)
14046 "Return to `org-read-date' with the date currently selected.
14047 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
14048 (interactive "e")
14049 (mouse-set-point ev)
14050 (when (calendar-cursor-to-date)
14051 (let* ((date (calendar-cursor-to-date))
14052 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14053 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
14054 (if (active-minibuffer-window) (exit-minibuffer))))
14055
14056 (defun org-check-deadlines (ndays)
14057 "Check if there are any deadlines due or past due.
14058 A deadline is considered due if it happens within `org-deadline-warning-days'
14059 days from today's date. If the deadline appears in an entry marked DONE,
14060 it is not shown. The prefix arg NDAYS can be used to test that many
14061 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
14062 (interactive "P")
14063 (let* ((org-warn-days
14064 (cond
14065 ((equal ndays '(4)) 100000)
14066 (ndays (prefix-numeric-value ndays))
14067 (t (abs org-deadline-warning-days))))
14068 (case-fold-search nil)
14069 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
14070 (callback
14071 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
14072
14073 (message "%d deadlines past-due or due within %d days"
14074 (org-occur regexp nil callback)
14075 org-warn-days)))
14076
14077 (defun org-check-before-date (date)
14078 "Check if there are deadlines or scheduled entries before DATE."
14079 (interactive (list (org-read-date)))
14080 (let ((case-fold-search nil)
14081 (regexp (concat "\\<\\(" org-deadline-string
14082 "\\|" org-scheduled-string
14083 "\\) *<\\([^>]+\\)>"))
14084 (callback
14085 (lambda () (time-less-p
14086 (org-time-string-to-time (match-string 2))
14087 (org-time-string-to-time date)))))
14088 (message "%d entries before %s"
14089 (org-occur regexp nil callback) date)))
14090
14091 (defun org-check-after-date (date)
14092 "Check if there are deadlines or scheduled entries after DATE."
14093 (interactive (list (org-read-date)))
14094 (let ((case-fold-search nil)
14095 (regexp (concat "\\<\\(" org-deadline-string
14096 "\\|" org-scheduled-string
14097 "\\) *<\\([^>]+\\)>"))
14098 (callback
14099 (lambda () (not
14100 (time-less-p
14101 (org-time-string-to-time (match-string 2))
14102 (org-time-string-to-time date))))))
14103 (message "%d entries after %s"
14104 (org-occur regexp nil callback) date)))
14105
14106 (defun org-evaluate-time-range (&optional to-buffer)
14107 "Evaluate a time range by computing the difference between start and end.
14108 Normally the result is just printed in the echo area, but with prefix arg
14109 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
14110 If the time range is actually in a table, the result is inserted into the
14111 next column.
14112 For time difference computation, a year is assumed to be exactly 365
14113 days in order to avoid rounding problems."
14114 (interactive "P")
14115 (or
14116 (org-clock-update-time-maybe)
14117 (save-excursion
14118 (unless (org-at-date-range-p t)
14119 (goto-char (point-at-bol))
14120 (re-search-forward org-tr-regexp-both (point-at-eol) t))
14121 (if (not (org-at-date-range-p t))
14122 (error "Not at a time-stamp range, and none found in current line")))
14123 (let* ((ts1 (match-string 1))
14124 (ts2 (match-string 2))
14125 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
14126 (match-end (match-end 0))
14127 (time1 (org-time-string-to-time ts1))
14128 (time2 (org-time-string-to-time ts2))
14129 (t1 (org-float-time time1))
14130 (t2 (org-float-time time2))
14131 (diff (abs (- t2 t1)))
14132 (negative (< (- t2 t1) 0))
14133 ;; (ys (floor (* 365 24 60 60)))
14134 (ds (* 24 60 60))
14135 (hs (* 60 60))
14136 (fy "%dy %dd %02d:%02d")
14137 (fy1 "%dy %dd")
14138 (fd "%dd %02d:%02d")
14139 (fd1 "%dd")
14140 (fh "%02d:%02d")
14141 y d h m align)
14142 (if havetime
14143 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14144 y 0
14145 d (floor (/ diff ds)) diff (mod diff ds)
14146 h (floor (/ diff hs)) diff (mod diff hs)
14147 m (floor (/ diff 60)))
14148 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
14149 y 0
14150 d (floor (+ (/ diff ds) 0.5))
14151 h 0 m 0))
14152 (if (not to-buffer)
14153 (message "%s" (org-make-tdiff-string y d h m))
14154 (if (org-at-table-p)
14155 (progn
14156 (goto-char match-end)
14157 (setq align t)
14158 (and (looking-at " *|") (goto-char (match-end 0))))
14159 (goto-char match-end))
14160 (if (looking-at
14161 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
14162 (replace-match ""))
14163 (if negative (insert " -"))
14164 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
14165 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
14166 (insert " " (format fh h m))))
14167 (if align (org-table-align))
14168 (message "Time difference inserted")))))
14169
14170 (defun org-make-tdiff-string (y d h m)
14171 (let ((fmt "")
14172 (l nil))
14173 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
14174 l (push y l)))
14175 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
14176 l (push d l)))
14177 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
14178 l (push h l)))
14179 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
14180 l (push m l)))
14181 (apply 'format fmt (nreverse l))))
14182
14183 (defun org-time-string-to-time (s)
14184 (apply 'encode-time (org-parse-time-string s)))
14185 (defun org-time-string-to-seconds (s)
14186 (org-float-time (org-time-string-to-time s)))
14187
14188 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
14189 "Convert a time stamp to an absolute day number.
14190 If there is a specifyer for a cyclic time stamp, get the closest date to
14191 DAYNR.
14192 PREFER and SHOW-ALL are passed through to `org-closest-date'.
14193 the variable date is bound by the calendar when this is called."
14194 (cond
14195 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
14196 (if (org-diary-sexp-entry (match-string 1 s) "" date)
14197 daynr
14198 (+ daynr 1000)))
14199 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
14200 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
14201 (time-to-days (current-time))) (match-string 0 s)
14202 prefer show-all))
14203 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
14204
14205 (defun org-days-to-iso-week (days)
14206 "Return the iso week number."
14207 (require 'cal-iso)
14208 (car (calendar-iso-from-absolute days)))
14209
14210 (defun org-small-year-to-year (year)
14211 "Convert 2-digit years into 4-digit years.
14212 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
14213 The year 2000 cannot be abbreviated. Any year larger than 99
14214 is returned unchanged."
14215 (if (< year 38)
14216 (setq year (+ 2000 year))
14217 (if (< year 100)
14218 (setq year (+ 1900 year))))
14219 year)
14220
14221 (defun org-time-from-absolute (d)
14222 "Return the time corresponding to date D.
14223 D may be an absolute day number, or a calendar-type list (month day year)."
14224 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
14225 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
14226
14227 (defun org-calendar-holiday ()
14228 "List of holidays, for Diary display in Org-mode."
14229 (require 'holidays)
14230 (let ((hl (funcall
14231 (if (fboundp 'calendar-check-holidays)
14232 'calendar-check-holidays 'check-calendar-holidays) date)))
14233 (if hl (mapconcat 'identity hl "; "))))
14234
14235 (defun org-diary-sexp-entry (sexp entry date)
14236 "Process a SEXP diary ENTRY for DATE."
14237 (require 'diary-lib)
14238 (let ((result (if calendar-debug-sexp
14239 (let ((stack-trace-on-error t))
14240 (eval (car (read-from-string sexp))))
14241 (condition-case nil
14242 (eval (car (read-from-string sexp)))
14243 (error
14244 (beep)
14245 (message "Bad sexp at line %d in %s: %s"
14246 (org-current-line)
14247 (buffer-file-name) sexp)
14248 (sleep-for 2))))))
14249 (cond ((stringp result) result)
14250 ((and (consp result)
14251 (stringp (cdr result))) (cdr result))
14252 (result entry)
14253 (t nil))))
14254
14255 (defun org-diary-to-ical-string (frombuf)
14256 "Get iCalendar entries from diary entries in buffer FROMBUF.
14257 This uses the icalendar.el library."
14258 (let* ((tmpdir (if (featurep 'xemacs)
14259 (temp-directory)
14260 temporary-file-directory))
14261 (tmpfile (make-temp-name
14262 (expand-file-name "orgics" tmpdir)))
14263 buf rtn b e)
14264 (with-current-buffer frombuf
14265 (icalendar-export-region (point-min) (point-max) tmpfile)
14266 (setq buf (find-buffer-visiting tmpfile))
14267 (set-buffer buf)
14268 (goto-char (point-min))
14269 (if (re-search-forward "^BEGIN:VEVENT" nil t)
14270 (setq b (match-beginning 0)))
14271 (goto-char (point-max))
14272 (if (re-search-backward "^END:VEVENT" nil t)
14273 (setq e (match-end 0)))
14274 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
14275 (kill-buffer buf)
14276 (delete-file tmpfile)
14277 rtn))
14278
14279 (defun org-closest-date (start current change prefer show-all)
14280 "Find the date closest to CURRENT that is consistent with START and CHANGE.
14281 When PREFER is `past' return a date that is either CURRENT or past.
14282 When PREFER is `future', return a date that is either CURRENT or future.
14283 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
14284 ;; Make the proper lists from the dates
14285 (catch 'exit
14286 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
14287 dn dw sday cday n1 n2 n0
14288 d m y y1 y2 date1 date2 nmonths nm ny m2)
14289
14290 (setq start (org-date-to-gregorian start)
14291 current (org-date-to-gregorian
14292 (if show-all
14293 current
14294 (time-to-days (current-time))))
14295 sday (calendar-absolute-from-gregorian start)
14296 cday (calendar-absolute-from-gregorian current))
14297
14298 (if (<= cday sday) (throw 'exit sday))
14299
14300 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
14301 (setq dn (string-to-number (match-string 1 change))
14302 dw (cdr (assoc (match-string 2 change) a1)))
14303 (error "Invalid change specifyer: %s" change))
14304 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
14305 (cond
14306 ((eq dw 'day)
14307 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
14308 n2 (+ n1 dn)))
14309 ((eq dw 'year)
14310 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
14311 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
14312 (setq date1 (list m d y1)
14313 n1 (calendar-absolute-from-gregorian date1)
14314 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
14315 n2 (calendar-absolute-from-gregorian date2)))
14316 ((eq dw 'month)
14317 ;; approx number of month between the two dates
14318 (setq nmonths (floor (/ (- cday sday) 30.436875)))
14319 ;; How often does dn fit in there?
14320 (setq d (nth 1 start) m (car start) y (nth 2 start)
14321 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
14322 m (+ m nm)
14323 ny (floor (/ m 12))
14324 y (+ y ny)
14325 m (- m (* ny 12)))
14326 (while (> m 12) (setq m (- m 12) y (1+ y)))
14327 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
14328 (setq m2 (+ m dn) y2 y)
14329 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14330 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
14331 (while (<= n2 cday)
14332 (setq n1 n2 m m2 y y2)
14333 (setq m2 (+ m dn) y2 y)
14334 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
14335 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
14336 ;; Make sure n1 is the earlier date
14337 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
14338 (if show-all
14339 (cond
14340 ((eq prefer 'past) (if (= cday n2) n2 n1))
14341 ((eq prefer 'future) (if (= cday n1) n1 n2))
14342 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
14343 (cond
14344 ((eq prefer 'past) (if (= cday n2) n2 n1))
14345 ((eq prefer 'future) (if (= cday n1) n1 n2))
14346 (t (if (= cday n1) n1 n2)))))))
14347
14348 (defun org-date-to-gregorian (date)
14349 "Turn any specification of DATE into a gregorian date for the calendar."
14350 (cond ((integerp date) (calendar-gregorian-from-absolute date))
14351 ((and (listp date) (= (length date) 3)) date)
14352 ((stringp date)
14353 (setq date (org-parse-time-string date))
14354 (list (nth 4 date) (nth 3 date) (nth 5 date)))
14355 ((listp date)
14356 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
14357
14358 (defun org-parse-time-string (s &optional nodefault)
14359 "Parse the standard Org-mode time string.
14360 This should be a lot faster than the normal `parse-time-string'.
14361 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
14362 hour and minute fields will be nil if not given."
14363 (if (string-match org-ts-regexp0 s)
14364 (list 0
14365 (if (or (match-beginning 8) (not nodefault))
14366 (string-to-number (or (match-string 8 s) "0")))
14367 (if (or (match-beginning 7) (not nodefault))
14368 (string-to-number (or (match-string 7 s) "0")))
14369 (string-to-number (match-string 4 s))
14370 (string-to-number (match-string 3 s))
14371 (string-to-number (match-string 2 s))
14372 nil nil nil)
14373 (error "Not a standard Org-mode time string: %s" s)))
14374
14375 (defun org-timestamp-up (&optional arg)
14376 "Increase the date item at the cursor by one.
14377 If the cursor is on the year, change the year. If it is on the month or
14378 the day, change that.
14379 With prefix ARG, change by that many units."
14380 (interactive "p")
14381 (org-timestamp-change (prefix-numeric-value arg)))
14382
14383 (defun org-timestamp-down (&optional arg)
14384 "Decrease the date item at the cursor by one.
14385 If the cursor is on the year, change the year. If it is on the month or
14386 the day, change that.
14387 With prefix ARG, change by that many units."
14388 (interactive "p")
14389 (org-timestamp-change (- (prefix-numeric-value arg))))
14390
14391 (defun org-timestamp-up-day (&optional arg)
14392 "Increase the date in the time stamp by one day.
14393 With prefix ARG, change that many days."
14394 (interactive "p")
14395 (if (and (not (org-at-timestamp-p t))
14396 (org-on-heading-p))
14397 (org-todo 'up)
14398 (org-timestamp-change (prefix-numeric-value arg) 'day)))
14399
14400 (defun org-timestamp-down-day (&optional arg)
14401 "Decrease the date in the time stamp by one day.
14402 With prefix ARG, change that many days."
14403 (interactive "p")
14404 (if (and (not (org-at-timestamp-p t))
14405 (org-on-heading-p))
14406 (org-todo 'down)
14407 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
14408
14409 (defun org-at-timestamp-p (&optional inactive-ok)
14410 "Determine if the cursor is in or at a timestamp."
14411 (interactive)
14412 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
14413 (pos (point))
14414 (ans (or (looking-at tsr)
14415 (save-excursion
14416 (skip-chars-backward "^[<\n\r\t")
14417 (if (> (point) (point-min)) (backward-char 1))
14418 (and (looking-at tsr)
14419 (> (- (match-end 0) pos) -1))))))
14420 (and ans
14421 (boundp 'org-ts-what)
14422 (setq org-ts-what
14423 (cond
14424 ((= pos (match-beginning 0)) 'bracket)
14425 ((= pos (1- (match-end 0))) 'bracket)
14426 ((org-pos-in-match-range pos 2) 'year)
14427 ((org-pos-in-match-range pos 3) 'month)
14428 ((org-pos-in-match-range pos 7) 'hour)
14429 ((org-pos-in-match-range pos 8) 'minute)
14430 ((or (org-pos-in-match-range pos 4)
14431 (org-pos-in-match-range pos 5)) 'day)
14432 ((and (> pos (or (match-end 8) (match-end 5)))
14433 (< pos (match-end 0)))
14434 (- pos (or (match-end 8) (match-end 5))))
14435 (t 'day))))
14436 ans))
14437
14438 (defun org-toggle-timestamp-type ()
14439 "Toggle the type (<active> or [inactive]) of a time stamp."
14440 (interactive)
14441 (when (org-at-timestamp-p t)
14442 (let ((beg (match-beginning 0)) (end (match-end 0))
14443 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
14444 (save-excursion
14445 (goto-char beg)
14446 (while (re-search-forward "[][<>]" end t)
14447 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
14448 t t)))
14449 (message "Timestamp is now %sactive"
14450 (if (equal (char-after beg) ?<) "" "in")))))
14451
14452 (defun org-timestamp-change (n &optional what)
14453 "Change the date in the time stamp at point.
14454 The date will be changed by N times WHAT. WHAT can be `day', `month',
14455 `year', `minute', `second'. If WHAT is not given, the cursor position
14456 in the timestamp determines what will be changed."
14457 (let ((pos (point))
14458 with-hm inactive
14459 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
14460 org-ts-what
14461 extra rem
14462 ts time time0)
14463 (if (not (org-at-timestamp-p t))
14464 (error "Not at a timestamp"))
14465 (if (and (not what) (eq org-ts-what 'bracket))
14466 (org-toggle-timestamp-type)
14467 (if (and (not what) (not (eq org-ts-what 'day))
14468 org-display-custom-times
14469 (get-text-property (point) 'display)
14470 (not (get-text-property (1- (point)) 'display)))
14471 (setq org-ts-what 'day))
14472 (setq org-ts-what (or what org-ts-what)
14473 inactive (= (char-after (match-beginning 0)) ?\[)
14474 ts (match-string 0))
14475 (replace-match "")
14476 (if (string-match
14477 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\(/[0-9]+[dwmy]\\)?\\)*\\)[]>]"
14478 ts)
14479 (setq extra (match-string 1 ts)))
14480 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
14481 (setq with-hm t))
14482 (setq time0 (org-parse-time-string ts))
14483 (when (and (eq org-ts-what 'minute)
14484 (eq current-prefix-arg nil))
14485 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
14486 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
14487 (setcar (cdr time0) (+ (nth 1 time0)
14488 (if (> n 0) (- rem) (- dm rem))))))
14489 (setq time
14490 (encode-time (or (car time0) 0)
14491 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
14492 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
14493 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
14494 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
14495 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
14496 (nthcdr 6 time0)))
14497 (when (and (member org-ts-what '(hour minute))
14498 extra
14499 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
14500 (setq extra (org-modify-ts-extra
14501 extra
14502 (if (eq org-ts-what 'hour) 2 5)
14503 n dm)))
14504 (when (integerp org-ts-what)
14505 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
14506 (if (eq what 'calendar)
14507 (let ((cal-date (org-get-date-from-calendar)))
14508 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
14509 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
14510 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
14511 (setcar time0 (or (car time0) 0))
14512 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
14513 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
14514 (setq time (apply 'encode-time time0))))
14515 (setq org-last-changed-timestamp
14516 (org-insert-time-stamp time with-hm inactive nil nil extra))
14517 (org-clock-update-time-maybe)
14518 (goto-char pos)
14519 ;; Try to recenter the calendar window, if any
14520 (if (and org-calendar-follow-timestamp-change
14521 (get-buffer-window "*Calendar*" t)
14522 (memq org-ts-what '(day month year)))
14523 (org-recenter-calendar (time-to-days time))))))
14524
14525 (defun org-modify-ts-extra (s pos n dm)
14526 "Change the different parts of the lead-time and repeat fields in timestamp."
14527 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
14528 ng h m new rem)
14529 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
14530 (cond
14531 ((or (org-pos-in-match-range pos 2)
14532 (org-pos-in-match-range pos 3))
14533 (setq m (string-to-number (match-string 3 s))
14534 h (string-to-number (match-string 2 s)))
14535 (if (org-pos-in-match-range pos 2)
14536 (setq h (+ h n))
14537 (setq n (* dm (org-no-warnings (signum n))))
14538 (when (not (= 0 (setq rem (% m dm))))
14539 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
14540 (setq m (+ m n)))
14541 (if (< m 0) (setq m (+ m 60) h (1- h)))
14542 (if (> m 59) (setq m (- m 60) h (1+ h)))
14543 (setq h (min 24 (max 0 h)))
14544 (setq ng 1 new (format "-%02d:%02d" h m)))
14545 ((org-pos-in-match-range pos 6)
14546 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
14547 ((org-pos-in-match-range pos 5)
14548 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
14549
14550 ((org-pos-in-match-range pos 9)
14551 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
14552 ((org-pos-in-match-range pos 8)
14553 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
14554
14555 (when ng
14556 (setq s (concat
14557 (substring s 0 (match-beginning ng))
14558 new
14559 (substring s (match-end ng))))))
14560 s))
14561
14562 (defun org-recenter-calendar (date)
14563 "If the calendar is visible, recenter it to DATE."
14564 (let* ((win (selected-window))
14565 (cwin (get-buffer-window "*Calendar*" t))
14566 (calendar-move-hook nil))
14567 (when cwin
14568 (select-window cwin)
14569 (calendar-goto-date (if (listp date) date
14570 (calendar-gregorian-from-absolute date)))
14571 (select-window win))))
14572
14573 (defun org-goto-calendar (&optional arg)
14574 "Go to the Emacs calendar at the current date.
14575 If there is a time stamp in the current line, go to that date.
14576 A prefix ARG can be used to force the current date."
14577 (interactive "P")
14578 (let ((tsr org-ts-regexp) diff
14579 (calendar-move-hook nil)
14580 (calendar-view-holidays-initially-flag nil)
14581 (view-calendar-holidays-initially nil)
14582 (calendar-view-diary-initially-flag nil)
14583 (view-diary-entries-initially nil))
14584 (if (or (org-at-timestamp-p)
14585 (save-excursion
14586 (beginning-of-line 1)
14587 (looking-at (concat ".*" tsr))))
14588 (let ((d1 (time-to-days (current-time)))
14589 (d2 (time-to-days
14590 (org-time-string-to-time (match-string 1)))))
14591 (setq diff (- d2 d1))))
14592 (calendar)
14593 (calendar-goto-today)
14594 (if (and diff (not arg)) (calendar-forward-day diff))))
14595
14596 (defun org-get-date-from-calendar ()
14597 "Return a list (month day year) of date at point in calendar."
14598 (with-current-buffer "*Calendar*"
14599 (save-match-data
14600 (calendar-cursor-to-date))))
14601
14602 (defun org-date-from-calendar ()
14603 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
14604 If there is already a time stamp at the cursor position, update it."
14605 (interactive)
14606 (if (org-at-timestamp-p t)
14607 (org-timestamp-change 0 'calendar)
14608 (let ((cal-date (org-get-date-from-calendar)))
14609 (org-insert-time-stamp
14610 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
14611
14612 (defun org-minutes-to-hh:mm-string (m)
14613 "Compute H:MM from a number of minutes."
14614 (let ((h (/ m 60)))
14615 (setq m (- m (* 60 h)))
14616 (format org-time-clocksum-format h m)))
14617
14618 (defun org-hh:mm-string-to-minutes (s)
14619 "Convert a string H:MM to a number of minutes.
14620 If the string is just a number, interpret it as minutes.
14621 In fact, the first hh:mm or number in the string will be taken,
14622 there can be extra stuff in the string.
14623 If no number is found, the return value is 0."
14624 (cond
14625 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
14626 (+ (* (string-to-number (match-string 1 s)) 60)
14627 (string-to-number (match-string 2 s))))
14628 ((string-match "\\([0-9]+\\)" s)
14629 (string-to-number (match-string 1 s)))
14630 (t 0)))
14631
14632 ;;;; Files
14633
14634 (defun org-save-all-org-buffers ()
14635 "Save all Org-mode buffers without user confirmation."
14636 (interactive)
14637 (message "Saving all Org-mode buffers...")
14638 (save-some-buffers t 'org-mode-p)
14639 (when (featurep 'org-id) (org-id-locations-save))
14640 (message "Saving all Org-mode buffers... done"))
14641
14642 (defun org-revert-all-org-buffers ()
14643 "Revert all Org-mode buffers.
14644 Prompt for confirmation when there are unsaved changes.
14645 Be sure you know what you are doing before letting this function
14646 overwrite your changes.
14647
14648 This function is useful in a setup where one tracks org files
14649 with a version control system, to revert on one machine after pulling
14650 changes from another. I believe the procedure must be like this:
14651
14652 1. M-x org-save-all-org-buffers
14653 2. Pull changes from the other machine, resolve conflicts
14654 3. M-x org-revert-all-org-buffers"
14655 (interactive)
14656 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
14657 (error "Abort"))
14658 (save-excursion
14659 (save-window-excursion
14660 (mapc
14661 (lambda (b)
14662 (when (and (with-current-buffer b (org-mode-p))
14663 (with-current-buffer b buffer-file-name))
14664 (switch-to-buffer b)
14665 (revert-buffer t 'no-confirm)))
14666 (buffer-list))
14667 (when (and (featurep 'org-id) org-id-track-globally)
14668 (org-id-locations-load)))))
14669
14670 ;;;; Agenda files
14671
14672 ;;;###autoload
14673 (defun org-iswitchb (&optional arg)
14674 "Use `org-icompleting-read' to prompt for an Org buffer to switch to.
14675 With a prefix argument, restrict available to files.
14676 With two prefix arguments, restrict available buffers to agenda files."
14677 (interactive "P")
14678 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
14679 ((equal arg '(16)) (org-buffer-list 'agenda))
14680 (t (org-buffer-list)))))
14681 (switch-to-buffer
14682 (org-icompleting-read "Org buffer: "
14683 (mapcar 'list (mapcar 'buffer-name blist))
14684 nil t))))
14685
14686 ;;;###autoload
14687 (defalias 'org-ido-switchb 'org-iswitchb)
14688
14689 (defun org-buffer-list (&optional predicate exclude-tmp)
14690 "Return a list of Org buffers.
14691 PREDICATE can be `export', `files' or `agenda'.
14692
14693 export restrict the list to Export buffers.
14694 files restrict the list to buffers visiting Org files.
14695 agenda restrict the list to buffers visiting agenda files.
14696
14697 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
14698 (let* ((bfn nil)
14699 (agenda-files (and (eq predicate 'agenda)
14700 (mapcar 'file-truename (org-agenda-files t))))
14701 (filter
14702 (cond
14703 ((eq predicate 'files)
14704 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
14705 ((eq predicate 'export)
14706 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
14707 ((eq predicate 'agenda)
14708 (lambda (b)
14709 (with-current-buffer b
14710 (and (eq major-mode 'org-mode)
14711 (setq bfn (buffer-file-name b))
14712 (member (file-truename bfn) agenda-files)))))
14713 (t (lambda (b) (with-current-buffer b
14714 (or (eq major-mode 'org-mode)
14715 (string-match "\*Org .*Export"
14716 (buffer-name b)))))))))
14717 (delq nil
14718 (mapcar
14719 (lambda(b)
14720 (if (and (funcall filter b)
14721 (or (not exclude-tmp)
14722 (not (string-match "tmp" (buffer-name b)))))
14723 b
14724 nil))
14725 (buffer-list)))))
14726
14727 (defun org-agenda-files (&optional unrestricted archives)
14728 "Get the list of agenda files.
14729 Optional UNRESTRICTED means return the full list even if a restriction
14730 is currently in place.
14731 When ARCHIVES is t, include all archive files that are really being
14732 used by the agenda files. If ARCHIVE is `ifmode', do this only if
14733 `org-agenda-archives-mode' is t."
14734 (let ((files
14735 (cond
14736 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
14737 ((stringp org-agenda-files) (org-read-agenda-file-list))
14738 ((listp org-agenda-files) org-agenda-files)
14739 (t (error "Invalid value of `org-agenda-files'")))))
14740 (setq files (apply 'append
14741 (mapcar (lambda (f)
14742 (if (file-directory-p f)
14743 (directory-files
14744 f t org-agenda-file-regexp)
14745 (list f)))
14746 files)))
14747 (when org-agenda-skip-unavailable-files
14748 (setq files (delq nil
14749 (mapcar (function
14750 (lambda (file)
14751 (and (file-readable-p file) file)))
14752 files))))
14753 (when (or (eq archives t)
14754 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
14755 (setq files (org-add-archive-files files)))
14756 files))
14757
14758 (defun org-edit-agenda-file-list ()
14759 "Edit the list of agenda files.
14760 Depending on setup, this either uses customize to edit the variable
14761 `org-agenda-files', or it visits the file that is holding the list. In the
14762 latter case, the buffer is set up in a way that saving it automatically kills
14763 the buffer and restores the previous window configuration."
14764 (interactive)
14765 (if (stringp org-agenda-files)
14766 (let ((cw (current-window-configuration)))
14767 (find-file org-agenda-files)
14768 (org-set-local 'org-window-configuration cw)
14769 (org-add-hook 'after-save-hook
14770 (lambda ()
14771 (set-window-configuration
14772 (prog1 org-window-configuration
14773 (kill-buffer (current-buffer))))
14774 (org-install-agenda-files-menu)
14775 (message "New agenda file list installed"))
14776 nil 'local)
14777 (message "%s" (substitute-command-keys
14778 "Edit list and finish with \\[save-buffer]")))
14779 (customize-variable 'org-agenda-files)))
14780
14781 (defun org-store-new-agenda-file-list (list)
14782 "Set new value for the agenda file list and save it correctly."
14783 (if (stringp org-agenda-files)
14784 (let ((fe (org-read-agenda-file-list t)) b u)
14785 (while (setq b (find-buffer-visiting org-agenda-files))
14786 (kill-buffer b))
14787 (with-temp-file org-agenda-files
14788 (insert
14789 (mapconcat
14790 (lambda (f) ;; Keep un-expanded entries.
14791 (if (setq u (assoc f fe))
14792 (cdr u)
14793 f))
14794 list "\n")
14795 "\n")))
14796 (let ((org-mode-hook nil) (org-inhibit-startup t)
14797 (org-insert-mode-line-in-empty-file nil))
14798 (setq org-agenda-files list)
14799 (customize-save-variable 'org-agenda-files org-agenda-files))))
14800
14801 (defun org-read-agenda-file-list (&optional pair-with-expansion)
14802 "Read the list of agenda files from a file.
14803 If PAIR-WITH-EXPANSION is t return pairs with un-expanded
14804 filenames, used by `org-store-new-agenda-file-list' to write back
14805 un-expanded file names."
14806 (when (file-directory-p org-agenda-files)
14807 (error "`org-agenda-files' cannot be a single directory"))
14808 (when (stringp org-agenda-files)
14809 (with-temp-buffer
14810 (insert-file-contents org-agenda-files)
14811 (mapcar
14812 (lambda (f)
14813 (let ((e (expand-file-name (substitute-in-file-name f)
14814 org-directory)))
14815 (if pair-with-expansion
14816 (cons e f)
14817 e)))
14818 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*")))))
14819
14820 ;;;###autoload
14821 (defun org-cycle-agenda-files ()
14822 "Cycle through the files in `org-agenda-files'.
14823 If the current buffer visits an agenda file, find the next one in the list.
14824 If the current buffer does not, find the first agenda file."
14825 (interactive)
14826 (let* ((fs (org-agenda-files t))
14827 (files (append fs (list (car fs))))
14828 (tcf (if buffer-file-name (file-truename buffer-file-name)))
14829 file)
14830 (unless files (error "No agenda files"))
14831 (catch 'exit
14832 (while (setq file (pop files))
14833 (if (equal (file-truename file) tcf)
14834 (when (car files)
14835 (find-file (car files))
14836 (throw 'exit t))))
14837 (find-file (car fs)))
14838 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
14839
14840 (defun org-agenda-file-to-front (&optional to-end)
14841 "Move/add the current file to the top of the agenda file list.
14842 If the file is not present in the list, it is added to the front. If it is
14843 present, it is moved there. With optional argument TO-END, add/move to the
14844 end of the list."
14845 (interactive "P")
14846 (let ((org-agenda-skip-unavailable-files nil)
14847 (file-alist (mapcar (lambda (x)
14848 (cons (file-truename x) x))
14849 (org-agenda-files t)))
14850 (ctf (file-truename buffer-file-name))
14851 x had)
14852 (setq x (assoc ctf file-alist) had x)
14853
14854 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
14855 (if to-end
14856 (setq file-alist (append (delq x file-alist) (list x)))
14857 (setq file-alist (cons x (delq x file-alist))))
14858 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
14859 (org-install-agenda-files-menu)
14860 (message "File %s to %s of agenda file list"
14861 (if had "moved" "added") (if to-end "end" "front"))))
14862
14863 (defun org-remove-file (&optional file)
14864 "Remove current file from the list of files in variable `org-agenda-files'.
14865 These are the files which are being checked for agenda entries.
14866 Optional argument FILE means use this file instead of the current."
14867 (interactive)
14868 (let* ((org-agenda-skip-unavailable-files nil)
14869 (file (or file buffer-file-name))
14870 (true-file (file-truename file))
14871 (afile (abbreviate-file-name file))
14872 (files (delq nil (mapcar
14873 (lambda (x)
14874 (if (equal true-file
14875 (file-truename x))
14876 nil x))
14877 (org-agenda-files t)))))
14878 (if (not (= (length files) (length (org-agenda-files t))))
14879 (progn
14880 (org-store-new-agenda-file-list files)
14881 (org-install-agenda-files-menu)
14882 (message "Removed file: %s" afile))
14883 (message "File was not in list: %s (not removed)" afile))))
14884
14885 (defun org-file-menu-entry (file)
14886 (vector file (list 'find-file file) t))
14887
14888 (defun org-check-agenda-file (file)
14889 "Make sure FILE exists. If not, ask user what to do."
14890 (when (not (file-exists-p file))
14891 (message "non-existent agenda file %s. [R]emove from list or [A]bort?"
14892 (abbreviate-file-name file))
14893 (let ((r (downcase (read-char-exclusive))))
14894 (cond
14895 ((equal r ?r)
14896 (org-remove-file file)
14897 (throw 'nextfile t))
14898 (t (error "Abort"))))))
14899
14900 (defun org-get-agenda-file-buffer (file)
14901 "Get a buffer visiting FILE. If the buffer needs to be created, add
14902 it to the list of buffers which might be released later."
14903 (let ((buf (org-find-base-buffer-visiting file)))
14904 (if buf
14905 buf ; just return it
14906 ;; Make a new buffer and remember it
14907 (setq buf (find-file-noselect file))
14908 (if buf (push buf org-agenda-new-buffers))
14909 buf)))
14910
14911 (defun org-release-buffers (blist)
14912 "Release all buffers in list, asking the user for confirmation when needed.
14913 When a buffer is unmodified, it is just killed. When modified, it is saved
14914 \(if the user agrees) and then killed."
14915 (let (buf file)
14916 (while (setq buf (pop blist))
14917 (setq file (buffer-file-name buf))
14918 (when (and (buffer-modified-p buf)
14919 file
14920 (y-or-n-p (format "Save file %s? " file)))
14921 (with-current-buffer buf (save-buffer)))
14922 (kill-buffer buf))))
14923
14924 (defun org-prepare-agenda-buffers (files)
14925 "Create buffers for all agenda files, protect archived trees and comments."
14926 (interactive)
14927 (let ((pa '(:org-archived t))
14928 (pc '(:org-comment t))
14929 (pall '(:org-archived t :org-comment t))
14930 (inhibit-read-only t)
14931 (rea (concat ":" org-archive-tag ":"))
14932 bmp file re)
14933 (save-excursion
14934 (save-restriction
14935 (while (setq file (pop files))
14936 (catch 'nextfile
14937 (if (bufferp file)
14938 (set-buffer file)
14939 (org-check-agenda-file file)
14940 (set-buffer (org-get-agenda-file-buffer file)))
14941 (widen)
14942 (setq bmp (buffer-modified-p))
14943 (org-refresh-category-properties)
14944 (setq org-todo-keywords-for-agenda
14945 (append org-todo-keywords-for-agenda org-todo-keywords-1))
14946 (setq org-done-keywords-for-agenda
14947 (append org-done-keywords-for-agenda org-done-keywords))
14948 (setq org-todo-keyword-alist-for-agenda
14949 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
14950 (setq org-drawers-for-agenda
14951 (append org-drawers-for-agenda org-drawers))
14952 (setq org-tag-alist-for-agenda
14953 (append org-tag-alist-for-agenda org-tag-alist))
14954
14955 (save-excursion
14956 (remove-text-properties (point-min) (point-max) pall)
14957 (when org-agenda-skip-archived-trees
14958 (goto-char (point-min))
14959 (while (re-search-forward rea nil t)
14960 (if (org-on-heading-p t)
14961 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
14962 (goto-char (point-min))
14963 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
14964 (while (re-search-forward re nil t)
14965 (add-text-properties
14966 (match-beginning 0) (org-end-of-subtree t) pc)))
14967 (set-buffer-modified-p bmp)))))
14968 (setq org-todo-keywords-for-agenda
14969 (org-uniquify org-todo-keywords-for-agenda))
14970 (setq org-todo-keyword-alist-for-agenda
14971 (org-uniquify org-todo-keyword-alist-for-agenda)
14972 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
14973
14974 ;;;; Embedded LaTeX
14975
14976 (defvar org-cdlatex-mode-map (make-sparse-keymap)
14977 "Keymap for the minor `org-cdlatex-mode'.")
14978
14979 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
14980 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
14981 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
14982 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
14983 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
14984
14985 (defvar org-cdlatex-texmathp-advice-is-done nil
14986 "Flag remembering if we have applied the advice to texmathp already.")
14987
14988 (define-minor-mode org-cdlatex-mode
14989 "Toggle the minor `org-cdlatex-mode'.
14990 This mode supports entering LaTeX environment and math in LaTeX fragments
14991 in Org-mode.
14992 \\{org-cdlatex-mode-map}"
14993 nil " OCDL" nil
14994 (when org-cdlatex-mode (require 'cdlatex))
14995 (unless org-cdlatex-texmathp-advice-is-done
14996 (setq org-cdlatex-texmathp-advice-is-done t)
14997 (defadvice texmathp (around org-math-always-on activate)
14998 "Always return t in org-mode buffers.
14999 This is because we want to insert math symbols without dollars even outside
15000 the LaTeX math segments. If Orgmode thinks that point is actually inside
15001 an embedded LaTeX fragment, let texmathp do its job.
15002 \\[org-cdlatex-mode-map]"
15003 (interactive)
15004 (let (p)
15005 (cond
15006 ((not (org-mode-p)) ad-do-it)
15007 ((eq this-command 'cdlatex-math-symbol)
15008 (setq ad-return-value t
15009 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
15010 (t
15011 (let ((p (org-inside-LaTeX-fragment-p)))
15012 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
15013 (setq ad-return-value t
15014 texmathp-why '("Org-mode embedded math" . 0))
15015 (if p ad-do-it)))))))))
15016
15017 (defun turn-on-org-cdlatex ()
15018 "Unconditionally turn on `org-cdlatex-mode'."
15019 (org-cdlatex-mode 1))
15020
15021 (defun org-inside-LaTeX-fragment-p ()
15022 "Test if point is inside a LaTeX fragment.
15023 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
15024 sequence appearing also before point.
15025 Even though the matchers for math are configurable, this function assumes
15026 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
15027 delimiters are skipped when they have been removed by customization.
15028 The return value is nil, or a cons cell with the delimiter and
15029 and the position of this delimiter.
15030
15031 This function does a reasonably good job, but can locally be fooled by
15032 for example currency specifications. For example it will assume being in
15033 inline math after \"$22.34\". The LaTeX fragment formatter will only format
15034 fragments that are properly closed, but during editing, we have to live
15035 with the uncertainty caused by missing closing delimiters. This function
15036 looks only before point, not after."
15037 (catch 'exit
15038 (let ((pos (point))
15039 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
15040 (lim (progn
15041 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
15042 (point)))
15043 dd-on str (start 0) m re)
15044 (goto-char pos)
15045 (when dodollar
15046 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
15047 re (nth 1 (assoc "$" org-latex-regexps)))
15048 (while (string-match re str start)
15049 (cond
15050 ((= (match-end 0) (length str))
15051 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
15052 ((= (match-end 0) (- (length str) 5))
15053 (throw 'exit nil))
15054 (t (setq start (match-end 0))))))
15055 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
15056 (goto-char pos)
15057 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
15058 (and (match-beginning 2) (throw 'exit nil))
15059 ;; count $$
15060 (while (re-search-backward "\\$\\$" lim t)
15061 (setq dd-on (not dd-on)))
15062 (goto-char pos)
15063 (if dd-on (cons "$$" m))))))
15064
15065 (defun org-inside-latex-macro-p ()
15066 "Is point inside a LaTeX macro or its arguments?"
15067 (save-match-data
15068 (org-in-regexp
15069 "\\\\[a-zA-Z]+\\*?\\(\\(\\[[^][\n{}]*\\]\\)\\|\\({[^{}\n]*}\\)\\)*")))
15070
15071 (defun test ()
15072 (interactive)
15073 (message "%s" (org-inside-latex-macro-p)))
15074
15075 (defun org-try-cdlatex-tab ()
15076 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
15077 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
15078 - inside a LaTeX fragment, or
15079 - after the first word in a line, where an abbreviation expansion could
15080 insert a LaTeX environment."
15081 (when org-cdlatex-mode
15082 (cond
15083 ((save-excursion
15084 (skip-chars-backward "a-zA-Z0-9*")
15085 (skip-chars-backward " \t")
15086 (bolp))
15087 (cdlatex-tab) t)
15088 ((org-inside-LaTeX-fragment-p)
15089 (cdlatex-tab) t)
15090 (t nil))))
15091
15092 (defun org-cdlatex-underscore-caret (&optional arg)
15093 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
15094 Revert to the normal definition outside of these fragments."
15095 (interactive "P")
15096 (if (org-inside-LaTeX-fragment-p)
15097 (call-interactively 'cdlatex-sub-superscript)
15098 (let (org-cdlatex-mode)
15099 (call-interactively (key-binding (vector last-input-event))))))
15100
15101 (defun org-cdlatex-math-modify (&optional arg)
15102 "Execute `cdlatex-math-modify' in LaTeX fragments.
15103 Revert to the normal definition outside of these fragments."
15104 (interactive "P")
15105 (if (org-inside-LaTeX-fragment-p)
15106 (call-interactively 'cdlatex-math-modify)
15107 (let (org-cdlatex-mode)
15108 (call-interactively (key-binding (vector last-input-event))))))
15109
15110 (defvar org-latex-fragment-image-overlays nil
15111 "List of overlays carrying the images of latex fragments.")
15112 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
15113
15114 (defun org-remove-latex-fragment-image-overlays ()
15115 "Remove all overlays with LaTeX fragment images in current buffer."
15116 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
15117 (setq org-latex-fragment-image-overlays nil))
15118
15119 (defun org-preview-latex-fragment (&optional subtree)
15120 "Preview the LaTeX fragment at point, or all locally or globally.
15121 If the cursor is in a LaTeX fragment, create the image and overlay
15122 it over the source code. If there is no fragment at point, display
15123 all fragments in the current text, from one headline to the next. With
15124 prefix SUBTREE, display all fragments in the current subtree. With a
15125 double prefix `C-u C-u', or when the cursor is before the first headline,
15126 display all fragments in the buffer.
15127 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
15128 (interactive "P")
15129 (org-remove-latex-fragment-image-overlays)
15130 (save-excursion
15131 (save-restriction
15132 (let (beg end at msg)
15133 (cond
15134 ((or (equal subtree '(16))
15135 (not (save-excursion
15136 (re-search-backward (concat "^" outline-regexp) nil t))))
15137 (setq beg (point-min) end (point-max)
15138 msg "Creating images for buffer...%s"))
15139 ((equal subtree '(4))
15140 (org-back-to-heading)
15141 (setq beg (point) end (org-end-of-subtree t)
15142 msg "Creating images for subtree...%s"))
15143 (t
15144 (if (setq at (org-inside-LaTeX-fragment-p))
15145 (goto-char (max (point-min) (- (cdr at) 2)))
15146 (org-back-to-heading))
15147 (setq beg (point) end (progn (outline-next-heading) (point))
15148 msg (if at "Creating image...%s"
15149 "Creating images for entry...%s"))))
15150 (message msg "")
15151 (narrow-to-region beg end)
15152 (goto-char beg)
15153 (org-format-latex
15154 (concat "ltxpng/" (file-name-sans-extension
15155 (file-name-nondirectory
15156 buffer-file-name)))
15157 default-directory 'overlays msg at 'forbuffer)
15158 (message msg "done. Use `C-c C-c' to remove images.")))))
15159
15160 (defvar org-latex-regexps
15161 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
15162 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
15163 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
15164 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15165 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
15166 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
15167 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 nil)
15168 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 nil))
15169 "Regular expressions for matching embedded LaTeX.")
15170
15171 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
15172 "Replace LaTeX fragments with links to an image, and produce images.
15173 Some of the options can be changed using the variable
15174 `org-format-latex-options'."
15175 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
15176 (let* ((prefixnodir (file-name-nondirectory prefix))
15177 (absprefix (expand-file-name prefix dir))
15178 (todir (file-name-directory absprefix))
15179 (opt org-format-latex-options)
15180 (matchers (plist-get opt :matchers))
15181 (re-list org-latex-regexps)
15182 (org-format-latex-header-extra
15183 (plist-get (org-infile-export-plist) :latex-header-extra))
15184 (cnt 0) txt hash link beg end re e checkdir
15185 executables-checked
15186 m n block linkfile movefile ov)
15187 ;; Check the different regular expressions
15188 (while (setq e (pop re-list))
15189 (setq m (car e) re (nth 1 e) n (nth 2 e)
15190 block (if (nth 3 e) "\n\n" ""))
15191 (when (member m matchers)
15192 (goto-char (point-min))
15193 (while (re-search-forward re nil t)
15194 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
15195 (not (get-text-property (match-beginning n)
15196 'org-protected))
15197 (or (not overlays)
15198 (not (eq (get-char-property (match-beginning n)
15199 'org-overlay-type)
15200 'org-latex-overlay))))
15201 (setq txt (match-string n)
15202 beg (match-beginning n) end (match-end n)
15203 cnt (1+ cnt))
15204 (let (print-length print-level) ; make sure full list is printed
15205 (setq hash (sha1 (prin1-to-string
15206 (list org-format-latex-header
15207 org-format-latex-header-extra
15208 org-export-latex-default-packages-alist
15209 org-export-latex-packages-alist
15210 org-format-latex-options
15211 forbuffer txt)))
15212 linkfile (format "%s_%s.png" prefix hash)
15213 movefile (format "%s_%s.png" absprefix hash)))
15214 (setq link (concat block "[[file:" linkfile "]]" block))
15215 (if msg (message msg cnt))
15216 (goto-char beg)
15217 (unless checkdir ; make sure the directory exists
15218 (setq checkdir t)
15219 (or (file-directory-p todir) (make-directory todir)))
15220
15221 (unless executables-checked
15222 (org-check-external-command
15223 "latex" "needed to convert LaTeX fragments to images")
15224 (org-check-external-command
15225 "dvipng" "needed to convert LaTeX fragments to images")
15226 (setq executables-checked t))
15227
15228 (unless (file-exists-p movefile)
15229 (org-create-formula-image
15230 txt movefile opt forbuffer))
15231 (if overlays
15232 (progn
15233 (mapc (lambda (o)
15234 (if (eq (org-overlay-get o 'org-overlay-type)
15235 'org-latex-overlay)
15236 (org-delete-overlay o)))
15237 (org-overlays-in beg end))
15238 (setq ov (org-make-overlay beg end))
15239 (org-overlay-put ov 'org-overlay-type 'org-latex-overlay)
15240 (if (featurep 'xemacs)
15241 (progn
15242 (org-overlay-put ov 'invisible t)
15243 (org-overlay-put
15244 ov 'end-glyph
15245 (make-glyph (vector 'png :file movefile))))
15246 (org-overlay-put
15247 ov 'display
15248 (list 'image :type 'png :file movefile :ascent 'center)))
15249 (push ov org-latex-fragment-image-overlays)
15250 (goto-char end))
15251 (delete-region beg end)
15252 (insert (org-add-props link
15253 (list 'org-latex-src
15254 (replace-regexp-in-string "\"" "" txt)))))))))))
15255
15256 ;; This function borrows from Ganesh Swami's latex2png.el
15257 (defun org-create-formula-image (string tofile options buffer)
15258 "This calls dvipng."
15259 (require 'org-latex)
15260 (let* ((tmpdir (if (featurep 'xemacs)
15261 (temp-directory)
15262 temporary-file-directory))
15263 (texfilebase (make-temp-name
15264 (expand-file-name "orgtex" tmpdir)))
15265 (texfile (concat texfilebase ".tex"))
15266 (dvifile (concat texfilebase ".dvi"))
15267 (pngfile (concat texfilebase ".png"))
15268 (fnh (if (featurep 'xemacs)
15269 (font-height (get-face-font 'default))
15270 (face-attribute 'default :height nil)))
15271 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
15272 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
15273 (fg (or (plist-get options (if buffer :foreground :html-foreground))
15274 "Black"))
15275 (bg (or (plist-get options (if buffer :background :html-background))
15276 "Transparent")))
15277 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
15278 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
15279 (with-temp-file texfile
15280 (insert (org-splice-latex-header
15281 org-format-latex-header
15282 org-export-latex-default-packages-alist
15283 org-export-latex-packages-alist
15284 org-format-latex-header-extra))
15285 (insert "\n\\begin{document}\n" string "\n\\end{document}\n")
15286 (require 'org-latex)
15287 (org-export-latex-fix-inputenc))
15288 (let ((dir default-directory))
15289 (condition-case nil
15290 (progn
15291 (cd tmpdir)
15292 (call-process "latex" nil nil nil texfile))
15293 (error nil))
15294 (cd dir))
15295 (if (not (file-exists-p dvifile))
15296 (progn (message "Failed to create dvi file from %s" texfile) nil)
15297 (condition-case nil
15298 (call-process "dvipng" nil nil nil
15299 "-fg" fg "-bg" bg
15300 "-D" dpi
15301 ;;"-x" scale "-y" scale
15302 "-T" "tight"
15303 "-o" pngfile
15304 dvifile)
15305 (error nil))
15306 (if (not (file-exists-p pngfile))
15307 (if org-format-latex-signal-error
15308 (error "Failed to create png file from %s" texfile)
15309 (message "Failed to create png file from %s" texfile)
15310 nil)
15311 ;; Use the requested file name and clean up
15312 (copy-file pngfile tofile 'replace)
15313 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
15314 (delete-file (concat texfilebase e)))
15315 pngfile))))
15316
15317 (defun org-splice-latex-header (tpl def-pkg pkg &optional extra)
15318 "Fill a LaTeX header template TPL.
15319 In the template, the following place holders will be recognized:
15320
15321 [DEFAULT-PACKAGES] \\usepackage statements for DEF-PKG
15322 [NO-DEFAULT-PACKAGES] do not include DEF-PKG
15323 [PACKAGES] \\usepackage statements for PKG
15324 [NO-PACKAGES] do not include PKG
15325 [EXTRA] the string EXTRA
15326 [NO-EXTRA] do not include EXTRA
15327
15328 For backward compatibility, if both the positive and the negative place
15329 holder is missing, the positive one (without the \"NO-\") will be
15330 assumed to be present at the end of the template.
15331 DEF-PKG and PKG are assumed to be alists of options/packagename lists.
15332 EXTRA is a string."
15333 (let (rpl (end ""))
15334 (if (string-match "^[ \t]*\\[\\(NO-\\)?DEFAULT-PACKAGES\\][ \t]*\n?" tpl)
15335 (setq rpl (if (or (match-end 1) (not def-pkg))
15336 "" (org-latex-packages-to-string def-pkg t))
15337 tpl (replace-match rpl t t tpl))
15338 (if def-pkg (setq end (org-latex-packages-to-string def-pkg))))
15339
15340 (if (string-match "\\[\\(NO-\\)?PACKAGES\\][ \t]*\n?" tpl)
15341 (setq rpl (if (or (match-end 1) (not pkg))
15342 "" (org-latex-packages-to-string pkg t))
15343 tpl (replace-match rpl t t tpl))
15344 (if pkg (setq end (concat end "\n" (org-latex-packages-to-string pkg)))))
15345
15346 (if (string-match "\\[\\(NO-\\)?EXTRA\\][ \t]*\n?" tpl)
15347 (setq rpl (if (or (match-end 1) (not extra))
15348 "" (concat extra "\n"))
15349 tpl (replace-match rpl t t tpl))
15350 (if (and extra (string-match "\\S-" extra))
15351 (setq end (concat end "\n" extra))))
15352
15353 (if (string-match "\\S-" end)
15354 (concat tpl "\n" end)
15355 tpl)))
15356
15357 (defun org-latex-packages-to-string (pkg &optional newline)
15358 "Turn an alist of packages into a string with the \\usepackage macros."
15359 (setq pkg (mapconcat (lambda(p)
15360 (cond
15361 ((stringp p) p)
15362 ((equal "" (car p))
15363 (format "\\usepackage{%s}" (cadr p)))
15364 (t
15365 (format "\\usepackage[%s]{%s}"
15366 (car p) (cadr p)))))
15367 pkg
15368 "\n"))
15369 (if newline (concat pkg "\n") pkg))
15370
15371 (defun org-dvipng-color (attr)
15372 "Return an rgb color specification for dvipng."
15373 (apply 'format "rgb %s %s %s"
15374 (mapcar 'org-normalize-color
15375 (color-values (face-attribute 'default attr nil)))))
15376
15377 (defun org-normalize-color (value)
15378 "Return string to be used as color value for an RGB component."
15379 (format "%g" (/ value 65535.0)))
15380
15381 ;;;; Key bindings
15382
15383 ;; Make `C-c C-x' a prefix key
15384 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
15385
15386 ;; TAB key with modifiers
15387 (org-defkey org-mode-map "\C-i" 'org-cycle)
15388 (org-defkey org-mode-map [(tab)] 'org-cycle)
15389 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
15390 (org-defkey org-mode-map [(meta tab)] 'org-complete)
15391 (org-defkey org-mode-map "\M-\t" 'org-complete)
15392 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
15393 ;; The following line is necessary under Suse GNU/Linux
15394 (unless (featurep 'xemacs)
15395 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
15396 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
15397 (define-key org-mode-map [backtab] 'org-shifttab)
15398
15399 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
15400 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
15401 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
15402
15403 ;; Cursor keys with modifiers
15404 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
15405 (org-defkey org-mode-map [(meta right)] 'org-metaright)
15406 (org-defkey org-mode-map [(meta up)] 'org-metaup)
15407 (org-defkey org-mode-map [(meta down)] 'org-metadown)
15408
15409 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
15410 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
15411 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
15412 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
15413
15414 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
15415 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
15416 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
15417 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
15418
15419 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
15420 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
15421
15422 ;;; Extra keys for tty access.
15423 ;; We only set them when really needed because otherwise the
15424 ;; menus don't show the simple keys
15425
15426 (when (or org-use-extra-keys
15427 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
15428 (not window-system))
15429 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
15430 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
15431 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
15432 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
15433 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
15434 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
15435 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
15436 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
15437 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
15438 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
15439 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
15440 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
15441 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
15442 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
15443 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
15444 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
15445 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
15446 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
15447 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
15448 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
15449 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
15450 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
15451 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
15452 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
15453 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
15454 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
15455 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
15456 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
15457
15458 ;; All the other keys
15459
15460 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
15461 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
15462 (if (boundp 'narrow-map)
15463 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
15464 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
15465 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
15466 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
15467 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
15468 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
15469 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-archive-subtree-default)
15470 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
15471 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
15472 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
15473 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
15474 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
15475 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
15476 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
15477 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
15478 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
15479 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
15480 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
15481 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
15482 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
15483 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
15484 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
15485 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
15486 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
15487 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
15488 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
15489 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
15490 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
15491 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
15492 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
15493 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
15494 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
15495 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
15496 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
15497 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
15498 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
15499 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
15500 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
15501 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
15502 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
15503 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
15504 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
15505 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
15506 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15507 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
15508 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
15509 (org-defkey org-mode-map "\C-c^" 'org-sort)
15510 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
15511 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
15512 (org-defkey org-mode-map "\C-c#" 'org-update-statistics-cookies)
15513 (org-defkey org-mode-map "\C-m" 'org-return)
15514 (org-defkey org-mode-map "\C-j" 'org-return-indent)
15515 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
15516 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
15517 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
15518 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
15519 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
15520 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
15521 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
15522 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
15523 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
15524 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
15525 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
15526 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
15527 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
15528 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
15529 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
15530 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
15531 (org-defkey org-mode-map "\C-c\C-x\C-mg" 'org-mobile-pull)
15532 (org-defkey org-mode-map "\C-c\C-x\C-mp" 'org-mobile-push)
15533 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
15534 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
15535
15536 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
15537 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
15538 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
15539 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
15540
15541 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
15542 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
15543 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
15544 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
15545 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
15546 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
15547 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
15548 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
15549 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
15550 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
15551 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
15552 (org-defkey org-mode-map "\C-c\C-xe" 'org-set-effort)
15553 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
15554 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
15555 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
15556
15557 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
15558 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
15559 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
15560 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
15561
15562 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
15563
15564 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
15565
15566 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
15567 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
15568
15569 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
15570
15571
15572 (when (featurep 'xemacs)
15573 (org-defkey org-mode-map 'button3 'popup-mode-menu))
15574
15575
15576 (defconst org-speed-commands-default
15577 '(
15578 ("Outline Navigation")
15579 ("n" . (org-speed-move-safe 'outline-next-visible-heading))
15580 ("p" . (org-speed-move-safe 'outline-previous-visible-heading))
15581 ("f" . (org-speed-move-safe 'org-forward-same-level))
15582 ("b" . (org-speed-move-safe 'org-backward-same-level))
15583 ("u" . (org-speed-move-safe 'outline-up-heading))
15584 ("j" . org-goto)
15585 ("g" . (org-refile t))
15586 ("Outline Visibility")
15587 ("c" . org-cycle)
15588 ("C" . org-shifttab)
15589 (" " . org-display-outline-path)
15590 ("Outline Structure Editing")
15591 ("U" . org-shiftmetaup)
15592 ("D" . org-shiftmetadown)
15593 ("r" . org-metaright)
15594 ("l" . org-metaleft)
15595 ("R" . org-shiftmetaright)
15596 ("L" . org-shiftmetaleft)
15597 ("i" . (progn (forward-char 1) (call-interactively
15598 'org-insert-heading-respect-content)))
15599 ("^" . org-sort)
15600 ("w" . org-refile)
15601 ("a" . org-archive-subtree-default-with-confirmation)
15602 ("." . outline-mark-subtree)
15603 ("Clock Commands")
15604 ("I" . org-clock-in)
15605 ("O" . org-clock-out)
15606 ("Meta Data Editing")
15607 ("t" . org-todo)
15608 ("0" . (org-priority ?\ ))
15609 ("1" . (org-priority ?A))
15610 ("2" . (org-priority ?B))
15611 ("3" . (org-priority ?C))
15612 (";" . org-set-tags-command)
15613 ("e" . org-set-effort)
15614 ("Agenda Views etc")
15615 ("v" . org-agenda)
15616 ("/" . org-sparse-tree)
15617 ("Misc")
15618 ("o" . org-open-at-point)
15619 ("?" . org-speed-command-help)
15620 )
15621 "The default speed commands.")
15622
15623 (defun org-print-speed-command (e)
15624 (if (> (length (car e)) 1)
15625 (progn
15626 (princ "\n")
15627 (princ (car e))
15628 (princ "\n")
15629 (princ (make-string (length (car e)) ?-))
15630 (princ "\n"))
15631 (princ (car e))
15632 (princ " ")
15633 (if (symbolp (cdr e))
15634 (princ (symbol-name (cdr e)))
15635 (prin1 (cdr e)))
15636 (princ "\n")))
15637
15638 (defun org-speed-command-help ()
15639 "Show the available speed commands."
15640 (interactive)
15641 (if (not org-use-speed-commands)
15642 (error "Speed commands are not activated, customize `org-use-speed-commands'.")
15643 (with-output-to-temp-buffer "*Help*"
15644 (princ "User-defined Speed commands\n===========================\n")
15645 (mapc 'org-print-speed-command org-speed-commands-user)
15646 (princ "\n")
15647 (princ "Built-in Speed commands\n=======================\n")
15648 (mapc 'org-print-speed-command org-speed-commands-default))
15649 (with-current-buffer "*Help*"
15650 (setq truncate-lines t))))
15651
15652 (defun org-speed-move-safe (cmd)
15653 "Execute CMD, but make sure that the cursor always ends up in a headline.
15654 If not, return to the original position and throw an error."
15655 (interactive)
15656 (let ((pos (point)))
15657 (call-interactively cmd)
15658 (unless (and (bolp) (org-on-heading-p))
15659 (goto-char pos)
15660 (error "Boundary reached while executing %s" cmd))))
15661
15662 (defvar org-self-insert-command-undo-counter 0)
15663
15664 (defvar org-table-auto-blank-field) ; defined in org-table.el
15665 (defvar org-speed-command nil)
15666 (defun org-self-insert-command (N)
15667 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
15668 If the cursor is in a table looking at whitespace, the whitespace is
15669 overwritten, and the table is not marked as requiring realignment."
15670 (interactive "p")
15671 (cond
15672 ((and org-use-speed-commands
15673 (or (and (bolp) (looking-at outline-regexp))
15674 (and (functionp org-use-speed-commands)
15675 (funcall org-use-speed-commands)))
15676 (setq
15677 org-speed-command
15678 (or (cdr (assoc (this-command-keys) org-speed-commands-user))
15679 (cdr (assoc (this-command-keys) org-speed-commands-default)))))
15680 (cond
15681 ((commandp org-speed-command)
15682 (setq this-command org-speed-command)
15683 (call-interactively org-speed-command))
15684 ((functionp org-speed-command)
15685 (funcall org-speed-command))
15686 ((and org-speed-command (listp org-speed-command))
15687 (eval org-speed-command))
15688 (t (let (org-use-speed-commands)
15689 (call-interactively 'org-self-insert-command)))))
15690 ((and
15691 (org-table-p)
15692 (progn
15693 ;; check if we blank the field, and if that triggers align
15694 (and (featurep 'org-table) org-table-auto-blank-field
15695 (member last-command
15696 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
15697 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
15698 ;; got extra space, this field does not determine column width
15699 (let (org-table-may-need-update) (org-table-blank-field))
15700 ;; no extra space, this field may determine column width
15701 (org-table-blank-field)))
15702 t)
15703 (eq N 1)
15704 (looking-at "[^|\n]* |"))
15705 (let (org-table-may-need-update)
15706 (goto-char (1- (match-end 0)))
15707 (delete-backward-char 1)
15708 (goto-char (match-beginning 0))
15709 (self-insert-command N)))
15710 (t
15711 (setq org-table-may-need-update t)
15712 (self-insert-command N)
15713 (org-fix-tags-on-the-fly)
15714 (if org-self-insert-cluster-for-undo
15715 (if (not (eq last-command 'org-self-insert-command))
15716 (setq org-self-insert-command-undo-counter 1)
15717 (if (>= org-self-insert-command-undo-counter 20)
15718 (setq org-self-insert-command-undo-counter 1)
15719 (and (> org-self-insert-command-undo-counter 0)
15720 buffer-undo-list
15721 (not (cadr buffer-undo-list)) ; remove nil entry
15722 (setcdr buffer-undo-list (cddr buffer-undo-list)))
15723 (setq org-self-insert-command-undo-counter
15724 (1+ org-self-insert-command-undo-counter))))))))
15725
15726 (defun org-fix-tags-on-the-fly ()
15727 (when (and (equal (char-after (point-at-bol)) ?*)
15728 (org-on-heading-p))
15729 (org-align-tags-here org-tags-column)))
15730
15731 (defun org-delete-backward-char (N)
15732 "Like `delete-backward-char', insert whitespace at field end in tables.
15733 When deleting backwards, in tables this function will insert whitespace in
15734 front of the next \"|\" separator, to keep the table aligned. The table will
15735 still be marked for re-alignment if the field did fill the entire column,
15736 because, in this case the deletion might narrow the column."
15737 (interactive "p")
15738 (if (and (org-table-p)
15739 (eq N 1)
15740 (string-match "|" (buffer-substring (point-at-bol) (point)))
15741 (looking-at ".*?|"))
15742 (let ((pos (point))
15743 (noalign (looking-at "[^|\n\r]* |"))
15744 (c org-table-may-need-update))
15745 (backward-delete-char N)
15746 (skip-chars-forward "^|")
15747 (insert " ")
15748 (goto-char (1- pos))
15749 ;; noalign: if there were two spaces at the end, this field
15750 ;; does not determine the width of the column.
15751 (if noalign (setq org-table-may-need-update c)))
15752 (backward-delete-char N)
15753 (org-fix-tags-on-the-fly)))
15754
15755 (defun org-delete-char (N)
15756 "Like `delete-char', but insert whitespace at field end in tables.
15757 When deleting characters, in tables this function will insert whitespace in
15758 front of the next \"|\" separator, to keep the table aligned. The table will
15759 still be marked for re-alignment if the field did fill the entire column,
15760 because, in this case the deletion might narrow the column."
15761 (interactive "p")
15762 (if (and (org-table-p)
15763 (not (bolp))
15764 (not (= (char-after) ?|))
15765 (eq N 1))
15766 (if (looking-at ".*?|")
15767 (let ((pos (point))
15768 (noalign (looking-at "[^|\n\r]* |"))
15769 (c org-table-may-need-update))
15770 (replace-match (concat
15771 (substring (match-string 0) 1 -1)
15772 " |"))
15773 (goto-char pos)
15774 ;; noalign: if there were two spaces at the end, this field
15775 ;; does not determine the width of the column.
15776 (if noalign (setq org-table-may-need-update c)))
15777 (delete-char N))
15778 (delete-char N)
15779 (org-fix-tags-on-the-fly)))
15780
15781 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
15782 (put 'org-self-insert-command 'delete-selection t)
15783 (put 'orgtbl-self-insert-command 'delete-selection t)
15784 (put 'org-delete-char 'delete-selection 'supersede)
15785 (put 'org-delete-backward-char 'delete-selection 'supersede)
15786 (put 'org-yank 'delete-selection 'yank)
15787
15788 ;; Make `flyspell-mode' delay after some commands
15789 (put 'org-self-insert-command 'flyspell-delayed t)
15790 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
15791 (put 'org-delete-char 'flyspell-delayed t)
15792 (put 'org-delete-backward-char 'flyspell-delayed t)
15793
15794 ;; Make pabbrev-mode expand after org-mode commands
15795 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
15796 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
15797
15798 ;; How to do this: Measure non-white length of current string
15799 ;; If equal to column width, we should realign.
15800
15801 (defun org-remap (map &rest commands)
15802 "In MAP, remap the functions given in COMMANDS.
15803 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
15804 (let (new old)
15805 (while commands
15806 (setq old (pop commands) new (pop commands))
15807 (if (fboundp 'command-remapping)
15808 (org-defkey map (vector 'remap old) new)
15809 (substitute-key-definition old new map global-map)))))
15810
15811 (when (eq org-enable-table-editor 'optimized)
15812 ;; If the user wants maximum table support, we need to hijack
15813 ;; some standard editing functions
15814 (org-remap org-mode-map
15815 'self-insert-command 'org-self-insert-command
15816 'delete-char 'org-delete-char
15817 'delete-backward-char 'org-delete-backward-char)
15818 (org-defkey org-mode-map "|" 'org-force-self-insert))
15819
15820 (defvar org-ctrl-c-ctrl-c-hook nil
15821 "Hook for functions attaching themselves to `C-c C-c'.
15822 This can be used to add additional functionality to the C-c C-c key which
15823 executes context-dependent commands.
15824 Each function will be called with no arguments. The function must check
15825 if the context is appropriate for it to act. If yes, it should do its
15826 thing and then return a non-nil value. If the context is wrong,
15827 just do nothing and return nil.")
15828
15829 (defvar org-tab-first-hook nil
15830 "Hook for functions to attach themselves to TAB.
15831 See `org-ctrl-c-ctrl-c-hook' for more information.
15832 This hook runs as the first action when TAB is pressed, even before
15833 `org-cycle' messes around with the `outline-regexp' to cater for
15834 inline tasks and plain list item folding.
15835 If any function in this hook returns t, not other actions like table
15836 field motion visibility cycling will be done.")
15837
15838 (defvar org-tab-after-check-for-table-hook nil
15839 "Hook for functions to attach themselves to TAB.
15840 See `org-ctrl-c-ctrl-c-hook' for more information.
15841 This hook runs after it has been established that the cursor is not in a
15842 table, but before checking if the cursor is in a headline or if global cycling
15843 should be done.
15844 If any function in this hook returns t, not other actions like visibility
15845 cycling will be done.")
15846
15847 (defvar org-tab-after-check-for-cycling-hook nil
15848 "Hook for functions to attach themselves to TAB.
15849 See `org-ctrl-c-ctrl-c-hook' for more information.
15850 This hook runs after it has been established that not table field motion and
15851 not visibility should be done because of current context. This is probably
15852 the place where a package like yasnippets can hook in.")
15853
15854 (defvar org-tab-before-tab-emulation-hook nil
15855 "Hook for functions to attach themselves to TAB.
15856 See `org-ctrl-c-ctrl-c-hook' for more information.
15857 This hook runs after every other options for TAB have been exhausted, but
15858 before indentation and \t insertion takes place.")
15859
15860 (defvar org-metaleft-hook nil
15861 "Hook for functions attaching themselves to `M-left'.
15862 See `org-ctrl-c-ctrl-c-hook' for more information.")
15863 (defvar org-metaright-hook nil
15864 "Hook for functions attaching themselves to `M-right'.
15865 See `org-ctrl-c-ctrl-c-hook' for more information.")
15866 (defvar org-metaup-hook nil
15867 "Hook for functions attaching themselves to `M-up'.
15868 See `org-ctrl-c-ctrl-c-hook' for more information.")
15869 (defvar org-metadown-hook nil
15870 "Hook for functions attaching themselves to `M-down'.
15871 See `org-ctrl-c-ctrl-c-hook' for more information.")
15872 (defvar org-shiftmetaleft-hook nil
15873 "Hook for functions attaching themselves to `M-S-left'.
15874 See `org-ctrl-c-ctrl-c-hook' for more information.")
15875 (defvar org-shiftmetaright-hook nil
15876 "Hook for functions attaching themselves to `M-S-right'.
15877 See `org-ctrl-c-ctrl-c-hook' for more information.")
15878 (defvar org-shiftmetaup-hook nil
15879 "Hook for functions attaching themselves to `M-S-up'.
15880 See `org-ctrl-c-ctrl-c-hook' for more information.")
15881 (defvar org-shiftmetadown-hook nil
15882 "Hook for functions attaching themselves to `M-S-down'.
15883 See `org-ctrl-c-ctrl-c-hook' for more information.")
15884 (defvar org-metareturn-hook nil
15885 "Hook for functions attaching themselves to `M-RET'.
15886 See `org-ctrl-c-ctrl-c-hook' for more information.")
15887
15888 (defun org-modifier-cursor-error ()
15889 "Throw an error, a modified cursor command was applied in wrong context."
15890 (error "This command is active in special context like tables, headlines or items"))
15891
15892 (defun org-shiftselect-error ()
15893 "Throw an error because Shift-Cursor command was applied in wrong context."
15894 (if (and (boundp 'shift-select-mode) shift-select-mode)
15895 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'")
15896 (error "This command works only in special context like headlines or timestamps")))
15897
15898 (defun org-call-for-shift-select (cmd)
15899 (let ((this-command-keys-shift-translated t))
15900 (call-interactively cmd)))
15901
15902 (defun org-shifttab (&optional arg)
15903 "Global visibility cycling or move to previous table field.
15904 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
15905 on context.
15906 See the individual commands for more information."
15907 (interactive "P")
15908 (cond
15909 ((org-at-table-p) (call-interactively 'org-table-previous-field))
15910 ((integerp arg)
15911 (let ((arg2 (if org-odd-levels-only (1- (* 2 arg)) arg)))
15912 (message "Content view to level: %d" arg)
15913 (org-content (prefix-numeric-value arg2))
15914 (setq org-cycle-global-status 'overview)))
15915 (t (call-interactively 'org-global-cycle))))
15916
15917 (defun org-shiftmetaleft ()
15918 "Promote subtree or delete table column.
15919 Calls `org-promote-subtree', `org-outdent-item',
15920 or `org-table-delete-column', depending on context.
15921 See the individual commands for more information."
15922 (interactive)
15923 (cond
15924 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
15925 ((org-at-table-p) (call-interactively 'org-table-delete-column))
15926 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
15927 ((org-at-item-p) (call-interactively 'org-outdent-item))
15928 (t (org-modifier-cursor-error))))
15929
15930 (defun org-shiftmetaright ()
15931 "Demote subtree or insert table column.
15932 Calls `org-demote-subtree', `org-indent-item',
15933 or `org-table-insert-column', depending on context.
15934 See the individual commands for more information."
15935 (interactive)
15936 (cond
15937 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
15938 ((org-at-table-p) (call-interactively 'org-table-insert-column))
15939 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
15940 ((org-at-item-p) (call-interactively 'org-indent-item))
15941 (t (org-modifier-cursor-error))))
15942
15943 (defun org-shiftmetaup (&optional arg)
15944 "Move subtree up or kill table row.
15945 Calls `org-move-subtree-up' or `org-table-kill-row' or
15946 `org-move-item-up' depending on context. See the individual commands
15947 for more information."
15948 (interactive "P")
15949 (cond
15950 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
15951 ((org-at-table-p) (call-interactively 'org-table-kill-row))
15952 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
15953 ((org-at-item-p) (call-interactively 'org-move-item-up))
15954 (t (org-modifier-cursor-error))))
15955
15956 (defun org-shiftmetadown (&optional arg)
15957 "Move subtree down or insert table row.
15958 Calls `org-move-subtree-down' or `org-table-insert-row' or
15959 `org-move-item-down', depending on context. See the individual
15960 commands for more information."
15961 (interactive "P")
15962 (cond
15963 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
15964 ((org-at-table-p) (call-interactively 'org-table-insert-row))
15965 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
15966 ((org-at-item-p) (call-interactively 'org-move-item-down))
15967 (t (org-modifier-cursor-error))))
15968
15969 (defun org-metaleft (&optional arg)
15970 "Promote heading or move table column to left.
15971 Calls `org-do-promote' or `org-table-move-column', depending on context.
15972 With no specific context, calls the Emacs default `backward-word'.
15973 See the individual commands for more information."
15974 (interactive "P")
15975 (cond
15976 ((run-hook-with-args-until-success 'org-metaleft-hook))
15977 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
15978 ((or (org-on-heading-p)
15979 (and (org-region-active-p)
15980 (save-excursion
15981 (goto-char (region-beginning))
15982 (org-on-heading-p))))
15983 (call-interactively 'org-do-promote))
15984 ((or (org-at-item-p)
15985 (and (org-region-active-p)
15986 (save-excursion
15987 (goto-char (region-beginning))
15988 (org-at-item-p))))
15989 (call-interactively 'org-outdent-item))
15990 (t (call-interactively 'backward-word))))
15991
15992 (defun org-metaright (&optional arg)
15993 "Demote subtree or move table column to right.
15994 Calls `org-do-demote' or `org-table-move-column', depending on context.
15995 With no specific context, calls the Emacs default `forward-word'.
15996 See the individual commands for more information."
15997 (interactive "P")
15998 (cond
15999 ((run-hook-with-args-until-success 'org-metaright-hook))
16000 ((org-at-table-p) (call-interactively 'org-table-move-column))
16001 ((or (org-on-heading-p)
16002 (and (org-region-active-p)
16003 (save-excursion
16004 (goto-char (region-beginning))
16005 (org-on-heading-p))))
16006 (call-interactively 'org-do-demote))
16007 ((or (org-at-item-p)
16008 (and (org-region-active-p)
16009 (save-excursion
16010 (goto-char (region-beginning))
16011 (org-at-item-p))))
16012 (call-interactively 'org-indent-item))
16013 (t (call-interactively 'forward-word))))
16014
16015 (defun org-metaup (&optional arg)
16016 "Move subtree up or move table row up.
16017 Calls `org-move-subtree-up' or `org-table-move-row' or
16018 `org-move-item-up', depending on context. See the individual commands
16019 for more information."
16020 (interactive "P")
16021 (cond
16022 ((run-hook-with-args-until-success 'org-metaup-hook))
16023 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
16024 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
16025 ((org-at-item-p) (call-interactively 'org-move-item-up))
16026 (t (transpose-lines 1) (beginning-of-line -1))))
16027
16028 (defun org-metadown (&optional arg)
16029 "Move subtree down or move table row down.
16030 Calls `org-move-subtree-down' or `org-table-move-row' or
16031 `org-move-item-down', depending on context. See the individual
16032 commands for more information."
16033 (interactive "P")
16034 (cond
16035 ((run-hook-with-args-until-success 'org-metadown-hook))
16036 ((org-at-table-p) (call-interactively 'org-table-move-row))
16037 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
16038 ((org-at-item-p) (call-interactively 'org-move-item-down))
16039 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
16040
16041 (defun org-shiftup (&optional arg)
16042 "Increase item in timestamp or increase priority of current headline.
16043 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
16044 depending on context. See the individual commands for more information."
16045 (interactive "P")
16046 (cond
16047 ((and org-support-shift-select (org-region-active-p))
16048 (org-call-for-shift-select 'previous-line))
16049 ((org-at-timestamp-p t)
16050 (call-interactively (if org-edit-timestamp-down-means-later
16051 'org-timestamp-down 'org-timestamp-up)))
16052 ((and (not (eq org-support-shift-select 'always))
16053 org-enable-priority-commands
16054 (org-on-heading-p))
16055 (call-interactively 'org-priority-up))
16056 ((and (not org-support-shift-select) (org-at-item-p))
16057 (call-interactively 'org-previous-item))
16058 ((org-clocktable-try-shift 'up arg))
16059 (org-support-shift-select
16060 (org-call-for-shift-select 'previous-line))
16061 (t (org-shiftselect-error))))
16062
16063 (defun org-shiftdown (&optional arg)
16064 "Decrease item in timestamp or decrease priority of current headline.
16065 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
16066 depending on context. See the individual commands for more information."
16067 (interactive "P")
16068 (cond
16069 ((and org-support-shift-select (org-region-active-p))
16070 (org-call-for-shift-select 'next-line))
16071 ((org-at-timestamp-p t)
16072 (call-interactively (if org-edit-timestamp-down-means-later
16073 'org-timestamp-up 'org-timestamp-down)))
16074 ((and (not (eq org-support-shift-select 'always))
16075 org-enable-priority-commands
16076 (org-on-heading-p))
16077 (call-interactively 'org-priority-down))
16078 ((and (not org-support-shift-select) (org-at-item-p))
16079 (call-interactively 'org-next-item))
16080 ((org-clocktable-try-shift 'down arg))
16081 (org-support-shift-select
16082 (org-call-for-shift-select 'next-line))
16083 (t (org-shiftselect-error))))
16084
16085 (defun org-shiftright (&optional arg)
16086 "Cycle the thing at point or in the current line, depending on context.
16087 Depending on context, this does one of the following:
16088
16089 - switch a timestamp at point one day into the future
16090 - on a headline, switch to the next TODO keyword.
16091 - on an item, switch entire list to the next bullet type
16092 - on a property line, switch to the next allowed value
16093 - on a clocktable definition line, move time block into the future"
16094 (interactive "P")
16095 (cond
16096 ((and org-support-shift-select (org-region-active-p))
16097 (org-call-for-shift-select 'forward-char))
16098 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
16099 ((and (not (eq org-support-shift-select 'always))
16100 (org-on-heading-p))
16101 (let ((org-inhibit-logging
16102 (not org-treat-S-cursor-todo-selection-as-state-change))
16103 (org-inhibit-blocking
16104 (not org-treat-S-cursor-todo-selection-as-state-change)))
16105 (org-call-with-arg 'org-todo 'right)))
16106 ((or (and org-support-shift-select
16107 (not (eq org-support-shift-select 'always))
16108 (org-at-item-bullet-p))
16109 (and (not org-support-shift-select) (org-at-item-p)))
16110 (org-call-with-arg 'org-cycle-list-bullet nil))
16111 ((and (not (eq org-support-shift-select 'always))
16112 (org-at-property-p))
16113 (call-interactively 'org-property-next-allowed-value))
16114 ((org-clocktable-try-shift 'right arg))
16115 (org-support-shift-select
16116 (org-call-for-shift-select 'forward-char))
16117 (t (org-shiftselect-error))))
16118
16119 (defun org-shiftleft (&optional arg)
16120 "Cycle the thing at point or in the current line, depending on context.
16121 Depending on context, this does one of the following:
16122
16123 - switch a timestamp at point one day into the past
16124 - on a headline, switch to the previous TODO keyword.
16125 - on an item, switch entire list to the previous bullet type
16126 - on a property line, switch to the previous allowed value
16127 - on a clocktable definition line, move time block into the past"
16128 (interactive "P")
16129 (cond
16130 ((and org-support-shift-select (org-region-active-p))
16131 (org-call-for-shift-select 'backward-char))
16132 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
16133 ((and (not (eq org-support-shift-select 'always))
16134 (org-on-heading-p))
16135 (let ((org-inhibit-logging
16136 (not org-treat-S-cursor-todo-selection-as-state-change))
16137 (org-inhibit-blocking
16138 (not org-treat-S-cursor-todo-selection-as-state-change)))
16139 (org-call-with-arg 'org-todo 'left)))
16140 ((or (and org-support-shift-select
16141 (not (eq org-support-shift-select 'always))
16142 (org-at-item-bullet-p))
16143 (and (not org-support-shift-select) (org-at-item-p)))
16144 (org-call-with-arg 'org-cycle-list-bullet 'previous))
16145 ((and (not (eq org-support-shift-select 'always))
16146 (org-at-property-p))
16147 (call-interactively 'org-property-previous-allowed-value))
16148 ((org-clocktable-try-shift 'left arg))
16149 (org-support-shift-select
16150 (org-call-for-shift-select 'backward-char))
16151 (t (org-shiftselect-error))))
16152
16153 (defun org-shiftcontrolright ()
16154 "Switch to next TODO set."
16155 (interactive)
16156 (cond
16157 ((and org-support-shift-select (org-region-active-p))
16158 (org-call-for-shift-select 'forward-word))
16159 ((and (not (eq org-support-shift-select 'always))
16160 (org-on-heading-p))
16161 (org-call-with-arg 'org-todo 'nextset))
16162 (org-support-shift-select
16163 (org-call-for-shift-select 'forward-word))
16164 (t (org-shiftselect-error))))
16165
16166 (defun org-shiftcontrolleft ()
16167 "Switch to previous TODO set."
16168 (interactive)
16169 (cond
16170 ((and org-support-shift-select (org-region-active-p))
16171 (org-call-for-shift-select 'backward-word))
16172 ((and (not (eq org-support-shift-select 'always))
16173 (org-on-heading-p))
16174 (org-call-with-arg 'org-todo 'previousset))
16175 (org-support-shift-select
16176 (org-call-for-shift-select 'backward-word))
16177 (t (org-shiftselect-error))))
16178
16179 (defun org-ctrl-c-ret ()
16180 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
16181 (interactive)
16182 (cond
16183 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
16184 (t (call-interactively 'org-insert-heading))))
16185
16186 (defun org-copy-special ()
16187 "Copy region in table or copy current subtree.
16188 Calls `org-table-copy' or `org-copy-subtree', depending on context.
16189 See the individual commands for more information."
16190 (interactive)
16191 (call-interactively
16192 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
16193
16194 (defun org-cut-special ()
16195 "Cut region in table or cut current subtree.
16196 Calls `org-table-copy' or `org-cut-subtree', depending on context.
16197 See the individual commands for more information."
16198 (interactive)
16199 (call-interactively
16200 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
16201
16202 (defun org-paste-special (arg)
16203 "Paste rectangular region into table, or past subtree relative to level.
16204 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
16205 See the individual commands for more information."
16206 (interactive "P")
16207 (if (org-at-table-p)
16208 (org-table-paste-rectangle)
16209 (org-paste-subtree arg)))
16210
16211 (defun org-edit-special ()
16212 "Call a special editor for the stuff at point.
16213 When at a table, call the formula editor with `org-table-edit-formulas'.
16214 When at the first line of an src example, call `org-edit-src-code'.
16215 When in an #+include line, visit the include file. Otherwise call
16216 `ffap' to visit the file at point."
16217 (interactive)
16218 (cond
16219 ((org-at-table.el-p)
16220 (org-edit-src-code))
16221 ((org-at-table-p)
16222 (call-interactively 'org-table-edit-formulas))
16223 ((save-excursion
16224 (beginning-of-line 1)
16225 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
16226 (find-file (org-trim (match-string 1))))
16227 ((org-edit-src-code))
16228 ((org-edit-fixed-width-region))
16229 (t (call-interactively 'ffap))))
16230
16231
16232 (defun org-ctrl-c-ctrl-c (&optional arg)
16233 "Set tags in headline, or update according to changed information at point.
16234
16235 This command does many different things, depending on context:
16236
16237 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
16238 this is what we do.
16239
16240 - If the cursor is on a statistics cookie, update it.
16241
16242 - If the cursor is in a headline, prompt for tags and insert them
16243 into the current line, aligned to `org-tags-column'. When called
16244 with prefix arg, realign all tags in the current buffer.
16245
16246 - If the cursor is in one of the special #+KEYWORD lines, this
16247 triggers scanning the buffer for these lines and updating the
16248 information.
16249
16250 - If the cursor is inside a table, realign the table. This command
16251 works even if the automatic table editor has been turned off.
16252
16253 - If the cursor is on a #+TBLFM line, re-apply the formulas to
16254 the entire table.
16255
16256 - If the cursor is at a footnote reference or definition, jump to
16257 the corresponding definition or references, respectively.
16258
16259 - If the cursor is a the beginning of a dynamic block, update it.
16260
16261 - If the current buffer is a remember buffer, close note and file
16262 it. A prefix argument of 1 files to the default location
16263 without further interaction. A prefix argument of 2 files to
16264 the currently clocking task.
16265
16266 - If the cursor is on a <<<target>>>, update radio targets and corresponding
16267 links in this buffer.
16268
16269 - If the cursor is on a numbered item in a plain list, renumber the
16270 ordered list.
16271
16272 - If the cursor is on a checkbox, toggle it."
16273 (interactive "P")
16274 (let ((org-enable-table-editor t))
16275 (cond
16276 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
16277 org-occur-highlights
16278 org-latex-fragment-image-overlays)
16279 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
16280 (org-remove-occur-highlights)
16281 (org-remove-latex-fragment-image-overlays)
16282 (message "Temporary highlights/overlays removed from current buffer"))
16283 ((and (local-variable-p 'org-finish-function (current-buffer))
16284 (fboundp org-finish-function))
16285 (funcall org-finish-function))
16286 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
16287 ((or (looking-at org-property-start-re)
16288 (org-at-property-p))
16289 (call-interactively 'org-property-action))
16290 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
16291 ((and (org-in-regexp "\\[\\([0-9]*%\\|[0-9]*/[0-9]*\\)\\]")
16292 (or (org-on-heading-p) (org-at-item-p)))
16293 (call-interactively 'org-update-statistics-cookies))
16294 ((org-on-heading-p) (call-interactively 'org-set-tags))
16295 ((org-at-table.el-p)
16296 (message "Use C-c ' to edit table.el tables"))
16297 ((org-at-table-p)
16298 (org-table-maybe-eval-formula)
16299 (if arg
16300 (call-interactively 'org-table-recalculate)
16301 (org-table-maybe-recalculate-line))
16302 (call-interactively 'org-table-align))
16303 ((or (org-footnote-at-reference-p)
16304 (org-footnote-at-definition-p))
16305 (call-interactively 'org-footnote-action))
16306 ((org-at-item-checkbox-p)
16307 (call-interactively 'org-toggle-checkbox))
16308 ((org-at-item-p)
16309 (if arg
16310 (call-interactively 'org-toggle-checkbox)
16311 (call-interactively 'org-maybe-renumber-ordered-list)))
16312 ((save-excursion (beginning-of-line 1) (looking-at org-dblock-start-re))
16313 ;; Dynamic block
16314 (beginning-of-line 1)
16315 (save-excursion (org-update-dblock)))
16316 ((save-excursion
16317 (beginning-of-line 1)
16318 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
16319 (cond
16320 ((equal (match-string 1) "TBLFM")
16321 ;; Recalculate the table before this line
16322 (save-excursion
16323 (beginning-of-line 1)
16324 (skip-chars-backward " \r\n\t")
16325 (if (org-at-table-p)
16326 (org-call-with-arg 'org-table-recalculate (or arg t)))))
16327 (t
16328 (let ((org-inhibit-startup-visibility-stuff t)
16329 (org-startup-align-all-tables nil))
16330 (org-save-outline-visibility 'use-markers (org-mode-restart)))
16331 (message "Local setup has been refreshed"))))
16332 ((org-clock-update-time-maybe))
16333 (t (error "C-c C-c can do nothing useful at this location")))))
16334
16335 (defun org-mode-restart ()
16336 "Restart Org-mode, to scan again for special lines.
16337 Also updates the keyword regular expressions."
16338 (interactive)
16339 (org-mode)
16340 (message "Org-mode restarted"))
16341
16342 (defun org-kill-note-or-show-branches ()
16343 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
16344 (interactive)
16345 (if (not org-finish-function)
16346 (call-interactively 'show-branches)
16347 (let ((org-note-abort t))
16348 (funcall org-finish-function))))
16349
16350 (defun org-return (&optional indent)
16351 "Goto next table row or insert a newline.
16352 Calls `org-table-next-row' or `newline', depending on context.
16353 See the individual commands for more information."
16354 (interactive)
16355 (cond
16356 ((bobp) (if indent (newline-and-indent) (newline)))
16357 ((org-at-table-p)
16358 (org-table-justify-field-maybe)
16359 (call-interactively 'org-table-next-row))
16360 ((and org-return-follows-link
16361 (eq (get-text-property (point) 'face) 'org-link))
16362 (call-interactively 'org-open-at-point))
16363 ((and (org-at-heading-p)
16364 (looking-at
16365 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
16366 (org-show-entry)
16367 (end-of-line 1)
16368 (newline))
16369 (t (if indent (newline-and-indent) (newline)))))
16370
16371 (defun org-return-indent ()
16372 "Goto next table row or insert a newline and indent.
16373 Calls `org-table-next-row' or `newline-and-indent', depending on
16374 context. See the individual commands for more information."
16375 (interactive)
16376 (org-return t))
16377
16378 (defun org-ctrl-c-star ()
16379 "Compute table, or change heading status of lines.
16380 Calls `org-table-recalculate' or `org-toggle-heading',
16381 depending on context."
16382 (interactive)
16383 (cond
16384 ((org-at-table-p)
16385 (call-interactively 'org-table-recalculate))
16386 (t
16387 ;; Convert all lines in region to list items
16388 (call-interactively 'org-toggle-heading))))
16389
16390 (defun org-ctrl-c-minus ()
16391 "Insert separator line in table or modify bullet status of line.
16392 Also turns a plain line or a region of lines into list items.
16393 Calls `org-table-insert-hline', `org-toggle-item', or
16394 `org-cycle-list-bullet', depending on context."
16395 (interactive)
16396 (cond
16397 ((org-at-table-p)
16398 (call-interactively 'org-table-insert-hline))
16399 ((org-region-active-p)
16400 (call-interactively 'org-toggle-item))
16401 ((org-in-item-p)
16402 (call-interactively 'org-cycle-list-bullet))
16403 (t
16404 (call-interactively 'org-toggle-item))))
16405
16406 (defun org-toggle-item ()
16407 "Convert headings or normal lines to items, items to normal lines.
16408 If there is no active region, only the current line is considered.
16409
16410 If the first line in the region is a headline, convert all headlines to items.
16411
16412 If the first line in the region is an item, convert all items to normal lines.
16413
16414 If the first line is normal text, add an item bullet to each line."
16415 (interactive)
16416 (let (l2 l beg end)
16417 (if (org-region-active-p)
16418 (setq beg (region-beginning) end (region-end))
16419 (setq beg (point-at-bol)
16420 end (min (1+ (point-at-eol)) (point-max))))
16421 (save-excursion
16422 (goto-char end)
16423 (setq l2 (org-current-line))
16424 (goto-char beg)
16425 (beginning-of-line 1)
16426 (setq l (1- (org-current-line)))
16427 (if (org-at-item-p)
16428 ;; We already have items, de-itemize
16429 (while (< (setq l (1+ l)) l2)
16430 (when (org-at-item-p)
16431 (goto-char (match-beginning 2))
16432 (delete-region (match-beginning 2) (match-end 2))
16433 (and (looking-at "[ \t]+") (replace-match "")))
16434 (beginning-of-line 2))
16435 (if (org-on-heading-p)
16436 ;; Headings, convert to items
16437 (while (< (setq l (1+ l)) l2)
16438 (if (looking-at org-outline-regexp)
16439 (replace-match "- " t t))
16440 (beginning-of-line 2))
16441 ;; normal lines, turn them into items
16442 (while (< (setq l (1+ l)) l2)
16443 (unless (org-at-item-p)
16444 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16445 (replace-match "\\1- \\2")))
16446 (beginning-of-line 2)))))))
16447
16448 (defun org-toggle-heading (&optional nstars)
16449 "Convert headings to normal text, or items or text to headings.
16450 If there is no active region, only the current line is considered.
16451
16452 If the first line is a heading, remove the stars from all headlines
16453 in the region.
16454
16455 If the first line is a plain list item, turn all plain list items
16456 into headings.
16457
16458 If the first line is a normal line, turn each and every line in the
16459 region into a heading.
16460
16461 When converting a line into a heading, the number of stars is chosen
16462 such that the lines become children of the current entry. However,
16463 when a prefix argument is given, its value determines the number of
16464 stars to add."
16465 (interactive "P")
16466 (let (l2 l itemp beg end)
16467 (if (org-region-active-p)
16468 (setq beg (region-beginning) end (region-end))
16469 (setq beg (point-at-bol)
16470 end (min (1+ (point-at-eol)) (point-max))))
16471 (save-excursion
16472 (goto-char end)
16473 (setq l2 (org-current-line))
16474 (goto-char beg)
16475 (beginning-of-line 1)
16476 (setq l (1- (org-current-line)))
16477 (if (org-on-heading-p)
16478 ;; We already have headlines, de-star them
16479 (while (< (setq l (1+ l)) l2)
16480 (when (org-on-heading-p t)
16481 (and (looking-at outline-regexp) (replace-match "")))
16482 (beginning-of-line 2))
16483 (setq itemp (org-at-item-p))
16484 (let* ((stars
16485 (if nstars
16486 (make-string (prefix-numeric-value current-prefix-arg)
16487 ?*)
16488 (save-excursion
16489 (if (re-search-backward org-complex-heading-regexp nil t)
16490 (match-string 1) ""))))
16491 (add-stars (cond (nstars "")
16492 ((equal stars "") "*")
16493 (org-odd-levels-only "**")
16494 (t "*")))
16495 (rpl (concat stars add-stars " ")))
16496 (while (< (setq l (1+ l)) l2)
16497 (if itemp
16498 (and (org-at-item-p) (replace-match rpl t t))
16499 (unless (org-on-heading-p)
16500 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
16501 (replace-match (concat rpl (match-string 2))))))
16502 (beginning-of-line 2)))))))
16503
16504 (defun org-meta-return (&optional arg)
16505 "Insert a new heading or wrap a region in a table.
16506 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
16507 See the individual commands for more information."
16508 (interactive "P")
16509 (cond
16510 ((run-hook-with-args-until-success 'org-metareturn-hook))
16511 ((org-at-table-p)
16512 (call-interactively 'org-table-wrap-region))
16513 (t (call-interactively 'org-insert-heading))))
16514
16515 ;;; Menu entries
16516
16517 ;; Define the Org-mode menus
16518 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
16519 '("Tbl"
16520 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
16521 ["Next Field" org-cycle (org-at-table-p)]
16522 ["Previous Field" org-shifttab (org-at-table-p)]
16523 ["Next Row" org-return (org-at-table-p)]
16524 "--"
16525 ["Blank Field" org-table-blank-field (org-at-table-p)]
16526 ["Edit Field" org-table-edit-field (org-at-table-p)]
16527 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
16528 "--"
16529 ("Column"
16530 ["Move Column Left" org-metaleft (org-at-table-p)]
16531 ["Move Column Right" org-metaright (org-at-table-p)]
16532 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
16533 ["Insert Column" org-shiftmetaright (org-at-table-p)])
16534 ("Row"
16535 ["Move Row Up" org-metaup (org-at-table-p)]
16536 ["Move Row Down" org-metadown (org-at-table-p)]
16537 ["Delete Row" org-shiftmetaup (org-at-table-p)]
16538 ["Insert Row" org-shiftmetadown (org-at-table-p)]
16539 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
16540 "--"
16541 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
16542 ("Rectangle"
16543 ["Copy Rectangle" org-copy-special (org-at-table-p)]
16544 ["Cut Rectangle" org-cut-special (org-at-table-p)]
16545 ["Paste Rectangle" org-paste-special (org-at-table-p)]
16546 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
16547 "--"
16548 ("Calculate"
16549 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
16550 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
16551 ["Edit Formulas" org-edit-special (org-at-table-p)]
16552 "--"
16553 ["Recalculate line" org-table-recalculate (org-at-table-p)]
16554 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
16555 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
16556 "--"
16557 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
16558 "--"
16559 ["Sum Column/Rectangle" org-table-sum
16560 (or (org-at-table-p) (org-region-active-p))]
16561 ["Which Column?" org-table-current-column (org-at-table-p)])
16562 ["Debug Formulas"
16563 org-table-toggle-formula-debugger
16564 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
16565 ["Show Col/Row Numbers"
16566 org-table-toggle-coordinate-overlays
16567 :style toggle
16568 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
16569 "--"
16570 ["Create" org-table-create (and (not (org-at-table-p))
16571 org-enable-table-editor)]
16572 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
16573 ["Import from File" org-table-import (not (org-at-table-p))]
16574 ["Export to File" org-table-export (org-at-table-p)]
16575 "--"
16576 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
16577
16578 (easy-menu-define org-org-menu org-mode-map "Org menu"
16579 '("Org"
16580 ("Show/Hide"
16581 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
16582 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
16583 ["Sparse Tree..." org-sparse-tree t]
16584 ["Reveal Context" org-reveal t]
16585 ["Show All" show-all t]
16586 "--"
16587 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
16588 "--"
16589 ["New Heading" org-insert-heading t]
16590 ("Navigate Headings"
16591 ["Up" outline-up-heading t]
16592 ["Next" outline-next-visible-heading t]
16593 ["Previous" outline-previous-visible-heading t]
16594 ["Next Same Level" outline-forward-same-level t]
16595 ["Previous Same Level" outline-backward-same-level t]
16596 "--"
16597 ["Jump" org-goto t])
16598 ("Edit Structure"
16599 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
16600 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
16601 "--"
16602 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
16603 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
16604 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
16605 "--"
16606 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
16607 "--"
16608 ["Promote Heading" org-metaleft (not (org-at-table-p))]
16609 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
16610 ["Demote Heading" org-metaright (not (org-at-table-p))]
16611 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
16612 "--"
16613 ["Sort Region/Children" org-sort (not (org-at-table-p))]
16614 "--"
16615 ["Convert to odd levels" org-convert-to-odd-levels t]
16616 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
16617 ("Editing"
16618 ["Emphasis..." org-emphasize t]
16619 ["Edit Source Example" org-edit-special t]
16620 "--"
16621 ["Footnote new/jump" org-footnote-action t]
16622 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
16623 ("Archive"
16624 ["Archive (default method)" org-archive-subtree-default t]
16625 "--"
16626 ["Move Subtree to Archive file" org-advertized-archive-subtree t]
16627 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
16628 ["Move subtree to Archive sibling" org-archive-to-archive-sibling t]
16629 )
16630 "--"
16631 ("Hyperlinks"
16632 ["Store Link (Global)" org-store-link t]
16633 ["Find existing link to here" org-occur-link-in-agenda-files t]
16634 ["Insert Link" org-insert-link t]
16635 ["Follow Link" org-open-at-point t]
16636 "--"
16637 ["Next link" org-next-link t]
16638 ["Previous link" org-previous-link t]
16639 "--"
16640 ["Descriptive Links"
16641 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
16642 :style radio
16643 :selected (member '(org-link) buffer-invisibility-spec)]
16644 ["Literal Links"
16645 (progn
16646 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
16647 :style radio
16648 :selected (not (member '(org-link) buffer-invisibility-spec))])
16649 "--"
16650 ("TODO Lists"
16651 ["TODO/DONE/-" org-todo t]
16652 ("Select keyword"
16653 ["Next keyword" org-shiftright (org-on-heading-p)]
16654 ["Previous keyword" org-shiftleft (org-on-heading-p)]
16655 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
16656 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
16657 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
16658 ["Show TODO Tree" org-show-todo-tree t]
16659 ["Global TODO list" org-todo-list t]
16660 "--"
16661 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
16662 :selected org-enforce-todo-dependencies :style toggle :active t]
16663 "Settings for tree at point"
16664 ["Do Children sequentially" org-toggle-ordered-property :style radio
16665 :selected (ignore-errors (org-entry-get nil "ORDERED"))
16666 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16667 ["Do Children parallel" org-toggle-ordered-property :style radio
16668 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
16669 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
16670 "--"
16671 ["Set Priority" org-priority t]
16672 ["Priority Up" org-shiftup t]
16673 ["Priority Down" org-shiftdown t]
16674 "--"
16675 ["Get news from all feeds" org-feed-update-all t]
16676 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
16677 ["Customize feeds" (customize-variable 'org-feed-alist) t])
16678 ("TAGS and Properties"
16679 ["Set Tags" org-set-tags-command t]
16680 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
16681 "--"
16682 ["Set property" org-set-property t]
16683 ["Column view of properties" org-columns t]
16684 ["Insert Column View DBlock" org-insert-columns-dblock t])
16685 ("Dates and Scheduling"
16686 ["Timestamp" org-time-stamp t]
16687 ["Timestamp (inactive)" org-time-stamp-inactive t]
16688 ("Change Date"
16689 ["1 Day Later" org-shiftright t]
16690 ["1 Day Earlier" org-shiftleft t]
16691 ["1 ... Later" org-shiftup t]
16692 ["1 ... Earlier" org-shiftdown t])
16693 ["Compute Time Range" org-evaluate-time-range t]
16694 ["Schedule Item" org-schedule t]
16695 ["Deadline" org-deadline t]
16696 "--"
16697 ["Custom time format" org-toggle-time-stamp-overlays
16698 :style radio :selected org-display-custom-times]
16699 "--"
16700 ["Goto Calendar" org-goto-calendar t]
16701 ["Date from Calendar" org-date-from-calendar t]
16702 "--"
16703 ["Start/Restart Timer" org-timer-start t]
16704 ["Pause/Continue Timer" org-timer-pause-or-continue t]
16705 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
16706 ["Insert Timer String" org-timer t]
16707 ["Insert Timer Item" org-timer-item t])
16708 ("Logging work"
16709 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
16710 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
16711 ["Clock out" org-clock-out t]
16712 ["Clock cancel" org-clock-cancel t]
16713 "--"
16714 ["Mark as default task" org-clock-mark-default-task t]
16715 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
16716 ["Goto running clock" org-clock-goto t]
16717 "--"
16718 ["Display times" org-clock-display t]
16719 ["Create clock table" org-clock-report t]
16720 "--"
16721 ["Record DONE time"
16722 (progn (setq org-log-done (not org-log-done))
16723 (message "Switching to %s will %s record a timestamp"
16724 (car org-done-keywords)
16725 (if org-log-done "automatically" "not")))
16726 :style toggle :selected org-log-done])
16727 "--"
16728 ["Agenda Command..." org-agenda t]
16729 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
16730 ("File List for Agenda")
16731 ("Special views current file"
16732 ["TODO Tree" org-show-todo-tree t]
16733 ["Check Deadlines" org-check-deadlines t]
16734 ["Timeline" org-timeline t]
16735 ["Tags/Property tree" org-match-sparse-tree t])
16736 "--"
16737 ["Export/Publish..." org-export t]
16738 ("LaTeX"
16739 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
16740 :selected org-cdlatex-mode]
16741 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
16742 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
16743 ["Modify math symbol" org-cdlatex-math-modify
16744 (org-inside-LaTeX-fragment-p)]
16745 ["Insert citation" org-reftex-citation t]
16746 "--"
16747 ["Export LaTeX fragments as images"
16748 (if (featurep 'org-exp)
16749 (setq org-export-with-LaTeX-fragments
16750 (not org-export-with-LaTeX-fragments))
16751 (require 'org-exp))
16752 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
16753 org-export-with-LaTeX-fragments)]
16754 "--"
16755 ["Template for BEAMER" org-beamer-settings-template t])
16756 "--"
16757 ("MobileOrg"
16758 ["Push Files and Views" org-mobile-push t]
16759 ["Get Captured and Flagged" org-mobile-pull t]
16760 ["Find FLAGGED Tasks" (org-agenda nil "?") :active t :keys "C-c a ?"]
16761 "--"
16762 ["Setup" (progn (require 'org-mobile) (customize-group 'org-mobile)) t])
16763 "--"
16764 ("Documentation"
16765 ["Show Version" org-version t]
16766 ["Info Documentation" org-info t])
16767 ("Customize"
16768 ["Browse Org Group" org-customize t]
16769 "--"
16770 ["Expand This Menu" org-create-customize-menu
16771 (fboundp 'customize-menu-create)])
16772 ["Send bug report" org-submit-bug-report t]
16773 "--"
16774 ("Refresh/Reload"
16775 ["Refresh setup current buffer" org-mode-restart t]
16776 ["Reload Org (after update)" org-reload t]
16777 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
16778 ))
16779
16780 (defun org-info (&optional node)
16781 "Read documentation for Org-mode in the info system.
16782 With optional NODE, go directly to that node."
16783 (interactive)
16784 (info (format "(org)%s" (or node ""))))
16785
16786 ;;;###autoload
16787 (defun org-submit-bug-report ()
16788 "Submit a bug report on Org-mode via mail.
16789
16790 Don't hesitate to report any problems or inaccurate documentation.
16791
16792 If you don't have setup sending mail from (X)Emacs, please copy the
16793 output buffer into your mail program, as it gives us important
16794 information about your Org-mode version and configuration."
16795 (interactive)
16796 (require 'reporter)
16797 (org-load-modules-maybe)
16798 (org-require-autoloaded-modules)
16799 (let ((reporter-prompt-for-summary-p "Bug report subject: "))
16800 (reporter-submit-bug-report
16801 "emacs-orgmode@gnu.org"
16802 (org-version)
16803 (let (list)
16804 (save-window-excursion
16805 (switch-to-buffer (get-buffer-create "*Warn about privacy*"))
16806 (delete-other-windows)
16807 (erase-buffer)
16808 (insert "You are about to submit a bug report to the Org-mode mailing list.
16809
16810 We would like to add your full Org-mode and Outline configuration to the
16811 bug report. This greatly simplifies the work of the maintainer and
16812 other experts on the mailing list.
16813
16814 HOWEVER, some variables you have customized may contain private
16815 information. The names of customers, colleagues, or friends, might
16816 appear in the form of file names, tags, todo states, or search strings.
16817 If you answer yes to the prompt, you might want to check and remove
16818 such private information before sending the email.")
16819 (add-text-properties (point-min) (point-max) '(face org-warning))
16820 (when (yes-or-no-p "Include your Org-mode configuration ")
16821 (mapatoms
16822 (lambda (v)
16823 (and (boundp v)
16824 (string-match "\\`\\(org-\\|outline-\\)" (symbol-name v))
16825 (or (and (symbol-value v)
16826 (string-match "\\(-hook\\|-function\\)\\'" (symbol-name v)))
16827 (and
16828 (get v 'custom-type) (get v 'standard-value)
16829 (not (equal (symbol-value v) (eval (car (get v 'standard-value)))))))
16830 (push v list)))))
16831 (kill-buffer (get-buffer "*Warn about privacy*"))
16832 list))
16833 nil nil
16834 "Remember to cover the basics, that is, what you expected to happen and
16835 what in fact did happen. You don't know how to make a good report? See
16836
16837 http://orgmode.org/manual/Feedback.html#Feedback
16838
16839 Your bug report will be posted to the Org-mode mailing list.
16840 ------------------------------------------------------------------------")
16841 (save-excursion
16842 (if (re-search-backward "^\\(Subject: \\)Org-mode version \\(.*?\\);[ \t]*\\(.*\\)" nil t)
16843 (replace-match "\\1Bug: \\3 [\\2]")))))
16844
16845
16846 (defun org-install-agenda-files-menu ()
16847 (let ((bl (buffer-list)))
16848 (save-excursion
16849 (while bl
16850 (set-buffer (pop bl))
16851 (if (org-mode-p) (setq bl nil)))
16852 (when (org-mode-p)
16853 (easy-menu-change
16854 '("Org") "File List for Agenda"
16855 (append
16856 (list
16857 ["Edit File List" (org-edit-agenda-file-list) t]
16858 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
16859 ["Remove Current File from List" org-remove-file t]
16860 ["Cycle through agenda files" org-cycle-agenda-files t]
16861 ["Occur in all agenda files" org-occur-in-agenda-files t]
16862 "--")
16863 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
16864
16865 ;;;; Documentation
16866
16867 ;;;###autoload
16868 (defun org-require-autoloaded-modules ()
16869 (interactive)
16870 (mapc 'require
16871 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
16872 org-docbook org-exp org-html org-icalendar
16873 org-id org-latex
16874 org-publish org-remember org-table
16875 org-timer org-xoxo)))
16876
16877 ;;;###autoload
16878 (defun org-reload (&optional uncompiled)
16879 "Reload all org lisp files.
16880 With prefix arg UNCOMPILED, load the uncompiled versions."
16881 (interactive "P")
16882 (require 'find-func)
16883 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
16884 (dir-org (file-name-directory (org-find-library-name "org")))
16885 (dir-org-contrib (ignore-errors
16886 (file-name-directory
16887 (org-find-library-name "org-contribdir"))))
16888 (files
16889 (append (directory-files dir-org t file-re)
16890 (and dir-org-contrib
16891 (directory-files dir-org-contrib t file-re))))
16892 (remove-re (concat (if (featurep 'xemacs)
16893 "org-colview" "org-colview-xemacs")
16894 "\\'")))
16895 (setq files (mapcar 'file-name-sans-extension files))
16896 (setq files (mapcar
16897 (lambda (x) (if (string-match remove-re x) nil x))
16898 files))
16899 (setq files (delq nil files))
16900 (mapc
16901 (lambda (f)
16902 (when (featurep (intern (file-name-nondirectory f)))
16903 (if (and (not uncompiled)
16904 (file-exists-p (concat f ".elc")))
16905 (load (concat f ".elc") nil nil t)
16906 (load (concat f ".el") nil nil t))))
16907 files))
16908 (org-version))
16909
16910 ;;;###autoload
16911 (defun org-customize ()
16912 "Call the customize function with org as argument."
16913 (interactive)
16914 (org-load-modules-maybe)
16915 (org-require-autoloaded-modules)
16916 (customize-browse 'org))
16917
16918 (defun org-create-customize-menu ()
16919 "Create a full customization menu for Org-mode, insert it into the menu."
16920 (interactive)
16921 (org-load-modules-maybe)
16922 (org-require-autoloaded-modules)
16923 (if (fboundp 'customize-menu-create)
16924 (progn
16925 (easy-menu-change
16926 '("Org") "Customize"
16927 `(["Browse Org group" org-customize t]
16928 "--"
16929 ,(customize-menu-create 'org)
16930 ["Set" Custom-set t]
16931 ["Save" Custom-save t]
16932 ["Reset to Current" Custom-reset-current t]
16933 ["Reset to Saved" Custom-reset-saved t]
16934 ["Reset to Standard Settings" Custom-reset-standard t]))
16935 (message "\"Org\"-menu now contains full customization menu"))
16936 (error "Cannot expand menu (outdated version of cus-edit.el)")))
16937
16938 ;;;; Miscellaneous stuff
16939
16940 ;;; Generally useful functions
16941
16942 (defun org-get-at-bol (property)
16943 "Get text property PROPERTY at beginning of line."
16944 (get-text-property (point-at-bol) property))
16945
16946 (defun org-find-text-property-in-string (prop s)
16947 "Return the first non-nil value of property PROP in string S."
16948 (or (get-text-property 0 prop s)
16949 (get-text-property (or (next-single-property-change 0 prop s) 0)
16950 prop s)))
16951
16952 (defun org-display-warning (message) ;; Copied from Emacs-Muse
16953 "Display the given MESSAGE as a warning."
16954 (if (fboundp 'display-warning)
16955 (display-warning 'org message
16956 (if (featurep 'xemacs)
16957 'warning
16958 :warning))
16959 (let ((buf (get-buffer-create "*Org warnings*")))
16960 (with-current-buffer buf
16961 (goto-char (point-max))
16962 (insert "Warning (Org): " message)
16963 (unless (bolp)
16964 (newline)))
16965 (display-buffer buf)
16966 (sit-for 0))))
16967
16968 (defun org-in-commented-line ()
16969 "Is point in a line starting with `#'?"
16970 (equal (char-after (point-at-bol)) ?#))
16971
16972 (defun org-in-verbatim-emphasis ()
16973 (save-match-data
16974 (and (org-in-regexp org-emph-re 2) (member (match-string 3) '("=" "~")))))
16975
16976 (defun org-goto-marker-or-bmk (marker &optional bookmark)
16977 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
16978 (if (and marker (marker-buffer marker)
16979 (buffer-live-p (marker-buffer marker)))
16980 (progn
16981 (switch-to-buffer (marker-buffer marker))
16982 (if (or (> marker (point-max)) (< marker (point-min)))
16983 (widen))
16984 (goto-char marker)
16985 (org-show-context 'org-goto))
16986 (if bookmark
16987 (bookmark-jump bookmark)
16988 (error "Cannot find location"))))
16989
16990 (defun org-quote-csv-field (s)
16991 "Quote field for inclusion in CSV material."
16992 (if (string-match "[\",]" s)
16993 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
16994 s))
16995
16996 (defun org-plist-delete (plist property)
16997 "Delete PROPERTY from PLIST.
16998 This is in contrast to merely setting it to 0."
16999 (let (p)
17000 (while plist
17001 (if (not (eq property (car plist)))
17002 (setq p (plist-put p (car plist) (nth 1 plist))))
17003 (setq plist (cddr plist)))
17004 p))
17005
17006 (defun org-force-self-insert (N)
17007 "Needed to enforce self-insert under remapping."
17008 (interactive "p")
17009 (self-insert-command N))
17010
17011 (defun org-string-width (s)
17012 "Compute width of string, ignoring invisible characters.
17013 This ignores character with invisibility property `org-link', and also
17014 characters with property `org-cwidth', because these will become invisible
17015 upon the next fontification round."
17016 (let (b l)
17017 (when (or (eq t buffer-invisibility-spec)
17018 (assq 'org-link buffer-invisibility-spec))
17019 (while (setq b (text-property-any 0 (length s)
17020 'invisible 'org-link s))
17021 (setq s (concat (substring s 0 b)
17022 (substring s (or (next-single-property-change
17023 b 'invisible s) (length s)))))))
17024 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
17025 (setq s (concat (substring s 0 b)
17026 (substring s (or (next-single-property-change
17027 b 'org-cwidth s) (length s))))))
17028 (setq l (string-width s) b -1)
17029 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
17030 (setq l (- l (get-text-property b 'org-dwidth-n s))))
17031 l))
17032
17033 (defun org-get-indentation (&optional line)
17034 "Get the indentation of the current line, interpreting tabs.
17035 When LINE is given, assume it represents a line and compute its indentation."
17036 (if line
17037 (if (string-match "^ *" (org-remove-tabs line))
17038 (match-end 0))
17039 (save-excursion
17040 (beginning-of-line 1)
17041 (skip-chars-forward " \t")
17042 (current-column))))
17043
17044 (defun org-remove-tabs (s &optional width)
17045 "Replace tabulators in S with spaces.
17046 Assumes that s is a single line, starting in column 0."
17047 (setq width (or width tab-width))
17048 (while (string-match "\t" s)
17049 (setq s (replace-match
17050 (make-string
17051 (- (* width (/ (+ (match-beginning 0) width) width))
17052 (match-beginning 0)) ?\ )
17053 t t s)))
17054 s)
17055
17056 (defun org-fix-indentation (line ind)
17057 "Fix indentation in LINE.
17058 IND is a cons cell with target and minimum indentation.
17059 If the current indentation in LINE is smaller than the minimum,
17060 leave it alone. If it is larger than ind, set it to the target."
17061 (let* ((l (org-remove-tabs line))
17062 (i (org-get-indentation l))
17063 (i1 (car ind)) (i2 (cdr ind)))
17064 (if (>= i i2) (setq l (substring line i2)))
17065 (if (> i1 0)
17066 (concat (make-string i1 ?\ ) l)
17067 l)))
17068
17069 (defun org-remove-indentation (code &optional n)
17070 "Remove the maximum common indentation from the lines in CODE.
17071 N may optionally be the number of spaces to remove."
17072 (with-temp-buffer
17073 (insert code)
17074 (org-do-remove-indentation n)
17075 (buffer-string)))
17076
17077 (defun org-do-remove-indentation (&optional n)
17078 "Remove the maximum common indentation from the buffer."
17079 (untabify (point-min) (point-max))
17080 (let ((min 10000) re)
17081 (if n
17082 (setq min n)
17083 (goto-char (point-min))
17084 (while (re-search-forward "^ *[^ \n]" nil t)
17085 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
17086 (unless (or (= min 0) (= min 10000))
17087 (setq re (format "^ \\{%d\\}" min))
17088 (goto-char (point-min))
17089 (while (re-search-forward re nil t)
17090 (replace-match "")
17091 (end-of-line 1))
17092 min)))
17093
17094 (defun org-fill-template (template alist)
17095 "Find each %key of ALIST in TEMPLATE and replace it."
17096 (let ((case-fold-search nil)
17097 entry key value)
17098 (setq alist (sort (copy-sequence alist)
17099 (lambda (a b) (< (length (car a)) (length (car b))))))
17100 (while (setq entry (pop alist))
17101 (setq template
17102 (replace-regexp-in-string
17103 (concat "%" (regexp-quote (car entry)))
17104 (cdr entry) template t t)))
17105 template))
17106
17107 (defun org-base-buffer (buffer)
17108 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
17109 (if (not buffer)
17110 buffer
17111 (or (buffer-base-buffer buffer)
17112 buffer)))
17113
17114 (defun org-trim (s)
17115 "Remove whitespace at beginning and end of string."
17116 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
17117 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
17118 s)
17119
17120 (defun org-wrap (string &optional width lines)
17121 "Wrap string to either a number of lines, or a width in characters.
17122 If WIDTH is non-nil, the string is wrapped to that width, however many lines
17123 that costs. If there is a word longer than WIDTH, the text is actually
17124 wrapped to the length of that word.
17125 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
17126 many lines, whatever width that takes.
17127 The return value is a list of lines, without newlines at the end."
17128 (let* ((words (org-split-string string "[ \t\n]+"))
17129 (maxword (apply 'max (mapcar 'org-string-width words)))
17130 w ll)
17131 (cond (width
17132 (org-do-wrap words (max maxword width)))
17133 (lines
17134 (setq w maxword)
17135 (setq ll (org-do-wrap words maxword))
17136 (if (<= (length ll) lines)
17137 ll
17138 (setq ll words)
17139 (while (> (length ll) lines)
17140 (setq w (1+ w))
17141 (setq ll (org-do-wrap words w)))
17142 ll))
17143 (t (error "Cannot wrap this")))))
17144
17145 (defun org-do-wrap (words width)
17146 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
17147 (let (lines line)
17148 (while words
17149 (setq line (pop words))
17150 (while (and words (< (+ (length line) (length (car words))) width))
17151 (setq line (concat line " " (pop words))))
17152 (setq lines (push line lines)))
17153 (nreverse lines)))
17154
17155 (defun org-split-string (string &optional separators)
17156 "Splits STRING into substrings at SEPARATORS.
17157 No empty strings are returned if there are matches at the beginning
17158 and end of string."
17159 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
17160 (start 0)
17161 notfirst
17162 (list nil))
17163 (while (and (string-match rexp string
17164 (if (and notfirst
17165 (= start (match-beginning 0))
17166 (< start (length string)))
17167 (1+ start) start))
17168 (< (match-beginning 0) (length string)))
17169 (setq notfirst t)
17170 (or (eq (match-beginning 0) 0)
17171 (and (eq (match-beginning 0) (match-end 0))
17172 (eq (match-beginning 0) start))
17173 (setq list
17174 (cons (substring string start (match-beginning 0))
17175 list)))
17176 (setq start (match-end 0)))
17177 (or (eq start (length string))
17178 (setq list
17179 (cons (substring string start)
17180 list)))
17181 (nreverse list)))
17182
17183 (defun org-quote-vert (s)
17184 "Replace \"|\" with \"\\vert\"."
17185 (while (string-match "|" s)
17186 (setq s (replace-match "\\vert" t t s)))
17187 s)
17188
17189 (defun org-uuidgen-p (s)
17190 "Is S an ID created by UUIDGEN?"
17191 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
17192
17193 (defun org-context ()
17194 "Return a list of contexts of the current cursor position.
17195 If several contexts apply, all are returned.
17196 Each context entry is a list with a symbol naming the context, and
17197 two positions indicating start and end of the context. Possible
17198 contexts are:
17199
17200 :headline anywhere in a headline
17201 :headline-stars on the leading stars in a headline
17202 :todo-keyword on a TODO keyword (including DONE) in a headline
17203 :tags on the TAGS in a headline
17204 :priority on the priority cookie in a headline
17205 :item on the first line of a plain list item
17206 :item-bullet on the bullet/number of a plain list item
17207 :checkbox on the checkbox in a plain list item
17208 :table in an org-mode table
17209 :table-special on a special filed in a table
17210 :table-table in a table.el table
17211 :link on a hyperlink
17212 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
17213 :target on a <<target>>
17214 :radio-target on a <<<radio-target>>>
17215 :latex-fragment on a LaTeX fragment
17216 :latex-preview on a LaTeX fragment with overlayed preview image
17217
17218 This function expects the position to be visible because it uses font-lock
17219 faces as a help to recognize the following contexts: :table-special, :link,
17220 and :keyword."
17221 (let* ((f (get-text-property (point) 'face))
17222 (faces (if (listp f) f (list f)))
17223 (p (point)) clist o)
17224 ;; First the large context
17225 (cond
17226 ((org-on-heading-p t)
17227 (push (list :headline (point-at-bol) (point-at-eol)) clist)
17228 (when (progn
17229 (beginning-of-line 1)
17230 (looking-at org-todo-line-tags-regexp))
17231 (push (org-point-in-group p 1 :headline-stars) clist)
17232 (push (org-point-in-group p 2 :todo-keyword) clist)
17233 (push (org-point-in-group p 4 :tags) clist))
17234 (goto-char p)
17235 (skip-chars-backward "^[\n\r \t") (or (bobp) (backward-char 1))
17236 (if (looking-at "\\[#[A-Z0-9]\\]")
17237 (push (org-point-in-group p 0 :priority) clist)))
17238
17239 ((org-at-item-p)
17240 (push (org-point-in-group p 2 :item-bullet) clist)
17241 (push (list :item (point-at-bol)
17242 (save-excursion (org-end-of-item) (point)))
17243 clist)
17244 (and (org-at-item-checkbox-p)
17245 (push (org-point-in-group p 0 :checkbox) clist)))
17246
17247 ((org-at-table-p)
17248 (push (list :table (org-table-begin) (org-table-end)) clist)
17249 (if (memq 'org-formula faces)
17250 (push (list :table-special
17251 (previous-single-property-change p 'face)
17252 (next-single-property-change p 'face)) clist)))
17253 ((org-at-table-p 'any)
17254 (push (list :table-table) clist)))
17255 (goto-char p)
17256
17257 ;; Now the small context
17258 (cond
17259 ((org-at-timestamp-p)
17260 (push (org-point-in-group p 0 :timestamp) clist))
17261 ((memq 'org-link faces)
17262 (push (list :link
17263 (previous-single-property-change p 'face)
17264 (next-single-property-change p 'face)) clist))
17265 ((memq 'org-special-keyword faces)
17266 (push (list :keyword
17267 (previous-single-property-change p 'face)
17268 (next-single-property-change p 'face)) clist))
17269 ((org-on-target-p)
17270 (push (org-point-in-group p 0 :target) clist)
17271 (goto-char (1- (match-beginning 0)))
17272 (if (looking-at org-radio-target-regexp)
17273 (push (org-point-in-group p 0 :radio-target) clist))
17274 (goto-char p))
17275 ((setq o (car (delq nil
17276 (mapcar
17277 (lambda (x)
17278 (if (memq x org-latex-fragment-image-overlays) x))
17279 (org-overlays-at (point))))))
17280 (push (list :latex-fragment
17281 (org-overlay-start o) (org-overlay-end o)) clist)
17282 (push (list :latex-preview
17283 (org-overlay-start o) (org-overlay-end o)) clist))
17284 ((org-inside-LaTeX-fragment-p)
17285 ;; FIXME: positions wrong.
17286 (push (list :latex-fragment (point) (point)) clist)))
17287
17288 (setq clist (nreverse (delq nil clist)))
17289 clist))
17290
17291 ;; FIXME: Compare with at-regexp-p Do we need both?
17292 (defun org-in-regexp (re &optional nlines visually)
17293 "Check if point is inside a match of regexp.
17294 Normally only the current line is checked, but you can include NLINES extra
17295 lines both before and after point into the search.
17296 If VISUALLY is set, require that the cursor is not after the match but
17297 really on, so that the block visually is on the match."
17298 (catch 'exit
17299 (let ((pos (point))
17300 (eol (point-at-eol (+ 1 (or nlines 0))))
17301 (inc (if visually 1 0)))
17302 (save-excursion
17303 (beginning-of-line (- 1 (or nlines 0)))
17304 (while (re-search-forward re eol t)
17305 (if (and (<= (match-beginning 0) pos)
17306 (>= (+ inc (match-end 0)) pos))
17307 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
17308
17309 (defun org-at-regexp-p (regexp)
17310 "Is point inside a match of REGEXP in the current line?"
17311 (catch 'exit
17312 (save-excursion
17313 (let ((pos (point)) (end (point-at-eol)))
17314 (beginning-of-line 1)
17315 (while (re-search-forward regexp end t)
17316 (if (and (<= (match-beginning 0) pos)
17317 (>= (match-end 0) pos))
17318 (throw 'exit t)))
17319 nil))))
17320
17321 (defun org-in-regexps-block-p (start-re end-re)
17322 "Returns t if the current point is between matches of START-RE and END-RE.
17323 This will also return to if point is on one of the two matches."
17324 (interactive)
17325 (let ((p (point)))
17326 (save-excursion
17327 (and (or (org-at-regexp-p start-re)
17328 (re-search-backward start-re nil t))
17329 (re-search-forward end-re nil t)
17330 (>= (point) p)))))
17331
17332 (defun org-occur-in-agenda-files (regexp &optional nlines)
17333 "Call `multi-occur' with buffers for all agenda files."
17334 (interactive "sOrg-files matching: \np")
17335 (let* ((files (org-agenda-files))
17336 (tnames (mapcar 'file-truename files))
17337 (extra org-agenda-text-search-extra-files)
17338 f)
17339 (when (eq (car extra) 'agenda-archives)
17340 (setq extra (cdr extra))
17341 (setq files (org-add-archive-files files)))
17342 (while (setq f (pop extra))
17343 (unless (member (file-truename f) tnames)
17344 (add-to-list 'files f 'append)
17345 (add-to-list 'tnames (file-truename f) 'append)))
17346 (multi-occur
17347 (mapcar (lambda (x)
17348 (with-current-buffer
17349 (or (get-file-buffer x) (find-file-noselect x))
17350 (widen)
17351 (current-buffer)))
17352 files)
17353 regexp)))
17354
17355 (if (boundp 'occur-mode-find-occurrence-hook)
17356 ;; Emacs 23
17357 (add-hook 'occur-mode-find-occurrence-hook
17358 (lambda ()
17359 (when (org-mode-p)
17360 (org-reveal))))
17361 ;; Emacs 22
17362 (defadvice occur-mode-goto-occurrence
17363 (after org-occur-reveal activate)
17364 (and (org-mode-p) (org-reveal)))
17365 (defadvice occur-mode-goto-occurrence-other-window
17366 (after org-occur-reveal activate)
17367 (and (org-mode-p) (org-reveal)))
17368 (defadvice occur-mode-display-occurrence
17369 (after org-occur-reveal activate)
17370 (when (org-mode-p)
17371 (let ((pos (occur-mode-find-occurrence)))
17372 (with-current-buffer (marker-buffer pos)
17373 (save-excursion
17374 (goto-char pos)
17375 (org-reveal)))))))
17376
17377 (defun org-occur-link-in-agenda-files ()
17378 "Create a link and search for it in the agendas.
17379 The link is not stored in `org-stored-links', it is just created
17380 for the search purpose."
17381 (interactive)
17382 (let ((link (condition-case nil
17383 (org-store-link nil)
17384 (error "Unable to create a link to here"))))
17385 (org-occur-in-agenda-files (regexp-quote link))))
17386
17387 (defun org-uniquify (list)
17388 "Remove duplicate elements from LIST."
17389 (let (res)
17390 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
17391 res))
17392
17393 (defun org-delete-all (elts list)
17394 "Remove all elements in ELTS from LIST."
17395 (while elts
17396 (setq list (delete (pop elts) list)))
17397 list)
17398
17399 (defun org-back-over-empty-lines ()
17400 "Move backwards over whitespace, to the beginning of the first empty line.
17401 Returns the number of empty lines passed."
17402 (let ((pos (point)))
17403 (skip-chars-backward " \t\n\r")
17404 (beginning-of-line 2)
17405 (goto-char (min (point) pos))
17406 (count-lines (point) pos)))
17407
17408 (defun org-skip-whitespace ()
17409 (skip-chars-forward " \t\n\r"))
17410
17411 (defun org-point-in-group (point group &optional context)
17412 "Check if POINT is in match-group GROUP.
17413 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
17414 match. If the match group does ot exist or point is not inside it,
17415 return nil."
17416 (and (match-beginning group)
17417 (>= point (match-beginning group))
17418 (<= point (match-end group))
17419 (if context
17420 (list context (match-beginning group) (match-end group))
17421 t)))
17422
17423 (defun org-switch-to-buffer-other-window (&rest args)
17424 "Switch to buffer in a second window on the current frame.
17425 In particular, do not allow pop-up frames."
17426 (let (pop-up-frames special-display-buffer-names special-display-regexps
17427 special-display-function)
17428 (apply 'switch-to-buffer-other-window args)))
17429
17430 (defun org-combine-plists (&rest plists)
17431 "Create a single property list from all plists in PLISTS.
17432 The process starts by copying the first list, and then setting properties
17433 from the other lists. Settings in the last list are the most significant
17434 ones and overrule settings in the other lists."
17435 (let ((rtn (copy-sequence (pop plists)))
17436 p v ls)
17437 (while plists
17438 (setq ls (pop plists))
17439 (while ls
17440 (setq p (pop ls) v (pop ls))
17441 (setq rtn (plist-put rtn p v))))
17442 rtn))
17443
17444 (defun org-move-line-down (arg)
17445 "Move the current line down. With prefix argument, move it past ARG lines."
17446 (interactive "p")
17447 (let ((col (current-column))
17448 beg end pos)
17449 (beginning-of-line 1) (setq beg (point))
17450 (beginning-of-line 2) (setq end (point))
17451 (beginning-of-line (+ 1 arg))
17452 (setq pos (move-marker (make-marker) (point)))
17453 (insert (delete-and-extract-region beg end))
17454 (goto-char pos)
17455 (org-move-to-column col)))
17456
17457 (defun org-move-line-up (arg)
17458 "Move the current line up. With prefix argument, move it past ARG lines."
17459 (interactive "p")
17460 (let ((col (current-column))
17461 beg end pos)
17462 (beginning-of-line 1) (setq beg (point))
17463 (beginning-of-line 2) (setq end (point))
17464 (beginning-of-line (- arg))
17465 (setq pos (move-marker (make-marker) (point)))
17466 (insert (delete-and-extract-region beg end))
17467 (goto-char pos)
17468 (org-move-to-column col)))
17469
17470 (defun org-replace-escapes (string table)
17471 "Replace %-escapes in STRING with values in TABLE.
17472 TABLE is an association list with keys like \"%a\" and string values.
17473 The sequences in STRING may contain normal field width and padding information,
17474 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
17475 so values can contain further %-escapes if they are define later in TABLE."
17476 (let ((case-fold-search nil)
17477 e re rpl)
17478 (while (setq e (pop table))
17479 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
17480 (while (string-match re string)
17481 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
17482 (cdr e)))
17483 (setq string (replace-match rpl t t string))))
17484 string))
17485
17486
17487 (defun org-sublist (list start end)
17488 "Return a section of LIST, from START to END.
17489 Counting starts at 1."
17490 (let (rtn (c start))
17491 (setq list (nthcdr (1- start) list))
17492 (while (and list (<= c end))
17493 (push (pop list) rtn)
17494 (setq c (1+ c)))
17495 (nreverse rtn)))
17496
17497 (defun org-find-base-buffer-visiting (file)
17498 "Like `find-buffer-visiting' but always return the base buffer and
17499 not an indirect buffer."
17500 (let ((buf (or (get-file-buffer file)
17501 (find-buffer-visiting file))))
17502 (if buf
17503 (or (buffer-base-buffer buf) buf)
17504 nil)))
17505
17506 (defun org-image-file-name-regexp (&optional extensions)
17507 "Return regexp matching the file names of images.
17508 If EXTENSIONS is given, only match these."
17509 (if (and (not extensions) (fboundp 'image-file-name-regexp))
17510 (image-file-name-regexp)
17511 (let ((image-file-name-extensions
17512 (or extensions
17513 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
17514 "xbm" "xpm" "pbm" "pgm" "ppm"))))
17515 (concat "\\."
17516 (regexp-opt (nconc (mapcar 'upcase
17517 image-file-name-extensions)
17518 image-file-name-extensions)
17519 t)
17520 "\\'"))))
17521
17522 (defun org-file-image-p (file &optional extensions)
17523 "Return non-nil if FILE is an image."
17524 (save-match-data
17525 (string-match (org-image-file-name-regexp extensions) file)))
17526
17527 (defun org-get-cursor-date ()
17528 "Return the date at cursor in as a time.
17529 This works in the calendar and in the agenda, anywhere else it just
17530 returns the current time."
17531 (let (date day defd)
17532 (cond
17533 ((eq major-mode 'calendar-mode)
17534 (setq date (calendar-cursor-to-date)
17535 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
17536 ((eq major-mode 'org-agenda-mode)
17537 (setq day (get-text-property (point) 'day))
17538 (if day
17539 (setq date (calendar-gregorian-from-absolute day)
17540 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
17541 (nth 2 date))))))
17542 (or defd (current-time))))
17543
17544 (defvar org-agenda-action-marker (make-marker)
17545 "Marker pointing to the entry for the next agenda action.")
17546
17547 (defun org-mark-entry-for-agenda-action ()
17548 "Mark the current entry as target of an agenda action.
17549 Agenda actions are actions executed from the agenda with the key `k',
17550 which make use of the date at the cursor."
17551 (interactive)
17552 (move-marker org-agenda-action-marker
17553 (save-excursion (org-back-to-heading t) (point))
17554 (current-buffer))
17555 (message
17556 "Entry marked for action; press `k' at desired date in agenda or calendar"))
17557
17558 ;;; Paragraph filling stuff.
17559 ;; We want this to be just right, so use the full arsenal.
17560
17561 (defun org-indent-line-function ()
17562 "Indent line like previous, but further if previous was headline or item."
17563 (interactive)
17564 (let* ((pos (point))
17565 (itemp (org-at-item-p))
17566 (case-fold-search t)
17567 (org-drawer-regexp (or org-drawer-regexp "\000"))
17568 column bpos bcol tpos tcol bullet btype bullet-type)
17569 ;; Find the previous relevant line
17570 (beginning-of-line 1)
17571 (cond
17572 ((looking-at "#") (setq column 0))
17573 ((looking-at "\\*+ ") (setq column 0))
17574 ((and (looking-at "[ \t]*:END:")
17575 (save-excursion (re-search-backward org-drawer-regexp nil t)))
17576 (save-excursion
17577 (goto-char (1- (match-beginning 1)))
17578 (setq column (current-column))))
17579 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
17580 (save-excursion
17581 (re-search-backward
17582 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
17583 (setq column (org-get-indentation (match-string 0))))
17584 (t
17585 (beginning-of-line 0)
17586 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
17587 (not (looking-at "[ \t]*:END:"))
17588 (not (looking-at org-drawer-regexp)))
17589 (beginning-of-line 0))
17590 (cond
17591 ((looking-at "\\*+[ \t]+")
17592 (if (not org-adapt-indentation)
17593 (setq column 0)
17594 (goto-char (match-end 0))
17595 (setq column (current-column))))
17596 ((looking-at org-drawer-regexp)
17597 (goto-char (1- (match-beginning 1)))
17598 (setq column (current-column)))
17599 ((looking-at "\\([ \t]*\\):END:")
17600 (goto-char (match-end 1))
17601 (setq column (current-column)))
17602 ((org-in-item-p)
17603 (org-beginning-of-item)
17604 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
17605 (setq bpos (match-beginning 1) tpos (match-end 0)
17606 bcol (progn (goto-char bpos) (current-column))
17607 tcol (progn (goto-char tpos) (current-column))
17608 bullet (match-string 1)
17609 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
17610 (if (> tcol (+ bcol org-description-max-indent))
17611 (setq tcol (+ bcol 5)))
17612 (if (not itemp)
17613 (setq column tcol)
17614 (goto-char pos)
17615 (beginning-of-line 1)
17616 (if (looking-at "\\S-")
17617 (progn
17618 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
17619 (setq bullet (match-string 1)
17620 btype (if (string-match "[0-9]" bullet) "n" bullet))
17621 (setq column (if (equal btype bullet-type) bcol tcol)))
17622 (setq column (org-get-indentation)))))
17623 (t (setq column (org-get-indentation))))))
17624 (goto-char pos)
17625 (if (<= (current-column) (current-indentation))
17626 (org-indent-line-to column)
17627 (save-excursion (org-indent-line-to column)))
17628 (setq column (current-column))
17629 (beginning-of-line 1)
17630 (if (looking-at
17631 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
17632 (replace-match (concat (match-string 1)
17633 (format org-property-format
17634 (match-string 2) (match-string 3)))
17635 t t))
17636 (org-move-to-column column)))
17637
17638 (defvar org-adaptive-fill-regexp-backup adaptive-fill-regexp
17639 "Variable to store copy of `adaptive-fill-regexp'.
17640 Since `adaptive-fill-regexp' is set to never match, we need to
17641 store a backup of its value before entering `org-mode' so that
17642 the functionality can be provided as a fall-back.")
17643
17644 (defun org-set-autofill-regexps ()
17645 (interactive)
17646 ;; In the paragraph separator we include headlines, because filling
17647 ;; text in a line directly attached to a headline would otherwise
17648 ;; fill the headline as well.
17649 (org-set-local 'comment-start-skip "^#+[ \t]*")
17650 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|#]")
17651 ;; The paragraph starter includes hand-formatted lists.
17652 (org-set-local
17653 'paragraph-start
17654 (concat
17655 "\f" "\\|"
17656 "[ ]*$" "\\|"
17657 "\\*+ " "\\|"
17658 "[ \t]*#" "\\|"
17659 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
17660 "[ \t]*[:|]" "\\|"
17661 "\\$\\$" "\\|"
17662 "\\\\\\(begin\\|end\\|[][]\\)"))
17663 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
17664 ;; But only if the user has not turned off tables or fixed-width regions
17665 (org-set-local
17666 'auto-fill-inhibit-regexp
17667 (concat "\\*+ \\|#\\+"
17668 "\\|[ \t]*" org-keyword-time-regexp
17669 (if (or org-enable-table-editor org-enable-fixed-width-editor)
17670 (concat
17671 "\\|[ \t]*["
17672 (if org-enable-table-editor "|" "")
17673 (if org-enable-fixed-width-editor ":" "")
17674 "]"))))
17675 ;; We use our own fill-paragraph function, to make sure that tables
17676 ;; and fixed-width regions are not wrapped. That function will pass
17677 ;; through to `fill-paragraph' when appropriate.
17678 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
17679 ;; Adaptive filling: To get full control, first make sure that
17680 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
17681 (unless (local-variable-p 'adaptive-fill-regexp)
17682 (org-set-local 'org-adaptive-fill-regexp-backup
17683 adaptive-fill-regexp))
17684 (org-set-local 'adaptive-fill-regexp "\000")
17685 (org-set-local 'adaptive-fill-function
17686 'org-adaptive-fill-function)
17687 (org-set-local
17688 'align-mode-rules-list
17689 '((org-in-buffer-settings
17690 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
17691 (modes . '(org-mode))))))
17692
17693 (defun org-fill-paragraph (&optional justify)
17694 "Re-align a table, pass through to fill-paragraph if no table."
17695 (let ((table-p (org-at-table-p))
17696 (table.el-p (org-at-table.el-p)))
17697 (cond ((and (equal (char-after (point-at-bol)) ?*)
17698 (save-excursion (goto-char (point-at-bol))
17699 (looking-at outline-regexp)))
17700 t) ; skip headlines
17701 (table.el-p t) ; skip table.el tables
17702 (table-p (org-table-align) t) ; align org-mode tables
17703 (t nil)))) ; call paragraph-fill
17704
17705 ;; For reference, this is the default value of adaptive-fill-regexp
17706 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
17707
17708 (defun org-adaptive-fill-function ()
17709 "Return a fill prefix for org-mode files.
17710 In particular, this makes sure hanging paragraphs for hand-formatted lists
17711 work correctly."
17712 (cond
17713 ;; Comment line
17714 ((looking-at "#[ \t]+")
17715 (match-string-no-properties 0))
17716 ;; Description list
17717 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
17718 (save-excursion
17719 (if (> (match-end 1) (+ (match-beginning 1)
17720 org-description-max-indent))
17721 (goto-char (+ (match-beginning 1) 5))
17722 (goto-char (match-end 0)))
17723 (make-string (current-column) ?\ )))
17724 ;; Ordered or unordered list
17725 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)")
17726 (save-excursion
17727 (goto-char (match-end 0))
17728 (make-string (current-column) ?\ )))
17729 ;; Other text
17730 ((looking-at org-adaptive-fill-regexp-backup)
17731 (match-string-no-properties 0))))
17732
17733 ;;; Other stuff.
17734
17735 (defun org-toggle-fixed-width-section (arg)
17736 "Toggle the fixed-width export.
17737 If there is no active region, the QUOTE keyword at the current headline is
17738 inserted or removed. When present, it causes the text between this headline
17739 and the next to be exported as fixed-width text, and unmodified.
17740 If there is an active region, this command adds or removes a colon as the
17741 first character of this line. If the first character of a line is a colon,
17742 this line is also exported in fixed-width font."
17743 (interactive "P")
17744 (let* ((cc 0)
17745 (regionp (org-region-active-p))
17746 (beg (if regionp (region-beginning) (point)))
17747 (end (if regionp (region-end)))
17748 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
17749 (case-fold-search nil)
17750 (re "[ \t]*\\(: \\)")
17751 off)
17752 (if regionp
17753 (save-excursion
17754 (goto-char beg)
17755 (setq cc (current-column))
17756 (beginning-of-line 1)
17757 (setq off (looking-at re))
17758 (while (> nlines 0)
17759 (setq nlines (1- nlines))
17760 (beginning-of-line 1)
17761 (cond
17762 (arg
17763 (org-move-to-column cc t)
17764 (insert ": \n")
17765 (forward-line -1))
17766 ((and off (looking-at re))
17767 (replace-match "" t t nil 1))
17768 ((not off) (org-move-to-column cc t) (insert ": ")))
17769 (forward-line 1)))
17770 (save-excursion
17771 (org-back-to-heading)
17772 (if (looking-at (concat outline-regexp
17773 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
17774 (replace-match "" t t nil 1)
17775 (if (looking-at outline-regexp)
17776 (progn
17777 (goto-char (match-end 0))
17778 (insert org-quote-string " "))))))))
17779
17780 (defun org-reftex-citation ()
17781 "Use reftex-citation to insert a citation into the buffer.
17782 This looks for a line like
17783
17784 #+BIBLIOGRAPHY: foo plain option:-d
17785
17786 and derives from it that foo.bib is the bibliography file relevant
17787 for this document. It then installs the necessary environment for RefTeX
17788 to work in this buffer and calls `reftex-citation' to insert a citation
17789 into the buffer.
17790
17791 Export of such citations to both LaTeX and HTML is handled by the contributed
17792 package org-exp-bibtex by Taru Karttunen."
17793 (interactive)
17794 (let ((reftex-docstruct-symbol 'rds)
17795 (reftex-cite-format "\\cite{%l}")
17796 rds bib)
17797 (save-excursion
17798 (save-restriction
17799 (widen)
17800 (let ((case-fold-search t)
17801 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
17802 (if (not (save-excursion
17803 (or (re-search-forward re nil t)
17804 (re-search-backward re nil t))))
17805 (error "No bibliography defined in file")
17806 (setq bib (concat (match-string 1) ".bib")
17807 rds (list (list 'bib bib)))))))
17808 (call-interactively 'reftex-citation)))
17809
17810 ;;;; Functions extending outline functionality
17811
17812 (defun org-beginning-of-line (&optional arg)
17813 "Go to the beginning of the current line. If that is invisible, continue
17814 to a visible line beginning. This makes the function of C-a more intuitive.
17815 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17816 first attempt, and only move to after the tags when the cursor is already
17817 beyond the end of the headline."
17818 (interactive "P")
17819 (let ((pos (point))
17820 (special (if (consp org-special-ctrl-a/e)
17821 (car org-special-ctrl-a/e)
17822 org-special-ctrl-a/e))
17823 refpos)
17824 (if (org-bound-and-true-p line-move-visual)
17825 (beginning-of-visual-line 1)
17826 (beginning-of-line 1))
17827 (if (and arg (fboundp 'move-beginning-of-line))
17828 (call-interactively 'move-beginning-of-line)
17829 (if (bobp)
17830 nil
17831 (backward-char 1)
17832 (if (org-invisible-p)
17833 (while (and (not (bobp)) (org-invisible-p))
17834 (backward-char 1)
17835 (beginning-of-line 1))
17836 (forward-char 1))))
17837 (when special
17838 (cond
17839 ((and (looking-at org-complex-heading-regexp)
17840 (= (char-after (match-end 1)) ?\ ))
17841 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
17842 (point-at-eol)))
17843 (goto-char
17844 (if (eq special t)
17845 (cond ((> pos refpos) refpos)
17846 ((= pos (point)) refpos)
17847 (t (point)))
17848 (cond ((> pos (point)) (point))
17849 ((not (eq last-command this-command)) (point))
17850 (t refpos)))))
17851 ((org-at-item-p)
17852 (goto-char
17853 (if (eq special t)
17854 (cond ((> pos (match-end 4)) (match-end 4))
17855 ((= pos (point)) (match-end 4))
17856 (t (point)))
17857 (cond ((> pos (point)) (point))
17858 ((not (eq last-command this-command)) (point))
17859 (t (match-end 4))))))))
17860 (org-no-warnings
17861 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17862
17863 (defun org-end-of-line (&optional arg)
17864 "Go to the end of the line.
17865 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
17866 first attempt, and only move to after the tags when the cursor is already
17867 beyond the end of the headline."
17868 (interactive "P")
17869 (let ((special (if (consp org-special-ctrl-a/e)
17870 (cdr org-special-ctrl-a/e)
17871 org-special-ctrl-a/e)))
17872 (if (or (not special)
17873 (not (org-on-heading-p))
17874 arg)
17875 (call-interactively
17876 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
17877 ((fboundp 'move-end-of-line) 'move-end-of-line)
17878 (t 'end-of-line)))
17879 (let ((pos (point)))
17880 (beginning-of-line 1)
17881 (if (looking-at (org-re ".*?\\(?:\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*\\)?$"))
17882 (if (eq special t)
17883 (if (or (< pos (match-beginning 1))
17884 (= pos (match-end 0)))
17885 (goto-char (match-beginning 1))
17886 (goto-char (match-end 0)))
17887 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
17888 (goto-char (match-end 0))
17889 (goto-char (match-beginning 1))))
17890 (call-interactively (if (fboundp 'move-end-of-line)
17891 'move-end-of-line
17892 'end-of-line)))))
17893 (org-no-warnings
17894 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
17895
17896 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
17897 (define-key org-mode-map "\C-e" 'org-end-of-line)
17898 (define-key org-mode-map [home] 'org-beginning-of-line)
17899 (define-key org-mode-map [end] 'org-end-of-line)
17900
17901 (defun org-backward-sentence (&optional arg)
17902 "Go to beginning of sentence, or beginning of table field.
17903 This will call `backward-sentence' or `org-table-beginning-of-field',
17904 depending on context."
17905 (interactive "P")
17906 (cond
17907 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
17908 (t (call-interactively 'backward-sentence))))
17909
17910 (defun org-forward-sentence (&optional arg)
17911 "Go to end of sentence, or end of table field.
17912 This will call `forward-sentence' or `org-table-end-of-field',
17913 depending on context."
17914 (interactive "P")
17915 (cond
17916 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
17917 (t (call-interactively 'forward-sentence))))
17918
17919 (define-key org-mode-map "\M-a" 'org-backward-sentence)
17920 (define-key org-mode-map "\M-e" 'org-forward-sentence)
17921
17922 (defun org-kill-line (&optional arg)
17923 "Kill line, to tags or end of line."
17924 (interactive "P")
17925 (cond
17926 ((or (not org-special-ctrl-k)
17927 (bolp)
17928 (not (org-on-heading-p)))
17929 (call-interactively 'kill-line))
17930 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
17931 (kill-region (point) (match-beginning 1))
17932 (org-set-tags nil t))
17933 (t (kill-region (point) (point-at-eol)))))
17934
17935 (define-key org-mode-map "\C-k" 'org-kill-line)
17936
17937 (defun org-yank (&optional arg)
17938 "Yank. If the kill is a subtree, treat it specially.
17939 This command will look at the current kill and check if is a single
17940 subtree, or a series of subtrees[1]. If it passes the test, and if the
17941 cursor is at the beginning of a line or after the stars of a currently
17942 empty headline, then the yank is handled specially. How exactly depends
17943 on the value of the following variables, both set by default.
17944
17945 org-yank-folded-subtrees
17946 When set, the subtree(s) will be folded after insertion, but only
17947 if doing so would now swallow text after the yanked text.
17948
17949 org-yank-adjusted-subtrees
17950 When set, the subtree will be promoted or demoted in order to
17951 fit into the local outline tree structure, which means that the level
17952 will be adjusted so that it becomes the smaller one of the two
17953 *visible* surrounding headings.
17954
17955 Any prefix to this command will cause `yank' to be called directly with
17956 no special treatment. In particular, a simple `C-u' prefix will just
17957 plainly yank the text as it is.
17958
17959 \[1] The test checks if the first non-white line is a heading
17960 and if there are no other headings with fewer stars."
17961 (interactive "P")
17962 (org-yank-generic 'yank arg))
17963
17964 (defun org-yank-generic (command arg)
17965 "Perform some yank-like command.
17966
17967 This function implements the behavior described in the `org-yank'
17968 documentation. However, it has been generalized to work for any
17969 interactive command with similar behavior."
17970
17971 ;; pretend to be command COMMAND
17972 (setq this-command command)
17973
17974 (if arg
17975 (call-interactively command)
17976
17977 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
17978 (and (org-kill-is-subtree-p)
17979 (or (bolp)
17980 (and (looking-at "[ \t]*$")
17981 (string-match
17982 "\\`\\*+\\'"
17983 (buffer-substring (point-at-bol) (point)))))))
17984 swallowp)
17985 (cond
17986 ((and subtreep org-yank-folded-subtrees)
17987 (let ((beg (point))
17988 end)
17989 (if (and subtreep org-yank-adjusted-subtrees)
17990 (org-paste-subtree nil nil 'for-yank)
17991 (call-interactively command))
17992
17993 (setq end (point))
17994 (goto-char beg)
17995 (when (and (bolp) subtreep
17996 (not (setq swallowp
17997 (org-yank-folding-would-swallow-text beg end))))
17998 (or (looking-at outline-regexp)
17999 (re-search-forward (concat "^" outline-regexp) end t))
18000 (while (and (< (point) end) (looking-at outline-regexp))
18001 (hide-subtree)
18002 (org-cycle-show-empty-lines 'folded)
18003 (condition-case nil
18004 (outline-forward-same-level 1)
18005 (error (goto-char end)))))
18006 (when swallowp
18007 (message
18008 "Inserted text not folded because that would swallow text"))
18009
18010 (goto-char end)
18011 (skip-chars-forward " \t\n\r")
18012 (beginning-of-line 1)
18013 (push-mark beg 'nomsg)))
18014 ((and subtreep org-yank-adjusted-subtrees)
18015 (let ((beg (point-at-bol)))
18016 (org-paste-subtree nil nil 'for-yank)
18017 (push-mark beg 'nomsg)))
18018 (t
18019 (call-interactively command))))))
18020
18021 (defun org-yank-folding-would-swallow-text (beg end)
18022 "Would hide-subtree at BEG swallow any text after END?"
18023 (let (level)
18024 (save-excursion
18025 (goto-char beg)
18026 (when (or (looking-at outline-regexp)
18027 (re-search-forward (concat "^" outline-regexp) end t))
18028 (setq level (org-outline-level)))
18029 (goto-char end)
18030 (skip-chars-forward " \t\r\n\v\f")
18031 (if (or (eobp)
18032 (and (bolp) (looking-at org-outline-regexp)
18033 (<= (org-outline-level) level)))
18034 nil ; Nothing would be swallowed
18035 t)))) ; something would swallow
18036
18037 (define-key org-mode-map "\C-y" 'org-yank)
18038
18039 (defun org-invisible-p ()
18040 "Check if point is at a character currently not visible."
18041 ;; Early versions of noutline don't have `outline-invisible-p'.
18042 (if (fboundp 'outline-invisible-p)
18043 (outline-invisible-p)
18044 (get-char-property (point) 'invisible)))
18045
18046 (defun org-invisible-p2 ()
18047 "Check if point is at a character currently not visible."
18048 (save-excursion
18049 (if (and (eolp) (not (bobp))) (backward-char 1))
18050 ;; Early versions of noutline don't have `outline-invisible-p'.
18051 (if (fboundp 'outline-invisible-p)
18052 (outline-invisible-p)
18053 (get-char-property (point) 'invisible))))
18054
18055 (defun org-back-to-heading (&optional invisible-ok)
18056 "Call `outline-back-to-heading', but provide a better error message."
18057 (condition-case nil
18058 (outline-back-to-heading invisible-ok)
18059 (error (error "Before first headline at position %d in buffer %s"
18060 (point) (current-buffer)))))
18061
18062 (defun org-before-first-heading-p ()
18063 "Before first heading?"
18064 (save-excursion
18065 (null (re-search-backward "^\\*+ " nil t))))
18066
18067 (defun org-on-heading-p (&optional ignored)
18068 (outline-on-heading-p t))
18069 (defun org-at-heading-p (&optional ignored)
18070 (outline-on-heading-p t))
18071
18072 (defun org-point-at-end-of-empty-headline ()
18073 "If point is at the end of an empty headline, return t, else nil.
18074 If the heading only contains a TODO keyword, it is still still considered
18075 empty."
18076 (and (looking-at "[ \t]*$")
18077 (save-excursion
18078 (beginning-of-line 1)
18079 (looking-at (concat "^\\(\\*+\\)[ \t]+\\(" org-todo-regexp
18080 "\\)?[ \t]*$")))))
18081 (defun org-at-heading-or-item-p ()
18082 (or (org-on-heading-p) (org-at-item-p)))
18083
18084 (defun org-on-target-p ()
18085 (or (org-in-regexp org-radio-target-regexp)
18086 (org-in-regexp org-target-regexp)))
18087
18088 (defun org-up-heading-all (arg)
18089 "Move to the heading line of which the present line is a subheading.
18090 This function considers both visible and invisible heading lines.
18091 With argument, move up ARG levels."
18092 (if (fboundp 'outline-up-heading-all)
18093 (outline-up-heading-all arg) ; emacs 21 version of outline.el
18094 (outline-up-heading arg t))) ; emacs 22 version of outline.el
18095
18096 (defun org-up-heading-safe ()
18097 "Move to the heading line of which the present line is a subheading.
18098 This version will not throw an error. It will return the level of the
18099 headline found, or nil if no higher level is found.
18100
18101 Also, this function will be a lot faster than `outline-up-heading',
18102 because it relies on stars being the outline starters. This can really
18103 make a significant difference in outlines with very many siblings."
18104 (let (start-level re)
18105 (org-back-to-heading t)
18106 (setq start-level (funcall outline-level))
18107 (if (equal start-level 1)
18108 nil
18109 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
18110 (if (re-search-backward re nil t)
18111 (funcall outline-level)))))
18112
18113 (defun org-first-sibling-p ()
18114 "Is this heading the first child of its parents?"
18115 (interactive)
18116 (let ((re (concat "^" outline-regexp))
18117 level l)
18118 (unless (org-at-heading-p t)
18119 (error "Not at a heading"))
18120 (setq level (funcall outline-level))
18121 (save-excursion
18122 (if (not (re-search-backward re nil t))
18123 t
18124 (setq l (funcall outline-level))
18125 (< l level)))))
18126
18127 (defun org-goto-sibling (&optional previous)
18128 "Goto the next sibling, even if it is invisible.
18129 When PREVIOUS is set, go to the previous sibling instead. Returns t
18130 when a sibling was found. When none is found, return nil and don't
18131 move point."
18132 (let ((fun (if previous 're-search-backward 're-search-forward))
18133 (pos (point))
18134 (re (concat "^" outline-regexp))
18135 level l)
18136 (when (condition-case nil (org-back-to-heading t) (error nil))
18137 (setq level (funcall outline-level))
18138 (catch 'exit
18139 (or previous (forward-char 1))
18140 (while (funcall fun re nil t)
18141 (setq l (funcall outline-level))
18142 (when (< l level) (goto-char pos) (throw 'exit nil))
18143 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
18144 (goto-char pos)
18145 nil))))
18146
18147 (defun org-show-siblings ()
18148 "Show all siblings of the current headline."
18149 (save-excursion
18150 (while (org-goto-sibling) (org-flag-heading nil)))
18151 (save-excursion
18152 (while (org-goto-sibling 'previous)
18153 (org-flag-heading nil))))
18154
18155 (defun org-show-hidden-entry ()
18156 "Show an entry where even the heading is hidden."
18157 (save-excursion
18158 (org-show-entry)))
18159
18160 (defun org-flag-heading (flag &optional entry)
18161 "Flag the current heading. FLAG non-nil means make invisible.
18162 When ENTRY is non-nil, show the entire entry."
18163 (save-excursion
18164 (org-back-to-heading t)
18165 ;; Check if we should show the entire entry
18166 (if entry
18167 (progn
18168 (org-show-entry)
18169 (save-excursion
18170 (and (outline-next-heading)
18171 (org-flag-heading nil))))
18172 (outline-flag-region (max (point-min) (1- (point)))
18173 (save-excursion (outline-end-of-heading) (point))
18174 flag))))
18175
18176 (defun org-get-next-sibling ()
18177 "Move to next heading of the same level, and return point.
18178 If there is no such heading, return nil.
18179 This is like outline-next-sibling, but invisible headings are ok."
18180 (let ((level (funcall outline-level)))
18181 (outline-next-heading)
18182 (while (and (not (eobp)) (> (funcall outline-level) level))
18183 (outline-next-heading))
18184 (if (or (eobp) (< (funcall outline-level) level))
18185 nil
18186 (point))))
18187
18188 (defun org-get-last-sibling ()
18189 "Move to previous heading of the same level, and return point.
18190 If there is no such heading, return nil."
18191 (let ((opoint (point))
18192 (level (funcall outline-level)))
18193 (outline-previous-heading)
18194 (when (and (/= (point) opoint) (outline-on-heading-p t))
18195 (while (and (> (funcall outline-level) level)
18196 (not (bobp)))
18197 (outline-previous-heading))
18198 (if (< (funcall outline-level) level)
18199 nil
18200 (point)))))
18201
18202 (defun org-end-of-subtree (&optional invisible-OK to-heading)
18203 ;; This contains an exact copy of the original function, but it uses
18204 ;; `org-back-to-heading', to make it work also in invisible
18205 ;; trees. And is uses an invisible-OK argument.
18206 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
18207 ;; Furthermore, when used inside Org, finding the end of a large subtree
18208 ;; with many children and grandchildren etc, this can be much faster
18209 ;; than the outline version.
18210 (org-back-to-heading invisible-OK)
18211 (let ((first t)
18212 (level (funcall outline-level)))
18213 (if (and (org-mode-p) (< level 1000))
18214 ;; A true heading (not a plain list item), in Org-mode
18215 ;; This means we can easily find the end by looking
18216 ;; only for the right number of stars. Using a regexp to do
18217 ;; this is so much faster than using a Lisp loop.
18218 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
18219 (forward-char 1)
18220 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
18221 ;; something else, do it the slow way
18222 (while (and (not (eobp))
18223 (or first (> (funcall outline-level) level)))
18224 (setq first nil)
18225 (outline-next-heading)))
18226 (unless to-heading
18227 (if (memq (preceding-char) '(?\n ?\^M))
18228 (progn
18229 ;; Go to end of line before heading
18230 (forward-char -1)
18231 (if (memq (preceding-char) '(?\n ?\^M))
18232 ;; leave blank line before heading
18233 (forward-char -1))))))
18234 (point))
18235
18236 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
18237 "Use Org version in org-mode, for dramatic speed-up."
18238 (if (eq major-mode 'org-mode)
18239 (progn
18240 (org-end-of-subtree nil t)
18241 (unless (eobp) (backward-char 1)))
18242 ad-do-it))
18243
18244 (defun org-forward-same-level (arg &optional invisible-ok)
18245 "Move forward to the arg'th subheading at same level as this one.
18246 Stop at the first and last subheadings of a superior heading."
18247 (interactive "p")
18248 (org-back-to-heading invisible-ok)
18249 (org-on-heading-p)
18250 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18251 (re (format "^\\*\\{1,%d\\} " level))
18252 l)
18253 (forward-char 1)
18254 (while (> arg 0)
18255 (while (and (re-search-forward re nil 'move)
18256 (setq l (- (match-end 0) (match-beginning 0) 1))
18257 (= l level)
18258 (not invisible-ok)
18259 (progn (backward-char 1) (org-invisible-p)))
18260 (if (< l level) (setq arg 1)))
18261 (setq arg (1- arg)))
18262 (beginning-of-line 1)))
18263
18264 (defun org-backward-same-level (arg &optional invisible-ok)
18265 "Move backward to the arg'th subheading at same level as this one.
18266 Stop at the first and last subheadings of a superior heading."
18267 (interactive "p")
18268 (org-back-to-heading)
18269 (org-on-heading-p)
18270 (let* ((level (- (match-end 0) (match-beginning 0) 1))
18271 (re (format "^\\*\\{1,%d\\} " level))
18272 l)
18273 (while (> arg 0)
18274 (while (and (re-search-backward re nil 'move)
18275 (setq l (- (match-end 0) (match-beginning 0) 1))
18276 (= l level)
18277 (not invisible-ok)
18278 (org-invisible-p))
18279 (if (< l level) (setq arg 1)))
18280 (setq arg (1- arg)))))
18281
18282 (defun org-show-subtree ()
18283 "Show everything after this heading at deeper levels."
18284 (outline-flag-region
18285 (point)
18286 (save-excursion
18287 (org-end-of-subtree t t))
18288 nil))
18289
18290 (defun org-show-entry ()
18291 "Show the body directly following this heading.
18292 Show the heading too, if it is currently invisible."
18293 (interactive)
18294 (save-excursion
18295 (condition-case nil
18296 (progn
18297 (org-back-to-heading t)
18298 (outline-flag-region
18299 (max (point-min) (1- (point)))
18300 (save-excursion
18301 (if (re-search-forward
18302 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
18303 (match-beginning 1)
18304 (point-max)))
18305 nil)
18306 (org-cycle-hide-drawers 'children))
18307 (error nil))))
18308
18309 (defun org-make-options-regexp (kwds &optional extra)
18310 "Make a regular expression for keyword lines."
18311 (concat
18312 "^"
18313 "#?[ \t]*\\+\\("
18314 (mapconcat 'regexp-quote kwds "\\|")
18315 (if extra (concat "\\|" extra))
18316 "\\):[ \t]*"
18317 "\\(.*\\)"))
18318
18319 ;; Make isearch reveal the necessary context
18320 (defun org-isearch-end ()
18321 "Reveal context after isearch exits."
18322 (when isearch-success ; only if search was successful
18323 (if (featurep 'xemacs)
18324 ;; Under XEmacs, the hook is run in the correct place,
18325 ;; we directly show the context.
18326 (org-show-context 'isearch)
18327 ;; In Emacs the hook runs *before* restoring the overlays.
18328 ;; So we have to use a one-time post-command-hook to do this.
18329 ;; (Emacs 22 has a special variable, see function `org-mode')
18330 (unless (and (boundp 'isearch-mode-end-hook-quit)
18331 isearch-mode-end-hook-quit)
18332 ;; Only when the isearch was not quitted.
18333 (org-add-hook 'post-command-hook 'org-isearch-post-command
18334 'append 'local)))))
18335
18336 (defun org-isearch-post-command ()
18337 "Remove self from hook, and show context."
18338 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
18339 (org-show-context 'isearch))
18340
18341
18342 ;;;; Integration with and fixes for other packages
18343
18344 ;;; Imenu support
18345
18346 (defvar org-imenu-markers nil
18347 "All markers currently used by Imenu.")
18348 (make-variable-buffer-local 'org-imenu-markers)
18349
18350 (defun org-imenu-new-marker (&optional pos)
18351 "Return a new marker for use by Imenu, and remember the marker."
18352 (let ((m (make-marker)))
18353 (move-marker m (or pos (point)))
18354 (push m org-imenu-markers)
18355 m))
18356
18357 (defun org-imenu-get-tree ()
18358 "Produce the index for Imenu."
18359 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
18360 (setq org-imenu-markers nil)
18361 (let* ((n org-imenu-depth)
18362 (re (concat "^" outline-regexp))
18363 (subs (make-vector (1+ n) nil))
18364 (last-level 0)
18365 m level head)
18366 (save-excursion
18367 (save-restriction
18368 (widen)
18369 (goto-char (point-max))
18370 (while (re-search-backward re nil t)
18371 (setq level (org-reduced-level (funcall outline-level)))
18372 (when (<= level n)
18373 (looking-at org-complex-heading-regexp)
18374 (setq head (org-link-display-format
18375 (org-match-string-no-properties 4))
18376 m (org-imenu-new-marker))
18377 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
18378 (if (>= level last-level)
18379 (push (cons head m) (aref subs level))
18380 (push (cons head (aref subs (1+ level))) (aref subs level))
18381 (loop for i from (1+ level) to n do (aset subs i nil)))
18382 (setq last-level level)))))
18383 (aref subs 1)))
18384
18385 (eval-after-load "imenu"
18386 '(progn
18387 (add-hook 'imenu-after-jump-hook
18388 (lambda ()
18389 (if (eq major-mode 'org-mode)
18390 (org-show-context 'org-goto))))))
18391
18392 (defun org-link-display-format (link)
18393 "Replace a link with either the description, or the link target
18394 if no description is present"
18395 (save-match-data
18396 (if (string-match org-bracket-link-analytic-regexp link)
18397 (replace-match (if (match-end 5)
18398 (match-string 5 link)
18399 (concat (match-string 1 link)
18400 (match-string 3 link)))
18401 nil t link)
18402 link)))
18403
18404 ;; Speedbar support
18405
18406 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
18407 "Overlay marking the agenda restriction line in speedbar.")
18408 (org-overlay-put org-speedbar-restriction-lock-overlay
18409 'face 'org-agenda-restriction-lock)
18410 (org-overlay-put org-speedbar-restriction-lock-overlay
18411 'help-echo "Agendas are currently limited to this item.")
18412 (org-detach-overlay org-speedbar-restriction-lock-overlay)
18413
18414 (defun org-speedbar-set-agenda-restriction ()
18415 "Restrict future agenda commands to the location at point in speedbar.
18416 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
18417 (interactive)
18418 (require 'org-agenda)
18419 (let (p m tp np dir txt)
18420 (cond
18421 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18422 'org-imenu t))
18423 (setq m (get-text-property p 'org-imenu-marker))
18424 (with-current-buffer (marker-buffer m)
18425 (goto-char m)
18426 (org-agenda-set-restriction-lock 'subtree)))
18427 ((setq p (text-property-any (point-at-bol) (point-at-eol)
18428 'speedbar-function 'speedbar-find-file))
18429 (setq tp (previous-single-property-change
18430 (1+ p) 'speedbar-function)
18431 np (next-single-property-change
18432 tp 'speedbar-function)
18433 dir (speedbar-line-directory)
18434 txt (buffer-substring-no-properties (or tp (point-min))
18435 (or np (point-max))))
18436 (with-current-buffer (find-file-noselect
18437 (let ((default-directory dir))
18438 (expand-file-name txt)))
18439 (unless (org-mode-p)
18440 (error "Cannot restrict to non-Org-mode file"))
18441 (org-agenda-set-restriction-lock 'file)))
18442 (t (error "Don't know how to restrict Org-mode's agenda")))
18443 (org-move-overlay org-speedbar-restriction-lock-overlay
18444 (point-at-bol) (point-at-eol))
18445 (setq current-prefix-arg nil)
18446 (org-agenda-maybe-redo)))
18447
18448 (eval-after-load "speedbar"
18449 '(progn
18450 (speedbar-add-supported-extension ".org")
18451 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
18452 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
18453 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
18454 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
18455 (add-hook 'speedbar-visiting-tag-hook
18456 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
18457
18458
18459 ;;; Fixes and Hacks for problems with other packages
18460
18461 ;; Make flyspell not check words in links, to not mess up our keymap
18462 (defun org-mode-flyspell-verify ()
18463 "Don't let flyspell put overlays at active buttons."
18464 (and (not (get-text-property (point) 'keymap))
18465 (not (get-text-property (point) 'org-no-flyspell))))
18466
18467 (defun org-remove-flyspell-overlays-in (beg end)
18468 "Remove flyspell overlays in region."
18469 (and (org-bound-and-true-p flyspell-mode)
18470 (fboundp 'flyspell-delete-region-overlays)
18471 (flyspell-delete-region-overlays beg end))
18472 (add-text-properties beg end '(org-no-flyspell t)))
18473
18474 ;; Make `bookmark-jump' shows the jump location if it was hidden.
18475 (eval-after-load "bookmark"
18476 '(if (boundp 'bookmark-after-jump-hook)
18477 ;; We can use the hook
18478 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
18479 ;; Hook not available, use advice
18480 (defadvice bookmark-jump (after org-make-visible activate)
18481 "Make the position visible."
18482 (org-bookmark-jump-unhide))))
18483
18484 ;; Make sure saveplace shows the location if it was hidden
18485 (eval-after-load "saveplace"
18486 '(defadvice save-place-find-file-hook (after org-make-visible activate)
18487 "Make the position visible."
18488 (org-bookmark-jump-unhide)))
18489
18490 ;; Make sure ecb shows the location if it was hidden
18491 (eval-after-load "ecb"
18492 '(defadvice ecb-method-clicked (after esf/org-show-context activate)
18493 "Make hierarchy visible when jumping into location from ECB tree buffer."
18494 (if (eq major-mode 'org-mode)
18495 (org-show-context))))
18496
18497 (defun org-bookmark-jump-unhide ()
18498 "Unhide the current position, to show the bookmark location."
18499 (and (org-mode-p)
18500 (or (org-invisible-p)
18501 (save-excursion (goto-char (max (point-min) (1- (point))))
18502 (org-invisible-p)))
18503 (org-show-context 'bookmark-jump)))
18504
18505 ;; Make session.el ignore our circular variable
18506 (eval-after-load "session"
18507 '(add-to-list 'session-globals-exclude 'org-mark-ring))
18508
18509 ;;;; Experimental code
18510
18511 (defun org-closed-in-range ()
18512 "Sparse tree of items closed in a certain time range.
18513 Still experimental, may disappear in the future."
18514 (interactive)
18515 ;; Get the time interval from the user.
18516 (let* ((time1 (org-float-time
18517 (org-read-date nil 'to-time nil "Starting date: ")))
18518 (time2 (org-float-time
18519 (org-read-date nil 'to-time nil "End date:")))
18520 ;; callback function
18521 (callback (lambda ()
18522 (let ((time
18523 (org-float-time
18524 (apply 'encode-time
18525 (org-parse-time-string
18526 (match-string 1))))))
18527 ;; check if time in interval
18528 (and (>= time time1) (<= time time2))))))
18529 ;; make tree, check each match with the callback
18530 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
18531
18532 ;;;; Finish up
18533
18534 (provide 'org)
18535
18536 (run-hooks 'org-load-hook)
18537
18538 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
18539
18540 ;;; org.el ends here