]> code.delx.au - gnu-emacs/blob - lisp/org/org.el
Add missing arch-tags
[gnu-emacs] / lisp / org / org.el
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009
4 ;; Free Software Foundation, Inc.
5 ;;
6 ;; Author: Carsten Dominik <carsten at orgmode dot org>
7 ;; Keywords: outlines, hypermedia, calendar, wp
8 ;; Homepage: http://orgmode.org
9 ;; Version: 6.29c
10 ;;
11 ;; This file is part of GNU Emacs.
12 ;;
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;
27 ;;; Commentary:
28 ;;
29 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
30 ;; project planning with a fast and effective plain-text system.
31 ;;
32 ;; Org-mode develops organizational tasks around NOTES files that contain
33 ;; information about projects as plain text. Org-mode is implemented on
34 ;; top of outline-mode, which makes it possible to keep the content of
35 ;; large files well structured. Visibility cycling and structure editing
36 ;; help to work with the tree. Tables are easily created with a built-in
37 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
38 ;; and scheduling. It dynamically compiles entries into an agenda that
39 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
40 ;; Plain text URL-like links connect to websites, emails, Usenet
41 ;; messages, BBDB entries, and any files related to the projects. For
42 ;; printing and sharing of notes, an Org-mode file can be exported as a
43 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
44 ;; iCalendar file. It can also serve as a publishing tool for a set of
45 ;; linked webpages.
46 ;;
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
50 ;;
51 ;; http://orgmode.org/org.html#Installation
52 ;;
53 ;; Documentation
54 ;; -------------
55 ;; The documentation of Org-mode can be found in the TeXInfo file. The
56 ;; distribution also contains a PDF version of it. At the homepage of
57 ;; Org-mode, you can read the same text online as HTML. There is also an
58 ;; excellent reference card made by Philip Rooke. This card can be found
59 ;; in the etc/ directory of Emacs 22.
60 ;;
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
63 ;;
64 ;;; Code:
65
66 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
67 (defvar org-table-formula-constants-local nil
68 "Local version of `org-table-formula-constants'.")
69 (make-variable-buffer-local 'org-table-formula-constants-local)
70
71 ;;;; Require other packages
72
73 (eval-when-compile
74 (require 'cl)
75 (require 'gnus-sum)
76 (require 'calendar))
77 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
78 ;; the file noutline.el being loaded.
79 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
80 ;; We require noutline, which might be provided in outline.el
81 (require 'outline) (require 'noutline)
82 ;; Other stuff we need.
83 (require 'time-date)
84 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
85 (require 'easymenu)
86
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-src)
92 (require 'org-footnote)
93
94 ;;;; Customization variables
95
96 ;;; Version
97
98 (defconst org-version "6.29c"
99 "The version number of the file org.el.")
100
101 (defun org-version (&optional here)
102 "Show the org-mode version in the echo area.
103 With prefix arg HERE, insert it at point."
104 (interactive "P")
105 (let ((version (format "Org-mode version %s" org-version)))
106 (message version)
107 (if here
108 (insert version))))
109
110 ;;; Compatibility constants
111
112 ;;; The custom variables
113
114 (defgroup org nil
115 "Outline-based notes management and organizer."
116 :tag "Org"
117 :group 'outlines
118 :group 'hypermedia
119 :group 'calendar)
120
121 (defcustom org-load-hook nil
122 "Hook that is run after org.el has been loaded."
123 :group 'org
124 :type 'hook)
125
126 (defvar org-modules) ; defined below
127 (defvar org-modules-loaded nil
128 "Have the modules been loaded already?")
129
130 (defun org-load-modules-maybe (&optional force)
131 "Load all extensions listed in `org-modules'."
132 (when (or force (not org-modules-loaded))
133 (mapc (lambda (ext)
134 (condition-case nil (require ext)
135 (error (message "Problems while trying to load feature `%s'" ext))))
136 org-modules)
137 (setq org-modules-loaded t)))
138
139 (defun org-set-modules (var value)
140 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
141 (set var value)
142 (when (featurep 'org)
143 (org-load-modules-maybe 'force)))
144
145 (when (org-bound-and-true-p org-modules)
146 (let ((a (member 'org-infojs org-modules)))
147 (and a (setcar a 'org-jsinfo))))
148
149 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
150 "Modules that should always be loaded together with org.el.
151 If a description starts with <C>, the file is not part of Emacs
152 and loading it will require that you have downloaded and properly installed
153 the org-mode distribution.
154
155 You can also use this system to load external packages (i.e. neither Org
156 core modules, not modules from the CONTRIB directory). Just add symbols
157 to the end of the list. If the package is called org-xyz.el, then you need
158 to add the symbol `xyz', and the package must have a call to
159
160 (provide 'org-xyz)"
161 :group 'org
162 :set 'org-set-modules
163 :type
164 '(set :greedy t
165 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
166 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
167 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
168 (const :tag " id: Global IDs for identifying entries" org-id)
169 (const :tag " info: Links to Info nodes" org-info)
170 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
171 (const :tag " inlinetask: Tasks independent of outline hierarchy" org-inlinetask)
172 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
173 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
174 (const :tag " mew Links to Mew folders/messages" org-mew)
175 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
176 (const :tag " protocol: Intercept calls from emacsclient" org-protocol)
177 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
178 (const :tag " vm: Links to VM folders/messages" org-vm)
179 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
180 (const :tag " w3m: Special cut/paste from w3m to Org." org-w3m)
181 (const :tag " mouse: Additional mouse support" org-mouse)
182
183 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
184 (const :tag "C annotation-helper: Call Remember directly from Browser (OBSOLETE, use org-protocol)" org-annotation-helper)
185 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
186 (const :tag "C browser-url: Store link, directly from Browser (OBSOLETE, use org-protocol)" org-browser-url)
187 (const :tag "C checklist: Extra functions for checklists in repeated tasks" org-checklist)
188 (const :tag "C choose: Use TODO keywords to mark decisions states" org-choose)
189 (const :tag "C collector: Collect properties into tables" org-collector)
190 (const :tag "C depend: TODO dependencies for Org-mode (PARTIALLY OBSOLETE, see built-in dependency support))" org-depend)
191 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
192 (const :tag "C eval: Include command output as text" org-eval)
193 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
194 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
195 (const :tag "C exp-bibtex: Export citations using BibTeX" org-exp-bibtex)
196 (const :tag "C interactive-query: Interactive modification of tags query (PARTIALLY OBSOLETE, see secondary filtering)" org-interactive-query)
197 (const :tag "C jira Add a jira:ticket protocol to Org" org-jira)
198 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
199 (const :tag "C mac-iCal Imports events from iCal.app to the Emacs diary" org-mac-iCal)
200 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
201 (const :tag "C mtags: Support for muse-like tags" org-mtags)
202 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
203 (const :tag "C R: Computation using the R language" org-R)
204 (const :tag "C registry: A registry for Org links" org-registry)
205 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
206 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
207 (const :tag "C special-blocks: Turn blocks into LaTeX envs and HTML divs" org-special-blocks)
208 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
209 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
210 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
211
212 (defcustom org-support-shift-select nil
213 "Non-nil means, make shift-cursor commands select text when possible.
214
215 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
216 selecting a region, or enlarge thusly regions started in this way.
217 In Org-mode, in special contexts, these same keys are used for other
218 purposes, important enough to compete with shift selection. Org tries
219 to balance these needs by supporting `shift-select-mode' outside these
220 special contexts, under control of this variable.
221
222 The default of this variable is nil, to avoid confusing behavior. Shifted
223 cursor keys will then execute Org commands in the following contexts:
224 - on a headline, changing TODO state (left/right) and priority (up/down)
225 - on a time stamp, changing the time
226 - in a plain list item, changing the bullet type
227 - in a property definition line, switching between allowed values
228 - in the BEGIN line of a clock table (changing the time block).
229 Outside these contexts, the commands will throw an error.
230
231 When this variable is t and the cursor is not in a special context,
232 Org-mode will support shift-selection for making and enlarging regions.
233 To make this more effective, the bullet cycling will no longer happen
234 anywhere in an item line, but only if the cursor is exactly on the bullet.
235
236 If you set this variable to the symbol `always', then the keys
237 will not be special in headlines, property lines, and item lines, to make
238 shift selection work there as well. If this is what you want, you can
239 use the following alternative commands: `C-c C-t' and `C-c ,' to
240 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
241 TODO sets, `C-c -' to cycle item bullet types, and properties can be
242 edited by hand or in column view.
243
244 However, when the cursor is on a timestamp, shift-cursor commands
245 will still edit the time stamp - this is just too good to give up.
246
247 XEmacs user should have this variable set to nil, because shift-select-mode
248 is Emacs 23 only."
249 :group 'org
250 :type '(choice
251 (const :tag "Never" nil)
252 (const :tag "When outside special context" t)
253 (const :tag "Everywhere except timestamps" always)))
254
255 (defgroup org-startup nil
256 "Options concerning startup of Org-mode."
257 :tag "Org Startup"
258 :group 'org)
259
260 (defcustom org-startup-folded t
261 "Non-nil means, entering Org-mode will switch to OVERVIEW.
262 This can also be configured on a per-file basis by adding one of
263 the following lines anywhere in the buffer:
264
265 #+STARTUP: fold
266 #+STARTUP: nofold
267 #+STARTUP: content"
268 :group 'org-startup
269 :type '(choice
270 (const :tag "nofold: show all" nil)
271 (const :tag "fold: overview" t)
272 (const :tag "content: all headlines" content)))
273
274 (defcustom org-startup-truncated t
275 "Non-nil means, entering Org-mode will set `truncate-lines'.
276 This is useful since some lines containing links can be very long and
277 uninteresting. Also tables look terrible when wrapped."
278 :group 'org-startup
279 :type 'boolean)
280
281 (defcustom org-startup-indented nil
282 "Non-nil means, turn on `org-indent-mode' on startup.
283 This can also be configured on a per-file basis by adding one of
284 the following lines anywhere in the buffer:
285
286 #+STARTUP: indent
287 #+STARTUP: noindent"
288 :group 'org-structure
289 :type '(choice
290 (const :tag "Not" nil)
291 (const :tag "Globally (slow on startup in large files)" t)))
292
293 (defcustom org-startup-align-all-tables nil
294 "Non-nil means, align all tables when visiting a file.
295 This is useful when the column width in tables is forced with <N> cookies
296 in table fields. Such tables will look correct only after the first re-align.
297 This can also be configured on a per-file basis by adding one of
298 the following lines anywhere in the buffer:
299 #+STARTUP: align
300 #+STARTUP: noalign"
301 :group 'org-startup
302 :type 'boolean)
303
304 (defcustom org-insert-mode-line-in-empty-file nil
305 "Non-nil means insert the first line setting Org-mode in empty files.
306 When the function `org-mode' is called interactively in an empty file, this
307 normally means that the file name does not automatically trigger Org-mode.
308 To ensure that the file will always be in Org-mode in the future, a
309 line enforcing Org-mode will be inserted into the buffer, if this option
310 has been set."
311 :group 'org-startup
312 :type 'boolean)
313
314 (defcustom org-replace-disputed-keys nil
315 "Non-nil means use alternative key bindings for some keys.
316 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
317 These keys are also used by other packages like shift-selection-mode'
318 \(built into Emacs 23), `CUA-mode' or `windmove.el'.
319 If you want to use Org-mode together with one of these other modes,
320 or more generally if you would like to move some Org-mode commands to
321 other keys, set this variable and configure the keys with the variable
322 `org-disputed-keys'.
323
324 This option is only relevant at load-time of Org-mode, and must be set
325 *before* org.el is loaded. Changing it requires a restart of Emacs to
326 become effective."
327 :group 'org-startup
328 :type 'boolean)
329
330 (defcustom org-use-extra-keys nil
331 "Non-nil means use extra key sequence definitions for certain
332 commands. This happens automatically if you run XEmacs or if
333 window-system is nil. This variable lets you do the same
334 manually. You must set it before loading org.
335
336 Example: on Carbon Emacs 22 running graphically, with an external
337 keyboard on a Powerbook, the default way of setting M-left might
338 not work for either Alt or ESC. Setting this variable will make
339 it work for ESC."
340 :group 'org-startup
341 :type 'boolean)
342
343 (if (fboundp 'defvaralias)
344 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
345
346 (defcustom org-disputed-keys
347 '(([(shift up)] . [(meta p)])
348 ([(shift down)] . [(meta n)])
349 ([(shift left)] . [(meta -)])
350 ([(shift right)] . [(meta +)])
351 ([(control shift right)] . [(meta shift +)])
352 ([(control shift left)] . [(meta shift -)]))
353 "Keys for which Org-mode and other modes compete.
354 This is an alist, cars are the default keys, second element specifies
355 the alternative to use when `org-replace-disputed-keys' is t.
356
357 Keys can be specified in any syntax supported by `define-key'.
358 The value of this option takes effect only at Org-mode's startup,
359 therefore you'll have to restart Emacs to apply it after changing."
360 :group 'org-startup
361 :type 'alist)
362
363 (defun org-key (key)
364 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
365 Or return the original if not disputed."
366 (if org-replace-disputed-keys
367 (let* ((nkey (key-description key))
368 (x (org-find-if (lambda (x)
369 (equal (key-description (car x)) nkey))
370 org-disputed-keys)))
371 (if x (cdr x) key))
372 key))
373
374 (defun org-find-if (predicate seq)
375 (catch 'exit
376 (while seq
377 (if (funcall predicate (car seq))
378 (throw 'exit (car seq))
379 (pop seq)))))
380
381 (defun org-defkey (keymap key def)
382 "Define a key, possibly translated, as returned by `org-key'."
383 (define-key keymap (org-key key) def))
384
385 (defcustom org-ellipsis nil
386 "The ellipsis to use in the Org-mode outline.
387 When nil, just use the standard three dots. When a string, use that instead,
388 When a face, use the standard 3 dots, but with the specified face.
389 The change affects only Org-mode (which will then use its own display table).
390 Changing this requires executing `M-x org-mode' in a buffer to become
391 effective."
392 :group 'org-startup
393 :type '(choice (const :tag "Default" nil)
394 (face :tag "Face" :value org-warning)
395 (string :tag "String" :value "...#")))
396
397 (defvar org-display-table nil
398 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
399
400 (defgroup org-keywords nil
401 "Keywords in Org-mode."
402 :tag "Org Keywords"
403 :group 'org)
404
405 (defcustom org-deadline-string "DEADLINE:"
406 "String to mark deadline entries.
407 A deadline is this string, followed by a time stamp. Should be a word,
408 terminated by a colon. You can insert a schedule keyword and
409 a timestamp with \\[org-deadline].
410 Changes become only effective after restarting Emacs."
411 :group 'org-keywords
412 :type 'string)
413
414 (defcustom org-scheduled-string "SCHEDULED:"
415 "String to mark scheduled TODO entries.
416 A schedule is this string, followed by a time stamp. Should be a word,
417 terminated by a colon. You can insert a schedule keyword and
418 a timestamp with \\[org-schedule].
419 Changes become only effective after restarting Emacs."
420 :group 'org-keywords
421 :type 'string)
422
423 (defcustom org-closed-string "CLOSED:"
424 "String used as the prefix for timestamps logging closing a TODO entry."
425 :group 'org-keywords
426 :type 'string)
427
428 (defcustom org-clock-string "CLOCK:"
429 "String used as prefix for timestamps clocking work hours on an item."
430 :group 'org-keywords
431 :type 'string)
432
433 (defcustom org-comment-string "COMMENT"
434 "Entries starting with this keyword will never be exported.
435 An entry can be toggled between COMMENT and normal with
436 \\[org-toggle-comment].
437 Changes become only effective after restarting Emacs."
438 :group 'org-keywords
439 :type 'string)
440
441 (defcustom org-quote-string "QUOTE"
442 "Entries starting with this keyword will be exported in fixed-width font.
443 Quoting applies only to the text in the entry following the headline, and does
444 not extend beyond the next headline, even if that is lower level.
445 An entry can be toggled between QUOTE and normal with
446 \\[org-toggle-fixed-width-section]."
447 :group 'org-keywords
448 :type 'string)
449
450 (defconst org-repeat-re
451 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
452 "Regular expression for specifying repeated events.
453 After a match, group 1 contains the repeat expression.")
454
455 (defgroup org-structure nil
456 "Options concerning the general structure of Org-mode files."
457 :tag "Org Structure"
458 :group 'org)
459
460 (defgroup org-reveal-location nil
461 "Options about how to make context of a location visible."
462 :tag "Org Reveal Location"
463 :group 'org-structure)
464
465 (defconst org-context-choice
466 '(choice
467 (const :tag "Always" t)
468 (const :tag "Never" nil)
469 (repeat :greedy t :tag "Individual contexts"
470 (cons
471 (choice :tag "Context"
472 (const agenda)
473 (const org-goto)
474 (const occur-tree)
475 (const tags-tree)
476 (const link-search)
477 (const mark-goto)
478 (const bookmark-jump)
479 (const isearch)
480 (const default))
481 (boolean))))
482 "Contexts for the reveal options.")
483
484 (defcustom org-show-hierarchy-above '((default . t))
485 "Non-nil means, show full hierarchy when revealing a location.
486 Org-mode often shows locations in an org-mode file which might have
487 been invisible before. When this is set, the hierarchy of headings
488 above the exposed location is shown.
489 Turning this off for example for sparse trees makes them very compact.
490 Instead of t, this can also be an alist specifying this option for different
491 contexts. Valid contexts are
492 agenda when exposing an entry from the agenda
493 org-goto when using the command `org-goto' on key C-c C-j
494 occur-tree when using the command `org-occur' on key C-c /
495 tags-tree when constructing a sparse tree based on tags matches
496 link-search when exposing search matches associated with a link
497 mark-goto when exposing the jump goal of a mark
498 bookmark-jump when exposing a bookmark location
499 isearch when exiting from an incremental search
500 default default for all contexts not set explicitly"
501 :group 'org-reveal-location
502 :type org-context-choice)
503
504 (defcustom org-show-following-heading '((default . nil))
505 "Non-nil means, show following heading when revealing a location.
506 Org-mode often shows locations in an org-mode file which might have
507 been invisible before. When this is set, the heading following the
508 match is shown.
509 Turning this off for example for sparse trees makes them very compact,
510 but makes it harder to edit the location of the match. In such a case,
511 use the command \\[org-reveal] to show more context.
512 Instead of t, this can also be an alist specifying this option for different
513 contexts. See `org-show-hierarchy-above' for valid contexts."
514 :group 'org-reveal-location
515 :type org-context-choice)
516
517 (defcustom org-show-siblings '((default . nil) (isearch t))
518 "Non-nil means, show all sibling heading when revealing a location.
519 Org-mode often shows locations in an org-mode file which might have
520 been invisible before. When this is set, the sibling of the current entry
521 heading are all made visible. If `org-show-hierarchy-above' is t,
522 the same happens on each level of the hierarchy above the current entry.
523
524 By default this is on for the isearch context, off for all other contexts.
525 Turning this off for example for sparse trees makes them very compact,
526 but makes it harder to edit the location of the match. In such a case,
527 use the command \\[org-reveal] to show more context.
528 Instead of t, this can also be an alist specifying this option for different
529 contexts. See `org-show-hierarchy-above' for valid contexts."
530 :group 'org-reveal-location
531 :type org-context-choice)
532
533 (defcustom org-show-entry-below '((default . nil))
534 "Non-nil means, show the entry below a headline when revealing a location.
535 Org-mode often shows locations in an org-mode file which might have
536 been invisible before. When this is set, the text below the headline that is
537 exposed is also shown.
538
539 By default this is off for all contexts.
540 Instead of t, this can also be an alist specifying this option for different
541 contexts. See `org-show-hierarchy-above' for valid contexts."
542 :group 'org-reveal-location
543 :type org-context-choice)
544
545 (defcustom org-indirect-buffer-display 'other-window
546 "How should indirect tree buffers be displayed?
547 This applies to indirect buffers created with the commands
548 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
549 Valid values are:
550 current-window Display in the current window
551 other-window Just display in another window.
552 dedicated-frame Create one new frame, and re-use it each time.
553 new-frame Make a new frame each time. Note that in this case
554 previously-made indirect buffers are kept, and you need to
555 kill these buffers yourself."
556 :group 'org-structure
557 :group 'org-agenda-windows
558 :type '(choice
559 (const :tag "In current window" current-window)
560 (const :tag "In current frame, other window" other-window)
561 (const :tag "Each time a new frame" new-frame)
562 (const :tag "One dedicated frame" dedicated-frame)))
563
564 (defgroup org-cycle nil
565 "Options concerning visibility cycling in Org-mode."
566 :tag "Org Cycle"
567 :group 'org-structure)
568
569 (defcustom org-cycle-skip-children-state-if-no-children t
570 "Non-nil means, skip CHILDREN state in entries that don't have any."
571 :group 'org-cycle
572 :type 'boolean)
573
574 (defcustom org-cycle-max-level nil
575 "Maximum level which should still be subject to visibility cycling.
576 Levels higher than this will, for cycling, be treated as text, not a headline.
577 When `org-odd-levels-only' is set, a value of N in this variable actually
578 means 2N-1 stars as the limiting headline.
579 When nil, cycle all levels.
580 Note that the limiting level of cycling is also influenced by
581 `org-inlinetask-min-level'. When `org-cycle-max-level' is not set but
582 `org-inlinetask-min-level' is, cycling will be limited to levels one less
583 than its value."
584 :group 'org-cycle
585 :type '(choice
586 (const :tag "No limit" nil)
587 (integer :tag "Maximum level")))
588
589 (defcustom org-drawers '("PROPERTIES" "CLOCK" "LOGBOOK")
590 "Names of drawers. Drawers are not opened by cycling on the headline above.
591 Drawers only open with a TAB on the drawer line itself. A drawer looks like
592 this:
593 :DRAWERNAME:
594 .....
595 :END:
596 The drawer \"PROPERTIES\" is special for capturing properties through
597 the property API.
598
599 Drawers can be defined on the per-file basis with a line like:
600
601 #+DRAWERS: HIDDEN STATE PROPERTIES"
602 :group 'org-structure
603 :group 'org-cycle
604 :type '(repeat (string :tag "Drawer Name")))
605
606 (defcustom org-hide-block-startup nil
607 "Non-nil means, , entering Org-mode will fold all blocks.
608 This can also be set in on a per-file basis with
609
610 #+STARTUP: hideblocks
611 #+STARTUP: showblocks"
612 :group 'org-startup
613 :group 'org-cycle
614 :type 'boolean)
615
616 (defcustom org-cycle-global-at-bob nil
617 "Cycle globally if cursor is at beginning of buffer and not at a headline.
618 This makes it possible to do global cycling without having to use S-TAB or
619 C-u TAB. For this special case to work, the first line of the buffer
620 must not be a headline - it may be empty or some other text. When used in
621 this way, `org-cycle-hook' is disables temporarily, to make sure the
622 cursor stays at the beginning of the buffer.
623 When this option is nil, don't do anything special at the beginning
624 of the buffer."
625 :group 'org-cycle
626 :type 'boolean)
627
628 (defcustom org-cycle-emulate-tab t
629 "Where should `org-cycle' emulate TAB.
630 nil Never
631 white Only in completely white lines
632 whitestart Only at the beginning of lines, before the first non-white char
633 t Everywhere except in headlines
634 exc-hl-bol Everywhere except at the start of a headline
635 If TAB is used in a place where it does not emulate TAB, the current subtree
636 visibility is cycled."
637 :group 'org-cycle
638 :type '(choice (const :tag "Never" nil)
639 (const :tag "Only in completely white lines" white)
640 (const :tag "Before first char in a line" whitestart)
641 (const :tag "Everywhere except in headlines" t)
642 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
643 ))
644
645 (defcustom org-cycle-separator-lines 2
646 "Number of empty lines needed to keep an empty line between collapsed trees.
647 If you leave an empty line between the end of a subtree and the following
648 headline, this empty line is hidden when the subtree is folded.
649 Org-mode will leave (exactly) one empty line visible if the number of
650 empty lines is equal or larger to the number given in this variable.
651 So the default 2 means, at least 2 empty lines after the end of a subtree
652 are needed to produce free space between a collapsed subtree and the
653 following headline.
654
655 Special case: when 0, never leave empty lines in collapsed view."
656 :group 'org-cycle
657 :type 'integer)
658 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
659
660 (defcustom org-pre-cycle-hook nil
661 "Hook that is run before visibility cycling is happening.
662 The function(s) in this hook must accept a single argument which indicates
663 the new state that will be set right after running this hook. The
664 argument is a symbol. Before a global state change, it can have the values
665 `overview', `content', or `all'. Before a local state change, it can have
666 the values `folded', `children', or `subtree'."
667 :group 'org-cycle
668 :type 'hook)
669
670 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
671 org-cycle-hide-drawers
672 org-cycle-show-empty-lines
673 org-optimize-window-after-visibility-change)
674 "Hook that is run after `org-cycle' has changed the buffer visibility.
675 The function(s) in this hook must accept a single argument which indicates
676 the new state that was set by the most recent `org-cycle' command. The
677 argument is a symbol. After a global state change, it can have the values
678 `overview', `content', or `all'. After a local state change, it can have
679 the values `folded', `children', or `subtree'."
680 :group 'org-cycle
681 :type 'hook)
682
683 (defgroup org-edit-structure nil
684 "Options concerning structure editing in Org-mode."
685 :tag "Org Edit Structure"
686 :group 'org-structure)
687
688 (defcustom org-odd-levels-only nil
689 "Non-nil means, skip even levels and only use odd levels for the outline.
690 This has the effect that two stars are being added/taken away in
691 promotion/demotion commands. It also influences how levels are
692 handled by the exporters.
693 Changing it requires restart of `font-lock-mode' to become effective
694 for fontification also in regions already fontified.
695 You may also set this on a per-file basis by adding one of the following
696 lines to the buffer:
697
698 #+STARTUP: odd
699 #+STARTUP: oddeven"
700 :group 'org-edit-structure
701 :group 'org-font-lock
702 :type 'boolean)
703
704 (defcustom org-adapt-indentation t
705 "Non-nil means, adapt indentation to outline node level.
706
707 When this variable is set, Org assumes that you write outlines by
708 indenting text in each node to align with the headline (after the stars).
709 The following issues are influenced by this variable:
710
711 - When this is set and the *entire* text in an entry is indented, the
712 indentation is increased by one space in a demotion command, and
713 decreased by one in a promotion command. If any line in the entry
714 body starts with text at column 0, indentation is not changed at all.
715
716 - Property drawers and planning information is inserted indented when
717 this variable s set. When nil, they will not be indented.
718
719 - TAB indents a line relative to context. The lines below a headline
720 will be indented when this variable is set.
721
722 Note that this is all about true indentation, by adding and removing
723 space characters. See also `org-indent.el' which does level-dependent
724 indentation in a virtual way, i.e. at display time in Emacs."
725 :group 'org-edit-structure
726 :type 'boolean)
727
728 (defcustom org-special-ctrl-a/e nil
729 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
730
731 When t, `C-a' will bring back the cursor to the beginning of the
732 headline text, i.e. after the stars and after a possible TODO keyword.
733 In an item, this will be the position after the bullet.
734 When the cursor is already at that position, another `C-a' will bring
735 it to the beginning of the line.
736
737 `C-e' will jump to the end of the headline, ignoring the presence of tags
738 in the headline. A second `C-e' will then jump to the true end of the
739 line, after any tags.
740
741 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
742 going to the true line boundary first. Only a directly following, identical
743 keypress will bring the cursor to the special positions.
744
745 This may also be a cons cell where the behavior for `C-a' and `C-e' is
746 set separately."
747 :group 'org-edit-structure
748 :type '(choice
749 (const :tag "off" nil)
750 (const :tag "after stars/bullet and before tags first" t)
751 (const :tag "true line boundary first" reversed)
752 (cons :tag "Set C-a and C-e separately"
753 (choice :tag "Special C-a"
754 (const :tag "off" nil)
755 (const :tag "after stars/bullet first" t)
756 (const :tag "before stars/bullet first" reversed))
757 (choice :tag "Special C-e"
758 (const :tag "off" nil)
759 (const :tag "before tags first" t)
760 (const :tag "after tags first" reversed)))))
761 (if (fboundp 'defvaralias)
762 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
763
764 (defcustom org-special-ctrl-k nil
765 "Non-nil means `C-k' will behave specially in headlines.
766 When nil, `C-k' will call the default `kill-line' command.
767 When t, the following will happen while the cursor is in the headline:
768
769 - When the cursor is at the beginning of a headline, kill the entire
770 line and possible the folded subtree below the line.
771 - When in the middle of the headline text, kill the headline up to the tags.
772 - When after the headline text, kill the tags."
773 :group 'org-edit-structure
774 :type 'boolean)
775
776 (defcustom org-yank-folded-subtrees t
777 "Non-nil means, when yanking subtrees, fold them.
778 If the kill is a single subtree, or a sequence of subtrees, i.e. if
779 it starts with a heading and all other headings in it are either children
780 or siblings, then fold all the subtrees. However, do this only if no
781 text after the yank would be swallowed into a folded tree by this action."
782 :group 'org-edit-structure
783 :type 'boolean)
784
785 (defcustom org-yank-adjusted-subtrees nil
786 "Non-nil means, when yanking subtrees, adjust the level.
787 With this setting, `org-paste-subtree' is used to insert the subtree, see
788 this function for details."
789 :group 'org-edit-structure
790 :type 'boolean)
791
792 (defcustom org-M-RET-may-split-line '((default . t))
793 "Non-nil means, M-RET will split the line at the cursor position.
794 When nil, it will go to the end of the line before making a
795 new line.
796 You may also set this option in a different way for different
797 contexts. Valid contexts are:
798
799 headline when creating a new headline
800 item when creating a new item
801 table in a table field
802 default the value to be used for all contexts not explicitly
803 customized"
804 :group 'org-structure
805 :group 'org-table
806 :type '(choice
807 (const :tag "Always" t)
808 (const :tag "Never" nil)
809 (repeat :greedy t :tag "Individual contexts"
810 (cons
811 (choice :tag "Context"
812 (const headline)
813 (const item)
814 (const table)
815 (const default))
816 (boolean)))))
817
818
819 (defcustom org-insert-heading-respect-content nil
820 "Non-nil means, insert new headings after the current subtree.
821 When nil, the new heading is created directly after the current line.
822 The commands \\[org-insert-heading-respect-content] and
823 \\[org-insert-todo-heading-respect-content] turn this variable on
824 for the duration of the command."
825 :group 'org-structure
826 :type 'boolean)
827
828 (defcustom org-blank-before-new-entry '((heading . auto)
829 (plain-list-item . auto))
830 "Should `org-insert-heading' leave a blank line before new heading/item?
831 The value is an alist, with `heading' and `plain-list-item' as car,
832 and a boolean flag as cdr. For plain lists, if the variable
833 `org-empty-line-terminates-plain-lists' is set, the setting here
834 is ignored and no empty line is inserted, to keep the list in tact."
835 :group 'org-edit-structure
836 :type '(list
837 (cons (const heading)
838 (choice (const :tag "Never" nil)
839 (const :tag "Always" t)
840 (const :tag "Auto" auto)))
841 (cons (const plain-list-item)
842 (choice (const :tag "Never" nil)
843 (const :tag "Always" t)
844 (const :tag "Auto" auto)))))
845
846 (defcustom org-insert-heading-hook nil
847 "Hook being run after inserting a new heading."
848 :group 'org-edit-structure
849 :type 'hook)
850
851 (defcustom org-enable-fixed-width-editor t
852 "Non-nil means, lines starting with \":\" are treated as fixed-width.
853 This currently only means, they are never auto-wrapped.
854 When nil, such lines will be treated like ordinary lines.
855 See also the QUOTE keyword."
856 :group 'org-edit-structure
857 :type 'boolean)
858
859
860 (defcustom org-goto-auto-isearch t
861 "Non-nil means, typing characters in org-goto starts incremental search."
862 :group 'org-edit-structure
863 :type 'boolean)
864
865 (defgroup org-sparse-trees nil
866 "Options concerning sparse trees in Org-mode."
867 :tag "Org Sparse Trees"
868 :group 'org-structure)
869
870 (defcustom org-highlight-sparse-tree-matches t
871 "Non-nil means, highlight all matches that define a sparse tree.
872 The highlights will automatically disappear the next time the buffer is
873 changed by an edit command."
874 :group 'org-sparse-trees
875 :type 'boolean)
876
877 (defcustom org-remove-highlights-with-change t
878 "Non-nil means, any change to the buffer will remove temporary highlights.
879 Such highlights are created by `org-occur' and `org-clock-display'.
880 When nil, `C-c C-c needs to be used to get rid of the highlights.
881 The highlights created by `org-preview-latex-fragment' always need
882 `C-c C-c' to be removed."
883 :group 'org-sparse-trees
884 :group 'org-time
885 :type 'boolean)
886
887
888 (defcustom org-occur-hook '(org-first-headline-recenter)
889 "Hook that is run after `org-occur' has constructed a sparse tree.
890 This can be used to recenter the window to show as much of the structure
891 as possible."
892 :group 'org-sparse-trees
893 :type 'hook)
894
895 (defgroup org-imenu-and-speedbar nil
896 "Options concerning imenu and speedbar in Org-mode."
897 :tag "Org Imenu and Speedbar"
898 :group 'org-structure)
899
900 (defcustom org-imenu-depth 2
901 "The maximum level for Imenu access to Org-mode headlines.
902 This also applied for speedbar access."
903 :group 'org-imenu-and-speedbar
904 :type 'integer)
905
906 (defgroup org-table nil
907 "Options concerning tables in Org-mode."
908 :tag "Org Table"
909 :group 'org)
910
911 (defcustom org-enable-table-editor 'optimized
912 "Non-nil means, lines starting with \"|\" are handled by the table editor.
913 When nil, such lines will be treated like ordinary lines.
914
915 When equal to the symbol `optimized', the table editor will be optimized to
916 do the following:
917 - Automatic overwrite mode in front of whitespace in table fields.
918 This makes the structure of the table stay in tact as long as the edited
919 field does not exceed the column width.
920 - Minimize the number of realigns. Normally, the table is aligned each time
921 TAB or RET are pressed to move to another field. With optimization this
922 happens only if changes to a field might have changed the column width.
923 Optimization requires replacing the functions `self-insert-command',
924 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
925 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
926 very good at guessing when a re-align will be necessary, but you can always
927 force one with \\[org-ctrl-c-ctrl-c].
928
929 If you would like to use the optimized version in Org-mode, but the
930 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
931
932 This variable can be used to turn on and off the table editor during a session,
933 but in order to toggle optimization, a restart is required.
934
935 See also the variable `org-table-auto-blank-field'."
936 :group 'org-table
937 :type '(choice
938 (const :tag "off" nil)
939 (const :tag "on" t)
940 (const :tag "on, optimized" optimized)))
941
942 (defcustom org-self-insert-cluster-for-undo t
943 "Non-nil means cluster self-insert commands for undo when possible.
944 If this is set, then, like in the Emacs command loop, 20 consequtive
945 characters will be undone together.
946 This is configurable, because there is some impact on typing performance."
947 :group 'org-table
948 :type 'boolean)
949
950 (defcustom org-table-tab-recognizes-table.el t
951 "Non-nil means, TAB will automatically notice a table.el table.
952 When it sees such a table, it moves point into it and - if necessary -
953 calls `table-recognize-table'."
954 :group 'org-table-editing
955 :type 'boolean)
956
957 (defgroup org-link nil
958 "Options concerning links in Org-mode."
959 :tag "Org Link"
960 :group 'org)
961
962 (defvar org-link-abbrev-alist-local nil
963 "Buffer-local version of `org-link-abbrev-alist', which see.
964 The value of this is taken from the #+LINK lines.")
965 (make-variable-buffer-local 'org-link-abbrev-alist-local)
966
967 (defcustom org-link-abbrev-alist nil
968 "Alist of link abbreviations.
969 The car of each element is a string, to be replaced at the start of a link.
970 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
971 links in Org-mode buffers can have an optional tag after a double colon, e.g.
972
973 [[linkkey:tag][description]]
974
975 The 'linkkey' must be a word word, starting with a letter, followed
976 by letters, numbers, '-' or '_'.
977
978 If REPLACE is a string, the tag will simply be appended to create the link.
979 If the string contains \"%s\", the tag will be inserted there. Alternatively,
980 the placeholder \"%h\" will cause a url-encoded version of the tag to
981 be inserted at that point (see the function `url-hexify-string').
982
983 REPLACE may also be a function that will be called with the tag as the
984 only argument to create the link, which should be returned as a string.
985
986 See the manual for examples."
987 :group 'org-link
988 :type '(repeat
989 (cons
990 (string :tag "Protocol")
991 (choice
992 (string :tag "Format")
993 (function)))))
994
995 (defcustom org-descriptive-links t
996 "Non-nil means, hide link part and only show description of bracket links.
997 Bracket links are like [[link][description]]. This variable sets the initial
998 state in new org-mode buffers. The setting can then be toggled on a
999 per-buffer basis from the Org->Hyperlinks menu."
1000 :group 'org-link
1001 :type 'boolean)
1002
1003 (defcustom org-link-file-path-type 'adaptive
1004 "How the path name in file links should be stored.
1005 Valid values are:
1006
1007 relative Relative to the current directory, i.e. the directory of the file
1008 into which the link is being inserted.
1009 absolute Absolute path, if possible with ~ for home directory.
1010 noabbrev Absolute path, no abbreviation of home directory.
1011 adaptive Use relative path for files in the current directory and sub-
1012 directories of it. For other files, use an absolute path."
1013 :group 'org-link
1014 :type '(choice
1015 (const relative)
1016 (const absolute)
1017 (const noabbrev)
1018 (const adaptive)))
1019
1020 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
1021 "Types of links that should be activated in Org-mode files.
1022 This is a list of symbols, each leading to the activation of a certain link
1023 type. In principle, it does not hurt to turn on most link types - there may
1024 be a small gain when turning off unused link types. The types are:
1025
1026 bracket The recommended [[link][description]] or [[link]] links with hiding.
1027 angular Links in angular brackets that may contain whitespace like
1028 <bbdb:Carsten Dominik>.
1029 plain Plain links in normal text, no whitespace, like http://google.com.
1030 radio Text that is matched by a radio target, see manual for details.
1031 tag Tag settings in a headline (link to tag search).
1032 date Time stamps (link to calendar).
1033 footnote Footnote labels.
1034
1035 Changing this variable requires a restart of Emacs to become effective."
1036 :group 'org-link
1037 :type '(set :greedy t
1038 (const :tag "Double bracket links (new style)" bracket)
1039 (const :tag "Angular bracket links (old style)" angular)
1040 (const :tag "Plain text links" plain)
1041 (const :tag "Radio target matches" radio)
1042 (const :tag "Tags" tag)
1043 (const :tag "Timestamps" date)
1044 (const :tag "Footnotes" footnote)))
1045
1046 (defcustom org-make-link-description-function nil
1047 "Function to use to generate link descriptions from links. If
1048 nil the link location will be used. This function must take two
1049 parameters; the first is the link and the second the description
1050 org-insert-link has generated, and should return the description
1051 to use."
1052 :group 'org-link
1053 :type 'function)
1054
1055 (defgroup org-link-store nil
1056 "Options concerning storing links in Org-mode."
1057 :tag "Org Store Link"
1058 :group 'org-link)
1059
1060 (defcustom org-email-link-description-format "Email %c: %.30s"
1061 "Format of the description part of a link to an email or usenet message.
1062 The following %-escapes will be replaced by corresponding information:
1063
1064 %F full \"From\" field
1065 %f name, taken from \"From\" field, address if no name
1066 %T full \"To\" field
1067 %t first name in \"To\" field, address if no name
1068 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1069 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1070 %s subject
1071 %m message-id.
1072
1073 You may use normal field width specification between the % and the letter.
1074 This is for example useful to limit the length of the subject.
1075
1076 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1077 :group 'org-link-store
1078 :type 'string)
1079
1080 (defcustom org-from-is-user-regexp
1081 (let (r1 r2)
1082 (when (and user-mail-address (not (string= user-mail-address "")))
1083 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1084 (when (and user-full-name (not (string= user-full-name "")))
1085 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1086 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1087 "Regexp matched against the \"From:\" header of an email or usenet message.
1088 It should match if the message is from the user him/herself."
1089 :group 'org-link-store
1090 :type 'regexp)
1091
1092 (defcustom org-link-to-org-use-id 'create-if-interactive-and-no-custom-id
1093 "Non-nil means, storing a link to an Org file will use entry IDs.
1094
1095 Note that before this variable is even considered, org-id must be loaded,
1096 so please customize `org-modules' and turn it on.
1097
1098 The variable can have the following values:
1099
1100 t Create an ID if needed to make a link to the current entry.
1101
1102 create-if-interactive
1103 If `org-store-link' is called directly (interactively, as a user
1104 command), do create an ID to support the link. But when doing the
1105 job for remember, only use the ID if it already exists. The
1106 purpose of this setting is to avoid proliferation of unwanted
1107 IDs, just because you happen to be in an Org file when you
1108 call `org-remember' that automatically and preemptively
1109 creates a link. If you do want to get an ID link in a remember
1110 template to an entry not having an ID, create it first by
1111 explicitly creating a link to it, using `C-c C-l' first.
1112
1113 create-if-interactive-and-no-custom-id
1114 Like create-if-interactive, but do not create an ID if there is
1115 a CUSTOM_ID property defined in the entry. This is the default.
1116
1117 use-existing
1118 Use existing ID, do not create one.
1119
1120 nil Never use an ID to make a link, instead link using a text search for
1121 the headline text."
1122 :group 'org-link-store
1123 :type '(choice
1124 (const :tag "Create ID to make link" t)
1125 (const :tag "Create if storing link interactively"
1126 create-if-interactive)
1127 (const :tag "Create if storing link interactively and no CUSTOM_ID is present"
1128 create-if-interactive-and-no-custom-id)
1129 (const :tag "Only use existing" use-existing)
1130 (const :tag "Do not use ID to create link" nil)))
1131
1132 (defcustom org-context-in-file-links t
1133 "Non-nil means, file links from `org-store-link' contain context.
1134 A search string will be added to the file name with :: as separator and
1135 used to find the context when the link is activated by the command
1136 `org-open-at-point'.
1137 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1138 negates this setting for the duration of the command."
1139 :group 'org-link-store
1140 :type 'boolean)
1141
1142 (defcustom org-keep-stored-link-after-insertion nil
1143 "Non-nil means, keep link in list for entire session.
1144
1145 The command `org-store-link' adds a link pointing to the current
1146 location to an internal list. These links accumulate during a session.
1147 The command `org-insert-link' can be used to insert links into any
1148 Org-mode file (offering completion for all stored links). When this
1149 option is nil, every link which has been inserted once using \\[org-insert-link]
1150 will be removed from the list, to make completing the unused links
1151 more efficient."
1152 :group 'org-link-store
1153 :type 'boolean)
1154
1155 (defgroup org-link-follow nil
1156 "Options concerning following links in Org-mode."
1157 :tag "Org Follow Link"
1158 :group 'org-link)
1159
1160 (defcustom org-link-translation-function nil
1161 "Function to translate links with different syntax to Org syntax.
1162 This can be used to translate links created for example by the Planner
1163 or emacs-wiki packages to Org syntax.
1164 The function must accept two parameters, a TYPE containing the link
1165 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1166 which is everything after the link protocol. It should return a cons
1167 with possibly modified values of type and path.
1168 Org contains a function for this, so if you set this variable to
1169 `org-translate-link-from-planner', you should be able follow many
1170 links created by planner."
1171 :group 'org-link-follow
1172 :type 'function)
1173
1174 (defcustom org-follow-link-hook nil
1175 "Hook that is run after a link has been followed."
1176 :group 'org-link-follow
1177 :type 'hook)
1178
1179 (defcustom org-tab-follows-link nil
1180 "Non-nil means, on links TAB will follow the link.
1181 Needs to be set before org.el is loaded.
1182 This really should not be used, it does not make sense, and the
1183 implementation is bad."
1184 :group 'org-link-follow
1185 :type 'boolean)
1186
1187 (defcustom org-return-follows-link nil
1188 "Non-nil means, on links RET will follow the link.
1189 Needs to be set before org.el is loaded."
1190 :group 'org-link-follow
1191 :type 'boolean)
1192
1193 (defcustom org-mouse-1-follows-link
1194 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1195 "Non-nil means, mouse-1 on a link will follow the link.
1196 A longer mouse click will still set point. Does not work on XEmacs.
1197 Needs to be set before org.el is loaded."
1198 :group 'org-link-follow
1199 :type 'boolean)
1200
1201 (defcustom org-mark-ring-length 4
1202 "Number of different positions to be recorded in the ring
1203 Changing this requires a restart of Emacs to work correctly."
1204 :group 'org-link-follow
1205 :type 'integer)
1206
1207 (defcustom org-link-frame-setup
1208 '((vm . vm-visit-folder-other-frame)
1209 (gnus . gnus-other-frame)
1210 (file . find-file-other-window))
1211 "Setup the frame configuration for following links.
1212 When following a link with Emacs, it may often be useful to display
1213 this link in another window or frame. This variable can be used to
1214 set this up for the different types of links.
1215 For VM, use any of
1216 `vm-visit-folder'
1217 `vm-visit-folder-other-frame'
1218 For Gnus, use any of
1219 `gnus'
1220 `gnus-other-frame'
1221 `org-gnus-no-new-news'
1222 For FILE, use any of
1223 `find-file'
1224 `find-file-other-window'
1225 `find-file-other-frame'
1226 For the calendar, use the variable `calendar-setup'.
1227 For BBDB, it is currently only possible to display the matches in
1228 another window."
1229 :group 'org-link-follow
1230 :type '(list
1231 (cons (const vm)
1232 (choice
1233 (const vm-visit-folder)
1234 (const vm-visit-folder-other-window)
1235 (const vm-visit-folder-other-frame)))
1236 (cons (const gnus)
1237 (choice
1238 (const gnus)
1239 (const gnus-other-frame)
1240 (const org-gnus-no-new-news)))
1241 (cons (const file)
1242 (choice
1243 (const find-file)
1244 (const find-file-other-window)
1245 (const find-file-other-frame)))))
1246
1247 (defcustom org-display-internal-link-with-indirect-buffer nil
1248 "Non-nil means, use indirect buffer to display infile links.
1249 Activating internal links (from one location in a file to another location
1250 in the same file) normally just jumps to the location. When the link is
1251 activated with a C-u prefix (or with mouse-3), the link is displayed in
1252 another window. When this option is set, the other window actually displays
1253 an indirect buffer clone of the current buffer, to avoid any visibility
1254 changes to the current buffer."
1255 :group 'org-link-follow
1256 :type 'boolean)
1257
1258 (defcustom org-open-non-existing-files nil
1259 "Non-nil means, `org-open-file' will open non-existing files.
1260 When nil, an error will be generated.
1261 This variable applies only to external applications because they
1262 might choke on non-existing files. If the link is to a file that
1263 will be openend in Emacs, the variable is ignored."
1264 :group 'org-link-follow
1265 :type 'boolean)
1266
1267 (defcustom org-open-directory-means-index-dot-org nil
1268 "Non-nil means, a link to a directory really means to index.org.
1269 When nil, following a directory link will run dired or open a finder/explorer
1270 window on that directory."
1271 :group 'org-link-follow
1272 :type 'boolean)
1273
1274 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1275 "Function and arguments to call for following mailto links.
1276 This is a list with the first element being a lisp function, and the
1277 remaining elements being arguments to the function. In string arguments,
1278 %a will be replaced by the address, and %s will be replaced by the subject
1279 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1280 :group 'org-link-follow
1281 :type '(choice
1282 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1283 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1284 (const :tag "message-mail" (message-mail "%a" "%s"))
1285 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1286
1287 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1288 "Non-nil means, ask for confirmation before executing shell links.
1289 Shell links can be dangerous: just think about a link
1290
1291 [[shell:rm -rf ~/*][Google Search]]
1292
1293 This link would show up in your Org-mode document as \"Google Search\",
1294 but really it would remove your entire home directory.
1295 Therefore we advise against setting this variable to nil.
1296 Just change it to `y-or-n-p' if you want to confirm with a
1297 single keystroke rather than having to type \"yes\"."
1298 :group 'org-link-follow
1299 :type '(choice
1300 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1301 (const :tag "with y-or-n (faster)" y-or-n-p)
1302 (const :tag "no confirmation (dangerous)" nil)))
1303
1304 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1305 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1306 Elisp links can be dangerous: just think about a link
1307
1308 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1309
1310 This link would show up in your Org-mode document as \"Google Search\",
1311 but really it would remove your entire home directory.
1312 Therefore we advise against setting this variable to nil.
1313 Just change it to `y-or-n-p' if you want to confirm with a
1314 single keystroke rather than having to type \"yes\"."
1315 :group 'org-link-follow
1316 :type '(choice
1317 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1318 (const :tag "with y-or-n (faster)" y-or-n-p)
1319 (const :tag "no confirmation (dangerous)" nil)))
1320
1321 (defconst org-file-apps-defaults-gnu
1322 '((remote . emacs)
1323 (system . mailcap)
1324 (t . mailcap))
1325 "Default file applications on a UNIX or GNU/Linux system.
1326 See `org-file-apps'.")
1327
1328 (defconst org-file-apps-defaults-macosx
1329 '((remote . emacs)
1330 (t . "open %s")
1331 (system . "open %s")
1332 ("ps.gz" . "gv %s")
1333 ("eps.gz" . "gv %s")
1334 ("dvi" . "xdvi %s")
1335 ("fig" . "xfig %s"))
1336 "Default file applications on a MacOS X system.
1337 The system \"open\" is known as a default, but we use X11 applications
1338 for some files for which the OS does not have a good default.
1339 See `org-file-apps'.")
1340
1341 (defconst org-file-apps-defaults-windowsnt
1342 (list
1343 '(remote . emacs)
1344 (cons t
1345 (list (if (featurep 'xemacs)
1346 'mswindows-shell-execute
1347 'w32-shell-execute)
1348 "open" 'file))
1349 (cons 'system
1350 (list (if (featurep 'xemacs)
1351 'mswindows-shell-execute
1352 'w32-shell-execute)
1353 "open" 'file)))
1354 "Default file applications on a Windows NT system.
1355 The system \"open\" is used for most files.
1356 See `org-file-apps'.")
1357
1358 (defcustom org-file-apps
1359 '(
1360 (auto-mode . emacs)
1361 ("\\.x?html?\\'" . default)
1362 ("\\.pdf\\'" . default)
1363 )
1364 "External applications for opening `file:path' items in a document.
1365 Org-mode uses system defaults for different file types, but
1366 you can use this variable to set the application for a given file
1367 extension. The entries in this list are cons cells where the car identifies
1368 files and the cdr the corresponding command. Possible values for the
1369 file identifier are
1370 \"regex\" Regular expression matched against the file name. For backward
1371 compatibility, this can also be a string with only alphanumeric
1372 characters, which is then interpreted as an extension.
1373 `directory' Matches a directory
1374 `remote' Matches a remote file, accessible through tramp or efs.
1375 Remote files most likely should be visited through Emacs
1376 because external applications cannot handle such paths.
1377 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1378 so all files Emacs knows how to handle. Using this with
1379 command `emacs' will open most files in Emacs. Beware that this
1380 will also open html files inside Emacs, unless you add
1381 (\"html\" . default) to the list as well.
1382 t Default for files not matched by any of the other options.
1383 `system' The system command to open files, like `open' on Windows
1384 and Mac OS X, and mailcap under GNU/Linux. This is the command
1385 that will be selected if you call `C-c C-o' with a double
1386 `C-u C-u' prefix.
1387
1388 Possible values for the command are:
1389 `emacs' The file will be visited by the current Emacs process.
1390 `default' Use the default application for this file type, which is the
1391 association for t in the list, most likely in the system-specific
1392 part.
1393 This can be used to overrule an unwanted setting in the
1394 system-specific variable.
1395 `system' Use the system command for opening files, like \"open\".
1396 This command is specified by the entry whose car is `system'.
1397 Most likely, the system-specific version of this variable
1398 does define this command, but you can overrule/replace it
1399 here.
1400 string A command to be executed by a shell; %s will be replaced
1401 by the path to the file.
1402 sexp A Lisp form which will be evaluated. The file path will
1403 be available in the Lisp variable `file'.
1404 For more examples, see the system specific constants
1405 `org-file-apps-defaults-macosx'
1406 `org-file-apps-defaults-windowsnt'
1407 `org-file-apps-defaults-gnu'."
1408 :group 'org-link-follow
1409 :type '(repeat
1410 (cons (choice :value ""
1411 (string :tag "Extension")
1412 (const :tag "System command to open files" system)
1413 (const :tag "Default for unrecognized files" t)
1414 (const :tag "Remote file" remote)
1415 (const :tag "Links to a directory" directory)
1416 (const :tag "Any files that have Emacs modes"
1417 auto-mode))
1418 (choice :value ""
1419 (const :tag "Visit with Emacs" emacs)
1420 (const :tag "Use default" default)
1421 (const :tag "Use the system command" system)
1422 (string :tag "Command")
1423 (sexp :tag "Lisp form")))))
1424
1425 (defgroup org-refile nil
1426 "Options concerning refiling entries in Org-mode."
1427 :tag "Org Refile"
1428 :group 'org)
1429
1430 (defcustom org-directory "~/org"
1431 "Directory with org files.
1432 This is just a default location to look for Org files. There is no need
1433 at all to put your files into this directory. It is only used in the
1434 following situations:
1435
1436 1. When a remember template specifies a target file that is not an
1437 absolute path. The path will then be interpreted relative to
1438 `org-directory'
1439 2. When a remember note is filed away in an interactive way (when exiting the
1440 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1441 with `org-directory' as the default path."
1442 :group 'org-refile
1443 :group 'org-remember
1444 :type 'directory)
1445
1446 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1447 "Default target for storing notes.
1448 Used by the hooks for remember.el. This can be a string, or nil to mean
1449 the value of `remember-data-file'.
1450 You can set this on a per-template basis with the variable
1451 `org-remember-templates'."
1452 :group 'org-refile
1453 :group 'org-remember
1454 :type '(choice
1455 (const :tag "Default from remember-data-file" nil)
1456 file))
1457
1458 (defcustom org-goto-interface 'outline
1459 "The default interface to be used for `org-goto'.
1460 Allowed values are:
1461 outline The interface shows an outline of the relevant file
1462 and the correct heading is found by moving through
1463 the outline or by searching with incremental search.
1464 outline-path-completion Headlines in the current buffer are offered via
1465 completion. This is the interface also used by
1466 the refile command."
1467 :group 'org-refile
1468 :type '(choice
1469 (const :tag "Outline" outline)
1470 (const :tag "Outline-path-completion" outline-path-completion)))
1471
1472 (defcustom org-goto-max-level 5
1473 "Maximum level to be considered when running org-goto with refile interface."
1474 :group 'org-refile
1475 :type 'integer)
1476
1477 (defcustom org-reverse-note-order nil
1478 "Non-nil means, store new notes at the beginning of a file or entry.
1479 When nil, new notes will be filed to the end of a file or entry.
1480 This can also be a list with cons cells of regular expressions that
1481 are matched against file names, and values."
1482 :group 'org-remember
1483 :group 'org-refile
1484 :type '(choice
1485 (const :tag "Reverse always" t)
1486 (const :tag "Reverse never" nil)
1487 (repeat :tag "By file name regexp"
1488 (cons regexp boolean))))
1489
1490 (defcustom org-refile-targets nil
1491 "Targets for refiling entries with \\[org-refile].
1492 This is list of cons cells. Each cell contains:
1493 - a specification of the files to be considered, either a list of files,
1494 or a symbol whose function or variable value will be used to retrieve
1495 a file name or a list of file names. If you use `org-agenda-files' for
1496 that, all agenda files will be scanned for targets. Nil means, consider
1497 headings in the current buffer.
1498 - A specification of how to find candidate refile targets. This may be
1499 any of:
1500 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1501 This tag has to be present in all target headlines, inheritance will
1502 not be considered.
1503 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1504 todo keyword.
1505 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1506 headlines that are refiling targets.
1507 - a cons cell (:level . N). Any headline of level N is considered a target.
1508 Note that, when `org-odd-levels-only' is set, level corresponds to
1509 order in hierarchy, not to the number of stars.
1510 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1511 Note that, when `org-odd-levels-only' is set, level corresponds to
1512 order in hierarchy, not to the number of stars.
1513
1514 You can set the variable `org-refile-target-verify-function' to a function
1515 to verify each headline found by the simple critery above.
1516
1517 When this variable is nil, all top-level headlines in the current buffer
1518 are used, equivalent to the value `((nil . (:level . 1))'."
1519 :group 'org-refile
1520 :type '(repeat
1521 (cons
1522 (choice :value org-agenda-files
1523 (const :tag "All agenda files" org-agenda-files)
1524 (const :tag "Current buffer" nil)
1525 (function) (variable) (file))
1526 (choice :tag "Identify target headline by"
1527 (cons :tag "Specific tag" (const :value :tag) (string))
1528 (cons :tag "TODO keyword" (const :value :todo) (string))
1529 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1530 (cons :tag "Level number" (const :value :level) (integer))
1531 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1532
1533 (defcustom org-refile-target-verify-function nil
1534 "Function to verify if the headline at point should be a refile target.
1535 The function will be called without arguments, with point at the
1536 beginning of the headline. It should return t and leave point
1537 where it is if the headline is a valid target for refiling.
1538
1539 If the target should not be selected, the function must return nil.
1540 In addition to this, it may move point to a place from where the search
1541 should be continued. For example, the function may decide that the entire
1542 subtree of the current entry should be excluded and move point to the end
1543 of the subtree."
1544 :group 'org-refile
1545 :type 'function)
1546
1547 (defcustom org-refile-use-outline-path nil
1548 "Non-nil means, provide refile targets as paths.
1549 So a level 3 headline will be available as level1/level2/level3.
1550
1551 When the value is `file', also include the file name (without directory)
1552 into the path. In this case, you can also stop the completion after
1553 the file name, to get entries inserted as top level in the file.
1554
1555 When `full-file-path', include the full file path."
1556 :group 'org-refile
1557 :type '(choice
1558 (const :tag "Not" nil)
1559 (const :tag "Yes" t)
1560 (const :tag "Start with file name" file)
1561 (const :tag "Start with full file path" full-file-path)))
1562
1563 (defcustom org-outline-path-complete-in-steps t
1564 "Non-nil means, complete the outline path in hierarchical steps.
1565 When Org-mode uses the refile interface to select an outline path
1566 \(see variable `org-refile-use-outline-path'), the completion of
1567 the path can be done is a single go, or if can be done in steps down
1568 the headline hierarchy. Going in steps is probably the best if you
1569 do not use a special completion package like `ido' or `icicles'.
1570 However, when using these packages, going in one step can be very
1571 fast, while still showing the whole path to the entry."
1572 :group 'org-refile
1573 :type 'boolean)
1574
1575 (defcustom org-refile-allow-creating-parent-nodes nil
1576 "Non-nil means, allow to create new nodes as refile targets.
1577 New nodes are then created by adding \"/new node name\" to the completion
1578 of an existing node. When the value of this variable is `confirm',
1579 new node creation must be confirmed by the user (recommended)
1580 When nil, the completion must match an existing entry.
1581
1582 Note that, if the new heading is not seen by the criteria
1583 listed in `org-refile-targets', multiple instances of the same
1584 heading would be created by trying again to file under the new
1585 heading."
1586 :group 'org-refile
1587 :type '(choice
1588 (const :tag "Never" nil)
1589 (const :tag "Always" t)
1590 (const :tag "Prompt for confirmation" confirm)))
1591
1592 (defgroup org-todo nil
1593 "Options concerning TODO items in Org-mode."
1594 :tag "Org TODO"
1595 :group 'org)
1596
1597 (defgroup org-progress nil
1598 "Options concerning Progress logging in Org-mode."
1599 :tag "Org Progress"
1600 :group 'org-time)
1601
1602 (defvar org-todo-interpretation-widgets
1603 '(
1604 (:tag "Sequence (cycling hits every state)" sequence)
1605 (:tag "Type (cycling directly to DONE)" type))
1606 "The available interpretation symbols for customizing
1607 `org-todo-keywords'.
1608 Interested libraries should add to this list.")
1609
1610 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1611 "List of TODO entry keyword sequences and their interpretation.
1612 \\<org-mode-map>This is a list of sequences.
1613
1614 Each sequence starts with a symbol, either `sequence' or `type',
1615 indicating if the keywords should be interpreted as a sequence of
1616 action steps, or as different types of TODO items. The first
1617 keywords are states requiring action - these states will select a headline
1618 for inclusion into the global TODO list Org-mode produces. If one of
1619 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1620 signify that no further action is necessary. If \"|\" is not found,
1621 the last keyword is treated as the only DONE state of the sequence.
1622
1623 The command \\[org-todo] cycles an entry through these states, and one
1624 additional state where no keyword is present. For details about this
1625 cycling, see the manual.
1626
1627 TODO keywords and interpretation can also be set on a per-file basis with
1628 the special #+SEQ_TODO and #+TYP_TODO lines.
1629
1630 Each keyword can optionally specify a character for fast state selection
1631 \(in combination with the variable `org-use-fast-todo-selection')
1632 and specifiers for state change logging, using the same syntax
1633 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1634 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1635 indicates to record a time stamp each time this state is selected.
1636
1637 Each keyword may also specify if a timestamp or a note should be
1638 recorded when entering or leaving the state, by adding additional
1639 characters in the parenthesis after the keyword. This looks like this:
1640 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1641 record only the time of the state change. With X and Y being either
1642 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1643 Y when leaving the state if and only if the *target* state does not
1644 define X. You may omit any of the fast-selection key or X or /Y,
1645 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1646
1647 For backward compatibility, this variable may also be just a list
1648 of keywords - in this case the interpretation (sequence or type) will be
1649 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1650 :group 'org-todo
1651 :group 'org-keywords
1652 :type '(choice
1653 (repeat :tag "Old syntax, just keywords"
1654 (string :tag "Keyword"))
1655 (repeat :tag "New syntax"
1656 (cons
1657 (choice
1658 :tag "Interpretation"
1659 ;;Quick and dirty way to see
1660 ;;`org-todo-interpretations'. This takes the
1661 ;;place of item arguments
1662 :convert-widget
1663 (lambda (widget)
1664 (widget-put widget
1665 :args (mapcar
1666 #'(lambda (x)
1667 (widget-convert
1668 (cons 'const x)))
1669 org-todo-interpretation-widgets))
1670 widget))
1671 (repeat
1672 (string :tag "Keyword"))))))
1673
1674 (defvar org-todo-keywords-1 nil
1675 "All TODO and DONE keywords active in a buffer.")
1676 (make-variable-buffer-local 'org-todo-keywords-1)
1677 (defvar org-todo-keywords-for-agenda nil)
1678 (defvar org-done-keywords-for-agenda nil)
1679 (defvar org-todo-keyword-alist-for-agenda nil)
1680 (defvar org-tag-alist-for-agenda nil)
1681 (defvar org-agenda-contributing-files nil)
1682 (defvar org-not-done-keywords nil)
1683 (make-variable-buffer-local 'org-not-done-keywords)
1684 (defvar org-done-keywords nil)
1685 (make-variable-buffer-local 'org-done-keywords)
1686 (defvar org-todo-heads nil)
1687 (make-variable-buffer-local 'org-todo-heads)
1688 (defvar org-todo-sets nil)
1689 (make-variable-buffer-local 'org-todo-sets)
1690 (defvar org-todo-log-states nil)
1691 (make-variable-buffer-local 'org-todo-log-states)
1692 (defvar org-todo-kwd-alist nil)
1693 (make-variable-buffer-local 'org-todo-kwd-alist)
1694 (defvar org-todo-key-alist nil)
1695 (make-variable-buffer-local 'org-todo-key-alist)
1696 (defvar org-todo-key-trigger nil)
1697 (make-variable-buffer-local 'org-todo-key-trigger)
1698
1699 (defcustom org-todo-interpretation 'sequence
1700 "Controls how TODO keywords are interpreted.
1701 This variable is in principle obsolete and is only used for
1702 backward compatibility, if the interpretation of todo keywords is
1703 not given already in `org-todo-keywords'. See that variable for
1704 more information."
1705 :group 'org-todo
1706 :group 'org-keywords
1707 :type '(choice (const sequence)
1708 (const type)))
1709
1710 (defcustom org-use-fast-todo-selection t
1711 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1712 This variable describes if and under what circumstances the cycling
1713 mechanism for TODO keywords will be replaced by a single-key, direct
1714 selection scheme.
1715
1716 When nil, fast selection is never used.
1717
1718 When the symbol `prefix', it will be used when `org-todo' is called with
1719 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1720 in an agenda buffer.
1721
1722 When t, fast selection is used by default. In this case, the prefix
1723 argument forces cycling instead.
1724
1725 In all cases, the special interface is only used if access keys have actually
1726 been assigned by the user, i.e. if keywords in the configuration are followed
1727 by a letter in parenthesis, like TODO(t)."
1728 :group 'org-todo
1729 :type '(choice
1730 (const :tag "Never" nil)
1731 (const :tag "By default" t)
1732 (const :tag "Only with C-u C-c C-t" prefix)))
1733
1734 (defcustom org-provide-todo-statistics t
1735 "Non-nil means, update todo statistics after insert and toggle.
1736 ALL-HEADLINES means update todo statistics by including headlines
1737 with no TODO keyword as well, counting them as not done.
1738 A list of TODO keywords means the same, but skip keywords that are
1739 not in this list.
1740
1741 When this is set, todo statistics is updated in the parent of the
1742 current entry each time a todo state is changed."
1743 :group 'org-todo
1744 :type '(choice
1745 (const :tag "Yes, only for TODO entries" t)
1746 (const :tag "Yes, including all entries" 'all-headlines)
1747 (repeat :tag "Yes, for TODOs in this list"
1748 (string :tag "TODO keyword"))
1749 (other :tag "No TODO statistics" nil)))
1750
1751 (defcustom org-hierarchical-todo-statistics t
1752 "Non-nil means, TODO statistics covers just direct children.
1753 When nil, all entries in the subtree are considered.
1754 This has only an effect if `org-provide-todo-statistics' is set."
1755 :group 'org-todo
1756 :type 'boolean)
1757
1758 (defcustom org-after-todo-state-change-hook nil
1759 "Hook which is run after the state of a TODO item was changed.
1760 The new state (a string with a TODO keyword, or nil) is available in the
1761 Lisp variable `state'."
1762 :group 'org-todo
1763 :type 'hook)
1764
1765 (defvar org-blocker-hook nil
1766 "Hook for functions that are allowed to block a state change.
1767
1768 Each function gets as its single argument a property list, see
1769 `org-trigger-hook' for more information about this list.
1770
1771 If any of the functions in this hook returns nil, the state change
1772 is blocked.")
1773
1774 (defvar org-trigger-hook nil
1775 "Hook for functions that are triggered by a state change.
1776
1777 Each function gets as its single argument a property list with at least
1778 the following elements:
1779
1780 (:type type-of-change :position pos-at-entry-start
1781 :from old-state :to new-state)
1782
1783 Depending on the type, more properties may be present.
1784
1785 This mechanism is currently implemented for:
1786
1787 TODO state changes
1788 ------------------
1789 :type todo-state-change
1790 :from previous state (keyword as a string), or nil, or a symbol
1791 'todo' or 'done', to indicate the general type of state.
1792 :to new state, like in :from")
1793
1794 (defcustom org-enforce-todo-dependencies nil
1795 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1796 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1797 be blocked if any prior sibling is not yet done.
1798 Finally, if the parent is blocked because of ordered siblings of its own,
1799 the child will also be blocked.
1800 This variable needs to be set before org.el is loaded, and you need to
1801 restart Emacs after a change to make the change effective. The only way
1802 to change is while Emacs is running is through the customize interface."
1803 :set (lambda (var val)
1804 (set var val)
1805 (if val
1806 (add-hook 'org-blocker-hook
1807 'org-block-todo-from-children-or-siblings-or-parent)
1808 (remove-hook 'org-blocker-hook
1809 'org-block-todo-from-children-or-siblings-or-parent)))
1810 :group 'org-todo
1811 :type 'boolean)
1812
1813 (defcustom org-enforce-todo-checkbox-dependencies nil
1814 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1815 When this is nil, checkboxes have no influence on switching TODO states.
1816 When non-nil, you first need to check off all check boxes before the TODO
1817 entry can be switched to DONE.
1818 This variable needs to be set before org.el is loaded, and you need to
1819 restart Emacs after a change to make the change effective. The only way
1820 to change is while Emacs is running is through the customize interface."
1821 :set (lambda (var val)
1822 (set var val)
1823 (if val
1824 (add-hook 'org-blocker-hook
1825 'org-block-todo-from-checkboxes)
1826 (remove-hook 'org-blocker-hook
1827 'org-block-todo-from-checkboxes)))
1828 :group 'org-todo
1829 :type 'boolean)
1830
1831 (defcustom org-treat-insert-todo-heading-as-state-change nil
1832 "Non-nil means, inserting a TODO heading is treated as state change.
1833 So when the command \\[org-insert-todo-heading] is used, state change
1834 logging will apply if appropriate. When nil, the new TODO item will
1835 be inserted directly, and no logging will take place."
1836 :group 'org-todo
1837 :type 'boolean)
1838
1839 (defcustom org-treat-S-cursor-todo-selection-as-state-change t
1840 "Non-nil means, switching TODO states with S-cursor counts as state change.
1841 This is the default behavior. However, setting this to nil allows a
1842 convenient way to select a TODO state and bypass any logging associated
1843 with that."
1844 :group 'org-todo
1845 :type 'boolean)
1846
1847 (defcustom org-todo-state-tags-triggers nil
1848 "Tag changes that should be triggered by TODO state changes.
1849 This is a list. Each entry is
1850
1851 (state-change (tag . flag) .......)
1852
1853 State-change can be a string with a state, and empty string to indicate the
1854 state that has no TODO keyword, or it can be one of the symbols `todo'
1855 or `done', meaning any not-done or done state, respectively."
1856 :group 'org-todo
1857 :group 'org-tags
1858 :type '(repeat
1859 (cons (choice :tag "When changing to"
1860 (const :tag "Not-done state" todo)
1861 (const :tag "Done state" done)
1862 (string :tag "State"))
1863 (repeat
1864 (cons :tag "Tag action"
1865 (string :tag "Tag")
1866 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1867
1868 (defcustom org-log-done nil
1869 "Information to record when a task moves to the DONE state.
1870
1871 Possible values are:
1872
1873 nil Don't add anything, just change the keyword
1874 time Add a time stamp to the task
1875 note Prompt a closing note and add it with template `org-log-note-headings'
1876
1877 This option can also be set with on a per-file-basis with
1878
1879 #+STARTUP: nologdone
1880 #+STARTUP: logdone
1881 #+STARTUP: lognotedone
1882
1883 You can have local logging settings for a subtree by setting the LOGGING
1884 property to one or more of these keywords."
1885 :group 'org-todo
1886 :group 'org-progress
1887 :type '(choice
1888 (const :tag "No logging" nil)
1889 (const :tag "Record CLOSED timestamp" time)
1890 (const :tag "Record CLOSED timestamp with closing note." note)))
1891
1892 ;; Normalize old uses of org-log-done.
1893 (cond
1894 ((eq org-log-done t) (setq org-log-done 'time))
1895 ((and (listp org-log-done) (memq 'done org-log-done))
1896 (setq org-log-done 'note)))
1897
1898 (defcustom org-log-note-clock-out nil
1899 "Non-nil means, record a note when clocking out of an item.
1900 This can also be configured on a per-file basis by adding one of
1901 the following lines anywhere in the buffer:
1902
1903 #+STARTUP: lognoteclock-out
1904 #+STARTUP: nolognoteclock-out"
1905 :group 'org-todo
1906 :group 'org-progress
1907 :type 'boolean)
1908
1909 (defcustom org-log-done-with-time t
1910 "Non-nil means, the CLOSED time stamp will contain date and time.
1911 When nil, only the date will be recorded."
1912 :group 'org-progress
1913 :type 'boolean)
1914
1915 (defcustom org-log-note-headings
1916 '((done . "CLOSING NOTE %t")
1917 (state . "State %-12s from %-12S %t")
1918 (note . "Note taken on %t")
1919 (clock-out . ""))
1920 "Headings for notes added to entries.
1921 The value is an alist, with the car being a symbol indicating the note
1922 context, and the cdr is the heading to be used. The heading may also be the
1923 empty string.
1924 %t in the heading will be replaced by a time stamp.
1925 %s will be replaced by the new TODO state, in double quotes.
1926 %S will be replaced by the old TODO state, in double quotes.
1927 %u will be replaced by the user name.
1928 %U will be replaced by the full user name."
1929 :group 'org-todo
1930 :group 'org-progress
1931 :type '(list :greedy t
1932 (cons (const :tag "Heading when closing an item" done) string)
1933 (cons (const :tag
1934 "Heading when changing todo state (todo sequence only)"
1935 state) string)
1936 (cons (const :tag "Heading when just taking a note" note) string)
1937 (cons (const :tag "Heading when clocking out" clock-out) string)))
1938
1939 (unless (assq 'note org-log-note-headings)
1940 (push '(note . "%t") org-log-note-headings))
1941
1942 (defcustom org-log-into-drawer nil
1943 "Non-nil means, insert state change notes and time stamps into a drawer.
1944 When nil, state changes notes will be inserted after the headline and
1945 any scheduling and clock lines, but not inside a drawer.
1946
1947 The value of this variable should be the name of the drawer to use.
1948 LOGBOOK is proposed at the default drawer for this purpose, you can
1949 also set this to a string to define the drawer of your choice.
1950
1951 A value of t is also allowed, representing \"LOGBOOK\".
1952
1953 If this variable is set, `org-log-state-notes-insert-after-drawers'
1954 will be ignored.
1955
1956 You can set the property LOG_INTO_DRAWER to overrule this setting for
1957 a subtree."
1958 :group 'org-todo
1959 :group 'org-progress
1960 :type '(choice
1961 (const :tag "Not into a drawer" nil)
1962 (const :tag "LOGBOOK" t)
1963 (string :tag "Other")))
1964
1965 (if (fboundp 'defvaralias)
1966 (defvaralias 'org-log-state-notes-into-drawer 'org-log-into-drawer))
1967
1968 (defun org-log-into-drawer ()
1969 "Return the value of `org-log-into-drawer', but let properties overrule.
1970 If the current entry has or inherits a LOG_INTO_DRAWER property, it will be
1971 used instead of the default value."
1972 (let ((p (ignore-errors (org-entry-get nil "LOG_INTO_DRAWER" 'inherit))))
1973 (cond
1974 ((or (not p) (equal p "nil")) org-log-into-drawer)
1975 ((equal p "t") "LOGBOOK")
1976 (t p))))
1977
1978 (defcustom org-log-state-notes-insert-after-drawers nil
1979 "Non-nil means, insert state change notes after any drawers in entry.
1980 Only the drawers that *immediately* follow the headline and the
1981 deadline/scheduled line are skipped.
1982 When nil, insert notes right after the heading and perhaps the line
1983 with deadline/scheduling if present.
1984
1985 This variable will have no effect if `org-log-into-drawer' is
1986 set."
1987 :group 'org-todo
1988 :group 'org-progress
1989 :type 'boolean)
1990
1991 (defcustom org-log-states-order-reversed t
1992 "Non-nil means, the latest state change note will be directly after heading.
1993 When nil, the notes will be orderer according to time."
1994 :group 'org-todo
1995 :group 'org-progress
1996 :type 'boolean)
1997
1998 (defcustom org-log-repeat 'time
1999 "Non-nil means, record moving through the DONE state when triggering repeat.
2000 An auto-repeating tasks is immediately switched back to TODO when marked
2001 done. If you are not logging state changes (by adding \"@\" or \"!\" to
2002 the TODO keyword definition, or recording a closing note by setting
2003 `org-log-done', there will be no record of the task moving through DONE.
2004 This variable forces taking a note anyway. Possible values are:
2005
2006 nil Don't force a record
2007 time Record a time stamp
2008 note Record a note
2009
2010 This option can also be set with on a per-file-basis with
2011
2012 #+STARTUP: logrepeat
2013 #+STARTUP: lognoterepeat
2014 #+STARTUP: nologrepeat
2015
2016 You can have local logging settings for a subtree by setting the LOGGING
2017 property to one or more of these keywords."
2018 :group 'org-todo
2019 :group 'org-progress
2020 :type '(choice
2021 (const :tag "Don't force a record" nil)
2022 (const :tag "Force recording the DONE state" time)
2023 (const :tag "Force recording a note with the DONE state" note)))
2024
2025
2026 (defgroup org-priorities nil
2027 "Priorities in Org-mode."
2028 :tag "Org Priorities"
2029 :group 'org-todo)
2030
2031 (defcustom org-enable-priority-commands t
2032 "Non-nil means, priority commands are active.
2033 When nil, these commands will be disabled, so that you never accidentally
2034 set a priority."
2035 :group 'org-priorities
2036 :type 'boolean)
2037
2038 (defcustom org-highest-priority ?A
2039 "The highest priority of TODO items. A character like ?A, ?B etc.
2040 Must have a smaller ASCII number than `org-lowest-priority'."
2041 :group 'org-priorities
2042 :type 'character)
2043
2044 (defcustom org-lowest-priority ?C
2045 "The lowest priority of TODO items. A character like ?A, ?B etc.
2046 Must have a larger ASCII number than `org-highest-priority'."
2047 :group 'org-priorities
2048 :type 'character)
2049
2050 (defcustom org-default-priority ?B
2051 "The default priority of TODO items.
2052 This is the priority an item get if no explicit priority is given."
2053 :group 'org-priorities
2054 :type 'character)
2055
2056 (defcustom org-priority-start-cycle-with-default t
2057 "Non-nil means, start with default priority when starting to cycle.
2058 When this is nil, the first step in the cycle will be (depending on the
2059 command used) one higher or lower that the default priority."
2060 :group 'org-priorities
2061 :type 'boolean)
2062
2063 (defgroup org-time nil
2064 "Options concerning time stamps and deadlines in Org-mode."
2065 :tag "Org Time"
2066 :group 'org)
2067
2068 (defcustom org-insert-labeled-timestamps-at-point nil
2069 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
2070 When nil, these labeled time stamps are forces into the second line of an
2071 entry, just after the headline. When scheduling from the global TODO list,
2072 the time stamp will always be forced into the second line."
2073 :group 'org-time
2074 :type 'boolean)
2075
2076 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
2077 "Formats for `format-time-string' which are used for time stamps.
2078 It is not recommended to change this constant.")
2079
2080 (defcustom org-time-stamp-rounding-minutes '(0 5)
2081 "Number of minutes to round time stamps to.
2082 These are two values, the first applies when first creating a time stamp.
2083 The second applies when changing it with the commands `S-up' and `S-down'.
2084 When changing the time stamp, this means that it will change in steps
2085 of N minutes, as given by the second value.
2086
2087 When a setting is 0 or 1, insert the time unmodified. Useful rounding
2088 numbers should be factors of 60, so for example 5, 10, 15.
2089
2090 When this is larger than 1, you can still force an exact time-stamp by using
2091 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
2092 and by using a prefix arg to `S-up/down' to specify the exact number
2093 of minutes to shift."
2094 :group 'org-time
2095 :get '(lambda (var) ; Make sure all entries have 5 elements
2096 (if (integerp (default-value var))
2097 (list (default-value var) 5)
2098 (default-value var)))
2099 :type '(list
2100 (integer :tag "when inserting times")
2101 (integer :tag "when modifying times")))
2102
2103 ;; Normalize old customizations of this variable.
2104 (when (integerp org-time-stamp-rounding-minutes)
2105 (setq org-time-stamp-rounding-minutes
2106 (list org-time-stamp-rounding-minutes
2107 org-time-stamp-rounding-minutes)))
2108
2109 (defcustom org-display-custom-times nil
2110 "Non-nil means, overlay custom formats over all time stamps.
2111 The formats are defined through the variable `org-time-stamp-custom-formats'.
2112 To turn this on on a per-file basis, insert anywhere in the file:
2113 #+STARTUP: customtime"
2114 :group 'org-time
2115 :set 'set-default
2116 :type 'sexp)
2117 (make-variable-buffer-local 'org-display-custom-times)
2118
2119 (defcustom org-time-stamp-custom-formats
2120 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
2121 "Custom formats for time stamps. See `format-time-string' for the syntax.
2122 These are overlayed over the default ISO format if the variable
2123 `org-display-custom-times' is set. Time like %H:%M should be at the
2124 end of the second format. The custom formats are also honored by export
2125 commands, if custom time display is turned on at the time of export."
2126 :group 'org-time
2127 :type 'sexp)
2128
2129 (defun org-time-stamp-format (&optional long inactive)
2130 "Get the right format for a time string."
2131 (let ((f (if long (cdr org-time-stamp-formats)
2132 (car org-time-stamp-formats))))
2133 (if inactive
2134 (concat "[" (substring f 1 -1) "]")
2135 f)))
2136
2137 (defcustom org-time-clocksum-format "%d:%02d"
2138 "The format string used when creating CLOCKSUM lines, or when
2139 org-mode generates a time duration."
2140 :group 'org-time
2141 :type 'string)
2142
2143 (defcustom org-deadline-warning-days 14
2144 "No. of days before expiration during which a deadline becomes active.
2145 This variable governs the display in sparse trees and in the agenda.
2146 When 0 or negative, it means use this number (the absolute value of it)
2147 even if a deadline has a different individual lead time specified.
2148
2149 Custom commands can set this variable in the options section."
2150 :group 'org-time
2151 :group 'org-agenda-daily/weekly
2152 :type 'integer)
2153
2154 (defcustom org-read-date-prefer-future t
2155 "Non-nil means, assume future for incomplete date input from user.
2156 This affects the following situations:
2157 1. The user gives a day, but no month.
2158 For example, if today is the 15th, and you enter \"3\", Org-mode will
2159 read this as the third of *next* month. However, if you enter \"17\",
2160 it will be considered as *this* month.
2161 2. The user gives a month but not a year.
2162 For example, if it is april and you enter \"feb 2\", this will be read
2163 as feb 2, *next* year. \"May 5\", however, will be this year.
2164
2165 Currently this does not work for ISO week specifications.
2166
2167 When this option is nil, the current month and year will always be used
2168 as defaults."
2169 :group 'org-time
2170 :type 'boolean)
2171
2172 (defcustom org-read-date-display-live t
2173 "Non-nil means, display current interpretation of date prompt live.
2174 This display will be in an overlay, in the minibuffer."
2175 :group 'org-time
2176 :type 'boolean)
2177
2178 (defcustom org-read-date-popup-calendar t
2179 "Non-nil means, pop up a calendar when prompting for a date.
2180 In the calendar, the date can be selected with mouse-1. However, the
2181 minibuffer will also be active, and you can simply enter the date as well.
2182 When nil, only the minibuffer will be available."
2183 :group 'org-time
2184 :type 'boolean)
2185 (if (fboundp 'defvaralias)
2186 (defvaralias 'org-popup-calendar-for-date-prompt
2187 'org-read-date-popup-calendar))
2188
2189 (defcustom org-read-date-minibuffer-setup-hook nil
2190 "Hook to be used to set up keys for the date/time interface.
2191 Add key definitions to `minibuffer-local-map', which will be a temporary
2192 copy."
2193 :group 'org-time
2194 :type 'hook)
2195
2196 (defcustom org-extend-today-until 0
2197 "The hour when your day really ends. Must be an integer.
2198 This has influence for the following applications:
2199 - When switching the agenda to \"today\". It it is still earlier than
2200 the time given here, the day recognized as TODAY is actually yesterday.
2201 - When a date is read from the user and it is still before the time given
2202 here, the current date and time will be assumed to be yesterday, 23:59.
2203 Also, timestamps inserted in remember templates follow this rule.
2204
2205 IMPORTANT: This is a feature whose implementation is and likely will
2206 remain incomplete. Really, it is only here because past midnight seems to
2207 be the favorite working time of John Wiegley :-)"
2208 :group 'org-time
2209 :type 'integer)
2210
2211 (defcustom org-edit-timestamp-down-means-later nil
2212 "Non-nil means, S-down will increase the time in a time stamp.
2213 When nil, S-up will increase."
2214 :group 'org-time
2215 :type 'boolean)
2216
2217 (defcustom org-calendar-follow-timestamp-change t
2218 "Non-nil means, make the calendar window follow timestamp changes.
2219 When a timestamp is modified and the calendar window is visible, it will be
2220 moved to the new date."
2221 :group 'org-time
2222 :type 'boolean)
2223
2224 (defgroup org-tags nil
2225 "Options concerning tags in Org-mode."
2226 :tag "Org Tags"
2227 :group 'org)
2228
2229 (defcustom org-tag-alist nil
2230 "List of tags allowed in Org-mode files.
2231 When this list is nil, Org-mode will base TAG input on what is already in the
2232 buffer.
2233 The value of this variable is an alist, the car of each entry must be a
2234 keyword as a string, the cdr may be a character that is used to select
2235 that tag through the fast-tag-selection interface.
2236 See the manual for details."
2237 :group 'org-tags
2238 :type '(repeat
2239 (choice
2240 (cons (string :tag "Tag name")
2241 (character :tag "Access char"))
2242 (const :tag "Start radio group" (:startgroup))
2243 (const :tag "End radio group" (:endgroup))
2244 (const :tag "New line" (:newline)))))
2245
2246 (defcustom org-tag-persistent-alist nil
2247 "List of tags that will always appear in all Org-mode files.
2248 This is in addition to any in buffer settings or customizations
2249 of `org-tag-alist'.
2250 When this list is nil, Org-mode will base TAG input on `org-tag-alist'.
2251 The value of this variable is an alist, the car of each entry must be a
2252 keyword as a string, the cdr may be a character that is used to select
2253 that tag through the fast-tag-selection interface.
2254 See the manual for details.
2255 To disable these tags on a per-file basis, insert anywhere in the file:
2256 #+STARTUP: noptag"
2257 :group 'org-tags
2258 :type '(repeat
2259 (choice
2260 (cons (string :tag "Tag name")
2261 (character :tag "Access char"))
2262 (const :tag "Start radio group" (:startgroup))
2263 (const :tag "End radio group" (:endgroup))
2264 (const :tag "New line" (:newline)))))
2265
2266 (defvar org-file-tags nil
2267 "List of tags that can be inherited by all entries in the file.
2268 The tags will be inherited if the variable `org-use-tag-inheritance'
2269 says they should be.
2270 This variable is populated from #+TAG lines.")
2271
2272 (defcustom org-use-fast-tag-selection 'auto
2273 "Non-nil means, use fast tag selection scheme.
2274 This is a special interface to select and deselect tags with single keys.
2275 When nil, fast selection is never used.
2276 When the symbol `auto', fast selection is used if and only if selection
2277 characters for tags have been configured, either through the variable
2278 `org-tag-alist' or through a #+TAGS line in the buffer.
2279 When t, fast selection is always used and selection keys are assigned
2280 automatically if necessary."
2281 :group 'org-tags
2282 :type '(choice
2283 (const :tag "Always" t)
2284 (const :tag "Never" nil)
2285 (const :tag "When selection characters are configured" 'auto)))
2286
2287 (defcustom org-fast-tag-selection-single-key nil
2288 "Non-nil means, fast tag selection exits after first change.
2289 When nil, you have to press RET to exit it.
2290 During fast tag selection, you can toggle this flag with `C-c'.
2291 This variable can also have the value `expert'. In this case, the window
2292 displaying the tags menu is not even shown, until you press C-c again."
2293 :group 'org-tags
2294 :type '(choice
2295 (const :tag "No" nil)
2296 (const :tag "Yes" t)
2297 (const :tag "Expert" expert)))
2298
2299 (defvar org-fast-tag-selection-include-todo nil
2300 "Non-nil means, fast tags selection interface will also offer TODO states.
2301 This is an undocumented feature, you should not rely on it.")
2302
2303 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2304 "The column to which tags should be indented in a headline.
2305 If this number is positive, it specifies the column. If it is negative,
2306 it means that the tags should be flushright to that column. For example,
2307 -80 works well for a normal 80 character screen."
2308 :group 'org-tags
2309 :type 'integer)
2310
2311 (defcustom org-auto-align-tags t
2312 "Non-nil means, realign tags after pro/demotion of TODO state change.
2313 These operations change the length of a headline and therefore shift
2314 the tags around. With this options turned on, after each such operation
2315 the tags are again aligned to `org-tags-column'."
2316 :group 'org-tags
2317 :type 'boolean)
2318
2319 (defcustom org-use-tag-inheritance t
2320 "Non-nil means, tags in levels apply also for sublevels.
2321 When nil, only the tags directly given in a specific line apply there.
2322 This may also be a list of tags that should be inherited, or a regexp that
2323 matches tags that should be inherited. Additional control is possible
2324 with the variable `org-tags-exclude-from-inheritance' which gives an
2325 explicit list of tags to be excluded from inheritance., even if the value of
2326 `org-use-tag-inheritance' would select it for inheritance.
2327
2328 If this option is t, a match early-on in a tree can lead to a large
2329 number of matches in the subtree when constructing the agenda or creating
2330 a sparse tree. If you only want to see the first match in a tree during
2331 a search, check out the variable `org-tags-match-list-sublevels'."
2332 :group 'org-tags
2333 :type '(choice
2334 (const :tag "Not" nil)
2335 (const :tag "Always" t)
2336 (repeat :tag "Specific tags" (string :tag "Tag"))
2337 (regexp :tag "Tags matched by regexp")))
2338
2339 (defcustom org-tags-exclude-from-inheritance nil
2340 "List of tags that should never be inherited.
2341 This is a way to exclude a few tags from inheritance. For way to do
2342 the opposite, to actively allow inheritance for selected tags,
2343 see the variable `org-use-tag-inheritance'."
2344 :group 'org-tags
2345 :type '(repeat (string :tag "Tag")))
2346
2347 (defun org-tag-inherit-p (tag)
2348 "Check if TAG is one that should be inherited."
2349 (cond
2350 ((member tag org-tags-exclude-from-inheritance) nil)
2351 ((eq org-use-tag-inheritance t) t)
2352 ((not org-use-tag-inheritance) nil)
2353 ((stringp org-use-tag-inheritance)
2354 (string-match org-use-tag-inheritance tag))
2355 ((listp org-use-tag-inheritance)
2356 (member tag org-use-tag-inheritance))
2357 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2358
2359 (defcustom org-tags-match-list-sublevels t
2360 "Non-nil means list also sublevels of headlines matching a search.
2361 This variable applies to tags/property searches, and also to stuck
2362 projects because this search is based on a tags match as well.
2363
2364 When set to the symbol `indented', sublevels are indented with
2365 leading dots.
2366
2367 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2368 the sublevels of a headline matching a tag search often also match
2369 the same search. Listing all of them can create very long lists.
2370 Setting this variable to nil causes subtrees of a match to be skipped.
2371
2372 This variable is semi-obsolete and probably should always be true. It
2373 is better to limit inheritance to certain tags using the variables
2374 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2375 :group 'org-tags
2376 :type '(choice
2377 (const :tag "No, don't list them" nil)
2378 (const :tag "Yes, do list them" t)
2379 (const :tag "List them, indented with leading dots" indented)))
2380
2381 (defcustom org-tags-sort-function nil
2382 "When set, tags are sorted using this function as a comparator"
2383 :group 'org-tags
2384 :type '(choice
2385 (const :tag "No sorting" nil)
2386 (const :tag "Alphabetical" string<)
2387 (const :tag "Reverse alphabetical" string>)
2388 (function :tag "Custom function" nil)))
2389
2390 (defvar org-tags-history nil
2391 "History of minibuffer reads for tags.")
2392 (defvar org-last-tags-completion-table nil
2393 "The last used completion table for tags.")
2394 (defvar org-after-tags-change-hook nil
2395 "Hook that is run after the tags in a line have changed.")
2396
2397 (defgroup org-properties nil
2398 "Options concerning properties in Org-mode."
2399 :tag "Org Properties"
2400 :group 'org)
2401
2402 (defcustom org-property-format "%-10s %s"
2403 "How property key/value pairs should be formatted by `indent-line'.
2404 When `indent-line' hits a property definition, it will format the line
2405 according to this format, mainly to make sure that the values are
2406 lined-up with respect to each other."
2407 :group 'org-properties
2408 :type 'string)
2409
2410 (defcustom org-use-property-inheritance nil
2411 "Non-nil means, properties apply also for sublevels.
2412
2413 This setting is chiefly used during property searches. Turning it on can
2414 cause significant overhead when doing a search, which is why it is not
2415 on by default.
2416
2417 When nil, only the properties directly given in the current entry count.
2418 When t, every property is inherited. The value may also be a list of
2419 properties that should have inheritance, or a regular expression matching
2420 properties that should be inherited.
2421
2422 However, note that some special properties use inheritance under special
2423 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2424 and the properties ending in \"_ALL\" when they are used as descriptor
2425 for valid values of a property.
2426
2427 Note for programmers:
2428 When querying an entry with `org-entry-get', you can control if inheritance
2429 should be used. By default, `org-entry-get' looks only at the local
2430 properties. You can request inheritance by setting the inherit argument
2431 to t (to force inheritance) or to `selective' (to respect the setting
2432 in this variable)."
2433 :group 'org-properties
2434 :type '(choice
2435 (const :tag "Not" nil)
2436 (const :tag "Always" t)
2437 (repeat :tag "Specific properties" (string :tag "Property"))
2438 (regexp :tag "Properties matched by regexp")))
2439
2440 (defun org-property-inherit-p (property)
2441 "Check if PROPERTY is one that should be inherited."
2442 (cond
2443 ((eq org-use-property-inheritance t) t)
2444 ((not org-use-property-inheritance) nil)
2445 ((stringp org-use-property-inheritance)
2446 (string-match org-use-property-inheritance property))
2447 ((listp org-use-property-inheritance)
2448 (member property org-use-property-inheritance))
2449 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2450
2451 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2452 "The default column format, if no other format has been defined.
2453 This variable can be set on the per-file basis by inserting a line
2454
2455 #+COLUMNS: %25ITEM ....."
2456 :group 'org-properties
2457 :type 'string)
2458
2459 (defcustom org-columns-ellipses ".."
2460 "The ellipses to be used when a field in column view is truncated.
2461 When this is the empty string, as many characters as possible are shown,
2462 but then there will be no visual indication that the field has been truncated.
2463 When this is a string of length N, the last N characters of a truncated
2464 field are replaced by this string. If the column is narrower than the
2465 ellipses string, only part of the ellipses string will be shown."
2466 :group 'org-properties
2467 :type 'string)
2468
2469 (defcustom org-columns-modify-value-for-display-function nil
2470 "Function that modifies values for display in column view.
2471 For example, it can be used to cut out a certain part from a time stamp.
2472 The function must take 2 arguments:
2473
2474 column-title The title of the column (*not* the property name)
2475 value The value that should be modified.
2476
2477 The function should return the value that should be displayed,
2478 or nil if the normal value should be used."
2479 :group 'org-properties
2480 :type 'function)
2481
2482 (defcustom org-effort-property "Effort"
2483 "The property that is being used to keep track of effort estimates.
2484 Effort estimates given in this property need to have the format H:MM."
2485 :group 'org-properties
2486 :group 'org-progress
2487 :type '(string :tag "Property"))
2488
2489 (defconst org-global-properties-fixed
2490 '(("VISIBILITY_ALL" . "folded children content all")
2491 ("CLOCK_MODELINE_TOTAL_ALL" . "current today repeat all auto"))
2492 "List of property/value pairs that can be inherited by any entry.
2493
2494 These are fixed values, for the preset properties. The user variable
2495 that can be used to add to this list is `org-global-properties'.
2496
2497 The entries in this list are cons cells where the car is a property
2498 name and cdr is a string with the value. If the value represents
2499 multiple items like an \"_ALL\" property, separate the items by
2500 spaces.")
2501
2502 (defcustom org-global-properties nil
2503 "List of property/value pairs that can be inherited by any entry.
2504
2505 This list will be combined with the constant `org-global-properties-fixed'.
2506
2507 The entries in this list are cons cells where the car is a property
2508 name and cdr is a string with the value.
2509
2510 You can set buffer-local values for the same purpose in the variable
2511 `org-file-properties' this by adding lines like
2512
2513 #+PROPERTY: NAME VALUE"
2514 :group 'org-properties
2515 :type '(repeat
2516 (cons (string :tag "Property")
2517 (string :tag "Value"))))
2518
2519 (defvar org-file-properties nil
2520 "List of property/value pairs that can be inherited by any entry.
2521 Valid for the current buffer.
2522 This variable is populated from #+PROPERTY lines.")
2523 (make-variable-buffer-local 'org-file-properties)
2524
2525 (defgroup org-agenda nil
2526 "Options concerning agenda views in Org-mode."
2527 :tag "Org Agenda"
2528 :group 'org)
2529
2530 (defvar org-category nil
2531 "Variable used by org files to set a category for agenda display.
2532 Such files should use a file variable to set it, for example
2533
2534 # -*- mode: org; org-category: \"ELisp\"
2535
2536 or contain a special line
2537
2538 #+CATEGORY: ELisp
2539
2540 If the file does not specify a category, then file's base name
2541 is used instead.")
2542 (make-variable-buffer-local 'org-category)
2543 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2544
2545 (defcustom org-agenda-files nil
2546 "The files to be used for agenda display.
2547 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2548 \\[org-remove-file]. You can also use customize to edit the list.
2549
2550 If an entry is a directory, all files in that directory that are matched by
2551 `org-agenda-file-regexp' will be part of the file list.
2552
2553 If the value of the variable is not a list but a single file name, then
2554 the list of agenda files is actually stored and maintained in that file, one
2555 agenda file per line."
2556 :group 'org-agenda
2557 :type '(choice
2558 (repeat :tag "List of files and directories" file)
2559 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2560
2561 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2562 "Regular expression to match files for `org-agenda-files'.
2563 If any element in the list in that variable contains a directory instead
2564 of a normal file, all files in that directory that are matched by this
2565 regular expression will be included."
2566 :group 'org-agenda
2567 :type 'regexp)
2568
2569 (defcustom org-agenda-text-search-extra-files nil
2570 "List of extra files to be searched by text search commands.
2571 These files will be search in addition to the agenda files by the
2572 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2573 Note that these files will only be searched for text search commands,
2574 not for the other agenda views like todo lists, tag searches or the weekly
2575 agenda. This variable is intended to list notes and possibly archive files
2576 that should also be searched by these two commands.
2577 In fact, if the first element in the list is the symbol `agenda-archives',
2578 than all archive files of all agenda files will be added to the search
2579 scope."
2580 :group 'org-agenda
2581 :type '(set :greedy t
2582 (const :tag "Agenda Archives" agenda-archives)
2583 (repeat :inline t (file))))
2584
2585 (if (fboundp 'defvaralias)
2586 (defvaralias 'org-agenda-multi-occur-extra-files
2587 'org-agenda-text-search-extra-files))
2588
2589 (defcustom org-agenda-skip-unavailable-files nil
2590 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2591 A nil value means to remove them, after a query, from the list."
2592 :group 'org-agenda
2593 :type 'boolean)
2594
2595 (defcustom org-calendar-to-agenda-key [?c]
2596 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2597 The command `org-calendar-goto-agenda' will be bound to this key. The
2598 default is the character `c' because then `c' can be used to switch back and
2599 forth between agenda and calendar."
2600 :group 'org-agenda
2601 :type 'sexp)
2602
2603 (defcustom org-calendar-agenda-action-key [?k]
2604 "The key to be installed in `calendar-mode-map' for agenda-action.
2605 The command `org-agenda-action' will be bound to this key. The
2606 default is the character `k' because we use the same key in the agenda."
2607 :group 'org-agenda
2608 :type 'sexp)
2609
2610 (eval-after-load "calendar"
2611 '(progn
2612 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2613 'org-calendar-goto-agenda)
2614 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2615 'org-agenda-action)))
2616
2617 (defgroup org-latex nil
2618 "Options for embedding LaTeX code into Org-mode."
2619 :tag "Org LaTeX"
2620 :group 'org)
2621
2622 (defcustom org-format-latex-options
2623 '(:foreground default :background default :scale 1.0
2624 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2625 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2626 "Options for creating images from LaTeX fragments.
2627 This is a property list with the following properties:
2628 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2629 `default' means use the foreground of the default face.
2630 :background the background color, or \"Transparent\".
2631 `default' means use the background of the default face.
2632 :scale a scaling factor for the size of the images.
2633 :html-foreground, :html-background, :html-scale
2634 the same numbers for HTML export.
2635 :matchers a list indicating which matchers should be used to
2636 find LaTeX fragments. Valid members of this list are:
2637 \"begin\" find environments
2638 \"$1\" find single characters surrounded by $.$
2639 \"$\" find math expressions surrounded by $...$
2640 \"$$\" find math expressions surrounded by $$....$$
2641 \"\\(\" find math expressions surrounded by \\(...\\)
2642 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2643 :group 'org-latex
2644 :type 'plist)
2645
2646 (defcustom org-format-latex-header "\\documentclass{article}
2647 \\usepackage{fullpage} % do not remove
2648 \\usepackage{amssymb}
2649 \\usepackage[usenames]{color}
2650 \\usepackage{amsmath}
2651 \\usepackage{latexsym}
2652 \\usepackage[mathscr]{eucal}
2653 \\pagestyle{empty} % do not remove"
2654 "The document header used for processing LaTeX fragments."
2655 :group 'org-latex
2656 :type 'string)
2657
2658
2659 (defgroup org-font-lock nil
2660 "Font-lock settings for highlighting in Org-mode."
2661 :tag "Org Font Lock"
2662 :group 'org)
2663
2664 (defcustom org-level-color-stars-only nil
2665 "Non-nil means fontify only the stars in each headline.
2666 When nil, the entire headline is fontified.
2667 Changing it requires restart of `font-lock-mode' to become effective
2668 also in regions already fontified."
2669 :group 'org-font-lock
2670 :type 'boolean)
2671
2672 (defcustom org-hide-leading-stars nil
2673 "Non-nil means, hide the first N-1 stars in a headline.
2674 This works by using the face `org-hide' for these stars. This
2675 face is white for a light background, and black for a dark
2676 background. You may have to customize the face `org-hide' to
2677 make this work.
2678 Changing it requires restart of `font-lock-mode' to become effective
2679 also in regions already fontified.
2680 You may also set this on a per-file basis by adding one of the following
2681 lines to the buffer:
2682
2683 #+STARTUP: hidestars
2684 #+STARTUP: showstars"
2685 :group 'org-font-lock
2686 :type 'boolean)
2687
2688 (defcustom org-fontify-done-headline nil
2689 "Non-nil means, change the face of a headline if it is marked DONE.
2690 Normally, only the TODO/DONE keyword indicates the state of a headline.
2691 When this is non-nil, the headline after the keyword is set to the
2692 `org-headline-done' as an additional indication."
2693 :group 'org-font-lock
2694 :type 'boolean)
2695
2696 (defcustom org-fontify-emphasized-text t
2697 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2698 Changing this variable requires a restart of Emacs to take effect."
2699 :group 'org-font-lock
2700 :type 'boolean)
2701
2702 (defcustom org-fontify-whole-heading-line nil
2703 "Non-nil means fontify the whole line for headings.
2704 This is useful when setting a background color for the
2705 org-leve-* faces."
2706 :group 'org-font-lock
2707 :type 'boolean)
2708
2709 (defcustom org-highlight-latex-fragments-and-specials nil
2710 "Non-nil means, fontify what is treated specially by the exporters."
2711 :group 'org-font-lock
2712 :type 'boolean)
2713
2714 (defcustom org-hide-emphasis-markers nil
2715 "Non-nil mean font-lock should hide the emphasis marker characters."
2716 :group 'org-font-lock
2717 :type 'boolean)
2718
2719 (defvar org-emph-re nil
2720 "Regular expression for matching emphasis.")
2721 (defvar org-verbatim-re nil
2722 "Regular expression for matching verbatim text.")
2723 (defvar org-emphasis-regexp-components) ; defined just below
2724 (defvar org-emphasis-alist) ; defined just below
2725 (defun org-set-emph-re (var val)
2726 "Set variable and compute the emphasis regular expression."
2727 (set var val)
2728 (when (and (boundp 'org-emphasis-alist)
2729 (boundp 'org-emphasis-regexp-components)
2730 org-emphasis-alist org-emphasis-regexp-components)
2731 (let* ((e org-emphasis-regexp-components)
2732 (pre (car e))
2733 (post (nth 1 e))
2734 (border (nth 2 e))
2735 (body (nth 3 e))
2736 (nl (nth 4 e))
2737 (body1 (concat body "*?"))
2738 (markers (mapconcat 'car org-emphasis-alist ""))
2739 (vmarkers (mapconcat
2740 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2741 org-emphasis-alist "")))
2742 ;; make sure special characters appear at the right position in the class
2743 (if (string-match "\\^" markers)
2744 (setq markers (concat (replace-match "" t t markers) "^")))
2745 (if (string-match "-" markers)
2746 (setq markers (concat (replace-match "" t t markers) "-")))
2747 (if (string-match "\\^" vmarkers)
2748 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2749 (if (string-match "-" vmarkers)
2750 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2751 (if (> nl 0)
2752 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2753 (int-to-string nl) "\\}")))
2754 ;; Make the regexp
2755 (setq org-emph-re
2756 (concat "\\([" pre "]\\|^\\)"
2757 "\\("
2758 "\\([" markers "]\\)"
2759 "\\("
2760 "[^" border "]\\|"
2761 "[^" border "]"
2762 body1
2763 "[^" border "]"
2764 "\\)"
2765 "\\3\\)"
2766 "\\([" post "]\\|$\\)"))
2767 (setq org-verbatim-re
2768 (concat "\\([" pre "]\\|^\\)"
2769 "\\("
2770 "\\([" vmarkers "]\\)"
2771 "\\("
2772 "[^" border "]\\|"
2773 "[^" border "]"
2774 body1
2775 "[^" border "]"
2776 "\\)"
2777 "\\3\\)"
2778 "\\([" post "]\\|$\\)")))))
2779
2780 (defcustom org-emphasis-regexp-components
2781 '(" \t('\"{" "- \t.,:!?;'\")}\\" " \t\r\n,\"'" "." 1)
2782 "Components used to build the regular expression for emphasis.
2783 This is a list with 6 entries. Terminology: In an emphasis string
2784 like \" *strong word* \", we call the initial space PREMATCH, the final
2785 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2786 and \"trong wor\" is the body. The different components in this variable
2787 specify what is allowed/forbidden in each part:
2788
2789 pre Chars allowed as prematch. Beginning of line will be allowed too.
2790 post Chars allowed as postmatch. End of line will be allowed too.
2791 border The chars *forbidden* as border characters.
2792 body-regexp A regexp like \".\" to match a body character. Don't use
2793 non-shy groups here, and don't allow newline here.
2794 newline The maximum number of newlines allowed in an emphasis exp.
2795
2796 Use customize to modify this, or restart Emacs after changing it."
2797 :group 'org-font-lock
2798 :set 'org-set-emph-re
2799 :type '(list
2800 (sexp :tag "Allowed chars in pre ")
2801 (sexp :tag "Allowed chars in post ")
2802 (sexp :tag "Forbidden chars in border ")
2803 (sexp :tag "Regexp for body ")
2804 (integer :tag "number of newlines allowed")
2805 (option (boolean :tag "Please ignore this button"))))
2806
2807 (defcustom org-emphasis-alist
2808 `(("*" bold "<b>" "</b>")
2809 ("/" italic "<i>" "</i>")
2810 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2811 ("=" org-code "<code>" "</code>" verbatim)
2812 ("~" org-verbatim "<code>" "</code>" verbatim)
2813 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2814 "<del>" "</del>")
2815 )
2816 "Special syntax for emphasized text.
2817 Text starting and ending with a special character will be emphasized, for
2818 example *bold*, _underlined_ and /italic/. This variable sets the marker
2819 characters, the face to be used by font-lock for highlighting in Org-mode
2820 Emacs buffers, and the HTML tags to be used for this.
2821 For LaTeX export, see the variable `org-export-latex-emphasis-alist'.
2822 Use customize to modify this, or restart Emacs after changing it."
2823 :group 'org-font-lock
2824 :set 'org-set-emph-re
2825 :type '(repeat
2826 (list
2827 (string :tag "Marker character")
2828 (choice
2829 (face :tag "Font-lock-face")
2830 (plist :tag "Face property list"))
2831 (string :tag "HTML start tag")
2832 (string :tag "HTML end tag")
2833 (option (const verbatim)))))
2834
2835 (defvar org-protecting-blocks
2836 '("src" "example" "latex" "ascii" "html" "docbook" "ditaa" "dot" "r" "R")
2837 "Blocks that contain text that is quoted, i.e. not processed as Org syntax.
2838 This is needed for font-lock setup.")
2839
2840 ;;; Miscellaneous options
2841
2842 (defgroup org-completion nil
2843 "Completion in Org-mode."
2844 :tag "Org Completion"
2845 :group 'org)
2846
2847 (defcustom org-completion-use-ido nil
2848 "Non-nil means, use ido completion wherever possible.
2849 Note that `ido-mode' must be active for this variable to be relevant.
2850 If you decide to turn this variable on, you might well want to turn off
2851 `org-outline-path-complete-in-steps'."
2852 :group 'org-completion
2853 :type 'boolean)
2854
2855 (defcustom org-completion-fallback-command 'hippie-expand
2856 "The expansion command called by \\[org-complete] in normal context.
2857 Normal means, no org-mode-specific context."
2858 :group 'org-completion
2859 :type 'function)
2860
2861 ;;; Functions and variables from ther packages
2862 ;; Declared here to avoid compiler warnings
2863
2864 ;; XEmacs only
2865 (defvar outline-mode-menu-heading)
2866 (defvar outline-mode-menu-show)
2867 (defvar outline-mode-menu-hide)
2868 (defvar zmacs-regions) ; XEmacs regions
2869
2870 ;; Emacs only
2871 (defvar mark-active)
2872
2873 ;; Various packages
2874 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2875 (declare-function calendar-forward-day "cal-move" (arg))
2876 (declare-function calendar-goto-date "cal-move" (date))
2877 (declare-function calendar-goto-today "cal-move" ())
2878 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2879 (defvar calc-embedded-close-formula)
2880 (defvar calc-embedded-open-formula)
2881 (declare-function cdlatex-tab "ext:cdlatex" ())
2882 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2883 (defvar font-lock-unfontify-region-function)
2884 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2885 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2886 (defvar iswitchb-temp-buflist)
2887 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2888 (defvar org-agenda-tags-todo-honor-ignore-options)
2889 (declare-function org-agenda-skip "org-agenda" ())
2890 (declare-function org-format-agenda-item "org-agenda"
2891 (extra txt &optional category tags dotime noprefix remove-re))
2892 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2893 (declare-function org-agenda-change-all-lines "org-agenda"
2894 (newhead hdmarker &optional fixface just-this))
2895 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2896 (declare-function org-agenda-maybe-redo "org-agenda" ())
2897 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2898 (beg end))
2899 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2900 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2901 "org-agenda" (&optional end))
2902 (declare-function org-inlinetask-remove-END-maybe "org-inlinetask" ())
2903 (declare-function org-indent-mode "org-indent" (arg))
2904 (declare-function parse-time-string "parse-time" (string))
2905 (declare-function remember "remember" (&optional initial))
2906 (declare-function remember-buffer-desc "remember" ())
2907 (declare-function remember-finalize "remember" ())
2908 (defvar remember-save-after-remembering)
2909 (defvar remember-data-file)
2910 (defvar remember-register)
2911 (defvar remember-buffer)
2912 (defvar remember-handler-functions)
2913 (defvar remember-annotation-functions)
2914 (defvar texmathp-why)
2915 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2916 (declare-function table--at-cell-p "table" (position &optional object at-column))
2917
2918 (defvar w3m-current-url)
2919 (defvar w3m-current-title)
2920
2921 (defvar org-latex-regexps)
2922
2923 ;;; Autoload and prepare some org modules
2924
2925 ;; Some table stuff that needs to be defined here, because it is used
2926 ;; by the functions setting up org-mode or checking for table context.
2927
2928 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2929 "Detects an org-type or table-type table.")
2930 (defconst org-table-line-regexp "^[ \t]*|"
2931 "Detects an org-type table line.")
2932 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2933 "Detects an org-type table line.")
2934 (defconst org-table-hline-regexp "^[ \t]*|-"
2935 "Detects an org-type table hline.")
2936 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2937 "Detects a table-type table hline.")
2938 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2939 "Searching from within a table (any type) this finds the first line
2940 outside the table.")
2941
2942 ;; Autoload the functions in org-table.el that are needed by functions here.
2943
2944 (eval-and-compile
2945 (org-autoload "org-table"
2946 '(org-table-align org-table-begin org-table-blank-field
2947 org-table-convert org-table-convert-region org-table-copy-down
2948 org-table-copy-region org-table-create
2949 org-table-create-or-convert-from-region
2950 org-table-create-with-table.el org-table-current-dline
2951 org-table-cut-region org-table-delete-column org-table-edit-field
2952 org-table-edit-formulas org-table-end org-table-eval-formula
2953 org-table-export org-table-field-info
2954 org-table-get-stored-formulas org-table-goto-column
2955 org-table-hline-and-move org-table-import org-table-insert-column
2956 org-table-insert-hline org-table-insert-row org-table-iterate
2957 org-table-justify-field-maybe org-table-kill-row
2958 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2959 org-table-move-column org-table-move-column-left
2960 org-table-move-column-right org-table-move-row
2961 org-table-move-row-down org-table-move-row-up
2962 org-table-next-field org-table-next-row org-table-paste-rectangle
2963 org-table-previous-field org-table-recalculate
2964 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2965 org-table-toggle-coordinate-overlays
2966 org-table-toggle-formula-debugger org-table-wrap-region
2967 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2968
2969 (defun org-at-table-p (&optional table-type)
2970 "Return t if the cursor is inside an org-type table.
2971 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2972 (if org-enable-table-editor
2973 (save-excursion
2974 (beginning-of-line 1)
2975 (looking-at (if table-type org-table-any-line-regexp
2976 org-table-line-regexp)))
2977 nil))
2978 (defsubst org-table-p () (org-at-table-p))
2979
2980 (defun org-at-table.el-p ()
2981 "Return t if and only if we are at a table.el table."
2982 (and (org-at-table-p 'any)
2983 (save-excursion
2984 (goto-char (org-table-begin 'any))
2985 (looking-at org-table1-hline-regexp))))
2986 (defun org-table-recognize-table.el ()
2987 "If there is a table.el table nearby, recognize it and move into it."
2988 (if org-table-tab-recognizes-table.el
2989 (if (org-at-table.el-p)
2990 (progn
2991 (beginning-of-line 1)
2992 (if (looking-at org-table-dataline-regexp)
2993 nil
2994 (if (looking-at org-table1-hline-regexp)
2995 (progn
2996 (beginning-of-line 2)
2997 (if (looking-at org-table-any-border-regexp)
2998 (beginning-of-line -1)))))
2999 (if (re-search-forward "|" (org-table-end t) t)
3000 (progn
3001 (require 'table)
3002 (if (table--at-cell-p (point))
3003 t
3004 (message "recognizing table.el table...")
3005 (table-recognize-table)
3006 (message "recognizing table.el table...done")))
3007 (error "This should not happen..."))
3008 t)
3009 nil)
3010 nil))
3011
3012 (defun org-at-table-hline-p ()
3013 "Return t if the cursor is inside a hline in a table."
3014 (if org-enable-table-editor
3015 (save-excursion
3016 (beginning-of-line 1)
3017 (looking-at org-table-hline-regexp))
3018 nil))
3019
3020 (defvar org-table-clean-did-remove-column nil)
3021
3022 (defun org-table-map-tables (function)
3023 "Apply FUNCTION to the start of all tables in the buffer."
3024 (save-excursion
3025 (save-restriction
3026 (widen)
3027 (goto-char (point-min))
3028 (while (re-search-forward org-table-any-line-regexp nil t)
3029 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
3030 (beginning-of-line 1)
3031 (when (looking-at org-table-line-regexp)
3032 (save-excursion (funcall function))
3033 (or (looking-at org-table-line-regexp)
3034 (forward-char 1)))
3035 (re-search-forward org-table-any-border-regexp nil 1))))
3036 (message "Mapping tables: done"))
3037
3038 ;; Declare and autoload functions from org-exp.el & Co
3039
3040 (declare-function org-default-export-plist "org-exp")
3041 (declare-function org-infile-export-plist "org-exp")
3042 (declare-function org-get-current-options "org-exp")
3043 (eval-and-compile
3044 (org-autoload "org-exp"
3045 '(org-export org-export-visible
3046 org-insert-export-options-template
3047 org-table-clean-before-export))
3048 (org-autoload "org-ascii"
3049 '(org-export-as-ascii org-export-ascii-preprocess
3050 org-export-as-ascii-to-buffer org-replace-region-by-ascii
3051 org-export-region-as-ascii))
3052 (org-autoload "org-html"
3053 '(org-export-as-html-and-open
3054 org-export-as-html-batch org-export-as-html-to-buffer
3055 org-replace-region-by-html org-export-region-as-html
3056 org-export-as-html))
3057 (org-autoload "org-icalendar"
3058 '(org-export-icalendar-this-file
3059 org-export-icalendar-all-agenda-files
3060 org-export-icalendar-combine-agenda-files))
3061 (org-autoload "org-xoxo" '(org-export-as-xoxo)))
3062
3063 ;; Declare and autoload functions from org-agenda.el
3064
3065 (eval-and-compile
3066 (org-autoload "org-agenda"
3067 '(org-agenda org-agenda-list org-search-view
3068 org-todo-list org-tags-view org-agenda-list-stuck-projects
3069 org-diary org-agenda-to-appt
3070 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
3071
3072 ;; Autoload org-remember
3073
3074 (eval-and-compile
3075 (org-autoload "org-remember"
3076 '(org-remember-insinuate org-remember-annotation
3077 org-remember-apply-template org-remember org-remember-handler)))
3078
3079 ;; Autoload org-clock.el
3080
3081
3082 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
3083 (beg end))
3084 (declare-function org-clock-update-mode-line "org-clock" ())
3085 (defvar org-clock-start-time)
3086 (defvar org-clock-marker (make-marker)
3087 "Marker recording the last clock-in.")
3088 (defun org-clock-is-active ()
3089 "Return non-nil if clock is currently running.
3090 The return value is actually the clock marker."
3091 (marker-buffer org-clock-marker))
3092
3093 (eval-and-compile
3094 (org-autoload
3095 "org-clock"
3096 '(org-clock-in org-clock-out org-clock-cancel
3097 org-clock-goto org-clock-sum org-clock-display
3098 org-clock-remove-overlays org-clock-report
3099 org-clocktable-shift org-dblock-write:clocktable
3100 org-get-clocktable)))
3101
3102 (defun org-clock-update-time-maybe ()
3103 "If this is a CLOCK line, update it and return t.
3104 Otherwise, return nil."
3105 (interactive)
3106 (save-excursion
3107 (beginning-of-line 1)
3108 (skip-chars-forward " \t")
3109 (when (looking-at org-clock-string)
3110 (let ((re (concat "[ \t]*" org-clock-string
3111 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
3112 "\\([ \t]*=>.*\\)?\\)?"))
3113 ts te h m s neg)
3114 (cond
3115 ((not (looking-at re))
3116 nil)
3117 ((not (match-end 2))
3118 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3119 (> org-clock-marker (point))
3120 (<= org-clock-marker (point-at-eol)))
3121 ;; The clock is running here
3122 (setq org-clock-start-time
3123 (apply 'encode-time
3124 (org-parse-time-string (match-string 1))))
3125 (org-clock-update-mode-line)))
3126 (t
3127 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
3128 (end-of-line 1)
3129 (setq ts (match-string 1)
3130 te (match-string 3))
3131 (setq s (- (time-to-seconds
3132 (apply 'encode-time (org-parse-time-string te)))
3133 (time-to-seconds
3134 (apply 'encode-time (org-parse-time-string ts))))
3135 neg (< s 0)
3136 s (abs s)
3137 h (floor (/ s 3600))
3138 s (- s (* 3600 h))
3139 m (floor (/ s 60))
3140 s (- s (* 60 s)))
3141 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
3142 t))))))
3143
3144 (defun org-check-running-clock ()
3145 "Check if the current buffer contains the running clock.
3146 If yes, offer to stop it and to save the buffer with the changes."
3147 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
3148 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
3149 (buffer-name))))
3150 (org-clock-out)
3151 (when (y-or-n-p "Save changed buffer?")
3152 (save-buffer))))
3153
3154 (defun org-clocktable-try-shift (dir n)
3155 "Check if this line starts a clock table, if yes, shift the time block."
3156 (when (org-match-line "#\\+BEGIN: clocktable\\>")
3157 (org-clocktable-shift dir n)))
3158
3159 ;; Autoload org-timer.el
3160
3161 (eval-and-compile
3162 (org-autoload
3163 "org-timer"
3164 '(org-timer-start org-timer org-timer-item
3165 org-timer-change-times-in-region
3166 org-timer-set-timer
3167 org-timer-reset-timers
3168 org-timer-show-remaining-time)))
3169
3170 ;; Autoload org-feed.el
3171
3172 (eval-and-compile
3173 (org-autoload
3174 "org-feed"
3175 '(org-feed-update org-feed-update-all org-feed-goto-inbox)))
3176
3177
3178 ;; Autoload org-indent.el
3179
3180 (eval-and-compile
3181 (org-autoload
3182 "org-indent"
3183 '(org-indent-mode)))
3184
3185 ;; Autoload archiving code
3186 ;; The stuff that is needed for cycling and tags has to be defined here.
3187
3188 (defgroup org-archive nil
3189 "Options concerning archiving in Org-mode."
3190 :tag "Org Archive"
3191 :group 'org-structure)
3192
3193 (defcustom org-archive-location "%s_archive::"
3194 "The location where subtrees should be archived.
3195
3196 The value of this variable is a string, consisting of two parts,
3197 separated by a double-colon. The first part is a filename and
3198 the second part is a headline.
3199
3200 When the filename is omitted, archiving happens in the same file.
3201 %s in the filename will be replaced by the current file
3202 name (without the directory part). Archiving to a different file
3203 is useful to keep archived entries from contributing to the
3204 Org-mode Agenda.
3205
3206 The archived entries will be filed as subtrees of the specified
3207 headline. When the headline is omitted, the subtrees are simply
3208 filed away at the end of the file, as top-level entries. Also in
3209 the heading you can use %s to represent the file name, this can be
3210 useful when using the same archive for a number of different files.
3211
3212 Here are a few examples:
3213 \"%s_archive::\"
3214 If the current file is Projects.org, archive in file
3215 Projects.org_archive, as top-level trees. This is the default.
3216
3217 \"::* Archived Tasks\"
3218 Archive in the current file, under the top-level headline
3219 \"* Archived Tasks\".
3220
3221 \"~/org/archive.org::\"
3222 Archive in file ~/org/archive.org (absolute path), as top-level trees.
3223
3224 \"~/org/archive.org::From %s\"
3225 Archive in file ~/org/archive.org (absolute path), und headlines
3226 \"From FILENAME\" where file name is the current file name.
3227
3228 \"basement::** Finished Tasks\"
3229 Archive in file ./basement (relative path), as level 3 trees
3230 below the level 2 heading \"** Finished Tasks\".
3231
3232 You may set this option on a per-file basis by adding to the buffer a
3233 line like
3234
3235 #+ARCHIVE: basement::** Finished Tasks
3236
3237 You may also define it locally for a subtree by setting an ARCHIVE property
3238 in the entry. If such a property is found in an entry, or anywhere up
3239 the hierarchy, it will be used."
3240 :group 'org-archive
3241 :type 'string)
3242
3243 (defcustom org-archive-tag "ARCHIVE"
3244 "The tag that marks a subtree as archived.
3245 An archived subtree does not open during visibility cycling, and does
3246 not contribute to the agenda listings.
3247 After changing this, font-lock must be restarted in the relevant buffers to
3248 get the proper fontification."
3249 :group 'org-archive
3250 :group 'org-keywords
3251 :type 'string)
3252
3253 (defcustom org-agenda-skip-archived-trees t
3254 "Non-nil means, the agenda will skip any items located in archived trees.
3255 An archived tree is a tree marked with the tag ARCHIVE. The use of this
3256 variable is no longer recommended, you should leave it at the value t.
3257 Instead, use the key `v' to cycle the archives-mode in the agenda."
3258 :group 'org-archive
3259 :group 'org-agenda-skip
3260 :type 'boolean)
3261
3262 (defcustom org-columns-skip-arrchived-trees t
3263 "Non-nil means, irgnore archived trees when creating column view."
3264 :group 'org-archive
3265 :group 'org-properties
3266 :type 'boolean)
3267
3268 (defcustom org-cycle-open-archived-trees nil
3269 "Non-nil means, `org-cycle' will open archived trees.
3270 An archived tree is a tree marked with the tag ARCHIVE.
3271 When nil, archived trees will stay folded. You can still open them with
3272 normal outline commands like `show-all', but not with the cycling commands."
3273 :group 'org-archive
3274 :group 'org-cycle
3275 :type 'boolean)
3276
3277 (defcustom org-sparse-tree-open-archived-trees nil
3278 "Non-nil means sparse tree construction shows matches in archived trees.
3279 When nil, matches in these trees are highlighted, but the trees are kept in
3280 collapsed state."
3281 :group 'org-archive
3282 :group 'org-sparse-trees
3283 :type 'boolean)
3284
3285 (defun org-cycle-hide-archived-subtrees (state)
3286 "Re-hide all archived subtrees after a visibility state change."
3287 (when (and (not org-cycle-open-archived-trees)
3288 (not (memq state '(overview folded))))
3289 (save-excursion
3290 (let* ((globalp (memq state '(contents all)))
3291 (beg (if globalp (point-min) (point)))
3292 (end (if globalp (point-max) (org-end-of-subtree t))))
3293 (org-hide-archived-subtrees beg end)
3294 (goto-char beg)
3295 (if (looking-at (concat ".*:" org-archive-tag ":"))
3296 (message "%s" (substitute-command-keys
3297 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
3298
3299 (defun org-force-cycle-archived ()
3300 "Cycle subtree even if it is archived."
3301 (interactive)
3302 (setq this-command 'org-cycle)
3303 (let ((org-cycle-open-archived-trees t))
3304 (call-interactively 'org-cycle)))
3305
3306 (defun org-hide-archived-subtrees (beg end)
3307 "Re-hide all archived subtrees after a visibility state change."
3308 (save-excursion
3309 (let* ((re (concat ":" org-archive-tag ":")))
3310 (goto-char beg)
3311 (while (re-search-forward re end t)
3312 (and (org-on-heading-p) (hide-subtree))
3313 (org-end-of-subtree t)))))
3314
3315 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
3316
3317 (eval-and-compile
3318 (org-autoload "org-archive"
3319 '(org-add-archive-files org-archive-subtree
3320 org-archive-to-archive-sibling org-toggle-archive-tag)))
3321
3322 ;; Autoload Column View Code
3323
3324 (declare-function org-columns-number-to-string "org-colview")
3325 (declare-function org-columns-get-format-and-top-level "org-colview")
3326 (declare-function org-columns-compute "org-colview")
3327
3328 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3329 '(org-columns-number-to-string org-columns-get-format-and-top-level
3330 org-columns-compute org-agenda-columns org-columns-remove-overlays
3331 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3332
3333 ;; Autoload ID code
3334
3335 (declare-function org-id-store-link "org-id")
3336 (declare-function org-id-locations-load "org-id")
3337 (declare-function org-id-locations-save "org-id")
3338 (defvar org-id-track-globally)
3339 (org-autoload "org-id"
3340 '(org-id-get-create org-id-new org-id-copy org-id-get
3341 org-id-get-with-outline-path-completion
3342 org-id-get-with-outline-drilling
3343 org-id-goto org-id-find org-id-store-link))
3344
3345 ;; Autoload Plotting Code
3346
3347 (org-autoload "org-plot"
3348 '(org-plot/gnuplot))
3349
3350 ;;; Variables for pre-computed regular expressions, all buffer local
3351
3352 (defvar org-drawer-regexp nil
3353 "Matches first line of a hidden block.")
3354 (make-variable-buffer-local 'org-drawer-regexp)
3355 (defvar org-todo-regexp nil
3356 "Matches any of the TODO state keywords.")
3357 (make-variable-buffer-local 'org-todo-regexp)
3358 (defvar org-not-done-regexp nil
3359 "Matches any of the TODO state keywords except the last one.")
3360 (make-variable-buffer-local 'org-not-done-regexp)
3361 (defvar org-not-done-heading-regexp nil
3362 "Matches a TODO headline that is not done.")
3363 (make-variable-buffer-local 'org-not-done-regexp)
3364 (defvar org-todo-line-regexp nil
3365 "Matches a headline and puts TODO state into group 2 if present.")
3366 (make-variable-buffer-local 'org-todo-line-regexp)
3367 (defvar org-complex-heading-regexp nil
3368 "Matches a headline and puts everything into groups:
3369 group 1: the stars
3370 group 2: The todo keyword, maybe
3371 group 3: Priority cookie
3372 group 4: True headline
3373 group 5: Tags")
3374 (make-variable-buffer-local 'org-complex-heading-regexp)
3375 (defvar org-todo-line-tags-regexp nil
3376 "Matches a headline and puts TODO state into group 2 if present.
3377 Also put tags into group 4 if tags are present.")
3378 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3379 (defvar org-nl-done-regexp nil
3380 "Matches newline followed by a headline with the DONE keyword.")
3381 (make-variable-buffer-local 'org-nl-done-regexp)
3382 (defvar org-looking-at-done-regexp nil
3383 "Matches the DONE keyword a point.")
3384 (make-variable-buffer-local 'org-looking-at-done-regexp)
3385 (defvar org-ds-keyword-length 12
3386 "Maximum length of the Deadline and SCHEDULED keywords.")
3387 (make-variable-buffer-local 'org-ds-keyword-length)
3388 (defvar org-deadline-regexp nil
3389 "Matches the DEADLINE keyword.")
3390 (make-variable-buffer-local 'org-deadline-regexp)
3391 (defvar org-deadline-time-regexp nil
3392 "Matches the DEADLINE keyword together with a time stamp.")
3393 (make-variable-buffer-local 'org-deadline-time-regexp)
3394 (defvar org-deadline-line-regexp nil
3395 "Matches the DEADLINE keyword and the rest of the line.")
3396 (make-variable-buffer-local 'org-deadline-line-regexp)
3397 (defvar org-scheduled-regexp nil
3398 "Matches the SCHEDULED keyword.")
3399 (make-variable-buffer-local 'org-scheduled-regexp)
3400 (defvar org-scheduled-time-regexp nil
3401 "Matches the SCHEDULED keyword together with a time stamp.")
3402 (make-variable-buffer-local 'org-scheduled-time-regexp)
3403 (defvar org-closed-time-regexp nil
3404 "Matches the CLOSED keyword together with a time stamp.")
3405 (make-variable-buffer-local 'org-closed-time-regexp)
3406
3407 (defvar org-keyword-time-regexp nil
3408 "Matches any of the 4 keywords, together with the time stamp.")
3409 (make-variable-buffer-local 'org-keyword-time-regexp)
3410 (defvar org-keyword-time-not-clock-regexp nil
3411 "Matches any of the 3 keywords, together with the time stamp.")
3412 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3413 (defvar org-maybe-keyword-time-regexp nil
3414 "Matches a timestamp, possibly preceeded by a keyword.")
3415 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3416 (defvar org-planning-or-clock-line-re nil
3417 "Matches a line with planning or clock info.")
3418 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3419
3420 (defconst org-plain-time-of-day-regexp
3421 (concat
3422 "\\(\\<[012]?[0-9]"
3423 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3424 "\\(--?"
3425 "\\(\\<[012]?[0-9]"
3426 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3427 "\\)?")
3428 "Regular expression to match a plain time or time range.
3429 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3430 groups carry important information:
3431 0 the full match
3432 1 the first time, range or not
3433 8 the second time, if it is a range.")
3434
3435 (defconst org-plain-time-extension-regexp
3436 (concat
3437 "\\(\\<[012]?[0-9]"
3438 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3439 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3440 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3441 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3442 groups carry important information:
3443 0 the full match
3444 7 hours of duration
3445 9 minutes of duration")
3446
3447 (defconst org-stamp-time-of-day-regexp
3448 (concat
3449 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3450 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3451 "\\(--?"
3452 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3453 "Regular expression to match a timestamp time or time range.
3454 After a match, the following groups carry important information:
3455 0 the full match
3456 1 date plus weekday, for backreferencing to make sure both times on same day
3457 2 the first time, range or not
3458 4 the second time, if it is a range.")
3459
3460 (defconst org-startup-options
3461 '(("fold" org-startup-folded t)
3462 ("overview" org-startup-folded t)
3463 ("nofold" org-startup-folded nil)
3464 ("showall" org-startup-folded nil)
3465 ("content" org-startup-folded content)
3466 ("indent" org-startup-indented t)
3467 ("noindent" org-startup-indented nil)
3468 ("hidestars" org-hide-leading-stars t)
3469 ("showstars" org-hide-leading-stars nil)
3470 ("odd" org-odd-levels-only t)
3471 ("oddeven" org-odd-levels-only nil)
3472 ("align" org-startup-align-all-tables t)
3473 ("noalign" org-startup-align-all-tables nil)
3474 ("customtime" org-display-custom-times t)
3475 ("logdone" org-log-done time)
3476 ("lognotedone" org-log-done note)
3477 ("nologdone" org-log-done nil)
3478 ("lognoteclock-out" org-log-note-clock-out t)
3479 ("nolognoteclock-out" org-log-note-clock-out nil)
3480 ("logrepeat" org-log-repeat state)
3481 ("lognoterepeat" org-log-repeat note)
3482 ("nologrepeat" org-log-repeat nil)
3483 ("fninline" org-footnote-define-inline t)
3484 ("nofninline" org-footnote-define-inline nil)
3485 ("fnlocal" org-footnote-section nil)
3486 ("fnauto" org-footnote-auto-label t)
3487 ("fnprompt" org-footnote-auto-label nil)
3488 ("fnconfirm" org-footnote-auto-label confirm)
3489 ("fnplain" org-footnote-auto-label plain)
3490 ("fnadjust" org-footnote-auto-adjust t)
3491 ("nofnadjust" org-footnote-auto-adjust nil)
3492 ("constcgs" constants-unit-system cgs)
3493 ("constSI" constants-unit-system SI)
3494 ("noptag" org-tag-persistent-alist nil)
3495 ("hideblocks" org-hide-block-startup t)
3496 ("nohideblocks" org-hide-block-startup nil))
3497 "Variable associated with STARTUP options for org-mode.
3498 Each element is a list of three items: The startup options as written
3499 in the #+STARTUP line, the corresponding variable, and the value to
3500 set this variable to if the option is found. An optional forth element PUSH
3501 means to push this value onto the list in the variable.")
3502
3503 (defun org-set-regexps-and-options ()
3504 "Precompute regular expressions for current buffer."
3505 (when (org-mode-p)
3506 (org-set-local 'org-todo-kwd-alist nil)
3507 (org-set-local 'org-todo-key-alist nil)
3508 (org-set-local 'org-todo-key-trigger nil)
3509 (org-set-local 'org-todo-keywords-1 nil)
3510 (org-set-local 'org-done-keywords nil)
3511 (org-set-local 'org-todo-heads nil)
3512 (org-set-local 'org-todo-sets nil)
3513 (org-set-local 'org-todo-log-states nil)
3514 (org-set-local 'org-file-properties nil)
3515 (org-set-local 'org-file-tags nil)
3516 (let ((re (org-make-options-regexp
3517 '("CATEGORY" "TODO" "COLUMNS"
3518 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3519 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")
3520 "\\(?:[a-zA-Z][0-9a-zA-Z_]*_TODO\\)"))
3521 (splitre "[ \t]+")
3522 kwds kws0 kwsa key log value cat arch tags const links hw dws
3523 tail sep kws1 prio props ftags drawers
3524 ext-setup-or-nil setup-contents (start 0))
3525 (save-excursion
3526 (save-restriction
3527 (widen)
3528 (goto-char (point-min))
3529 (while (or (and ext-setup-or-nil
3530 (string-match re ext-setup-or-nil start)
3531 (setq start (match-end 0)))
3532 (and (setq ext-setup-or-nil nil start 0)
3533 (re-search-forward re nil t)))
3534 (setq key (upcase (match-string 1 ext-setup-or-nil))
3535 value (org-match-string-no-properties 2 ext-setup-or-nil))
3536 (cond
3537 ((equal key "CATEGORY")
3538 (if (string-match "[ \t]+$" value)
3539 (setq value (replace-match "" t t value)))
3540 (setq cat value))
3541 ((member key '("SEQ_TODO" "TODO"))
3542 (push (cons 'sequence (org-split-string value splitre)) kwds))
3543 ((equal key "TYP_TODO")
3544 (push (cons 'type (org-split-string value splitre)) kwds))
3545 ((string-match "\\`\\([a-zA-Z][0-9a-zA-Z_]*\\)_TODO\\'" key)
3546 ;; general TODO-like setup
3547 (push (cons (intern (downcase (match-string 1 key)))
3548 (org-split-string value splitre)) kwds))
3549 ((equal key "TAGS")
3550 (setq tags (append tags (if tags '("\\n") nil)
3551 (org-split-string value splitre))))
3552 ((equal key "COLUMNS")
3553 (org-set-local 'org-columns-default-format value))
3554 ((equal key "LINK")
3555 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3556 (push (cons (match-string 1 value)
3557 (org-trim (match-string 2 value)))
3558 links)))
3559 ((equal key "PRIORITIES")
3560 (setq prio (org-split-string value " +")))
3561 ((equal key "PROPERTY")
3562 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3563 (push (cons (match-string 1 value) (match-string 2 value))
3564 props)))
3565 ((equal key "FILETAGS")
3566 (when (string-match "\\S-" value)
3567 (setq ftags
3568 (append
3569 ftags
3570 (apply 'append
3571 (mapcar (lambda (x) (org-split-string x ":"))
3572 (org-split-string value)))))))
3573 ((equal key "DRAWERS")
3574 (setq drawers (org-split-string value splitre)))
3575 ((equal key "CONSTANTS")
3576 (setq const (append const (org-split-string value splitre))))
3577 ((equal key "STARTUP")
3578 (let ((opts (org-split-string value splitre))
3579 l var val)
3580 (while (setq l (pop opts))
3581 (when (setq l (assoc l org-startup-options))
3582 (setq var (nth 1 l) val (nth 2 l))
3583 (if (not (nth 3 l))
3584 (set (make-local-variable var) val)
3585 (if (not (listp (symbol-value var)))
3586 (set (make-local-variable var) nil))
3587 (set (make-local-variable var) (symbol-value var))
3588 (add-to-list var val))))))
3589 ((equal key "ARCHIVE")
3590 (string-match " *$" value)
3591 (setq arch (replace-match "" t t value))
3592 (remove-text-properties 0 (length arch)
3593 '(face t fontified t) arch))
3594 ((equal key "SETUPFILE")
3595 (setq setup-contents (org-file-contents
3596 (expand-file-name
3597 (org-remove-double-quotes value))
3598 'noerror))
3599 (if (not ext-setup-or-nil)
3600 (setq ext-setup-or-nil setup-contents start 0)
3601 (setq ext-setup-or-nil
3602 (concat (substring ext-setup-or-nil 0 start)
3603 "\n" setup-contents "\n"
3604 (substring ext-setup-or-nil start)))))
3605 ))))
3606 (when cat
3607 (org-set-local 'org-category (intern cat))
3608 (push (cons "CATEGORY" cat) props))
3609 (when prio
3610 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3611 (setq prio (mapcar 'string-to-char prio))
3612 (org-set-local 'org-highest-priority (nth 0 prio))
3613 (org-set-local 'org-lowest-priority (nth 1 prio))
3614 (org-set-local 'org-default-priority (nth 2 prio)))
3615 (and props (org-set-local 'org-file-properties (nreverse props)))
3616 (and ftags (org-set-local 'org-file-tags
3617 (mapcar 'org-add-prop-inherited ftags)))
3618 (and drawers (org-set-local 'org-drawers drawers))
3619 (and arch (org-set-local 'org-archive-location arch))
3620 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3621 ;; Process the TODO keywords
3622 (unless kwds
3623 ;; Use the global values as if they had been given locally.
3624 (setq kwds (default-value 'org-todo-keywords))
3625 (if (stringp (car kwds))
3626 (setq kwds (list (cons org-todo-interpretation
3627 (default-value 'org-todo-keywords)))))
3628 (setq kwds (reverse kwds)))
3629 (setq kwds (nreverse kwds))
3630 (let (inter kws kw)
3631 (while (setq kws (pop kwds))
3632 (let ((kws (or
3633 (run-hook-with-args-until-success
3634 'org-todo-setup-filter-hook kws)
3635 kws)))
3636 (setq inter (pop kws) sep (member "|" kws)
3637 kws0 (delete "|" (copy-sequence kws))
3638 kwsa nil
3639 kws1 (mapcar
3640 (lambda (x)
3641 ;; 1 2
3642 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3643 (progn
3644 (setq kw (match-string 1 x)
3645 key (and (match-end 2) (match-string 2 x))
3646 log (org-extract-log-state-settings x))
3647 (push (cons kw (and key (string-to-char key))) kwsa)
3648 (and log (push log org-todo-log-states))
3649 kw)
3650 (error "Invalid TODO keyword %s" x)))
3651 kws0)
3652 kwsa (if kwsa (append '((:startgroup))
3653 (nreverse kwsa)
3654 '((:endgroup))))
3655 hw (car kws1)
3656 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3657 tail (list inter hw (car dws) (org-last dws))))
3658 (add-to-list 'org-todo-heads hw 'append)
3659 (push kws1 org-todo-sets)
3660 (setq org-done-keywords (append org-done-keywords dws nil))
3661 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3662 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3663 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3664 (setq org-todo-sets (nreverse org-todo-sets)
3665 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3666 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3667 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3668 ;; Process the constants
3669 (when const
3670 (let (e cst)
3671 (while (setq e (pop const))
3672 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3673 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3674 (setq org-table-formula-constants-local cst)))
3675
3676 ;; Process the tags.
3677 (when tags
3678 (let (e tgs)
3679 (while (setq e (pop tags))
3680 (cond
3681 ((equal e "{") (push '(:startgroup) tgs))
3682 ((equal e "}") (push '(:endgroup) tgs))
3683 ((equal e "\\n") (push '(:newline) tgs))
3684 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3685 (push (cons (match-string 1 e)
3686 (string-to-char (match-string 2 e)))
3687 tgs))
3688 (t (push (list e) tgs))))
3689 (org-set-local 'org-tag-alist nil)
3690 (while (setq e (pop tgs))
3691 (or (and (stringp (car e))
3692 (assoc (car e) org-tag-alist))
3693 (push e org-tag-alist)))))
3694
3695 ;; Compute the regular expressions and other local variables
3696 (if (not org-done-keywords)
3697 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3698 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3699 (length org-scheduled-string)
3700 (length org-clock-string)
3701 (length org-closed-string)))
3702 org-drawer-regexp
3703 (concat "^[ \t]*:\\("
3704 (mapconcat 'regexp-quote org-drawers "\\|")
3705 "\\):[ \t]*$")
3706 org-not-done-keywords
3707 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3708 org-todo-regexp
3709 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3710 "\\|") "\\)\\>")
3711 org-not-done-regexp
3712 (concat "\\<\\("
3713 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3714 "\\)\\>")
3715 org-not-done-heading-regexp
3716 (concat "^\\(\\*+\\)[ \t]+\\("
3717 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3718 "\\)\\>")
3719 org-todo-line-regexp
3720 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3721 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3722 "\\)\\>\\)?[ \t]*\\(.*\\)")
3723 org-complex-heading-regexp
3724 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3725 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3726 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3727 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3728 org-nl-done-regexp
3729 (concat "\n\\*+[ \t]+"
3730 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3731 "\\)" "\\>")
3732 org-todo-line-tags-regexp
3733 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3734 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3735 (org-re
3736 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3737 org-looking-at-done-regexp
3738 (concat "^" "\\(?:"
3739 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3740 "\\>")
3741 org-deadline-regexp (concat "\\<" org-deadline-string)
3742 org-deadline-time-regexp
3743 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3744 org-deadline-line-regexp
3745 (concat "\\<\\(" org-deadline-string "\\).*")
3746 org-scheduled-regexp
3747 (concat "\\<" org-scheduled-string)
3748 org-scheduled-time-regexp
3749 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3750 org-closed-time-regexp
3751 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3752 org-keyword-time-regexp
3753 (concat "\\<\\(" org-scheduled-string
3754 "\\|" org-deadline-string
3755 "\\|" org-closed-string
3756 "\\|" org-clock-string "\\)"
3757 " *[[<]\\([^]>]+\\)[]>]")
3758 org-keyword-time-not-clock-regexp
3759 (concat "\\<\\(" org-scheduled-string
3760 "\\|" org-deadline-string
3761 "\\|" org-closed-string
3762 "\\)"
3763 " *[[<]\\([^]>]+\\)[]>]")
3764 org-maybe-keyword-time-regexp
3765 (concat "\\(\\<\\(" org-scheduled-string
3766 "\\|" org-deadline-string
3767 "\\|" org-closed-string
3768 "\\|" org-clock-string "\\)\\)?"
3769 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3770 org-planning-or-clock-line-re
3771 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3772 "\\|" org-deadline-string
3773 "\\|" org-closed-string "\\|" org-clock-string
3774 "\\)\\>\\)")
3775 )
3776 (org-compute-latex-and-specials-regexp)
3777 (org-set-font-lock-defaults))))
3778
3779 (defun org-file-contents (file &optional noerror)
3780 "Return the contents of FILE, as a string."
3781 (if (or (not file)
3782 (not (file-readable-p file)))
3783 (if noerror
3784 (progn
3785 (message "Cannot read file %s" file)
3786 (ding) (sit-for 2)
3787 "")
3788 (error "Cannot read file %s" file))
3789 (with-temp-buffer
3790 (insert-file-contents file)
3791 (buffer-string))))
3792
3793 (defun org-extract-log-state-settings (x)
3794 "Extract the log state setting from a TODO keyword string.
3795 This will extract info from a string like \"WAIT(w@/!)\"."
3796 (let (kw key log1 log2)
3797 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3798 (setq kw (match-string 1 x)
3799 key (and (match-end 2) (match-string 2 x))
3800 log1 (and (match-end 3) (match-string 3 x))
3801 log2 (and (match-end 4) (match-string 4 x)))
3802 (and (or log1 log2)
3803 (list kw
3804 (and log1 (if (equal log1 "!") 'time 'note))
3805 (and log2 (if (equal log2 "!") 'time 'note)))))))
3806
3807 (defun org-remove-keyword-keys (list)
3808 "Remove a pair of parenthesis at the end of each string in LIST."
3809 (mapcar (lambda (x)
3810 (if (string-match "(.*)$" x)
3811 (substring x 0 (match-beginning 0))
3812 x))
3813 list))
3814
3815 ;; FIXME: this could be done much better, using second characters etc.
3816 (defun org-assign-fast-keys (alist)
3817 "Assign fast keys to a keyword-key alist.
3818 Respect keys that are already there."
3819 (let (new e k c c1 c2 (char ?a))
3820 (while (setq e (pop alist))
3821 (cond
3822 ((equal e '(:startgroup)) (push e new))
3823 ((equal e '(:endgroup)) (push e new))
3824 ((equal e '(:newline)) (push e new))
3825 (t
3826 (setq k (car e) c2 nil)
3827 (if (cdr e)
3828 (setq c (cdr e))
3829 ;; automatically assign a character.
3830 (setq c1 (string-to-char
3831 (downcase (substring
3832 k (if (= (string-to-char k) ?@) 1 0)))))
3833 (if (or (rassoc c1 new) (rassoc c1 alist))
3834 (while (or (rassoc char new) (rassoc char alist))
3835 (setq char (1+ char)))
3836 (setq c2 c1))
3837 (setq c (or c2 char)))
3838 (push (cons k c) new))))
3839 (nreverse new)))
3840
3841 ;;; Some variables used in various places
3842
3843 (defvar org-window-configuration nil
3844 "Used in various places to store a window configuration.")
3845 (defvar org-finish-function nil
3846 "Function to be called when `C-c C-c' is used.
3847 This is for getting out of special buffers like remember.")
3848
3849
3850 ;; FIXME: Occasionally check by commenting these, to make sure
3851 ;; no other functions uses these, forgetting to let-bind them.
3852 (defvar entry)
3853 (defvar last-state)
3854 (defvar date)
3855
3856 ;; Defined somewhere in this file, but used before definition.
3857 (defvar org-html-entities)
3858 (defvar org-struct-menu)
3859 (defvar org-org-menu)
3860 (defvar org-tbl-menu)
3861 (defvar org-agenda-keymap)
3862
3863 ;;;; Define the Org-mode
3864
3865 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3866 (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."))
3867
3868
3869 ;; We use a before-change function to check if a table might need
3870 ;; an update.
3871 (defvar org-table-may-need-update t
3872 "Indicates that a table might need an update.
3873 This variable is set by `org-before-change-function'.
3874 `org-table-align' sets it back to nil.")
3875 (defun org-before-change-function (beg end)
3876 "Every change indicates that a table might need an update."
3877 (setq org-table-may-need-update t))
3878 (defvar org-mode-map)
3879 (defvar org-mode-hook nil
3880 "Mode hook for Org-mode, run after the mode was turned on.")
3881 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3882 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3883 (defvar org-inhibit-logging nil) ; Dynamically-scoped param.
3884 (defvar org-inhibit-blocking nil) ; Dynamically-scoped param.
3885 (defvar org-table-buffer-is-an nil)
3886 (defconst org-outline-regexp "\\*+ ")
3887
3888 ;;;###autoload
3889 (define-derived-mode org-mode outline-mode "Org"
3890 "Outline-based notes management and organizer, alias
3891 \"Carsten's outline-mode for keeping track of everything.\"
3892
3893 Org-mode develops organizational tasks around a NOTES file which
3894 contains information about projects as plain text. Org-mode is
3895 implemented on top of outline-mode, which is ideal to keep the content
3896 of large files well structured. It supports ToDo items, deadlines and
3897 time stamps, which magically appear in the diary listing of the Emacs
3898 calendar. Tables are easily created with a built-in table editor.
3899 Plain text URL-like links connect to websites, emails (VM), Usenet
3900 messages (Gnus), BBDB entries, and any files related to the project.
3901 For printing and sharing of notes, an Org-mode file (or a part of it)
3902 can be exported as a structured ASCII or HTML file.
3903
3904 The following commands are available:
3905
3906 \\{org-mode-map}"
3907
3908 ;; Get rid of Outline menus, they are not needed
3909 ;; Need to do this here because define-derived-mode sets up
3910 ;; the keymap so late. Still, it is a waste to call this each time
3911 ;; we switch another buffer into org-mode.
3912 (if (featurep 'xemacs)
3913 (when (boundp 'outline-mode-menu-heading)
3914 ;; Assume this is Greg's port, it used easymenu
3915 (easy-menu-remove outline-mode-menu-heading)
3916 (easy-menu-remove outline-mode-menu-show)
3917 (easy-menu-remove outline-mode-menu-hide))
3918 (define-key org-mode-map [menu-bar headings] 'undefined)
3919 (define-key org-mode-map [menu-bar hide] 'undefined)
3920 (define-key org-mode-map [menu-bar show] 'undefined))
3921
3922 (org-load-modules-maybe)
3923 (easy-menu-add org-org-menu)
3924 (easy-menu-add org-tbl-menu)
3925 (org-install-agenda-files-menu)
3926 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3927 (org-add-to-invisibility-spec '(org-cwidth))
3928 (org-add-to-invisibility-spec '(org-hide-block . t))
3929 (when (featurep 'xemacs)
3930 (org-set-local 'line-move-ignore-invisible t))
3931 (org-set-local 'outline-regexp org-outline-regexp)
3932 (org-set-local 'outline-level 'org-outline-level)
3933 (when (and org-ellipsis
3934 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3935 (fboundp 'make-glyph-code))
3936 (unless org-display-table
3937 (setq org-display-table (make-display-table)))
3938 (set-display-table-slot
3939 org-display-table 4
3940 (vconcat (mapcar
3941 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3942 org-ellipsis)))
3943 (if (stringp org-ellipsis) org-ellipsis "..."))))
3944 (setq buffer-display-table org-display-table))
3945 (org-set-regexps-and-options)
3946 (when (and org-tag-faces (not org-tags-special-faces-re))
3947 ;; tag faces set outside customize.... force initialization.
3948 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3949 ;; Calc embedded
3950 (org-set-local 'calc-embedded-open-mode "# ")
3951 (modify-syntax-entry ?# "<")
3952 (modify-syntax-entry ?@ "w")
3953 (if org-startup-truncated (setq truncate-lines t))
3954 (org-set-local 'font-lock-unfontify-region-function
3955 'org-unfontify-region)
3956 ;; Activate before-change-function
3957 (org-set-local 'org-table-may-need-update t)
3958 (org-add-hook 'before-change-functions 'org-before-change-function nil
3959 'local)
3960 ;; Check for running clock before killing a buffer
3961 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3962 ;; Paragraphs and auto-filling
3963 (org-set-autofill-regexps)
3964 (setq indent-line-function 'org-indent-line-function)
3965 (org-update-radio-target-regexp)
3966 ;; Make sure dependence stuff works reliably, even for users who set it
3967 ;; too late :-(
3968 (if org-enforce-todo-dependencies
3969 (add-hook 'org-blocker-hook
3970 'org-block-todo-from-children-or-siblings-or-parent)
3971 (remove-hook 'org-blocker-hook
3972 'org-block-todo-from-children-or-siblings-or-parent))
3973 (if org-enforce-todo-checkbox-dependencies
3974 (add-hook 'org-blocker-hook
3975 'org-block-todo-from-checkboxes)
3976 (remove-hook 'org-blocker-hook
3977 'org-block-todo-from-checkboxes))
3978
3979 ;; Comment characters
3980 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3981 (org-set-local 'comment-padding " ")
3982
3983 ;; Align options lines
3984 (org-set-local
3985 'align-mode-rules-list
3986 '((org-in-buffer-settings
3987 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3988 (modes . '(org-mode)))))
3989
3990 ;; Imenu
3991 (org-set-local 'imenu-create-index-function
3992 'org-imenu-get-tree)
3993
3994 ;; Make isearch reveal context
3995 (if (or (featurep 'xemacs)
3996 (not (boundp 'outline-isearch-open-invisible-function)))
3997 ;; Emacs 21 and XEmacs make use of the hook
3998 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3999 ;; Emacs 22 deals with this through a special variable
4000 (org-set-local 'outline-isearch-open-invisible-function
4001 (lambda (&rest ignore) (org-show-context 'isearch))))
4002
4003 ;; If empty file that did not turn on org-mode automatically, make it to.
4004 (if (and org-insert-mode-line-in-empty-file
4005 (interactive-p)
4006 (= (point-min) (point-max)))
4007 (insert "# -*- mode: org -*-\n\n"))
4008
4009 (unless org-inhibit-startup
4010 (when org-startup-align-all-tables
4011 (let ((bmp (buffer-modified-p)))
4012 (org-table-map-tables 'org-table-align)
4013 (set-buffer-modified-p bmp)))
4014 (when org-startup-indented
4015 (require 'org-indent)
4016 (org-indent-mode 1))
4017 (org-set-startup-visibility)))
4018
4019 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
4020
4021 (defun org-current-time ()
4022 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
4023 (if (> (car org-time-stamp-rounding-minutes) 1)
4024 (let ((r (car org-time-stamp-rounding-minutes))
4025 (time (decode-time)))
4026 (apply 'encode-time
4027 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
4028 (nthcdr 2 time))))
4029 (current-time)))
4030
4031 ;;;; Font-Lock stuff, including the activators
4032
4033 (defvar org-mouse-map (make-sparse-keymap))
4034 (org-defkey org-mouse-map
4035 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
4036 (org-defkey org-mouse-map
4037 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
4038 (when org-mouse-1-follows-link
4039 (org-defkey org-mouse-map [follow-link] 'mouse-face))
4040 (when org-tab-follows-link
4041 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
4042 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
4043
4044 (require 'font-lock)
4045
4046 (defconst org-non-link-chars "]\t\n\r<>")
4047 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
4048 "shell" "elisp"))
4049 (defvar org-link-types-re nil
4050 "Matches a link that has a url-like prefix like \"http:\"")
4051 (defvar org-link-re-with-space nil
4052 "Matches a link with spaces, optional angular brackets around it.")
4053 (defvar org-link-re-with-space2 nil
4054 "Matches a link with spaces, optional angular brackets around it.")
4055 (defvar org-link-re-with-space3 nil
4056 "Matches a link with spaces, only for internal part in bracket links.")
4057 (defvar org-angle-link-re nil
4058 "Matches link with angular brackets, spaces are allowed.")
4059 (defvar org-plain-link-re nil
4060 "Matches plain link, without spaces.")
4061 (defvar org-bracket-link-regexp nil
4062 "Matches a link in double brackets.")
4063 (defvar org-bracket-link-analytic-regexp nil
4064 "Regular expression used to analyze links.
4065 Here is what the match groups contain after a match:
4066 1: http:
4067 2: http
4068 3: path
4069 4: [desc]
4070 5: desc")
4071 (defvar org-bracket-link-analytic-regexp++ nil
4072 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
4073 (defvar org-any-link-re nil
4074 "Regular expression matching any link.")
4075
4076 (defun org-make-link-regexps ()
4077 "Update the link regular expressions.
4078 This should be called after the variable `org-link-types' has changed."
4079 (setq org-link-types-re
4080 (concat
4081 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
4082 org-link-re-with-space
4083 (concat
4084 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4085 "\\([^" org-non-link-chars " ]"
4086 "[^" org-non-link-chars "]*"
4087 "[^" org-non-link-chars " ]\\)>?")
4088 org-link-re-with-space2
4089 (concat
4090 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4091 "\\([^" org-non-link-chars " ]"
4092 "[^\t\n\r]*"
4093 "[^" org-non-link-chars " ]\\)>?")
4094 org-link-re-with-space3
4095 (concat
4096 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4097 "\\([^" org-non-link-chars " ]"
4098 "[^\t\n\r]*\\)")
4099 org-angle-link-re
4100 (concat
4101 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4102 "\\([^" org-non-link-chars " ]"
4103 "[^" org-non-link-chars "]*"
4104 "\\)>")
4105 org-plain-link-re
4106 (concat
4107 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
4108 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
4109 org-bracket-link-regexp
4110 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
4111 org-bracket-link-analytic-regexp
4112 (concat
4113 "\\[\\["
4114 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
4115 "\\([^]]+\\)"
4116 "\\]"
4117 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4118 "\\]")
4119 org-bracket-link-analytic-regexp++
4120 (concat
4121 "\\[\\["
4122 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
4123 "\\([^]]+\\)"
4124 "\\]"
4125 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
4126 "\\]")
4127 org-any-link-re
4128 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
4129 org-angle-link-re "\\)\\|\\("
4130 org-plain-link-re "\\)")))
4131
4132 (org-make-link-regexps)
4133
4134 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
4135 "Regular expression for fast time stamp matching.")
4136 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
4137 "Regular expression for fast time stamp matching.")
4138 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4139 "Regular expression matching time strings for analysis.
4140 This one does not require the space after the date, so it can be used
4141 on a string that terminates immediately after the date.")
4142 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
4143 "Regular expression matching time strings for analysis.")
4144 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
4145 "Regular expression matching time stamps, with groups.")
4146 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
4147 "Regular expression matching time stamps (also [..]), with groups.")
4148 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
4149 "Regular expression matching a time stamp range.")
4150 (defconst org-tr-regexp-both
4151 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
4152 "Regular expression matching a time stamp range.")
4153 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
4154 org-ts-regexp "\\)?")
4155 "Regular expression matching a time stamp or time stamp range.")
4156 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
4157 org-ts-regexp-both "\\)?")
4158 "Regular expression matching a time stamp or time stamp range.
4159 The time stamps may be either active or inactive.")
4160
4161 (defvar org-emph-face nil)
4162
4163 (defun org-do-emphasis-faces (limit)
4164 "Run through the buffer and add overlays to links."
4165 (let (rtn a)
4166 (while (and (not rtn) (re-search-forward org-emph-re limit t))
4167 (if (not (= (char-after (match-beginning 3))
4168 (char-after (match-beginning 4))))
4169 (progn
4170 (setq rtn t)
4171 (setq a (assoc (match-string 3) org-emphasis-alist))
4172 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
4173 'face
4174 (nth 1 a))
4175 (and (nth 4 a)
4176 (org-remove-flyspell-overlays-in
4177 (match-beginning 0) (match-end 0)))
4178 (add-text-properties (match-beginning 2) (match-end 2)
4179 '(font-lock-multiline t))
4180 (when org-hide-emphasis-markers
4181 (add-text-properties (match-end 4) (match-beginning 5)
4182 '(invisible org-link))
4183 (add-text-properties (match-beginning 3) (match-end 3)
4184 '(invisible org-link)))))
4185 (backward-char 1))
4186 rtn))
4187
4188 (defun org-emphasize (&optional char)
4189 "Insert or change an emphasis, i.e. a font like bold or italic.
4190 If there is an active region, change that region to a new emphasis.
4191 If there is no region, just insert the marker characters and position
4192 the cursor between them.
4193 CHAR should be either the marker character, or the first character of the
4194 HTML tag associated with that emphasis. If CHAR is a space, the means
4195 to remove the emphasis of the selected region.
4196 If char is not given (for example in an interactive call) it
4197 will be prompted for."
4198 (interactive)
4199 (let ((eal org-emphasis-alist) e det
4200 (erc org-emphasis-regexp-components)
4201 (prompt "")
4202 (string "") beg end move tag c s)
4203 (if (org-region-active-p)
4204 (setq beg (region-beginning) end (region-end)
4205 string (buffer-substring beg end))
4206 (setq move t))
4207
4208 (while (setq e (pop eal))
4209 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
4210 c (aref tag 0))
4211 (push (cons c (string-to-char (car e))) det)
4212 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
4213 (substring tag 1)))))
4214 (setq det (nreverse det))
4215 (unless char
4216 (message "%s" (concat "Emphasis marker or tag:" prompt))
4217 (setq char (read-char-exclusive)))
4218 (setq char (or (cdr (assoc char det)) char))
4219 (if (equal char ?\ )
4220 (setq s "" move nil)
4221 (unless (assoc (char-to-string char) org-emphasis-alist)
4222 (error "No such emphasis marker: \"%c\"" char))
4223 (setq s (char-to-string char)))
4224 (while (and (> (length string) 1)
4225 (equal (substring string 0 1) (substring string -1))
4226 (assoc (substring string 0 1) org-emphasis-alist))
4227 (setq string (substring string 1 -1)))
4228 (setq string (concat s string s))
4229 (if beg (delete-region beg end))
4230 (unless (or (bolp)
4231 (string-match (concat "[" (nth 0 erc) "\n]")
4232 (char-to-string (char-before (point)))))
4233 (insert " "))
4234 (unless (string-match (concat "[" (nth 1 erc) "\n]")
4235 (char-to-string (char-after (point))))
4236 (insert " ") (backward-char 1))
4237 (insert string)
4238 (and move (backward-char 1))))
4239
4240 (defconst org-nonsticky-props
4241 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
4242
4243 (defsubst org-rear-nonsticky-at (pos)
4244 (add-text-properties (1- pos) pos (list 'rear-nonsticky org-nonsticky-props)))
4245
4246 (defun org-activate-plain-links (limit)
4247 "Run through the buffer and add overlays to links."
4248 (catch 'exit
4249 (let (f)
4250 (if (re-search-forward org-plain-link-re limit t)
4251 (progn
4252 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4253 (setq f (get-text-property (match-beginning 0) 'face))
4254 (if (or (eq f 'org-tag)
4255 (and (listp f) (memq 'org-tag f)))
4256 nil
4257 (add-text-properties (match-beginning 0) (match-end 0)
4258 (list 'mouse-face 'highlight
4259 'keymap org-mouse-map))
4260 (org-rear-nonsticky-at (match-end 0)))
4261 t)))))
4262
4263 (defun org-activate-code (limit)
4264 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
4265 (progn
4266 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4267 (remove-text-properties (match-beginning 0) (match-end 0)
4268 '(display t invisible t intangible t))
4269 t)))
4270
4271 (defun org-fontify-meta-lines-and-blocks (limit)
4272 "Fontify #+ lines and blocks, in the correct ways."
4273 (let ((case-fold-search t))
4274 (if (re-search-forward
4275 "^\\([ \t]*#\\+\\(\\([a-zA-Z]+:?\\)\\(_\\([a-zA-Z]+\\)\\)?\\)\\(.*\\)\\)"
4276 limit t)
4277 (let ((beg (match-beginning 0))
4278 (beg1 (line-beginning-position 2))
4279 (dc1 (downcase (match-string 2)))
4280 (dc3 (downcase (match-string 3)))
4281 end end1 quoting)
4282 (cond
4283 ((member dc1 '("html:" "ascii:" "latex:" "docbook:"))
4284 ;; a single line of backend-specific content
4285 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4286 (remove-text-properties (match-beginning 0) (match-end 0)
4287 '(display t invisible t intangible t))
4288 (add-text-properties (match-beginning 1) (match-end 3)
4289 '(font-lock-fontified t face org-meta-line))
4290 (add-text-properties (match-beginning 6) (match-end 6)
4291 '(font-lock-fontified t face org-block))
4292 t)
4293 ((and (match-end 4) (equal dc3 "begin"))
4294 ;; Truely a block
4295 (setq quoting (member (downcase (match-string 5))
4296 org-protecting-blocks))
4297 (when (re-search-forward
4298 (concat "^[ \t]*#\\+end" (match-string 4) "\\>.*")
4299 nil t) ;; on purpose, we look further than LIMIT
4300 (setq end (match-end 0) end1 (1- (match-beginning 0)))
4301 (when quoting
4302 (remove-text-properties beg end
4303 '(display t invisible t intangible t)))
4304 (add-text-properties
4305 beg end
4306 '(font-lock-fontified t font-lock-multiline t))
4307 (add-text-properties beg beg1 '(face org-meta-line))
4308 (add-text-properties end1 end '(face org-meta-line))
4309 (when quoting
4310 (add-text-properties beg1 end1 '(face org-block)))
4311 t))
4312 ((not (member (char-after beg) '(?\ ?\t)))
4313 ;; just any other in-buffer setting, but not indented
4314 (add-text-properties
4315 beg (match-end 0)
4316 '(font-lock-fontified t face org-meta-line))
4317 t)
4318 ((or (member dc1 '("caption:" "label:" "orgtbl:" "tblfm:" "tblname:"))
4319 (and (match-end 4) (equal dc3 "attr")))
4320 (add-text-properties
4321 beg (match-end 0)
4322 '(font-lock-fontified t face org-meta-line))
4323 t)
4324 (t nil))))))
4325
4326 (defun org-activate-angle-links (limit)
4327 "Run through the buffer and add overlays to links."
4328 (if (re-search-forward org-angle-link-re limit t)
4329 (progn
4330 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4331 (add-text-properties (match-beginning 0) (match-end 0)
4332 (list 'mouse-face 'highlight
4333 'keymap org-mouse-map))
4334 (org-rear-nonsticky-at (match-end 0))
4335 t)))
4336
4337 (defun org-activate-footnote-links (limit)
4338 "Run through the buffer and add overlays to links."
4339 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
4340 limit t)
4341 (progn
4342 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4343 (add-text-properties (match-beginning 2) (match-end 2)
4344 (list 'mouse-face 'highlight
4345 'keymap org-mouse-map
4346 'help-echo
4347 (if (= (point-at-bol) (match-beginning 2))
4348 "Footnote definition"
4349 "Footnote reference")
4350 ))
4351 (org-rear-nonsticky-at (match-end 2))
4352 t)))
4353
4354 (defun org-activate-bracket-links (limit)
4355 "Run through the buffer and add overlays to bracketed links."
4356 (if (re-search-forward org-bracket-link-regexp limit t)
4357 (let* ((help (concat "LINK: "
4358 (org-match-string-no-properties 1)))
4359 ;; FIXME: above we should remove the escapes.
4360 ;; but that requires another match, protecting match data,
4361 ;; a lot of overhead for font-lock.
4362 (ip (org-maybe-intangible
4363 (list 'invisible 'org-link
4364 'keymap org-mouse-map 'mouse-face 'highlight
4365 'font-lock-multiline t 'help-echo help)))
4366 (vp (list 'keymap org-mouse-map 'mouse-face 'highlight
4367 'font-lock-multiline t 'help-echo help)))
4368 ;; We need to remove the invisible property here. Table narrowing
4369 ;; may have made some of this invisible.
4370 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4371 (remove-text-properties (match-beginning 0) (match-end 0)
4372 '(invisible nil))
4373 (if (match-end 3)
4374 (progn
4375 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
4376 (org-rear-nonsticky-at (match-beginning 3))
4377 (add-text-properties (match-beginning 3) (match-end 3) vp)
4378 (org-rear-nonsticky-at (match-end 3))
4379 (add-text-properties (match-end 3) (match-end 0) ip)
4380 (org-rear-nonsticky-at (match-end 0)))
4381 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
4382 (org-rear-nonsticky-at (match-beginning 1))
4383 (add-text-properties (match-beginning 1) (match-end 1) vp)
4384 (org-rear-nonsticky-at (match-end 1))
4385 (add-text-properties (match-end 1) (match-end 0) ip)
4386 (org-rear-nonsticky-at (match-end 0)))
4387 t)))
4388
4389 (defun org-activate-dates (limit)
4390 "Run through the buffer and add overlays to dates."
4391 (if (re-search-forward org-tsr-regexp-both limit t)
4392 (progn
4393 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4394 (add-text-properties (match-beginning 0) (match-end 0)
4395 (list 'mouse-face 'highlight
4396 'keymap org-mouse-map))
4397 (org-rear-nonsticky-at (match-end 0))
4398 (when org-display-custom-times
4399 (if (match-end 3)
4400 (org-display-custom-time (match-beginning 3) (match-end 3)))
4401 (org-display-custom-time (match-beginning 1) (match-end 1)))
4402 t)))
4403
4404 (defvar org-target-link-regexp nil
4405 "Regular expression matching radio targets in plain text.")
4406 (make-variable-buffer-local 'org-target-link-regexp)
4407 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
4408 "Regular expression matching a link target.")
4409 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
4410 "Regular expression matching a radio target.")
4411 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
4412 "Regular expression matching any target.")
4413
4414 (defun org-activate-target-links (limit)
4415 "Run through the buffer and add overlays to target matches."
4416 (when org-target-link-regexp
4417 (let ((case-fold-search t))
4418 (if (re-search-forward org-target-link-regexp limit t)
4419 (progn
4420 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4421 (add-text-properties (match-beginning 0) (match-end 0)
4422 (list 'mouse-face 'highlight
4423 'keymap org-mouse-map
4424 'help-echo "Radio target link"
4425 'org-linked-text t))
4426 (org-rear-nonsticky-at (match-end 0))
4427 t)))))
4428
4429 (defun org-update-radio-target-regexp ()
4430 "Find all radio targets in this file and update the regular expression."
4431 (interactive)
4432 (when (memq 'radio org-activate-links)
4433 (setq org-target-link-regexp
4434 (org-make-target-link-regexp (org-all-targets 'radio)))
4435 (org-restart-font-lock)))
4436
4437 (defun org-hide-wide-columns (limit)
4438 (let (s e)
4439 (setq s (text-property-any (point) (or limit (point-max))
4440 'org-cwidth t))
4441 (when s
4442 (setq e (next-single-property-change s 'org-cwidth))
4443 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4444 (goto-char e)
4445 t)))
4446
4447 (defvar org-latex-and-specials-regexp nil
4448 "Regular expression for highlighting export special stuff.")
4449 (defvar org-match-substring-regexp)
4450 (defvar org-match-substring-with-braces-regexp)
4451 (defvar org-export-html-special-string-regexps)
4452
4453 (defun org-compute-latex-and-specials-regexp ()
4454 "Compute regular expression for stuff treated specially by exporters."
4455 (if (not org-highlight-latex-fragments-and-specials)
4456 (org-set-local 'org-latex-and-specials-regexp nil)
4457 (require 'org-exp)
4458 (let*
4459 ((matchers (plist-get org-format-latex-options :matchers))
4460 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4461 org-latex-regexps)))
4462 (options (org-combine-plists (org-default-export-plist)
4463 (org-infile-export-plist)))
4464 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4465 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4466 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4467 (org-export-html-expand (plist-get options :expand-quoted-html))
4468 (org-export-with-special-strings (plist-get options :special-strings))
4469 (re-sub
4470 (cond
4471 ((equal org-export-with-sub-superscripts '{})
4472 (list org-match-substring-with-braces-regexp))
4473 (org-export-with-sub-superscripts
4474 (list org-match-substring-regexp))
4475 (t nil)))
4476 (re-latex
4477 (if org-export-with-LaTeX-fragments
4478 (mapcar (lambda (x) (nth 1 x)) latexs)))
4479 (re-macros
4480 (if org-export-with-TeX-macros
4481 (list (concat "\\\\"
4482 (regexp-opt
4483 (append (mapcar 'car org-html-entities)
4484 (if (boundp 'org-latex-entities)
4485 (mapcar (lambda (x)
4486 (or (car-safe x) x))
4487 org-latex-entities)
4488 nil))
4489 'words))) ; FIXME
4490 ))
4491 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4492 (re-special (if org-export-with-special-strings
4493 (mapcar (lambda (x) (car x))
4494 org-export-html-special-string-regexps)))
4495 (re-rest
4496 (delq nil
4497 (list
4498 (if org-export-html-expand "@<[^>\n]+>")
4499 ))))
4500 (org-set-local
4501 'org-latex-and-specials-regexp
4502 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4503 re-rest) "\\|")))))
4504
4505 (defun org-do-latex-and-special-faces (limit)
4506 "Run through the buffer and add overlays to links."
4507 (when org-latex-and-specials-regexp
4508 (let (rtn d)
4509 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4510 limit t))
4511 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4512 'face))
4513 '(org-code org-verbatim underline)))
4514 (progn
4515 (setq rtn t
4516 d (cond ((member (char-after (1+ (match-beginning 0)))
4517 '(?_ ?^)) 1)
4518 (t 0)))
4519 (font-lock-prepend-text-property
4520 (+ d (match-beginning 0)) (match-end 0)
4521 'face 'org-latex-and-export-specials)
4522 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4523 '(font-lock-multiline t)))))
4524 rtn)))
4525
4526 (defun org-restart-font-lock ()
4527 "Restart font-lock-mode, to force refontification."
4528 (when (and (boundp 'font-lock-mode) font-lock-mode)
4529 (font-lock-mode -1)
4530 (font-lock-mode 1)))
4531
4532 (defun org-all-targets (&optional radio)
4533 "Return a list of all targets in this file.
4534 With optional argument RADIO, only find radio targets."
4535 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4536 rtn)
4537 (save-excursion
4538 (goto-char (point-min))
4539 (while (re-search-forward re nil t)
4540 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4541 rtn)))
4542
4543 (defun org-make-target-link-regexp (targets)
4544 "Make regular expression matching all strings in TARGETS.
4545 The regular expression finds the targets also if there is a line break
4546 between words."
4547 (and targets
4548 (concat
4549 "\\<\\("
4550 (mapconcat
4551 (lambda (x)
4552 (while (string-match " +" x)
4553 (setq x (replace-match "\\s-+" t t x)))
4554 x)
4555 targets
4556 "\\|")
4557 "\\)\\>")))
4558
4559 (defun org-activate-tags (limit)
4560 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4561 (progn
4562 (org-remove-flyspell-overlays-in (match-beginning 0) (match-end 0))
4563 (add-text-properties (match-beginning 1) (match-end 1)
4564 (list 'mouse-face 'highlight
4565 'keymap org-mouse-map))
4566 (org-rear-nonsticky-at (match-end 1))
4567 t)))
4568
4569 (defun org-outline-level ()
4570 (save-excursion
4571 (looking-at outline-regexp)
4572 (if (match-beginning 1)
4573 (+ (org-get-string-indentation (match-string 1)) 1000)
4574 (1- (- (match-end 0) (match-beginning 0))))))
4575
4576 (defvar org-font-lock-keywords nil)
4577
4578 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4579 "Regular expression matching a property line.")
4580
4581 (defvar org-font-lock-hook nil
4582 "Functions to be called for special font lock stuff.")
4583
4584 (defun org-font-lock-hook (limit)
4585 (run-hook-with-args 'org-font-lock-hook limit))
4586
4587 (defun org-set-font-lock-defaults ()
4588 (let* ((em org-fontify-emphasized-text)
4589 (lk org-activate-links)
4590 (org-font-lock-extra-keywords
4591 (list
4592 ;; Call the hook
4593 '(org-font-lock-hook)
4594 ;; Headlines
4595 `(,(if org-fontify-whole-heading-line
4596 "^\\(\\**\\)\\(\\* \\)\\(.*\n?\\)"
4597 "^\\(\\**\\)\\(\\* \\)\\(.*\\)")
4598 (1 (org-get-level-face 1))
4599 (2 (org-get-level-face 2))
4600 (3 (org-get-level-face 3)))
4601 ;; Table lines
4602 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4603 (1 'org-table t))
4604 ;; Table internals
4605 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4606 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4607 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4608 '("| *\\(<[lr]?[0-9]*>\\)" (1 'org-formula t))
4609 ;; Drawers
4610 (list org-drawer-regexp '(0 'org-special-keyword t))
4611 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4612 ;; Properties
4613 (list org-property-re
4614 '(1 'org-special-keyword t)
4615 '(3 'org-property-value t))
4616 ;; Links
4617 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4618 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4619 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4620 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4621 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4622 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4623 (if (memq 'footnote lk) '(org-activate-footnote-links
4624 (2 'org-footnote t)))
4625 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4626 '(org-hide-wide-columns (0 nil append))
4627 ;; TODO lines
4628 (list (concat "^\\*+[ \t]+" org-todo-regexp "\\([ \t]\\|$\\)")
4629 '(1 (org-get-todo-face 1) t))
4630 ;; DONE
4631 (if org-fontify-done-headline
4632 (list (concat "^[*]+ +\\<\\("
4633 (mapconcat 'regexp-quote org-done-keywords "\\|")
4634 "\\)\\(.*\\)")
4635 '(2 'org-headline-done t))
4636 nil)
4637 ;; Priorities
4638 '(org-font-lock-add-priority-faces)
4639 ;; Tags
4640 '(org-font-lock-add-tag-faces)
4641 ;; Special keywords
4642 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4643 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4644 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4645 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4646 ;; Emphasis
4647 (if em
4648 (if (featurep 'xemacs)
4649 '(org-do-emphasis-faces (0 nil append))
4650 '(org-do-emphasis-faces)))
4651 ;; Checkboxes
4652 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4653 2 'org-checkbox prepend)
4654 (if org-provide-checkbox-statistics
4655 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4656 (0 (org-get-checkbox-statistics-face) t)))
4657 ;; Description list items
4658 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4659 2 'bold prepend)
4660 ;; ARCHIVEd headings
4661 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4662 '(1 'org-archived prepend))
4663 ;; Specials
4664 '(org-do-latex-and-special-faces)
4665 ;; Code
4666 '(org-activate-code (1 'org-code t))
4667 ;; COMMENT
4668 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4669 "\\|" org-quote-string "\\)\\>")
4670 '(1 'org-special-keyword t))
4671 '("^#.*" (0 'font-lock-comment-face t))
4672 ;; Blocks and meta lines
4673 '(org-fontify-meta-lines-and-blocks)
4674 )))
4675 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4676 ;; Now set the full font-lock-keywords
4677 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4678 (org-set-local 'font-lock-defaults
4679 '(org-font-lock-keywords t nil nil backward-paragraph))
4680 (kill-local-variable 'font-lock-keywords) nil))
4681
4682 (defun org-fontify-like-in-org-mode (s &optional odd-levels)
4683 "Fontify string S like in Org-mode"
4684 (with-temp-buffer
4685 (insert s)
4686 (let ((org-odd-levels-only odd-levels))
4687 (org-mode)
4688 (font-lock-fontify-buffer)
4689 (buffer-string))))
4690
4691 (defvar org-m nil)
4692 (defvar org-l nil)
4693 (defvar org-f nil)
4694 (defun org-get-level-face (n)
4695 "Get the right face for match N in font-lock matching of headlines."
4696 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4697 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4698 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4699 (cond
4700 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4701 ((eq n 2) org-f)
4702 (t (if org-level-color-stars-only nil org-f))))
4703
4704 (defun org-get-todo-face (kwd)
4705 "Get the right face for a TODO keyword KWD.
4706 If KWD is a number, get the corresponding match group."
4707 (if (numberp kwd) (setq kwd (match-string kwd)))
4708 (or (cdr (assoc kwd org-todo-keyword-faces))
4709 (and (member kwd org-done-keywords) 'org-done)
4710 'org-todo))
4711
4712 (defun org-font-lock-add-tag-faces (limit)
4713 "Add the special tag faces."
4714 (when (and org-tag-faces org-tags-special-faces-re)
4715 (while (re-search-forward org-tags-special-faces-re limit t)
4716 (add-text-properties (match-beginning 1) (match-end 1)
4717 (list 'face (org-get-tag-face 1)
4718 'font-lock-fontified t))
4719 (backward-char 1))))
4720
4721 (defun org-font-lock-add-priority-faces (limit)
4722 "Add the special priority faces."
4723 (while (re-search-forward "\\[#\\([A-Z0-9]\\)\\]" limit t)
4724 (add-text-properties
4725 (match-beginning 0) (match-end 0)
4726 (list 'face (or (cdr (assoc (char-after (match-beginning 1))
4727 org-priority-faces))
4728 'org-special-keyword)
4729 'font-lock-fontified t))))
4730
4731 (defun org-get-tag-face (kwd)
4732 "Get the right face for a TODO keyword KWD.
4733 If KWD is a number, get the corresponding match group."
4734 (if (numberp kwd) (setq kwd (match-string kwd)))
4735 (or (cdr (assoc kwd org-tag-faces))
4736 'org-tag))
4737
4738 (defun org-unfontify-region (beg end &optional maybe_loudly)
4739 "Remove fontification and activation overlays from links."
4740 (font-lock-default-unfontify-region beg end)
4741 (let* ((buffer-undo-list t)
4742 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4743 (inhibit-modification-hooks t)
4744 deactivate-mark buffer-file-name buffer-file-truename)
4745 (remove-text-properties beg end
4746 '(mouse-face t keymap t org-linked-text t
4747 invisible t intangible t
4748 line-prefix t wrap-prefix t
4749 org-no-flyspell t))))
4750
4751 ;;;; Visibility cycling, including org-goto and indirect buffer
4752
4753 ;;; Cycling
4754
4755 (defvar org-cycle-global-status nil)
4756 (make-variable-buffer-local 'org-cycle-global-status)
4757 (defvar org-cycle-subtree-status nil)
4758 (make-variable-buffer-local 'org-cycle-subtree-status)
4759
4760 ;;;###autoload
4761
4762 (defvar org-inlinetask-min-level)
4763
4764 (defun org-cycle (&optional arg)
4765 "TAB-action and visibility cycling for Org-mode.
4766
4767 This is the command invoked in Org-moe by the TAB key. It's main purpose
4768 is outine visibility cycling, but it also invokes other actions
4769 in special contexts.
4770
4771 - When this function is called with a prefix argument, rotate the entire
4772 buffer through 3 states (global cycling)
4773 1. OVERVIEW: Show only top-level headlines.
4774 2. CONTENTS: Show all headlines of all levels, but no body text.
4775 3. SHOW ALL: Show everything.
4776 When called with two `C-u C-u' prefixes, switch to the startup visibility,
4777 determined by the variable `org-startup-folded', and by any VISIBILITY
4778 properties in the buffer.
4779 When called with three `C-u C-u C-u' prefixed, show the entire buffer,
4780 including any drawers.
4781
4782 - When inside a table, re-align the table and move to the next field.
4783
4784 - When point is at the beginning of a headline, rotate the subtree started
4785 by this line through 3 different states (local cycling)
4786 1. FOLDED: Only the main headline is shown.
4787 2. CHILDREN: The main headline and the direct children are shown.
4788 From this state, you can move to one of the children
4789 and zoom in further.
4790 3. SUBTREE: Show the entire subtree, including body text.
4791 If there is no subtree, switch directly from CHILDREN to FOLDED.
4792
4793 - When there is a numeric prefix, go up to a heading with level ARG, do
4794 a `show-subtree' and return to the previous cursor position. If ARG
4795 is negative, go up that many levels.
4796
4797 - When point is not at the beginning of a headline, execute the global
4798 binding for TAB, which is re-indenting the line. See the option
4799 `org-cycle-emulate-tab' for details.
4800
4801 - Special case: if point is at the beginning of the buffer and there is
4802 no headline in line 1, this function will act as if called with prefix arg.
4803 But only if also the variable `org-cycle-global-at-bob' is t."
4804 (interactive "P")
4805 (org-load-modules-maybe)
4806 (unless (run-hook-with-args-until-success 'org-tab-first-hook)
4807 (let* ((limit-level
4808 (or org-cycle-max-level
4809 (and (boundp 'org-inlinetask-min-level)
4810 org-inlinetask-min-level
4811 (1- org-inlinetask-min-level))))
4812 (nstars (and limit-level
4813 (if org-odd-levels-only
4814 (and limit-level (1- (* limit-level 2)))
4815 limit-level)))
4816 (outline-regexp
4817 (cond
4818 ((not (org-mode-p)) outline-regexp)
4819 ((or (eq org-cycle-include-plain-lists 'integrate)
4820 (and org-cycle-include-plain-lists (org-at-item-p)))
4821 (concat "\\(?:\\*"
4822 (if nstars (format "\\{1,%d\\}" nstars) "+")
4823 " \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"))
4824 (t (concat "\\*" (if nstars (format "\\{1,%d\\} " nstars) "+ ")))))
4825 (bob-special (and org-cycle-global-at-bob (bobp)
4826 (not (looking-at outline-regexp))))
4827 (org-cycle-hook
4828 (if bob-special
4829 (delq 'org-optimize-window-after-visibility-change
4830 (copy-sequence org-cycle-hook))
4831 org-cycle-hook))
4832 (pos (point)))
4833
4834 (if (or bob-special (equal arg '(4)))
4835 ;; special case: use global cycling
4836 (setq arg t))
4837
4838 (cond
4839
4840 ((equal arg '(16))
4841 (org-set-startup-visibility)
4842 (message "Startup visibility, plus VISIBILITY properties"))
4843
4844 ((equal arg '(64))
4845 (show-all)
4846 (message "Entire buffer visible, including drawers"))
4847
4848 ((org-at-table-p 'any)
4849 ;; Enter the table or move to the next field in the table
4850 (or (org-table-recognize-table.el)
4851 (progn
4852 (if arg (org-table-edit-field t)
4853 (org-table-justify-field-maybe)
4854 (call-interactively 'org-table-next-field)))))
4855
4856 ((run-hook-with-args-until-success
4857 'org-tab-after-check-for-table-hook))
4858
4859 ((eq arg t) ;; Global cycling
4860 (org-cycle-internal-global))
4861
4862 ((and org-drawers org-drawer-regexp
4863 (save-excursion
4864 (beginning-of-line 1)
4865 (looking-at org-drawer-regexp)))
4866 ;; Toggle block visibility
4867 (org-flag-drawer
4868 (not (get-char-property (match-end 0) 'invisible))))
4869
4870 ((integerp arg)
4871 ;; Show-subtree, ARG levels up from here.
4872 (save-excursion
4873 (org-back-to-heading)
4874 (outline-up-heading (if (< arg 0) (- arg)
4875 (- (funcall outline-level) arg)))
4876 (org-show-subtree)))
4877
4878 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4879 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4880
4881 (org-cycle-internal-local))
4882
4883 ;; TAB emulation and template completion
4884 (buffer-read-only (org-back-to-heading))
4885
4886 ((run-hook-with-args-until-success
4887 'org-tab-after-check-for-cycling-hook))
4888
4889 ((org-try-structure-completion))
4890
4891 ((org-try-cdlatex-tab))
4892
4893 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4894 (or (not (bolp))
4895 (not (looking-at outline-regexp))))
4896 (call-interactively (global-key-binding "\t")))
4897
4898 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4899 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4900 (or (and (eq org-cycle-emulate-tab 'white)
4901 (= (match-end 0) (point-at-eol)))
4902 (and (eq org-cycle-emulate-tab 'whitestart)
4903 (>= (match-end 0) pos))))
4904 t
4905 (eq org-cycle-emulate-tab t))
4906 (call-interactively (global-key-binding "\t")))
4907
4908 (t (save-excursion
4909 (org-back-to-heading)
4910 (org-cycle)))))))
4911
4912 (defun org-cycle-internal-global ()
4913 "Do the global cycling action."
4914 (cond
4915 ((and (eq last-command this-command)
4916 (eq org-cycle-global-status 'overview))
4917 ;; We just created the overview - now do table of contents
4918 ;; This can be slow in very large buffers, so indicate action
4919 (run-hook-with-args 'org-pre-cycle-hook 'contents)
4920 (message "CONTENTS...")
4921 (org-content)
4922 (message "CONTENTS...done")
4923 (setq org-cycle-global-status 'contents)
4924 (run-hook-with-args 'org-cycle-hook 'contents))
4925
4926 ((and (eq last-command this-command)
4927 (eq org-cycle-global-status 'contents))
4928 ;; We just showed the table of contents - now show everything
4929 (run-hook-with-args 'org-pre-cycle-hook 'all)
4930 (show-all)
4931 (message "SHOW ALL")
4932 (setq org-cycle-global-status 'all)
4933 (run-hook-with-args 'org-cycle-hook 'all))
4934
4935 (t
4936 ;; Default action: go to overview
4937 (run-hook-with-args 'org-pre-cycle-hook 'overview)
4938 (org-overview)
4939 (message "OVERVIEW")
4940 (setq org-cycle-global-status 'overview)
4941 (run-hook-with-args 'org-cycle-hook 'overview))))
4942
4943 (defun org-cycle-internal-local ()
4944 "Do the local cycling action."
4945 (org-back-to-heading)
4946 (let ((goal-column 0) eoh eol eos level has-children children-skipped)
4947 ;; First, some boundaries
4948 (save-excursion
4949 (org-back-to-heading)
4950 (setq level (funcall outline-level))
4951 (save-excursion
4952 (beginning-of-line 2)
4953 (if (or (featurep 'xemacs) (<= emacs-major-version 21))
4954 ; XEmacs does not have `next-single-char-property-change'
4955 ; I'm not sure about Emacs 21.
4956 (while (and (not (eobp)) ;; this is like `next-line'
4957 (get-char-property (1- (point)) 'invisible))
4958 (beginning-of-line 2))
4959 (while (and (not (eobp)) ;; this is like `next-line'
4960 (get-char-property (1- (point)) 'invisible))
4961 (goto-char (next-single-char-property-change (point) 'invisible))
4962 ;;;??? (or (bolp) (beginning-of-line 2))))
4963 (and (eolp) (beginning-of-line 2))))
4964 (setq eol (point)))
4965 (outline-end-of-heading) (setq eoh (point))
4966 (save-excursion
4967 (outline-next-heading)
4968 (setq has-children (and (org-at-heading-p t)
4969 (> (funcall outline-level) level))))
4970 (org-end-of-subtree t)
4971 (unless (eobp)
4972 (skip-chars-forward " \t\n")
4973 (beginning-of-line 1) ; in case this is an item
4974 )
4975 (setq eos (1- (point))))
4976 ;; Find out what to do next and set `this-command'
4977 (cond
4978 ((= eos eoh)
4979 ;; Nothing is hidden behind this heading
4980 (run-hook-with-args 'org-pre-cycle-hook 'empty)
4981 (message "EMPTY ENTRY")
4982 (setq org-cycle-subtree-status nil)
4983 (save-excursion
4984 (goto-char eos)
4985 (outline-next-heading)
4986 (if (org-invisible-p) (org-flag-heading nil))))
4987 ((and (or (>= eol eos)
4988 (not (string-match "\\S-" (buffer-substring eol eos))))
4989 (or has-children
4990 (not (setq children-skipped
4991 org-cycle-skip-children-state-if-no-children))))
4992 ;; Entire subtree is hidden in one line: children view
4993 (run-hook-with-args 'org-pre-cycle-hook 'children)
4994 (org-show-entry)
4995 (show-children)
4996 (message "CHILDREN")
4997 (save-excursion
4998 (goto-char eos)
4999 (outline-next-heading)
5000 (if (org-invisible-p) (org-flag-heading nil)))
5001 (setq org-cycle-subtree-status 'children)
5002 (run-hook-with-args 'org-cycle-hook 'children))
5003 ((or children-skipped
5004 (and (eq last-command this-command)
5005 (eq org-cycle-subtree-status 'children)))
5006 ;; We just showed the children, or no children are there,
5007 ;; now show everything.
5008 (run-hook-with-args 'org-pre-cycle-hook 'subtree)
5009 (org-show-subtree)
5010 (message (if children-skipped "SUBTREE (NO CHILDREN)" "SUBTREE"))
5011 (setq org-cycle-subtree-status 'subtree)
5012 (run-hook-with-args 'org-cycle-hook 'subtree))
5013 (t
5014 ;; Default action: hide the subtree.
5015 (run-hook-with-args 'org-pre-cycle-hook 'folded)
5016 (hide-subtree)
5017 (message "FOLDED")
5018 (setq org-cycle-subtree-status 'folded)
5019 (run-hook-with-args 'org-cycle-hook 'folded)))))
5020
5021 ;;;###autoload
5022 (defun org-global-cycle (&optional arg)
5023 "Cycle the global visibility. For details see `org-cycle'.
5024 With C-u prefix arg, switch to startup visibility.
5025 With a numeric prefix, show all headlines up to that level."
5026 (interactive "P")
5027 (let ((org-cycle-include-plain-lists
5028 (if (org-mode-p) org-cycle-include-plain-lists nil)))
5029 (cond
5030 ((integerp arg)
5031 (show-all)
5032 (hide-sublevels arg)
5033 (setq org-cycle-global-status 'contents))
5034 ((equal arg '(4))
5035 (org-set-startup-visibility)
5036 (message "Startup visibility, plus VISIBILITY properties."))
5037 (t
5038 (org-cycle '(4))))))
5039
5040 (defun org-set-startup-visibility ()
5041 "Set the visibility required by startup options and properties."
5042 (cond
5043 ((eq org-startup-folded t)
5044 (org-cycle '(4)))
5045 ((eq org-startup-folded 'content)
5046 (let ((this-command 'org-cycle) (last-command 'org-cycle))
5047 (org-cycle '(4)) (org-cycle '(4)))))
5048 (if org-hide-block-startup (org-hide-block-all))
5049 (org-set-visibility-according-to-property 'no-cleanup)
5050 (org-cycle-hide-archived-subtrees 'all)
5051 (org-cycle-hide-drawers 'all)
5052 (org-cycle-show-empty-lines 'all))
5053
5054 (defun org-set-visibility-according-to-property (&optional no-cleanup)
5055 "Switch subtree visibilities according to :VISIBILITY: property."
5056 (interactive)
5057 (let (org-show-entry-below state)
5058 (save-excursion
5059 (goto-char (point-min))
5060 (while (re-search-forward
5061 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
5062 nil t)
5063 (setq state (match-string 1))
5064 (save-excursion
5065 (org-back-to-heading t)
5066 (hide-subtree)
5067 (org-reveal)
5068 (cond
5069 ((equal state '("fold" "folded"))
5070 (hide-subtree))
5071 ((equal state "children")
5072 (org-show-hidden-entry)
5073 (show-children))
5074 ((equal state "content")
5075 (save-excursion
5076 (save-restriction
5077 (org-narrow-to-subtree)
5078 (org-content))))
5079 ((member state '("all" "showall"))
5080 (show-subtree)))))
5081 (unless no-cleanup
5082 (org-cycle-hide-archived-subtrees 'all)
5083 (org-cycle-hide-drawers 'all)
5084 (org-cycle-show-empty-lines 'all)))))
5085
5086 (defun org-overview ()
5087 "Switch to overview mode, showing only top-level headlines.
5088 Really, this shows all headlines with level equal or greater than the level
5089 of the first headline in the buffer. This is important, because if the
5090 first headline is not level one, then (hide-sublevels 1) gives confusing
5091 results."
5092 (interactive)
5093 (let ((level (save-excursion
5094 (goto-char (point-min))
5095 (if (re-search-forward (concat "^" outline-regexp) nil t)
5096 (progn
5097 (goto-char (match-beginning 0))
5098 (funcall outline-level))))))
5099 (and level (hide-sublevels level))))
5100
5101 (defun org-content (&optional arg)
5102 "Show all headlines in the buffer, like a table of contents.
5103 With numerical argument N, show content up to level N."
5104 (interactive "P")
5105 (save-excursion
5106 ;; Visit all headings and show their offspring
5107 (and (integerp arg) (org-overview))
5108 (goto-char (point-max))
5109 (catch 'exit
5110 (while (and (progn (condition-case nil
5111 (outline-previous-visible-heading 1)
5112 (error (goto-char (point-min))))
5113 t)
5114 (looking-at outline-regexp))
5115 (if (integerp arg)
5116 (show-children (1- arg))
5117 (show-branches))
5118 (if (bobp) (throw 'exit nil))))))
5119
5120
5121 (defun org-optimize-window-after-visibility-change (state)
5122 "Adjust the window after a change in outline visibility.
5123 This function is the default value of the hook `org-cycle-hook'."
5124 (when (get-buffer-window (current-buffer))
5125 (cond
5126 ((eq state 'content) nil)
5127 ((eq state 'all) nil)
5128 ((eq state 'folded) nil)
5129 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
5130 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
5131
5132 ;; FIXME: no longer in use
5133 (defun org-compact-display-after-subtree-move ()
5134 "Show a compacter version of the tree of the entry's parent."
5135 (save-excursion
5136 (if (org-up-heading-safe)
5137 (progn
5138 (hide-subtree)
5139 (show-entry)
5140 (show-children)
5141 (org-cycle-show-empty-lines 'children)
5142 (org-cycle-hide-drawers 'children))
5143 (org-overview))))
5144
5145 (defun org-remove-empty-overlays-at (pos)
5146 "Remove outline overlays that do not contain non-white stuff."
5147 (mapc
5148 (lambda (o)
5149 (and (eq 'outline (org-overlay-get o 'invisible))
5150 (not (string-match "\\S-" (buffer-substring (org-overlay-start o)
5151 (org-overlay-end o))))
5152 (org-delete-overlay o)))
5153 (org-overlays-at pos)))
5154
5155 (defun org-clean-visibility-after-subtree-move ()
5156 "Fix visibility issues after moving a subtree."
5157 ;; First, find a reasonable region to look at:
5158 ;; Start two siblings above, end three below
5159 (let* ((beg (save-excursion
5160 (and (outline-get-last-sibling)
5161 (outline-get-last-sibling))
5162 (point)))
5163 (end (save-excursion
5164 (and (outline-get-next-sibling)
5165 (outline-get-next-sibling)
5166 (outline-get-next-sibling))
5167 (if (org-at-heading-p)
5168 (point-at-eol)
5169 (point))))
5170 (level (looking-at "\\*+"))
5171 (re (if level (concat "^" (regexp-quote (match-string 0)) " "))))
5172 (save-excursion
5173 (save-restriction
5174 (narrow-to-region beg end)
5175 (when re
5176 ;; Properly fold already folded siblings
5177 (goto-char (point-min))
5178 (while (re-search-forward re nil t)
5179 (if (save-excursion (goto-char (point-at-eol)) (org-invisible-p))
5180 (hide-entry))))
5181 (org-cycle-show-empty-lines 'overview)
5182 (org-cycle-hide-drawers 'overview)))))
5183
5184 (defun org-cycle-show-empty-lines (state)
5185 "Show empty lines above all visible headlines.
5186 The region to be covered depends on STATE when called through
5187 `org-cycle-hook'. Lisp program can use t for STATE to get the
5188 entire buffer covered. Note that an empty line is only shown if there
5189 are at least `org-cycle-separator-lines' empty lines before the headline."
5190 (when (> org-cycle-separator-lines 0)
5191 (save-excursion
5192 (let* ((n org-cycle-separator-lines)
5193 (re (cond
5194 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
5195 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
5196 (t (let ((ns (number-to-string (- n 2))))
5197 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
5198 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
5199 beg end)
5200 (cond
5201 ((memq state '(overview contents t))
5202 (setq beg (point-min) end (point-max)))
5203 ((memq state '(children folded))
5204 (setq beg (point) end (progn (org-end-of-subtree t t)
5205 (beginning-of-line 2)
5206 (point)))))
5207 (when beg
5208 (goto-char beg)
5209 (while (re-search-forward re end t)
5210 (if (not (get-char-property (match-end 1) 'invisible))
5211 (outline-flag-region
5212 (match-beginning 1) (match-end 1) nil)))))))
5213 ;; Never hide empty lines at the end of the file.
5214 (save-excursion
5215 (goto-char (point-max))
5216 (outline-previous-heading)
5217 (outline-end-of-heading)
5218 (if (and (looking-at "[ \t\n]+")
5219 (= (match-end 0) (point-max)))
5220 (outline-flag-region (point) (match-end 0) nil))))
5221
5222 (defun org-show-empty-lines-in-parent ()
5223 "Move to the parent and re-show empty lines before visible headlines."
5224 (save-excursion
5225 (let ((context (if (org-up-heading-safe) 'children 'overview)))
5226 (org-cycle-show-empty-lines context))))
5227
5228 (defun org-cycle-hide-drawers (state)
5229 "Re-hide all drawers after a visibility state change."
5230 (when (and (org-mode-p)
5231 (not (memq state '(overview folded contents))))
5232 (save-excursion
5233 (let* ((globalp (memq state '(contents all)))
5234 (beg (if globalp (point-min) (point)))
5235 (end (if globalp (point-max)
5236 (if (eq state 'children)
5237 (save-excursion (outline-next-heading) (point))
5238 (org-end-of-subtree t)))))
5239 (goto-char beg)
5240 (while (re-search-forward org-drawer-regexp end t)
5241 (org-flag-drawer t))))))
5242
5243 (defun org-flag-drawer (flag)
5244 (save-excursion
5245 (beginning-of-line 1)
5246 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
5247 (let ((b (match-end 0))
5248 (outline-regexp org-outline-regexp))
5249 (if (re-search-forward
5250 "^[ \t]*:END:"
5251 (save-excursion (outline-next-heading) (point)) t)
5252 (outline-flag-region b (point-at-eol) flag)
5253 (error ":END: line missing"))))))
5254
5255 (defun org-subtree-end-visible-p ()
5256 "Is the end of the current subtree visible?"
5257 (pos-visible-in-window-p
5258 (save-excursion (org-end-of-subtree t) (point))))
5259
5260 (defun org-first-headline-recenter (&optional N)
5261 "Move cursor to the first headline and recenter the headline.
5262 Optional argument N means, put the headline into the Nth line of the window."
5263 (goto-char (point-min))
5264 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
5265 (beginning-of-line)
5266 (recenter (prefix-numeric-value N))))
5267
5268 ;;; Folding of blocks
5269
5270 (defconst org-block-regexp
5271
5272 "^[ \t]*#\\+begin_\\([^ \n]+\\)\\(\\([^\n]+\\)\\)?\n\\([^\000]+?\\)#\\+end_\\1[ \t]*$"
5273 "Regular expression for hiding blocks.")
5274
5275 (defvar org-hide-block-overlays nil
5276 "Overays hiding blocks.")
5277 (make-variable-buffer-local 'org-hide-block-overlays)
5278
5279 (defun org-block-map (function &optional start end)
5280 "Call func at the head of all source blocks in the current
5281 buffer. Optional arguments START and END can be used to limit
5282 the range."
5283 (let ((start (or start (point-min)))
5284 (end (or end (point-max))))
5285 (save-excursion
5286 (goto-char start)
5287 (while (and (< (point) end) (re-search-forward org-block-regexp end t))
5288 (save-excursion
5289 (save-match-data
5290 (goto-char (match-beginning 0))
5291 (funcall function)))))))
5292
5293 (defun org-hide-block-toggle-all ()
5294 "Toggle the visibility of all blocks in the current buffer."
5295 (org-block-map #'org-hide-block-toggle))
5296
5297 (defun org-hide-block-all ()
5298 "Fold all blocks in the current buffer."
5299 (interactive)
5300 (org-show-block-all)
5301 (org-block-map #'org-hide-block-toggle-maybe))
5302
5303 (defun org-show-block-all ()
5304 "Unfold all blocks in the current buffer."
5305 (mapc 'org-delete-overlay org-hide-block-overlays)
5306 (setq org-hide-block-overlays nil))
5307
5308 (defun org-hide-block-toggle-maybe ()
5309 "Toggle visibility of block at point."
5310 (interactive)
5311 (let ((case-fold-search t))
5312 (if (save-excursion
5313 (beginning-of-line 1)
5314 (looking-at org-block-regexp))
5315 (progn (org-hide-block-toggle)
5316 t) ;; to signal that we took action
5317 nil))) ;; to signal that we did not
5318
5319 (defun org-hide-block-toggle (&optional force)
5320 "Toggle the visibility of the current block."
5321 (interactive)
5322 (save-excursion
5323 (beginning-of-line)
5324 (if (re-search-forward org-block-regexp nil t)
5325 (let ((start (- (match-beginning 4) 1)) ;; beginning of body
5326 (end (match-end 0))
5327 ov) ;; end of entire body
5328 (if (memq t (mapcar (lambda (overlay)
5329 (eq (org-overlay-get overlay 'invisible)
5330 'org-hide-block))
5331 (org-overlays-at start)))
5332 (if (or (not force) (eq force 'off))
5333 (mapc (lambda (ov)
5334 (when (member ov org-hide-block-overlays)
5335 (setq org-hide-block-overlays
5336 (delq ov org-hide-block-overlays)))
5337 (when (eq (org-overlay-get ov 'invisible)
5338 'org-hide-block)
5339 (org-delete-overlay ov)))
5340 (org-overlays-at start)))
5341 (setq ov (org-make-overlay start end))
5342 (org-overlay-put ov 'invisible 'org-hide-block)
5343 (push ov org-hide-block-overlays)))
5344 (error "Not looking at a source block"))))
5345
5346 ;; org-tab-after-check-for-cycling-hook
5347 (add-hook 'org-tab-first-hook 'org-hide-block-toggle-maybe)
5348 ;; Remove overlays when changing major mode
5349 (add-hook 'org-mode-hook
5350 (lambda () (org-add-hook 'change-major-mode-hook
5351 'org-show-block-all 'append 'local)))
5352
5353 ;;; Org-goto
5354
5355 (defvar org-goto-window-configuration nil)
5356 (defvar org-goto-marker nil)
5357 (defvar org-goto-map
5358 (let ((map (make-sparse-keymap)))
5359 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
5360 (while (setq cmd (pop cmds))
5361 (substitute-key-definition cmd cmd map global-map)))
5362 (suppress-keymap map)
5363 (org-defkey map "\C-m" 'org-goto-ret)
5364 (org-defkey map [(return)] 'org-goto-ret)
5365 (org-defkey map [(left)] 'org-goto-left)
5366 (org-defkey map [(right)] 'org-goto-right)
5367 (org-defkey map [(control ?g)] 'org-goto-quit)
5368 (org-defkey map "\C-i" 'org-cycle)
5369 (org-defkey map [(tab)] 'org-cycle)
5370 (org-defkey map [(down)] 'outline-next-visible-heading)
5371 (org-defkey map [(up)] 'outline-previous-visible-heading)
5372 (if org-goto-auto-isearch
5373 (if (fboundp 'define-key-after)
5374 (define-key-after map [t] 'org-goto-local-auto-isearch)
5375 nil)
5376 (org-defkey map "q" 'org-goto-quit)
5377 (org-defkey map "n" 'outline-next-visible-heading)
5378 (org-defkey map "p" 'outline-previous-visible-heading)
5379 (org-defkey map "f" 'outline-forward-same-level)
5380 (org-defkey map "b" 'outline-backward-same-level)
5381 (org-defkey map "u" 'outline-up-heading))
5382 (org-defkey map "/" 'org-occur)
5383 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
5384 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
5385 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
5386 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
5387 (org-defkey map "\C-c\C-u" 'outline-up-heading)
5388 map))
5389
5390 (defconst org-goto-help
5391 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
5392 RET=jump to location [Q]uit and return to previous location
5393 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
5394
5395 (defvar org-goto-start-pos) ; dynamically scoped parameter
5396
5397 ;; FIXME: Docstring doe not mention both interfaces
5398 (defun org-goto (&optional alternative-interface)
5399 "Look up a different location in the current file, keeping current visibility.
5400
5401 When you want look-up or go to a different location in a document, the
5402 fastest way is often to fold the entire buffer and then dive into the tree.
5403 This method has the disadvantage, that the previous location will be folded,
5404 which may not be what you want.
5405
5406 This command works around this by showing a copy of the current buffer
5407 in an indirect buffer, in overview mode. You can dive into the tree in
5408 that copy, use org-occur and incremental search to find a location.
5409 When pressing RET or `Q', the command returns to the original buffer in
5410 which the visibility is still unchanged. After RET is will also jump to
5411 the location selected in the indirect buffer and expose the
5412 the headline hierarchy above."
5413 (interactive "P")
5414 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
5415 (org-refile-use-outline-path t)
5416 (org-refile-target-verify-function nil)
5417 (interface
5418 (if (not alternative-interface)
5419 org-goto-interface
5420 (if (eq org-goto-interface 'outline)
5421 'outline-path-completion
5422 'outline)))
5423 (org-goto-start-pos (point))
5424 (selected-point
5425 (if (eq interface 'outline)
5426 (car (org-get-location (current-buffer) org-goto-help))
5427 (nth 3 (org-refile-get-location "Goto: ")))))
5428 (if selected-point
5429 (progn
5430 (org-mark-ring-push org-goto-start-pos)
5431 (goto-char selected-point)
5432 (if (or (org-invisible-p) (org-invisible-p2))
5433 (org-show-context 'org-goto)))
5434 (message "Quit"))))
5435
5436 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
5437 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
5438 (defvar org-goto-local-auto-isearch-map) ; defined below
5439
5440 (defun org-get-location (buf help)
5441 "Let the user select a location in the Org-mode buffer BUF.
5442 This function uses a recursive edit. It returns the selected position
5443 or nil."
5444 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
5445 (isearch-hide-immediately nil)
5446 (isearch-search-fun-function
5447 (lambda () 'org-goto-local-search-headings))
5448 (org-goto-selected-point org-goto-exit-command))
5449 (save-excursion
5450 (save-window-excursion
5451 (delete-other-windows)
5452 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
5453 (switch-to-buffer
5454 (condition-case nil
5455 (make-indirect-buffer (current-buffer) "*org-goto*")
5456 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
5457 (with-output-to-temp-buffer "*Help*"
5458 (princ help))
5459 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
5460 (setq buffer-read-only nil)
5461 (let ((org-startup-truncated t)
5462 (org-startup-folded nil)
5463 (org-startup-align-all-tables nil))
5464 (org-mode)
5465 (org-overview))
5466 (setq buffer-read-only t)
5467 (if (and (boundp 'org-goto-start-pos)
5468 (integer-or-marker-p org-goto-start-pos))
5469 (let ((org-show-hierarchy-above t)
5470 (org-show-siblings t)
5471 (org-show-following-heading t))
5472 (goto-char org-goto-start-pos)
5473 (and (org-invisible-p) (org-show-context)))
5474 (goto-char (point-min)))
5475 (let (org-special-ctrl-a/e) (org-beginning-of-line))
5476 (message "Select location and press RET")
5477 (use-local-map org-goto-map)
5478 (recursive-edit)
5479 ))
5480 (kill-buffer "*org-goto*")
5481 (cons org-goto-selected-point org-goto-exit-command)))
5482
5483 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
5484 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
5485 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
5486 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
5487
5488 (defun org-goto-local-search-headings (string bound noerror)
5489 "Search and make sure that any matches are in headlines."
5490 (catch 'return
5491 (while (if isearch-forward
5492 (search-forward string bound noerror)
5493 (search-backward string bound noerror))
5494 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
5495 (and (member :headline context)
5496 (not (member :tags context))))
5497 (throw 'return (point))))))
5498
5499 (defun org-goto-local-auto-isearch ()
5500 "Start isearch."
5501 (interactive)
5502 (goto-char (point-min))
5503 (let ((keys (this-command-keys)))
5504 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
5505 (isearch-mode t)
5506 (isearch-process-search-char (string-to-char keys)))))
5507
5508 (defun org-goto-ret (&optional arg)
5509 "Finish `org-goto' by going to the new location."
5510 (interactive "P")
5511 (setq org-goto-selected-point (point)
5512 org-goto-exit-command 'return)
5513 (throw 'exit nil))
5514
5515 (defun org-goto-left ()
5516 "Finish `org-goto' by going to the new location."
5517 (interactive)
5518 (if (org-on-heading-p)
5519 (progn
5520 (beginning-of-line 1)
5521 (setq org-goto-selected-point (point)
5522 org-goto-exit-command 'left)
5523 (throw 'exit nil))
5524 (error "Not on a heading")))
5525
5526 (defun org-goto-right ()
5527 "Finish `org-goto' by going to the new location."
5528 (interactive)
5529 (if (org-on-heading-p)
5530 (progn
5531 (setq org-goto-selected-point (point)
5532 org-goto-exit-command 'right)
5533 (throw 'exit nil))
5534 (error "Not on a heading")))
5535
5536 (defun org-goto-quit ()
5537 "Finish `org-goto' without cursor motion."
5538 (interactive)
5539 (setq org-goto-selected-point nil)
5540 (setq org-goto-exit-command 'quit)
5541 (throw 'exit nil))
5542
5543 ;;; Indirect buffer display of subtrees
5544
5545 (defvar org-indirect-dedicated-frame nil
5546 "This is the frame being used for indirect tree display.")
5547 (defvar org-last-indirect-buffer nil)
5548
5549 (defun org-tree-to-indirect-buffer (&optional arg)
5550 "Create indirect buffer and narrow it to current subtree.
5551 With numerical prefix ARG, go up to this level and then take that tree.
5552 If ARG is negative, go up that many levels.
5553 If `org-indirect-buffer-display' is not `new-frame', the command removes the
5554 indirect buffer previously made with this command, to avoid proliferation of
5555 indirect buffers. However, when you call the command with a `C-u' prefix, or
5556 when `org-indirect-buffer-display' is `new-frame', the last buffer
5557 is kept so that you can work with several indirect buffers at the same time.
5558 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
5559 requests that a new frame be made for the new buffer, so that the dedicated
5560 frame is not changed."
5561 (interactive "P")
5562 (let ((cbuf (current-buffer))
5563 (cwin (selected-window))
5564 (pos (point))
5565 beg end level heading ibuf)
5566 (save-excursion
5567 (org-back-to-heading t)
5568 (when (numberp arg)
5569 (setq level (org-outline-level))
5570 (if (< arg 0) (setq arg (+ level arg)))
5571 (while (> (setq level (org-outline-level)) arg)
5572 (outline-up-heading 1 t)))
5573 (setq beg (point)
5574 heading (org-get-heading))
5575 (org-end-of-subtree t) (setq end (point)))
5576 (if (and (buffer-live-p org-last-indirect-buffer)
5577 (not (eq org-indirect-buffer-display 'new-frame))
5578 (not arg))
5579 (kill-buffer org-last-indirect-buffer))
5580 (setq ibuf (org-get-indirect-buffer cbuf)
5581 org-last-indirect-buffer ibuf)
5582 (cond
5583 ((or (eq org-indirect-buffer-display 'new-frame)
5584 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
5585 (select-frame (make-frame))
5586 (delete-other-windows)
5587 (switch-to-buffer ibuf)
5588 (org-set-frame-title heading))
5589 ((eq org-indirect-buffer-display 'dedicated-frame)
5590 (raise-frame
5591 (select-frame (or (and org-indirect-dedicated-frame
5592 (frame-live-p org-indirect-dedicated-frame)
5593 org-indirect-dedicated-frame)
5594 (setq org-indirect-dedicated-frame (make-frame)))))
5595 (delete-other-windows)
5596 (switch-to-buffer ibuf)
5597 (org-set-frame-title (concat "Indirect: " heading)))
5598 ((eq org-indirect-buffer-display 'current-window)
5599 (switch-to-buffer ibuf))
5600 ((eq org-indirect-buffer-display 'other-window)
5601 (pop-to-buffer ibuf))
5602 (t (error "Invalid value.")))
5603 (if (featurep 'xemacs)
5604 (save-excursion (org-mode) (turn-on-font-lock)))
5605 (narrow-to-region beg end)
5606 (show-all)
5607 (goto-char pos)
5608 (and (window-live-p cwin) (select-window cwin))))
5609
5610 (defun org-get-indirect-buffer (&optional buffer)
5611 (setq buffer (or buffer (current-buffer)))
5612 (let ((n 1) (base (buffer-name buffer)) bname)
5613 (while (buffer-live-p
5614 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
5615 (setq n (1+ n)))
5616 (condition-case nil
5617 (make-indirect-buffer buffer bname 'clone)
5618 (error (make-indirect-buffer buffer bname)))))
5619
5620 (defun org-set-frame-title (title)
5621 "Set the title of the current frame to the string TITLE."
5622 ;; FIXME: how to name a single frame in XEmacs???
5623 (unless (featurep 'xemacs)
5624 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
5625
5626 ;;;; Structure editing
5627
5628 ;;; Inserting headlines
5629
5630 (defun org-previous-line-empty-p ()
5631 (save-excursion
5632 (and (not (bobp))
5633 (or (beginning-of-line 0) t)
5634 (save-match-data
5635 (looking-at "[ \t]*$")))))
5636
5637 (defun org-insert-heading (&optional force-heading)
5638 "Insert a new heading or item with same depth at point.
5639 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
5640 If point is at the beginning of a headline, insert a sibling before the
5641 current headline. If point is not at the beginning, do not split the line,
5642 but create the new headline after the current line."
5643 (interactive "P")
5644 (if (= (buffer-size) 0)
5645 (insert "\n* ")
5646 (when (or force-heading (not (org-insert-item)))
5647 (let* ((empty-line-p nil)
5648 (head (save-excursion
5649 (condition-case nil
5650 (progn
5651 (org-back-to-heading)
5652 (setq empty-line-p (org-previous-line-empty-p))
5653 (match-string 0))
5654 (error "*"))))
5655 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5656 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5657 pos hide-previous previous-pos)
5658 (cond
5659 ((and (org-on-heading-p) (bolp)
5660 (or (bobp)
5661 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5662 ;; insert before the current line
5663 (open-line (if blank 2 1)))
5664 ((and (bolp)
5665 (or (bobp)
5666 (save-excursion
5667 (backward-char 1) (not (org-invisible-p)))))
5668 ;; insert right here
5669 nil)
5670 (t
5671 ;; somewhere in the line
5672 (save-excursion
5673 (setq previous-pos (point-at-bol))
5674 (end-of-line)
5675 (setq hide-previous (org-invisible-p)))
5676 (and org-insert-heading-respect-content (org-show-subtree))
5677 (let ((split
5678 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5679 (save-excursion
5680 (let ((p (point)))
5681 (goto-char (point-at-bol))
5682 (and (looking-at org-complex-heading-regexp)
5683 (> p (match-beginning 4)))))))
5684 tags pos)
5685 (cond
5686 (org-insert-heading-respect-content
5687 (org-end-of-subtree nil t)
5688 (or (bolp) (newline))
5689 (or (org-previous-line-empty-p)
5690 (and blank (newline)))
5691 (open-line 1))
5692 ((org-on-heading-p)
5693 (when hide-previous
5694 (show-children)
5695 (org-show-entry))
5696 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5697 (setq tags (and (match-end 2) (match-string 2)))
5698 (and (match-end 1)
5699 (delete-region (match-beginning 1) (match-end 1)))
5700 (setq pos (point-at-bol))
5701 (or split (end-of-line 1))
5702 (delete-horizontal-space)
5703 (newline (if blank 2 1))
5704 (when tags
5705 (save-excursion
5706 (goto-char pos)
5707 (end-of-line 1)
5708 (insert " " tags)
5709 (org-set-tags nil 'align))))
5710 (t
5711 (or split (end-of-line 1))
5712 (newline (if blank 2 1)))))))
5713 (insert head) (just-one-space)
5714 (setq pos (point))
5715 (end-of-line 1)
5716 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5717 (when (and org-insert-heading-respect-content hide-previous)
5718 (save-excursion
5719 (goto-char previous-pos)
5720 (hide-subtree)))
5721 (run-hooks 'org-insert-heading-hook)))))
5722
5723 (defun org-get-heading (&optional no-tags)
5724 "Return the heading of the current entry, without the stars."
5725 (save-excursion
5726 (org-back-to-heading t)
5727 (if (looking-at
5728 (if no-tags
5729 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5730 "\\*+[ \t]+\\([^\r\n]*\\)"))
5731 (match-string 1) "")))
5732
5733 (defun org-heading-components ()
5734 "Return the components of the current heading.
5735 This is a list with the following elements:
5736 - the level as an integer
5737 - the reduced level, different if `org-odd-levels-only' is set.
5738 - the TODO keyword, or nil
5739 - the priority character, like ?A, or nil if no priority is given
5740 - the headline text itself, or the tags string if no headline text
5741 - the tags string, or nil."
5742 (save-excursion
5743 (org-back-to-heading t)
5744 (if (looking-at org-complex-heading-regexp)
5745 (list (length (match-string 1))
5746 (org-reduced-level (length (match-string 1)))
5747 (org-match-string-no-properties 2)
5748 (and (match-end 3) (aref (match-string 3) 2))
5749 (org-match-string-no-properties 4)
5750 (org-match-string-no-properties 5)))))
5751
5752 (defun org-get-entry ()
5753 "Get the entry text, after heading, entire subtree."
5754 (save-excursion
5755 (org-back-to-heading t)
5756 (buffer-substring (point-at-bol 2) (org-end-of-subtree t))))
5757
5758 (defun org-insert-heading-after-current ()
5759 "Insert a new heading with same level as current, after current subtree."
5760 (interactive)
5761 (org-back-to-heading)
5762 (org-insert-heading)
5763 (org-move-subtree-down)
5764 (end-of-line 1))
5765
5766 (defun org-insert-heading-respect-content ()
5767 (interactive)
5768 (let ((org-insert-heading-respect-content t))
5769 (org-insert-heading t)))
5770
5771 (defun org-insert-todo-heading-respect-content (&optional force-state)
5772 (interactive "P")
5773 (let ((org-insert-heading-respect-content t))
5774 (org-insert-todo-heading force-state t)))
5775
5776 (defun org-insert-todo-heading (arg &optional force-heading)
5777 "Insert a new heading with the same level and TODO state as current heading.
5778 If the heading has no TODO state, or if the state is DONE, use the first
5779 state (TODO by default). Also with prefix arg, force first state."
5780 (interactive "P")
5781 (when (or force-heading (not (org-insert-item 'checkbox)))
5782 (org-insert-heading force-heading)
5783 (save-excursion
5784 (org-back-to-heading)
5785 (outline-previous-heading)
5786 (looking-at org-todo-line-regexp))
5787 (let*
5788 ((new-mark-x
5789 (if (or arg
5790 (not (match-beginning 2))
5791 (member (match-string 2) org-done-keywords))
5792 (car org-todo-keywords-1)
5793 (match-string 2)))
5794 (new-mark
5795 (or
5796 (run-hook-with-args-until-success
5797 'org-todo-get-default-hook new-mark-x nil)
5798 new-mark-x)))
5799 (beginning-of-line 1)
5800 (and (looking-at "\\*+ ") (goto-char (match-end 0))
5801 (if org-treat-insert-todo-heading-as-state-change
5802 (org-todo new-mark)
5803 (insert new-mark " "))))
5804 (when org-provide-todo-statistics
5805 (org-update-parent-todo-statistics))))
5806
5807 (defun org-insert-subheading (arg)
5808 "Insert a new subheading and demote it.
5809 Works for outline headings and for plain lists alike."
5810 (interactive "P")
5811 (org-insert-heading arg)
5812 (cond
5813 ((org-on-heading-p) (org-do-demote))
5814 ((org-at-item-p) (org-indent-item 1))))
5815
5816 (defun org-insert-todo-subheading (arg)
5817 "Insert a new subheading with TODO keyword or checkbox and demote it.
5818 Works for outline headings and for plain lists alike."
5819 (interactive "P")
5820 (org-insert-todo-heading arg)
5821 (cond
5822 ((org-on-heading-p) (org-do-demote))
5823 ((org-at-item-p) (org-indent-item 1))))
5824
5825 ;;; Promotion and Demotion
5826
5827 (defvar org-after-demote-entry-hook nil
5828 "Hook run after an entry has been demoted.
5829 The cursor will be at the beginning of the entry.
5830 When a subtree is being demoted, the hook will be called for each node.")
5831
5832 (defvar org-after-promote-entry-hook nil
5833 "Hook run after an entry has been promoted.
5834 The cursor will be at the beginning of the entry.
5835 When a subtree is being promoted, the hook will be called for each node.")
5836
5837 (defun org-promote-subtree ()
5838 "Promote the entire subtree.
5839 See also `org-promote'."
5840 (interactive)
5841 (save-excursion
5842 (org-map-tree 'org-promote))
5843 (org-fix-position-after-promote))
5844
5845 (defun org-demote-subtree ()
5846 "Demote the entire subtree. See `org-demote'.
5847 See also `org-promote'."
5848 (interactive)
5849 (save-excursion
5850 (org-map-tree 'org-demote))
5851 (org-fix-position-after-promote))
5852
5853
5854 (defun org-do-promote ()
5855 "Promote the current heading higher up the tree.
5856 If the region is active in `transient-mark-mode', promote all headings
5857 in the region."
5858 (interactive)
5859 (save-excursion
5860 (if (org-region-active-p)
5861 (org-map-region 'org-promote (region-beginning) (region-end))
5862 (org-promote)))
5863 (org-fix-position-after-promote))
5864
5865 (defun org-do-demote ()
5866 "Demote the current heading lower down the tree.
5867 If the region is active in `transient-mark-mode', demote all headings
5868 in the region."
5869 (interactive)
5870 (save-excursion
5871 (if (org-region-active-p)
5872 (org-map-region 'org-demote (region-beginning) (region-end))
5873 (org-demote)))
5874 (org-fix-position-after-promote))
5875
5876 (defun org-fix-position-after-promote ()
5877 "Make sure that after pro/demotion cursor position is right."
5878 (let ((pos (point)))
5879 (when (save-excursion
5880 (beginning-of-line 1)
5881 (looking-at org-todo-line-regexp)
5882 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5883 (cond ((eobp) (insert " "))
5884 ((eolp) (insert " "))
5885 ((equal (char-after) ?\ ) (forward-char 1))))))
5886
5887 (defun org-reduced-level (l)
5888 "Compute the effective level of a heading.
5889 This takes into account the setting of `org-odd-levels-only'."
5890 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5891
5892 (defun org-get-valid-level (level &optional change)
5893 "Rectify a level change under the influence of `org-odd-levels-only'
5894 LEVEL is a current level, CHANGE is by how much the level should be
5895 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5896 even level numbers will become the next higher odd number."
5897 (if org-odd-levels-only
5898 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5899 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5900 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5901 (max 1 (+ level (or change 0)))))
5902
5903 (if (boundp 'define-obsolete-function-alias)
5904 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5905 (define-obsolete-function-alias 'org-get-legal-level
5906 'org-get-valid-level)
5907 (define-obsolete-function-alias 'org-get-legal-level
5908 'org-get-valid-level "23.1")))
5909
5910 (defun org-promote ()
5911 "Promote the current heading higher up the tree.
5912 If the region is active in `transient-mark-mode', promote all headings
5913 in the region."
5914 (org-back-to-heading t)
5915 (let* ((level (save-match-data (funcall outline-level)))
5916 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5917 (diff (abs (- level (length up-head) -1))))
5918 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5919 (replace-match up-head nil t)
5920 ;; Fixup tag positioning
5921 (and org-auto-align-tags (org-set-tags nil t))
5922 (if org-adapt-indentation (org-fixup-indentation (- diff)))
5923 (run-hooks 'org-after-promote-entry-hook)))
5924
5925 (defun org-demote ()
5926 "Demote the current heading lower down the tree.
5927 If the region is active in `transient-mark-mode', demote all headings
5928 in the region."
5929 (org-back-to-heading t)
5930 (let* ((level (save-match-data (funcall outline-level)))
5931 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5932 (diff (abs (- level (length down-head) -1))))
5933 (replace-match down-head nil t)
5934 ;; Fixup tag positioning
5935 (and org-auto-align-tags (org-set-tags nil t))
5936 (if org-adapt-indentation (org-fixup-indentation diff))
5937 (run-hooks 'org-after-demote-entry-hook)))
5938
5939 (defun org-map-tree (fun)
5940 "Call FUN for every heading underneath the current one."
5941 (org-back-to-heading)
5942 (let ((level (funcall outline-level)))
5943 (save-excursion
5944 (funcall fun)
5945 (while (and (progn
5946 (outline-next-heading)
5947 (> (funcall outline-level) level))
5948 (not (eobp)))
5949 (funcall fun)))))
5950
5951 (defun org-map-region (fun beg end)
5952 "Call FUN for every heading between BEG and END."
5953 (let ((org-ignore-region t))
5954 (save-excursion
5955 (setq end (copy-marker end))
5956 (goto-char beg)
5957 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5958 (< (point) end))
5959 (funcall fun))
5960 (while (and (progn
5961 (outline-next-heading)
5962 (< (point) end))
5963 (not (eobp)))
5964 (funcall fun)))))
5965
5966 (defun org-fixup-indentation (diff)
5967 "Change the indentation in the current entry by DIFF
5968 However, if any line in the current entry has no indentation, or if it
5969 would end up with no indentation after the change, nothing at all is done."
5970 (save-excursion
5971 (let ((end (save-excursion (outline-next-heading)
5972 (point-marker)))
5973 (prohibit (if (> diff 0)
5974 "^\\S-"
5975 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5976 col)
5977 (unless (save-excursion (end-of-line 1)
5978 (re-search-forward prohibit end t))
5979 (while (and (< (point) end)
5980 (re-search-forward "^[ \t]+" end t))
5981 (goto-char (match-end 0))
5982 (setq col (current-column))
5983 (if (< diff 0) (replace-match ""))
5984 (org-indent-to-column (+ diff col))))
5985 (move-marker end nil))))
5986
5987 (defun org-convert-to-odd-levels ()
5988 "Convert an org-mode file with all levels allowed to one with odd levels.
5989 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5990 level 5 etc."
5991 (interactive)
5992 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5993 (let ((org-odd-levels-only nil) n)
5994 (save-excursion
5995 (goto-char (point-min))
5996 (while (re-search-forward "^\\*\\*+ " nil t)
5997 (setq n (- (length (match-string 0)) 2))
5998 (while (>= (setq n (1- n)) 0)
5999 (org-demote))
6000 (end-of-line 1))))))
6001
6002
6003 (defun org-convert-to-oddeven-levels ()
6004 "Convert an org-mode file with only odd levels to one with odd and even levels.
6005 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
6006 section with an even level, conversion would destroy the structure of the file. An error
6007 is signaled in this case."
6008 (interactive)
6009 (goto-char (point-min))
6010 ;; First check if there are no even levels
6011 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
6012 (org-show-context t)
6013 (error "Not all levels are odd in this file. Conversion not possible."))
6014 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
6015 (let ((org-odd-levels-only nil) n)
6016 (save-excursion
6017 (goto-char (point-min))
6018 (while (re-search-forward "^\\*\\*+ " nil t)
6019 (setq n (/ (1- (length (match-string 0))) 2))
6020 (while (>= (setq n (1- n)) 0)
6021 (org-promote))
6022 (end-of-line 1))))))
6023
6024 (defun org-tr-level (n)
6025 "Make N odd if required."
6026 (if org-odd-levels-only (1+ (/ n 2)) n))
6027
6028 ;;; Vertical tree motion, cutting and pasting of subtrees
6029
6030 (defun org-move-subtree-up (&optional arg)
6031 "Move the current subtree up past ARG headlines of the same level."
6032 (interactive "p")
6033 (org-move-subtree-down (- (prefix-numeric-value arg))))
6034
6035 (defun org-move-subtree-down (&optional arg)
6036 "Move the current subtree down past ARG headlines of the same level."
6037 (interactive "p")
6038 (setq arg (prefix-numeric-value arg))
6039 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
6040 'outline-get-last-sibling))
6041 (ins-point (make-marker))
6042 (cnt (abs arg))
6043 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
6044 ;; Select the tree
6045 (org-back-to-heading)
6046 (setq beg0 (point))
6047 (save-excursion
6048 (setq ne-beg (org-back-over-empty-lines))
6049 (setq beg (point)))
6050 (save-match-data
6051 (save-excursion (outline-end-of-heading)
6052 (setq folded (org-invisible-p)))
6053 (outline-end-of-subtree))
6054 (outline-next-heading)
6055 (setq ne-end (org-back-over-empty-lines))
6056 (setq end (point))
6057 (goto-char beg0)
6058 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
6059 ;; include less whitespace
6060 (save-excursion
6061 (goto-char beg)
6062 (forward-line (- ne-beg ne-end))
6063 (setq beg (point))))
6064 ;; Find insertion point, with error handling
6065 (while (> cnt 0)
6066 (or (and (funcall movfunc) (looking-at outline-regexp))
6067 (progn (goto-char beg0)
6068 (error "Cannot move past superior level or buffer limit")))
6069 (setq cnt (1- cnt)))
6070 (if (> arg 0)
6071 ;; Moving forward - still need to move over subtree
6072 (progn (org-end-of-subtree t t)
6073 (save-excursion
6074 (org-back-over-empty-lines)
6075 (or (bolp) (newline)))))
6076 (setq ne-ins (org-back-over-empty-lines))
6077 (move-marker ins-point (point))
6078 (setq txt (buffer-substring beg end))
6079 (org-save-markers-in-region beg end)
6080 (delete-region beg end)
6081 (org-remove-empty-overlays-at beg)
6082 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
6083 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
6084 (and (not (bolp)) (looking-at "\n") (forward-char 1))
6085 (let ((bbb (point)))
6086 (insert-before-markers txt)
6087 (org-reinstall-markers-in-region bbb)
6088 (move-marker ins-point bbb))
6089 (or (bolp) (insert "\n"))
6090 (setq ins-end (point))
6091 (goto-char ins-point)
6092 (org-skip-whitespace)
6093 (when (and (< arg 0)
6094 (org-first-sibling-p)
6095 (> ne-ins ne-beg))
6096 ;; Move whitespace back to beginning
6097 (save-excursion
6098 (goto-char ins-end)
6099 (let ((kill-whole-line t))
6100 (kill-line (- ne-ins ne-beg)) (point)))
6101 (insert (make-string (- ne-ins ne-beg) ?\n)))
6102 (move-marker ins-point nil)
6103 (if folded
6104 (hide-subtree)
6105 (org-show-entry)
6106 (show-children)
6107 (org-cycle-hide-drawers 'children))
6108 (org-clean-visibility-after-subtree-move)))
6109
6110 (defvar org-subtree-clip ""
6111 "Clipboard for cut and paste of subtrees.
6112 This is actually only a copy of the kill, because we use the normal kill
6113 ring. We need it to check if the kill was created by `org-copy-subtree'.")
6114
6115 (defvar org-subtree-clip-folded nil
6116 "Was the last copied subtree folded?
6117 This is used to fold the tree back after pasting.")
6118
6119 (defun org-cut-subtree (&optional n)
6120 "Cut the current subtree into the clipboard.
6121 With prefix arg N, cut this many sequential subtrees.
6122 This is a short-hand for marking the subtree and then cutting it."
6123 (interactive "p")
6124 (org-copy-subtree n 'cut))
6125
6126 (defun org-copy-subtree (&optional n cut force-store-markers)
6127 "Cut the current subtree into the clipboard.
6128 With prefix arg N, cut this many sequential subtrees.
6129 This is a short-hand for marking the subtree and then copying it.
6130 If CUT is non-nil, actually cut the subtree.
6131 If FORCE-STORE-MARKERS is non-nil, store the relative locations
6132 of some markers in the region, even if CUT is non-nil. This is
6133 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
6134 (interactive "p")
6135 (let (beg end folded (beg0 (point)))
6136 (if (interactive-p)
6137 (org-back-to-heading nil) ; take what looks like a subtree
6138 (org-back-to-heading t)) ; take what is really there
6139 (org-back-over-empty-lines)
6140 (setq beg (point))
6141 (skip-chars-forward " \t\r\n")
6142 (save-match-data
6143 (save-excursion (outline-end-of-heading)
6144 (setq folded (org-invisible-p)))
6145 (condition-case nil
6146 (org-forward-same-level (1- n) t)
6147 (error nil))
6148 (org-end-of-subtree t t))
6149 (org-back-over-empty-lines)
6150 (setq end (point))
6151 (goto-char beg0)
6152 (when (> end beg)
6153 (setq org-subtree-clip-folded folded)
6154 (when (or cut force-store-markers)
6155 (org-save-markers-in-region beg end))
6156 (if cut (kill-region beg end) (copy-region-as-kill beg end))
6157 (setq org-subtree-clip (current-kill 0))
6158 (message "%s: Subtree(s) with %d characters"
6159 (if cut "Cut" "Copied")
6160 (length org-subtree-clip)))))
6161
6162 (defun org-paste-subtree (&optional level tree for-yank)
6163 "Paste the clipboard as a subtree, with modification of headline level.
6164 The entire subtree is promoted or demoted in order to match a new headline
6165 level.
6166
6167 If the cursor is at the beginning of a headline, the same level as
6168 that headline is used to paste the tree
6169
6170 If not, the new level is derived from the *visible* headings
6171 before and after the insertion point, and taken to be the inferior headline
6172 level of the two. So if the previous visible heading is level 3 and the
6173 next is level 4 (or vice versa), level 4 will be used for insertion.
6174 This makes sure that the subtree remains an independent subtree and does
6175 not swallow low level entries.
6176
6177 You can also force a different level, either by using a numeric prefix
6178 argument, or by inserting the heading marker by hand. For example, if the
6179 cursor is after \"*****\", then the tree will be shifted to level 5.
6180
6181 If optional TREE is given, use this text instead of the kill ring.
6182
6183 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
6184 move back over whitespace before inserting, and move point to the end of
6185 the inserted text when done."
6186 (interactive "P")
6187 (setq tree (or tree (and kill-ring (current-kill 0))))
6188 (unless (org-kill-is-subtree-p tree)
6189 (error "%s"
6190 (substitute-command-keys
6191 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
6192 (let* ((visp (not (org-invisible-p)))
6193 (txt tree)
6194 (^re (concat "^\\(" outline-regexp "\\)"))
6195 (re (concat "\\(" outline-regexp "\\)"))
6196 (^re_ (concat "\\(\\*+\\)[ \t]*"))
6197
6198 (old-level (if (string-match ^re txt)
6199 (- (match-end 0) (match-beginning 0) 1)
6200 -1))
6201 (force-level (cond (level (prefix-numeric-value level))
6202 ((and (looking-at "[ \t]*$")
6203 (string-match
6204 ^re_ (buffer-substring
6205 (point-at-bol) (point))))
6206 (- (match-end 1) (match-beginning 1)))
6207 ((and (bolp)
6208 (looking-at org-outline-regexp))
6209 (- (match-end 0) (point) 1))
6210 (t nil)))
6211 (previous-level (save-excursion
6212 (condition-case nil
6213 (progn
6214 (outline-previous-visible-heading 1)
6215 (if (looking-at re)
6216 (- (match-end 0) (match-beginning 0) 1)
6217 1))
6218 (error 1))))
6219 (next-level (save-excursion
6220 (condition-case nil
6221 (progn
6222 (or (looking-at outline-regexp)
6223 (outline-next-visible-heading 1))
6224 (if (looking-at re)
6225 (- (match-end 0) (match-beginning 0) 1)
6226 1))
6227 (error 1))))
6228 (new-level (or force-level (max previous-level next-level)))
6229 (shift (if (or (= old-level -1)
6230 (= new-level -1)
6231 (= old-level new-level))
6232 0
6233 (- new-level old-level)))
6234 (delta (if (> shift 0) -1 1))
6235 (func (if (> shift 0) 'org-demote 'org-promote))
6236 (org-odd-levels-only nil)
6237 beg end newend)
6238 ;; Remove the forced level indicator
6239 (if force-level
6240 (delete-region (point-at-bol) (point)))
6241 ;; Paste
6242 (beginning-of-line 1)
6243 (unless for-yank (org-back-over-empty-lines))
6244 (setq beg (point))
6245 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
6246 (insert-before-markers txt)
6247 (unless (string-match "\n\\'" txt) (insert "\n"))
6248 (setq newend (point))
6249 (org-reinstall-markers-in-region beg)
6250 (setq end (point))
6251 (goto-char beg)
6252 (skip-chars-forward " \t\n\r")
6253 (setq beg (point))
6254 (if (and (org-invisible-p) visp)
6255 (save-excursion (outline-show-heading)))
6256 ;; Shift if necessary
6257 (unless (= shift 0)
6258 (save-restriction
6259 (narrow-to-region beg end)
6260 (while (not (= shift 0))
6261 (org-map-region func (point-min) (point-max))
6262 (setq shift (+ delta shift)))
6263 (goto-char (point-min))
6264 (setq newend (point-max))))
6265 (when (or (interactive-p) for-yank)
6266 (message "Clipboard pasted as level %d subtree" new-level))
6267 (if (and (not for-yank) ; in this case, org-yank will decide about folding
6268 kill-ring
6269 (eq org-subtree-clip (current-kill 0))
6270 org-subtree-clip-folded)
6271 ;; The tree was folded before it was killed/copied
6272 (hide-subtree))
6273 (and for-yank (goto-char newend))))
6274
6275 (defun org-kill-is-subtree-p (&optional txt)
6276 "Check if the current kill is an outline subtree, or a set of trees.
6277 Returns nil if kill does not start with a headline, or if the first
6278 headline level is not the largest headline level in the tree.
6279 So this will actually accept several entries of equal levels as well,
6280 which is OK for `org-paste-subtree'.
6281 If optional TXT is given, check this string instead of the current kill."
6282 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
6283 (start-level (and kill
6284 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
6285 org-outline-regexp "\\)")
6286 kill)
6287 (- (match-end 2) (match-beginning 2) 1)))
6288 (re (concat "^" org-outline-regexp))
6289 (start (1+ (or (match-beginning 2) -1))))
6290 (if (not start-level)
6291 (progn
6292 nil) ;; does not even start with a heading
6293 (catch 'exit
6294 (while (setq start (string-match re kill (1+ start)))
6295 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
6296 (throw 'exit nil)))
6297 t))))
6298
6299 (defvar org-markers-to-move nil
6300 "Markers that should be moved with a cut-and-paste operation.
6301 Those markers are stored together with their positions relative to
6302 the start of the region.")
6303
6304 (defun org-save-markers-in-region (beg end)
6305 "Check markers in region.
6306 If these markers are between BEG and END, record their position relative
6307 to BEG, so that after moving the block of text, we can put the markers back
6308 into place.
6309 This function gets called just before an entry or tree gets cut from the
6310 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
6311 called immediately, to move the markers with the entries."
6312 (setq org-markers-to-move nil)
6313 (when (featurep 'org-clock)
6314 (org-clock-save-markers-for-cut-and-paste beg end))
6315 (when (featurep 'org-agenda)
6316 (org-agenda-save-markers-for-cut-and-paste beg end)))
6317
6318 (defun org-check-and-save-marker (marker beg end)
6319 "Check if MARKER is between BEG and END.
6320 If yes, remember the marker and the distance to BEG."
6321 (when (and (marker-buffer marker)
6322 (equal (marker-buffer marker) (current-buffer)))
6323 (if (and (>= marker beg) (< marker end))
6324 (push (cons marker (- marker beg)) org-markers-to-move))))
6325
6326 (defun org-reinstall-markers-in-region (beg)
6327 "Move all remembered markers to their position relative to BEG."
6328 (mapc (lambda (x)
6329 (move-marker (car x) (+ beg (cdr x))))
6330 org-markers-to-move)
6331 (setq org-markers-to-move nil))
6332
6333 (defun org-narrow-to-subtree ()
6334 "Narrow buffer to the current subtree."
6335 (interactive)
6336 (save-excursion
6337 (save-match-data
6338 (narrow-to-region
6339 (progn (org-back-to-heading t) (point))
6340 (progn (org-end-of-subtree t) (point))))))
6341
6342 (defun org-clone-subtree-with-time-shift (n &optional shift)
6343 "Clone the task (subtree) at point N times.
6344 The clones will be inserted as siblings.
6345
6346 In interactive use, the user will be prompted for the number of clones
6347 to be produced, and for a time SHIFT, which may be a repeater as used
6348 in time stamps, for example `+3d'.
6349
6350 When a valid repeater is given and the entry contains any time stamps,
6351 the clones will become a sequence in time, with time stamps in the
6352 subtree shifted for each clone produced. If SHIFT is nil or the
6353 empty string, time stamps will be left alone.
6354
6355 If the original subtree did contain time stamps with a repeater,
6356 the following will happen:
6357 - the repeater will be removed in each clone
6358 - an additional clone will be produced, with the current, unshifted
6359 date(s) in the entry.
6360 - the original entry will be placed *after* all the clones, with
6361 repeater intact.
6362 - the start days in the repeater in the original entry will be shifted
6363 to past the last clone.
6364 I this way you can spell out a number of instances of a repeating task,
6365 and still retain the repeater to cover future instances of the task."
6366 (interactive "nNumber of clones to produce: \nsDate shift per clone (e.g. +1w, empty to copy unchanged): ")
6367 (let (beg end template task
6368 shift-n shift-what doshift nmin nmax (n-no-remove -1))
6369 (if (not (and (integerp n) (> n 0)))
6370 (error "Invalid number of replications %s" n))
6371 (if (and (setq doshift (and (stringp shift) (string-match "\\S-" shift)))
6372 (not (string-match "\\`[ \t]*\\+?\\([0-9]+\\)\\([dwmy]\\)[ \t]*\\'"
6373 shift)))
6374 (error "Invalid shift specification %s" shift))
6375 (when doshift
6376 (setq shift-n (string-to-number (match-string 1 shift))
6377 shift-what (cdr (assoc (match-string 2 shift)
6378 '(("d" . day) ("w" . week)
6379 ("m" . month) ("y" . year))))))
6380 (if (eq shift-what 'week) (setq shift-n (* 7 shift-n) shift-what 'day))
6381 (setq nmin 1 nmax n)
6382 (org-back-to-heading t)
6383 (setq beg (point))
6384 (org-end-of-subtree t t)
6385 (setq end (point))
6386 (setq template (buffer-substring beg end))
6387 (when (and doshift
6388 (string-match "<[^<>\n]+ \\+[0-9]+[dwmy][^<>\n]*>" template))
6389 (delete-region beg end)
6390 (setq end beg)
6391 (setq nmin 0 nmax (1+ nmax) n-no-remove nmax))
6392 (goto-char end)
6393 (loop for n from nmin to nmax do
6394 (if (not doshift)
6395 (setq task template)
6396 (with-temp-buffer
6397 (insert template)
6398 (org-mode)
6399 (goto-char (point-min))
6400 (while (re-search-forward org-ts-regexp-both nil t)
6401 (org-timestamp-change (* n shift-n) shift-what))
6402 (unless (= n n-no-remove)
6403 (goto-char (point-min))
6404 (while (re-search-forward org-ts-regexp nil t)
6405 (save-excursion
6406 (goto-char (match-beginning 0))
6407 (if (looking-at "<[^<>\n]+\\( +\\+[0-9]+[dwmy]\\)")
6408 (delete-region (match-beginning 1) (match-end 1))))))
6409 (setq task (buffer-string))))
6410 (insert task))
6411 (goto-char beg)))
6412
6413 ;;; Outline Sorting
6414
6415 (defun org-sort (with-case)
6416 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
6417 Optional argument WITH-CASE means sort case-sensitively.
6418 With a double prefix argument, also remove duplicate entries."
6419 (interactive "P")
6420 (if (org-at-table-p)
6421 (org-call-with-arg 'org-table-sort-lines with-case)
6422 (org-call-with-arg 'org-sort-entries-or-items with-case)))
6423
6424 (defun org-sort-remove-invisible (s)
6425 (remove-text-properties 0 (length s) org-rm-props s)
6426 (while (string-match org-bracket-link-regexp s)
6427 (setq s (replace-match (if (match-end 2)
6428 (match-string 3 s)
6429 (match-string 1 s)) t t s)))
6430 s)
6431
6432 (defvar org-priority-regexp) ; defined later in the file
6433
6434 (defvar org-after-sorting-entries-or-items-hook nil
6435 "Hook that is run after a bunch of entries or items have been sorted.
6436 When children are sorted, the cursor is in the parent line when this
6437 hook gets called. When a region or a plain list is sorted, the cursor
6438 will be in the first entry of the sorted region/list.")
6439
6440 (defun org-sort-entries-or-items
6441 (&optional with-case sorting-type getkey-func compare-func property)
6442 "Sort entries on a certain level of an outline tree, or plain list items.
6443 If there is an active region, the entries in the region are sorted.
6444 Else, if the cursor is before the first entry, sort the top-level items.
6445 Else, the children of the entry at point are sorted.
6446 If the cursor is at the first item in a plain list, the list items will be
6447 sorted.
6448
6449 Sorting can be alphabetically, numerically, by date/time as given by
6450 a time stamp, by a property or by priority.
6451
6452 The command prompts for the sorting type unless it has been given to the
6453 function through the SORTING-TYPE argument, which needs to a character,
6454 \(?n ?N ?a ?A ?t ?T ?s ?S ?d ?D ?p ?P ?r ?R ?f ?F). Here is the
6455 precise meaning of each character:
6456
6457 n Numerically, by converting the beginning of the entry/item to a number.
6458 a Alphabetically, ignoring the TODO keyword and the priority, if any.
6459 t By date/time, either the first active time stamp in the entry, or, if
6460 none exist, by the first inactive one.
6461 In items, only the first line will be chekced.
6462 s By the scheduled date/time.
6463 d By deadline date/time.
6464 c By creation time, which is assumed to be the first inactive time stamp
6465 at the beginning of a line.
6466 p By priority according to the cookie.
6467 r By the value of a property.
6468
6469 Capital letters will reverse the sort order.
6470
6471 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
6472 called with point at the beginning of the record. It must return either
6473 a string or a number that should serve as the sorting key for that record.
6474
6475 Comparing entries ignores case by default. However, with an optional argument
6476 WITH-CASE, the sorting considers case as well."
6477 (interactive "P")
6478 (let ((case-func (if with-case 'identity 'downcase))
6479 start beg end stars re re2
6480 txt what tmp plain-list-p)
6481 ;; Find beginning and end of region to sort
6482 (cond
6483 ((org-region-active-p)
6484 ;; we will sort the region
6485 (setq end (region-end)
6486 what "region")
6487 (goto-char (region-beginning))
6488 (if (not (org-on-heading-p)) (outline-next-heading))
6489 (setq start (point)))
6490 ((org-at-item-p)
6491 ;; we will sort this plain list
6492 (org-beginning-of-item-list) (setq start (point))
6493 (org-end-of-item-list) (setq end (point))
6494 (goto-char start)
6495 (setq plain-list-p t
6496 what "plain list"))
6497 ((or (org-on-heading-p)
6498 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
6499 ;; we will sort the children of the current headline
6500 (org-back-to-heading)
6501 (setq start (point)
6502 end (progn (org-end-of-subtree t t)
6503 (org-back-over-empty-lines)
6504 (point))
6505 what "children")
6506 (goto-char start)
6507 (show-subtree)
6508 (outline-next-heading))
6509 (t
6510 ;; we will sort the top-level entries in this file
6511 (goto-char (point-min))
6512 (or (org-on-heading-p) (outline-next-heading))
6513 (setq start (point) end (point-max) what "top-level")
6514 (goto-char start)
6515 (show-all)))
6516
6517 (setq beg (point))
6518 (if (>= beg end) (error "Nothing to sort"))
6519
6520 (unless plain-list-p
6521 (looking-at "\\(\\*+\\)")
6522 (setq stars (match-string 1)
6523 re (concat "^" (regexp-quote stars) " +")
6524 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
6525 txt (buffer-substring beg end))
6526 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
6527 (if (and (not (equal stars "*")) (string-match re2 txt))
6528 (error "Region to sort contains a level above the first entry")))
6529
6530 (unless sorting-type
6531 (message
6532 (if plain-list-p
6533 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
6534 "Sort %s: [a]lpha [n]umeric [p]riority p[r]operty todo[o]rder [f]unc
6535 [t]ime [s]cheduled [d]eadline [c]reated
6536 A/N/T/S/D/C/P/O/F means reversed:")
6537 what)
6538 (setq sorting-type (read-char-exclusive))
6539
6540 (and (= (downcase sorting-type) ?f)
6541 (setq getkey-func
6542 (org-ido-completing-read "Sort using function: "
6543 obarray 'fboundp t nil nil))
6544 (setq getkey-func (intern getkey-func)))
6545
6546 (and (= (downcase sorting-type) ?r)
6547 (setq property
6548 (org-ido-completing-read "Property: "
6549 (mapcar 'list (org-buffer-property-keys t))
6550 nil t))))
6551
6552 (message "Sorting entries...")
6553
6554 (save-restriction
6555 (narrow-to-region start end)
6556
6557 (let ((dcst (downcase sorting-type))
6558 (case-fold-search nil)
6559 (now (current-time)))
6560 (sort-subr
6561 (/= dcst sorting-type)
6562 ;; This function moves to the beginning character of the "record" to
6563 ;; be sorted.
6564 (if plain-list-p
6565 (lambda nil
6566 (if (org-at-item-p) t (goto-char (point-max))))
6567 (lambda nil
6568 (if (re-search-forward re nil t)
6569 (goto-char (match-beginning 0))
6570 (goto-char (point-max)))))
6571 ;; This function moves to the last character of the "record" being
6572 ;; sorted.
6573 (if plain-list-p
6574 'org-end-of-item
6575 (lambda nil
6576 (save-match-data
6577 (condition-case nil
6578 (outline-forward-same-level 1)
6579 (error
6580 (goto-char (point-max)))))))
6581
6582 ;; This function returns the value that gets sorted against.
6583 (if plain-list-p
6584 (lambda nil
6585 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
6586 (cond
6587 ((= dcst ?n)
6588 (string-to-number (buffer-substring (match-end 0)
6589 (point-at-eol))))
6590 ((= dcst ?a)
6591 (buffer-substring (match-end 0) (point-at-eol)))
6592 ((= dcst ?t)
6593 (if (or (re-search-forward org-ts-regexp (point-at-eol) t)
6594 (re-search-forward org-ts-regexp-both
6595 (point-at-eol) t))
6596 (org-time-string-to-seconds (match-string 0))
6597 (time-to-seconds now)))
6598 ((= dcst ?f)
6599 (if getkey-func
6600 (progn
6601 (setq tmp (funcall getkey-func))
6602 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6603 tmp)
6604 (error "Invalid key function `%s'" getkey-func)))
6605 (t (error "Invalid sorting type `%c'" sorting-type)))))
6606 (lambda nil
6607 (cond
6608 ((= dcst ?n)
6609 (if (looking-at org-complex-heading-regexp)
6610 (string-to-number (match-string 4))
6611 nil))
6612 ((= dcst ?a)
6613 (if (looking-at org-complex-heading-regexp)
6614 (funcall case-func (match-string 4))
6615 nil))
6616 ((= dcst ?t)
6617 (let ((end (save-excursion (outline-next-heading) (point))))
6618 (if (or (re-search-forward org-ts-regexp end t)
6619 (re-search-forward org-ts-regexp-both end t))
6620 (org-time-string-to-seconds (match-string 0))
6621 (time-to-seconds now))))
6622 ((= dcst ?c)
6623 (let ((end (save-excursion (outline-next-heading) (point))))
6624 (if (re-search-forward
6625 (concat "^[ \t]*\\[" org-ts-regexp1 "\\]")
6626 end t)
6627 (org-time-string-to-seconds (match-string 0))
6628 (time-to-seconds now))))
6629 ((= dcst ?s)
6630 (let ((end (save-excursion (outline-next-heading) (point))))
6631 (if (re-search-forward org-scheduled-time-regexp end t)
6632 (org-time-string-to-seconds (match-string 1))
6633 (time-to-seconds now))))
6634 ((= dcst ?d)
6635 (let ((end (save-excursion (outline-next-heading) (point))))
6636 (if (re-search-forward org-deadline-time-regexp end t)
6637 (org-time-string-to-seconds (match-string 1))
6638 (time-to-seconds now))))
6639 ((= dcst ?p)
6640 (if (re-search-forward org-priority-regexp (point-at-eol) t)
6641 (string-to-char (match-string 2))
6642 org-default-priority))
6643 ((= dcst ?r)
6644 (or (org-entry-get nil property) ""))
6645 ((= dcst ?o)
6646 (if (looking-at org-complex-heading-regexp)
6647 (- 9999 (length (member (match-string 2)
6648 org-todo-keywords-1)))))
6649 ((= dcst ?f)
6650 (if getkey-func
6651 (progn
6652 (setq tmp (funcall getkey-func))
6653 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
6654 tmp)
6655 (error "Invalid key function `%s'" getkey-func)))
6656 (t (error "Invalid sorting type `%c'" sorting-type)))))
6657 nil
6658 (cond
6659 ((= dcst ?a) 'string<)
6660 ((= dcst ?f) compare-func)
6661 ((member dcst '(?p ?t ?s ?d ?c)) '<)
6662 (t nil)))))
6663 (run-hooks 'org-after-sorting-entries-or-items-hook)
6664 (message "Sorting entries...done")))
6665
6666 (defun org-do-sort (table what &optional with-case sorting-type)
6667 "Sort TABLE of WHAT according to SORTING-TYPE.
6668 The user will be prompted for the SORTING-TYPE if the call to this
6669 function does not specify it. WHAT is only for the prompt, to indicate
6670 what is being sorted. The sorting key will be extracted from
6671 the car of the elements of the table.
6672 If WITH-CASE is non-nil, the sorting will be case-sensitive."
6673 (unless sorting-type
6674 (message
6675 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
6676 what)
6677 (setq sorting-type (read-char-exclusive)))
6678 (let ((dcst (downcase sorting-type))
6679 extractfun comparefun)
6680 ;; Define the appropriate functions
6681 (cond
6682 ((= dcst ?n)
6683 (setq extractfun 'string-to-number
6684 comparefun (if (= dcst sorting-type) '< '>)))
6685 ((= dcst ?a)
6686 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
6687 (lambda(x) (downcase (org-sort-remove-invisible x))))
6688 comparefun (if (= dcst sorting-type)
6689 'string<
6690 (lambda (a b) (and (not (string< a b))
6691 (not (string= a b)))))))
6692 ((= dcst ?t)
6693 (setq extractfun
6694 (lambda (x)
6695 (if (or (string-match org-ts-regexp x)
6696 (string-match org-ts-regexp-both x))
6697 (time-to-seconds
6698 (org-time-string-to-time (match-string 0 x)))
6699 0))
6700 comparefun (if (= dcst sorting-type) '< '>)))
6701 (t (error "Invalid sorting type `%c'" sorting-type)))
6702
6703 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
6704 table)
6705 (lambda (a b) (funcall comparefun (car a) (car b))))))
6706
6707
6708 ;;; The orgstruct minor mode
6709
6710 ;; Define a minor mode which can be used in other modes in order to
6711 ;; integrate the org-mode structure editing commands.
6712
6713 ;; This is really a hack, because the org-mode structure commands use
6714 ;; keys which normally belong to the major mode. Here is how it
6715 ;; works: The minor mode defines all the keys necessary to operate the
6716 ;; structure commands, but wraps the commands into a function which
6717 ;; tests if the cursor is currently at a headline or a plain list
6718 ;; item. If that is the case, the structure command is used,
6719 ;; temporarily setting many Org-mode variables like regular
6720 ;; expressions for filling etc. However, when any of those keys is
6721 ;; used at a different location, function uses `key-binding' to look
6722 ;; up if the key has an associated command in another currently active
6723 ;; keymap (minor modes, major mode, global), and executes that
6724 ;; command. There might be problems if any of the keys is otherwise
6725 ;; used as a prefix key.
6726
6727 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6728 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6729 ;; addresses this by checking explicitly for both bindings.
6730
6731 (defvar orgstruct-mode-map (make-sparse-keymap)
6732 "Keymap for the minor `orgstruct-mode'.")
6733
6734 (defvar org-local-vars nil
6735 "List of local variables, for use by `orgstruct-mode'")
6736
6737 ;;;###autoload
6738 (define-minor-mode orgstruct-mode
6739 "Toggle the minor more `orgstruct-mode'.
6740 This mode is for using Org-mode structure commands in other modes.
6741 The following key behave as if Org-mode was active, if the cursor
6742 is on a headline, or on a plain list item (both in the definition
6743 of Org-mode).
6744
6745 M-up Move entry/item up
6746 M-down Move entry/item down
6747 M-left Promote
6748 M-right Demote
6749 M-S-up Move entry/item up
6750 M-S-down Move entry/item down
6751 M-S-left Promote subtree
6752 M-S-right Demote subtree
6753 M-q Fill paragraph and items like in Org-mode
6754 C-c ^ Sort entries
6755 C-c - Cycle list bullet
6756 TAB Cycle item visibility
6757 M-RET Insert new heading/item
6758 S-M-RET Insert new TODO heading / Checkbox item
6759 C-c C-c Set tags / toggle checkbox"
6760 nil " OrgStruct" nil
6761 (org-load-modules-maybe)
6762 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6763
6764 ;;;###autoload
6765 (defun turn-on-orgstruct ()
6766 "Unconditionally turn on `orgstruct-mode'."
6767 (orgstruct-mode 1))
6768
6769 (defun orgstruct++-mode (&optional arg)
6770 "Toggle `orgstruct-mode', the enhanced version of it.
6771 In addition to setting orgstruct-mode, this also exports all indentation
6772 and autofilling variables from org-mode into the buffer. It will also
6773 recognize item context in multiline items.
6774 Note that turning off orgstruct-mode will *not* remove the
6775 indentation/paragraph settings. This can only be done by refreshing the
6776 major mode, for example with \\[normal-mode]."
6777 (interactive "P")
6778 (setq arg (prefix-numeric-value (or arg (if orgstruct-mode -1 1))))
6779 (if (< arg 1)
6780 (orgstruct-mode -1)
6781 (orgstruct-mode 1)
6782 (let (var val)
6783 (mapc
6784 (lambda (x)
6785 (when (string-match
6786 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6787 (symbol-name (car x)))
6788 (setq var (car x) val (nth 1 x))
6789 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6790 org-local-vars)
6791 (org-set-local 'orgstruct-is-++ t))))
6792
6793 (defvar orgstruct-is-++ nil
6794 "Is orgstruct-mode in ++ version in the current-buffer?")
6795 (make-variable-buffer-local 'orgstruct-is-++)
6796
6797 ;;;###autoload
6798 (defun turn-on-orgstruct++ ()
6799 "Unconditionally turn on `orgstruct++-mode'."
6800 (orgstruct++-mode 1))
6801
6802 (defun orgstruct-error ()
6803 "Error when there is no default binding for a structure key."
6804 (interactive)
6805 (error "This key has no function outside structure elements"))
6806
6807 (defun orgstruct-setup ()
6808 "Setup orgstruct keymaps."
6809 (let ((nfunc 0)
6810 (bindings
6811 (list
6812 '([(meta up)] org-metaup)
6813 '([(meta down)] org-metadown)
6814 '([(meta left)] org-metaleft)
6815 '([(meta right)] org-metaright)
6816 '([(meta shift up)] org-shiftmetaup)
6817 '([(meta shift down)] org-shiftmetadown)
6818 '([(meta shift left)] org-shiftmetaleft)
6819 '([(meta shift right)] org-shiftmetaright)
6820 '([?\e (up)] org-metaup)
6821 '([?\e (down)] org-metadown)
6822 '([?\e (left)] org-metaleft)
6823 '([?\e (right)] org-metaright)
6824 '([?\e (shift up)] org-shiftmetaup)
6825 '([?\e (shift down)] org-shiftmetadown)
6826 '([?\e (shift left)] org-shiftmetaleft)
6827 '([?\e (shift right)] org-shiftmetaright)
6828 '([(shift up)] org-shiftup)
6829 '([(shift down)] org-shiftdown)
6830 '([(shift left)] org-shiftleft)
6831 '([(shift right)] org-shiftright)
6832 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6833 '("\M-q" fill-paragraph)
6834 '("\C-c^" org-sort)
6835 '("\C-c-" org-cycle-list-bullet)))
6836 elt key fun cmd)
6837 (while (setq elt (pop bindings))
6838 (setq nfunc (1+ nfunc))
6839 (setq key (org-key (car elt))
6840 fun (nth 1 elt)
6841 cmd (orgstruct-make-binding fun nfunc key))
6842 (org-defkey orgstruct-mode-map key cmd))
6843
6844 ;; Special treatment needed for TAB and RET
6845 (org-defkey orgstruct-mode-map [(tab)]
6846 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6847 (org-defkey orgstruct-mode-map "\C-i"
6848 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6849
6850 (org-defkey orgstruct-mode-map "\M-\C-m"
6851 (orgstruct-make-binding 'org-insert-heading 105
6852 "\M-\C-m" [(meta return)]))
6853 (org-defkey orgstruct-mode-map [(meta return)]
6854 (orgstruct-make-binding 'org-insert-heading 106
6855 [(meta return)] "\M-\C-m"))
6856
6857 (org-defkey orgstruct-mode-map [(shift meta return)]
6858 (orgstruct-make-binding 'org-insert-todo-heading 107
6859 [(meta return)] "\M-\C-m"))
6860
6861 (org-defkey orgstruct-mode-map "\e\C-m"
6862 (orgstruct-make-binding 'org-insert-heading 108
6863 "\e\C-m" [?\e (return)]))
6864 (org-defkey orgstruct-mode-map [?\e (return)]
6865 (orgstruct-make-binding 'org-insert-heading 109
6866 [?\e (return)] "\e\C-m"))
6867 (org-defkey orgstruct-mode-map [?\e (shift return)]
6868 (orgstruct-make-binding 'org-insert-todo-heading 110
6869 [?\e (return)] "\e\C-m"))
6870
6871 (unless org-local-vars
6872 (setq org-local-vars (org-get-local-variables)))
6873
6874 t))
6875
6876 (defun orgstruct-make-binding (fun n &rest keys)
6877 "Create a function for binding in the structure minor mode.
6878 FUN is the command to call inside a table. N is used to create a unique
6879 command name. KEYS are keys that should be checked in for a command
6880 to execute outside of tables."
6881 (eval
6882 (list 'defun
6883 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6884 '(arg)
6885 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6886 "Outside of structure, run the binding of `"
6887 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6888 "'.")
6889 '(interactive "p")
6890 (list 'if
6891 `(org-context-p 'headline 'item
6892 (and orgstruct-is-++
6893 ,(and (memq fun '(org-insert-heading org-insert-todo-heading)) t)
6894 'item-body))
6895 (list 'org-run-like-in-org-mode (list 'quote fun))
6896 (list 'let '(orgstruct-mode)
6897 (list 'call-interactively
6898 (append '(or)
6899 (mapcar (lambda (k)
6900 (list 'key-binding k))
6901 keys)
6902 '('orgstruct-error))))))))
6903
6904 (defun org-context-p (&rest contexts)
6905 "Check if local context is any of CONTEXTS.
6906 Possible values in the list of contexts are `table', `headline', and `item'."
6907 (let ((pos (point)))
6908 (goto-char (point-at-bol))
6909 (prog1 (or (and (memq 'table contexts)
6910 (looking-at "[ \t]*|"))
6911 (and (memq 'headline contexts)
6912 ;;????????? (looking-at "\\*+"))
6913 (looking-at outline-regexp))
6914 (and (memq 'item contexts)
6915 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)"))
6916 (and (memq 'item-body contexts)
6917 (org-in-item-p)))
6918 (goto-char pos))))
6919
6920 (defun org-get-local-variables ()
6921 "Return a list of all local variables in an org-mode buffer."
6922 (let (varlist)
6923 (with-current-buffer (get-buffer-create "*Org tmp*")
6924 (erase-buffer)
6925 (org-mode)
6926 (setq varlist (buffer-local-variables)))
6927 (kill-buffer "*Org tmp*")
6928 (delq nil
6929 (mapcar
6930 (lambda (x)
6931 (setq x
6932 (if (symbolp x)
6933 (list x)
6934 (list (car x) (list 'quote (cdr x)))))
6935 (if (string-match
6936 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6937 (symbol-name (car x)))
6938 x nil))
6939 varlist))))
6940
6941 ;;;###autoload
6942 (defun org-run-like-in-org-mode (cmd)
6943 "Run a command, pretending that the current buffer is in Org-mode.
6944 This will temporarily bind local variables that are typically bound in
6945 Org-mode to the values they have in Org-mode, and then interactively
6946 call CMD."
6947 (org-load-modules-maybe)
6948 (unless org-local-vars
6949 (setq org-local-vars (org-get-local-variables)))
6950 (eval (list 'let org-local-vars
6951 (list 'call-interactively (list 'quote cmd)))))
6952
6953 ;;;; Archiving
6954
6955 (defun org-get-category (&optional pos)
6956 "Get the category applying to position POS."
6957 (get-text-property (or pos (point)) 'org-category))
6958
6959 (defun org-refresh-category-properties ()
6960 "Refresh category text properties in the buffer."
6961 (let ((def-cat (cond
6962 ((null org-category)
6963 (if buffer-file-name
6964 (file-name-sans-extension
6965 (file-name-nondirectory buffer-file-name))
6966 "???"))
6967 ((symbolp org-category) (symbol-name org-category))
6968 (t org-category)))
6969 beg end cat pos optionp)
6970 (org-unmodified
6971 (save-excursion
6972 (save-restriction
6973 (widen)
6974 (goto-char (point-min))
6975 (put-text-property (point) (point-max) 'org-category def-cat)
6976 (while (re-search-forward
6977 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6978 (setq pos (match-end 0)
6979 optionp (equal (char-after (match-beginning 0)) ?#)
6980 cat (org-trim (match-string 2)))
6981 (if optionp
6982 (setq beg (point-at-bol) end (point-max))
6983 (org-back-to-heading t)
6984 (setq beg (point) end (org-end-of-subtree t t)))
6985 (put-text-property beg end 'org-category cat)
6986 (goto-char pos)))))))
6987
6988
6989 ;;;; Link Stuff
6990
6991 ;;; Link abbreviations
6992
6993 (defun org-link-expand-abbrev (link)
6994 "Apply replacements as defined in `org-link-abbrev-alist."
6995 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6996 (let* ((key (match-string 1 link))
6997 (as (or (assoc key org-link-abbrev-alist-local)
6998 (assoc key org-link-abbrev-alist)))
6999 (tag (and (match-end 2) (match-string 3 link)))
7000 rpl)
7001 (if (not as)
7002 link
7003 (setq rpl (cdr as))
7004 (cond
7005 ((symbolp rpl) (funcall rpl tag))
7006 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
7007 ((string-match "%h" rpl)
7008 (replace-match (url-hexify-string (or tag "")) t t rpl))
7009 (t (concat rpl tag)))))
7010 link))
7011
7012 ;;; Storing and inserting links
7013
7014 (defvar org-insert-link-history nil
7015 "Minibuffer history for links inserted with `org-insert-link'.")
7016
7017 (defvar org-stored-links nil
7018 "Contains the links stored with `org-store-link'.")
7019
7020 (defvar org-store-link-plist nil
7021 "Plist with info about the most recently link created with `org-store-link'.")
7022
7023 (defvar org-link-protocols nil
7024 "Link protocols added to Org-mode using `org-add-link-type'.")
7025
7026 (defvar org-store-link-functions nil
7027 "List of functions that are called to create and store a link.
7028 Each function will be called in turn until one returns a non-nil
7029 value. Each function should check if it is responsible for creating
7030 this link (for example by looking at the major mode).
7031 If not, it must exit and return nil.
7032 If yes, it should return a non-nil value after a calling
7033 `org-store-link-props' with a list of properties and values.
7034 Special properties are:
7035
7036 :type The link prefix. like \"http\". This must be given.
7037 :link The link, like \"http://www.astro.uva.nl/~dominik\".
7038 This is obligatory as well.
7039 :description Optional default description for the second pair
7040 of brackets in an Org-mode link. The user can still change
7041 this when inserting this link into an Org-mode buffer.
7042
7043 In addition to these, any additional properties can be specified
7044 and then used in remember templates.")
7045
7046 (defun org-add-link-type (type &optional follow export)
7047 "Add TYPE to the list of `org-link-types'.
7048 Re-compute all regular expressions depending on `org-link-types'
7049
7050 FOLLOW and EXPORT are two functions.
7051
7052 FOLLOW should take the link path as the single argument and do whatever
7053 is necessary to follow the link, for example find a file or display
7054 a mail message.
7055
7056 EXPORT should format the link path for export to one of the export formats.
7057 It should be a function accepting three arguments:
7058
7059 path the path of the link, the text after the prefix (like \"http:\")
7060 desc the description of the link, if any, nil if there was no description
7061 format the export format, a symbol like `html' or `latex'.
7062
7063 The function may use the FORMAT information to return different values
7064 depending on the format. The return value will be put literally into
7065 the exported file.
7066 Org-mode has a built-in default for exporting links. If you are happy with
7067 this default, there is no need to define an export function for the link
7068 type. For a simple example of an export function, see `org-bbdb.el'."
7069 (add-to-list 'org-link-types type t)
7070 (org-make-link-regexps)
7071 (if (assoc type org-link-protocols)
7072 (setcdr (assoc type org-link-protocols) (list follow export))
7073 (push (list type follow export) org-link-protocols)))
7074
7075 ;;;###autoload
7076 (defun org-store-link (arg)
7077 "\\<org-mode-map>Store an org-link to the current location.
7078 This link is added to `org-stored-links' and can later be inserted
7079 into an org-buffer with \\[org-insert-link].
7080
7081 For some link types, a prefix arg is interpreted:
7082 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
7083 For file links, arg negates `org-context-in-file-links'."
7084 (interactive "P")
7085 (org-load-modules-maybe)
7086 (setq org-store-link-plist nil) ; reset
7087 (let ((outline-regexp (org-get-limited-outline-regexp))
7088 link cpltxt desc description search txt custom-id)
7089 (cond
7090
7091 ((run-hook-with-args-until-success 'org-store-link-functions)
7092 (setq link (plist-get org-store-link-plist :link)
7093 desc (or (plist-get org-store-link-plist :description) link)))
7094
7095 ((equal (buffer-name) "*Org Edit Src Example*")
7096 (let (label gc)
7097 (while (or (not label)
7098 (save-excursion
7099 (save-restriction
7100 (widen)
7101 (goto-char (point-min))
7102 (re-search-forward
7103 (regexp-quote (format org-coderef-label-format label))
7104 nil t))))
7105 (when label (message "Label exists already") (sit-for 2))
7106 (setq label (read-string "Code line label: " label)))
7107 (end-of-line 1)
7108 (setq link (format org-coderef-label-format label))
7109 (setq gc (- 79 (length link)))
7110 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
7111 (insert link)
7112 (setq link (concat "(" label ")") desc nil)))
7113
7114 ((eq major-mode 'calendar-mode)
7115 (let ((cd (calendar-cursor-to-date)))
7116 (setq link
7117 (format-time-string
7118 (car org-time-stamp-formats)
7119 (apply 'encode-time
7120 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
7121 nil nil nil))))
7122 (org-store-link-props :type "calendar" :date cd)))
7123
7124 ((eq major-mode 'w3-mode)
7125 (setq cpltxt (if (and (buffer-name)
7126 (not (string-match "Untitled" (buffer-name))))
7127 (buffer-name)
7128 (url-view-url t))
7129 link (org-make-link (url-view-url t)))
7130 (org-store-link-props :type "w3" :url (url-view-url t)))
7131
7132 ((eq major-mode 'w3m-mode)
7133 (setq cpltxt (or w3m-current-title w3m-current-url)
7134 link (org-make-link w3m-current-url))
7135 (org-store-link-props :type "w3m" :url (url-view-url t)))
7136
7137 ((setq search (run-hook-with-args-until-success
7138 'org-create-file-search-functions))
7139 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
7140 "::" search))
7141 (setq cpltxt (or description link)))
7142
7143 ((eq major-mode 'image-mode)
7144 (setq cpltxt (concat "file:"
7145 (abbreviate-file-name buffer-file-name))
7146 link (org-make-link cpltxt))
7147 (org-store-link-props :type "image" :file buffer-file-name))
7148
7149 ((eq major-mode 'dired-mode)
7150 ;; link to the file in the current line
7151 (setq cpltxt (concat "file:"
7152 (abbreviate-file-name
7153 (expand-file-name
7154 (dired-get-filename nil t))))
7155 link (org-make-link cpltxt)))
7156
7157 ((and buffer-file-name (org-mode-p))
7158 (setq custom-id (ignore-errors (org-entry-get nil "CUSTOM_ID")))
7159 (cond
7160 ((org-in-regexp "<<\\(.*?\\)>>")
7161 (setq cpltxt
7162 (concat "file:"
7163 (abbreviate-file-name buffer-file-name)
7164 "::" (match-string 1))
7165 link (org-make-link cpltxt)))
7166 ((and (featurep 'org-id)
7167 (or (eq org-link-to-org-use-id t)
7168 (and (eq org-link-to-org-use-id 'create-if-interactive)
7169 (interactive-p))
7170 (and (eq org-link-to-org-use-id 'create-if-interactive-and-no-custom-id)
7171 (interactive-p)
7172 (not custom-id))
7173 (and org-link-to-org-use-id
7174 (condition-case nil
7175 (org-entry-get nil "ID")
7176 (error nil)))))
7177 ;; We can make a link using the ID.
7178 (setq link (condition-case nil
7179 (prog1 (org-id-store-link)
7180 (setq desc (plist-get org-store-link-plist
7181 :description)))
7182 (error
7183 ;; probably before first headline, link to file only
7184 (concat "file:"
7185 (abbreviate-file-name buffer-file-name))))))
7186 (t
7187 ;; Just link to current headline
7188 (setq cpltxt (concat "file:"
7189 (abbreviate-file-name buffer-file-name)))
7190 ;; Add a context search string
7191 (when (org-xor org-context-in-file-links arg)
7192 (setq txt (cond
7193 ((org-on-heading-p) nil)
7194 ((org-region-active-p)
7195 (buffer-substring (region-beginning) (region-end)))
7196 (t nil)))
7197 (when (or (null txt) (string-match "\\S-" txt))
7198 (setq cpltxt
7199 (concat cpltxt "::"
7200 (condition-case nil
7201 (org-make-org-heading-search-string txt)
7202 (error "")))
7203 desc (or (nth 4 (org-heading-components)) "NONE"))))
7204 (if (string-match "::\\'" cpltxt)
7205 (setq cpltxt (substring cpltxt 0 -2)))
7206 (setq link (org-make-link cpltxt)))))
7207
7208 ((buffer-file-name (buffer-base-buffer))
7209 ;; Just link to this file here.
7210 (setq cpltxt (concat "file:"
7211 (abbreviate-file-name
7212 (buffer-file-name (buffer-base-buffer)))))
7213 ;; Add a context string
7214 (when (org-xor org-context-in-file-links arg)
7215 (setq txt (if (org-region-active-p)
7216 (buffer-substring (region-beginning) (region-end))
7217 (buffer-substring (point-at-bol) (point-at-eol))))
7218 ;; Only use search option if there is some text.
7219 (when (string-match "\\S-" txt)
7220 (setq cpltxt
7221 (concat cpltxt "::" (org-make-org-heading-search-string txt))
7222 desc "NONE")))
7223 (setq link (org-make-link cpltxt)))
7224
7225 ((interactive-p)
7226 (error "Cannot link to a buffer which is not visiting a file"))
7227
7228 (t (setq link nil)))
7229
7230 (if (consp link) (setq cpltxt (car link) link (cdr link)))
7231 (setq link (or link cpltxt)
7232 desc (or desc cpltxt))
7233 (if (equal desc "NONE") (setq desc nil))
7234
7235 (if (and (or (interactive-p) executing-kbd-macro) link)
7236 (progn
7237 (setq org-stored-links
7238 (cons (list link desc) org-stored-links))
7239 (message "Stored: %s" (or desc link))
7240 (when custom-id
7241 (setq link (concat "file:" (abbreviate-file-name (buffer-file-name))
7242 "::#" custom-id))
7243 (setq org-stored-links
7244 (cons (list link desc) org-stored-links))))
7245 (and link (org-make-link-string link desc)))))
7246
7247 (defun org-store-link-props (&rest plist)
7248 "Store link properties, extract names and addresses."
7249 (let (x adr)
7250 (when (setq x (plist-get plist :from))
7251 (setq adr (mail-extract-address-components x))
7252 (setq plist (plist-put plist :fromname (car adr)))
7253 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
7254 (when (setq x (plist-get plist :to))
7255 (setq adr (mail-extract-address-components x))
7256 (setq plist (plist-put plist :toname (car adr)))
7257 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
7258 (let ((from (plist-get plist :from))
7259 (to (plist-get plist :to)))
7260 (when (and from to org-from-is-user-regexp)
7261 (setq plist
7262 (plist-put plist :fromto
7263 (if (string-match org-from-is-user-regexp from)
7264 (concat "to %t")
7265 (concat "from %f"))))))
7266 (setq org-store-link-plist plist))
7267
7268 (defun org-add-link-props (&rest plist)
7269 "Add these properties to the link property list."
7270 (let (key value)
7271 (while plist
7272 (setq key (pop plist) value (pop plist))
7273 (setq org-store-link-plist
7274 (plist-put org-store-link-plist key value)))))
7275
7276 (defun org-email-link-description (&optional fmt)
7277 "Return the description part of an email link.
7278 This takes information from `org-store-link-plist' and formats it
7279 according to FMT (default from `org-email-link-description-format')."
7280 (setq fmt (or fmt org-email-link-description-format))
7281 (let* ((p org-store-link-plist)
7282 (to (plist-get p :toaddress))
7283 (from (plist-get p :fromaddress))
7284 (table
7285 (list
7286 (cons "%c" (plist-get p :fromto))
7287 (cons "%F" (plist-get p :from))
7288 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
7289 (cons "%T" (plist-get p :to))
7290 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
7291 (cons "%s" (plist-get p :subject))
7292 (cons "%m" (plist-get p :message-id)))))
7293 (when (string-match "%c" fmt)
7294 ;; Check if the user wrote this message
7295 (if (and org-from-is-user-regexp from to
7296 (save-match-data (string-match org-from-is-user-regexp from)))
7297 (setq fmt (replace-match "to %t" t t fmt))
7298 (setq fmt (replace-match "from %f" t t fmt))))
7299 (org-replace-escapes fmt table)))
7300
7301 (defun org-make-org-heading-search-string (&optional string heading)
7302 "Make search string for STRING or current headline."
7303 (interactive)
7304 (let ((s (or string (org-get-heading))))
7305 (unless (and string (not heading))
7306 ;; We are using a headline, clean up garbage in there.
7307 (if (string-match org-todo-regexp s)
7308 (setq s (replace-match "" t t s)))
7309 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
7310 (setq s (replace-match "" t t s)))
7311 (setq s (org-trim s))
7312 (if (string-match (concat "^\\(" org-quote-string "\\|"
7313 org-comment-string "\\)") s)
7314 (setq s (replace-match "" t t s)))
7315 (while (string-match org-ts-regexp s)
7316 (setq s (replace-match "" t t s))))
7317 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
7318 (setq s (replace-match " " t t s)))
7319 (or string (setq s (concat "*" s))) ; Add * for headlines
7320 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
7321
7322 (defun org-make-link (&rest strings)
7323 "Concatenate STRINGS."
7324 (apply 'concat strings))
7325
7326 (defun org-make-link-string (link &optional description)
7327 "Make a link with brackets, consisting of LINK and DESCRIPTION."
7328 (unless (string-match "\\S-" link)
7329 (error "Empty link"))
7330 (when (stringp description)
7331 ;; Remove brackets from the description, they are fatal.
7332 (while (string-match "\\[" description)
7333 (setq description (replace-match "{" t t description)))
7334 (while (string-match "\\]" description)
7335 (setq description (replace-match "}" t t description))))
7336 (when (equal (org-link-escape link) description)
7337 ;; No description needed, it is identical
7338 (setq description nil))
7339 (when (and (not description)
7340 (not (equal link (org-link-escape link))))
7341 (setq description (org-extract-attributes link)))
7342 (concat "[[" (org-link-escape link) "]"
7343 (if description (concat "[" description "]") "")
7344 "]"))
7345
7346 (defconst org-link-escape-chars
7347 '((?\ . "%20")
7348 (?\[ . "%5B")
7349 (?\] . "%5D")
7350 (?\340 . "%E0") ; `a
7351 (?\342 . "%E2") ; ^a
7352 (?\347 . "%E7") ; ,c
7353 (?\350 . "%E8") ; `e
7354 (?\351 . "%E9") ; 'e
7355 (?\352 . "%EA") ; ^e
7356 (?\356 . "%EE") ; ^i
7357 (?\364 . "%F4") ; ^o
7358 (?\371 . "%F9") ; `u
7359 (?\373 . "%FB") ; ^u
7360 (?\; . "%3B")
7361 (?? . "%3F")
7362 (?= . "%3D")
7363 (?+ . "%2B")
7364 )
7365 "Association list of escapes for some characters problematic in links.
7366 This is the list that is used for internal purposes.")
7367
7368 (defvar org-url-encoding-use-url-hexify nil)
7369
7370 (defconst org-link-escape-chars-browser
7371 '((?\ . "%20")) ; 32 for the SPC char
7372 "Association list of escapes for some characters problematic in links.
7373 This is the list that is used before handing over to the browser.")
7374
7375 (defun org-link-escape (text &optional table)
7376 "Escape characters in TEXT that are problematic for links."
7377 (if org-url-encoding-use-url-hexify
7378 (url-hexify-string text)
7379 (setq table (or table org-link-escape-chars))
7380 (when text
7381 (let ((re (mapconcat (lambda (x) (regexp-quote
7382 (char-to-string (car x))))
7383 table "\\|")))
7384 (while (string-match re text)
7385 (setq text
7386 (replace-match
7387 (cdr (assoc (string-to-char (match-string 0 text))
7388 table))
7389 t t text)))
7390 text))))
7391
7392 (defun org-link-unescape (text &optional table)
7393 "Reverse the action of `org-link-escape'."
7394 (if org-url-encoding-use-url-hexify
7395 (url-unhex-string text)
7396 (setq table (or table org-link-escape-chars))
7397 (when text
7398 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
7399 table "\\|")))
7400 (while (string-match re text)
7401 (setq text
7402 (replace-match
7403 (char-to-string (car (rassoc (match-string 0 text) table)))
7404 t t text)))
7405 text))))
7406
7407 (defun org-xor (a b)
7408 "Exclusive or."
7409 (if a (not b) b))
7410
7411 (defun org-fixup-message-id-for-http (s)
7412 "Replace special characters in a message id, so it can be used in an http query."
7413 (while (string-match "<" s)
7414 (setq s (replace-match "%3C" t t s)))
7415 (while (string-match ">" s)
7416 (setq s (replace-match "%3E" t t s)))
7417 (while (string-match "@" s)
7418 (setq s (replace-match "%40" t t s)))
7419 s)
7420
7421 ;;;###autoload
7422 (defun org-insert-link-global ()
7423 "Insert a link like Org-mode does.
7424 This command can be called in any mode to insert a link in Org-mode syntax."
7425 (interactive)
7426 (org-load-modules-maybe)
7427 (org-run-like-in-org-mode 'org-insert-link))
7428
7429 (defun org-insert-link (&optional complete-file link-location)
7430 "Insert a link. At the prompt, enter the link.
7431
7432 Completion can be used to insert any of the link protocol prefixes like
7433 http or ftp in use.
7434
7435 The history can be used to select a link previously stored with
7436 `org-store-link'. When the empty string is entered (i.e. if you just
7437 press RET at the prompt), the link defaults to the most recently
7438 stored link. As SPC triggers completion in the minibuffer, you need to
7439 use M-SPC or C-q SPC to force the insertion of a space character.
7440
7441 You will also be prompted for a description, and if one is given, it will
7442 be displayed in the buffer instead of the link.
7443
7444 If there is already a link at point, this command will allow you to edit link
7445 and description parts.
7446
7447 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
7448 be selected using completion. The path to the file will be relative to the
7449 current directory if the file is in the current directory or a subdirectory.
7450 Otherwise, the link will be the absolute path as completed in the minibuffer
7451 \(i.e. normally ~/path/to/file). You can configure this behavior using the
7452 option `org-link-file-path-type'.
7453
7454 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
7455 the current directory or below.
7456
7457 With three \\[universal-argument] prefixes, negate the meaning of
7458 `org-keep-stored-link-after-insertion'.
7459
7460 If `org-make-link-description-function' is non-nil, this function will be
7461 called with the link target, and the result will be the default
7462 link description.
7463
7464 If the LINK-LOCATION parameter is non-nil, this value will be
7465 used as the link location instead of reading one interactively."
7466 (interactive "P")
7467 (let* ((wcf (current-window-configuration))
7468 (region (if (org-region-active-p)
7469 (buffer-substring (region-beginning) (region-end))))
7470 (remove (and region (list (region-beginning) (region-end))))
7471 (desc region)
7472 tmphist ; byte-compile incorrectly complains about this
7473 (link link-location)
7474 entry file all-prefixes)
7475 (cond
7476 (link-location) ; specified by arg, just use it.
7477 ((org-in-regexp org-bracket-link-regexp 1)
7478 ;; We do have a link at point, and we are going to edit it.
7479 (setq remove (list (match-beginning 0) (match-end 0)))
7480 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
7481 (setq link (read-string "Link: "
7482 (org-link-unescape
7483 (org-match-string-no-properties 1)))))
7484 ((or (org-in-regexp org-angle-link-re)
7485 (org-in-regexp org-plain-link-re))
7486 ;; Convert to bracket link
7487 (setq remove (list (match-beginning 0) (match-end 0))
7488 link (read-string "Link: "
7489 (org-remove-angle-brackets (match-string 0)))))
7490 ((member complete-file '((4) (16)))
7491 ;; Completing read for file names.
7492 (setq link (org-file-complete-link complete-file)))
7493 (t
7494 ;; Read link, with completion for stored links.
7495 (with-output-to-temp-buffer "*Org Links*"
7496 (princ "Insert a link.
7497 Use TAB to complete link prefixes, then RET for type-specific completion support\n")
7498 (when org-stored-links
7499 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
7500 (princ (mapconcat
7501 (lambda (x)
7502 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
7503 (reverse org-stored-links) "\n"))))
7504 (let ((cw (selected-window)))
7505 (select-window (get-buffer-window "*Org Links*"))
7506 (setq truncate-lines t)
7507 (unless (pos-visible-in-window-p (point-max))
7508 (org-fit-window-to-buffer))
7509 (and (window-live-p cw) (select-window cw)))
7510 ;; Fake a link history, containing the stored links.
7511 (setq tmphist (append (mapcar 'car org-stored-links)
7512 org-insert-link-history))
7513 (setq all-prefixes (append (mapcar 'car org-link-abbrev-alist-local)
7514 (mapcar 'car org-link-abbrev-alist)
7515 org-link-types))
7516 (unwind-protect
7517 (progn
7518 (setq link
7519 (let ((org-completion-use-ido nil))
7520 (org-completing-read
7521 "Link: "
7522 (append
7523 (mapcar (lambda (x) (list (concat x ":")))
7524 all-prefixes)
7525 (mapcar 'car org-stored-links))
7526 nil nil nil
7527 'tmphist
7528 (car (car org-stored-links)))))
7529 (if (or (member link all-prefixes)
7530 (and (equal ":" (substring link -1))
7531 (member (substring link 0 -1) all-prefixes)
7532 (setq link (substring link 0 -1))))
7533 (setq link (org-link-try-special-completion link))))
7534 (set-window-configuration wcf)
7535 (kill-buffer "*Org Links*"))
7536 (setq entry (assoc link org-stored-links))
7537 (or entry (push link org-insert-link-history))
7538 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
7539 (not org-keep-stored-link-after-insertion))
7540 (setq org-stored-links (delq (assoc link org-stored-links)
7541 org-stored-links)))
7542 (setq desc (or desc (nth 1 entry)))))
7543
7544 (if (string-match org-plain-link-re link)
7545 ;; URL-like link, normalize the use of angular brackets.
7546 (setq link (org-make-link (org-remove-angle-brackets link))))
7547
7548 ;; Check if we are linking to the current file with a search option
7549 ;; If yes, simplify the link by using only the search option.
7550 (when (and buffer-file-name
7551 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
7552 (let* ((path (match-string 1 link))
7553 (case-fold-search nil)
7554 (search (match-string 2 link)))
7555 (save-match-data
7556 (if (equal (file-truename buffer-file-name) (file-truename path))
7557 ;; We are linking to this same file, with a search option
7558 (setq link search)))))
7559
7560 ;; Check if we can/should use a relative path. If yes, simplify the link
7561 (when (string-match "^file:\\(.*\\)" link)
7562 (let* ((path (match-string 1 link))
7563 (origpath path)
7564 (case-fold-search nil))
7565 (cond
7566 ((or (eq org-link-file-path-type 'absolute)
7567 (equal complete-file '(16)))
7568 (setq path (abbreviate-file-name (expand-file-name path))))
7569 ((eq org-link-file-path-type 'noabbrev)
7570 (setq path (expand-file-name path)))
7571 ((eq org-link-file-path-type 'relative)
7572 (setq path (file-relative-name path)))
7573 (t
7574 (save-match-data
7575 (if (string-match (concat "^" (regexp-quote
7576 (file-name-as-directory
7577 (expand-file-name "."))))
7578 (expand-file-name path))
7579 ;; We are linking a file with relative path name.
7580 (setq path (substring (expand-file-name path)
7581 (match-end 0)))
7582 (setq path (abbreviate-file-name (expand-file-name path)))))))
7583 (setq link (concat "file:" path))
7584 (if (equal desc origpath)
7585 (setq desc path))))
7586
7587 (if org-make-link-description-function
7588 (setq desc (funcall org-make-link-description-function link desc)))
7589
7590 (setq desc (read-string "Description: " desc))
7591 (unless (string-match "\\S-" desc) (setq desc nil))
7592 (if remove (apply 'delete-region remove))
7593 (insert (org-make-link-string link desc))))
7594
7595 (defun org-link-try-special-completion (type)
7596 "If there is completion support for link type TYPE, offer it."
7597 (let ((fun (intern (concat "org-" type "-complete-link"))))
7598 (if (functionp fun)
7599 (funcall fun)
7600 (read-string "Link (no completion support): " (concat type ":")))))
7601
7602 (defun org-file-complete-link (&optional arg)
7603 "Create a file link using completion."
7604 (let (file link)
7605 (setq file (read-file-name "File: "))
7606 (let ((pwd (file-name-as-directory (expand-file-name ".")))
7607 (pwd1 (file-name-as-directory (abbreviate-file-name
7608 (expand-file-name ".")))))
7609 (cond
7610 ((equal arg '(16))
7611 (setq link (org-make-link
7612 "file:"
7613 (abbreviate-file-name (expand-file-name file)))))
7614 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
7615 (setq link (org-make-link "file:" (match-string 1 file))))
7616 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
7617 (expand-file-name file))
7618 (setq link (org-make-link
7619 "file:" (match-string 1 (expand-file-name file)))))
7620 (t (setq link (org-make-link "file:" file)))))
7621 link))
7622
7623 (defun org-completing-read (&rest args)
7624 "Completing-read with SPACE being a normal character."
7625 (let ((minibuffer-local-completion-map
7626 (copy-keymap minibuffer-local-completion-map)))
7627 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7628 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
7629 (apply 'org-ido-completing-read args)))
7630
7631 (defun org-completing-read-no-ido (&rest args)
7632 (let (org-completion-use-ido)
7633 (apply 'org-completing-read args)))
7634
7635 (defun org-ido-completing-read (&rest args)
7636 "Completing-read using `ido-mode' speedups if available"
7637 (if (and org-completion-use-ido
7638 (fboundp 'ido-completing-read)
7639 (boundp 'ido-mode) ido-mode
7640 (listp (second args)))
7641 (let ((ido-enter-matching-directory nil))
7642 (apply 'ido-completing-read (concat (car args))
7643 (if (consp (car (nth 1 args)))
7644 (mapcar (lambda (x) (car x)) (nth 1 args))
7645 (nth 1 args))
7646 (cddr args)))
7647 (apply 'completing-read args)))
7648
7649 (defun org-extract-attributes (s)
7650 "Extract the attributes cookie from a string and set as text property."
7651 (let (a attr (start 0) key value)
7652 (save-match-data
7653 (when (string-match "{{\\([^}]+\\)}}$" s)
7654 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7655 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7656 (setq key (match-string 1 a) value (match-string 2 a)
7657 start (match-end 0)
7658 attr (plist-put attr (intern key) value))))
7659 (org-add-props s nil 'org-attr attr))
7660 s))
7661
7662 (defun org-extract-attributes-from-string (tag)
7663 (let (key value attr)
7664 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"\\s-?" tag)
7665 (setq key (match-string 1 tag) value (match-string 2 tag)
7666 tag (replace-match "" t t tag)
7667 attr (plist-put attr (intern key) value)))
7668 (cons tag attr)))
7669
7670 (defun org-attributes-to-string (plist)
7671 "Format a property list into an HTML attribute list."
7672 (let ((s "") key value)
7673 (while plist
7674 (setq key (pop plist) value (pop plist))
7675 (and value
7676 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
7677 s))
7678
7679 ;;; Opening/following a link
7680
7681 (defvar org-link-search-failed nil)
7682
7683 (defun org-next-link ()
7684 "Move forward to the next link.
7685 If the link is in hidden text, expose it."
7686 (interactive)
7687 (when (and org-link-search-failed (eq this-command last-command))
7688 (goto-char (point-min))
7689 (message "Link search wrapped back to beginning of buffer"))
7690 (setq org-link-search-failed nil)
7691 (let* ((pos (point))
7692 (ct (org-context))
7693 (a (assoc :link ct)))
7694 (if a (goto-char (nth 2 a)))
7695 (if (re-search-forward org-any-link-re nil t)
7696 (progn
7697 (goto-char (match-beginning 0))
7698 (if (org-invisible-p) (org-show-context)))
7699 (goto-char pos)
7700 (setq org-link-search-failed t)
7701 (error "No further link found"))))
7702
7703 (defun org-previous-link ()
7704 "Move backward to the previous link.
7705 If the link is in hidden text, expose it."
7706 (interactive)
7707 (when (and org-link-search-failed (eq this-command last-command))
7708 (goto-char (point-max))
7709 (message "Link search wrapped back to end of buffer"))
7710 (setq org-link-search-failed nil)
7711 (let* ((pos (point))
7712 (ct (org-context))
7713 (a (assoc :link ct)))
7714 (if a (goto-char (nth 1 a)))
7715 (if (re-search-backward org-any-link-re nil t)
7716 (progn
7717 (goto-char (match-beginning 0))
7718 (if (org-invisible-p) (org-show-context)))
7719 (goto-char pos)
7720 (setq org-link-search-failed t)
7721 (error "No further link found"))))
7722
7723 (defun org-translate-link (s)
7724 "Translate a link string if a translation function has been defined."
7725 (if (and org-link-translation-function
7726 (fboundp org-link-translation-function)
7727 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7728 (progn
7729 (setq s (funcall org-link-translation-function
7730 (match-string 1) (match-string 2)))
7731 (concat (car s) ":" (cdr s)))
7732 s))
7733
7734 (defun org-translate-link-from-planner (type path)
7735 "Translate a link from Emacs Planner syntax so that Org can follow it.
7736 This is still an experimental function, your mileage may vary."
7737 (cond
7738 ((member type '("http" "https" "news" "ftp"))
7739 ;; standard Internet links are the same.
7740 nil)
7741 ((and (equal type "irc") (string-match "^//" path))
7742 ;; Planner has two / at the beginning of an irc link, we have 1.
7743 ;; We should have zero, actually....
7744 (setq path (substring path 1)))
7745 ((and (equal type "lisp") (string-match "^/" path))
7746 ;; Planner has a slash, we do not.
7747 (setq type "elisp" path (substring path 1)))
7748 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7749 ;; A typical message link. Planner has the id after the fina slash,
7750 ;; we separate it with a hash mark
7751 (setq path (concat (match-string 1 path) "#"
7752 (org-remove-angle-brackets (match-string 2 path)))))
7753 )
7754 (cons type path))
7755
7756 (defun org-find-file-at-mouse (ev)
7757 "Open file link or URL at mouse."
7758 (interactive "e")
7759 (mouse-set-point ev)
7760 (org-open-at-point 'in-emacs))
7761
7762 (defun org-open-at-mouse (ev)
7763 "Open file link or URL at mouse."
7764 (interactive "e")
7765 (mouse-set-point ev)
7766 (if (eq major-mode 'org-agenda-mode)
7767 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7768 (org-open-at-point))
7769
7770 (defvar org-window-config-before-follow-link nil
7771 "The window configuration before following a link.
7772 This is saved in case the need arises to restore it.")
7773
7774 (defvar org-open-link-marker (make-marker)
7775 "Marker pointing to the location where `org-open-at-point; was called.")
7776
7777 ;;;###autoload
7778 (defun org-open-at-point-global ()
7779 "Follow a link like Org-mode does.
7780 This command can be called in any mode to follow a link that has
7781 Org-mode syntax."
7782 (interactive)
7783 (org-run-like-in-org-mode 'org-open-at-point))
7784
7785 ;;;###autoload
7786 (defun org-open-link-from-string (s &optional arg)
7787 "Open a link in the string S, as if it was in Org-mode."
7788 (interactive "sLink: \nP")
7789 (let ((reference-buffer (current-buffer)))
7790 (with-temp-buffer
7791 (let ((org-inhibit-startup t))
7792 (org-mode)
7793 (insert s)
7794 (goto-char (point-min))
7795 (org-open-at-point arg reference-buffer)))))
7796
7797 (defun org-open-at-point (&optional in-emacs reference-buffer)
7798 "Open link at or after point.
7799 If there is no link at point, this function will search forward up to
7800 the end of the current line.
7801 Normally, files will be opened by an appropriate application. If the
7802 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7803 With a double prefix argument, try to open outside of Emacs, in the
7804 application the system uses for this file type."
7805 (interactive "P")
7806 (org-load-modules-maybe)
7807 (move-marker org-open-link-marker (point))
7808 (setq org-window-config-before-follow-link (current-window-configuration))
7809 (org-remove-occur-highlights nil nil t)
7810 (cond
7811 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7812 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7813 (org-footnote-action))
7814 (t
7815 (let (type path link line search (pos (point)))
7816 (catch 'match
7817 (save-excursion
7818 (skip-chars-forward "^]\n\r")
7819 (when (org-in-regexp org-bracket-link-regexp)
7820 (setq link (org-extract-attributes
7821 (org-link-unescape (org-match-string-no-properties 1))))
7822 (while (string-match " *\n *" link)
7823 (setq link (replace-match " " t t link)))
7824 (setq link (org-link-expand-abbrev link))
7825 (cond
7826 ((or (file-name-absolute-p link)
7827 (string-match "^\\.\\.?/" link))
7828 (setq type "file" path link))
7829 ((string-match org-link-re-with-space3 link)
7830 (setq type (match-string 1 link) path (match-string 2 link)))
7831 (t (setq type "thisfile" path link)))
7832 (throw 'match t)))
7833
7834 (when (get-text-property (point) 'org-linked-text)
7835 (setq type "thisfile"
7836 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7837 (1+ (point)) (point))
7838 path (buffer-substring
7839 (previous-single-property-change pos 'org-linked-text)
7840 (next-single-property-change pos 'org-linked-text)))
7841 (throw 'match t))
7842
7843 (save-excursion
7844 (when (or (org-in-regexp org-angle-link-re)
7845 (org-in-regexp org-plain-link-re))
7846 (setq type (match-string 1) path (match-string 2))
7847 (throw 'match t)))
7848 (save-excursion
7849 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7850 (setq type "tags"
7851 path (match-string 1))
7852 (while (string-match ":" path)
7853 (setq path (replace-match "+" t t path)))
7854 (throw 'match t)))
7855 (when (org-in-regexp "<\\([^><\n]+\\)>")
7856 (setq type "tree-match"
7857 path (match-string 1))
7858 (throw 'match t)))
7859 (unless path
7860 (error "No link found"))
7861
7862 ;; switch back to reference buffer
7863 ;; needed when if called in a temporary buffer through
7864 ;; org-open-link-from-string
7865 (and reference-buffer (switch-to-buffer reference-buffer))
7866
7867 ;; Remove any trailing spaces in path
7868 (if (string-match " +\\'" path)
7869 (setq path (replace-match "" t t path)))
7870 (if (and org-link-translation-function
7871 (fboundp org-link-translation-function))
7872 ;; Check if we need to translate the link
7873 (let ((tmp (funcall org-link-translation-function type path)))
7874 (setq type (car tmp) path (cdr tmp))))
7875
7876 (cond
7877
7878 ((assoc type org-link-protocols)
7879 (funcall (nth 1 (assoc type org-link-protocols)) path))
7880
7881 ((equal type "mailto")
7882 (let ((cmd (car org-link-mailto-program))
7883 (args (cdr org-link-mailto-program)) args1
7884 (address path) (subject "") a)
7885 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7886 (setq address (match-string 1 path)
7887 subject (org-link-escape (match-string 2 path))))
7888 (while args
7889 (cond
7890 ((not (stringp (car args))) (push (pop args) args1))
7891 (t (setq a (pop args))
7892 (if (string-match "%a" a)
7893 (setq a (replace-match address t t a)))
7894 (if (string-match "%s" a)
7895 (setq a (replace-match subject t t a)))
7896 (push a args1))))
7897 (apply cmd (nreverse args1))))
7898
7899 ((member type '("http" "https" "ftp" "news"))
7900 (browse-url (concat type ":" (org-link-escape
7901 path org-link-escape-chars-browser))))
7902
7903 ((member type '("message"))
7904 (browse-url (concat type ":" path)))
7905
7906 ((string= type "tags")
7907 (org-tags-view in-emacs path))
7908 ((string= type "thisfile")
7909 (if in-emacs
7910 (switch-to-buffer-other-window
7911 (org-get-buffer-for-internal-link (current-buffer)))
7912 (org-mark-ring-push))
7913 (let ((cmd `(org-link-search
7914 ,path
7915 ,(cond ((equal in-emacs '(4)) 'occur)
7916 ((equal in-emacs '(16)) 'org-occur)
7917 (t nil))
7918 ,pos)))
7919 (condition-case nil (eval cmd)
7920 (error (progn (widen) (eval cmd))))))
7921
7922 ((string= type "tree-match")
7923 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7924
7925 ((string= type "file")
7926 (if (string-match "::\\([0-9]+\\)\\'" path)
7927 (setq line (string-to-number (match-string 1 path))
7928 path (substring path 0 (match-beginning 0)))
7929 (if (string-match "::\\(.+\\)\\'" path)
7930 (setq search (match-string 1 path)
7931 path (substring path 0 (match-beginning 0)))))
7932 (if (string-match "[*?{]" (file-name-nondirectory path))
7933 (dired path)
7934 (org-open-file path in-emacs line search)))
7935
7936 ((string= type "news")
7937 (require 'org-gnus)
7938 (org-gnus-follow-link path))
7939
7940 ((string= type "shell")
7941 (let ((cmd path))
7942 (if (or (not org-confirm-shell-link-function)
7943 (funcall org-confirm-shell-link-function
7944 (format "Execute \"%s\" in shell? "
7945 (org-add-props cmd nil
7946 'face 'org-warning))))
7947 (progn
7948 (message "Executing %s" cmd)
7949 (shell-command cmd))
7950 (error "Abort"))))
7951
7952 ((string= type "elisp")
7953 (let ((cmd path))
7954 (if (or (not org-confirm-elisp-link-function)
7955 (funcall org-confirm-elisp-link-function
7956 (format "Execute \"%s\" as elisp? "
7957 (org-add-props cmd nil
7958 'face 'org-warning))))
7959 (message "%s => %s" cmd
7960 (if (equal (string-to-char cmd) ?\()
7961 (eval (read cmd))
7962 (call-interactively (read cmd))))
7963 (error "Abort"))))
7964
7965 (t
7966 (browse-url-at-point))))))
7967 (move-marker org-open-link-marker nil)
7968 (run-hook-with-args 'org-follow-link-hook))
7969
7970 ;;;; Time estimates
7971
7972 (defun org-get-effort (&optional pom)
7973 "Get the effort estimate for the current entry."
7974 (org-entry-get pom org-effort-property))
7975
7976 ;;; File search
7977
7978 (defvar org-create-file-search-functions nil
7979 "List of functions to construct the right search string for a file link.
7980 These functions are called in turn with point at the location to
7981 which the link should point.
7982
7983 A function in the hook should first test if it would like to
7984 handle this file type, for example by checking the major-mode or
7985 the file extension. If it decides not to handle this file, it
7986 should just return nil to give other functions a chance. If it
7987 does handle the file, it must return the search string to be used
7988 when following the link. The search string will be part of the
7989 file link, given after a double colon, and `org-open-at-point'
7990 will automatically search for it. If special measures must be
7991 taken to make the search successful, another function should be
7992 added to the companion hook `org-execute-file-search-functions',
7993 which see.
7994
7995 A function in this hook may also use `setq' to set the variable
7996 `description' to provide a suggestion for the descriptive text to
7997 be used for this link when it gets inserted into an Org-mode
7998 buffer with \\[org-insert-link].")
7999
8000 (defvar org-execute-file-search-functions nil
8001 "List of functions to execute a file search triggered by a link.
8002
8003 Functions added to this hook must accept a single argument, the
8004 search string that was part of the file link, the part after the
8005 double colon. The function must first check if it would like to
8006 handle this search, for example by checking the major-mode or the
8007 file extension. If it decides not to handle this search, it
8008 should just return nil to give other functions a chance. If it
8009 does handle the search, it must return a non-nil value to keep
8010 other functions from trying.
8011
8012 Each function can access the current prefix argument through the
8013 variable `current-prefix-argument'. Note that a single prefix is
8014 used to force opening a link in Emacs, so it may be good to only
8015 use a numeric or double prefix to guide the search function.
8016
8017 In case this is needed, a function in this hook can also restore
8018 the window configuration before `org-open-at-point' was called using:
8019
8020 (set-window-configuration org-window-config-before-follow-link)")
8021
8022 (defun org-link-search (s &optional type avoid-pos)
8023 "Search for a link search option.
8024 If S is surrounded by forward slashes, it is interpreted as a
8025 regular expression. In org-mode files, this will create an `org-occur'
8026 sparse tree. In ordinary files, `occur' will be used to list matches.
8027 If the current buffer is in `dired-mode', grep will be used to search
8028 in all files. If AVOID-POS is given, ignore matches near that position."
8029 (let ((case-fold-search t)
8030 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
8031 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
8032 (append '(("") (" ") ("\t") ("\n"))
8033 org-emphasis-alist)
8034 "\\|") "\\)"))
8035 (pos (point))
8036 (pre nil) (post nil)
8037 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
8038 (cond
8039 ;; First check if there are any special
8040 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
8041 ;; Now try the builtin stuff
8042 ((and (equal (string-to-char s0) ?#)
8043 (> (length s0) 1)
8044 (save-excursion
8045 (goto-char (point-min))
8046 (and
8047 (re-search-forward
8048 (concat "^[ \t]*:CUSTOM_ID:[ \t]+" (regexp-quote (substring s0 1)) "[ \t]*$") nil t)
8049 (setq type 'dedicated
8050 pos (match-beginning 0))))
8051 ;; There is an exact target for this
8052 (goto-char pos)
8053 (org-back-to-heading t)))
8054 ((save-excursion
8055 (goto-char (point-min))
8056 (and
8057 (re-search-forward
8058 (concat "<<" (regexp-quote s0) ">>") nil t)
8059 (setq type 'dedicated
8060 pos (match-beginning 0))))
8061 ;; There is an exact target for this
8062 (goto-char pos))
8063 ((and (string-match "^(\\(.*\\))$" s0)
8064 (save-excursion
8065 (goto-char (point-min))
8066 (and
8067 (re-search-forward
8068 (concat "[^[]" (regexp-quote
8069 (format org-coderef-label-format
8070 (match-string 1 s0))))
8071 nil t)
8072 (setq type 'dedicated
8073 pos (1+ (match-beginning 0))))))
8074 ;; There is a coderef target for this
8075 (goto-char pos))
8076 ((string-match "^/\\(.*\\)/$" s)
8077 ;; A regular expression
8078 (cond
8079 ((org-mode-p)
8080 (org-occur (match-string 1 s)))
8081 ;;((eq major-mode 'dired-mode)
8082 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
8083 (t (org-do-occur (match-string 1 s)))))
8084 (t
8085 ;; A normal search strings
8086 (when (equal (string-to-char s) ?*)
8087 ;; Anchor on headlines, post may include tags.
8088 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
8089 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
8090 s (substring s 1)))
8091 (remove-text-properties
8092 0 (length s)
8093 '(face nil mouse-face nil keymap nil fontified nil) s)
8094 ;; Make a series of regular expressions to find a match
8095 (setq words (org-split-string s "[ \n\r\t]+")
8096
8097 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
8098 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
8099 "\\)" markers)
8100 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
8101 re2a (concat "[ \t\r\n]" re2a_)
8102 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
8103 re4 (concat "[^a-zA-Z_]" re4_)
8104
8105 re1 (concat pre re2 post)
8106 re3 (concat pre (if pre re4_ re4) post)
8107 re5 (concat pre ".*" re4)
8108 re2 (concat pre re2)
8109 re2a (concat pre (if pre re2a_ re2a))
8110 re4 (concat pre (if pre re4_ re4))
8111 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
8112 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
8113 re5 "\\)"
8114 ))
8115 (cond
8116 ((eq type 'org-occur) (org-occur reall))
8117 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
8118 (t (goto-char (point-min))
8119 (setq type 'fuzzy)
8120 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
8121 (org-search-not-self 1 re1 nil t)
8122 (org-search-not-self 1 re2 nil t)
8123 (org-search-not-self 1 re2a nil t)
8124 (org-search-not-self 1 re3 nil t)
8125 (org-search-not-self 1 re4 nil t)
8126 (org-search-not-self 1 re5 nil t)
8127 )
8128 (goto-char (match-beginning 1))
8129 (goto-char pos)
8130 (error "No match")))))
8131 (t
8132 ;; Normal string-search
8133 (goto-char (point-min))
8134 (if (search-forward s nil t)
8135 (goto-char (match-beginning 0))
8136 (error "No match"))))
8137 (and (org-mode-p) (org-show-context 'link-search))
8138 type))
8139
8140 (defun org-search-not-self (group &rest args)
8141 "Execute `re-search-forward', but only accept matches that do not
8142 enclose the position of `org-open-link-marker'."
8143 (let ((m org-open-link-marker))
8144 (catch 'exit
8145 (while (apply 're-search-forward args)
8146 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
8147 (goto-char (match-end group))
8148 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
8149 (> (match-beginning 0) (marker-position m))
8150 (< (match-end 0) (marker-position m)))
8151 (save-match-data
8152 (or (not (org-in-regexp
8153 org-bracket-link-analytic-regexp 1))
8154 (not (match-end 4)) ; no description
8155 (and (<= (match-beginning 4) (point))
8156 (>= (match-end 4) (point))))))
8157 (throw 'exit (point))))))))
8158
8159 (defun org-get-buffer-for-internal-link (buffer)
8160 "Return a buffer to be used for displaying the link target of internal links."
8161 (cond
8162 ((not org-display-internal-link-with-indirect-buffer)
8163 buffer)
8164 ((string-match "(Clone)$" (buffer-name buffer))
8165 (message "Buffer is already a clone, not making another one")
8166 ;; we also do not modify visibility in this case
8167 buffer)
8168 (t ; make a new indirect buffer for displaying the link
8169 (let* ((bn (buffer-name buffer))
8170 (ibn (concat bn "(Clone)"))
8171 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
8172 (with-current-buffer ib (org-overview))
8173 ib))))
8174
8175 (defun org-do-occur (regexp &optional cleanup)
8176 "Call the Emacs command `occur'.
8177 If CLEANUP is non-nil, remove the printout of the regular expression
8178 in the *Occur* buffer. This is useful if the regex is long and not useful
8179 to read."
8180 (occur regexp)
8181 (when cleanup
8182 (let ((cwin (selected-window)) win beg end)
8183 (when (setq win (get-buffer-window "*Occur*"))
8184 (select-window win))
8185 (goto-char (point-min))
8186 (when (re-search-forward "match[a-z]+" nil t)
8187 (setq beg (match-end 0))
8188 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
8189 (setq end (1- (match-beginning 0)))))
8190 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
8191 (goto-char (point-min))
8192 (select-window cwin))))
8193
8194 ;;; The mark ring for links jumps
8195
8196 (defvar org-mark-ring nil
8197 "Mark ring for positions before jumps in Org-mode.")
8198 (defvar org-mark-ring-last-goto nil
8199 "Last position in the mark ring used to go back.")
8200 ;; Fill and close the ring
8201 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
8202 (loop for i from 1 to org-mark-ring-length do
8203 (push (make-marker) org-mark-ring))
8204 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
8205 org-mark-ring)
8206
8207 (defun org-mark-ring-push (&optional pos buffer)
8208 "Put the current position or POS into the mark ring and rotate it."
8209 (interactive)
8210 (setq pos (or pos (point)))
8211 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
8212 (move-marker (car org-mark-ring)
8213 (or pos (point))
8214 (or buffer (current-buffer)))
8215 (message "%s"
8216 (substitute-command-keys
8217 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
8218
8219 (defun org-mark-ring-goto (&optional n)
8220 "Jump to the previous position in the mark ring.
8221 With prefix arg N, jump back that many stored positions. When
8222 called several times in succession, walk through the entire ring.
8223 Org-mode commands jumping to a different position in the current file,
8224 or to another Org-mode file, automatically push the old position
8225 onto the ring."
8226 (interactive "p")
8227 (let (p m)
8228 (if (eq last-command this-command)
8229 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
8230 (setq p org-mark-ring))
8231 (setq org-mark-ring-last-goto p)
8232 (setq m (car p))
8233 (switch-to-buffer (marker-buffer m))
8234 (goto-char m)
8235 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
8236
8237 (defun org-remove-angle-brackets (s)
8238 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
8239 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
8240 s)
8241 (defun org-add-angle-brackets (s)
8242 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
8243 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
8244 s)
8245 (defun org-remove-double-quotes (s)
8246 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
8247 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
8248 s)
8249
8250 ;;; Following specific links
8251
8252 (defun org-follow-timestamp-link ()
8253 (cond
8254 ((org-at-date-range-p t)
8255 (let ((org-agenda-start-on-weekday)
8256 (t1 (match-string 1))
8257 (t2 (match-string 2)))
8258 (setq t1 (time-to-days (org-time-string-to-time t1))
8259 t2 (time-to-days (org-time-string-to-time t2)))
8260 (org-agenda-list nil t1 (1+ (- t2 t1)))))
8261 ((org-at-timestamp-p t)
8262 (org-agenda-list nil (time-to-days (org-time-string-to-time
8263 (substring (match-string 1) 0 10)))
8264 1))
8265 (t (error "This should not happen"))))
8266
8267
8268 ;;; Following file links
8269 (defvar org-wait nil)
8270 (defun org-open-file (path &optional in-emacs line search)
8271 "Open the file at PATH.
8272 First, this expands any special file name abbreviations. Then the
8273 configuration variable `org-file-apps' is checked if it contains an
8274 entry for this file type, and if yes, the corresponding command is launched.
8275
8276 If no application is found, Emacs simply visits the file.
8277
8278 With optional prefix argument IN-EMACS, Emacs will visit the file.
8279 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
8280 and o use an external application to visit the file.
8281
8282 Optional LINE specifies a line to go to, optional SEARCH a string to
8283 search for. If LINE or SEARCH is given, the file will always be
8284 opened in Emacs.
8285 If the file does not exist, an error is thrown."
8286 (setq in-emacs (or in-emacs line search))
8287 (let* ((file (if (equal path "")
8288 buffer-file-name
8289 (substitute-in-file-name (expand-file-name path))))
8290 (apps (append org-file-apps (org-default-apps)))
8291 (remp (and (assq 'remote apps) (org-file-remote-p file)))
8292 (dirp (if remp nil (file-directory-p file)))
8293 (file (if (and dirp org-open-directory-means-index-dot-org)
8294 (concat (file-name-as-directory file) "index.org")
8295 file))
8296 (a-m-a-p (assq 'auto-mode apps))
8297 (dfile (downcase file))
8298 (old-buffer (current-buffer))
8299 (old-pos (point))
8300 (old-mode major-mode)
8301 ext cmd)
8302 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
8303 (setq ext (match-string 1 dfile))
8304 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
8305 (setq ext (match-string 1 dfile))))
8306 (cond
8307 ((equal in-emacs '(16))
8308 (setq cmd (cdr (assoc 'system apps))))
8309 (in-emacs (setq cmd 'emacs))
8310 (t
8311 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
8312 (and dirp (cdr (assoc 'directory apps)))
8313 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
8314 'string-match)
8315 (cdr (assoc ext apps))
8316 (cdr (assoc t apps))))))
8317 (when (eq cmd 'system)
8318 (setq cmd (cdr (assoc 'system apps))))
8319 (when (eq cmd 'default)
8320 (setq cmd (cdr (assoc t apps))))
8321 (when (eq cmd 'mailcap)
8322 (require 'mailcap)
8323 (mailcap-parse-mailcaps)
8324 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
8325 (command (mailcap-mime-info mime-type)))
8326 (if (stringp command)
8327 (setq cmd command)
8328 (setq cmd 'emacs))))
8329 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
8330 (not (file-exists-p file))
8331 (not org-open-non-existing-files))
8332 (error "No such file: %s" file))
8333 (cond
8334 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
8335 ;; Remove quotes around the file name - we'll use shell-quote-argument.
8336 (while (string-match "['\"]%s['\"]" cmd)
8337 (setq cmd (replace-match "%s" t t cmd)))
8338 (while (string-match "%s" cmd)
8339 (setq cmd (replace-match
8340 (save-match-data
8341 (shell-quote-argument
8342 (convert-standard-filename file)))
8343 t t cmd)))
8344 (save-window-excursion
8345 (start-process-shell-command cmd nil cmd)
8346 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
8347 ))
8348 ((or (stringp cmd)
8349 (eq cmd 'emacs))
8350 (funcall (cdr (assq 'file org-link-frame-setup)) file)
8351 (widen)
8352 (if line (goto-line line)
8353 (if search (org-link-search search))))
8354 ((consp cmd)
8355 (let ((file (convert-standard-filename file)))
8356 (eval cmd)))
8357 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
8358 (and (org-mode-p) (eq old-mode 'org-mode)
8359 (or (not (equal old-buffer (current-buffer)))
8360 (not (equal old-pos (point))))
8361 (org-mark-ring-push old-pos old-buffer))))
8362
8363 (defun org-default-apps ()
8364 "Return the default applications for this operating system."
8365 (cond
8366 ((eq system-type 'darwin)
8367 org-file-apps-defaults-macosx)
8368 ((eq system-type 'windows-nt)
8369 org-file-apps-defaults-windowsnt)
8370 (t org-file-apps-defaults-gnu)))
8371
8372 (defun org-apps-regexp-alist (list &optional add-auto-mode)
8373 "Convert extensions to regular expressions in the cars of LIST.
8374 Also, weed out any non-string entries, because the return value is used
8375 only for regexp matching.
8376 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
8377 point to the symbol `emacs', indicating that the file should
8378 be opened in Emacs."
8379 (append
8380 (delq nil
8381 (mapcar (lambda (x)
8382 (if (not (stringp (car x)))
8383 nil
8384 (if (string-match "\\W" (car x))
8385 x
8386 (cons (concat "\\." (car x) "\\'") (cdr x)))))
8387 list))
8388 (if add-auto-mode
8389 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
8390
8391 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
8392 (defun org-file-remote-p (file)
8393 "Test whether FILE specifies a location on a remote system.
8394 Return non-nil if the location is indeed remote.
8395
8396 For example, the filename \"/user@host:/foo\" specifies a location
8397 on the system \"/user@host:\"."
8398 (cond ((fboundp 'file-remote-p)
8399 (file-remote-p file))
8400 ((fboundp 'tramp-handle-file-remote-p)
8401 (tramp-handle-file-remote-p file))
8402 ((and (boundp 'ange-ftp-name-format)
8403 (string-match (car ange-ftp-name-format) file))
8404 t)
8405 (t nil)))
8406
8407
8408 ;;;; Refiling
8409
8410 (defun org-get-org-file ()
8411 "Read a filename, with default directory `org-directory'."
8412 (let ((default (or org-default-notes-file remember-data-file)))
8413 (read-file-name (format "File name [%s]: " default)
8414 (file-name-as-directory org-directory)
8415 default)))
8416
8417 (defun org-notes-order-reversed-p ()
8418 "Check if the current file should receive notes in reversed order."
8419 (cond
8420 ((not org-reverse-note-order) nil)
8421 ((eq t org-reverse-note-order) t)
8422 ((not (listp org-reverse-note-order)) nil)
8423 (t (catch 'exit
8424 (let ((all org-reverse-note-order)
8425 entry)
8426 (while (setq entry (pop all))
8427 (if (string-match (car entry) buffer-file-name)
8428 (throw 'exit (cdr entry))))
8429 nil)))))
8430
8431 (defvar org-refile-target-table nil
8432 "The list of refile targets, created by `org-refile'.")
8433
8434 (defvar org-agenda-new-buffers nil
8435 "Buffers created to visit agenda files.")
8436
8437 (defun org-get-refile-targets (&optional default-buffer)
8438 "Produce a table with refile targets."
8439 (let ((case-fold-search nil)
8440 ;; otherwise org confuses "TODO" as a kw and "Todo" as a word
8441 (entries (or org-refile-targets '((nil . (:level . 1)))))
8442 targets txt re files f desc descre fast-path-p level pos0)
8443 (message "Getting targets...")
8444 (with-current-buffer (or default-buffer (current-buffer))
8445 (while (setq entry (pop entries))
8446 (setq files (car entry) desc (cdr entry))
8447 (setq fast-path-p nil)
8448 (cond
8449 ((null files) (setq files (list (current-buffer))))
8450 ((eq files 'org-agenda-files)
8451 (setq files (org-agenda-files 'unrestricted)))
8452 ((and (symbolp files) (fboundp files))
8453 (setq files (funcall files)))
8454 ((and (symbolp files) (boundp files))
8455 (setq files (symbol-value files))))
8456 (if (stringp files) (setq files (list files)))
8457 (cond
8458 ((eq (car desc) :tag)
8459 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
8460 ((eq (car desc) :todo)
8461 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
8462 ((eq (car desc) :regexp)
8463 (setq descre (cdr desc)))
8464 ((eq (car desc) :level)
8465 (setq descre (concat "^\\*\\{" (number-to-string
8466 (if org-odd-levels-only
8467 (1- (* 2 (cdr desc)))
8468 (cdr desc)))
8469 "\\}[ \t]")))
8470 ((eq (car desc) :maxlevel)
8471 (setq fast-path-p t)
8472 (setq descre (concat "^\\*\\{1," (number-to-string
8473 (if org-odd-levels-only
8474 (1- (* 2 (cdr desc)))
8475 (cdr desc)))
8476 "\\}[ \t]")))
8477 (t (error "Bad refiling target description %s" desc)))
8478 (while (setq f (pop files))
8479 (save-excursion
8480 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
8481 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
8482 (setq f (expand-file-name f))
8483 (if (eq org-refile-use-outline-path 'file)
8484 (push (list (file-name-nondirectory f) f nil nil) targets))
8485 (save-excursion
8486 (save-restriction
8487 (widen)
8488 (goto-char (point-min))
8489 (while (re-search-forward descre nil t)
8490 (goto-char (setq pos0 (point-at-bol)))
8491 (catch 'next
8492 (when org-refile-target-verify-function
8493 (save-match-data
8494 (or (funcall org-refile-target-verify-function)
8495 (throw 'next t))))
8496 (when (looking-at org-complex-heading-regexp)
8497 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
8498 txt (org-link-display-format (match-string 4))
8499 re (concat "^" (regexp-quote
8500 (buffer-substring (match-beginning 1)
8501 (match-end 4)))))
8502 (if (match-end 5) (setq re (concat re "[ \t]+"
8503 (regexp-quote
8504 (match-string 5)))))
8505 (setq re (concat re "[ \t]*$"))
8506 (when org-refile-use-outline-path
8507 (setq txt (mapconcat 'org-protect-slash
8508 (append
8509 (if (eq org-refile-use-outline-path 'file)
8510 (list (file-name-nondirectory
8511 (buffer-file-name (buffer-base-buffer))))
8512 (if (eq org-refile-use-outline-path 'full-file-path)
8513 (list (buffer-file-name (buffer-base-buffer)))))
8514 (org-get-outline-path fast-path-p level txt)
8515 (list txt))
8516 "/")))
8517 (push (list txt f re (point)) targets)))
8518 (when (= (point) pos0)
8519 ;; verification function has not moved point
8520 (goto-char (point-at-eol))))))))))
8521 (message "Getting targets...done")
8522 (nreverse targets)))
8523
8524 (defun org-protect-slash (s)
8525 (while (string-match "/" s)
8526 (setq s (replace-match "\\" t t s)))
8527 s)
8528
8529 (defvar org-olpa (make-vector 20 nil))
8530
8531 (defun org-get-outline-path (&optional fastp level heading)
8532 "Return the outline path to the current entry, as a list."
8533 (if fastp
8534 (progn
8535 (if (> level 19)
8536 (error "Outline path failure, more than 19 levels."))
8537 (loop for i from level upto 19 do
8538 (aset org-olpa i nil))
8539 (prog1
8540 (delq nil (append org-olpa nil))
8541 (aset org-olpa level heading)))
8542 (let (rtn)
8543 (save-excursion
8544 (while (org-up-heading-safe)
8545 (when (looking-at org-complex-heading-regexp)
8546 (push (org-match-string-no-properties 4) rtn)))
8547 rtn))))
8548
8549 (defvar org-refile-history nil
8550 "History for refiling operations.")
8551
8552 (defvar org-after-refile-insert-hook nil
8553 "Hook run after `org-refile' has inserted its stuff at the new location.
8554 Note that this is still *before* the stuff will be removed from
8555 the *old* location.")
8556
8557 (defun org-refile (&optional goto default-buffer rfloc)
8558 "Move the entry at point to another heading.
8559 The list of target headings is compiled using the information in
8560 `org-refile-targets', which see. This list is created before each use
8561 and will therefore always be up-to-date.
8562
8563 At the target location, the entry is filed as a subitem of the target heading.
8564 Depending on `org-reverse-note-order', the new subitem will either be the
8565 first or the last subitem.
8566
8567 If there is an active region, all entries in that region will be moved.
8568 However, the region must fulfil the requirement that the first heading
8569 is the first one sets the top-level of the moved text - at most siblings
8570 below it are allowed.
8571
8572 With prefix arg GOTO, the command will only visit the target location,
8573 not actually move anything.
8574 With a double prefix `C-u C-u', go to the location where the last refiling
8575 operation has put the subtree.
8576
8577 RFLOC can be a refile location obtained in a different way.
8578
8579 See also `org-refile-use-outline-path' and `org-completion-use-ido'"
8580 (interactive "P")
8581 (let* ((cbuf (current-buffer))
8582 (regionp (org-region-active-p))
8583 (region-start (and regionp (region-beginning)))
8584 (region-end (and regionp (region-end)))
8585 (region-length (and regionp (- region-end region-start)))
8586 (filename (buffer-file-name (buffer-base-buffer cbuf)))
8587 pos it nbuf file re level reversed)
8588 (when regionp
8589 (goto-char region-start)
8590 (or (bolp) (goto-char (point-at-bol)))
8591 (setq region-start (point))
8592 (unless (org-kill-is-subtree-p
8593 (buffer-substring region-start region-end))
8594 (error "The region is not a (sequence of) subtree(s)")))
8595 (if (equal goto '(16))
8596 (org-refile-goto-last-stored)
8597 (when (setq it (or rfloc
8598 (save-excursion
8599 (org-refile-get-location
8600 (if goto "Goto: " "Refile to: ") default-buffer
8601 org-refile-allow-creating-parent-nodes))))
8602 (setq file (nth 1 it)
8603 re (nth 2 it)
8604 pos (nth 3 it))
8605 (if (and (not goto)
8606 pos
8607 (equal (buffer-file-name) file)
8608 (if regionp
8609 (and (>= pos region-start)
8610 (<= pos region-end))
8611 (and (>= pos (point))
8612 (< pos (save-excursion
8613 (org-end-of-subtree t t))))))
8614 (error "Cannot refile to position inside the tree or region"))
8615
8616 (setq nbuf (or (find-buffer-visiting file)
8617 (find-file-noselect file)))
8618 (if goto
8619 (progn
8620 (switch-to-buffer nbuf)
8621 (goto-char pos)
8622 (org-show-context 'org-goto))
8623 (if regionp
8624 (progn
8625 (org-kill-new (buffer-substring region-start region-end))
8626 (org-save-markers-in-region region-start region-end))
8627 (org-copy-subtree 1 nil t))
8628 (save-excursion
8629 (set-buffer (setq nbuf (or (find-buffer-visiting file)
8630 (find-file-noselect file))))
8631 (setq reversed (org-notes-order-reversed-p))
8632 (save-excursion
8633 (save-restriction
8634 (widen)
8635 (if pos
8636 (progn
8637 (goto-char pos)
8638 (looking-at outline-regexp)
8639 (setq level (org-get-valid-level (funcall outline-level) 1))
8640 (goto-char
8641 (if reversed
8642 (or (outline-next-heading) (point-max))
8643 (or (save-excursion (outline-get-next-sibling))
8644 (org-end-of-subtree t t)
8645 (point-max)))))
8646 (setq level 1)
8647 (if (not reversed)
8648 (goto-char (point-max))
8649 (goto-char (point-min))
8650 (or (outline-next-heading) (goto-char (point-max)))))
8651 (if (not (bolp)) (newline))
8652 (bookmark-set "org-refile-last-stored")
8653 (org-paste-subtree level)
8654 (if (fboundp 'deactivate-mark) (deactivate-mark))
8655 (run-hooks 'org-after-refile-insert-hook))))
8656 (if regionp
8657 (delete-region (point) (+ (point) region-length))
8658 (org-cut-subtree))
8659 (when (featurep 'org-inlinetask)
8660 (org-inlinetask-remove-END-maybe))
8661 (setq org-markers-to-move nil)
8662 (message "Refiled to \"%s\"" (car it))))))
8663 (org-reveal))
8664
8665 (defun org-refile-goto-last-stored ()
8666 "Go to the location where the last refile was stored."
8667 (interactive)
8668 (bookmark-jump "org-refile-last-stored")
8669 (message "This is the location of the last refile"))
8670
8671 (defun org-refile-get-location (&optional prompt default-buffer new-nodes)
8672 "Prompt the user for a refile location, using PROMPT."
8673 (let ((org-refile-targets org-refile-targets)
8674 (org-refile-use-outline-path org-refile-use-outline-path))
8675 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
8676 (unless org-refile-target-table
8677 (error "No refile targets"))
8678 (let* ((cbuf (current-buffer))
8679 (partial-completion-mode nil)
8680 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
8681 (cfunc (if (and org-refile-use-outline-path
8682 org-outline-path-complete-in-steps)
8683 'org-olpath-completing-read
8684 'org-ido-completing-read))
8685 (extra (if org-refile-use-outline-path "/" ""))
8686 (filename (and cfn (expand-file-name cfn)))
8687 (tbl (mapcar
8688 (lambda (x)
8689 (if (and (not (member org-refile-use-outline-path
8690 '(file full-file-path)))
8691 (not (equal filename (nth 1 x))))
8692 (cons (concat (car x) extra " ("
8693 (file-name-nondirectory (nth 1 x)) ")")
8694 (cdr x))
8695 (cons (concat (car x) extra) (cdr x))))
8696 org-refile-target-table))
8697 (completion-ignore-case t)
8698 pa answ parent-target child parent old-hist)
8699 (setq old-hist org-refile-history)
8700 (setq answ (funcall cfunc prompt tbl nil (not new-nodes)
8701 nil 'org-refile-history))
8702 (setq pa (or (assoc answ tbl) (assoc (concat answ "/") tbl)))
8703 (if pa
8704 (progn
8705 (when (or (not org-refile-history)
8706 (not (eq old-hist org-refile-history))
8707 (not (equal (car pa) (car org-refile-history))))
8708 (setq org-refile-history
8709 (cons (car pa) (if (assoc (car org-refile-history) tbl)
8710 org-refile-history
8711 (cdr org-refile-history))))
8712 (if (equal (car org-refile-history) (nth 1 org-refile-history))
8713 (pop org-refile-history)))
8714 pa)
8715 (when (string-match "\\`\\(.*\\)/\\([^/]+\\)\\'" answ)
8716 (setq parent (match-string 1 answ)
8717 child (match-string 2 answ))
8718 (setq parent-target (or (assoc parent tbl) (assoc (concat parent "/") tbl)))
8719 (when (and parent-target
8720 (or (eq new-nodes t)
8721 (and (eq new-nodes 'confirm)
8722 (y-or-n-p (format "Create new node \"%s\"? " child)))))
8723 (org-refile-new-child parent-target child))))))
8724
8725 (defun org-refile-new-child (parent-target child)
8726 "Use refile target PARENT-TARGET to add new CHILD below it."
8727 (unless parent-target
8728 (error "Cannot find parent for new node"))
8729 (let ((file (nth 1 parent-target))
8730 (pos (nth 3 parent-target))
8731 level)
8732 (with-current-buffer (or (find-buffer-visiting file)
8733 (find-file-noselect file))
8734 (save-excursion
8735 (save-restriction
8736 (widen)
8737 (if pos
8738 (goto-char pos)
8739 (goto-char (point-max))
8740 (if (not (bolp)) (newline)))
8741 (when (looking-at outline-regexp)
8742 (setq level (funcall outline-level))
8743 (org-end-of-subtree t t))
8744 (org-back-over-empty-lines)
8745 (insert "\n" (make-string
8746 (if pos (org-get-valid-level level 1) 1) ?*)
8747 " " child "\n")
8748 (beginning-of-line 0)
8749 (list (concat (car parent-target) "/" child) file "" (point)))))))
8750
8751 (defun org-olpath-completing-read (prompt collection &rest args)
8752 "Read an outline path like a file name."
8753 (let ((thetable collection)
8754 (org-completion-use-ido nil)) ; does not work with ido.
8755 (apply
8756 'org-ido-completing-read prompt
8757 (lambda (string predicate &optional flag)
8758 (let (rtn r f (l (length string)))
8759 (cond
8760 ((eq flag nil)
8761 ;; try completion
8762 (try-completion string thetable))
8763 ((eq flag t)
8764 ;; all-completions
8765 (setq rtn (all-completions string thetable predicate))
8766 (mapcar
8767 (lambda (x)
8768 (setq r (substring x l))
8769 (if (string-match " ([^)]*)$" x)
8770 (setq f (match-string 0 x))
8771 (setq f ""))
8772 (if (string-match "/" r)
8773 (concat string (substring r 0 (match-end 0)) f)
8774 x))
8775 rtn))
8776 ((eq flag 'lambda)
8777 ;; exact match?
8778 (assoc string thetable)))
8779 ))
8780 args)))
8781
8782 ;;;; Dynamic blocks
8783
8784 (defun org-find-dblock (name)
8785 "Find the first dynamic block with name NAME in the buffer.
8786 If not found, stay at current position and return nil."
8787 (let (pos)
8788 (save-excursion
8789 (goto-char (point-min))
8790 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
8791 nil t)
8792 (match-beginning 0))))
8793 (if pos (goto-char pos))
8794 pos))
8795
8796 (defconst org-dblock-start-re
8797 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8798 "Matches the startline of a dynamic block, with parameters.")
8799
8800 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8801 "Matches the end of a dynamic block.")
8802
8803 (defun org-create-dblock (plist)
8804 "Create a dynamic block section, with parameters taken from PLIST.
8805 PLIST must contain a :name entry which is used as name of the block."
8806 (unless (bolp) (newline))
8807 (let ((name (plist-get plist :name)))
8808 (insert "#+BEGIN: " name)
8809 (while plist
8810 (if (eq (car plist) :name)
8811 (setq plist (cddr plist))
8812 (insert " " (prin1-to-string (pop plist)))))
8813 (insert "\n\n#+END:\n")
8814 (beginning-of-line -2)))
8815
8816 (defun org-prepare-dblock ()
8817 "Prepare dynamic block for refresh.
8818 This empties the block, puts the cursor at the insert position and returns
8819 the property list including an extra property :name with the block name."
8820 (unless (looking-at org-dblock-start-re)
8821 (error "Not at a dynamic block"))
8822 (let* ((begdel (1+ (match-end 0)))
8823 (name (org-no-properties (match-string 1)))
8824 (params (append (list :name name)
8825 (read (concat "(" (match-string 3) ")")))))
8826 (unless (re-search-forward org-dblock-end-re nil t)
8827 (error "Dynamic block not terminated"))
8828 (setq params
8829 (append params
8830 (list :content (buffer-substring
8831 begdel (match-beginning 0)))))
8832 (delete-region begdel (match-beginning 0))
8833 (goto-char begdel)
8834 (open-line 1)
8835 params))
8836
8837 (defun org-map-dblocks (&optional command)
8838 "Apply COMMAND to all dynamic blocks in the current buffer.
8839 If COMMAND is not given, use `org-update-dblock'."
8840 (let ((cmd (or command 'org-update-dblock))
8841 pos)
8842 (save-excursion
8843 (goto-char (point-min))
8844 (while (re-search-forward org-dblock-start-re nil t)
8845 (goto-char (setq pos (match-beginning 0)))
8846 (condition-case nil
8847 (funcall cmd)
8848 (error (message "Error during update of dynamic block")))
8849 (goto-char pos)
8850 (unless (re-search-forward org-dblock-end-re nil t)
8851 (error "Dynamic block not terminated"))))))
8852
8853 (defun org-dblock-update (&optional arg)
8854 "User command for updating dynamic blocks.
8855 Update the dynamic block at point. With prefix ARG, update all dynamic
8856 blocks in the buffer."
8857 (interactive "P")
8858 (if arg
8859 (org-update-all-dblocks)
8860 (or (looking-at org-dblock-start-re)
8861 (org-beginning-of-dblock))
8862 (org-update-dblock)))
8863
8864 (defun org-update-dblock ()
8865 "Update the dynamic block at point
8866 This means to empty the block, parse for parameters and then call
8867 the correct writing function."
8868 (save-window-excursion
8869 (let* ((pos (point))
8870 (line (org-current-line))
8871 (params (org-prepare-dblock))
8872 (name (plist-get params :name))
8873 (cmd (intern (concat "org-dblock-write:" name))))
8874 (message "Updating dynamic block `%s' at line %d..." name line)
8875 (funcall cmd params)
8876 (message "Updating dynamic block `%s' at line %d...done" name line)
8877 (goto-char pos))))
8878
8879 (defun org-beginning-of-dblock ()
8880 "Find the beginning of the dynamic block at point.
8881 Error if there is no such block at point."
8882 (let ((pos (point))
8883 beg)
8884 (end-of-line 1)
8885 (if (and (re-search-backward org-dblock-start-re nil t)
8886 (setq beg (match-beginning 0))
8887 (re-search-forward org-dblock-end-re nil t)
8888 (> (match-end 0) pos))
8889 (goto-char beg)
8890 (goto-char pos)
8891 (error "Not in a dynamic block"))))
8892
8893 (defun org-update-all-dblocks ()
8894 "Update all dynamic blocks in the buffer.
8895 This function can be used in a hook."
8896 (when (org-mode-p)
8897 (org-map-dblocks 'org-update-dblock)))
8898
8899
8900 ;;;; Completion
8901
8902 (defconst org-additional-option-like-keywords
8903 '("BEGIN_HTML" "END_HTML" "HTML:" "ATTR_HTML"
8904 "BEGIN_DocBook" "END_DocBook" "DocBook:" "ATTR_DocBook"
8905 "BEGIN_LaTeX" "END_LaTeX" "LaTeX:" "LATEX_HEADER:" "ATTR_LaTeX"
8906 "BEGIN:" "END:"
8907 "ORGTBL" "TBLFM:" "TBLNAME:"
8908 "BEGIN_EXAMPLE" "END_EXAMPLE"
8909 "BEGIN_QUOTE" "END_QUOTE"
8910 "BEGIN_VERSE" "END_VERSE"
8911 "BEGIN_CENTER" "END_CENTER"
8912 "BEGIN_SRC" "END_SRC"
8913 "CATEGORY" "COLUMNS"
8914 "CAPTION" "LABEL"
8915 "BIND"))
8916
8917 (defcustom org-structure-template-alist
8918 '(
8919 ("s" "#+begin_src ?\n\n#+end_src"
8920 "<src lang=\"?\">\n\n</src>")
8921 ("e" "#+begin_example\n?\n#+end_example"
8922 "<example>\n?\n</example>")
8923 ("q" "#+begin_quote\n?\n#+end_quote"
8924 "<quote>\n?\n</quote>")
8925 ("v" "#+begin_verse\n?\n#+end_verse"
8926 "<verse>\n?\n/verse>")
8927 ("c" "#+begin_center\n?\n#+end_center"
8928 "<center>\n?\n/center>")
8929 ("l" "#+begin_latex\n?\n#+end_latex"
8930 "<literal style=\"latex\">\n?\n</literal>")
8931 ("L" "#+latex: "
8932 "<literal style=\"latex\">?</literal>")
8933 ("h" "#+begin_html\n?\n#+end_html"
8934 "<literal style=\"html\">\n?\n</literal>")
8935 ("H" "#+html: "
8936 "<literal style=\"html\">?</literal>")
8937 ("a" "#+begin_ascii\n?\n#+end_ascii")
8938 ("A" "#+ascii: ")
8939 ("i" "#+include %file ?"
8940 "<include file=%file markup=\"?\">")
8941 )
8942 "Structure completion elements.
8943 This is a list of abbreviation keys and values. The value gets inserted
8944 it you type @samp{.} followed by the key and then the completion key,
8945 usually `M-TAB'. %file will be replaced by a file name after prompting
8946 for the file using completion.
8947 There are two templates for each key, the first uses the original Org syntax,
8948 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8949 the default when the /org-mtags.el/ module has been loaded. See also the
8950 variable `org-mtags-prefer-muse-templates'.
8951 This is an experimental feature, it is undecided if it is going to stay in."
8952 :group 'org-completion
8953 :type '(repeat
8954 (string :tag "Key")
8955 (string :tag "Template")
8956 (string :tag "Muse Template")))
8957
8958 (defun org-try-structure-completion ()
8959 "Try to complete a structure template before point.
8960 This looks for strings like \"<e\" on an otherwise empty line and
8961 expands them."
8962 (let ((l (buffer-substring (point-at-bol) (point)))
8963 a)
8964 (when (and (looking-at "[ \t]*$")
8965 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8966 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8967 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8968 (match-beginning 1)) a)
8969 t)))
8970
8971 (defun org-complete-expand-structure-template (start cell)
8972 "Expand a structure template."
8973 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8974 (rpl (nth (if musep 2 1) cell))
8975 (ind ""))
8976 (delete-region start (point))
8977 (when (string-match "\\`#\\+" rpl)
8978 (cond
8979 ((bolp))
8980 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8981 (setq ind (buffer-substring (point-at-bol) (point))))
8982 (t (newline))))
8983 (setq start (point))
8984 (if (string-match "%file" rpl)
8985 (setq rpl (replace-match
8986 (concat
8987 "\""
8988 (save-match-data
8989 (abbreviate-file-name (read-file-name "Include file: ")))
8990 "\"")
8991 t t rpl)))
8992 (setq rpl (mapconcat 'identity (split-string rpl "\n")
8993 (concat "\n" ind)))
8994 (insert rpl)
8995 (if (re-search-backward "\\?" start t) (delete-char 1))))
8996
8997
8998 (defun org-complete (&optional arg)
8999 "Perform completion on word at point.
9000 At the beginning of a headline, this completes TODO keywords as given in
9001 `org-todo-keywords'.
9002 If the current word is preceded by a backslash, completes the TeX symbols
9003 that are supported for HTML support.
9004 If the current word is preceded by \"#+\", completes special words for
9005 setting file options.
9006 In the line after \"#+STARTUP:, complete valid keywords.\"
9007 At all other locations, this simply calls the value of
9008 `org-completion-fallback-command'."
9009 (interactive "P")
9010 (org-without-partial-completion
9011 (catch 'exit
9012 (let* ((a nil)
9013 (end (point))
9014 (beg1 (save-excursion
9015 (skip-chars-backward (org-re "[:alnum:]_@"))
9016 (point)))
9017 (beg (save-excursion
9018 (skip-chars-backward "a-zA-Z0-9_:$")
9019 (point)))
9020 (confirm (lambda (x) (stringp (car x))))
9021 (searchhead (equal (char-before beg) ?*))
9022 (struct
9023 (when (and (member (char-before beg1) '(?. ?<))
9024 (setq a (assoc (buffer-substring beg1 (point))
9025 org-structure-template-alist)))
9026 (org-complete-expand-structure-template (1- beg1) a)
9027 (throw 'exit t)))
9028 (tag (and (equal (char-before beg1) ?:)
9029 (equal (char-after (point-at-bol)) ?*)))
9030 (prop (and (equal (char-before beg1) ?:)
9031 (not (equal (char-after (point-at-bol)) ?*))))
9032 (texp (equal (char-before beg) ?\\))
9033 (link (equal (char-before beg) ?\[))
9034 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
9035 beg)
9036 "#+"))
9037 (startup (string-match "^#\\+STARTUP:.*"
9038 (buffer-substring (point-at-bol) (point))))
9039 (completion-ignore-case opt)
9040 (type nil)
9041 (tbl nil)
9042 (table (cond
9043 (opt
9044 (setq type :opt)
9045 (require 'org-exp)
9046 (append
9047 (mapcar
9048 (lambda (x)
9049 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
9050 (cons (match-string 2 x) (match-string 1 x)))
9051 (org-split-string (org-get-current-options) "\n"))
9052 (mapcar 'list org-additional-option-like-keywords)))
9053 (startup
9054 (setq type :startup)
9055 org-startup-options)
9056 (link (append org-link-abbrev-alist-local
9057 org-link-abbrev-alist))
9058 (texp
9059 (setq type :tex)
9060 org-html-entities)
9061 ((string-match "\\`\\*+[ \t]+\\'"
9062 (buffer-substring (point-at-bol) beg))
9063 (setq type :todo)
9064 (mapcar 'list org-todo-keywords-1))
9065 (searchhead
9066 (setq type :searchhead)
9067 (save-excursion
9068 (goto-char (point-min))
9069 (while (re-search-forward org-todo-line-regexp nil t)
9070 (push (list
9071 (org-make-org-heading-search-string
9072 (match-string 3) t))
9073 tbl)))
9074 tbl)
9075 (tag (setq type :tag beg beg1)
9076 (or org-tag-alist (org-get-buffer-tags)))
9077 (prop (setq type :prop beg beg1)
9078 (mapcar 'list (org-buffer-property-keys nil t t)))
9079 (t (progn
9080 (call-interactively org-completion-fallback-command)
9081 (throw 'exit nil)))))
9082 (pattern (buffer-substring-no-properties beg end))
9083 (completion (try-completion pattern table confirm)))
9084 (cond ((eq completion t)
9085 (if (not (assoc (upcase pattern) table))
9086 (message "Already complete")
9087 (if (and (equal type :opt)
9088 (not (member (car (assoc (upcase pattern) table))
9089 org-additional-option-like-keywords)))
9090 (insert (substring (cdr (assoc (upcase pattern) table))
9091 (length pattern)))
9092 (if (memq type '(:tag :prop)) (insert ":")))))
9093 ((null completion)
9094 (message "Can't find completion for \"%s\"" pattern)
9095 (ding))
9096 ((not (string= pattern completion))
9097 (delete-region beg end)
9098 (if (string-match " +$" completion)
9099 (setq completion (replace-match "" t t completion)))
9100 (insert completion)
9101 (if (get-buffer-window "*Completions*")
9102 (delete-window (get-buffer-window "*Completions*")))
9103 (if (assoc completion table)
9104 (if (eq type :todo) (insert " ")
9105 (if (memq type '(:tag :prop)) (insert ":"))))
9106 (if (and (equal type :opt) (assoc completion table))
9107 (message "%s" (substitute-command-keys
9108 "Press \\[org-complete] again to insert example settings"))))
9109 (t
9110 (message "Making completion list...")
9111 (let ((list (sort (all-completions pattern table confirm)
9112 'string<)))
9113 (with-output-to-temp-buffer "*Completions*"
9114 (condition-case nil
9115 ;; Protection needed for XEmacs and emacs 21
9116 (display-completion-list list pattern)
9117 (error (display-completion-list list)))))
9118 (message "Making completion list...%s" "done")))))))
9119
9120 ;;;; TODO, DEADLINE, Comments
9121
9122 (defun org-toggle-comment ()
9123 "Change the COMMENT state of an entry."
9124 (interactive)
9125 (save-excursion
9126 (org-back-to-heading)
9127 (let (case-fold-search)
9128 (if (looking-at (concat outline-regexp
9129 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
9130 (replace-match "" t t nil 1)
9131 (if (looking-at outline-regexp)
9132 (progn
9133 (goto-char (match-end 0))
9134 (insert org-comment-string " ")))))))
9135
9136 (defvar org-last-todo-state-is-todo nil
9137 "This is non-nil when the last TODO state change led to a TODO state.
9138 If the last change removed the TODO tag or switched to DONE, then
9139 this is nil.")
9140
9141 (defvar org-setting-tags nil) ; dynamically skipped
9142
9143 (defun org-parse-local-options (string var)
9144 "Parse STRING for startup setting relevant for variable VAR."
9145 (let ((rtn (symbol-value var))
9146 e opts)
9147 (save-match-data
9148 (if (or (not string) (not (string-match "\\S-" string)))
9149 rtn
9150 (setq opts (delq nil (mapcar (lambda (x)
9151 (setq e (assoc x org-startup-options))
9152 (if (eq (nth 1 e) var) e nil))
9153 (org-split-string string "[ \t]+"))))
9154 (if (not opts)
9155 rtn
9156 (setq rtn nil)
9157 (while (setq e (pop opts))
9158 (if (not (nth 3 e))
9159 (setq rtn (nth 2 e))
9160 (if (not (listp rtn)) (setq rtn nil))
9161 (push (nth 2 e) rtn)))
9162 rtn)))))
9163
9164 (defvar org-todo-setup-filter-hook nil
9165 "Hook for functions that pre-filter todo specs.
9166
9167 Each function takes a todo spec and returns either `nil' or the spec
9168 transformed into canonical form." )
9169
9170 (defvar org-todo-get-default-hook nil
9171 "Hook for functions that get a default item for todo.
9172
9173 Each function takes arguments (NEW-MARK OLD-MARK) and returns either
9174 `nil' or a string to be used for the todo mark." )
9175
9176 (defvar org-agenda-headline-snapshot-before-repeat)
9177
9178 (defun org-todo (&optional arg)
9179 "Change the TODO state of an item.
9180 The state of an item is given by a keyword at the start of the heading,
9181 like
9182 *** TODO Write paper
9183 *** DONE Call mom
9184
9185 The different keywords are specified in the variable `org-todo-keywords'.
9186 By default the available states are \"TODO\" and \"DONE\".
9187 So for this example: when the item starts with TODO, it is changed to DONE.
9188 When it starts with DONE, the DONE is removed. And when neither TODO nor
9189 DONE are present, add TODO at the beginning of the heading.
9190
9191 With C-u prefix arg, use completion to determine the new state.
9192 With numeric prefix arg, switch to that state.
9193 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
9194 With a tripple C-u prefix, circumvent any state blocking.
9195
9196 For calling through lisp, arg is also interpreted in the following way:
9197 'none -> empty state
9198 \"\"(empty string) -> switch to empty state
9199 'done -> switch to DONE
9200 'nextset -> switch to the next set of keywords
9201 'previousset -> switch to the previous set of keywords
9202 \"WAITING\" -> switch to the specified keyword, but only if it
9203 really is a member of `org-todo-keywords'."
9204 (interactive "P")
9205 (if (equal arg '(16)) (setq arg 'nextset))
9206 (let ((org-blocker-hook org-blocker-hook)
9207 (case-fold-search nil))
9208 (when (equal arg '(64))
9209 (setq arg nil org-blocker-hook nil))
9210 (when (and org-blocker-hook
9211 (or org-inhibit-blocking
9212 (org-entry-get nil "NOBLOCKING")))
9213 (setq org-blocker-hook nil))
9214 (save-excursion
9215 (catch 'exit
9216 (org-back-to-heading)
9217 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
9218 (or (looking-at (concat " +" org-todo-regexp "\\( +\\|$\\)"))
9219 (looking-at " *"))
9220 (let* ((match-data (match-data))
9221 (startpos (point-at-bol))
9222 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
9223 (org-log-done org-log-done)
9224 (org-log-repeat org-log-repeat)
9225 (org-todo-log-states org-todo-log-states)
9226 (this (match-string 1))
9227 (hl-pos (match-beginning 0))
9228 (head (org-get-todo-sequence-head this))
9229 (ass (assoc head org-todo-kwd-alist))
9230 (interpret (nth 1 ass))
9231 (done-word (nth 3 ass))
9232 (final-done-word (nth 4 ass))
9233 (last-state (or this ""))
9234 (completion-ignore-case t)
9235 (member (member this org-todo-keywords-1))
9236 (tail (cdr member))
9237 (state (cond
9238 ((and org-todo-key-trigger
9239 (or (and (equal arg '(4))
9240 (eq org-use-fast-todo-selection 'prefix))
9241 (and (not arg) org-use-fast-todo-selection
9242 (not (eq org-use-fast-todo-selection
9243 'prefix)))))
9244 ;; Use fast selection
9245 (org-fast-todo-selection))
9246 ((and (equal arg '(4))
9247 (or (not org-use-fast-todo-selection)
9248 (not org-todo-key-trigger)))
9249 ;; Read a state with completion
9250 (org-ido-completing-read
9251 "State: " (mapcar (lambda(x) (list x))
9252 org-todo-keywords-1)
9253 nil t))
9254 ((eq arg 'right)
9255 (if this
9256 (if tail (car tail) nil)
9257 (car org-todo-keywords-1)))
9258 ((eq arg 'left)
9259 (if (equal member org-todo-keywords-1)
9260 nil
9261 (if this
9262 (nth (- (length org-todo-keywords-1)
9263 (length tail) 2)
9264 org-todo-keywords-1)
9265 (org-last org-todo-keywords-1))))
9266 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
9267 (setq arg nil))) ; hack to fall back to cycling
9268 (arg
9269 ;; user or caller requests a specific state
9270 (cond
9271 ((equal arg "") nil)
9272 ((eq arg 'none) nil)
9273 ((eq arg 'done) (or done-word (car org-done-keywords)))
9274 ((eq arg 'nextset)
9275 (or (car (cdr (member head org-todo-heads)))
9276 (car org-todo-heads)))
9277 ((eq arg 'previousset)
9278 (let ((org-todo-heads (reverse org-todo-heads)))
9279 (or (car (cdr (member head org-todo-heads)))
9280 (car org-todo-heads))))
9281 ((car (member arg org-todo-keywords-1)))
9282 ((nth (1- (prefix-numeric-value arg))
9283 org-todo-keywords-1))))
9284 ((null member) (or head (car org-todo-keywords-1)))
9285 ((equal this final-done-word) nil) ;; -> make empty
9286 ((null tail) nil) ;; -> first entry
9287 ((memq interpret '(type priority))
9288 (if (eq this-command last-command)
9289 (car tail)
9290 (if (> (length tail) 0)
9291 (or done-word (car org-done-keywords))
9292 nil)))
9293 (t
9294 (car tail))))
9295 (state (or
9296 (run-hook-with-args-until-success
9297 'org-todo-get-default-hook state last-state)
9298 state))
9299 (next (if state (concat " " state " ") " "))
9300 (change-plist (list :type 'todo-state-change :from this :to state
9301 :position startpos))
9302 dolog now-done-p)
9303 (when org-blocker-hook
9304 (setq org-last-todo-state-is-todo
9305 (not (member this org-done-keywords)))
9306 (unless (save-excursion
9307 (save-match-data
9308 (run-hook-with-args-until-failure
9309 'org-blocker-hook change-plist)))
9310 (if (interactive-p)
9311 (error "TODO state change from %s to %s blocked" this state)
9312 ;; fail silently
9313 (message "TODO state change from %s to %s blocked" this state)
9314 (throw 'exit nil))))
9315 (store-match-data match-data)
9316 (replace-match next t t)
9317 (unless (pos-visible-in-window-p hl-pos)
9318 (message "TODO state changed to %s" (org-trim next)))
9319 (unless head
9320 (setq head (org-get-todo-sequence-head state)
9321 ass (assoc head org-todo-kwd-alist)
9322 interpret (nth 1 ass)
9323 done-word (nth 3 ass)
9324 final-done-word (nth 4 ass)))
9325 (when (memq arg '(nextset previousset))
9326 (message "Keyword-Set %d/%d: %s"
9327 (- (length org-todo-sets) -1
9328 (length (memq (assoc state org-todo-sets) org-todo-sets)))
9329 (length org-todo-sets)
9330 (mapconcat 'identity (assoc state org-todo-sets) " ")))
9331 (setq org-last-todo-state-is-todo
9332 (not (member state org-done-keywords)))
9333 (setq now-done-p (and (member state org-done-keywords)
9334 (not (member this org-done-keywords))))
9335 (and logging (org-local-logging logging))
9336 (when (and (or org-todo-log-states org-log-done)
9337 (not (eq org-inhibit-logging t))
9338 (not (memq arg '(nextset previousset))))
9339 ;; we need to look at recording a time and note
9340 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
9341 (nth 2 (assoc this org-todo-log-states))))
9342 (if (and (eq dolog 'note) (eq org-inhibit-logging 'note))
9343 (setq dolog 'time))
9344 (when (and state
9345 (member state org-not-done-keywords)
9346 (not (member this org-not-done-keywords)))
9347 ;; This is now a todo state and was not one before
9348 ;; If there was a CLOSED time stamp, get rid of it.
9349 (org-add-planning-info nil nil 'closed))
9350 (when (and now-done-p org-log-done)
9351 ;; It is now done, and it was not done before
9352 (org-add-planning-info 'closed (org-current-time))
9353 (if (and (not dolog) (eq 'note org-log-done))
9354 (org-add-log-setup 'done state this 'findpos 'note)))
9355 (when (and state dolog)
9356 ;; This is a non-nil state, and we need to log it
9357 (org-add-log-setup 'state state this 'findpos dolog)))
9358 ;; Fixup tag positioning
9359 (org-todo-trigger-tag-changes state)
9360 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
9361 (when org-provide-todo-statistics
9362 (org-update-parent-todo-statistics))
9363 (run-hooks 'org-after-todo-state-change-hook)
9364 (if (and arg (not (member state org-done-keywords)))
9365 (setq head (org-get-todo-sequence-head state)))
9366 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
9367 ;; Do we need to trigger a repeat?
9368 (when now-done-p
9369 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
9370 ;; This is for the agenda, take a snapshot of the headline.
9371 (save-match-data
9372 (setq org-agenda-headline-snapshot-before-repeat
9373 (org-get-heading))))
9374 (org-auto-repeat-maybe state))
9375 ;; Fixup cursor location if close to the keyword
9376 (if (and (outline-on-heading-p)
9377 (not (bolp))
9378 (save-excursion (beginning-of-line 1)
9379 (looking-at org-todo-line-regexp))
9380 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
9381 (progn
9382 (goto-char (or (match-end 2) (match-end 1)))
9383 (and (looking-at " ") (just-one-space))))
9384 (when org-trigger-hook
9385 (save-excursion
9386 (run-hook-with-args 'org-trigger-hook change-plist))))))))
9387
9388 (defun org-block-todo-from-children-or-siblings-or-parent (change-plist)
9389 "Block turning an entry into a TODO, using the hierarchy.
9390 This checks whether the current task should be blocked from state
9391 changes. Such blocking occurs when:
9392
9393 1. The task has children which are not all in a completed state.
9394
9395 2. A task has a parent with the property :ORDERED:, and there
9396 are siblings prior to the current task with incomplete
9397 status.
9398
9399 3. The parent of the task is blocked because it has siblings that should
9400 be done first, or is child of a block grandparent TODO entry."
9401
9402 (catch 'dont-block
9403 ;; If this is not a todo state change, or if this entry is already DONE,
9404 ;; do not block
9405 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9406 (member (plist-get change-plist :from)
9407 (cons 'done org-done-keywords))
9408 (member (plist-get change-plist :to)
9409 (cons 'todo org-not-done-keywords)))
9410 (throw 'dont-block t))
9411 ;; If this task has children, and any are undone, it's blocked
9412 (save-excursion
9413 (org-back-to-heading t)
9414 (let ((this-level (funcall outline-level)))
9415 (outline-next-heading)
9416 (let ((child-level (funcall outline-level)))
9417 (while (and (not (eobp))
9418 (> child-level this-level))
9419 ;; this todo has children, check whether they are all
9420 ;; completed
9421 (if (and (not (org-entry-is-done-p))
9422 (org-entry-is-todo-p))
9423 (throw 'dont-block nil))
9424 (outline-next-heading)
9425 (setq child-level (funcall outline-level))))))
9426 ;; Otherwise, if the task's parent has the :ORDERED: property, and
9427 ;; any previous siblings are undone, it's blocked
9428 (save-excursion
9429 (org-back-to-heading t)
9430 (let* ((pos (point))
9431 (parent-pos (and (org-up-heading-safe) (point))))
9432 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9433 (when (and (org-entry-get (point) "ORDERED")
9434 (forward-line 1)
9435 (re-search-forward org-not-done-heading-regexp pos t))
9436 (throw 'dont-block nil)) ; block, there is an older sibling not done.
9437 ;; Search further up the hierarchy, to see if an anchestor is blocked
9438 (while t
9439 (goto-char parent-pos)
9440 (if (not (looking-at org-not-done-heading-regexp))
9441 (throw 'dont-block t)) ; do not block, parent is not a TODO
9442 (setq pos (point))
9443 (setq parent-pos (and (org-up-heading-safe) (point)))
9444 (if (not parent-pos) (throw 'dont-block t)) ; no parent
9445 (when (and (org-entry-get (point) "ORDERED")
9446 (forward-line 1)
9447 (re-search-forward org-not-done-heading-regexp pos t))
9448 (throw 'dont-block nil))))))) ; block, older sibling not done.
9449
9450 (defcustom org-track-ordered-property-with-tag nil
9451 "Should the ORDERED property also be shown as a tag?
9452 The ORDERED property decides if an entry should require subtasks to be
9453 completed in sequence. Since a property is not very visible, setting
9454 this option means that toggling the ORDERED property with the command
9455 `org-toggle-ordered-property' will also toggle a tag ORDERED. That tag is
9456 not relevant for the behavior, but it makes things more visible.
9457
9458 Note that toggling the tag with tags commands will not change the property
9459 and therefore not influence behavior!
9460
9461 This can be t, meaning the tag ORDERED should be used, It can also be a
9462 string to select a different tag for this task."
9463 :group 'org-todo
9464 :type '(choice
9465 (const :tag "No tracking" nil)
9466 (const :tag "Track with ORDERED tag" t)
9467 (string :tag "Use other tag")))
9468
9469 (defun org-toggle-ordered-property ()
9470 "Toggle the ORDERED property of the current entry.
9471 For better visibility, you can track the value of this property with a tag.
9472 See variable `org-track-ordered-property-with-tag'."
9473 (interactive)
9474 (let* ((t1 org-track-ordered-property-with-tag)
9475 (tag (and t1 (if (stringp t1) t1 "ORDERED"))))
9476 (save-excursion
9477 (org-back-to-heading)
9478 (if (org-entry-get nil "ORDERED")
9479 (progn
9480 (org-delete-property "ORDERED")
9481 (and tag (org-toggle-tag tag 'off))
9482 (message "Subtasks can be completed in arbitrary order"))
9483 (org-entry-put nil "ORDERED" "t")
9484 (and tag (org-toggle-tag tag 'on))
9485 (message "Subtasks must be completed in sequence")))))
9486
9487 (defvar org-blocked-by-checkboxes) ; dynamically scoped
9488 (defun org-block-todo-from-checkboxes (change-plist)
9489 "Block turning an entry into a TODO, using checkboxes.
9490 This checks whether the current task should be blocked from state
9491 changes because there are uncheckd boxes in this entry."
9492 (catch 'dont-block
9493 ;; If this is not a todo state change, or if this entry is already DONE,
9494 ;; do not block
9495 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
9496 (member (plist-get change-plist :from)
9497 (cons 'done org-done-keywords))
9498 (member (plist-get change-plist :to)
9499 (cons 'todo org-not-done-keywords)))
9500 (throw 'dont-block t))
9501 ;; If this task has checkboxes that are not checked, it's blocked
9502 (save-excursion
9503 (org-back-to-heading t)
9504 (let ((beg (point)) end)
9505 (outline-next-heading)
9506 (setq end (point))
9507 (goto-char beg)
9508 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
9509 end t)
9510 (progn
9511 (if (boundp 'org-blocked-by-checkboxes)
9512 (setq org-blocked-by-checkboxes t))
9513 (throw 'dont-block nil)))))
9514 t)) ; do not block
9515
9516 (defvar org-entry-property-inherited-from) ;; defined below
9517 (defun org-update-parent-todo-statistics ()
9518 "Update any statistics cookie in the parent of the current headline.
9519 When `org-hierarchical-todo-statistics' is nil, statistics will cover
9520 the entire subtree and this will travel up the hierarchy and update
9521 statistics everywhere."
9522 (interactive)
9523 (let* ((lim 0) prop
9524 (recursive (or (not org-hierarchical-todo-statistics)
9525 (string-match
9526 "\\<recursive\\>"
9527 (or (setq prop (org-entry-get
9528 nil "COOKIE_DATA" 'inherit)) ""))))
9529 (lim (or (and prop (marker-position
9530 org-entry-property-inherited-from))
9531 lim))
9532 (first t)
9533 (box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
9534 level ltoggle l1
9535 (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
9536 (catch 'exit
9537 (save-excursion
9538 (beginning-of-line 1)
9539 (if (org-at-heading-p)
9540 (setq ltoggle (funcall outline-level))
9541 (error "This should not happen"))
9542 (while (and (setq level (org-up-heading-safe))
9543 (or recursive first)
9544 (>= (point) lim))
9545 (setq first nil)
9546 (unless (and level
9547 (not (string-match
9548 "\\<checkbox\\>"
9549 (downcase
9550 (or (org-entry-get
9551 nil "COOKIE_DATA")
9552 "")))))
9553 (throw 'exit nil))
9554 (while (re-search-forward box-re (point-at-eol) t)
9555 (setq cnt-all 0 cnt-done 0 cookie-present t)
9556 (setq is-percent (match-end 2))
9557 (save-match-data
9558 (unless (outline-next-heading) (throw 'exit nil))
9559 (while (and (looking-at org-complex-heading-regexp)
9560 (> (setq l1 (length (match-string 1))) level))
9561 (setq kwd (and (or recursive (= l1 ltoggle))
9562 (match-string 2)))
9563 (if (or (eq org-provide-todo-statistics 'all-headlines)
9564 (and (listp org-provide-todo-statistics)
9565 (or (member kwd org-provide-todo-statistics)
9566 (member kwd org-done-keywords))))
9567 (setq cnt-all (1+ cnt-all))
9568 (if (eq org-provide-todo-statistics t)
9569 (and kwd (setq cnt-all (1+ cnt-all)))))
9570 (and (member kwd org-done-keywords)
9571 (setq cnt-done (1+ cnt-done)))
9572 (outline-next-heading)))
9573 (replace-match
9574 (if is-percent
9575 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
9576 (format "[%d/%d]" cnt-done cnt-all)))))
9577 (when cookie-present
9578 (run-hook-with-args 'org-after-todo-statistics-hook
9579 cnt-done (- cnt-all cnt-done)))))
9580 (run-hooks 'org-todo-statistics-hook)))
9581
9582 (defvar org-after-todo-statistics-hook nil
9583 "Hook that is called after a TODO statistics cookie has been updated.
9584 Each function is called with two arguments: the number of not-done entries
9585 and the number of done entries.
9586
9587 For example, the following function, when added to this hook, will switch
9588 an entry to DONE when all children are done, and back to TODO when new
9589 entries are set to a TODO status. Note that this hook is only called
9590 when there is a statistics cookie in the headline!
9591
9592 (defun org-summary-todo (n-done n-not-done)
9593 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
9594 (let (org-log-done org-log-states) ; turn off logging
9595 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
9596 ")
9597
9598 (defvar org-todo-statistics-hook nil
9599 "Hook that is run whenever Org thinks TODO statistics should be updated.
9600 This hook runs even if there is no statisics cookie present, in which case
9601 `org-after-todo-statistics-hook' would not run.")
9602
9603 (defun org-todo-trigger-tag-changes (state)
9604 "Apply the changes defined in `org-todo-state-tags-triggers'."
9605 (let ((l org-todo-state-tags-triggers)
9606 changes)
9607 (when (or (not state) (equal state ""))
9608 (setq changes (append changes (cdr (assoc "" l)))))
9609 (when (and (stringp state) (> (length state) 0))
9610 (setq changes (append changes (cdr (assoc state l)))))
9611 (when (member state org-not-done-keywords)
9612 (setq changes (append changes (cdr (assoc 'todo l)))))
9613 (when (member state org-done-keywords)
9614 (setq changes (append changes (cdr (assoc 'done l)))))
9615 (dolist (c changes)
9616 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
9617
9618 (defun org-local-logging (value)
9619 "Get logging settings from a property VALUE."
9620 (let* (words w a)
9621 ;; directly set the variables, they are already local.
9622 (setq org-log-done nil
9623 org-log-repeat nil
9624 org-todo-log-states nil)
9625 (setq words (org-split-string value))
9626 (while (setq w (pop words))
9627 (cond
9628 ((setq a (assoc w org-startup-options))
9629 (and (member (nth 1 a) '(org-log-done org-log-repeat))
9630 (set (nth 1 a) (nth 2 a))))
9631 ((setq a (org-extract-log-state-settings w))
9632 (and (member (car a) org-todo-keywords-1)
9633 (push a org-todo-log-states)))))))
9634
9635 (defun org-get-todo-sequence-head (kwd)
9636 "Return the head of the TODO sequence to which KWD belongs.
9637 If KWD is not set, check if there is a text property remembering the
9638 right sequence."
9639 (let (p)
9640 (cond
9641 ((not kwd)
9642 (or (get-text-property (point-at-bol) 'org-todo-head)
9643 (progn
9644 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
9645 nil (point-at-eol)))
9646 (get-text-property p 'org-todo-head))))
9647 ((not (member kwd org-todo-keywords-1))
9648 (car org-todo-keywords-1))
9649 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
9650
9651 (defun org-fast-todo-selection ()
9652 "Fast TODO keyword selection with single keys.
9653 Returns the new TODO keyword, or nil if no state change should occur."
9654 (let* ((fulltable org-todo-key-alist)
9655 (done-keywords org-done-keywords) ;; needed for the faces.
9656 (maxlen (apply 'max (mapcar
9657 (lambda (x)
9658 (if (stringp (car x)) (string-width (car x)) 0))
9659 fulltable)))
9660 (expert nil)
9661 (fwidth (+ maxlen 3 1 3))
9662 (ncol (/ (- (window-width) 4) fwidth))
9663 tg cnt e c tbl
9664 groups ingroup)
9665 (save-excursion
9666 (save-window-excursion
9667 (if expert
9668 (set-buffer (get-buffer-create " *Org todo*"))
9669 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
9670 (erase-buffer)
9671 (org-set-local 'org-done-keywords done-keywords)
9672 (setq tbl fulltable cnt 0)
9673 (while (setq e (pop tbl))
9674 (cond
9675 ((equal e '(:startgroup))
9676 (push '() groups) (setq ingroup t)
9677 (when (not (= cnt 0))
9678 (setq cnt 0)
9679 (insert "\n"))
9680 (insert "{ "))
9681 ((equal e '(:endgroup))
9682 (setq ingroup nil cnt 0)
9683 (insert "}\n"))
9684 ((equal e '(:newline))
9685 (when (not (= cnt 0))
9686 (setq cnt 0)
9687 (insert "\n")
9688 (setq e (car tbl))
9689 (while (equal (car tbl) '(:newline))
9690 (insert "\n")
9691 (setq tbl (cdr tbl)))))
9692 (t
9693 (setq tg (car e) c (cdr e))
9694 (if ingroup (push tg (car groups)))
9695 (setq tg (org-add-props tg nil 'face
9696 (org-get-todo-face tg)))
9697 (if (and (= cnt 0) (not ingroup)) (insert " "))
9698 (insert "[" c "] " tg (make-string
9699 (- fwidth 4 (length tg)) ?\ ))
9700 (when (= (setq cnt (1+ cnt)) ncol)
9701 (insert "\n")
9702 (if ingroup (insert " "))
9703 (setq cnt 0)))))
9704 (insert "\n")
9705 (goto-char (point-min))
9706 (if (not expert) (org-fit-window-to-buffer))
9707 (message "[a-z..]:Set [SPC]:clear")
9708 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9709 (cond
9710 ((or (= c ?\C-g)
9711 (and (= c ?q) (not (rassoc c fulltable))))
9712 (setq quit-flag t))
9713 ((= c ?\ ) nil)
9714 ((setq e (rassoc c fulltable) tg (car e))
9715 tg)
9716 (t (setq quit-flag t)))))))
9717
9718 (defun org-entry-is-todo-p ()
9719 (member (org-get-todo-state) org-not-done-keywords))
9720
9721 (defun org-entry-is-done-p ()
9722 (member (org-get-todo-state) org-done-keywords))
9723
9724 (defun org-get-todo-state ()
9725 (save-excursion
9726 (org-back-to-heading t)
9727 (and (looking-at org-todo-line-regexp)
9728 (match-end 2)
9729 (match-string 2))))
9730
9731 (defun org-at-date-range-p (&optional inactive-ok)
9732 "Is the cursor inside a date range?"
9733 (interactive)
9734 (save-excursion
9735 (catch 'exit
9736 (let ((pos (point)))
9737 (skip-chars-backward "^[<\r\n")
9738 (skip-chars-backward "<[")
9739 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9740 (>= (match-end 0) pos)
9741 (throw 'exit t))
9742 (skip-chars-backward "^<[\r\n")
9743 (skip-chars-backward "<[")
9744 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
9745 (>= (match-end 0) pos)
9746 (throw 'exit t)))
9747 nil)))
9748
9749 (defun org-get-repeat ()
9750 "Check if there is a deadline/schedule with repeater in this entry."
9751 (save-match-data
9752 (save-excursion
9753 (org-back-to-heading t)
9754 (if (re-search-forward
9755 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
9756 (match-string 1)))))
9757
9758 (defvar org-last-changed-timestamp)
9759 (defvar org-last-inserted-timestamp)
9760 (defvar org-log-post-message)
9761 (defvar org-log-note-purpose)
9762 (defvar org-log-note-how)
9763 (defvar org-log-note-extra)
9764 (defun org-auto-repeat-maybe (done-word)
9765 "Check if the current headline contains a repeated deadline/schedule.
9766 If yes, set TODO state back to what it was and change the base date
9767 of repeating deadline/scheduled time stamps to new date.
9768 This function is run automatically after each state change to a DONE state."
9769 ;; last-state is dynamically scoped into this function
9770 (let* ((repeat (org-get-repeat))
9771 (aa (assoc last-state org-todo-kwd-alist))
9772 (interpret (nth 1 aa))
9773 (head (nth 2 aa))
9774 (whata '(("d" . day) ("m" . month) ("y" . year)))
9775 (msg "Entry repeats: ")
9776 (org-log-done nil)
9777 (org-todo-log-states nil)
9778 (nshiftmax 10) (nshift 0)
9779 re type n what ts time)
9780 (when repeat
9781 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
9782 (org-todo (if (eq interpret 'type) last-state head))
9783 (org-entry-put nil "LAST_REPEAT" (format-time-string
9784 (org-time-stamp-format t t)))
9785 (when org-log-repeat
9786 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
9787 (memq 'org-add-log-note post-command-hook))
9788 ;; OK, we are already setup for some record
9789 (if (eq org-log-repeat 'note)
9790 ;; make sure we take a note, not only a time stamp
9791 (setq org-log-note-how 'note))
9792 ;; Set up for taking a record
9793 (org-add-log-setup 'state (or done-word (car org-done-keywords))
9794 last-state
9795 'findpos org-log-repeat)))
9796 (org-back-to-heading t)
9797 (org-add-planning-info nil nil 'closed)
9798 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
9799 org-deadline-time-regexp "\\)\\|\\("
9800 org-ts-regexp "\\)"))
9801 (while (re-search-forward
9802 re (save-excursion (outline-next-heading) (point)) t)
9803 (setq type (if (match-end 1) org-scheduled-string
9804 (if (match-end 3) org-deadline-string "Plain:"))
9805 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
9806 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
9807 (setq n (string-to-number (match-string 2 ts))
9808 what (match-string 3 ts))
9809 (if (equal what "w") (setq n (* n 7) what "d"))
9810 ;; Preparation, see if we need to modify the start date for the change
9811 (when (match-end 1)
9812 (setq time (save-match-data (org-time-string-to-time ts)))
9813 (cond
9814 ((equal (match-string 1 ts) ".")
9815 ;; Shift starting date to today
9816 (org-timestamp-change
9817 (- (time-to-days (current-time)) (time-to-days time))
9818 'day))
9819 ((equal (match-string 1 ts) "+")
9820 (while (or (= nshift 0)
9821 (<= (time-to-days time) (time-to-days (current-time))))
9822 (when (= (incf nshift) nshiftmax)
9823 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
9824 (error "Abort")))
9825 (org-timestamp-change n (cdr (assoc what whata)))
9826 (org-at-timestamp-p t)
9827 (setq ts (match-string 1))
9828 (setq time (save-match-data (org-time-string-to-time ts))))
9829 (org-timestamp-change (- n) (cdr (assoc what whata)))
9830 ;; rematch, so that we have everything in place for the real shift
9831 (org-at-timestamp-p t)
9832 (setq ts (match-string 1))
9833 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
9834 (org-timestamp-change n (cdr (assoc what whata)))
9835 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
9836 (setq org-log-post-message msg)
9837 (message "%s" msg))))
9838
9839 (defun org-show-todo-tree (arg)
9840 "Make a compact tree which shows all headlines marked with TODO.
9841 The tree will show the lines where the regexp matches, and all higher
9842 headlines above the match.
9843 With a \\[universal-argument] prefix, prompt for a regexp to match.
9844 With a numeric prefix N, construct a sparse tree for the Nth element
9845 of `org-todo-keywords-1'."
9846 (interactive "P")
9847 (let ((case-fold-search nil)
9848 (kwd-re
9849 (cond ((null arg) org-not-done-regexp)
9850 ((equal arg '(4))
9851 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
9852 (mapcar 'list org-todo-keywords-1))))
9853 (concat "\\("
9854 (mapconcat 'identity (org-split-string kwd "|") "\\|")
9855 "\\)\\>")))
9856 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
9857 (regexp-quote (nth (1- (prefix-numeric-value arg))
9858 org-todo-keywords-1)))
9859 (t (error "Invalid prefix argument: %s" arg)))))
9860 (message "%d TODO entries found"
9861 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
9862
9863 (defun org-deadline (&optional remove time)
9864 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
9865 With argument REMOVE, remove any deadline from the item.
9866 When TIME is set, it should be an internal time specification, and the
9867 scheduling will use the corresponding date."
9868 (interactive "P")
9869 (if remove
9870 (progn
9871 (org-remove-timestamp-with-keyword org-deadline-string)
9872 (message "Item no longer has a deadline."))
9873 (if (org-get-repeat)
9874 (error "Cannot change deadline on task with repeater, please do that by hand")
9875 (org-add-planning-info 'deadline time 'closed)
9876 (message "Deadline on %s" org-last-inserted-timestamp))))
9877
9878 (defun org-schedule (&optional remove time)
9879 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
9880 With argument REMOVE, remove any scheduling date from the item.
9881 When TIME is set, it should be an internal time specification, and the
9882 scheduling will use the corresponding date."
9883 (interactive "P")
9884 (if remove
9885 (progn
9886 (org-remove-timestamp-with-keyword org-scheduled-string)
9887 (message "Item is no longer scheduled."))
9888 (if (org-get-repeat)
9889 (error "Cannot reschedule task with repeater, please do that by hand")
9890 (org-add-planning-info 'scheduled time 'closed)
9891 (message "Scheduled to %s" org-last-inserted-timestamp))))
9892
9893 (defun org-get-scheduled-time (pom &optional inherit)
9894 "Get the scheduled time as a time tuple, of a format suitable
9895 for calling org-schedule with, or if there is no scheduling,
9896 returns nil."
9897 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
9898 (when time
9899 (apply 'encode-time (org-parse-time-string time)))))
9900
9901 (defun org-get-deadline-time (pom &optional inherit)
9902 "Get the deadine as a time tuple, of a format suitable for
9903 calling org-deadlin with, or if there is no scheduling, returns
9904 nil."
9905 (let ((time (org-entry-get pom "DEADLINE" inherit)))
9906 (when time
9907 (apply 'encode-time (org-parse-time-string time)))))
9908
9909 (defun org-remove-timestamp-with-keyword (keyword)
9910 "Remove all time stamps with KEYWORD in the current entry."
9911 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
9912 beg)
9913 (save-excursion
9914 (org-back-to-heading t)
9915 (setq beg (point))
9916 (org-end-of-subtree t t)
9917 (while (re-search-backward re beg t)
9918 (replace-match "")
9919 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9920 (equal (char-before) ?\ ))
9921 (backward-delete-char 1)
9922 (if (string-match "^[ \t]*$" (buffer-substring
9923 (point-at-bol) (point-at-eol)))
9924 (delete-region (point-at-bol)
9925 (min (point-max) (1+ (point-at-eol))))))))))
9926
9927 (defun org-add-planning-info (what &optional time &rest remove)
9928 "Insert new timestamp with keyword in the line directly after the headline.
9929 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9930 If non is given, the user is prompted for a date.
9931 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9932 be removed."
9933 (interactive)
9934 (let (org-time-was-given org-end-time-was-given ts
9935 end default-time default-input)
9936
9937 (catch 'exit
9938 (when (and (not time) (memq what '(scheduled deadline)))
9939 ;; Try to get a default date/time from existing timestamp
9940 (save-excursion
9941 (org-back-to-heading t)
9942 (setq end (save-excursion (outline-next-heading) (point)))
9943 (when (re-search-forward (if (eq what 'scheduled)
9944 org-scheduled-time-regexp
9945 org-deadline-time-regexp)
9946 end t)
9947 (setq ts (match-string 1)
9948 default-time
9949 (apply 'encode-time (org-parse-time-string ts))
9950 default-input (and ts (org-get-compact-tod ts))))))
9951 (when what
9952 ;; If necessary, get the time from the user
9953 (setq time (or time (org-read-date nil 'to-time nil nil
9954 default-time default-input))))
9955
9956 (when (and org-insert-labeled-timestamps-at-point
9957 (member what '(scheduled deadline)))
9958 (insert
9959 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9960 (org-insert-time-stamp time org-time-was-given
9961 nil nil nil (list org-end-time-was-given))
9962 (setq what nil))
9963 (save-excursion
9964 (save-restriction
9965 (let (col list elt ts buffer-invisibility-spec)
9966 (org-back-to-heading t)
9967 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9968 (goto-char (match-end 1))
9969 (setq col (current-column))
9970 (goto-char (match-end 0))
9971 (if (eobp) (insert "\n") (forward-char 1))
9972 (when (and (not what)
9973 (not (looking-at
9974 (concat "[ \t]*"
9975 org-keyword-time-not-clock-regexp))))
9976 ;; Nothing to add, nothing to remove...... :-)
9977 (throw 'exit nil))
9978 (if (and (not (looking-at outline-regexp))
9979 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9980 "[^\r\n]*"))
9981 (not (equal (match-string 1) org-clock-string)))
9982 (narrow-to-region (match-beginning 0) (match-end 0))
9983 (insert-before-markers "\n")
9984 (backward-char 1)
9985 (narrow-to-region (point) (point))
9986 (and org-adapt-indentation (org-indent-to-column col)))
9987 ;; Check if we have to remove something.
9988 (setq list (cons what remove))
9989 (while list
9990 (setq elt (pop list))
9991 (goto-char (point-min))
9992 (when (or (and (eq elt 'scheduled)
9993 (re-search-forward org-scheduled-time-regexp nil t))
9994 (and (eq elt 'deadline)
9995 (re-search-forward org-deadline-time-regexp nil t))
9996 (and (eq elt 'closed)
9997 (re-search-forward org-closed-time-regexp nil t)))
9998 (replace-match "")
9999 (if (looking-at "--+<[^>]+>") (replace-match ""))
10000 (if (looking-at " +") (replace-match ""))))
10001 (goto-char (point-max))
10002 (when what
10003 (insert
10004 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
10005 (cond ((eq what 'scheduled) org-scheduled-string)
10006 ((eq what 'deadline) org-deadline-string)
10007 ((eq what 'closed) org-closed-string))
10008 " ")
10009 (setq ts (org-insert-time-stamp
10010 time
10011 (or org-time-was-given
10012 (and (eq what 'closed) org-log-done-with-time))
10013 (eq what 'closed)
10014 nil nil (list org-end-time-was-given)))
10015 (end-of-line 1))
10016 (goto-char (point-min))
10017 (widen)
10018 (if (and (looking-at "[ \t]+\n")
10019 (equal (char-before) ?\n))
10020 (delete-region (1- (point)) (point-at-eol)))
10021 ts))))))
10022
10023 (defvar org-log-note-marker (make-marker))
10024 (defvar org-log-note-purpose nil)
10025 (defvar org-log-note-state nil)
10026 (defvar org-log-note-previous-state nil)
10027 (defvar org-log-note-how nil)
10028 (defvar org-log-note-extra nil)
10029 (defvar org-log-note-window-configuration nil)
10030 (defvar org-log-note-return-to (make-marker))
10031 (defvar org-log-post-message nil
10032 "Message to be displayed after a log note has been stored.
10033 The auto-repeater uses this.")
10034
10035 (defun org-add-note ()
10036 "Add a note to the current entry.
10037 This is done in the same way as adding a state change note."
10038 (interactive)
10039 (org-add-log-setup 'note nil nil 'findpos nil))
10040
10041 (defvar org-property-end-re)
10042 (defun org-add-log-setup (&optional purpose state prev-state
10043 findpos how &optional extra)
10044 "Set up the post command hook to take a note.
10045 If this is about to TODO state change, the new state is expected in STATE.
10046 When FINDPOS is non-nil, find the correct position for the note in
10047 the current entry. If not, assume that it can be inserted at point.
10048 HOW is an indicator what kind of note should be created.
10049 EXTRA is additional text that will be inserted into the notes buffer."
10050 (let* ((org-log-into-drawer (org-log-into-drawer))
10051 (drawer (cond ((stringp org-log-into-drawer)
10052 org-log-into-drawer)
10053 (org-log-into-drawer "LOGBOOK")
10054 (t nil))))
10055 (save-restriction
10056 (save-excursion
10057 (when findpos
10058 (org-back-to-heading t)
10059 (narrow-to-region (point) (save-excursion
10060 (outline-next-heading) (point)))
10061 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
10062 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
10063 "[^\r\n]*\\)?"))
10064 (goto-char (match-end 0))
10065 (cond
10066 (drawer
10067 (if (re-search-forward (concat "^[ \t]*:" drawer ":[ \t]*$")
10068 nil t)
10069 (progn
10070 (goto-char (match-end 0))
10071 (or org-log-states-order-reversed
10072 (and (re-search-forward org-property-end-re nil t)
10073 (goto-char (1- (match-beginning 0))))))
10074 (insert "\n:" drawer ":\n:END:")
10075 (beginning-of-line 0)
10076 (org-indent-line-function)
10077 (beginning-of-line 2)
10078 (org-indent-line-function)
10079 (end-of-line 0)))
10080 ((and org-log-state-notes-insert-after-drawers
10081 (save-excursion
10082 (forward-line) (looking-at org-drawer-regexp)))
10083 (forward-line)
10084 (while (looking-at org-drawer-regexp)
10085 (goto-char (match-end 0))
10086 (re-search-forward org-property-end-re (point-max) t)
10087 (forward-line))
10088 (forward-line -1)))
10089 (unless org-log-states-order-reversed
10090 (and (= (char-after) ?\n) (forward-char 1))
10091 (org-skip-over-state-notes)
10092 (skip-chars-backward " \t\n\r")))
10093 (move-marker org-log-note-marker (point))
10094 (setq org-log-note-purpose purpose
10095 org-log-note-state state
10096 org-log-note-previous-state prev-state
10097 org-log-note-how how
10098 org-log-note-extra extra)
10099 (add-hook 'post-command-hook 'org-add-log-note 'append)))))
10100
10101 (defun org-skip-over-state-notes ()
10102 "Skip past the list of State notes in an entry."
10103 (if (looking-at "\n[ \t]*- State") (forward-char 1))
10104 (while (looking-at "[ \t]*- State")
10105 (condition-case nil
10106 (org-next-item)
10107 (error (org-end-of-item)))))
10108
10109 (defun org-add-log-note (&optional purpose)
10110 "Pop up a window for taking a note, and add this note later at point."
10111 (remove-hook 'post-command-hook 'org-add-log-note)
10112 (setq org-log-note-window-configuration (current-window-configuration))
10113 (delete-other-windows)
10114 (move-marker org-log-note-return-to (point))
10115 (switch-to-buffer (marker-buffer org-log-note-marker))
10116 (goto-char org-log-note-marker)
10117 (org-switch-to-buffer-other-window "*Org Note*")
10118 (erase-buffer)
10119 (if (memq org-log-note-how '(time state))
10120 (let (current-prefix-arg) (org-store-log-note))
10121 (let ((org-inhibit-startup t)) (org-mode))
10122 (insert (format "# Insert note for %s.
10123 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
10124 (cond
10125 ((eq org-log-note-purpose 'clock-out) "stopped clock")
10126 ((eq org-log-note-purpose 'done) "closed todo item")
10127 ((eq org-log-note-purpose 'state)
10128 (format "state change from \"%s\" to \"%s\""
10129 (or org-log-note-previous-state "")
10130 (or org-log-note-state "")))
10131 ((eq org-log-note-purpose 'note)
10132 "this entry")
10133 (t (error "This should not happen")))))
10134 (if org-log-note-extra (insert org-log-note-extra))
10135 (org-set-local 'org-finish-function 'org-store-log-note)))
10136
10137 (defvar org-note-abort nil) ; dynamically scoped
10138 (defun org-store-log-note ()
10139 "Finish taking a log note, and insert it to where it belongs."
10140 (let ((txt (buffer-string))
10141 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
10142 lines ind)
10143 (kill-buffer (current-buffer))
10144 (while (string-match "\\`#.*\n[ \t\n]*" txt)
10145 (setq txt (replace-match "" t t txt)))
10146 (if (string-match "\\s-+\\'" txt)
10147 (setq txt (replace-match "" t t txt)))
10148 (setq lines (org-split-string txt "\n"))
10149 (when (and note (string-match "\\S-" note))
10150 (setq note
10151 (org-replace-escapes
10152 note
10153 (list (cons "%u" (user-login-name))
10154 (cons "%U" user-full-name)
10155 (cons "%t" (format-time-string
10156 (org-time-stamp-format 'long 'inactive)
10157 (current-time)))
10158 (cons "%s" (if org-log-note-state
10159 (concat "\"" org-log-note-state "\"")
10160 ""))
10161 (cons "%S" (if org-log-note-previous-state
10162 (concat "\"" org-log-note-previous-state "\"")
10163 "\"\"")))))
10164 (if lines (setq note (concat note " \\\\")))
10165 (push note lines))
10166 (when (or current-prefix-arg org-note-abort)
10167 (when org-log-into-drawer
10168 (org-remove-empty-drawer-at
10169 (if (stringp org-log-into-drawer) org-log-into-drawer "LOGBOOK")
10170 org-log-note-marker))
10171 (setq lines nil))
10172 (when lines
10173 (save-excursion
10174 (set-buffer (marker-buffer org-log-note-marker))
10175 (save-excursion
10176 (goto-char org-log-note-marker)
10177 (move-marker org-log-note-marker nil)
10178 (end-of-line 1)
10179 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
10180 (insert "- " (pop lines))
10181 (org-indent-line-function)
10182 (beginning-of-line 1)
10183 (looking-at "[ \t]*")
10184 (setq ind (concat (match-string 0) " "))
10185 (end-of-line 1)
10186 (while lines (insert "\n" ind (pop lines)))
10187 (message "Note stored")
10188 (org-back-to-heading t)
10189 (org-cycle-hide-drawers 'children)))))
10190 (set-window-configuration org-log-note-window-configuration)
10191 (with-current-buffer (marker-buffer org-log-note-return-to)
10192 (goto-char org-log-note-return-to))
10193 (move-marker org-log-note-return-to nil)
10194 (and org-log-post-message (message "%s" org-log-post-message)))
10195
10196 (defun org-remove-empty-drawer-at (drawer pos)
10197 "Remove an emptyr DARWER drawer at position POS.
10198 POS may also be a marker."
10199 (with-current-buffer (if (markerp pos) (marker-buffer pos) (current-buffer))
10200 (save-excursion
10201 (save-restriction
10202 (widen)
10203 (goto-char pos)
10204 (if (org-in-regexp
10205 (concat "^[ \t]*:" drawer ":[ \t]*\n[ \t]*:END:[ \t]*\n?") 2)
10206 (replace-match ""))))))
10207
10208 (defun org-sparse-tree (&optional arg)
10209 "Create a sparse tree, prompt for the details.
10210 This command can create sparse trees. You first need to select the type
10211 of match used to create the tree:
10212
10213 t Show entries with a specific TODO keyword.
10214 m Show entries selected by a tags/property match.
10215 p Enter a property name and its value (both with completion on existing
10216 names/values) and show entries with that property.
10217 r Show entries matching a regular expression.
10218 d Show deadlines due within `org-deadline-warning-days'.
10219 b Show deadlines and scheduled items before a date.
10220 a Show deadlines and scheduled items after a date."
10221 (interactive "P")
10222 (let (ans kwd value)
10223 (message "Sparse tree: [/]regexp [t]odo-kwd [m]atch [p]roperty [d]eadlines [b]efore-date [a]fter-date")
10224 (setq ans (read-char-exclusive))
10225 (cond
10226 ((equal ans ?d)
10227 (call-interactively 'org-check-deadlines))
10228 ((equal ans ?b)
10229 (call-interactively 'org-check-before-date))
10230 ((equal ans ?a)
10231 (call-interactively 'org-check-after-date))
10232 ((equal ans ?t)
10233 (org-show-todo-tree '(4)))
10234 ((member ans '(?T ?m))
10235 (call-interactively 'org-match-sparse-tree))
10236 ((member ans '(?p ?P))
10237 (setq kwd (org-ido-completing-read "Property: "
10238 (mapcar 'list (org-buffer-property-keys))))
10239 (setq value (org-ido-completing-read "Value: "
10240 (mapcar 'list (org-property-values kwd))))
10241 (unless (string-match "\\`{.*}\\'" value)
10242 (setq value (concat "\"" value "\"")))
10243 (org-match-sparse-tree arg (concat kwd "=" value)))
10244 ((member ans '(?r ?R ?/))
10245 (call-interactively 'org-occur))
10246 (t (error "No such sparse tree command \"%c\"" ans)))))
10247
10248 (defvar org-occur-highlights nil
10249 "List of overlays used for occur matches.")
10250 (make-variable-buffer-local 'org-occur-highlights)
10251 (defvar org-occur-parameters nil
10252 "Parameters of the active org-occur calls.
10253 This is a list, each call to org-occur pushes as cons cell,
10254 containing the regular expression and the callback, onto the list.
10255 The list can contain several entries if `org-occur' has been called
10256 several time with the KEEP-PREVIOUS argument. Otherwise, this list
10257 will only contain one set of parameters. When the highlights are
10258 removed (for example with `C-c C-c', or with the next edit (depending
10259 on `org-remove-highlights-with-change'), this variable is emptied
10260 as well.")
10261 (make-variable-buffer-local 'org-occur-parameters)
10262
10263 (defun org-occur (regexp &optional keep-previous callback)
10264 "Make a compact tree which shows all matches of REGEXP.
10265 The tree will show the lines where the regexp matches, and all higher
10266 headlines above the match. It will also show the heading after the match,
10267 to make sure editing the matching entry is easy.
10268 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
10269 call to `org-occur' will be kept, to allow stacking of calls to this
10270 command.
10271 If CALLBACK is non-nil, it is a function which is called to confirm
10272 that the match should indeed be shown."
10273 (interactive "sRegexp: \nP")
10274 (when (equal regexp "")
10275 (error "Regexp cannot be empty"))
10276 (unless keep-previous
10277 (org-remove-occur-highlights nil nil t))
10278 (push (cons regexp callback) org-occur-parameters)
10279 (let ((cnt 0))
10280 (save-excursion
10281 (goto-char (point-min))
10282 (if (or (not keep-previous) ; do not want to keep
10283 (not org-occur-highlights)) ; no previous matches
10284 ;; hide everything
10285 (org-overview))
10286 (while (re-search-forward regexp nil t)
10287 (when (or (not callback)
10288 (save-match-data (funcall callback)))
10289 (setq cnt (1+ cnt))
10290 (when org-highlight-sparse-tree-matches
10291 (org-highlight-new-match (match-beginning 0) (match-end 0)))
10292 (org-show-context 'occur-tree))))
10293 (when org-remove-highlights-with-change
10294 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
10295 nil 'local))
10296 (unless org-sparse-tree-open-archived-trees
10297 (org-hide-archived-subtrees (point-min) (point-max)))
10298 (run-hooks 'org-occur-hook)
10299 (if (interactive-p)
10300 (message "%d match(es) for regexp %s" cnt regexp))
10301 cnt))
10302
10303 (defun org-show-context (&optional key)
10304 "Make sure point and context and visible.
10305 How much context is shown depends upon the variables
10306 `org-show-hierarchy-above', `org-show-following-heading'. and
10307 `org-show-siblings'."
10308 (let ((heading-p (org-on-heading-p t))
10309 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
10310 (following-p (org-get-alist-option org-show-following-heading key))
10311 (entry-p (org-get-alist-option org-show-entry-below key))
10312 (siblings-p (org-get-alist-option org-show-siblings key)))
10313 (catch 'exit
10314 ;; Show heading or entry text
10315 (if (and heading-p (not entry-p))
10316 (org-flag-heading nil) ; only show the heading
10317 (and (or entry-p (org-invisible-p) (org-invisible-p2))
10318 (org-show-hidden-entry))) ; show entire entry
10319 (when following-p
10320 ;; Show next sibling, or heading below text
10321 (save-excursion
10322 (and (if heading-p (org-goto-sibling) (outline-next-heading))
10323 (org-flag-heading nil))))
10324 (when siblings-p (org-show-siblings))
10325 (when hierarchy-p
10326 ;; show all higher headings, possibly with siblings
10327 (save-excursion
10328 (while (and (condition-case nil
10329 (progn (org-up-heading-all 1) t)
10330 (error nil))
10331 (not (bobp)))
10332 (org-flag-heading nil)
10333 (when siblings-p (org-show-siblings))))))))
10334
10335 (defun org-reveal (&optional siblings)
10336 "Show current entry, hierarchy above it, and the following headline.
10337 This can be used to show a consistent set of context around locations
10338 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
10339 not t for the search context.
10340
10341 With optional argument SIBLINGS, on each level of the hierarchy all
10342 siblings are shown. This repairs the tree structure to what it would
10343 look like when opened with hierarchical calls to `org-cycle'."
10344 (interactive "P")
10345 (let ((org-show-hierarchy-above t)
10346 (org-show-following-heading t)
10347 (org-show-siblings (if siblings t org-show-siblings)))
10348 (org-show-context nil)))
10349
10350 (defun org-highlight-new-match (beg end)
10351 "Highlight from BEG to END and mark the highlight is an occur headline."
10352 (let ((ov (org-make-overlay beg end)))
10353 (org-overlay-put ov 'face 'secondary-selection)
10354 (push ov org-occur-highlights)))
10355
10356 (defun org-remove-occur-highlights (&optional beg end noremove)
10357 "Remove the occur highlights from the buffer.
10358 BEG and END are ignored. If NOREMOVE is nil, remove this function
10359 from the `before-change-functions' in the current buffer."
10360 (interactive)
10361 (unless org-inhibit-highlight-removal
10362 (mapc 'org-delete-overlay org-occur-highlights)
10363 (setq org-occur-highlights nil)
10364 (setq org-occur-parameters nil)
10365 (unless noremove
10366 (remove-hook 'before-change-functions
10367 'org-remove-occur-highlights 'local))))
10368
10369 ;;;; Priorities
10370
10371 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
10372 "Regular expression matching the priority indicator.")
10373
10374 (defvar org-remove-priority-next-time nil)
10375
10376 (defun org-priority-up ()
10377 "Increase the priority of the current item."
10378 (interactive)
10379 (org-priority 'up))
10380
10381 (defun org-priority-down ()
10382 "Decrease the priority of the current item."
10383 (interactive)
10384 (org-priority 'down))
10385
10386 (defun org-priority (&optional action)
10387 "Change the priority of an item by ARG.
10388 ACTION can be `set', `up', `down', or a character."
10389 (interactive)
10390 (unless org-enable-priority-commands
10391 (error "Priority commands are disabled"))
10392 (setq action (or action 'set))
10393 (let (current new news have remove)
10394 (save-excursion
10395 (org-back-to-heading t)
10396 (if (looking-at org-priority-regexp)
10397 (setq current (string-to-char (match-string 2))
10398 have t)
10399 (setq current org-default-priority))
10400 (cond
10401 ((or (eq action 'set)
10402 (if (featurep 'xemacs) (characterp action) (integerp action)))
10403 (if (not (eq action 'set))
10404 (setq new action)
10405 (message "Priority %c-%c, SPC to remove: "
10406 org-highest-priority org-lowest-priority)
10407 (setq new (read-char-exclusive)))
10408 (if (and (= (upcase org-highest-priority) org-highest-priority)
10409 (= (upcase org-lowest-priority) org-lowest-priority))
10410 (setq new (upcase new)))
10411 (cond ((equal new ?\ ) (setq remove t))
10412 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
10413 (error "Priority must be between `%c' and `%c'"
10414 org-highest-priority org-lowest-priority))))
10415 ((eq action 'up)
10416 (if (and (not have) (eq last-command this-command))
10417 (setq new org-lowest-priority)
10418 (setq new (if (and org-priority-start-cycle-with-default (not have))
10419 org-default-priority (1- current)))))
10420 ((eq action 'down)
10421 (if (and (not have) (eq last-command this-command))
10422 (setq new org-highest-priority)
10423 (setq new (if (and org-priority-start-cycle-with-default (not have))
10424 org-default-priority (1+ current)))))
10425 (t (error "Invalid action")))
10426 (if (or (< (upcase new) org-highest-priority)
10427 (> (upcase new) org-lowest-priority))
10428 (setq remove t))
10429 (setq news (format "%c" new))
10430 (if have
10431 (if remove
10432 (replace-match "" t t nil 1)
10433 (replace-match news t t nil 2))
10434 (if remove
10435 (error "No priority cookie found in line")
10436 (let ((case-fold-search nil))
10437 (looking-at org-todo-line-regexp))
10438 (if (match-end 2)
10439 (progn
10440 (goto-char (match-end 2))
10441 (insert " [#" news "]"))
10442 (goto-char (match-beginning 3))
10443 (insert "[#" news "] "))))
10444 (org-preserve-lc (org-set-tags nil 'align)))
10445 (if remove
10446 (message "Priority removed")
10447 (message "Priority of current item set to %s" news))))
10448
10449 (defun org-get-priority (s)
10450 "Find priority cookie and return priority."
10451 (save-match-data
10452 (if (not (string-match org-priority-regexp s))
10453 (* 1000 (- org-lowest-priority org-default-priority))
10454 (* 1000 (- org-lowest-priority
10455 (string-to-char (match-string 2 s)))))))
10456
10457 ;;;; Tags
10458
10459 (defvar org-agenda-archives-mode)
10460 (defvar org-map-continue-from nil
10461 "Position from where mapping should continue.
10462 Can be set byt the action argument to `org-scan-tag's and `org-map-entries'.")
10463
10464 (defvar org-scanner-tags nil
10465 "The current tag list while the tags scanner is running.")
10466 (defvar org-trust-scanner-tags nil
10467 "Should `org-get-tags-at' use the tags fro the scanner.
10468 This is for internal dynamical scoping only.
10469 When this is non-nil, the function `org-get-tags-at' will return the value
10470 of `org-scanner-tags' instead of building the list by itself. This
10471 can lead to large speed-ups when the tags scanner is used in a file with
10472 many entries, and when the list of tags is retrieved, for example to
10473 obtain a list of properties. Building the tags list for each entry in such
10474 a file becomes an N^2 operation - but with this variable set, it scales
10475 as N.")
10476
10477 (defun org-scan-tags (action matcher &optional todo-only)
10478 "Scan headline tags with inheritance and produce output ACTION.
10479
10480 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
10481 or `agenda' to produce an entry list for an agenda view. It can also be
10482 a Lisp form or a function that should be called at each matched headline, in
10483 this case the return value is a list of all return values from these calls.
10484
10485 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
10486 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
10487 only lines with a TODO keyword are included in the output."
10488 (require 'org-agenda)
10489 (let* ((re (concat "^" outline-regexp " *\\(\\<\\("
10490 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
10491 (org-re
10492 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
10493 (props (list 'face 'default
10494 'done-face 'org-agenda-done
10495 'undone-face 'default
10496 'mouse-face 'highlight
10497 'org-not-done-regexp org-not-done-regexp
10498 'org-todo-regexp org-todo-regexp
10499 'keymap org-agenda-keymap
10500 'help-echo
10501 (format "mouse-2 or RET jump to org file %s"
10502 (abbreviate-file-name
10503 (or (buffer-file-name (buffer-base-buffer))
10504 (buffer-name (buffer-base-buffer)))))))
10505 (case-fold-search nil)
10506 (org-map-continue-from nil)
10507 lspos tags tags-list
10508 (tags-alist (list (cons 0 org-file-tags)))
10509 (llast 0) rtn rtn1 level category i txt
10510 todo marker entry priority)
10511 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
10512 (setq action (list 'lambda nil action)))
10513 (save-excursion
10514 (goto-char (point-min))
10515 (when (eq action 'sparse-tree)
10516 (org-overview)
10517 (org-remove-occur-highlights))
10518 (while (re-search-forward re nil t)
10519 (catch :skip
10520 (setq todo (if (match-end 1) (org-match-string-no-properties 2))
10521 tags (if (match-end 4) (org-match-string-no-properties 4)))
10522 (goto-char (setq lspos (match-beginning 0)))
10523 (setq level (org-reduced-level (funcall outline-level))
10524 category (org-get-category))
10525 (setq i llast llast level)
10526 ;; remove tag lists from same and sublevels
10527 (while (>= i level)
10528 (when (setq entry (assoc i tags-alist))
10529 (setq tags-alist (delete entry tags-alist)))
10530 (setq i (1- i)))
10531 ;; add the next tags
10532 (when tags
10533 (setq tags (org-split-string tags ":")
10534 tags-alist
10535 (cons (cons level tags) tags-alist)))
10536 ;; compile tags for current headline
10537 (setq tags-list
10538 (if org-use-tag-inheritance
10539 (apply 'append (mapcar 'cdr (reverse tags-alist)))
10540 tags)
10541 org-scanner-tags tags-list)
10542 (when org-use-tag-inheritance
10543 (setcdr (car tags-alist)
10544 (mapcar (lambda (x)
10545 (setq x (copy-sequence x))
10546 (org-add-prop-inherited x))
10547 (cdar tags-alist))))
10548 (when (and tags org-use-tag-inheritance
10549 (or (not (eq t org-use-tag-inheritance))
10550 org-tags-exclude-from-inheritance))
10551 ;; selective inheritance, remove uninherited ones
10552 (setcdr (car tags-alist)
10553 (org-remove-uniherited-tags (cdar tags-alist))))
10554 (when (and (or (not todo-only)
10555 (and (member todo org-not-done-keywords)
10556 (or (not org-agenda-tags-todo-honor-ignore-options)
10557 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
10558 (let ((case-fold-search t)) (eval matcher))
10559 (or
10560 (not (member org-archive-tag tags-list))
10561 ;; we have an archive tag, should we use this anyway?
10562 (or (not org-agenda-skip-archived-trees)
10563 (and (eq action 'agenda) org-agenda-archives-mode))))
10564 (unless (eq action 'sparse-tree) (org-agenda-skip))
10565
10566 ;; select this headline
10567
10568 (cond
10569 ((eq action 'sparse-tree)
10570 (and org-highlight-sparse-tree-matches
10571 (org-get-heading) (match-end 0)
10572 (org-highlight-new-match
10573 (match-beginning 0) (match-beginning 1)))
10574 (org-show-context 'tags-tree))
10575 ((eq action 'agenda)
10576 (setq txt (org-format-agenda-item
10577 ""
10578 (concat
10579 (if (eq org-tags-match-list-sublevels 'indented)
10580 (make-string (1- level) ?.) "")
10581 (org-get-heading))
10582 category
10583 tags-list
10584 )
10585 priority (org-get-priority txt))
10586 (goto-char lspos)
10587 (setq marker (org-agenda-new-marker))
10588 (org-add-props txt props
10589 'org-marker marker 'org-hd-marker marker 'org-category category
10590 'todo-state todo
10591 'priority priority 'type "tagsmatch")
10592 (push txt rtn))
10593 ((functionp action)
10594 (setq org-map-continue-from nil)
10595 (save-excursion
10596 (setq rtn1 (funcall action))
10597 (push rtn1 rtn)))
10598 (t (error "Invalid action")))
10599
10600 ;; if we are to skip sublevels, jump to end of subtree
10601 (unless org-tags-match-list-sublevels
10602 (org-end-of-subtree t)
10603 (backward-char 1))))
10604 ;; Get the correct position from where to continue
10605 (if org-map-continue-from
10606 (goto-char org-map-continue-from)
10607 (and (= (point) lspos) (end-of-line 1)))))
10608 (when (and (eq action 'sparse-tree)
10609 (not org-sparse-tree-open-archived-trees))
10610 (org-hide-archived-subtrees (point-min) (point-max)))
10611 (nreverse rtn)))
10612
10613 (defun org-remove-uniherited-tags (tags)
10614 "Remove all tags that are not inherited from the list TAGS."
10615 (cond
10616 ((eq org-use-tag-inheritance t)
10617 (if org-tags-exclude-from-inheritance
10618 (org-delete-all org-tags-exclude-from-inheritance tags)
10619 tags))
10620 ((not org-use-tag-inheritance) nil)
10621 ((stringp org-use-tag-inheritance)
10622 (delq nil (mapcar
10623 (lambda (x)
10624 (if (and (string-match org-use-tag-inheritance x)
10625 (not (member x org-tags-exclude-from-inheritance)))
10626 x nil))
10627 tags)))
10628 ((listp org-use-tag-inheritance)
10629 (delq nil (mapcar
10630 (lambda (x)
10631 (if (member x org-use-tag-inheritance) x nil))
10632 tags)))))
10633
10634 (defvar todo-only) ;; dynamically scoped
10635
10636 (defun org-match-sparse-tree (&optional todo-only match)
10637 "Create a sparse tree according to tags string MATCH.
10638 MATCH can contain positive and negative selection of tags, like
10639 \"+WORK+URGENT-WITHBOSS\".
10640 If optional argument TODO-ONLY is non-nil, only select lines that are
10641 also TODO lines."
10642 (interactive "P")
10643 (org-prepare-agenda-buffers (list (current-buffer)))
10644 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
10645
10646 (defalias 'org-tags-sparse-tree 'org-match-sparse-tree)
10647
10648 (defvar org-cached-props nil)
10649 (defun org-cached-entry-get (pom property)
10650 (if (or (eq t org-use-property-inheritance)
10651 (and (stringp org-use-property-inheritance)
10652 (string-match org-use-property-inheritance property))
10653 (and (listp org-use-property-inheritance)
10654 (member property org-use-property-inheritance)))
10655 ;; Caching is not possible, check it directly
10656 (org-entry-get pom property 'inherit)
10657 ;; Get all properties, so that we can do complicated checks easily
10658 (cdr (assoc property (or org-cached-props
10659 (setq org-cached-props
10660 (org-entry-properties pom)))))))
10661
10662 (defun org-global-tags-completion-table (&optional files)
10663 "Return the list of all tags in all agenda buffer/files."
10664 (save-excursion
10665 (org-uniquify
10666 (delq nil
10667 (apply 'append
10668 (mapcar
10669 (lambda (file)
10670 (set-buffer (find-file-noselect file))
10671 (append (org-get-buffer-tags)
10672 (mapcar (lambda (x) (if (stringp (car-safe x))
10673 (list (car-safe x)) nil))
10674 org-tag-alist)))
10675 (if (and files (car files))
10676 files
10677 (org-agenda-files))))))))
10678
10679 (defun org-make-tags-matcher (match)
10680 "Create the TAGS//TODO matcher form for the selection string MATCH."
10681 ;; todo-only is scoped dynamically into this function, and the function
10682 ;; may change it if the matcher asks for it.
10683 (unless match
10684 ;; Get a new match request, with completion
10685 (let ((org-last-tags-completion-table
10686 (org-global-tags-completion-table)))
10687 (setq match (org-completing-read-no-ido
10688 "Match: " 'org-tags-completion-function nil nil nil
10689 'org-tags-history))))
10690
10691 ;; Parse the string and create a lisp form
10692 (let ((match0 match)
10693 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
10694 minus tag mm
10695 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
10696 orterms term orlist re-p str-p level-p level-op time-p
10697 prop-p pn pv po cat-p gv rest)
10698 (if (string-match "/+" match)
10699 ;; match contains also a todo-matching request
10700 (progn
10701 (setq tagsmatch (substring match 0 (match-beginning 0))
10702 todomatch (substring match (match-end 0)))
10703 (if (string-match "^!" todomatch)
10704 (setq todo-only t todomatch (substring todomatch 1)))
10705 (if (string-match "^\\s-*$" todomatch)
10706 (setq todomatch nil)))
10707 ;; only matching tags
10708 (setq tagsmatch match todomatch nil))
10709
10710 ;; Make the tags matcher
10711 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
10712 (setq tagsmatcher t)
10713 (setq orterms (org-split-string tagsmatch "|") orlist nil)
10714 (while (setq term (pop orterms))
10715 (while (and (equal (substring term -1) "\\") orterms)
10716 (setq term (concat term "|" (pop orterms)))) ; repair bad split
10717 (while (string-match re term)
10718 (setq rest (substring term (match-end 0))
10719 minus (and (match-end 1)
10720 (equal (match-string 1 term) "-"))
10721 tag (match-string 2 term)
10722 re-p (equal (string-to-char tag) ?{)
10723 level-p (match-end 4)
10724 prop-p (match-end 5)
10725 mm (cond
10726 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
10727 (level-p
10728 (setq level-op (org-op-to-function (match-string 3 term)))
10729 `(,level-op level ,(string-to-number
10730 (match-string 4 term))))
10731 (prop-p
10732 (setq pn (match-string 5 term)
10733 po (match-string 6 term)
10734 pv (match-string 7 term)
10735 cat-p (equal pn "CATEGORY")
10736 re-p (equal (string-to-char pv) ?{)
10737 str-p (equal (string-to-char pv) ?\")
10738 time-p (save-match-data
10739 (string-match "^\"[[<].*[]>]\"$" pv))
10740 pv (if (or re-p str-p) (substring pv 1 -1) pv))
10741 (if time-p (setq pv (org-matcher-time pv)))
10742 (setq po (org-op-to-function po (if time-p 'time str-p)))
10743 (cond
10744 ((equal pn "CATEGORY")
10745 (setq gv '(get-text-property (point) 'org-category)))
10746 ((equal pn "TODO")
10747 (setq gv 'todo))
10748 (t
10749 (setq gv `(org-cached-entry-get nil ,pn))))
10750 (if re-p
10751 (if (eq po 'org<>)
10752 `(not (string-match ,pv (or ,gv "")))
10753 `(string-match ,pv (or ,gv "")))
10754 (if str-p
10755 `(,po (or ,gv "") ,pv)
10756 `(,po (string-to-number (or ,gv ""))
10757 ,(string-to-number pv) ))))
10758 (t `(member ,tag tags-list)))
10759 mm (if minus (list 'not mm) mm)
10760 term rest)
10761 (push mm tagsmatcher))
10762 (push (if (> (length tagsmatcher) 1)
10763 (cons 'and tagsmatcher)
10764 (car tagsmatcher))
10765 orlist)
10766 (setq tagsmatcher nil))
10767 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
10768 (setq tagsmatcher
10769 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
10770 ;; Make the todo matcher
10771 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
10772 (setq todomatcher t)
10773 (setq orterms (org-split-string todomatch "|") orlist nil)
10774 (while (setq term (pop orterms))
10775 (while (string-match re term)
10776 (setq minus (and (match-end 1)
10777 (equal (match-string 1 term) "-"))
10778 kwd (match-string 2 term)
10779 re-p (equal (string-to-char kwd) ?{)
10780 term (substring term (match-end 0))
10781 mm (if re-p
10782 `(string-match ,(substring kwd 1 -1) todo)
10783 (list 'equal 'todo kwd))
10784 mm (if minus (list 'not mm) mm))
10785 (push mm todomatcher))
10786 (push (if (> (length todomatcher) 1)
10787 (cons 'and todomatcher)
10788 (car todomatcher))
10789 orlist)
10790 (setq todomatcher nil))
10791 (setq todomatcher (if (> (length orlist) 1)
10792 (cons 'or orlist) (car orlist))))
10793
10794 ;; Return the string and lisp forms of the matcher
10795 (setq matcher (if todomatcher
10796 (list 'and tagsmatcher todomatcher)
10797 tagsmatcher))
10798 (cons match0 matcher)))
10799
10800 (defun org-op-to-function (op &optional stringp)
10801 "Turn an operator into the appropriate function."
10802 (setq op
10803 (cond
10804 ((equal op "<" ) '(< string< org-time<))
10805 ((equal op ">" ) '(> org-string> org-time>))
10806 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
10807 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
10808 ((member op '("=" "==")) '(= string= org-time=))
10809 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
10810 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
10811
10812 (defun org<> (a b) (not (= a b)))
10813 (defun org-string<= (a b) (or (string= a b) (string< a b)))
10814 (defun org-string>= (a b) (not (string< a b)))
10815 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
10816 (defun org-string<> (a b) (not (string= a b)))
10817 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
10818 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
10819 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
10820 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
10821 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
10822 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
10823 (defun org-2ft (s)
10824 "Convert S to a floating point time.
10825 If S is already a number, just return it. If it is a string, parse
10826 it as a time string and apply `float-time' to it. If S is nil, just return 0."
10827 (cond
10828 ((numberp s) s)
10829 ((stringp s)
10830 (condition-case nil
10831 (float-time (apply 'encode-time (org-parse-time-string s)))
10832 (error 0.)))
10833 (t 0.)))
10834
10835 (defun org-time-today ()
10836 "Time in seconds today at 0:00.
10837 Returns the float number of seconds since the beginning of the
10838 epoch to the beginning of today (00:00)."
10839 (float-time (apply 'encode-time
10840 (append '(0 0 0) (nthcdr 3 (decode-time))))))
10841
10842 (defun org-matcher-time (s)
10843 "Interpret a time comparison value."
10844 (save-match-data
10845 (cond
10846 ((string= s "<now>") (float-time))
10847 ((string= s "<today>") (org-time-today))
10848 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
10849 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
10850 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
10851 (+ (org-time-today)
10852 (* (string-to-number (match-string 1 s))
10853 (cdr (assoc (match-string 2 s)
10854 '(("d" . 86400.0) ("w" . 604800.0)
10855 ("m" . 2678400.0) ("y" . 31557600.0)))))))
10856 (t (org-2ft s)))))
10857
10858 (defun org-match-any-p (re list)
10859 "Does re match any element of list?"
10860 (setq list (mapcar (lambda (x) (string-match re x)) list))
10861 (delq nil list))
10862
10863 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
10864 (defvar org-tags-overlay (org-make-overlay 1 1))
10865 (org-detach-overlay org-tags-overlay)
10866
10867 (defun org-get-local-tags-at (&optional pos)
10868 "Get a list of tags defined in the current headline."
10869 (org-get-tags-at pos 'local))
10870
10871 (defun org-get-local-tags ()
10872 "Get a list of tags defined in the current headline."
10873 (org-get-tags-at nil 'local))
10874
10875 (defun org-get-tags-at (&optional pos local)
10876 "Get a list of all headline tags applicable at POS.
10877 POS defaults to point. If tags are inherited, the list contains
10878 the targets in the same sequence as the headlines appear, i.e.
10879 the tags of the current headline come last.
10880 When LOCAL is non-nil, only return tags from the current headline,
10881 ignore inherited ones."
10882 (interactive)
10883 (if (and org-trust-scanner-tags
10884 (or (not pos) (equal pos (point)))
10885 (not local))
10886 org-scanner-tags
10887 (let (tags ltags lastpos parent)
10888 (save-excursion
10889 (save-restriction
10890 (widen)
10891 (goto-char (or pos (point)))
10892 (save-match-data
10893 (catch 'done
10894 (condition-case nil
10895 (progn
10896 (org-back-to-heading t)
10897 (while (not (equal lastpos (point)))
10898 (setq lastpos (point))
10899 (when (looking-at
10900 (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
10901 (setq ltags (org-split-string
10902 (org-match-string-no-properties 1) ":"))
10903 (when parent
10904 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
10905 (setq tags (append
10906 (if parent
10907 (org-remove-uniherited-tags ltags)
10908 ltags)
10909 tags)))
10910 (or org-use-tag-inheritance (throw 'done t))
10911 (if local (throw 'done t))
10912 (or (org-up-heading-safe) (error nil))
10913 (setq parent t)))
10914 (error nil)))))
10915 (append (org-remove-uniherited-tags org-file-tags) tags)))))
10916
10917 (defun org-add-prop-inherited (s)
10918 (add-text-properties 0 (length s) '(inherited t) s)
10919 s)
10920
10921 (defun org-toggle-tag (tag &optional onoff)
10922 "Toggle the tag TAG for the current line.
10923 If ONOFF is `on' or `off', don't toggle but set to this state."
10924 (let (res current)
10925 (save-excursion
10926 (org-back-to-heading t)
10927 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
10928 (point-at-eol) t)
10929 (progn
10930 (setq current (match-string 1))
10931 (replace-match ""))
10932 (setq current ""))
10933 (setq current (nreverse (org-split-string current ":")))
10934 (cond
10935 ((eq onoff 'on)
10936 (setq res t)
10937 (or (member tag current) (push tag current)))
10938 ((eq onoff 'off)
10939 (or (not (member tag current)) (setq current (delete tag current))))
10940 (t (if (member tag current)
10941 (setq current (delete tag current))
10942 (setq res t)
10943 (push tag current))))
10944 (end-of-line 1)
10945 (if current
10946 (progn
10947 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
10948 (org-set-tags nil t))
10949 (delete-horizontal-space))
10950 (run-hooks 'org-after-tags-change-hook))
10951 res))
10952
10953 (defun org-align-tags-here (to-col)
10954 ;; Assumes that this is a headline
10955 (let ((pos (point)) (col (current-column)) ncol tags-l p)
10956 (beginning-of-line 1)
10957 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10958 (< pos (match-beginning 2)))
10959 (progn
10960 (setq tags-l (- (match-end 2) (match-beginning 2)))
10961 (goto-char (match-beginning 1))
10962 (insert " ")
10963 (delete-region (point) (1+ (match-beginning 2)))
10964 (setq ncol (max (1+ (current-column))
10965 (1+ col)
10966 (if (> to-col 0)
10967 to-col
10968 (- (abs to-col) tags-l))))
10969 (setq p (point))
10970 (insert (make-string (- ncol (current-column)) ?\ ))
10971 (setq ncol (current-column))
10972 (when indent-tabs-mode (tabify p (point-at-eol)))
10973 (org-move-to-column (min ncol col) t))
10974 (goto-char pos))))
10975
10976 (defun org-set-tags-command (&optional arg just-align)
10977 "Call the set-tags command for the current entry."
10978 (interactive "P")
10979 (if (org-on-heading-p)
10980 (org-set-tags arg just-align)
10981 (save-excursion
10982 (org-back-to-heading t)
10983 (org-set-tags arg just-align))))
10984
10985 (defun org-set-tags (&optional arg just-align)
10986 "Set the tags for the current headline.
10987 With prefix ARG, realign all tags in headings in the current buffer."
10988 (interactive "P")
10989 (let* ((re (concat "^" outline-regexp))
10990 (current (org-get-tags-string))
10991 (col (current-column))
10992 (org-setting-tags t)
10993 table current-tags inherited-tags ; computed below when needed
10994 tags p0 c0 c1 rpl)
10995 (if arg
10996 (save-excursion
10997 (goto-char (point-min))
10998 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
10999 (while (re-search-forward re nil t)
11000 (org-set-tags nil t)
11001 (end-of-line 1)))
11002 (message "All tags realigned to column %d" org-tags-column))
11003 (if just-align
11004 (setq tags current)
11005 ;; Get a new set of tags from the user
11006 (save-excursion
11007 (setq table (append org-tag-persistent-alist
11008 (or org-tag-alist (org-get-buffer-tags)))
11009 org-last-tags-completion-table table
11010 current-tags (org-split-string current ":")
11011 inherited-tags (nreverse
11012 (nthcdr (length current-tags)
11013 (nreverse (org-get-tags-at))))
11014 tags
11015 (if (or (eq t org-use-fast-tag-selection)
11016 (and org-use-fast-tag-selection
11017 (delq nil (mapcar 'cdr table))))
11018 (org-fast-tag-selection
11019 current-tags inherited-tags table
11020 (if org-fast-tag-selection-include-todo org-todo-key-alist))
11021 (let ((org-add-colon-after-tag-completion t))
11022 (org-trim
11023 (org-without-partial-completion
11024 (org-ido-completing-read "Tags: " 'org-tags-completion-function
11025 nil nil current 'org-tags-history)))))))
11026 (while (string-match "[-+&]+" tags)
11027 ;; No boolean logic, just a list
11028 (setq tags (replace-match ":" t t tags))))
11029
11030 (if org-tags-sort-function
11031 (setq tags (mapconcat 'identity
11032 (sort (org-split-string tags (org-re "[^[:alnum:]_@]+"))
11033 org-tags-sort-function) ":")))
11034
11035 (if (string-match "\\`[\t ]*\\'" tags)
11036 (setq tags "")
11037 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
11038 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
11039
11040 ;; Insert new tags at the correct column
11041 (beginning-of-line 1)
11042 (cond
11043 ((and (equal current "") (equal tags "")))
11044 ((re-search-forward
11045 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
11046 (point-at-eol) t)
11047 (if (equal tags "")
11048 (setq rpl "")
11049 (goto-char (match-beginning 0))
11050 (setq c0 (current-column) p0 (point)
11051 c1 (max (1+ c0) (if (> org-tags-column 0)
11052 org-tags-column
11053 (- (- org-tags-column) (length tags))))
11054 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
11055 (replace-match rpl t t)
11056 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
11057 tags)
11058 (t (error "Tags alignment failed")))
11059 (org-move-to-column col)
11060 (unless just-align
11061 (run-hooks 'org-after-tags-change-hook)))))
11062
11063 (defun org-change-tag-in-region (beg end tag off)
11064 "Add or remove TAG for each entry in the region.
11065 This works in the agenda, and also in an org-mode buffer."
11066 (interactive
11067 (list (region-beginning) (region-end)
11068 (let ((org-last-tags-completion-table
11069 (if (org-mode-p)
11070 (org-get-buffer-tags)
11071 (org-global-tags-completion-table))))
11072 (org-ido-completing-read
11073 "Tag: " 'org-tags-completion-function nil nil nil
11074 'org-tags-history))
11075 (progn
11076 (message "[s]et or [r]emove? ")
11077 (equal (read-char-exclusive) ?r))))
11078 (if (fboundp 'deactivate-mark) (deactivate-mark))
11079 (let ((agendap (equal major-mode 'org-agenda-mode))
11080 l1 l2 m buf pos newhead (cnt 0))
11081 (goto-char end)
11082 (setq l2 (1- (org-current-line)))
11083 (goto-char beg)
11084 (setq l1 (org-current-line))
11085 (loop for l from l1 to l2 do
11086 (goto-line l)
11087 (setq m (get-text-property (point) 'org-hd-marker))
11088 (when (or (and (org-mode-p) (org-on-heading-p))
11089 (and agendap m))
11090 (setq buf (if agendap (marker-buffer m) (current-buffer))
11091 pos (if agendap m (point)))
11092 (with-current-buffer buf
11093 (save-excursion
11094 (save-restriction
11095 (goto-char pos)
11096 (setq cnt (1+ cnt))
11097 (org-toggle-tag tag (if off 'off 'on))
11098 (setq newhead (org-get-heading)))))
11099 (and agendap (org-agenda-change-all-lines newhead m))))
11100 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
11101
11102 (defun org-tags-completion-function (string predicate &optional flag)
11103 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
11104 (confirm (lambda (x) (stringp (car x)))))
11105 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
11106 (setq s1 (match-string 1 string)
11107 s2 (match-string 2 string))
11108 (setq s1 "" s2 string))
11109 (cond
11110 ((eq flag nil)
11111 ;; try completion
11112 (setq rtn (try-completion s2 ctable confirm))
11113 (if (stringp rtn)
11114 (setq rtn
11115 (concat s1 s2 (substring rtn (length s2))
11116 (if (and org-add-colon-after-tag-completion
11117 (assoc rtn ctable))
11118 ":" ""))))
11119 rtn)
11120 ((eq flag t)
11121 ;; all-completions
11122 (all-completions s2 ctable confirm)
11123 )
11124 ((eq flag 'lambda)
11125 ;; exact match?
11126 (assoc s2 ctable)))
11127 ))
11128
11129 (defun org-fast-tag-insert (kwd tags face &optional end)
11130 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
11131 (insert (format "%-12s" (concat kwd ":"))
11132 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
11133 (or end "")))
11134
11135 (defun org-fast-tag-show-exit (flag)
11136 (save-excursion
11137 (goto-line 3)
11138 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
11139 (replace-match ""))
11140 (when flag
11141 (end-of-line 1)
11142 (org-move-to-column (- (window-width) 19) t)
11143 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
11144
11145 (defun org-set-current-tags-overlay (current prefix)
11146 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
11147 (if (featurep 'xemacs)
11148 (org-overlay-display org-tags-overlay (concat prefix s)
11149 'secondary-selection)
11150 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
11151 (org-overlay-display org-tags-overlay (concat prefix s)))))
11152
11153 (defun org-fast-tag-selection (current inherited table &optional todo-table)
11154 "Fast tag selection with single keys.
11155 CURRENT is the current list of tags in the headline, INHERITED is the
11156 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
11157 possibly with grouping information. TODO-TABLE is a similar table with
11158 TODO keywords, should these have keys assigned to them.
11159 If the keys are nil, a-z are automatically assigned.
11160 Returns the new tags string, or nil to not change the current settings."
11161 (let* ((fulltable (append table todo-table))
11162 (maxlen (apply 'max (mapcar
11163 (lambda (x)
11164 (if (stringp (car x)) (string-width (car x)) 0))
11165 fulltable)))
11166 (buf (current-buffer))
11167 (expert (eq org-fast-tag-selection-single-key 'expert))
11168 (buffer-tags nil)
11169 (fwidth (+ maxlen 3 1 3))
11170 (ncol (/ (- (window-width) 4) fwidth))
11171 (i-face 'org-done)
11172 (c-face 'org-todo)
11173 tg cnt e c char c1 c2 ntable tbl rtn
11174 ov-start ov-end ov-prefix
11175 (exit-after-next org-fast-tag-selection-single-key)
11176 (done-keywords org-done-keywords)
11177 groups ingroup)
11178 (save-excursion
11179 (beginning-of-line 1)
11180 (if (looking-at
11181 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11182 (setq ov-start (match-beginning 1)
11183 ov-end (match-end 1)
11184 ov-prefix "")
11185 (setq ov-start (1- (point-at-eol))
11186 ov-end (1+ ov-start))
11187 (skip-chars-forward "^\n\r")
11188 (setq ov-prefix
11189 (concat
11190 (buffer-substring (1- (point)) (point))
11191 (if (> (current-column) org-tags-column)
11192 " "
11193 (make-string (- org-tags-column (current-column)) ?\ ))))))
11194 (org-move-overlay org-tags-overlay ov-start ov-end)
11195 (save-window-excursion
11196 (if expert
11197 (set-buffer (get-buffer-create " *Org tags*"))
11198 (delete-other-windows)
11199 (split-window-vertically)
11200 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
11201 (erase-buffer)
11202 (org-set-local 'org-done-keywords done-keywords)
11203 (org-fast-tag-insert "Inherited" inherited i-face "\n")
11204 (org-fast-tag-insert "Current" current c-face "\n\n")
11205 (org-fast-tag-show-exit exit-after-next)
11206 (org-set-current-tags-overlay current ov-prefix)
11207 (setq tbl fulltable char ?a cnt 0)
11208 (while (setq e (pop tbl))
11209 (cond
11210 ((equal e '(:startgroup))
11211 (push '() groups) (setq ingroup t)
11212 (when (not (= cnt 0))
11213 (setq cnt 0)
11214 (insert "\n"))
11215 (insert "{ "))
11216 ((equal e '(:endgroup))
11217 (setq ingroup nil cnt 0)
11218 (insert "}\n"))
11219 ((equal e '(:newline))
11220 (when (not (= cnt 0))
11221 (setq cnt 0)
11222 (insert "\n")
11223 (setq e (car tbl))
11224 (while (equal (car tbl) '(:newline))
11225 (insert "\n")
11226 (setq tbl (cdr tbl)))))
11227 (t
11228 (setq tg (car e) c2 nil)
11229 (if (cdr e)
11230 (setq c (cdr e))
11231 ;; automatically assign a character.
11232 (setq c1 (string-to-char
11233 (downcase (substring
11234 tg (if (= (string-to-char tg) ?@) 1 0)))))
11235 (if (or (rassoc c1 ntable) (rassoc c1 table))
11236 (while (or (rassoc char ntable) (rassoc char table))
11237 (setq char (1+ char)))
11238 (setq c2 c1))
11239 (setq c (or c2 char)))
11240 (if ingroup (push tg (car groups)))
11241 (setq tg (org-add-props tg nil 'face
11242 (cond
11243 ((not (assoc tg table))
11244 (org-get-todo-face tg))
11245 ((member tg current) c-face)
11246 ((member tg inherited) i-face)
11247 (t nil))))
11248 (if (and (= cnt 0) (not ingroup)) (insert " "))
11249 (insert "[" c "] " tg (make-string
11250 (- fwidth 4 (length tg)) ?\ ))
11251 (push (cons tg c) ntable)
11252 (when (= (setq cnt (1+ cnt)) ncol)
11253 (insert "\n")
11254 (if ingroup (insert " "))
11255 (setq cnt 0)))))
11256 (setq ntable (nreverse ntable))
11257 (insert "\n")
11258 (goto-char (point-min))
11259 (if (not expert) (org-fit-window-to-buffer))
11260 (setq rtn
11261 (catch 'exit
11262 (while t
11263 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
11264 (if groups " [!] no groups" " [!]groups")
11265 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
11266 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
11267 (cond
11268 ((= c ?\r) (throw 'exit t))
11269 ((= c ?!)
11270 (setq groups (not groups))
11271 (goto-char (point-min))
11272 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
11273 ((= c ?\C-c)
11274 (if (not expert)
11275 (org-fast-tag-show-exit
11276 (setq exit-after-next (not exit-after-next)))
11277 (setq expert nil)
11278 (delete-other-windows)
11279 (split-window-vertically)
11280 (org-switch-to-buffer-other-window " *Org tags*")
11281 (org-fit-window-to-buffer)))
11282 ((or (= c ?\C-g)
11283 (and (= c ?q) (not (rassoc c ntable))))
11284 (org-detach-overlay org-tags-overlay)
11285 (setq quit-flag t))
11286 ((= c ?\ )
11287 (setq current nil)
11288 (if exit-after-next (setq exit-after-next 'now)))
11289 ((= c ?\t)
11290 (condition-case nil
11291 (setq tg (org-ido-completing-read
11292 "Tag: "
11293 (or buffer-tags
11294 (with-current-buffer buf
11295 (org-get-buffer-tags)))))
11296 (quit (setq tg "")))
11297 (when (string-match "\\S-" tg)
11298 (add-to-list 'buffer-tags (list tg))
11299 (if (member tg current)
11300 (setq current (delete tg current))
11301 (push tg current)))
11302 (if exit-after-next (setq exit-after-next 'now)))
11303 ((setq e (rassoc c todo-table) tg (car e))
11304 (with-current-buffer buf
11305 (save-excursion (org-todo tg)))
11306 (if exit-after-next (setq exit-after-next 'now)))
11307 ((setq e (rassoc c ntable) tg (car e))
11308 (if (member tg current)
11309 (setq current (delete tg current))
11310 (loop for g in groups do
11311 (if (member tg g)
11312 (mapc (lambda (x)
11313 (setq current (delete x current)))
11314 g)))
11315 (push tg current))
11316 (if exit-after-next (setq exit-after-next 'now))))
11317
11318 ;; Create a sorted list
11319 (setq current
11320 (sort current
11321 (lambda (a b)
11322 (assoc b (cdr (memq (assoc a ntable) ntable))))))
11323 (if (eq exit-after-next 'now) (throw 'exit t))
11324 (goto-char (point-min))
11325 (beginning-of-line 2)
11326 (delete-region (point) (point-at-eol))
11327 (org-fast-tag-insert "Current" current c-face)
11328 (org-set-current-tags-overlay current ov-prefix)
11329 (while (re-search-forward
11330 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
11331 (setq tg (match-string 1))
11332 (add-text-properties
11333 (match-beginning 1) (match-end 1)
11334 (list 'face
11335 (cond
11336 ((member tg current) c-face)
11337 ((member tg inherited) i-face)
11338 (t (get-text-property (match-beginning 1) 'face))))))
11339 (goto-char (point-min)))))
11340 (org-detach-overlay org-tags-overlay)
11341 (if rtn
11342 (mapconcat 'identity current ":")
11343 nil))))
11344
11345 (defun org-get-tags-string ()
11346 "Get the TAGS string in the current headline."
11347 (unless (org-on-heading-p t)
11348 (error "Not on a heading"))
11349 (save-excursion
11350 (beginning-of-line 1)
11351 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
11352 (org-match-string-no-properties 1)
11353 "")))
11354
11355 (defun org-get-tags ()
11356 "Get the list of tags specified in the current headline."
11357 (org-split-string (org-get-tags-string) ":"))
11358
11359 (defun org-get-buffer-tags ()
11360 "Get a table of all tags used in the buffer, for completion."
11361 (let (tags)
11362 (save-excursion
11363 (goto-char (point-min))
11364 (while (re-search-forward
11365 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
11366 (when (equal (char-after (point-at-bol 0)) ?*)
11367 (mapc (lambda (x) (add-to-list 'tags x))
11368 (org-split-string (org-match-string-no-properties 1) ":")))))
11369 (mapcar 'list tags)))
11370
11371 ;;;; The mapping API
11372
11373 ;;;###autoload
11374 (defun org-map-entries (func &optional match scope &rest skip)
11375 "Call FUNC at each headline selected by MATCH in SCOPE.
11376
11377 FUNC is a function or a lisp form. The function will be called without
11378 arguments, with the cursor positioned at the beginning of the headline.
11379 The return values of all calls to the function will be collected and
11380 returned as a list.
11381
11382 The call to FUNC will be wrapped into a save-excursion form, so FUNC
11383 does not need to preserve point. After evaluation, the cursor will be
11384 moved to the end of the line (presumably of the headline of the
11385 processed entry) and search continues from there. Under some
11386 circumstances, this may not produce the wanted results. For example,
11387 if you have removed (e.g. archived) the current (sub)tree it could
11388 mean that the next entry will be skipped entirely. In such cases, you
11389 can specify the position from where search should continue by making
11390 FUNC set the variable `org-map-continue-from' to the desired buffer
11391 position.
11392
11393 MATCH is a tags/property/todo match as it is used in the agenda tags view.
11394 Only headlines that are matched by this query will be considered during
11395 the iteration. When MATCH is nil or t, all headlines will be
11396 visited by the iteration.
11397
11398 SCOPE determines the scope of this command. It can be any of:
11399
11400 nil The current buffer, respecting the restriction if any
11401 tree The subtree started with the entry at point
11402 file The current buffer, without restriction
11403 file-with-archives
11404 The current buffer, and any archives associated with it
11405 agenda All agenda files
11406 agenda-with-archives
11407 All agenda files with any archive files associated with them
11408 \(file1 file2 ...)
11409 If this is a list, all files in the list will be scanned
11410
11411 The remaining args are treated as settings for the skipping facilities of
11412 the scanner. The following items can be given here:
11413
11414 archive skip trees with the archive tag.
11415 comment skip trees with the COMMENT keyword
11416 function or Emacs Lisp form:
11417 will be used as value for `org-agenda-skip-function', so whenever
11418 the the function returns t, FUNC will not be called for that
11419 entry and search will continue from the point where the
11420 function leaves it.
11421
11422 If your function needs to retrieve the tags including inherited tags
11423 at the *current* entry, you can use the value of the variable
11424 `org-scanner-tags' which will be much faster than getting the value
11425 with `org-get-tags-at'. If your function gets properties with
11426 `org-entry-properties' at the *current* entry, bind `org-trust-scanner-tags'
11427 to t around the call to `org-entry-properties' to get the same speedup.
11428 Note that if your function moves around to retrieve tags and properties at
11429 a *different* entry, you cannot use these techniques."
11430 (let* ((org-agenda-archives-mode nil) ; just to make sure
11431 (org-agenda-skip-archived-trees (memq 'archive skip))
11432 (org-agenda-skip-comment-trees (memq 'comment skip))
11433 (org-agenda-skip-function
11434 (car (org-delete-all '(comment archive) skip)))
11435 (org-tags-match-list-sublevels t)
11436 matcher file res
11437 org-todo-keywords-for-agenda
11438 org-done-keywords-for-agenda
11439 org-todo-keyword-alist-for-agenda
11440 org-tag-alist-for-agenda)
11441
11442 (cond
11443 ((eq match t) (setq matcher t))
11444 ((eq match nil) (setq matcher t))
11445 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
11446
11447 (save-excursion
11448 (save-restriction
11449 (when (eq scope 'tree)
11450 (org-back-to-heading t)
11451 (org-narrow-to-subtree)
11452 (setq scope nil))
11453
11454 (if (not scope)
11455 (progn
11456 (org-prepare-agenda-buffers
11457 (list (buffer-file-name (current-buffer))))
11458 (setq res (org-scan-tags func matcher)))
11459 ;; Get the right scope
11460 (cond
11461 ((and scope (listp scope) (symbolp (car scope)))
11462 (setq scope (eval scope)))
11463 ((eq scope 'agenda)
11464 (setq scope (org-agenda-files t)))
11465 ((eq scope 'agenda-with-archives)
11466 (setq scope (org-agenda-files t))
11467 (setq scope (org-add-archive-files scope)))
11468 ((eq scope 'file)
11469 (setq scope (list (buffer-file-name))))
11470 ((eq scope 'file-with-archives)
11471 (setq scope (org-add-archive-files (list (buffer-file-name))))))
11472 (org-prepare-agenda-buffers scope)
11473 (while (setq file (pop scope))
11474 (with-current-buffer (org-find-base-buffer-visiting file)
11475 (save-excursion
11476 (save-restriction
11477 (widen)
11478 (goto-char (point-min))
11479 (setq res (append res (org-scan-tags func matcher))))))))))
11480 res))
11481
11482 ;;;; Properties
11483
11484 ;;; Setting and retrieving properties
11485
11486 (defconst org-special-properties
11487 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
11488 "TIMESTAMP" "TIMESTAMP_IA")
11489 "The special properties valid in Org-mode.
11490
11491 These are properties that are not defined in the property drawer,
11492 but in some other way.")
11493
11494 (defconst org-default-properties
11495 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION" "CUSTOM_ID"
11496 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
11497 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
11498 "EXPORT_FILE_NAME" "EXPORT_TITLE" "EXPORT_AUTHOR" "EXPORT_DATE"
11499 "ORDERED" "NOBLOCKING" "COOKIE_DATA" "LOG_INTO_DRAWER"
11500 "CLOCK_MODELINE_TOTAL")
11501 "Some properties that are used by Org-mode for various purposes.
11502 Being in this list makes sure that they are offered for completion.")
11503
11504 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
11505 "Regular expression matching the first line of a property drawer.")
11506
11507 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
11508 "Regular expression matching the first line of a property drawer.")
11509
11510 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
11511 "Regular expression matching the first line of a property drawer.")
11512
11513 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
11514 "Regular expression matching the first line of a property drawer.")
11515
11516 (defconst org-property-drawer-re
11517 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
11518 org-property-end-re "\\)\n?")
11519 "Matches an entire property drawer.")
11520
11521 (defconst org-clock-drawer-re
11522 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
11523 org-property-end-re "\\)\n?")
11524 "Matches an entire clock drawer.")
11525
11526 (defun org-property-action ()
11527 "Do an action on properties."
11528 (interactive)
11529 (let (c)
11530 (org-at-property-p)
11531 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
11532 (setq c (read-char-exclusive))
11533 (cond
11534 ((equal c ?s)
11535 (call-interactively 'org-set-property))
11536 ((equal c ?d)
11537 (call-interactively 'org-delete-property))
11538 ((equal c ?D)
11539 (call-interactively 'org-delete-property-globally))
11540 ((equal c ?c)
11541 (call-interactively 'org-compute-property-at-point))
11542 (t (error "No such property action %c" c)))))
11543
11544 (defun org-at-property-p ()
11545 "Is the cursor in a property line?"
11546 ;; FIXME: Does not check if we are actually in the drawer.
11547 ;; FIXME: also returns true on any drawers.....
11548 ;; This is used by C-c C-c for property action.
11549 (save-excursion
11550 (beginning-of-line 1)
11551 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
11552
11553 (defun org-get-property-block (&optional beg end force)
11554 "Return the (beg . end) range of the body of the property drawer.
11555 BEG and END can be beginning and end of subtree, if not given
11556 they will be found.
11557 If the drawer does not exist and FORCE is non-nil, create the drawer."
11558 (catch 'exit
11559 (save-excursion
11560 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
11561 (end (or end (progn (outline-next-heading) (point)))))
11562 (goto-char beg)
11563 (if (re-search-forward org-property-start-re end t)
11564 (setq beg (1+ (match-end 0)))
11565 (if force
11566 (save-excursion
11567 (org-insert-property-drawer)
11568 (setq end (progn (outline-next-heading) (point))))
11569 (throw 'exit nil))
11570 (goto-char beg)
11571 (if (re-search-forward org-property-start-re end t)
11572 (setq beg (1+ (match-end 0)))))
11573 (if (re-search-forward org-property-end-re end t)
11574 (setq end (match-beginning 0))
11575 (or force (throw 'exit nil))
11576 (goto-char beg)
11577 (setq end beg)
11578 (org-indent-line-function)
11579 (insert ":END:\n"))
11580 (cons beg end)))))
11581
11582 (defun org-entry-properties (&optional pom which)
11583 "Get all properties of the entry at point-or-marker POM.
11584 This includes the TODO keyword, the tags, time strings for deadline,
11585 scheduled, and clocking, and any additional properties defined in the
11586 entry. The return value is an alist, keys may occur multiple times
11587 if the property key was used several times.
11588 POM may also be nil, in which case the current entry is used.
11589 If WHICH is nil or `all', get all properties. If WHICH is
11590 `special' or `standard', only get that subclass."
11591 (setq which (or which 'all))
11592 (org-with-point-at pom
11593 (let ((clockstr (substring org-clock-string 0 -1))
11594 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
11595 beg end range props sum-props key value string clocksum)
11596 (save-excursion
11597 (when (condition-case nil
11598 (and (org-mode-p) (org-back-to-heading t))
11599 (error nil))
11600 (setq beg (point))
11601 (setq sum-props (get-text-property (point) 'org-summaries))
11602 (setq clocksum (get-text-property (point) :org-clock-minutes))
11603 (outline-next-heading)
11604 (setq end (point))
11605 (when (memq which '(all special))
11606 ;; Get the special properties, like TODO and tags
11607 (goto-char beg)
11608 (when (and (looking-at org-todo-line-regexp) (match-end 2))
11609 (push (cons "TODO" (org-match-string-no-properties 2)) props))
11610 (when (looking-at org-priority-regexp)
11611 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
11612 (when (and (setq value (org-get-tags-string))
11613 (string-match "\\S-" value))
11614 (push (cons "TAGS" value) props))
11615 (when (setq value (org-get-tags-at))
11616 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
11617 props))
11618 (while (re-search-forward org-maybe-keyword-time-regexp end t)
11619 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
11620 string (if (equal key clockstr)
11621 (org-no-properties
11622 (org-trim
11623 (buffer-substring
11624 (match-beginning 3) (goto-char (point-at-eol)))))
11625 (substring (org-match-string-no-properties 3) 1 -1)))
11626 (unless key
11627 (if (= (char-after (match-beginning 3)) ?\[)
11628 (setq key "TIMESTAMP_IA")
11629 (setq key "TIMESTAMP")))
11630 (when (or (equal key clockstr) (not (assoc key props)))
11631 (push (cons key string) props)))
11632
11633 )
11634
11635 (when (memq which '(all standard))
11636 ;; Get the standard properties, like :PROP: ...
11637 (setq range (org-get-property-block beg end))
11638 (when range
11639 (goto-char (car range))
11640 (while (re-search-forward
11641 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
11642 (cdr range) t)
11643 (setq key (org-match-string-no-properties 1)
11644 value (org-trim (or (org-match-string-no-properties 2) "")))
11645 (unless (member key excluded)
11646 (push (cons key (or value "")) props)))))
11647 (if clocksum
11648 (push (cons "CLOCKSUM"
11649 (org-columns-number-to-string (/ (float clocksum) 60.)
11650 'add_times))
11651 props))
11652 (unless (assoc "CATEGORY" props)
11653 (setq value (or (org-get-category)
11654 (progn (org-refresh-category-properties)
11655 (org-get-category))))
11656 (push (cons "CATEGORY" value) props))
11657 (append sum-props (nreverse props)))))))
11658
11659 (defun org-entry-get (pom property &optional inherit)
11660 "Get value of PROPERTY for entry at point-or-marker POM.
11661 If INHERIT is non-nil and the entry does not have the property,
11662 then also check higher levels of the hierarchy.
11663 If INHERIT is the symbol `selective', use inheritance only if the setting
11664 in `org-use-property-inheritance' selects PROPERTY for inheritance.
11665 If the property is present but empty, the return value is the empty string.
11666 If the property is not present at all, nil is returned."
11667 (org-with-point-at pom
11668 (if (and inherit (if (eq inherit 'selective)
11669 (org-property-inherit-p property)
11670 t))
11671 (org-entry-get-with-inheritance property)
11672 (if (member property org-special-properties)
11673 ;; We need a special property. Use brute force, get all properties.
11674 (cdr (assoc property (org-entry-properties nil 'special)))
11675 (let ((range (org-get-property-block)))
11676 (if (and range
11677 (goto-char (car range))
11678 (re-search-forward
11679 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
11680 (cdr range) t))
11681 ;; Found the property, return it.
11682 (if (match-end 1)
11683 (org-match-string-no-properties 1)
11684 "")))))))
11685
11686 (defun org-property-or-variable-value (var &optional inherit)
11687 "Check if there is a property fixing the value of VAR.
11688 If yes, return this value. If not, return the current value of the variable."
11689 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
11690 (if (and prop (stringp prop) (string-match "\\S-" prop))
11691 (read prop)
11692 (symbol-value var))))
11693
11694 (defun org-entry-delete (pom property)
11695 "Delete the property PROPERTY from entry at point-or-marker POM."
11696 (org-with-point-at pom
11697 (if (member property org-special-properties)
11698 nil ; cannot delete these properties.
11699 (let ((range (org-get-property-block)))
11700 (if (and range
11701 (goto-char (car range))
11702 (re-search-forward
11703 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
11704 (cdr range) t))
11705 (progn
11706 (delete-region (match-beginning 0) (1+ (point-at-eol)))
11707 t)
11708 nil)))))
11709
11710 ;; Multi-values properties are properties that contain multiple values
11711 ;; These values are assumed to be single words, separated by whitespace.
11712 (defun org-entry-add-to-multivalued-property (pom property value)
11713 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
11714 (let* ((old (org-entry-get pom property))
11715 (values (and old (org-split-string old "[ \t]"))))
11716 (setq value (org-entry-protect-space value))
11717 (unless (member value values)
11718 (setq values (cons value values))
11719 (org-entry-put pom property
11720 (mapconcat 'identity values " ")))))
11721
11722 (defun org-entry-remove-from-multivalued-property (pom property value)
11723 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
11724 (let* ((old (org-entry-get pom property))
11725 (values (and old (org-split-string old "[ \t]"))))
11726 (setq value (org-entry-protect-space value))
11727 (when (member value values)
11728 (setq values (delete value values))
11729 (org-entry-put pom property
11730 (mapconcat 'identity values " ")))))
11731
11732 (defun org-entry-member-in-multivalued-property (pom property value)
11733 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
11734 (let* ((old (org-entry-get pom property))
11735 (values (and old (org-split-string old "[ \t]"))))
11736 (setq value (org-entry-protect-space value))
11737 (member value values)))
11738
11739 (defun org-entry-get-multivalued-property (pom property)
11740 "Return a list of values in a multivalued property."
11741 (let* ((value (org-entry-get pom property))
11742 (values (and value (org-split-string value "[ \t]"))))
11743 (mapcar 'org-entry-restore-space values)))
11744
11745 (defun org-entry-put-multivalued-property (pom property &rest values)
11746 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
11747 VALUES should be a list of strings. Spaces will be protected."
11748 (org-entry-put pom property
11749 (mapconcat 'org-entry-protect-space values " "))
11750 (let* ((value (org-entry-get pom property))
11751 (values (and value (org-split-string value "[ \t]"))))
11752 (mapcar 'org-entry-restore-space values)))
11753
11754 (defun org-entry-protect-space (s)
11755 "Protect spaces and newline in string S."
11756 (while (string-match " " s)
11757 (setq s (replace-match "%20" t t s)))
11758 (while (string-match "\n" s)
11759 (setq s (replace-match "%0A" t t s)))
11760 s)
11761
11762 (defun org-entry-restore-space (s)
11763 "Restore spaces and newline in string S."
11764 (while (string-match "%20" s)
11765 (setq s (replace-match " " t t s)))
11766 (while (string-match "%0A" s)
11767 (setq s (replace-match "\n" t t s)))
11768 s)
11769
11770 (defvar org-entry-property-inherited-from (make-marker)
11771 "Marker pointing to the entry from where a property was inherited.
11772 Each call to `org-entry-get-with-inheritance' will set this marker to the
11773 location of the entry where the inheritance search matched. If there was
11774 no match, the marker will point nowhere.
11775 Note that also `org-entry-get' calls this function, if the INHERIT flag
11776 is set.")
11777
11778 (defun org-entry-get-with-inheritance (property)
11779 "Get entry property, and search higher levels if not present."
11780 (move-marker org-entry-property-inherited-from nil)
11781 (let (tmp)
11782 (save-excursion
11783 (save-restriction
11784 (widen)
11785 (catch 'ex
11786 (while t
11787 (when (setq tmp (org-entry-get nil property))
11788 (org-back-to-heading t)
11789 (move-marker org-entry-property-inherited-from (point))
11790 (throw 'ex tmp))
11791 (or (org-up-heading-safe) (throw 'ex nil)))))
11792 (or tmp
11793 (cdr (assoc property org-file-properties))
11794 (cdr (assoc property org-global-properties))
11795 (cdr (assoc property org-global-properties-fixed))))))
11796
11797 (defun org-entry-put (pom property value)
11798 "Set PROPERTY to VALUE for entry at point-or-marker POM."
11799 (org-with-point-at pom
11800 (org-back-to-heading t)
11801 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
11802 range)
11803 (cond
11804 ((equal property "TODO")
11805 (when (and (stringp value) (string-match "\\S-" value)
11806 (not (member value org-todo-keywords-1)))
11807 (error "\"%s\" is not a valid TODO state" value))
11808 (if (or (not value)
11809 (not (string-match "\\S-" value)))
11810 (setq value 'none))
11811 (org-todo value)
11812 (org-set-tags nil 'align))
11813 ((equal property "PRIORITY")
11814 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
11815 (string-to-char value) ?\ ))
11816 (org-set-tags nil 'align))
11817 ((equal property "SCHEDULED")
11818 (if (re-search-forward org-scheduled-time-regexp end t)
11819 (cond
11820 ((eq value 'earlier) (org-timestamp-change -1 'day))
11821 ((eq value 'later) (org-timestamp-change 1 'day))
11822 (t (call-interactively 'org-schedule)))
11823 (call-interactively 'org-schedule)))
11824 ((equal property "DEADLINE")
11825 (if (re-search-forward org-deadline-time-regexp end t)
11826 (cond
11827 ((eq value 'earlier) (org-timestamp-change -1 'day))
11828 ((eq value 'later) (org-timestamp-change 1 'day))
11829 (t (call-interactively 'org-deadline)))
11830 (call-interactively 'org-deadline)))
11831 ((member property org-special-properties)
11832 (error "The %s property can not yet be set with `org-entry-put'"
11833 property))
11834 (t ; a non-special property
11835 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
11836 (setq range (org-get-property-block beg end 'force))
11837 (goto-char (car range))
11838 (if (re-search-forward
11839 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
11840 (progn
11841 (delete-region (match-beginning 1) (match-end 1))
11842 (goto-char (match-beginning 1)))
11843 (goto-char (cdr range))
11844 (insert "\n")
11845 (backward-char 1)
11846 (org-indent-line-function)
11847 (insert ":" property ":"))
11848 (and value (insert " " value))
11849 (org-indent-line-function)))))))
11850
11851 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
11852 "Get all property keys in the current buffer.
11853 With INCLUDE-SPECIALS, also list the special properties that reflect things
11854 like tags and TODO state.
11855 With INCLUDE-DEFAULTS, also include properties that has special meaning
11856 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
11857 With INCLUDE-COLUMNS, also include property names given in COLUMN
11858 formats in the current buffer."
11859 (let (rtn range cfmt s p)
11860 (save-excursion
11861 (save-restriction
11862 (widen)
11863 (goto-char (point-min))
11864 (while (re-search-forward org-property-start-re nil t)
11865 (setq range (org-get-property-block))
11866 (goto-char (car range))
11867 (while (re-search-forward
11868 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
11869 (cdr range) t)
11870 (add-to-list 'rtn (org-match-string-no-properties 1)))
11871 (outline-next-heading))))
11872
11873 (when include-specials
11874 (setq rtn (append org-special-properties rtn)))
11875
11876 (when include-defaults
11877 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties)
11878 (add-to-list 'rtn org-effort-property))
11879
11880 (when include-columns
11881 (save-excursion
11882 (save-restriction
11883 (widen)
11884 (goto-char (point-min))
11885 (while (re-search-forward
11886 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
11887 nil t)
11888 (setq cfmt (match-string 2) s 0)
11889 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
11890 cfmt s)
11891 (setq s (match-end 0)
11892 p (match-string 1 cfmt))
11893 (unless (or (equal p "ITEM")
11894 (member p org-special-properties))
11895 (add-to-list 'rtn (match-string 1 cfmt))))))))
11896
11897 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
11898
11899 (defun org-property-values (key)
11900 "Return a list of all values of property KEY."
11901 (save-excursion
11902 (save-restriction
11903 (widen)
11904 (goto-char (point-min))
11905 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
11906 values)
11907 (while (re-search-forward re nil t)
11908 (add-to-list 'values (org-trim (match-string 1))))
11909 (delete "" values)))))
11910
11911 (defun org-insert-property-drawer ()
11912 "Insert a property drawer into the current entry."
11913 (interactive)
11914 (org-back-to-heading t)
11915 (looking-at outline-regexp)
11916 (let ((indent (if org-adapt-indentation
11917 (- (match-end 0)(match-beginning 0))
11918 0))
11919 (beg (point))
11920 (re (concat "^[ \t]*" org-keyword-time-regexp))
11921 end hiddenp)
11922 (outline-next-heading)
11923 (setq end (point))
11924 (goto-char beg)
11925 (while (re-search-forward re end t))
11926 (setq hiddenp (org-invisible-p))
11927 (end-of-line 1)
11928 (and (equal (char-after) ?\n) (forward-char 1))
11929 (while (looking-at "^[ \t]*\\(:CLOCK:\\|:LOGBOOK:\\|CLOCK:\\|:END:\\)")
11930 (if (member (match-string 1) '("CLOCK:" ":END:"))
11931 ;; just skip this line
11932 (beginning-of-line 2)
11933 ;; Drawer start, find the end
11934 (re-search-forward "^\\*+ \\|^[ \t]*:END:" nil t)
11935 (beginning-of-line 1)))
11936 (org-skip-over-state-notes)
11937 (skip-chars-backward " \t\n\r")
11938 (if (eq (char-before) ?*) (forward-char 1))
11939 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
11940 (beginning-of-line 0)
11941 (org-indent-to-column indent)
11942 (beginning-of-line 2)
11943 (org-indent-to-column indent)
11944 (beginning-of-line 0)
11945 (if hiddenp
11946 (save-excursion
11947 (org-back-to-heading t)
11948 (hide-entry))
11949 (org-flag-drawer t))))
11950
11951 (defun org-set-property (property value)
11952 "In the current entry, set PROPERTY to VALUE.
11953 When called interactively, this will prompt for a property name, offering
11954 completion on existing and default properties. And then it will prompt
11955 for a value, offering completion either on allowed values (via an inherited
11956 xxx_ALL property) or on existing values in other instances of this property
11957 in the current file."
11958 (interactive
11959 (let* ((completion-ignore-case t)
11960 (keys (org-buffer-property-keys nil t t))
11961 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
11962 (prop (if (member prop0 keys)
11963 prop0
11964 (or (cdr (assoc (downcase prop0)
11965 (mapcar (lambda (x) (cons (downcase x) x))
11966 keys)))
11967 prop0)))
11968 (cur (org-entry-get nil prop))
11969 (allowed (org-property-get-allowed-values nil prop 'table))
11970 (existing (mapcar 'list (org-property-values prop)))
11971 (val (if allowed
11972 (org-completing-read "Value: " allowed nil 'req-match)
11973 (let (org-completion-use-ido)
11974 (org-completing-read
11975 (concat "Value" (if (and cur (string-match "\\S-" cur))
11976 (concat "[" cur "]") "")
11977 ": ")
11978 existing nil nil "" nil cur)))))
11979 (list prop (if (equal val "") cur val))))
11980 (unless (equal (org-entry-get nil property) value)
11981 (org-entry-put nil property value)))
11982
11983 (defun org-delete-property (property)
11984 "In the current entry, delete PROPERTY."
11985 (interactive
11986 (let* ((completion-ignore-case t)
11987 (prop (org-ido-completing-read
11988 "Property: " (org-entry-properties nil 'standard))))
11989 (list prop)))
11990 (message "Property %s %s" property
11991 (if (org-entry-delete nil property)
11992 "deleted"
11993 "was not present in the entry")))
11994
11995 (defun org-delete-property-globally (property)
11996 "Remove PROPERTY globally, from all entries."
11997 (interactive
11998 (let* ((completion-ignore-case t)
11999 (prop (org-ido-completing-read
12000 "Globally remove property: "
12001 (mapcar 'list (org-buffer-property-keys)))))
12002 (list prop)))
12003 (save-excursion
12004 (save-restriction
12005 (widen)
12006 (goto-char (point-min))
12007 (let ((cnt 0))
12008 (while (re-search-forward
12009 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
12010 nil t)
12011 (setq cnt (1+ cnt))
12012 (replace-match ""))
12013 (message "Property \"%s\" removed from %d entries" property cnt)))))
12014
12015 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
12016
12017 (defun org-compute-property-at-point ()
12018 "Compute the property at point.
12019 This looks for an enclosing column format, extracts the operator and
12020 then applies it to the property in the column format's scope."
12021 (interactive)
12022 (unless (org-at-property-p)
12023 (error "Not at a property"))
12024 (let ((prop (org-match-string-no-properties 2)))
12025 (org-columns-get-format-and-top-level)
12026 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
12027 (error "No operator defined for property %s" prop))
12028 (org-columns-compute prop)))
12029
12030 (defun org-property-get-allowed-values (pom property &optional table)
12031 "Get allowed values for the property PROPERTY.
12032 When TABLE is non-nil, return an alist that can directly be used for
12033 completion."
12034 (let (vals)
12035 (cond
12036 ((equal property "TODO")
12037 (setq vals (org-with-point-at pom
12038 (append org-todo-keywords-1 '("")))))
12039 ((equal property "PRIORITY")
12040 (let ((n org-lowest-priority))
12041 (while (>= n org-highest-priority)
12042 (push (char-to-string n) vals)
12043 (setq n (1- n)))))
12044 ((member property org-special-properties))
12045 (t
12046 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
12047
12048 (when (and vals (string-match "\\S-" vals))
12049 (setq vals (car (read-from-string (concat "(" vals ")"))))
12050 (setq vals (mapcar (lambda (x)
12051 (cond ((stringp x) x)
12052 ((numberp x) (number-to-string x))
12053 ((symbolp x) (symbol-name x))
12054 (t "???")))
12055 vals)))))
12056 (if table (mapcar 'list vals) vals)))
12057
12058 (defun org-property-previous-allowed-value (&optional previous)
12059 "Switch to the next allowed value for this property."
12060 (interactive)
12061 (org-property-next-allowed-value t))
12062
12063 (defun org-property-next-allowed-value (&optional previous)
12064 "Switch to the next allowed value for this property."
12065 (interactive)
12066 (unless (org-at-property-p)
12067 (error "Not at a property"))
12068 (let* ((key (match-string 2))
12069 (value (match-string 3))
12070 (allowed (or (org-property-get-allowed-values (point) key)
12071 (and (member value '("[ ]" "[-]" "[X]"))
12072 '("[ ]" "[X]"))))
12073 nval)
12074 (unless allowed
12075 (error "Allowed values for this property have not been defined"))
12076 (if previous (setq allowed (reverse allowed)))
12077 (if (member value allowed)
12078 (setq nval (car (cdr (member value allowed)))))
12079 (setq nval (or nval (car allowed)))
12080 (if (equal nval value)
12081 (error "Only one allowed value for this property"))
12082 (org-at-property-p)
12083 (replace-match (concat " :" key ": " nval) t t)
12084 (org-indent-line-function)
12085 (beginning-of-line 1)
12086 (skip-chars-forward " \t")))
12087
12088 (defun org-find-entry-with-id (ident)
12089 "Locate the entry that contains the ID property with exact value IDENT.
12090 IDENT can be a string, a symbol or a number, this function will search for
12091 the string representation of it.
12092 Return the position where this entry starts, or nil if there is no such entry."
12093 (interactive "sID: ")
12094 (let ((id (cond
12095 ((stringp ident) ident)
12096 ((symbol-name ident) (symbol-name ident))
12097 ((numberp ident) (number-to-string ident))
12098 (t (error "IDENT %s must be a string, symbol or number" ident))))
12099 (case-fold-search nil))
12100 (save-excursion
12101 (save-restriction
12102 (widen)
12103 (goto-char (point-min))
12104 (when (re-search-forward
12105 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
12106 nil t)
12107 (org-back-to-heading t)
12108 (point))))))
12109
12110 ;;;; Timestamps
12111
12112 (defvar org-last-changed-timestamp nil)
12113 (defvar org-last-inserted-timestamp nil
12114 "The last time stamp inserted with `org-insert-time-stamp'.")
12115 (defvar org-time-was-given) ; dynamically scoped parameter
12116 (defvar org-end-time-was-given) ; dynamically scoped parameter
12117 (defvar org-ts-what) ; dynamically scoped parameter
12118
12119 (defun org-time-stamp (arg &optional inactive)
12120 "Prompt for a date/time and insert a time stamp.
12121 If the user specifies a time like HH:MM, or if this command is called
12122 with a prefix argument, the time stamp will contain date and time.
12123 Otherwise, only the date will be included. All parts of a date not
12124 specified by the user will be filled in from the current date/time.
12125 So if you press just return without typing anything, the time stamp
12126 will represent the current date/time. If there is already a timestamp
12127 at the cursor, it will be modified."
12128 (interactive "P")
12129 (let* ((ts nil)
12130 (default-time
12131 ;; Default time is either today, or, when entering a range,
12132 ;; the range start.
12133 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
12134 (save-excursion
12135 (re-search-backward
12136 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
12137 (- (point) 20) t)))
12138 (apply 'encode-time (org-parse-time-string (match-string 1)))
12139 (current-time)))
12140 (default-input (and ts (org-get-compact-tod ts)))
12141 org-time-was-given org-end-time-was-given time)
12142 (cond
12143 ((and (org-at-timestamp-p t)
12144 (memq last-command '(org-time-stamp org-time-stamp-inactive))
12145 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
12146 (insert "--")
12147 (setq time (let ((this-command this-command))
12148 (org-read-date arg 'totime nil nil
12149 default-time default-input)))
12150 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
12151 ((org-at-timestamp-p t)
12152 (setq time (let ((this-command this-command))
12153 (org-read-date arg 'totime nil nil default-time default-input)))
12154 (when (org-at-timestamp-p t) ; just to get the match data
12155 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
12156 (replace-match "")
12157 (setq org-last-changed-timestamp
12158 (org-insert-time-stamp
12159 time (or org-time-was-given arg)
12160 inactive nil nil (list org-end-time-was-given))))
12161 (message "Timestamp updated"))
12162 (t
12163 (setq time (let ((this-command this-command))
12164 (org-read-date arg 'totime nil nil default-time default-input)))
12165 (org-insert-time-stamp time (or org-time-was-given arg) inactive
12166 nil nil (list org-end-time-was-given))))))
12167
12168 ;; FIXME: can we use this for something else, like computing time differences?
12169 (defun org-get-compact-tod (s)
12170 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
12171 (let* ((t1 (match-string 1 s))
12172 (h1 (string-to-number (match-string 2 s)))
12173 (m1 (string-to-number (match-string 3 s)))
12174 (t2 (and (match-end 4) (match-string 5 s)))
12175 (h2 (and t2 (string-to-number (match-string 6 s))))
12176 (m2 (and t2 (string-to-number (match-string 7 s))))
12177 dh dm)
12178 (if (not t2)
12179 t1
12180 (setq dh (- h2 h1) dm (- m2 m1))
12181 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
12182 (concat t1 "+" (number-to-string dh)
12183 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
12184
12185 (defun org-time-stamp-inactive (&optional arg)
12186 "Insert an inactive time stamp.
12187 An inactive time stamp is enclosed in square brackets instead of angle
12188 brackets. It is inactive in the sense that it does not trigger agenda entries,
12189 does not link to the calendar and cannot be changed with the S-cursor keys.
12190 So these are more for recording a certain time/date."
12191 (interactive "P")
12192 (org-time-stamp arg 'inactive))
12193
12194 (defvar org-date-ovl (org-make-overlay 1 1))
12195 (org-overlay-put org-date-ovl 'face 'org-warning)
12196 (org-detach-overlay org-date-ovl)
12197
12198 (defvar org-ans1) ; dynamically scoped parameter
12199 (defvar org-ans2) ; dynamically scoped parameter
12200
12201 (defvar org-plain-time-of-day-regexp) ; defined below
12202
12203 (defvar org-overriding-default-time nil) ; dynamically scoped
12204 (defvar org-read-date-overlay nil)
12205 (defvar org-dcst nil) ; dynamically scoped
12206 (defvar org-read-date-history nil)
12207 (defvar org-read-date-final-answer nil)
12208
12209 (defun org-read-date (&optional with-time to-time from-string prompt
12210 default-time default-input)
12211 "Read a date, possibly a time, and make things smooth for the user.
12212 The prompt will suggest to enter an ISO date, but you can also enter anything
12213 which will at least partially be understood by `parse-time-string'.
12214 Unrecognized parts of the date will default to the current day, month, year,
12215 hour and minute. If this command is called to replace a timestamp at point,
12216 of to enter the second timestamp of a range, the default time is taken from the
12217 existing stamp. For example,
12218 3-2-5 --> 2003-02-05
12219 feb 15 --> currentyear-02-15
12220 sep 12 9 --> 2009-09-12
12221 12:45 --> today 12:45
12222 22 sept 0:34 --> currentyear-09-22 0:34
12223 12 --> currentyear-currentmonth-12
12224 Fri --> nearest Friday (today or later)
12225 etc.
12226
12227 Furthermore you can specify a relative date by giving, as the *first* thing
12228 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
12229 change in days weeks, months, years.
12230 With a single plus or minus, the date is relative to today. With a double
12231 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
12232 +4d --> four days from today
12233 +4 --> same as above
12234 +2w --> two weeks from today
12235 ++5 --> five days from default date
12236
12237 The function understands only English month and weekday abbreviations,
12238 but this can be configured with the variables `parse-time-months' and
12239 `parse-time-weekdays'.
12240
12241 While prompting, a calendar is popped up - you can also select the
12242 date with the mouse (button 1). The calendar shows a period of three
12243 months. To scroll it to other months, use the keys `>' and `<'.
12244 If you don't like the calendar, turn it off with
12245 \(setq org-read-date-popup-calendar nil)
12246
12247 With optional argument TO-TIME, the date will immediately be converted
12248 to an internal time.
12249 With an optional argument WITH-TIME, the prompt will suggest to also
12250 insert a time. Note that when WITH-TIME is not set, you can still
12251 enter a time, and this function will inform the calling routine about
12252 this change. The calling routine may then choose to change the format
12253 used to insert the time stamp into the buffer to include the time.
12254 With optional argument FROM-STRING, read from this string instead from
12255 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
12256 the time/date that is used for everything that is not specified by the
12257 user."
12258 (require 'parse-time)
12259 (let* ((org-time-stamp-rounding-minutes
12260 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
12261 (org-dcst org-display-custom-times)
12262 (ct (org-current-time))
12263 (def (or org-overriding-default-time default-time ct))
12264 (defdecode (decode-time def))
12265 (dummy (progn
12266 (when (< (nth 2 defdecode) org-extend-today-until)
12267 (setcar (nthcdr 2 defdecode) -1)
12268 (setcar (nthcdr 1 defdecode) 59)
12269 (setq def (apply 'encode-time defdecode)
12270 defdecode (decode-time def)))))
12271 (calendar-frame-setup nil)
12272 (calendar-move-hook nil)
12273 (calendar-view-diary-initially-flag nil)
12274 (view-diary-entries-initially nil)
12275 (calendar-view-holidays-initially-flag nil)
12276 (view-calendar-holidays-initially nil)
12277 (timestr (format-time-string
12278 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
12279 (prompt (concat (if prompt (concat prompt " ") "")
12280 (format "Date+time [%s]: " timestr)))
12281 ans (org-ans0 "") org-ans1 org-ans2 final)
12282
12283 (cond
12284 (from-string (setq ans from-string))
12285 (org-read-date-popup-calendar
12286 (save-excursion
12287 (save-window-excursion
12288 (calendar)
12289 (calendar-forward-day (- (time-to-days def)
12290 (calendar-absolute-from-gregorian
12291 (calendar-current-date))))
12292 (org-eval-in-calendar nil t)
12293 (let* ((old-map (current-local-map))
12294 (map (copy-keymap calendar-mode-map))
12295 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
12296 (org-defkey map (kbd "RET") 'org-calendar-select)
12297 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
12298 'org-calendar-select-mouse)
12299 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
12300 'org-calendar-select-mouse)
12301 (org-defkey minibuffer-local-map [(meta shift left)]
12302 (lambda () (interactive)
12303 (org-eval-in-calendar '(calendar-backward-month 1))))
12304 (org-defkey minibuffer-local-map [(meta shift right)]
12305 (lambda () (interactive)
12306 (org-eval-in-calendar '(calendar-forward-month 1))))
12307 (org-defkey minibuffer-local-map [(meta shift up)]
12308 (lambda () (interactive)
12309 (org-eval-in-calendar '(calendar-backward-year 1))))
12310 (org-defkey minibuffer-local-map [(meta shift down)]
12311 (lambda () (interactive)
12312 (org-eval-in-calendar '(calendar-forward-year 1))))
12313 (org-defkey minibuffer-local-map [?\e (shift left)]
12314 (lambda () (interactive)
12315 (org-eval-in-calendar '(calendar-backward-month 1))))
12316 (org-defkey minibuffer-local-map [?\e (shift right)]
12317 (lambda () (interactive)
12318 (org-eval-in-calendar '(calendar-forward-month 1))))
12319 (org-defkey minibuffer-local-map [?\e (shift up)]
12320 (lambda () (interactive)
12321 (org-eval-in-calendar '(calendar-backward-year 1))))
12322 (org-defkey minibuffer-local-map [?\e (shift down)]
12323 (lambda () (interactive)
12324 (org-eval-in-calendar '(calendar-forward-year 1))))
12325 (org-defkey minibuffer-local-map [(shift up)]
12326 (lambda () (interactive)
12327 (org-eval-in-calendar '(calendar-backward-week 1))))
12328 (org-defkey minibuffer-local-map [(shift down)]
12329 (lambda () (interactive)
12330 (org-eval-in-calendar '(calendar-forward-week 1))))
12331 (org-defkey minibuffer-local-map [(shift left)]
12332 (lambda () (interactive)
12333 (org-eval-in-calendar '(calendar-backward-day 1))))
12334 (org-defkey minibuffer-local-map [(shift right)]
12335 (lambda () (interactive)
12336 (org-eval-in-calendar '(calendar-forward-day 1))))
12337 (org-defkey minibuffer-local-map ">"
12338 (lambda () (interactive)
12339 (org-eval-in-calendar '(scroll-calendar-left 1))))
12340 (org-defkey minibuffer-local-map "<"
12341 (lambda () (interactive)
12342 (org-eval-in-calendar '(scroll-calendar-right 1))))
12343 (run-hooks 'org-read-date-minibuffer-setup-hook)
12344 (unwind-protect
12345 (progn
12346 (use-local-map map)
12347 (add-hook 'post-command-hook 'org-read-date-display)
12348 (setq org-ans0 (read-string prompt default-input
12349 'org-read-date-history nil))
12350 ;; org-ans0: from prompt
12351 ;; org-ans1: from mouse click
12352 ;; org-ans2: from calendar motion
12353 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
12354 (remove-hook 'post-command-hook 'org-read-date-display)
12355 (use-local-map old-map)
12356 (when org-read-date-overlay
12357 (org-delete-overlay org-read-date-overlay)
12358 (setq org-read-date-overlay nil)))))))
12359
12360 (t ; Naked prompt only
12361 (unwind-protect
12362 (setq ans (read-string prompt default-input
12363 'org-read-date-history timestr))
12364 (when org-read-date-overlay
12365 (org-delete-overlay org-read-date-overlay)
12366 (setq org-read-date-overlay nil)))))
12367
12368 (setq final (org-read-date-analyze ans def defdecode))
12369 (setq org-read-date-final-answer ans)
12370
12371 (if to-time
12372 (apply 'encode-time final)
12373 (if (and (boundp 'org-time-was-given) org-time-was-given)
12374 (format "%04d-%02d-%02d %02d:%02d"
12375 (nth 5 final) (nth 4 final) (nth 3 final)
12376 (nth 2 final) (nth 1 final))
12377 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
12378
12379 (defvar def)
12380 (defvar defdecode)
12381 (defvar with-time)
12382 (defun org-read-date-display ()
12383 "Display the current date prompt interpretation in the minibuffer."
12384 (when org-read-date-display-live
12385 (when org-read-date-overlay
12386 (org-delete-overlay org-read-date-overlay))
12387 (let ((p (point)))
12388 (end-of-line 1)
12389 (while (not (equal (buffer-substring
12390 (max (point-min) (- (point) 4)) (point))
12391 " "))
12392 (insert " "))
12393 (goto-char p))
12394 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
12395 " " (or org-ans1 org-ans2)))
12396 (org-end-time-was-given nil)
12397 (f (org-read-date-analyze ans def defdecode))
12398 (fmts (if org-dcst
12399 org-time-stamp-custom-formats
12400 org-time-stamp-formats))
12401 (fmt (if (or with-time
12402 (and (boundp 'org-time-was-given) org-time-was-given))
12403 (cdr fmts)
12404 (car fmts)))
12405 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
12406 (when (and org-end-time-was-given
12407 (string-match org-plain-time-of-day-regexp txt))
12408 (setq txt (concat (substring txt 0 (match-end 0)) "-"
12409 org-end-time-was-given
12410 (substring txt (match-end 0)))))
12411 (setq org-read-date-overlay
12412 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
12413 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
12414
12415 (defun org-read-date-analyze (ans def defdecode)
12416 "Analyse the combined answer of the date prompt."
12417 ;; FIXME: cleanup and comment
12418 (let (delta deltan deltaw deltadef year month day
12419 hour minute second wday pm h2 m2 tl wday1
12420 iso-year iso-weekday iso-week iso-year iso-date)
12421
12422 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
12423 (setq ans "+0"))
12424
12425 (when (setq delta (org-read-date-get-relative ans (current-time) def))
12426 (setq ans (replace-match "" t t ans)
12427 deltan (car delta)
12428 deltaw (nth 1 delta)
12429 deltadef (nth 2 delta)))
12430
12431 ;; Check if there is an iso week date in there
12432 ;; If yes, sore the info and postpone interpreting it until the rest
12433 ;; of the parsing is done
12434 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
12435 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
12436 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
12437 iso-week (string-to-number (match-string 2 ans)))
12438 (setq ans (replace-match "" t t ans)))
12439
12440 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
12441 (when (string-match
12442 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
12443 (setq year (if (match-end 2)
12444 (string-to-number (match-string 2 ans))
12445 (string-to-number (format-time-string "%Y")))
12446 month (string-to-number (match-string 3 ans))
12447 day (string-to-number (match-string 4 ans)))
12448 (if (< year 100) (setq year (+ 2000 year)))
12449 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
12450 t nil ans)))
12451 ;; Help matching am/pm times, because `parse-time-string' does not do that.
12452 ;; If there is a time with am/pm, and *no* time without it, we convert
12453 ;; so that matching will be successful.
12454 (loop for i from 1 to 2 do ; twice, for end time as well
12455 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
12456 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
12457 (setq hour (string-to-number (match-string 1 ans))
12458 minute (if (match-end 3)
12459 (string-to-number (match-string 3 ans))
12460 0)
12461 pm (equal ?p
12462 (string-to-char (downcase (match-string 4 ans)))))
12463 (if (and (= hour 12) (not pm))
12464 (setq hour 0)
12465 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
12466 (setq ans (replace-match (format "%02d:%02d" hour minute)
12467 t t ans))))
12468
12469 ;; Check if a time range is given as a duration
12470 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
12471 (setq hour (string-to-number (match-string 1 ans))
12472 h2 (+ hour (string-to-number (match-string 3 ans)))
12473 minute (string-to-number (match-string 2 ans))
12474 m2 (+ minute (if (match-end 5) (string-to-number
12475 (match-string 5 ans))0)))
12476 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
12477 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
12478 t t ans)))
12479
12480 ;; Check if there is a time range
12481 (when (boundp 'org-end-time-was-given)
12482 (setq org-time-was-given nil)
12483 (when (and (string-match org-plain-time-of-day-regexp ans)
12484 (match-end 8))
12485 (setq org-end-time-was-given (match-string 8 ans))
12486 (setq ans (concat (substring ans 0 (match-beginning 7))
12487 (substring ans (match-end 7))))))
12488
12489 (setq tl (parse-time-string ans)
12490 day (or (nth 3 tl) (nth 3 defdecode))
12491 month (or (nth 4 tl)
12492 (if (and org-read-date-prefer-future
12493 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
12494 (1+ (nth 4 defdecode))
12495 (nth 4 defdecode)))
12496 year (or (nth 5 tl)
12497 (if (and org-read-date-prefer-future
12498 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
12499 (1+ (nth 5 defdecode))
12500 (nth 5 defdecode)))
12501 hour (or (nth 2 tl) (nth 2 defdecode))
12502 minute (or (nth 1 tl) (nth 1 defdecode))
12503 second (or (nth 0 tl) 0)
12504 wday (nth 6 tl))
12505
12506 ;; Special date definitions below
12507 (cond
12508 (iso-week
12509 ;; There was an iso week
12510 (setq year (or iso-year year)
12511 day (or iso-weekday wday 1)
12512 wday nil ; to make sure that the trigger below does not match
12513 iso-date (calendar-gregorian-from-absolute
12514 (calendar-absolute-from-iso
12515 (list iso-week day year))))
12516 ; FIXME: Should we also push ISO weeks into the future?
12517 ; (when (and org-read-date-prefer-future
12518 ; (not iso-year)
12519 ; (< (calendar-absolute-from-gregorian iso-date)
12520 ; (time-to-days (current-time))))
12521 ; (setq year (1+ year)
12522 ; iso-date (calendar-gregorian-from-absolute
12523 ; (calendar-absolute-from-iso
12524 ; (list iso-week day year)))))
12525 (setq month (car iso-date)
12526 year (nth 2 iso-date)
12527 day (nth 1 iso-date)))
12528 (deltan
12529 (unless deltadef
12530 (let ((now (decode-time (current-time))))
12531 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
12532 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
12533 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
12534 ((equal deltaw "m") (setq month (+ month deltan)))
12535 ((equal deltaw "y") (setq year (+ year deltan)))))
12536 ((and wday (not (nth 3 tl)))
12537 ;; Weekday was given, but no day, so pick that day in the week
12538 ;; on or after the derived date.
12539 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
12540 (unless (equal wday wday1)
12541 (setq day (+ day (% (- wday wday1 -7) 7))))))
12542 (if (and (boundp 'org-time-was-given)
12543 (nth 2 tl))
12544 (setq org-time-was-given t))
12545 (if (< year 100) (setq year (+ 2000 year)))
12546 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
12547 (list second minute hour day month year)))
12548
12549 (defvar parse-time-weekdays)
12550
12551 (defun org-read-date-get-relative (s today default)
12552 "Check string S for special relative date string.
12553 TODAY and DEFAULT are internal times, for today and for a default.
12554 Return shift list (N what def-flag)
12555 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
12556 N is the number of WHATs to shift.
12557 DEF-FLAG is t when a double ++ or -- indicates shift relative to
12558 the DEFAULT date rather than TODAY."
12559 (when (and
12560 (string-match
12561 (concat
12562 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
12563 "\\([0-9]+\\)?"
12564 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
12565 "\\([ \t]\\|$\\)") s)
12566 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
12567 (let* ((dir (if (> (match-end 1) (match-beginning 1))
12568 (string-to-char (substring (match-string 1 s) -1))
12569 ?+))
12570 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
12571 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
12572 (what (if (match-end 3) (match-string 3 s) "d"))
12573 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
12574 (date (if rel default today))
12575 (wday (nth 6 (decode-time date)))
12576 delta)
12577 (if wday1
12578 (progn
12579 (setq delta (mod (+ 7 (- wday1 wday)) 7))
12580 (if (= dir ?-) (setq delta (- delta 7)))
12581 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
12582 (list delta "d" rel))
12583 (list (* n (if (= dir ?-) -1 1)) what rel)))))
12584
12585 (defun org-eval-in-calendar (form &optional keepdate)
12586 "Eval FORM in the calendar window and return to current window.
12587 Also, store the cursor date in variable org-ans2."
12588 (let ((sf (selected-frame))
12589 (sw (selected-window)))
12590 (select-window (get-buffer-window "*Calendar*" t))
12591 (eval form)
12592 (when (and (not keepdate) (calendar-cursor-to-date))
12593 (let* ((date (calendar-cursor-to-date))
12594 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12595 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
12596 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
12597 (select-window sw)
12598 (select-frame-set-input-focus sf)))
12599
12600 (defun org-calendar-select ()
12601 "Return to `org-read-date' with the date currently selected.
12602 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12603 (interactive)
12604 (when (calendar-cursor-to-date)
12605 (let* ((date (calendar-cursor-to-date))
12606 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12607 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12608 (if (active-minibuffer-window) (exit-minibuffer))))
12609
12610 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
12611 "Insert a date stamp for the date given by the internal TIME.
12612 WITH-HM means, use the stamp format that includes the time of the day.
12613 INACTIVE means use square brackets instead of angular ones, so that the
12614 stamp will not contribute to the agenda.
12615 PRE and POST are optional strings to be inserted before and after the
12616 stamp.
12617 The command returns the inserted time stamp."
12618 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
12619 stamp)
12620 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
12621 (insert-before-markers (or pre ""))
12622 (insert-before-markers (setq stamp (format-time-string fmt time)))
12623 (when (listp extra)
12624 (setq extra (car extra))
12625 (if (and (stringp extra)
12626 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
12627 (setq extra (format "-%02d:%02d"
12628 (string-to-number (match-string 1 extra))
12629 (string-to-number (match-string 2 extra))))
12630 (setq extra nil)))
12631 (when extra
12632 (backward-char 1)
12633 (insert-before-markers extra)
12634 (forward-char 1))
12635 (insert-before-markers (or post ""))
12636 (setq org-last-inserted-timestamp stamp)))
12637
12638 (defun org-toggle-time-stamp-overlays ()
12639 "Toggle the use of custom time stamp formats."
12640 (interactive)
12641 (setq org-display-custom-times (not org-display-custom-times))
12642 (unless org-display-custom-times
12643 (let ((p (point-min)) (bmp (buffer-modified-p)))
12644 (while (setq p (next-single-property-change p 'display))
12645 (if (and (get-text-property p 'display)
12646 (eq (get-text-property p 'face) 'org-date))
12647 (remove-text-properties
12648 p (setq p (next-single-property-change p 'display))
12649 '(display t))))
12650 (set-buffer-modified-p bmp)))
12651 (if (featurep 'xemacs)
12652 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
12653 (org-restart-font-lock)
12654 (setq org-table-may-need-update t)
12655 (if org-display-custom-times
12656 (message "Time stamps are overlayed with custom format")
12657 (message "Time stamp overlays removed")))
12658
12659 (defun org-display-custom-time (beg end)
12660 "Overlay modified time stamp format over timestamp between BEG and END."
12661 (let* ((ts (buffer-substring beg end))
12662 t1 w1 with-hm tf time str w2 (off 0))
12663 (save-match-data
12664 (setq t1 (org-parse-time-string ts t))
12665 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
12666 (setq off (- (match-end 0) (match-beginning 0)))))
12667 (setq end (- end off))
12668 (setq w1 (- end beg)
12669 with-hm (and (nth 1 t1) (nth 2 t1))
12670 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
12671 time (org-fix-decoded-time t1)
12672 str (org-add-props
12673 (format-time-string
12674 (substring tf 1 -1) (apply 'encode-time time))
12675 nil 'mouse-face 'highlight)
12676 w2 (length str))
12677 (if (not (= w2 w1))
12678 (add-text-properties (1+ beg) (+ 2 beg)
12679 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
12680 (if (featurep 'xemacs)
12681 (progn
12682 (put-text-property beg end 'invisible t)
12683 (put-text-property beg end 'end-glyph (make-glyph str)))
12684 (put-text-property beg end 'display str))))
12685
12686 (defun org-translate-time (string)
12687 "Translate all timestamps in STRING to custom format.
12688 But do this only if the variable `org-display-custom-times' is set."
12689 (when org-display-custom-times
12690 (save-match-data
12691 (let* ((start 0)
12692 (re org-ts-regexp-both)
12693 t1 with-hm inactive tf time str beg end)
12694 (while (setq start (string-match re string start))
12695 (setq beg (match-beginning 0)
12696 end (match-end 0)
12697 t1 (save-match-data
12698 (org-parse-time-string (substring string beg end) t))
12699 with-hm (and (nth 1 t1) (nth 2 t1))
12700 inactive (equal (substring string beg (1+ beg)) "[")
12701 tf (funcall (if with-hm 'cdr 'car)
12702 org-time-stamp-custom-formats)
12703 time (org-fix-decoded-time t1)
12704 str (format-time-string
12705 (concat
12706 (if inactive "[" "<") (substring tf 1 -1)
12707 (if inactive "]" ">"))
12708 (apply 'encode-time time))
12709 string (replace-match str t t string)
12710 start (+ start (length str)))))))
12711 string)
12712
12713 (defun org-fix-decoded-time (time)
12714 "Set 0 instead of nil for the first 6 elements of time.
12715 Don't touch the rest."
12716 (let ((n 0))
12717 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
12718
12719 (defun org-days-to-time (timestamp-string)
12720 "Difference between TIMESTAMP-STRING and now in days."
12721 (- (time-to-days (org-time-string-to-time timestamp-string))
12722 (time-to-days (current-time))))
12723
12724 (defun org-deadline-close (timestamp-string &optional ndays)
12725 "Is the time in TIMESTAMP-STRING close to the current date?"
12726 (setq ndays (or ndays (org-get-wdays timestamp-string)))
12727 (and (< (org-days-to-time timestamp-string) ndays)
12728 (not (org-entry-is-done-p))))
12729
12730 (defun org-get-wdays (ts)
12731 "Get the deadline lead time appropriate for timestring TS."
12732 (cond
12733 ((<= org-deadline-warning-days 0)
12734 ;; 0 or negative, enforce this value no matter what
12735 (- org-deadline-warning-days))
12736 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\| \\)" ts)
12737 ;; lead time is specified.
12738 (floor (* (string-to-number (match-string 1 ts))
12739 (cdr (assoc (match-string 2 ts)
12740 '(("d" . 1) ("w" . 7)
12741 ("m" . 30.4) ("y" . 365.25)))))))
12742 ;; go for the default.
12743 (t org-deadline-warning-days)))
12744
12745 (defun org-calendar-select-mouse (ev)
12746 "Return to `org-read-date' with the date currently selected.
12747 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
12748 (interactive "e")
12749 (mouse-set-point ev)
12750 (when (calendar-cursor-to-date)
12751 (let* ((date (calendar-cursor-to-date))
12752 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
12753 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
12754 (if (active-minibuffer-window) (exit-minibuffer))))
12755
12756 (defun org-check-deadlines (ndays)
12757 "Check if there are any deadlines due or past due.
12758 A deadline is considered due if it happens within `org-deadline-warning-days'
12759 days from today's date. If the deadline appears in an entry marked DONE,
12760 it is not shown. The prefix arg NDAYS can be used to test that many
12761 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
12762 (interactive "P")
12763 (let* ((org-warn-days
12764 (cond
12765 ((equal ndays '(4)) 100000)
12766 (ndays (prefix-numeric-value ndays))
12767 (t (abs org-deadline-warning-days))))
12768 (case-fold-search nil)
12769 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
12770 (callback
12771 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
12772
12773 (message "%d deadlines past-due or due within %d days"
12774 (org-occur regexp nil callback)
12775 org-warn-days)))
12776
12777 (defun org-check-before-date (date)
12778 "Check if there are deadlines or scheduled entries before DATE."
12779 (interactive (list (org-read-date)))
12780 (let ((case-fold-search nil)
12781 (regexp (concat "\\<\\(" org-deadline-string
12782 "\\|" org-scheduled-string
12783 "\\) *<\\([^>]+\\)>"))
12784 (callback
12785 (lambda () (time-less-p
12786 (org-time-string-to-time (match-string 2))
12787 (org-time-string-to-time date)))))
12788 (message "%d entries before %s"
12789 (org-occur regexp nil callback) date)))
12790
12791 (defun org-check-after-date (date)
12792 "Check if there are deadlines or scheduled entries after DATE."
12793 (interactive (list (org-read-date)))
12794 (let ((case-fold-search nil)
12795 (regexp (concat "\\<\\(" org-deadline-string
12796 "\\|" org-scheduled-string
12797 "\\) *<\\([^>]+\\)>"))
12798 (callback
12799 (lambda () (not
12800 (time-less-p
12801 (org-time-string-to-time (match-string 2))
12802 (org-time-string-to-time date))))))
12803 (message "%d entries after %s"
12804 (org-occur regexp nil callback) date)))
12805
12806 (defun org-evaluate-time-range (&optional to-buffer)
12807 "Evaluate a time range by computing the difference between start and end.
12808 Normally the result is just printed in the echo area, but with prefix arg
12809 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
12810 If the time range is actually in a table, the result is inserted into the
12811 next column.
12812 For time difference computation, a year is assumed to be exactly 365
12813 days in order to avoid rounding problems."
12814 (interactive "P")
12815 (or
12816 (org-clock-update-time-maybe)
12817 (save-excursion
12818 (unless (org-at-date-range-p t)
12819 (goto-char (point-at-bol))
12820 (re-search-forward org-tr-regexp-both (point-at-eol) t))
12821 (if (not (org-at-date-range-p t))
12822 (error "Not at a time-stamp range, and none found in current line")))
12823 (let* ((ts1 (match-string 1))
12824 (ts2 (match-string 2))
12825 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
12826 (match-end (match-end 0))
12827 (time1 (org-time-string-to-time ts1))
12828 (time2 (org-time-string-to-time ts2))
12829 (t1 (time-to-seconds time1))
12830 (t2 (time-to-seconds time2))
12831 (diff (abs (- t2 t1)))
12832 (negative (< (- t2 t1) 0))
12833 ;; (ys (floor (* 365 24 60 60)))
12834 (ds (* 24 60 60))
12835 (hs (* 60 60))
12836 (fy "%dy %dd %02d:%02d")
12837 (fy1 "%dy %dd")
12838 (fd "%dd %02d:%02d")
12839 (fd1 "%dd")
12840 (fh "%02d:%02d")
12841 y d h m align)
12842 (if havetime
12843 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12844 y 0
12845 d (floor (/ diff ds)) diff (mod diff ds)
12846 h (floor (/ diff hs)) diff (mod diff hs)
12847 m (floor (/ diff 60)))
12848 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
12849 y 0
12850 d (floor (+ (/ diff ds) 0.5))
12851 h 0 m 0))
12852 (if (not to-buffer)
12853 (message "%s" (org-make-tdiff-string y d h m))
12854 (if (org-at-table-p)
12855 (progn
12856 (goto-char match-end)
12857 (setq align t)
12858 (and (looking-at " *|") (goto-char (match-end 0))))
12859 (goto-char match-end))
12860 (if (looking-at
12861 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
12862 (replace-match ""))
12863 (if negative (insert " -"))
12864 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
12865 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
12866 (insert " " (format fh h m))))
12867 (if align (org-table-align))
12868 (message "Time difference inserted")))))
12869
12870 (defun org-make-tdiff-string (y d h m)
12871 (let ((fmt "")
12872 (l nil))
12873 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
12874 l (push y l)))
12875 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
12876 l (push d l)))
12877 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
12878 l (push h l)))
12879 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
12880 l (push m l)))
12881 (apply 'format fmt (nreverse l))))
12882
12883 (defun org-time-string-to-time (s)
12884 (apply 'encode-time (org-parse-time-string s)))
12885 (defun org-time-string-to-seconds (s)
12886 (time-to-seconds (org-time-string-to-time s)))
12887
12888 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
12889 "Convert a time stamp to an absolute day number.
12890 If there is a specifyer for a cyclic time stamp, get the closest date to
12891 DAYNR.
12892 PREFER and SHOW-ALL are passed through to `org-closest-date'.
12893 the variable date is bound by the calendar when this is called."
12894 (cond
12895 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
12896 (if (org-diary-sexp-entry (match-string 1 s) "" date)
12897 daynr
12898 (+ daynr 1000)))
12899 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
12900 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
12901 (time-to-days (current-time))) (match-string 0 s)
12902 prefer show-all))
12903 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
12904
12905 (defun org-days-to-iso-week (days)
12906 "Return the iso week number."
12907 (require 'cal-iso)
12908 (car (calendar-iso-from-absolute days)))
12909
12910 (defun org-small-year-to-year (year)
12911 "Convert 2-digit years into 4-digit years.
12912 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
12913 The year 2000 cannot be abbreviated. Any year larger than 99
12914 is returned unchanged."
12915 (if (< year 38)
12916 (setq year (+ 2000 year))
12917 (if (< year 100)
12918 (setq year (+ 1900 year))))
12919 year)
12920
12921 (defun org-time-from-absolute (d)
12922 "Return the time corresponding to date D.
12923 D may be an absolute day number, or a calendar-type list (month day year)."
12924 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
12925 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
12926
12927 (defun org-calendar-holiday ()
12928 "List of holidays, for Diary display in Org-mode."
12929 (require 'holidays)
12930 (let ((hl (funcall
12931 (if (fboundp 'calendar-check-holidays)
12932 'calendar-check-holidays 'check-calendar-holidays) date)))
12933 (if hl (mapconcat 'identity hl "; "))))
12934
12935 (defun org-diary-sexp-entry (sexp entry date)
12936 "Process a SEXP diary ENTRY for DATE."
12937 (require 'diary-lib)
12938 (let ((result (if calendar-debug-sexp
12939 (let ((stack-trace-on-error t))
12940 (eval (car (read-from-string sexp))))
12941 (condition-case nil
12942 (eval (car (read-from-string sexp)))
12943 (error
12944 (beep)
12945 (message "Bad sexp at line %d in %s: %s"
12946 (org-current-line)
12947 (buffer-file-name) sexp)
12948 (sleep-for 2))))))
12949 (cond ((stringp result) result)
12950 ((and (consp result)
12951 (stringp (cdr result))) (cdr result))
12952 (result entry)
12953 (t nil))))
12954
12955 (defun org-diary-to-ical-string (frombuf)
12956 "Get iCalendar entries from diary entries in buffer FROMBUF.
12957 This uses the icalendar.el library."
12958 (let* ((tmpdir (if (featurep 'xemacs)
12959 (temp-directory)
12960 temporary-file-directory))
12961 (tmpfile (make-temp-name
12962 (expand-file-name "orgics" tmpdir)))
12963 buf rtn b e)
12964 (save-excursion
12965 (set-buffer frombuf)
12966 (icalendar-export-region (point-min) (point-max) tmpfile)
12967 (setq buf (find-buffer-visiting tmpfile))
12968 (set-buffer buf)
12969 (goto-char (point-min))
12970 (if (re-search-forward "^BEGIN:VEVENT" nil t)
12971 (setq b (match-beginning 0)))
12972 (goto-char (point-max))
12973 (if (re-search-backward "^END:VEVENT" nil t)
12974 (setq e (match-end 0)))
12975 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
12976 (kill-buffer buf)
12977 (delete-file tmpfile)
12978 rtn))
12979
12980 (defun org-closest-date (start current change prefer show-all)
12981 "Find the date closest to CURRENT that is consistent with START and CHANGE.
12982 When PREFER is `past' return a date that is either CURRENT or past.
12983 When PREFER is `future', return a date that is either CURRENT or future.
12984 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
12985 ;; Make the proper lists from the dates
12986 (catch 'exit
12987 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
12988 dn dw sday cday n1 n2 n0
12989 d m y y1 y2 date1 date2 nmonths nm ny m2)
12990
12991 (setq start (org-date-to-gregorian start)
12992 current (org-date-to-gregorian
12993 (if show-all
12994 current
12995 (time-to-days (current-time))))
12996 sday (calendar-absolute-from-gregorian start)
12997 cday (calendar-absolute-from-gregorian current))
12998
12999 (if (<= cday sday) (throw 'exit sday))
13000
13001 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
13002 (setq dn (string-to-number (match-string 1 change))
13003 dw (cdr (assoc (match-string 2 change) a1)))
13004 (error "Invalid change specifyer: %s" change))
13005 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
13006 (cond
13007 ((eq dw 'day)
13008 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
13009 n2 (+ n1 dn)))
13010 ((eq dw 'year)
13011 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
13012 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
13013 (setq date1 (list m d y1)
13014 n1 (calendar-absolute-from-gregorian date1)
13015 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
13016 n2 (calendar-absolute-from-gregorian date2)))
13017 ((eq dw 'month)
13018 ;; approx number of month between the two dates
13019 (setq nmonths (floor (/ (- cday sday) 30.436875)))
13020 ;; How often does dn fit in there?
13021 (setq d (nth 1 start) m (car start) y (nth 2 start)
13022 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
13023 m (+ m nm)
13024 ny (floor (/ m 12))
13025 y (+ y ny)
13026 m (- m (* ny 12)))
13027 (while (> m 12) (setq m (- m 12) y (1+ y)))
13028 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
13029 (setq m2 (+ m dn) y2 y)
13030 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13031 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
13032 (while (<= n2 cday)
13033 (setq n1 n2 m m2 y y2)
13034 (setq m2 (+ m dn) y2 y)
13035 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
13036 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
13037 ;; Make sure n1 is the earlier date
13038 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
13039 (if show-all
13040 (cond
13041 ((eq prefer 'past) n1)
13042 ((eq prefer 'future) (if (= cday n1) n1 n2))
13043 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
13044 (cond
13045 ((eq prefer 'past) n1)
13046 ((eq prefer 'future) (if (= cday n1) n1 n2))
13047 (t (if (= cday n1) n1 n2)))))))
13048
13049 (defun org-date-to-gregorian (date)
13050 "Turn any specification of DATE into a gregorian date for the calendar."
13051 (cond ((integerp date) (calendar-gregorian-from-absolute date))
13052 ((and (listp date) (= (length date) 3)) date)
13053 ((stringp date)
13054 (setq date (org-parse-time-string date))
13055 (list (nth 4 date) (nth 3 date) (nth 5 date)))
13056 ((listp date)
13057 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
13058
13059 (defun org-parse-time-string (s &optional nodefault)
13060 "Parse the standard Org-mode time string.
13061 This should be a lot faster than the normal `parse-time-string'.
13062 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
13063 hour and minute fields will be nil if not given."
13064 (if (string-match org-ts-regexp0 s)
13065 (list 0
13066 (if (or (match-beginning 8) (not nodefault))
13067 (string-to-number (or (match-string 8 s) "0")))
13068 (if (or (match-beginning 7) (not nodefault))
13069 (string-to-number (or (match-string 7 s) "0")))
13070 (string-to-number (match-string 4 s))
13071 (string-to-number (match-string 3 s))
13072 (string-to-number (match-string 2 s))
13073 nil nil nil)
13074 (make-list 9 0)))
13075
13076 (defun org-timestamp-up (&optional arg)
13077 "Increase the date item at the cursor by one.
13078 If the cursor is on the year, change the year. If it is on the month or
13079 the day, change that.
13080 With prefix ARG, change by that many units."
13081 (interactive "p")
13082 (org-timestamp-change (prefix-numeric-value arg)))
13083
13084 (defun org-timestamp-down (&optional arg)
13085 "Decrease the date item at the cursor by one.
13086 If the cursor is on the year, change the year. If it is on the month or
13087 the day, change that.
13088 With prefix ARG, change by that many units."
13089 (interactive "p")
13090 (org-timestamp-change (- (prefix-numeric-value arg))))
13091
13092 (defun org-timestamp-up-day (&optional arg)
13093 "Increase the date in the time stamp by one day.
13094 With prefix ARG, change that many days."
13095 (interactive "p")
13096 (if (and (not (org-at-timestamp-p t))
13097 (org-on-heading-p))
13098 (org-todo 'up)
13099 (org-timestamp-change (prefix-numeric-value arg) 'day)))
13100
13101 (defun org-timestamp-down-day (&optional arg)
13102 "Decrease the date in the time stamp by one day.
13103 With prefix ARG, change that many days."
13104 (interactive "p")
13105 (if (and (not (org-at-timestamp-p t))
13106 (org-on-heading-p))
13107 (org-todo 'down)
13108 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
13109
13110 (defun org-at-timestamp-p (&optional inactive-ok)
13111 "Determine if the cursor is in or at a timestamp."
13112 (interactive)
13113 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
13114 (pos (point))
13115 (ans (or (looking-at tsr)
13116 (save-excursion
13117 (skip-chars-backward "^[<\n\r\t")
13118 (if (> (point) (point-min)) (backward-char 1))
13119 (and (looking-at tsr)
13120 (> (- (match-end 0) pos) -1))))))
13121 (and ans
13122 (boundp 'org-ts-what)
13123 (setq org-ts-what
13124 (cond
13125 ((= pos (match-beginning 0)) 'bracket)
13126 ((= pos (1- (match-end 0))) 'bracket)
13127 ((org-pos-in-match-range pos 2) 'year)
13128 ((org-pos-in-match-range pos 3) 'month)
13129 ((org-pos-in-match-range pos 7) 'hour)
13130 ((org-pos-in-match-range pos 8) 'minute)
13131 ((or (org-pos-in-match-range pos 4)
13132 (org-pos-in-match-range pos 5)) 'day)
13133 ((and (> pos (or (match-end 8) (match-end 5)))
13134 (< pos (match-end 0)))
13135 (- pos (or (match-end 8) (match-end 5))))
13136 (t 'day))))
13137 ans))
13138
13139 (defun org-toggle-timestamp-type ()
13140 "Toggle the type (<active> or [inactive]) of a time stamp."
13141 (interactive)
13142 (when (org-at-timestamp-p t)
13143 (let ((beg (match-beginning 0)) (end (match-end 0))
13144 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
13145 (save-excursion
13146 (goto-char beg)
13147 (while (re-search-forward "[][<>]" end t)
13148 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
13149 t t)))
13150 (message "Timestamp is now %sactive"
13151 (if (equal (char-after beg) ?<) "" "in")))))
13152
13153 (defun org-timestamp-change (n &optional what)
13154 "Change the date in the time stamp at point.
13155 The date will be changed by N times WHAT. WHAT can be `day', `month',
13156 `year', `minute', `second'. If WHAT is not given, the cursor position
13157 in the timestamp determines what will be changed."
13158 (let ((pos (point))
13159 with-hm inactive
13160 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
13161 org-ts-what
13162 extra rem
13163 ts time time0)
13164 (if (not (org-at-timestamp-p t))
13165 (error "Not at a timestamp"))
13166 (if (and (not what) (eq org-ts-what 'bracket))
13167 (org-toggle-timestamp-type)
13168 (if (and (not what) (not (eq org-ts-what 'day))
13169 org-display-custom-times
13170 (get-text-property (point) 'display)
13171 (not (get-text-property (1- (point)) 'display)))
13172 (setq org-ts-what 'day))
13173 (setq org-ts-what (or what org-ts-what)
13174 inactive (= (char-after (match-beginning 0)) ?\[)
13175 ts (match-string 0))
13176 (replace-match "")
13177 (if (string-match
13178 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
13179 ts)
13180 (setq extra (match-string 1 ts)))
13181 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
13182 (setq with-hm t))
13183 (setq time0 (org-parse-time-string ts))
13184 (when (and (eq org-ts-what 'minute)
13185 (eq current-prefix-arg nil))
13186 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
13187 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
13188 (setcar (cdr time0) (+ (nth 1 time0)
13189 (if (> n 0) (- rem) (- dm rem))))))
13190 (setq time
13191 (encode-time (or (car time0) 0)
13192 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
13193 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
13194 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
13195 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
13196 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
13197 (nthcdr 6 time0)))
13198 (when (and (member org-ts-what '(hour minute))
13199 extra
13200 (string-match "-\\([012][0-9]\\):\\([0-5][0-9]\\)" extra))
13201 (setq extra (org-modify-ts-extra
13202 extra
13203 (if (eq org-ts-what 'hour) 2 5)
13204 n dm)))
13205 (when (integerp org-ts-what)
13206 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
13207 (if (eq what 'calendar)
13208 (let ((cal-date (org-get-date-from-calendar)))
13209 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
13210 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
13211 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
13212 (setcar time0 (or (car time0) 0))
13213 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
13214 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
13215 (setq time (apply 'encode-time time0))))
13216 (setq org-last-changed-timestamp
13217 (org-insert-time-stamp time with-hm inactive nil nil extra))
13218 (org-clock-update-time-maybe)
13219 (goto-char pos)
13220 ;; Try to recenter the calendar window, if any
13221 (if (and org-calendar-follow-timestamp-change
13222 (get-buffer-window "*Calendar*" t)
13223 (memq org-ts-what '(day month year)))
13224 (org-recenter-calendar (time-to-days time))))))
13225
13226 (defun org-modify-ts-extra (s pos n dm)
13227 "Change the different parts of the lead-time and repeat fields in timestamp."
13228 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
13229 ng h m new rem)
13230 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
13231 (cond
13232 ((or (org-pos-in-match-range pos 2)
13233 (org-pos-in-match-range pos 3))
13234 (setq m (string-to-number (match-string 3 s))
13235 h (string-to-number (match-string 2 s)))
13236 (if (org-pos-in-match-range pos 2)
13237 (setq h (+ h n))
13238 (setq n (* dm (org-no-warnings (signum n))))
13239 (when (not (= 0 (setq rem (% m dm))))
13240 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
13241 (setq m (+ m n)))
13242 (if (< m 0) (setq m (+ m 60) h (1- h)))
13243 (if (> m 59) (setq m (- m 60) h (1+ h)))
13244 (setq h (min 24 (max 0 h)))
13245 (setq ng 1 new (format "-%02d:%02d" h m)))
13246 ((org-pos-in-match-range pos 6)
13247 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
13248 ((org-pos-in-match-range pos 5)
13249 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
13250
13251 ((org-pos-in-match-range pos 9)
13252 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
13253 ((org-pos-in-match-range pos 8)
13254 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
13255
13256 (when ng
13257 (setq s (concat
13258 (substring s 0 (match-beginning ng))
13259 new
13260 (substring s (match-end ng))))))
13261 s))
13262
13263 (defun org-recenter-calendar (date)
13264 "If the calendar is visible, recenter it to DATE."
13265 (let* ((win (selected-window))
13266 (cwin (get-buffer-window "*Calendar*" t))
13267 (calendar-move-hook nil))
13268 (when cwin
13269 (select-window cwin)
13270 (calendar-goto-date (if (listp date) date
13271 (calendar-gregorian-from-absolute date)))
13272 (select-window win))))
13273
13274 (defun org-goto-calendar (&optional arg)
13275 "Go to the Emacs calendar at the current date.
13276 If there is a time stamp in the current line, go to that date.
13277 A prefix ARG can be used to force the current date."
13278 (interactive "P")
13279 (let ((tsr org-ts-regexp) diff
13280 (calendar-move-hook nil)
13281 (calendar-view-holidays-initially-flag nil)
13282 (view-calendar-holidays-initially nil)
13283 (calendar-view-diary-initially-flag nil)
13284 (view-diary-entries-initially nil))
13285 (if (or (org-at-timestamp-p)
13286 (save-excursion
13287 (beginning-of-line 1)
13288 (looking-at (concat ".*" tsr))))
13289 (let ((d1 (time-to-days (current-time)))
13290 (d2 (time-to-days
13291 (org-time-string-to-time (match-string 1)))))
13292 (setq diff (- d2 d1))))
13293 (calendar)
13294 (calendar-goto-today)
13295 (if (and diff (not arg)) (calendar-forward-day diff))))
13296
13297 (defun org-get-date-from-calendar ()
13298 "Return a list (month day year) of date at point in calendar."
13299 (with-current-buffer "*Calendar*"
13300 (save-match-data
13301 (calendar-cursor-to-date))))
13302
13303 (defun org-date-from-calendar ()
13304 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
13305 If there is already a time stamp at the cursor position, update it."
13306 (interactive)
13307 (if (org-at-timestamp-p t)
13308 (org-timestamp-change 0 'calendar)
13309 (let ((cal-date (org-get-date-from-calendar)))
13310 (org-insert-time-stamp
13311 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
13312
13313 (defun org-minutes-to-hh:mm-string (m)
13314 "Compute H:MM from a number of minutes."
13315 (let ((h (/ m 60)))
13316 (setq m (- m (* 60 h)))
13317 (format org-time-clocksum-format h m)))
13318
13319 (defun org-hh:mm-string-to-minutes (s)
13320 "Convert a string H:MM to a number of minutes.
13321 If the string is just a number, interprete it as minutes.
13322 In fact, the first hh:mm or number in the string will be taken,
13323 there can be extra stuff in the string.
13324 If no number is found, the return value is 0."
13325 (cond
13326 ((string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
13327 (+ (* (string-to-number (match-string 1 s)) 60)
13328 (string-to-number (match-string 2 s))))
13329 ((string-match "\\([0-9]+\\)" s)
13330 (string-to-number (match-string 1 s)))
13331 (t 0)))
13332
13333 ;;;; Files
13334
13335 (defun org-save-all-org-buffers ()
13336 "Save all Org-mode buffers without user confirmation."
13337 (interactive)
13338 (message "Saving all Org-mode buffers...")
13339 (save-some-buffers t 'org-mode-p)
13340 (when (featurep 'org-id) (org-id-locations-save))
13341 (message "Saving all Org-mode buffers... done"))
13342
13343 (defun org-revert-all-org-buffers ()
13344 "Revert all Org-mode buffers.
13345 Prompt for confirmation when there are unsaved changes.
13346 Be sure you know what you are doing before letting this function
13347 overwrite your changes.
13348
13349 This function is useful in a setup where one tracks org files
13350 with a version control system, to revert on one machine after pulling
13351 changes from another. I believe the procedure must be like this:
13352
13353 1. M-x org-save-all-org-buffers
13354 2. Pull changes from the other machine, resolve conflicts
13355 3. M-x org-revert-all-org-buffers"
13356 (interactive)
13357 (unless (yes-or-no-p "Revert all Org buffers from their files? ")
13358 (error "Abort"))
13359 (save-excursion
13360 (save-window-excursion
13361 (mapc
13362 (lambda (b)
13363 (when (and (with-current-buffer b (org-mode-p))
13364 (with-current-buffer b buffer-file-name))
13365 (switch-to-buffer b)
13366 (revert-buffer t 'no-confirm)))
13367 (buffer-list))
13368 (when (and (featurep 'org-id) org-id-track-globally)
13369 (org-id-locations-load)))))
13370
13371 ;;;; Agenda files
13372
13373 ;;;###autoload
13374 (defun org-iswitchb (&optional arg)
13375 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
13376 With a prefix argument, restrict available to files.
13377 With two prefix arguments, restrict available buffers to agenda files.
13378
13379 Due to some yet unresolved reason, the global function
13380 `iswitchb-mode' needs to be active for this function to work."
13381 (interactive "P")
13382 (require 'iswitchb)
13383 (let ((enabled iswitchb-mode) blist)
13384 (or enabled (iswitchb-mode 1))
13385 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13386 ((equal arg '(16)) (org-buffer-list 'agenda))
13387 (t (org-buffer-list))))
13388 (unwind-protect
13389 (let ((iswitchb-make-buflist-hook
13390 (lambda ()
13391 (setq iswitchb-temp-buflist
13392 (mapcar 'buffer-name blist)))))
13393 (switch-to-buffer
13394 (iswitchb-read-buffer
13395 "Switch-to: " nil t))
13396 (or enabled (iswitchb-mode -1))))))
13397
13398 ;;;###autoload
13399 (defun org-ido-switchb (&optional arg)
13400 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
13401 With a prefix argument, restrict available to files.
13402 With two prefix arguments, restrict available buffers to agenda files."
13403 (interactive "P")
13404 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
13405 ((equal arg '(16)) (org-buffer-list 'agenda))
13406 (t (org-buffer-list)))))
13407 (switch-to-buffer
13408 (org-ido-completing-read "Org buffer: "
13409 (mapcar 'list (mapcar 'buffer-name blist))
13410 nil t))))
13411
13412 (defun org-buffer-list (&optional predicate exclude-tmp)
13413 "Return a list of Org buffers.
13414 PREDICATE can be `export', `files' or `agenda'.
13415
13416 export restrict the list to Export buffers.
13417 files restrict the list to buffers visiting Org files.
13418 agenda restrict the list to buffers visiting agenda files.
13419
13420 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
13421 (let* ((bfn nil)
13422 (agenda-files (and (eq predicate 'agenda)
13423 (mapcar 'file-truename (org-agenda-files t))))
13424 (filter
13425 (cond
13426 ((eq predicate 'files)
13427 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
13428 ((eq predicate 'export)
13429 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
13430 ((eq predicate 'agenda)
13431 (lambda (b)
13432 (with-current-buffer b
13433 (and (eq major-mode 'org-mode)
13434 (setq bfn (buffer-file-name b))
13435 (member (file-truename bfn) agenda-files)))))
13436 (t (lambda (b) (with-current-buffer b
13437 (or (eq major-mode 'org-mode)
13438 (string-match "\*Org .*Export"
13439 (buffer-name b)))))))))
13440 (delq nil
13441 (mapcar
13442 (lambda(b)
13443 (if (and (funcall filter b)
13444 (or (not exclude-tmp)
13445 (not (string-match "tmp" (buffer-name b)))))
13446 b
13447 nil))
13448 (buffer-list)))))
13449
13450 (defun org-agenda-files (&optional unrestricted archives)
13451 "Get the list of agenda files.
13452 Optional UNRESTRICTED means return the full list even if a restriction
13453 is currently in place.
13454 When ARCHIVES is t, include all archive files hat are really being
13455 used by the agenda files. If ARCHIVE is `ifmode', do this only if
13456 `org-agenda-archives-mode' is t."
13457 (let ((files
13458 (cond
13459 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
13460 ((stringp org-agenda-files) (org-read-agenda-file-list))
13461 ((listp org-agenda-files) org-agenda-files)
13462 (t (error "Invalid value of `org-agenda-files'")))))
13463 (setq files (apply 'append
13464 (mapcar (lambda (f)
13465 (if (file-directory-p f)
13466 (directory-files
13467 f t org-agenda-file-regexp)
13468 (list f)))
13469 files)))
13470 (when org-agenda-skip-unavailable-files
13471 (setq files (delq nil
13472 (mapcar (function
13473 (lambda (file)
13474 (and (file-readable-p file) file)))
13475 files))))
13476 (when (or (eq archives t)
13477 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
13478 (setq files (org-add-archive-files files)))
13479 files))
13480
13481 (defun org-edit-agenda-file-list ()
13482 "Edit the list of agenda files.
13483 Depending on setup, this either uses customize to edit the variable
13484 `org-agenda-files', or it visits the file that is holding the list. In the
13485 latter case, the buffer is set up in a way that saving it automatically kills
13486 the buffer and restores the previous window configuration."
13487 (interactive)
13488 (if (stringp org-agenda-files)
13489 (let ((cw (current-window-configuration)))
13490 (find-file org-agenda-files)
13491 (org-set-local 'org-window-configuration cw)
13492 (org-add-hook 'after-save-hook
13493 (lambda ()
13494 (set-window-configuration
13495 (prog1 org-window-configuration
13496 (kill-buffer (current-buffer))))
13497 (org-install-agenda-files-menu)
13498 (message "New agenda file list installed"))
13499 nil 'local)
13500 (message "%s" (substitute-command-keys
13501 "Edit list and finish with \\[save-buffer]")))
13502 (customize-variable 'org-agenda-files)))
13503
13504 (defun org-store-new-agenda-file-list (list)
13505 "Set new value for the agenda file list and save it correctly."
13506 (if (stringp org-agenda-files)
13507 (let ((f org-agenda-files) b)
13508 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
13509 (with-temp-file f
13510 (insert (mapconcat 'identity list "\n") "\n")))
13511 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
13512 (setq org-agenda-files list)
13513 (customize-save-variable 'org-agenda-files org-agenda-files))))
13514
13515 (defun org-read-agenda-file-list ()
13516 "Read the list of agenda files from a file."
13517 (when (file-directory-p org-agenda-files)
13518 (error "`org-agenda-files' cannot be a single directory"))
13519 (when (stringp org-agenda-files)
13520 (with-temp-buffer
13521 (insert-file-contents org-agenda-files)
13522 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
13523
13524
13525 ;;;###autoload
13526 (defun org-cycle-agenda-files ()
13527 "Cycle through the files in `org-agenda-files'.
13528 If the current buffer visits an agenda file, find the next one in the list.
13529 If the current buffer does not, find the first agenda file."
13530 (interactive)
13531 (let* ((fs (org-agenda-files t))
13532 (files (append fs (list (car fs))))
13533 (tcf (if buffer-file-name (file-truename buffer-file-name)))
13534 file)
13535 (unless files (error "No agenda files"))
13536 (catch 'exit
13537 (while (setq file (pop files))
13538 (if (equal (file-truename file) tcf)
13539 (when (car files)
13540 (find-file (car files))
13541 (throw 'exit t))))
13542 (find-file (car fs)))
13543 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
13544
13545 (defun org-agenda-file-to-front (&optional to-end)
13546 "Move/add the current file to the top of the agenda file list.
13547 If the file is not present in the list, it is added to the front. If it is
13548 present, it is moved there. With optional argument TO-END, add/move to the
13549 end of the list."
13550 (interactive "P")
13551 (let ((org-agenda-skip-unavailable-files nil)
13552 (file-alist (mapcar (lambda (x)
13553 (cons (file-truename x) x))
13554 (org-agenda-files t)))
13555 (ctf (file-truename buffer-file-name))
13556 x had)
13557 (setq x (assoc ctf file-alist) had x)
13558
13559 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
13560 (if to-end
13561 (setq file-alist (append (delq x file-alist) (list x)))
13562 (setq file-alist (cons x (delq x file-alist))))
13563 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
13564 (org-install-agenda-files-menu)
13565 (message "File %s to %s of agenda file list"
13566 (if had "moved" "added") (if to-end "end" "front"))))
13567
13568 (defun org-remove-file (&optional file)
13569 "Remove current file from the list of files in variable `org-agenda-files'.
13570 These are the files which are being checked for agenda entries.
13571 Optional argument FILE means, use this file instead of the current."
13572 (interactive)
13573 (let* ((org-agenda-skip-unavailable-files nil)
13574 (file (or file buffer-file-name))
13575 (true-file (file-truename file))
13576 (afile (abbreviate-file-name file))
13577 (files (delq nil (mapcar
13578 (lambda (x)
13579 (if (equal true-file
13580 (file-truename x))
13581 nil x))
13582 (org-agenda-files t)))))
13583 (if (not (= (length files) (length (org-agenda-files t))))
13584 (progn
13585 (org-store-new-agenda-file-list files)
13586 (org-install-agenda-files-menu)
13587 (message "Removed file: %s" afile))
13588 (message "File was not in list: %s (not removed)" afile))))
13589
13590 (defun org-file-menu-entry (file)
13591 (vector file (list 'find-file file) t))
13592
13593 (defun org-check-agenda-file (file)
13594 "Make sure FILE exists. If not, ask user what to do."
13595 (when (not (file-exists-p file))
13596 (message "non-existent file %s. [R]emove from list or [A]bort?"
13597 (abbreviate-file-name file))
13598 (let ((r (downcase (read-char-exclusive))))
13599 (cond
13600 ((equal r ?r)
13601 (org-remove-file file)
13602 (throw 'nextfile t))
13603 (t (error "Abort"))))))
13604
13605 (defun org-get-agenda-file-buffer (file)
13606 "Get a buffer visiting FILE. If the buffer needs to be created, add
13607 it to the list of buffers which might be released later."
13608 (let ((buf (org-find-base-buffer-visiting file)))
13609 (if buf
13610 buf ; just return it
13611 ;; Make a new buffer and remember it
13612 (setq buf (find-file-noselect file))
13613 (if buf (push buf org-agenda-new-buffers))
13614 buf)))
13615
13616 (defun org-release-buffers (blist)
13617 "Release all buffers in list, asking the user for confirmation when needed.
13618 When a buffer is unmodified, it is just killed. When modified, it is saved
13619 \(if the user agrees) and then killed."
13620 (let (buf file)
13621 (while (setq buf (pop blist))
13622 (setq file (buffer-file-name buf))
13623 (when (and (buffer-modified-p buf)
13624 file
13625 (y-or-n-p (format "Save file %s? " file)))
13626 (with-current-buffer buf (save-buffer)))
13627 (kill-buffer buf))))
13628
13629 (defun org-prepare-agenda-buffers (files)
13630 "Create buffers for all agenda files, protect archived trees and comments."
13631 (interactive)
13632 (let ((pa '(:org-archived t))
13633 (pc '(:org-comment t))
13634 (pall '(:org-archived t :org-comment t))
13635 (inhibit-read-only t)
13636 (rea (concat ":" org-archive-tag ":"))
13637 bmp file re)
13638 (save-excursion
13639 (save-restriction
13640 (while (setq file (pop files))
13641 (catch 'nextfile
13642 (if (bufferp file)
13643 (set-buffer file)
13644 (org-check-agenda-file file)
13645 (set-buffer (org-get-agenda-file-buffer file)))
13646 (widen)
13647 (setq bmp (buffer-modified-p))
13648 (org-refresh-category-properties)
13649 (setq org-todo-keywords-for-agenda
13650 (append org-todo-keywords-for-agenda org-todo-keywords-1))
13651 (setq org-done-keywords-for-agenda
13652 (append org-done-keywords-for-agenda org-done-keywords))
13653 (setq org-todo-keyword-alist-for-agenda
13654 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
13655 (setq org-tag-alist-for-agenda
13656 (append org-tag-alist-for-agenda org-tag-alist))
13657
13658 (save-excursion
13659 (remove-text-properties (point-min) (point-max) pall)
13660 (when org-agenda-skip-archived-trees
13661 (goto-char (point-min))
13662 (while (re-search-forward rea nil t)
13663 (if (org-on-heading-p t)
13664 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
13665 (goto-char (point-min))
13666 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
13667 (while (re-search-forward re nil t)
13668 (add-text-properties
13669 (match-beginning 0) (org-end-of-subtree t) pc)))
13670 (set-buffer-modified-p bmp)))))
13671 (setq org-todo-keyword-alist-for-agenda
13672 (org-uniquify org-todo-keyword-alist-for-agenda)
13673 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
13674
13675 ;;;; Embedded LaTeX
13676
13677 (defvar org-cdlatex-mode-map (make-sparse-keymap)
13678 "Keymap for the minor `org-cdlatex-mode'.")
13679
13680 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
13681 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
13682 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
13683 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
13684 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
13685
13686 (defvar org-cdlatex-texmathp-advice-is-done nil
13687 "Flag remembering if we have applied the advice to texmathp already.")
13688
13689 (define-minor-mode org-cdlatex-mode
13690 "Toggle the minor `org-cdlatex-mode'.
13691 This mode supports entering LaTeX environment and math in LaTeX fragments
13692 in Org-mode.
13693 \\{org-cdlatex-mode-map}"
13694 nil " OCDL" nil
13695 (when org-cdlatex-mode (require 'cdlatex))
13696 (unless org-cdlatex-texmathp-advice-is-done
13697 (setq org-cdlatex-texmathp-advice-is-done t)
13698 (defadvice texmathp (around org-math-always-on activate)
13699 "Always return t in org-mode buffers.
13700 This is because we want to insert math symbols without dollars even outside
13701 the LaTeX math segments. If Orgmode thinks that point is actually inside
13702 an embedded LaTeX fragment, let texmathp do its job.
13703 \\[org-cdlatex-mode-map]"
13704 (interactive)
13705 (let (p)
13706 (cond
13707 ((not (org-mode-p)) ad-do-it)
13708 ((eq this-command 'cdlatex-math-symbol)
13709 (setq ad-return-value t
13710 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
13711 (t
13712 (let ((p (org-inside-LaTeX-fragment-p)))
13713 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
13714 (setq ad-return-value t
13715 texmathp-why '("Org-mode embedded math" . 0))
13716 (if p ad-do-it)))))))))
13717
13718 (defun turn-on-org-cdlatex ()
13719 "Unconditionally turn on `org-cdlatex-mode'."
13720 (org-cdlatex-mode 1))
13721
13722 (defun org-inside-LaTeX-fragment-p ()
13723 "Test if point is inside a LaTeX fragment.
13724 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
13725 sequence appearing also before point.
13726 Even though the matchers for math are configurable, this function assumes
13727 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
13728 delimiters are skipped when they have been removed by customization.
13729 The return value is nil, or a cons cell with the delimiter and
13730 and the position of this delimiter.
13731
13732 This function does a reasonably good job, but can locally be fooled by
13733 for example currency specifications. For example it will assume being in
13734 inline math after \"$22.34\". The LaTeX fragment formatter will only format
13735 fragments that are properly closed, but during editing, we have to live
13736 with the uncertainty caused by missing closing delimiters. This function
13737 looks only before point, not after."
13738 (catch 'exit
13739 (let ((pos (point))
13740 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
13741 (lim (progn
13742 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
13743 (point)))
13744 dd-on str (start 0) m re)
13745 (goto-char pos)
13746 (when dodollar
13747 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
13748 re (nth 1 (assoc "$" org-latex-regexps)))
13749 (while (string-match re str start)
13750 (cond
13751 ((= (match-end 0) (length str))
13752 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
13753 ((= (match-end 0) (- (length str) 5))
13754 (throw 'exit nil))
13755 (t (setq start (match-end 0))))))
13756 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
13757 (goto-char pos)
13758 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
13759 (and (match-beginning 2) (throw 'exit nil))
13760 ;; count $$
13761 (while (re-search-backward "\\$\\$" lim t)
13762 (setq dd-on (not dd-on)))
13763 (goto-char pos)
13764 (if dd-on (cons "$$" m))))))
13765
13766
13767 (defun org-try-cdlatex-tab ()
13768 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
13769 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
13770 - inside a LaTeX fragment, or
13771 - after the first word in a line, where an abbreviation expansion could
13772 insert a LaTeX environment."
13773 (when org-cdlatex-mode
13774 (cond
13775 ((save-excursion
13776 (skip-chars-backward "a-zA-Z0-9*")
13777 (skip-chars-backward " \t")
13778 (bolp))
13779 (cdlatex-tab) t)
13780 ((org-inside-LaTeX-fragment-p)
13781 (cdlatex-tab) t)
13782 (t nil))))
13783
13784 (defun org-cdlatex-underscore-caret (&optional arg)
13785 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
13786 Revert to the normal definition outside of these fragments."
13787 (interactive "P")
13788 (if (org-inside-LaTeX-fragment-p)
13789 (call-interactively 'cdlatex-sub-superscript)
13790 (let (org-cdlatex-mode)
13791 (call-interactively (key-binding (vector last-input-event))))))
13792
13793 (defun org-cdlatex-math-modify (&optional arg)
13794 "Execute `cdlatex-math-modify' in LaTeX fragments.
13795 Revert to the normal definition outside of these fragments."
13796 (interactive "P")
13797 (if (org-inside-LaTeX-fragment-p)
13798 (call-interactively 'cdlatex-math-modify)
13799 (let (org-cdlatex-mode)
13800 (call-interactively (key-binding (vector last-input-event))))))
13801
13802 (defvar org-latex-fragment-image-overlays nil
13803 "List of overlays carrying the images of latex fragments.")
13804 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
13805
13806 (defun org-remove-latex-fragment-image-overlays ()
13807 "Remove all overlays with LaTeX fragment images in current buffer."
13808 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
13809 (setq org-latex-fragment-image-overlays nil))
13810
13811 (defun org-preview-latex-fragment (&optional subtree)
13812 "Preview the LaTeX fragment at point, or all locally or globally.
13813 If the cursor is in a LaTeX fragment, create the image and overlay
13814 it over the source code. If there is no fragment at point, display
13815 all fragments in the current text, from one headline to the next. With
13816 prefix SUBTREE, display all fragments in the current subtree. With a
13817 double prefix `C-u C-u', or when the cursor is before the first headline,
13818 display all fragments in the buffer.
13819 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
13820 (interactive "P")
13821 (org-remove-latex-fragment-image-overlays)
13822 (save-excursion
13823 (save-restriction
13824 (let (beg end at msg)
13825 (cond
13826 ((or (equal subtree '(16))
13827 (not (save-excursion
13828 (re-search-backward (concat "^" outline-regexp) nil t))))
13829 (setq beg (point-min) end (point-max)
13830 msg "Creating images for buffer...%s"))
13831 ((equal subtree '(4))
13832 (org-back-to-heading)
13833 (setq beg (point) end (org-end-of-subtree t)
13834 msg "Creating images for subtree...%s"))
13835 (t
13836 (if (setq at (org-inside-LaTeX-fragment-p))
13837 (goto-char (max (point-min) (- (cdr at) 2)))
13838 (org-back-to-heading))
13839 (setq beg (point) end (progn (outline-next-heading) (point))
13840 msg (if at "Creating image...%s"
13841 "Creating images for entry...%s"))))
13842 (message msg "")
13843 (narrow-to-region beg end)
13844 (goto-char beg)
13845 (org-format-latex
13846 (concat "ltxpng/" (file-name-sans-extension
13847 (file-name-nondirectory
13848 buffer-file-name)))
13849 default-directory 'overlays msg at 'forbuffer)
13850 (message msg "done. Use `C-c C-c' to remove images.")))))
13851
13852 (defvar org-latex-regexps
13853 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
13854 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
13855 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
13856 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13857 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
13858 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
13859 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
13860 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
13861 "Regular expressions for matching embedded LaTeX.")
13862
13863 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
13864 "Replace LaTeX fragments with links to an image, and produce images."
13865 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
13866 (let* ((prefixnodir (file-name-nondirectory prefix))
13867 (absprefix (expand-file-name prefix dir))
13868 (todir (file-name-directory absprefix))
13869 (opt org-format-latex-options)
13870 (matchers (plist-get opt :matchers))
13871 (re-list org-latex-regexps)
13872 (cnt 0) txt link beg end re e checkdir
13873 executables-checked
13874 m n block linkfile movefile ov)
13875 ;; Check if there are old images files with this prefix, and remove them
13876 (when (file-directory-p todir)
13877 (mapc 'delete-file
13878 (directory-files
13879 todir 'full
13880 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
13881 ;; Check the different regular expressions
13882 (while (setq e (pop re-list))
13883 (setq m (car e) re (nth 1 e) n (nth 2 e)
13884 block (if (nth 3 e) "\n\n" ""))
13885 (when (member m matchers)
13886 (goto-char (point-min))
13887 (while (re-search-forward re nil t)
13888 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
13889 (not (get-text-property (match-beginning n)
13890 'org-protected)))
13891 (setq txt (match-string n)
13892 beg (match-beginning n) end (match-end n)
13893 cnt (1+ cnt)
13894 linkfile (format "%s_%04d.png" prefix cnt)
13895 movefile (format "%s_%04d.png" absprefix cnt)
13896 link (concat block "[[file:" linkfile "]]" block))
13897 (if msg (message msg cnt))
13898 (goto-char beg)
13899 (unless checkdir ; make sure the directory exists
13900 (setq checkdir t)
13901 (or (file-directory-p todir) (make-directory todir)))
13902
13903 (unless executables-checked
13904 (org-check-external-command
13905 "latex" "needed to convert LaTeX fragments to images")
13906 (org-check-external-command
13907 "dvipng" "needed to convert LaTeX fragments to images")
13908 (setq executables-checked t))
13909
13910 (org-create-formula-image
13911 txt movefile opt forbuffer)
13912 (if overlays
13913 (progn
13914 (setq ov (org-make-overlay beg end))
13915 (if (featurep 'xemacs)
13916 (progn
13917 (org-overlay-put ov 'invisible t)
13918 (org-overlay-put
13919 ov 'end-glyph
13920 (make-glyph (vector 'png :file movefile))))
13921 (org-overlay-put
13922 ov 'display
13923 (list 'image :type 'png :file movefile :ascent 'center)))
13924 (push ov org-latex-fragment-image-overlays)
13925 (goto-char end))
13926 (delete-region beg end)
13927 (insert link))))))))
13928
13929 ;; This function borrows from Ganesh Swami's latex2png.el
13930 (defun org-create-formula-image (string tofile options buffer)
13931 (let* ((tmpdir (if (featurep 'xemacs)
13932 (temp-directory)
13933 temporary-file-directory))
13934 (texfilebase (make-temp-name
13935 (expand-file-name "orgtex" tmpdir)))
13936 (texfile (concat texfilebase ".tex"))
13937 (dvifile (concat texfilebase ".dvi"))
13938 (pngfile (concat texfilebase ".png"))
13939 (fnh (if (featurep 'xemacs)
13940 (font-height (get-face-font 'default))
13941 (face-attribute 'default :height nil)))
13942 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
13943 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
13944 (fg (or (plist-get options (if buffer :foreground :html-foreground))
13945 "Black"))
13946 (bg (or (plist-get options (if buffer :background :html-background))
13947 "Transparent")))
13948 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
13949 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
13950 (with-temp-file texfile
13951 (insert org-format-latex-header
13952 "\n\\begin{document}\n" string "\n\\end{document}\n"))
13953 (let ((dir default-directory))
13954 (condition-case nil
13955 (progn
13956 (cd tmpdir)
13957 (call-process "latex" nil nil nil texfile))
13958 (error nil))
13959 (cd dir))
13960 (if (not (file-exists-p dvifile))
13961 (progn (message "Failed to create dvi file from %s" texfile) nil)
13962 (condition-case nil
13963 (call-process "dvipng" nil nil nil
13964 "-fg" fg "-bg" bg
13965 "-D" dpi
13966 ;;"-x" scale "-y" scale
13967 "-T" "tight"
13968 "-o" pngfile
13969 dvifile)
13970 (error nil))
13971 (if (not (file-exists-p pngfile))
13972 (progn (message "Failed to create png file from %s" texfile) nil)
13973 ;; Use the requested file name and clean up
13974 (copy-file pngfile tofile 'replace)
13975 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
13976 (delete-file (concat texfilebase e)))
13977 pngfile))))
13978
13979 (defun org-dvipng-color (attr)
13980 "Return an rgb color specification for dvipng."
13981 (apply 'format "rgb %s %s %s"
13982 (mapcar 'org-normalize-color
13983 (color-values (face-attribute 'default attr nil)))))
13984
13985 (defun org-normalize-color (value)
13986 "Return string to be used as color value for an RGB component."
13987 (format "%g" (/ value 65535.0)))
13988
13989 ;;;; Key bindings
13990
13991 ;; Make `C-c C-x' a prefix key
13992 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
13993
13994 ;; TAB key with modifiers
13995 (org-defkey org-mode-map "\C-i" 'org-cycle)
13996 (org-defkey org-mode-map [(tab)] 'org-cycle)
13997 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
13998 (org-defkey org-mode-map [(meta tab)] 'org-complete)
13999 (org-defkey org-mode-map "\M-\t" 'org-complete)
14000 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
14001 ;; The following line is necessary under Suse GNU/Linux
14002 (unless (featurep 'xemacs)
14003 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
14004 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
14005 (define-key org-mode-map [backtab] 'org-shifttab)
14006
14007 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
14008 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
14009 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
14010
14011 ;; Cursor keys with modifiers
14012 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
14013 (org-defkey org-mode-map [(meta right)] 'org-metaright)
14014 (org-defkey org-mode-map [(meta up)] 'org-metaup)
14015 (org-defkey org-mode-map [(meta down)] 'org-metadown)
14016
14017 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
14018 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
14019 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
14020 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
14021
14022 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
14023 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
14024 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
14025 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
14026
14027 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
14028 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
14029
14030 ;;; Extra keys for tty access.
14031 ;; We only set them when really needed because otherwise the
14032 ;; menus don't show the simple keys
14033
14034 (when (or org-use-extra-keys
14035 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
14036 (not window-system))
14037 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
14038 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
14039 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
14040 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
14041 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
14042 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
14043 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
14044 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
14045 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
14046 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
14047 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
14048 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
14049 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
14050 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
14051 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
14052 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
14053 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
14054 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
14055 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
14056 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
14057 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
14058 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft)
14059 (org-defkey org-mode-map [?\e (tab)] 'org-complete)
14060 (org-defkey org-mode-map [?\e (shift return)] 'org-insert-todo-heading)
14061 (org-defkey org-mode-map [?\e (shift left)] 'org-shiftmetaleft)
14062 (org-defkey org-mode-map [?\e (shift right)] 'org-shiftmetaright)
14063 (org-defkey org-mode-map [?\e (shift up)] 'org-shiftmetaup)
14064 (org-defkey org-mode-map [?\e (shift down)] 'org-shiftmetadown))
14065
14066 ;; All the other keys
14067
14068 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
14069 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
14070 (if (boundp 'narrow-map)
14071 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
14072 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
14073 (org-defkey org-mode-map "\C-c\C-f" 'org-forward-same-level)
14074 (org-defkey org-mode-map "\C-c\C-b" 'org-backward-same-level)
14075 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
14076 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
14077 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
14078 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
14079 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
14080 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
14081 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
14082 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
14083 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
14084 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
14085 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
14086 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
14087 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
14088 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
14089 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
14090 (org-defkey org-mode-map "\C-c\\" 'org-match-sparse-tree) ; Minor-mode res.
14091 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
14092 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
14093 (org-defkey org-mode-map "\C-c\C-xc" 'org-clone-subtree-with-time-shift)
14094 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
14095 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
14096 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
14097 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
14098 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
14099 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
14100 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
14101 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
14102 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
14103 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
14104 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
14105 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
14106 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
14107 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
14108 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
14109 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
14110 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
14111 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
14112 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
14113 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
14114 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14115 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
14116 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
14117 (org-defkey org-mode-map "\C-c^" 'org-sort)
14118 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
14119 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
14120 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
14121 (org-defkey org-mode-map "\C-m" 'org-return)
14122 (org-defkey org-mode-map "\C-j" 'org-return-indent)
14123 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
14124 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
14125 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
14126 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
14127 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
14128 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
14129 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
14130 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
14131 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
14132 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
14133 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
14134 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
14135 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
14136 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
14137 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
14138 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
14139 (org-defkey org-mode-map [?\C-c (control ?*)] 'org-list-make-subtree)
14140 ;;(org-defkey org-mode-map [?\C-c (control ?-)] 'org-list-make-list-from-subtree)
14141
14142 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
14143 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
14144 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
14145 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
14146
14147 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
14148 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
14149 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
14150 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
14151 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
14152 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
14153 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
14154 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
14155 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
14156 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
14157 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
14158 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
14159 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
14160 (org-defkey org-mode-map [(control ?c) (control ?x) ?\;] 'org-timer-set-timer)
14161
14162 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
14163 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
14164 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
14165 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
14166
14167 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
14168
14169 (define-key org-mode-map "\C-c\C-x!" 'org-reload)
14170
14171 (define-key org-mode-map "\C-c\C-xg" 'org-feed-update-all)
14172 (define-key org-mode-map "\C-c\C-xG" 'org-feed-goto-inbox)
14173
14174 (define-key org-mode-map "\C-c\C-x[" 'org-reftex-citation)
14175
14176
14177 (when (featurep 'xemacs)
14178 (org-defkey org-mode-map 'button3 'popup-mode-menu))
14179
14180
14181 (defvar org-self-insert-command-undo-counter 0)
14182
14183 (defvar org-table-auto-blank-field) ; defined in org-table.el
14184 (defun org-self-insert-command (N)
14185 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
14186 If the cursor is in a table looking at whitespace, the whitespace is
14187 overwritten, and the table is not marked as requiring realignment."
14188 (interactive "p")
14189 (if (and
14190 (org-table-p)
14191 (progn
14192 ;; check if we blank the field, and if that triggers align
14193 (and (featurep 'org-table) org-table-auto-blank-field
14194 (member last-command
14195 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c yas/expand))
14196 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
14197 ;; got extra space, this field does not determine column width
14198 (let (org-table-may-need-update) (org-table-blank-field))
14199 ;; no extra space, this field may determine column width
14200 (org-table-blank-field)))
14201 t)
14202 (eq N 1)
14203 (looking-at "[^|\n]* |"))
14204 (let (org-table-may-need-update)
14205 (goto-char (1- (match-end 0)))
14206 (delete-backward-char 1)
14207 (goto-char (match-beginning 0))
14208 (self-insert-command N))
14209 (setq org-table-may-need-update t)
14210 (self-insert-command N)
14211 (org-fix-tags-on-the-fly)
14212 (if org-self-insert-cluster-for-undo
14213 (if (not (eq last-command 'org-self-insert-command))
14214 (setq org-self-insert-command-undo-counter 1)
14215 (if (>= org-self-insert-command-undo-counter 20)
14216 (setq org-self-insert-command-undo-counter 1)
14217 (and (> org-self-insert-command-undo-counter 0)
14218 buffer-undo-list
14219 (not (cadr buffer-undo-list)) ; remove nil entry
14220 (setcdr buffer-undo-list (cddr buffer-undo-list)))
14221 (setq org-self-insert-command-undo-counter
14222 (1+ org-self-insert-command-undo-counter)))))))
14223
14224 (defun org-fix-tags-on-the-fly ()
14225 (when (and (equal (char-after (point-at-bol)) ?*)
14226 (org-on-heading-p))
14227 (org-align-tags-here org-tags-column)))
14228
14229 (defun org-delete-backward-char (N)
14230 "Like `delete-backward-char', insert whitespace at field end in tables.
14231 When deleting backwards, in tables this function will insert whitespace in
14232 front of the next \"|\" separator, to keep the table aligned. The table will
14233 still be marked for re-alignment if the field did fill the entire column,
14234 because, in this case the deletion might narrow the column."
14235 (interactive "p")
14236 (if (and (org-table-p)
14237 (eq N 1)
14238 (string-match "|" (buffer-substring (point-at-bol) (point)))
14239 (looking-at ".*?|"))
14240 (let ((pos (point))
14241 (noalign (looking-at "[^|\n\r]* |"))
14242 (c org-table-may-need-update))
14243 (backward-delete-char N)
14244 (skip-chars-forward "^|")
14245 (insert " ")
14246 (goto-char (1- pos))
14247 ;; noalign: if there were two spaces at the end, this field
14248 ;; does not determine the width of the column.
14249 (if noalign (setq org-table-may-need-update c)))
14250 (backward-delete-char N)
14251 (org-fix-tags-on-the-fly)))
14252
14253 (defun org-delete-char (N)
14254 "Like `delete-char', but insert whitespace at field end in tables.
14255 When deleting characters, in tables this function will insert whitespace in
14256 front of the next \"|\" separator, to keep the table aligned. The table will
14257 still be marked for re-alignment if the field did fill the entire column,
14258 because, in this case the deletion might narrow the column."
14259 (interactive "p")
14260 (if (and (org-table-p)
14261 (not (bolp))
14262 (not (= (char-after) ?|))
14263 (eq N 1))
14264 (if (looking-at ".*?|")
14265 (let ((pos (point))
14266 (noalign (looking-at "[^|\n\r]* |"))
14267 (c org-table-may-need-update))
14268 (replace-match (concat
14269 (substring (match-string 0) 1 -1)
14270 " |"))
14271 (goto-char pos)
14272 ;; noalign: if there were two spaces at the end, this field
14273 ;; does not determine the width of the column.
14274 (if noalign (setq org-table-may-need-update c)))
14275 (delete-char N))
14276 (delete-char N)
14277 (org-fix-tags-on-the-fly)))
14278
14279 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
14280 (put 'org-self-insert-command 'delete-selection t)
14281 (put 'orgtbl-self-insert-command 'delete-selection t)
14282 (put 'org-delete-char 'delete-selection 'supersede)
14283 (put 'org-delete-backward-char 'delete-selection 'supersede)
14284 (put 'org-yank 'delete-selection 'yank)
14285
14286 ;; Make `flyspell-mode' delay after some commands
14287 (put 'org-self-insert-command 'flyspell-delayed t)
14288 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
14289 (put 'org-delete-char 'flyspell-delayed t)
14290 (put 'org-delete-backward-char 'flyspell-delayed t)
14291
14292 ;; Make pabbrev-mode expand after org-mode commands
14293 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
14294 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
14295
14296 ;; How to do this: Measure non-white length of current string
14297 ;; If equal to column width, we should realign.
14298
14299 (defun org-remap (map &rest commands)
14300 "In MAP, remap the functions given in COMMANDS.
14301 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
14302 (let (new old)
14303 (while commands
14304 (setq old (pop commands) new (pop commands))
14305 (if (fboundp 'command-remapping)
14306 (org-defkey map (vector 'remap old) new)
14307 (substitute-key-definition old new map global-map)))))
14308
14309 (when (eq org-enable-table-editor 'optimized)
14310 ;; If the user wants maximum table support, we need to hijack
14311 ;; some standard editing functions
14312 (org-remap org-mode-map
14313 'self-insert-command 'org-self-insert-command
14314 'delete-char 'org-delete-char
14315 'delete-backward-char 'org-delete-backward-char)
14316 (org-defkey org-mode-map "|" 'org-force-self-insert))
14317
14318 (defvar org-ctrl-c-ctrl-c-hook nil
14319 "Hook for functions attaching themselves to `C-c C-c'.
14320 This can be used to add additional functionality to the C-c C-c key which
14321 executes context-dependent commands.
14322 Each function will be called with no arguments. The function must check
14323 if the context is appropriate for it to act. If yes, it should do its
14324 thing and then return a non-nil value. If the context is wrong,
14325 just do nothing and return nil.")
14326
14327 (defvar org-tab-first-hook nil
14328 "Hook for functions to attach themselves to TAB.
14329 See `org-ctrl-c-ctrl-c-hook' for more information.
14330 This hook runs as the first action when TAB is pressed, even before
14331 `org-cycle' messes around with the `outline-regexp' to cater for
14332 inline tasks and plain list item folding.
14333 If any function in this hook returns t, not other actions like table
14334 field motion visibility cycling will be done.")
14335
14336 (defvar org-tab-after-check-for-table-hook nil
14337 "Hook for functions to attach themselves to TAB.
14338 See `org-ctrl-c-ctrl-c-hook' for more information.
14339 This hook runs after it has been established that the cursor is not in a
14340 table, but before checking if the cursor is in a headline or if global cycling
14341 should be done.
14342 If any function in this hook returns t, not other actions like visibility
14343 cycling will be done.")
14344
14345 (defvar org-tab-after-check-for-cycling-hook nil
14346 "Hook for functions to attach themselves to TAB.
14347 See `org-ctrl-c-ctrl-c-hook' for more information.
14348 This hook runs after it has been established that not table field motion and
14349 not visibility should be done because of current context. This is probably
14350 the place where a package like yasnippets can hook in.")
14351
14352 (defvar org-metaleft-hook nil
14353 "Hook for functions attaching themselves to `M-left'.
14354 See `org-ctrl-c-ctrl-c-hook' for more information.")
14355 (defvar org-metaright-hook nil
14356 "Hook for functions attaching themselves to `M-right'.
14357 See `org-ctrl-c-ctrl-c-hook' for more information.")
14358 (defvar org-metaup-hook nil
14359 "Hook for functions attaching themselves to `M-up'.
14360 See `org-ctrl-c-ctrl-c-hook' for more information.")
14361 (defvar org-metadown-hook nil
14362 "Hook for functions attaching themselves to `M-down'.
14363 See `org-ctrl-c-ctrl-c-hook' for more information.")
14364 (defvar org-shiftmetaleft-hook nil
14365 "Hook for functions attaching themselves to `M-S-left'.
14366 See `org-ctrl-c-ctrl-c-hook' for more information.")
14367 (defvar org-shiftmetaright-hook nil
14368 "Hook for functions attaching themselves to `M-S-right'.
14369 See `org-ctrl-c-ctrl-c-hook' for more information.")
14370 (defvar org-shiftmetaup-hook nil
14371 "Hook for functions attaching themselves to `M-S-up'.
14372 See `org-ctrl-c-ctrl-c-hook' for more information.")
14373 (defvar org-shiftmetadown-hook nil
14374 "Hook for functions attaching themselves to `M-S-down'.
14375 See `org-ctrl-c-ctrl-c-hook' for more information.")
14376 (defvar org-metareturn-hook nil
14377 "Hook for functions attaching themselves to `M-RET'.
14378 See `org-ctrl-c-ctrl-c-hook' for more information.")
14379
14380 (defun org-modifier-cursor-error ()
14381 "Throw an error, a modified cursor command was applied in wrong context."
14382 (error "This command is active in special context like tables, headlines or items"))
14383
14384 (defun org-shiftselect-error ()
14385 "Throw an error because Shift-Cursor command was applied in wrong context."
14386 (if (and (boundp 'shift-select-mode) shift-select-mode)
14387 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
14388 (error "This command works only in special context like headlines or timestamps.")))
14389
14390 (defun org-call-for-shift-select (cmd)
14391 (let ((this-command-keys-shift-translated t))
14392 (call-interactively cmd)))
14393
14394 (defun org-shifttab (&optional arg)
14395 "Global visibility cycling or move to previous table field.
14396 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
14397 on context.
14398 See the individual commands for more information."
14399 (interactive "P")
14400 (cond
14401 ((org-at-table-p) (call-interactively 'org-table-previous-field))
14402 ((integerp arg)
14403 (message "Content view to level: %d" arg)
14404 (org-content (prefix-numeric-value arg))
14405 (setq org-cycle-global-status 'overview))
14406 (t (call-interactively 'org-global-cycle))))
14407
14408 (defun org-shiftmetaleft ()
14409 "Promote subtree or delete table column.
14410 Calls `org-promote-subtree', `org-outdent-item',
14411 or `org-table-delete-column', depending on context.
14412 See the individual commands for more information."
14413 (interactive)
14414 (cond
14415 ((run-hook-with-args-until-success 'org-shiftmetaleft-hook))
14416 ((org-at-table-p) (call-interactively 'org-table-delete-column))
14417 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
14418 ((org-at-item-p) (call-interactively 'org-outdent-item))
14419 (t (org-modifier-cursor-error))))
14420
14421 (defun org-shiftmetaright ()
14422 "Demote subtree or insert table column.
14423 Calls `org-demote-subtree', `org-indent-item',
14424 or `org-table-insert-column', depending on context.
14425 See the individual commands for more information."
14426 (interactive)
14427 (cond
14428 ((run-hook-with-args-until-success 'org-shiftmetaright-hook))
14429 ((org-at-table-p) (call-interactively 'org-table-insert-column))
14430 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
14431 ((org-at-item-p) (call-interactively 'org-indent-item))
14432 (t (org-modifier-cursor-error))))
14433
14434 (defun org-shiftmetaup (&optional arg)
14435 "Move subtree up or kill table row.
14436 Calls `org-move-subtree-up' or `org-table-kill-row' or
14437 `org-move-item-up' depending on context. See the individual commands
14438 for more information."
14439 (interactive "P")
14440 (cond
14441 ((run-hook-with-args-until-success 'org-shiftmetaup-hook))
14442 ((org-at-table-p) (call-interactively 'org-table-kill-row))
14443 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14444 ((org-at-item-p) (call-interactively 'org-move-item-up))
14445 (t (org-modifier-cursor-error))))
14446
14447 (defun org-shiftmetadown (&optional arg)
14448 "Move subtree down or insert table row.
14449 Calls `org-move-subtree-down' or `org-table-insert-row' or
14450 `org-move-item-down', depending on context. See the individual
14451 commands for more information."
14452 (interactive "P")
14453 (cond
14454 ((run-hook-with-args-until-success 'org-shiftmetadown-hook))
14455 ((org-at-table-p) (call-interactively 'org-table-insert-row))
14456 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14457 ((org-at-item-p) (call-interactively 'org-move-item-down))
14458 (t (org-modifier-cursor-error))))
14459
14460 (defun org-metaleft (&optional arg)
14461 "Promote heading or move table column to left.
14462 Calls `org-do-promote' or `org-table-move-column', depending on context.
14463 With no specific context, calls the Emacs default `backward-word'.
14464 See the individual commands for more information."
14465 (interactive "P")
14466 (cond
14467 ((run-hook-with-args-until-success 'org-metaleft-hook))
14468 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
14469 ((or (org-on-heading-p)
14470 (and (org-region-active-p)
14471 (save-excursion
14472 (goto-char (region-beginning))
14473 (org-on-heading-p))))
14474 (call-interactively 'org-do-promote))
14475 ((or (org-at-item-p)
14476 (and (org-region-active-p)
14477 (save-excursion
14478 (goto-char (region-beginning))
14479 (org-at-item-p))))
14480 (call-interactively 'org-outdent-item))
14481 (t (call-interactively 'backward-word))))
14482
14483 (defun org-metaright (&optional arg)
14484 "Demote subtree or move table column to right.
14485 Calls `org-do-demote' or `org-table-move-column', depending on context.
14486 With no specific context, calls the Emacs default `forward-word'.
14487 See the individual commands for more information."
14488 (interactive "P")
14489 (cond
14490 ((run-hook-with-args-until-success 'org-metaright-hook))
14491 ((org-at-table-p) (call-interactively 'org-table-move-column))
14492 ((or (org-on-heading-p)
14493 (and (org-region-active-p)
14494 (save-excursion
14495 (goto-char (region-beginning))
14496 (org-on-heading-p))))
14497 (call-interactively 'org-do-demote))
14498 ((or (org-at-item-p)
14499 (and (org-region-active-p)
14500 (save-excursion
14501 (goto-char (region-beginning))
14502 (org-at-item-p))))
14503 (call-interactively 'org-indent-item))
14504 (t (call-interactively 'forward-word))))
14505
14506 (defun org-metaup (&optional arg)
14507 "Move subtree up or move table row up.
14508 Calls `org-move-subtree-up' or `org-table-move-row' or
14509 `org-move-item-up', depending on context. See the individual commands
14510 for more information."
14511 (interactive "P")
14512 (cond
14513 ((run-hook-with-args-until-success 'org-metaup-hook))
14514 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
14515 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
14516 ((org-at-item-p) (call-interactively 'org-move-item-up))
14517 (t (transpose-lines 1) (beginning-of-line -1))))
14518
14519 (defun org-metadown (&optional arg)
14520 "Move subtree down or move table row down.
14521 Calls `org-move-subtree-down' or `org-table-move-row' or
14522 `org-move-item-down', depending on context. See the individual
14523 commands for more information."
14524 (interactive "P")
14525 (cond
14526 ((run-hook-with-args-until-success 'org-metadown-hook))
14527 ((org-at-table-p) (call-interactively 'org-table-move-row))
14528 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
14529 ((org-at-item-p) (call-interactively 'org-move-item-down))
14530 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
14531
14532 (defun org-shiftup (&optional arg)
14533 "Increase item in timestamp or increase priority of current headline.
14534 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
14535 depending on context. See the individual commands for more information."
14536 (interactive "P")
14537 (cond
14538 ((and org-support-shift-select (org-region-active-p))
14539 (org-call-for-shift-select 'previous-line))
14540 ((org-at-timestamp-p t)
14541 (call-interactively (if org-edit-timestamp-down-means-later
14542 'org-timestamp-down 'org-timestamp-up)))
14543 ((and (not (eq org-support-shift-select 'always))
14544 org-enable-priority-commands
14545 (org-on-heading-p))
14546 (call-interactively 'org-priority-up))
14547 ((and (not org-support-shift-select) (org-at-item-p))
14548 (call-interactively 'org-previous-item))
14549 ((org-clocktable-try-shift 'up arg))
14550 (org-support-shift-select
14551 (org-call-for-shift-select 'previous-line))
14552 (t (org-shiftselect-error))))
14553
14554 (defun org-shiftdown (&optional arg)
14555 "Decrease item in timestamp or decrease priority of current headline.
14556 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
14557 depending on context. See the individual commands for more information."
14558 (interactive "P")
14559 (cond
14560 ((and org-support-shift-select (org-region-active-p))
14561 (org-call-for-shift-select 'next-line))
14562 ((org-at-timestamp-p t)
14563 (call-interactively (if org-edit-timestamp-down-means-later
14564 'org-timestamp-up 'org-timestamp-down)))
14565 ((and (not (eq org-support-shift-select 'always))
14566 org-enable-priority-commands
14567 (org-on-heading-p))
14568 (call-interactively 'org-priority-down))
14569 ((and (not org-support-shift-select) (org-at-item-p))
14570 (call-interactively 'org-next-item))
14571 ((org-clocktable-try-shift 'down arg))
14572 (org-support-shift-select
14573 (org-call-for-shift-select 'next-line))
14574 (t (org-shiftselect-error))))
14575
14576 (defun org-shiftright (&optional arg)
14577 "Cycle the thing at point or in the current line, depending on context.
14578 Depending on context, this does one of the following:
14579
14580 - switch a timestamp at point one day into the future
14581 - on a headline, switch to the next TODO keyword.
14582 - on an item, switch entire list to the next bullet type
14583 - on a property line, switch to the next allowed value
14584 - on a clocktable definition line, move time block into the future"
14585 (interactive "P")
14586 (cond
14587 ((and org-support-shift-select (org-region-active-p))
14588 (org-call-for-shift-select 'forward-char))
14589 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
14590 ((and (not (eq org-support-shift-select 'always))
14591 (org-on-heading-p))
14592 (let ((org-inhibit-logging
14593 (not org-treat-S-cursor-todo-selection-as-state-change))
14594 (org-inhibit-blocking
14595 (not org-treat-S-cursor-todo-selection-as-state-change)))
14596 (org-call-with-arg 'org-todo 'right)))
14597 ((or (and org-support-shift-select
14598 (not (eq org-support-shift-select 'always))
14599 (org-at-item-bullet-p))
14600 (and (not org-support-shift-select) (org-at-item-p)))
14601 (org-call-with-arg 'org-cycle-list-bullet nil))
14602 ((and (not (eq org-support-shift-select 'always))
14603 (org-at-property-p))
14604 (call-interactively 'org-property-next-allowed-value))
14605 ((org-clocktable-try-shift 'right arg))
14606 (org-support-shift-select
14607 (org-call-for-shift-select 'forward-char))
14608 (t (org-shiftselect-error))))
14609
14610 (defun org-shiftleft (&optional arg)
14611 "Cycle the thing at point or in the current line, depending on context.
14612 Depending on context, this does one of the following:
14613
14614 - switch a timestamp at point one day into the past
14615 - on a headline, switch to the previous TODO keyword.
14616 - on an item, switch entire list to the previous bullet type
14617 - on a property line, switch to the previous allowed value
14618 - on a clocktable definition line, move time block into the past"
14619 (interactive "P")
14620 (cond
14621 ((and org-support-shift-select (org-region-active-p))
14622 (org-call-for-shift-select 'backward-char))
14623 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
14624 ((and (not (eq org-support-shift-select 'always))
14625 (org-on-heading-p))
14626 (let ((org-inhibit-logging
14627 (not org-treat-S-cursor-todo-selection-as-state-change))
14628 (org-inhibit-blocking
14629 (not org-treat-S-cursor-todo-selection-as-state-change)))
14630 (org-call-with-arg 'org-todo 'left)))
14631 ((or (and org-support-shift-select
14632 (not (eq org-support-shift-select 'always))
14633 (org-at-item-bullet-p))
14634 (and (not org-support-shift-select) (org-at-item-p)))
14635 (org-call-with-arg 'org-cycle-list-bullet 'previous))
14636 ((and (not (eq org-support-shift-select 'always))
14637 (org-at-property-p))
14638 (call-interactively 'org-property-previous-allowed-value))
14639 ((org-clocktable-try-shift 'left arg))
14640 (org-support-shift-select
14641 (org-call-for-shift-select 'backward-char))
14642 (t (org-shiftselect-error))))
14643
14644 (defun org-shiftcontrolright ()
14645 "Switch to next TODO set."
14646 (interactive)
14647 (cond
14648 ((and org-support-shift-select (org-region-active-p))
14649 (org-call-for-shift-select 'forward-word))
14650 ((and (not (eq org-support-shift-select 'always))
14651 (org-on-heading-p))
14652 (org-call-with-arg 'org-todo 'nextset))
14653 (org-support-shift-select
14654 (org-call-for-shift-select 'forward-word))
14655 (t (org-shiftselect-error))))
14656
14657 (defun org-shiftcontrolleft ()
14658 "Switch to previous TODO set."
14659 (interactive)
14660 (cond
14661 ((and org-support-shift-select (org-region-active-p))
14662 (org-call-for-shift-select 'backward-word))
14663 ((and (not (eq org-support-shift-select 'always))
14664 (org-on-heading-p))
14665 (org-call-with-arg 'org-todo 'previousset))
14666 (org-support-shift-select
14667 (org-call-for-shift-select 'backward-word))
14668 (t (org-shiftselect-error))))
14669
14670 (defun org-ctrl-c-ret ()
14671 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
14672 (interactive)
14673 (cond
14674 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
14675 (t (call-interactively 'org-insert-heading))))
14676
14677 (defun org-copy-special ()
14678 "Copy region in table or copy current subtree.
14679 Calls `org-table-copy' or `org-copy-subtree', depending on context.
14680 See the individual commands for more information."
14681 (interactive)
14682 (call-interactively
14683 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
14684
14685 (defun org-cut-special ()
14686 "Cut region in table or cut current subtree.
14687 Calls `org-table-copy' or `org-cut-subtree', depending on context.
14688 See the individual commands for more information."
14689 (interactive)
14690 (call-interactively
14691 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
14692
14693 (defun org-paste-special (arg)
14694 "Paste rectangular region into table, or past subtree relative to level.
14695 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
14696 See the individual commands for more information."
14697 (interactive "P")
14698 (if (org-at-table-p)
14699 (org-table-paste-rectangle)
14700 (org-paste-subtree arg)))
14701
14702 (defun org-edit-special ()
14703 "Call a special editor for the stuff at point.
14704 When at a table, call the formula editor with `org-table-edit-formulas'.
14705 When at the first line of an src example, call `org-edit-src-code'.
14706 When in an #+include line, visit the include file. Otherwise call
14707 `ffap' to visit the file at point."
14708 (interactive)
14709 (cond
14710 ((org-at-table-p)
14711 (call-interactively 'org-table-edit-formulas))
14712 ((save-excursion
14713 (beginning-of-line 1)
14714 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
14715 (find-file (org-trim (match-string 1))))
14716 ((org-edit-src-code))
14717 ((org-edit-fixed-width-region))
14718 (t (call-interactively 'ffap))))
14719
14720
14721 (defun org-ctrl-c-ctrl-c (&optional arg)
14722 "Set tags in headline, or update according to changed information at point.
14723
14724 This command does many different things, depending on context:
14725
14726 - If a function in `org-ctrl-c-ctrl-c-hook' recognizes this location,
14727 this is what we do.
14728
14729 - If the cursor is in a headline, prompt for tags and insert them
14730 into the current line, aligned to `org-tags-column'. When called
14731 with prefix arg, realign all tags in the current buffer.
14732
14733 - If the cursor is in one of the special #+KEYWORD lines, this
14734 triggers scanning the buffer for these lines and updating the
14735 information.
14736
14737 - If the cursor is inside a table, realign the table. This command
14738 works even if the automatic table editor has been turned off.
14739
14740 - If the cursor is on a #+TBLFM line, re-apply the formulas to
14741 the entire table.
14742
14743 - If the cursor is at a footnote reference or definition, jump to
14744 the corresponding definition or references, respectively.
14745
14746 - If the cursor is a the beginning of a dynamic block, update it.
14747
14748 - If the cursor is inside a table created by the table.el package,
14749 activate that table.
14750
14751 - If the current buffer is a remember buffer, close note and file
14752 it. A prefix argument of 1 files to the default location
14753 without further interaction. A prefix argument of 2 files to
14754 the currently clocking task.
14755
14756 - If the cursor is on a <<<target>>>, update radio targets and corresponding
14757 links in this buffer.
14758
14759 - If the cursor is on a numbered item in a plain list, renumber the
14760 ordered list.
14761
14762 - If the cursor is on a checkbox, toggle it."
14763 (interactive "P")
14764 (let ((org-enable-table-editor t))
14765 (cond
14766 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
14767 org-occur-highlights
14768 org-latex-fragment-image-overlays)
14769 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
14770 (org-remove-occur-highlights)
14771 (org-remove-latex-fragment-image-overlays)
14772 (message "Temporary highlights/overlays removed from current buffer"))
14773 ((and (local-variable-p 'org-finish-function (current-buffer))
14774 (fboundp org-finish-function))
14775 (funcall org-finish-function))
14776 ((run-hook-with-args-until-success 'org-ctrl-c-ctrl-c-hook))
14777 ((org-at-property-p)
14778 (call-interactively 'org-property-action))
14779 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
14780 ((org-on-heading-p) (call-interactively 'org-set-tags))
14781 ((org-at-table.el-p)
14782 (require 'table)
14783 (beginning-of-line 1)
14784 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
14785 (call-interactively 'table-recognize-table))
14786 ((org-at-table-p)
14787 (org-table-maybe-eval-formula)
14788 (if arg
14789 (call-interactively 'org-table-recalculate)
14790 (org-table-maybe-recalculate-line))
14791 (call-interactively 'org-table-align))
14792 ((or (org-footnote-at-reference-p)
14793 (org-footnote-at-definition-p))
14794 (call-interactively 'org-footnote-action))
14795 ((org-at-item-checkbox-p)
14796 (call-interactively 'org-toggle-checkbox))
14797 ((org-at-item-p)
14798 (if arg
14799 (call-interactively 'org-toggle-checkbox)
14800 (call-interactively 'org-maybe-renumber-ordered-list)))
14801 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
14802 ;; Dynamic block
14803 (beginning-of-line 1)
14804 (save-excursion (org-update-dblock)))
14805 ((save-excursion
14806 (beginning-of-line 1)
14807 (looking-at "[ \t]*#\\+\\([A-Z]+\\)"))
14808 (cond
14809 ((equal (match-string 1) "TBLFM")
14810 ;; Recalculate the table before this line
14811 (save-excursion
14812 (beginning-of-line 1)
14813 (skip-chars-backward " \r\n\t")
14814 (if (org-at-table-p)
14815 (org-call-with-arg 'org-table-recalculate t))))
14816 (t
14817 ; (org-set-regexps-and-options)
14818 ; (org-restart-font-lock)
14819 (let ((org-inhibit-startup t)) (org-mode-restart))
14820 (message "Local setup has been refreshed"))))
14821 ((org-clock-update-time-maybe))
14822 (t (error "C-c C-c can do nothing useful at this location.")))))
14823
14824 (defun org-mode-restart ()
14825 "Restart Org-mode, to scan again for special lines.
14826 Also updates the keyword regular expressions."
14827 (interactive)
14828 (org-mode)
14829 (message "Org-mode restarted"))
14830
14831 (defun org-kill-note-or-show-branches ()
14832 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
14833 (interactive)
14834 (if (not org-finish-function)
14835 (call-interactively 'show-branches)
14836 (let ((org-note-abort t))
14837 (funcall org-finish-function))))
14838
14839 (defun org-return (&optional indent)
14840 "Goto next table row or insert a newline.
14841 Calls `org-table-next-row' or `newline', depending on context.
14842 See the individual commands for more information."
14843 (interactive)
14844 (cond
14845 ((bobp) (if indent (newline-and-indent) (newline)))
14846 ((org-at-table-p)
14847 (org-table-justify-field-maybe)
14848 (call-interactively 'org-table-next-row))
14849 ((and org-return-follows-link
14850 (eq (get-text-property (point) 'face) 'org-link))
14851 (call-interactively 'org-open-at-point))
14852 ((and (org-at-heading-p)
14853 (looking-at
14854 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
14855 (org-show-entry)
14856 (end-of-line 1)
14857 (newline))
14858 (t (if indent (newline-and-indent) (newline)))))
14859
14860 (defun org-return-indent ()
14861 "Goto next table row or insert a newline and indent.
14862 Calls `org-table-next-row' or `newline-and-indent', depending on
14863 context. See the individual commands for more information."
14864 (interactive)
14865 (org-return t))
14866
14867 (defun org-ctrl-c-star ()
14868 "Compute table, or change heading status of lines.
14869 Calls `org-table-recalculate' or `org-toggle-heading',
14870 depending on context."
14871 (interactive)
14872 (cond
14873 ((org-at-table-p)
14874 (call-interactively 'org-table-recalculate))
14875 (t
14876 ;; Convert all lines in region to list items
14877 (call-interactively 'org-toggle-heading))))
14878
14879 (defun org-ctrl-c-minus ()
14880 "Insert separator line in table or modify bullet status of line.
14881 Also turns a plain line or a region of lines into list items.
14882 Calls `org-table-insert-hline', `org-toggle-item', or
14883 `org-cycle-list-bullet', depending on context."
14884 (interactive)
14885 (cond
14886 ((org-at-table-p)
14887 (call-interactively 'org-table-insert-hline))
14888 ((org-region-active-p)
14889 (call-interactively 'org-toggle-item))
14890 ((org-in-item-p)
14891 (call-interactively 'org-cycle-list-bullet))
14892 (t
14893 (call-interactively 'org-toggle-item))))
14894
14895 (defun org-toggle-item ()
14896 "Convert headings or normal lines to items, items to normal lines.
14897 If there is no active region, only the current line is considered.
14898
14899 If the first line in the region is a headline, convert all headlines to items.
14900
14901 If the first line in the region is an item, convert all items to normal lines.
14902
14903 If the first line is normal text, add an item bullet to each line."
14904 (interactive)
14905 (let (l2 l beg end)
14906 (if (org-region-active-p)
14907 (setq beg (region-beginning) end (region-end))
14908 (setq beg (point-at-bol)
14909 end (min (1+ (point-at-eol)) (point-max))))
14910 (save-excursion
14911 (goto-char end)
14912 (setq l2 (org-current-line))
14913 (goto-char beg)
14914 (beginning-of-line 1)
14915 (setq l (1- (org-current-line)))
14916 (if (org-at-item-p)
14917 ;; We already have items, de-itemize
14918 (while (< (setq l (1+ l)) l2)
14919 (when (org-at-item-p)
14920 (goto-char (match-beginning 2))
14921 (delete-region (match-beginning 2) (match-end 2))
14922 (and (looking-at "[ \t]+") (replace-match "")))
14923 (beginning-of-line 2))
14924 (if (org-on-heading-p)
14925 ;; Headings, convert to items
14926 (while (< (setq l (1+ l)) l2)
14927 (if (looking-at org-outline-regexp)
14928 (replace-match "- " t t))
14929 (beginning-of-line 2))
14930 ;; normal lines, turn them into items
14931 (while (< (setq l (1+ l)) l2)
14932 (unless (org-at-item-p)
14933 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14934 (replace-match "\\1- \\2")))
14935 (beginning-of-line 2)))))))
14936
14937 (defun org-toggle-heading (&optional nstars)
14938 "Convert headings to normal text, or items or text to headings.
14939 If there is no active region, only the current line is considered.
14940
14941 If the first line is a heading, remove the stars from all headlines
14942 in the region.
14943
14944 If the first line is a plain list item, turn all plain list items
14945 into headings.
14946
14947 If the first line is a normal line, turn each and every line in the
14948 region into a heading.
14949
14950 When converting a line into a heading, the number of stars is chosen
14951 such that the lines become children of the current entry. However,
14952 when a prefix argument is given, its value determines the number of
14953 stars to add."
14954 (interactive "P")
14955 (let (l2 l itemp beg end)
14956 (if (org-region-active-p)
14957 (setq beg (region-beginning) end (region-end))
14958 (setq beg (point-at-bol)
14959 end (min (1+ (point-at-eol)) (point-max))))
14960 (save-excursion
14961 (goto-char end)
14962 (setq l2 (org-current-line))
14963 (goto-char beg)
14964 (beginning-of-line 1)
14965 (setq l (1- (org-current-line)))
14966 (if (org-on-heading-p)
14967 ;; We already have headlines, de-star them
14968 (while (< (setq l (1+ l)) l2)
14969 (when (org-on-heading-p t)
14970 (and (looking-at outline-regexp) (replace-match "")))
14971 (beginning-of-line 2))
14972 (setq itemp (org-at-item-p))
14973 (let* ((stars
14974 (if nstars
14975 (make-string (prefix-numeric-value current-prefix-arg)
14976 ?*)
14977 (save-excursion
14978 (if (re-search-backward org-complex-heading-regexp nil t)
14979 (match-string 1) ""))))
14980 (add-stars (cond (nstars "")
14981 ((equal stars "") "*")
14982 (org-odd-levels-only "**")
14983 (t "*")))
14984 (rpl (concat stars add-stars " ")))
14985 (while (< (setq l (1+ l)) l2)
14986 (if itemp
14987 (and (org-at-item-p) (replace-match rpl t t))
14988 (unless (org-on-heading-p)
14989 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
14990 (replace-match (concat rpl (match-string 2))))))
14991 (beginning-of-line 2)))))))
14992
14993 (defun org-meta-return (&optional arg)
14994 "Insert a new heading or wrap a region in a table.
14995 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
14996 See the individual commands for more information."
14997 (interactive "P")
14998 (cond
14999 ((run-hook-with-args-until-success 'org-metareturn-hook))
15000 ((org-at-table-p)
15001 (call-interactively 'org-table-wrap-region))
15002 (t (call-interactively 'org-insert-heading))))
15003
15004 ;;; Menu entries
15005
15006 ;; Define the Org-mode menus
15007 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
15008 '("Tbl"
15009 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
15010 ["Next Field" org-cycle (org-at-table-p)]
15011 ["Previous Field" org-shifttab (org-at-table-p)]
15012 ["Next Row" org-return (org-at-table-p)]
15013 "--"
15014 ["Blank Field" org-table-blank-field (org-at-table-p)]
15015 ["Edit Field" org-table-edit-field (org-at-table-p)]
15016 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
15017 "--"
15018 ("Column"
15019 ["Move Column Left" org-metaleft (org-at-table-p)]
15020 ["Move Column Right" org-metaright (org-at-table-p)]
15021 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
15022 ["Insert Column" org-shiftmetaright (org-at-table-p)])
15023 ("Row"
15024 ["Move Row Up" org-metaup (org-at-table-p)]
15025 ["Move Row Down" org-metadown (org-at-table-p)]
15026 ["Delete Row" org-shiftmetaup (org-at-table-p)]
15027 ["Insert Row" org-shiftmetadown (org-at-table-p)]
15028 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
15029 "--"
15030 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
15031 ("Rectangle"
15032 ["Copy Rectangle" org-copy-special (org-at-table-p)]
15033 ["Cut Rectangle" org-cut-special (org-at-table-p)]
15034 ["Paste Rectangle" org-paste-special (org-at-table-p)]
15035 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
15036 "--"
15037 ("Calculate"
15038 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
15039 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
15040 ["Edit Formulas" org-edit-special (org-at-table-p)]
15041 "--"
15042 ["Recalculate line" org-table-recalculate (org-at-table-p)]
15043 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
15044 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
15045 "--"
15046 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
15047 "--"
15048 ["Sum Column/Rectangle" org-table-sum
15049 (or (org-at-table-p) (org-region-active-p))]
15050 ["Which Column?" org-table-current-column (org-at-table-p)])
15051 ["Debug Formulas"
15052 org-table-toggle-formula-debugger
15053 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
15054 ["Show Col/Row Numbers"
15055 org-table-toggle-coordinate-overlays
15056 :style toggle
15057 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
15058 "--"
15059 ["Create" org-table-create (and (not (org-at-table-p))
15060 org-enable-table-editor)]
15061 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
15062 ["Import from File" org-table-import (not (org-at-table-p))]
15063 ["Export to File" org-table-export (org-at-table-p)]
15064 "--"
15065 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
15066
15067 (easy-menu-define org-org-menu org-mode-map "Org menu"
15068 '("Org"
15069 ("Show/Hide"
15070 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
15071 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
15072 ["Sparse Tree..." org-sparse-tree t]
15073 ["Reveal Context" org-reveal t]
15074 ["Show All" show-all t]
15075 "--"
15076 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
15077 "--"
15078 ["New Heading" org-insert-heading t]
15079 ("Navigate Headings"
15080 ["Up" outline-up-heading t]
15081 ["Next" outline-next-visible-heading t]
15082 ["Previous" outline-previous-visible-heading t]
15083 ["Next Same Level" outline-forward-same-level t]
15084 ["Previous Same Level" outline-backward-same-level t]
15085 "--"
15086 ["Jump" org-goto t])
15087 ("Edit Structure"
15088 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
15089 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
15090 "--"
15091 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
15092 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
15093 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
15094 "--"
15095 ["Clone subtree, shift time" org-clone-subtree-with-time-shift t]
15096 "--"
15097 ["Promote Heading" org-metaleft (not (org-at-table-p))]
15098 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
15099 ["Demote Heading" org-metaright (not (org-at-table-p))]
15100 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
15101 "--"
15102 ["Sort Region/Children" org-sort (not (org-at-table-p))]
15103 "--"
15104 ["Convert to odd levels" org-convert-to-odd-levels t]
15105 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
15106 ("Editing"
15107 ["Emphasis..." org-emphasize t]
15108 ["Edit Source Example" org-edit-special t]
15109 "--"
15110 ["Footnote new/jump" org-footnote-action t]
15111 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
15112 ("Archive"
15113 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
15114 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
15115 ; :active t :keys "C-u C-c C-x C-a"]
15116 ["Sparse trees open ARCHIVE trees"
15117 (setq org-sparse-tree-open-archived-trees
15118 (not org-sparse-tree-open-archived-trees))
15119 :style toggle :selected org-sparse-tree-open-archived-trees]
15120 ["Cycling opens ARCHIVE trees"
15121 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
15122 :style toggle :selected org-cycle-open-archived-trees]
15123 "--"
15124 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
15125 ["Move Subtree to Archive" org-advertized-archive-subtree t]
15126 ; ["Check and Move Children" (org-archive-subtree '(4))
15127 ; :active t :keys "C-u C-c C-x C-s"]
15128 )
15129 "--"
15130 ("Hyperlinks"
15131 ["Store Link (Global)" org-store-link t]
15132 ["Find existing link to here" org-occur-link-in-agenda-files t]
15133 ["Insert Link" org-insert-link t]
15134 ["Follow Link" org-open-at-point t]
15135 "--"
15136 ["Next link" org-next-link t]
15137 ["Previous link" org-previous-link t]
15138 "--"
15139 ["Descriptive Links"
15140 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
15141 :style radio
15142 :selected (member '(org-link) buffer-invisibility-spec)]
15143 ["Literal Links"
15144 (progn
15145 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
15146 :style radio
15147 :selected (not (member '(org-link) buffer-invisibility-spec))])
15148 "--"
15149 ("TODO Lists"
15150 ["TODO/DONE/-" org-todo t]
15151 ("Select keyword"
15152 ["Next keyword" org-shiftright (org-on-heading-p)]
15153 ["Previous keyword" org-shiftleft (org-on-heading-p)]
15154 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
15155 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
15156 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
15157 ["Show TODO Tree" org-show-todo-tree t]
15158 ["Global TODO list" org-todo-list t]
15159 "--"
15160 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
15161 :selected org-enforce-todo-dependencies :style toggle :active t]
15162 "Settings for tree at point"
15163 ["Do Children sequentially" org-toggle-ordered-property :style radio
15164 :selected (ignore-errors (org-entry-get nil "ORDERED"))
15165 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15166 ["Do Children parallel" org-toggle-ordered-property :style radio
15167 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
15168 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
15169 "--"
15170 ["Set Priority" org-priority t]
15171 ["Priority Up" org-shiftup t]
15172 ["Priority Down" org-shiftdown t]
15173 "--"
15174 ["Get news from all feeds" org-feed-update-all t]
15175 ["Go to the inbox of a feed..." org-feed-goto-inbox t]
15176 ["Customize feeds" (customize-variable 'org-feed-alist) t])
15177 ("TAGS and Properties"
15178 ["Set Tags" org-set-tags-command t]
15179 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
15180 "--"
15181 ["Set property" org-set-property t]
15182 ["Column view of properties" org-columns t]
15183 ["Insert Column View DBlock" org-insert-columns-dblock t])
15184 ("Dates and Scheduling"
15185 ["Timestamp" org-time-stamp t]
15186 ["Timestamp (inactive)" org-time-stamp-inactive t]
15187 ("Change Date"
15188 ["1 Day Later" org-shiftright t]
15189 ["1 Day Earlier" org-shiftleft t]
15190 ["1 ... Later" org-shiftup t]
15191 ["1 ... Earlier" org-shiftdown t])
15192 ["Compute Time Range" org-evaluate-time-range t]
15193 ["Schedule Item" org-schedule t]
15194 ["Deadline" org-deadline t]
15195 "--"
15196 ["Custom time format" org-toggle-time-stamp-overlays
15197 :style radio :selected org-display-custom-times]
15198 "--"
15199 ["Goto Calendar" org-goto-calendar t]
15200 ["Date from Calendar" org-date-from-calendar t]
15201 "--"
15202 ["Start/Restart Timer" org-timer-start t]
15203 ["Pause/Continue Timer" org-timer-pause-or-continue t]
15204 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
15205 ["Insert Timer String" org-timer t]
15206 ["Insert Timer Item" org-timer-item t])
15207 ("Logging work"
15208 ["Clock in" org-clock-in :active t :keys "C-c C-x C-i"]
15209 ["Switch task" (lambda () (interactive) (org-clock-in '(4))) :active t :keys "C-u C-c C-x C-i"]
15210 ["Clock out" org-clock-out t]
15211 ["Clock cancel" org-clock-cancel t]
15212 "--"
15213 ["Mark as default task" org-clock-mark-default-task t]
15214 ["Clock in, mark as default" (lambda () (interactive) (org-clock-in '(16))) :active t :keys "C-u C-u C-c C-x C-i"]
15215 ["Goto running clock" org-clock-goto t]
15216 "--"
15217 ["Display times" org-clock-display t]
15218 ["Create clock table" org-clock-report t]
15219 "--"
15220 ["Record DONE time"
15221 (progn (setq org-log-done (not org-log-done))
15222 (message "Switching to %s will %s record a timestamp"
15223 (car org-done-keywords)
15224 (if org-log-done "automatically" "not")))
15225 :style toggle :selected org-log-done])
15226 "--"
15227 ["Agenda Command..." org-agenda t]
15228 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
15229 ("File List for Agenda")
15230 ("Special views current file"
15231 ["TODO Tree" org-show-todo-tree t]
15232 ["Check Deadlines" org-check-deadlines t]
15233 ["Timeline" org-timeline t]
15234 ["Tags/Property tree" org-match-sparse-tree t])
15235 "--"
15236 ["Export/Publish..." org-export t]
15237 ("LaTeX"
15238 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
15239 :selected org-cdlatex-mode]
15240 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
15241 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
15242 ["Modify math symbol" org-cdlatex-math-modify
15243 (org-inside-LaTeX-fragment-p)]
15244 ["Insert citation" org-reftex-citation t]
15245 "--"
15246 ["Export LaTeX fragments as images"
15247 (if (featurep 'org-exp)
15248 (setq org-export-with-LaTeX-fragments
15249 (not org-export-with-LaTeX-fragments))
15250 (require 'org-exp))
15251 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
15252 org-export-with-LaTeX-fragments)])
15253 "--"
15254 ("Documentation"
15255 ["Show Version" org-version t]
15256 ["Info Documentation" org-info t])
15257 ("Customize"
15258 ["Browse Org Group" org-customize t]
15259 "--"
15260 ["Expand This Menu" org-create-customize-menu
15261 (fboundp 'customize-menu-create)])
15262 "--"
15263 ("Refresh/Reload"
15264 ["Refresh setup current buffer" org-mode-restart t]
15265 ["Reload Org (after update)" org-reload t]
15266 ["Reload Org uncompiled" (org-reload t) :active t :keys "C-u C-c C-x r"])
15267 ))
15268
15269 (defun org-info (&optional node)
15270 "Read documentation for Org-mode in the info system.
15271 With optional NODE, go directly to that node."
15272 (interactive)
15273 (info (format "(org)%s" (or node ""))))
15274
15275 (defun org-install-agenda-files-menu ()
15276 (let ((bl (buffer-list)))
15277 (save-excursion
15278 (while bl
15279 (set-buffer (pop bl))
15280 (if (org-mode-p) (setq bl nil)))
15281 (when (org-mode-p)
15282 (easy-menu-change
15283 '("Org") "File List for Agenda"
15284 (append
15285 (list
15286 ["Edit File List" (org-edit-agenda-file-list) t]
15287 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
15288 ["Remove Current File from List" org-remove-file t]
15289 ["Cycle through agenda files" org-cycle-agenda-files t]
15290 ["Occur in all agenda files" org-occur-in-agenda-files t]
15291 "--")
15292 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
15293
15294 ;;;; Documentation
15295
15296 ;;;###autoload
15297 (defun org-require-autoloaded-modules ()
15298 (interactive)
15299 (mapc 'require
15300 '(org-agenda org-archive org-ascii org-attach org-clock org-colview
15301 org-docbook org-exp org-html org-icalendar
15302 org-id org-latex
15303 org-publish org-remember org-table
15304 org-timer org-xoxo)))
15305
15306 ;;;###autoload
15307 (defun org-reload (&optional uncompiled)
15308 "Reload all org lisp files.
15309 With prefix arg UNCOMPILED, load the uncompiled versions."
15310 (interactive "P")
15311 (require 'find-func)
15312 (let* ((file-re "^\\(org\\|orgtbl\\)\\(\\.el\\|-.*\\.el\\)")
15313 (dir-org (file-name-directory (org-find-library-name "org")))
15314 (dir-org-contrib (ignore-errors
15315 (file-name-directory
15316 (org-find-library-name "org-contribdir"))))
15317 (files
15318 (append (directory-files dir-org t file-re)
15319 (and dir-org-contrib
15320 (directory-files dir-org-contrib t file-re))))
15321 (remove-re (concat (if (featurep 'xemacs)
15322 "org-colview" "org-colview-xemacs")
15323 "\\'")))
15324 (setq files (mapcar 'file-name-sans-extension files))
15325 (setq files (mapcar
15326 (lambda (x) (if (string-match remove-re x) nil x))
15327 files))
15328 (setq files (delq nil files))
15329 (mapc
15330 (lambda (f)
15331 (when (featurep (intern (file-name-nondirectory f)))
15332 (if (and (not uncompiled)
15333 (file-exists-p (concat f ".elc")))
15334 (load (concat f ".elc") nil nil t)
15335 (load (concat f ".el") nil nil t))))
15336 files))
15337 (org-version))
15338
15339 ;;;###autoload
15340 (defun org-customize ()
15341 "Call the customize function with org as argument."
15342 (interactive)
15343 (org-load-modules-maybe)
15344 (org-require-autoloaded-modules)
15345 (customize-browse 'org))
15346
15347 (defun org-create-customize-menu ()
15348 "Create a full customization menu for Org-mode, insert it into the menu."
15349 (interactive)
15350 (org-load-modules-maybe)
15351 (org-require-autoloaded-modules)
15352 (if (fboundp 'customize-menu-create)
15353 (progn
15354 (easy-menu-change
15355 '("Org") "Customize"
15356 `(["Browse Org group" org-customize t]
15357 "--"
15358 ,(customize-menu-create 'org)
15359 ["Set" Custom-set t]
15360 ["Save" Custom-save t]
15361 ["Reset to Current" Custom-reset-current t]
15362 ["Reset to Saved" Custom-reset-saved t]
15363 ["Reset to Standard Settings" Custom-reset-standard t]))
15364 (message "\"Org\"-menu now contains full customization menu"))
15365 (error "Cannot expand menu (outdated version of cus-edit.el)")))
15366
15367 ;;;; Miscellaneous stuff
15368
15369 ;;; Generally useful functions
15370
15371 (defun org-find-text-property-in-string (prop s)
15372 "Return the first non-nil value of property PROP in string S."
15373 (or (get-text-property 0 prop s)
15374 (get-text-property (or (next-single-property-change 0 prop s) 0)
15375 prop s)))
15376
15377 (defun org-display-warning (message) ;; Copied from Emacs-Muse
15378 "Display the given MESSAGE as a warning."
15379 (if (fboundp 'display-warning)
15380 (display-warning 'org message
15381 (if (featurep 'xemacs)
15382 'warning
15383 :warning))
15384 (let ((buf (get-buffer-create "*Org warnings*")))
15385 (with-current-buffer buf
15386 (goto-char (point-max))
15387 (insert "Warning (Org): " message)
15388 (unless (bolp)
15389 (newline)))
15390 (display-buffer buf)
15391 (sit-for 0))))
15392
15393 (defun org-goto-marker-or-bmk (marker &optional bookmark)
15394 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
15395 (if (and marker (marker-buffer marker)
15396 (buffer-live-p (marker-buffer marker)))
15397 (progn
15398 (switch-to-buffer (marker-buffer marker))
15399 (if (or (> marker (point-max)) (< marker (point-min)))
15400 (widen))
15401 (goto-char marker)
15402 (org-show-context 'org-goto))
15403 (if bookmark
15404 (bookmark-jump bookmark)
15405 (error "Cannot find location"))))
15406
15407 (defun org-quote-csv-field (s)
15408 "Quote field for inclusion in CSV material."
15409 (if (string-match "[\",]" s)
15410 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
15411 s))
15412
15413 (defun org-plist-delete (plist property)
15414 "Delete PROPERTY from PLIST.
15415 This is in contrast to merely setting it to 0."
15416 (let (p)
15417 (while plist
15418 (if (not (eq property (car plist)))
15419 (setq p (plist-put p (car plist) (nth 1 plist))))
15420 (setq plist (cddr plist)))
15421 p))
15422
15423 (defun org-force-self-insert (N)
15424 "Needed to enforce self-insert under remapping."
15425 (interactive "p")
15426 (self-insert-command N))
15427
15428 (defun org-string-width (s)
15429 "Compute width of string, ignoring invisible characters.
15430 This ignores character with invisibility property `org-link', and also
15431 characters with property `org-cwidth', because these will become invisible
15432 upon the next fontification round."
15433 (let (b l)
15434 (when (or (eq t buffer-invisibility-spec)
15435 (assq 'org-link buffer-invisibility-spec))
15436 (while (setq b (text-property-any 0 (length s)
15437 'invisible 'org-link s))
15438 (setq s (concat (substring s 0 b)
15439 (substring s (or (next-single-property-change
15440 b 'invisible s) (length s)))))))
15441 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
15442 (setq s (concat (substring s 0 b)
15443 (substring s (or (next-single-property-change
15444 b 'org-cwidth s) (length s))))))
15445 (setq l (string-width s) b -1)
15446 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
15447 (setq l (- l (get-text-property b 'org-dwidth-n s))))
15448 l))
15449
15450 (defun org-get-indentation (&optional line)
15451 "Get the indentation of the current line, interpreting tabs.
15452 When LINE is given, assume it represents a line and compute its indentation."
15453 (if line
15454 (if (string-match "^ *" (org-remove-tabs line))
15455 (match-end 0))
15456 (save-excursion
15457 (beginning-of-line 1)
15458 (skip-chars-forward " \t")
15459 (current-column))))
15460
15461 (defun org-remove-tabs (s &optional width)
15462 "Replace tabulators in S with spaces.
15463 Assumes that s is a single line, starting in column 0."
15464 (setq width (or width tab-width))
15465 (while (string-match "\t" s)
15466 (setq s (replace-match
15467 (make-string
15468 (- (* width (/ (+ (match-beginning 0) width) width))
15469 (match-beginning 0)) ?\ )
15470 t t s)))
15471 s)
15472
15473 (defun org-fix-indentation (line ind)
15474 "Fix indentation in LINE.
15475 IND is a cons cell with target and minimum indentation.
15476 If the current indentation in LINE is smaller than the minimum,
15477 leave it alone. If it is larger than ind, set it to the target."
15478 (let* ((l (org-remove-tabs line))
15479 (i (org-get-indentation l))
15480 (i1 (car ind)) (i2 (cdr ind)))
15481 (if (>= i i2) (setq l (substring line i2)))
15482 (if (> i1 0)
15483 (concat (make-string i1 ?\ ) l)
15484 l)))
15485
15486 (defun org-remove-indentation (code &optional n)
15487 "Remove the maximum common indentation from the lines in CODE.
15488 N may optionally be the number of spaces to remove."
15489 (with-temp-buffer
15490 (insert code)
15491 (org-do-remove-indentation n)
15492 (buffer-string)))
15493
15494 (defun org-do-remove-indentation (&optional n)
15495 "Remove the maximum common indentation from the buffer."
15496 (untabify (point-min) (point-max))
15497 (let ((min 10000) re)
15498 (if n
15499 (setq min n)
15500 (goto-char (point-min))
15501 (while (re-search-forward "^ *[^ \n]" nil t)
15502 (setq min (min min (1- (- (match-end 0) (match-beginning 0)))))))
15503 (unless (or (= min 0) (= min 10000))
15504 (setq re (format "^ \\{%d\\}" min))
15505 (goto-char (point-min))
15506 (while (re-search-forward re nil t)
15507 (replace-match "")
15508 (end-of-line 1))
15509 min)))
15510
15511 (defun org-base-buffer (buffer)
15512 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
15513 (if (not buffer)
15514 buffer
15515 (or (buffer-base-buffer buffer)
15516 buffer)))
15517
15518 (defun org-trim (s)
15519 "Remove whitespace at beginning and end of string."
15520 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
15521 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
15522 s)
15523
15524 (defun org-wrap (string &optional width lines)
15525 "Wrap string to either a number of lines, or a width in characters.
15526 If WIDTH is non-nil, the string is wrapped to that width, however many lines
15527 that costs. If there is a word longer than WIDTH, the text is actually
15528 wrapped to the length of that word.
15529 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
15530 many lines, whatever width that takes.
15531 The return value is a list of lines, without newlines at the end."
15532 (let* ((words (org-split-string string "[ \t\n]+"))
15533 (maxword (apply 'max (mapcar 'org-string-width words)))
15534 w ll)
15535 (cond (width
15536 (org-do-wrap words (max maxword width)))
15537 (lines
15538 (setq w maxword)
15539 (setq ll (org-do-wrap words maxword))
15540 (if (<= (length ll) lines)
15541 ll
15542 (setq ll words)
15543 (while (> (length ll) lines)
15544 (setq w (1+ w))
15545 (setq ll (org-do-wrap words w)))
15546 ll))
15547 (t (error "Cannot wrap this")))))
15548
15549 (defun org-do-wrap (words width)
15550 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
15551 (let (lines line)
15552 (while words
15553 (setq line (pop words))
15554 (while (and words (< (+ (length line) (length (car words))) width))
15555 (setq line (concat line " " (pop words))))
15556 (setq lines (push line lines)))
15557 (nreverse lines)))
15558
15559 (defun org-split-string (string &optional separators)
15560 "Splits STRING into substrings at SEPARATORS.
15561 No empty strings are returned if there are matches at the beginning
15562 and end of string."
15563 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
15564 (start 0)
15565 notfirst
15566 (list nil))
15567 (while (and (string-match rexp string
15568 (if (and notfirst
15569 (= start (match-beginning 0))
15570 (< start (length string)))
15571 (1+ start) start))
15572 (< (match-beginning 0) (length string)))
15573 (setq notfirst t)
15574 (or (eq (match-beginning 0) 0)
15575 (and (eq (match-beginning 0) (match-end 0))
15576 (eq (match-beginning 0) start))
15577 (setq list
15578 (cons (substring string start (match-beginning 0))
15579 list)))
15580 (setq start (match-end 0)))
15581 (or (eq start (length string))
15582 (setq list
15583 (cons (substring string start)
15584 list)))
15585 (nreverse list)))
15586
15587 (defun org-quote-vert (s)
15588 "Replace \"|\" with \"\\vert\"."
15589 (while (string-match "|" s)
15590 (setq s (replace-match "\\vert" t t s)))
15591 s)
15592
15593 (defun org-uuidgen-p (s)
15594 "Is S an ID created by UUIDGEN?"
15595 (string-match "\\`[0-9a-f]\\{8\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{4\\}-[0-9a-f]\\{12\\}\\'" (downcase s)))
15596
15597 (defun org-context ()
15598 "Return a list of contexts of the current cursor position.
15599 If several contexts apply, all are returned.
15600 Each context entry is a list with a symbol naming the context, and
15601 two positions indicating start and end of the context. Possible
15602 contexts are:
15603
15604 :headline anywhere in a headline
15605 :headline-stars on the leading stars in a headline
15606 :todo-keyword on a TODO keyword (including DONE) in a headline
15607 :tags on the TAGS in a headline
15608 :priority on the priority cookie in a headline
15609 :item on the first line of a plain list item
15610 :item-bullet on the bullet/number of a plain list item
15611 :checkbox on the checkbox in a plain list item
15612 :table in an org-mode table
15613 :table-special on a special filed in a table
15614 :table-table in a table.el table
15615 :link on a hyperlink
15616 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
15617 :target on a <<target>>
15618 :radio-target on a <<<radio-target>>>
15619 :latex-fragment on a LaTeX fragment
15620 :latex-preview on a LaTeX fragment with overlayed preview image
15621
15622 This function expects the position to be visible because it uses font-lock
15623 faces as a help to recognize the following contexts: :table-special, :link,
15624 and :keyword."
15625 (let* ((f (get-text-property (point) 'face))
15626 (faces (if (listp f) f (list f)))
15627 (p (point)) clist o)
15628 ;; First the large context
15629 (cond
15630 ((org-on-heading-p t)
15631 (push (list :headline (point-at-bol) (point-at-eol)) clist)
15632 (when (progn
15633 (beginning-of-line 1)
15634 (looking-at org-todo-line-tags-regexp))
15635 (push (org-point-in-group p 1 :headline-stars) clist)
15636 (push (org-point-in-group p 2 :todo-keyword) clist)
15637 (push (org-point-in-group p 4 :tags) clist))
15638 (goto-char p)
15639 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
15640 (if (looking-at "\\[#[A-Z0-9]\\]")
15641 (push (org-point-in-group p 0 :priority) clist)))
15642
15643 ((org-at-item-p)
15644 (push (org-point-in-group p 2 :item-bullet) clist)
15645 (push (list :item (point-at-bol)
15646 (save-excursion (org-end-of-item) (point)))
15647 clist)
15648 (and (org-at-item-checkbox-p)
15649 (push (org-point-in-group p 0 :checkbox) clist)))
15650
15651 ((org-at-table-p)
15652 (push (list :table (org-table-begin) (org-table-end)) clist)
15653 (if (memq 'org-formula faces)
15654 (push (list :table-special
15655 (previous-single-property-change p 'face)
15656 (next-single-property-change p 'face)) clist)))
15657 ((org-at-table-p 'any)
15658 (push (list :table-table) clist)))
15659 (goto-char p)
15660
15661 ;; Now the small context
15662 (cond
15663 ((org-at-timestamp-p)
15664 (push (org-point-in-group p 0 :timestamp) clist))
15665 ((memq 'org-link faces)
15666 (push (list :link
15667 (previous-single-property-change p 'face)
15668 (next-single-property-change p 'face)) clist))
15669 ((memq 'org-special-keyword faces)
15670 (push (list :keyword
15671 (previous-single-property-change p 'face)
15672 (next-single-property-change p 'face)) clist))
15673 ((org-on-target-p)
15674 (push (org-point-in-group p 0 :target) clist)
15675 (goto-char (1- (match-beginning 0)))
15676 (if (looking-at org-radio-target-regexp)
15677 (push (org-point-in-group p 0 :radio-target) clist))
15678 (goto-char p))
15679 ((setq o (car (delq nil
15680 (mapcar
15681 (lambda (x)
15682 (if (memq x org-latex-fragment-image-overlays) x))
15683 (org-overlays-at (point))))))
15684 (push (list :latex-fragment
15685 (org-overlay-start o) (org-overlay-end o)) clist)
15686 (push (list :latex-preview
15687 (org-overlay-start o) (org-overlay-end o)) clist))
15688 ((org-inside-LaTeX-fragment-p)
15689 ;; FIXME: positions wrong.
15690 (push (list :latex-fragment (point) (point)) clist)))
15691
15692 (setq clist (nreverse (delq nil clist)))
15693 clist))
15694
15695 ;; FIXME: Compare with at-regexp-p Do we need both?
15696 (defun org-in-regexp (re &optional nlines visually)
15697 "Check if point is inside a match of regexp.
15698 Normally only the current line is checked, but you can include NLINES extra
15699 lines both before and after point into the search.
15700 If VISUALLY is set, require that the cursor is not after the match but
15701 really on, so that the block visually is on the match."
15702 (catch 'exit
15703 (let ((pos (point))
15704 (eol (point-at-eol (+ 1 (or nlines 0))))
15705 (inc (if visually 1 0)))
15706 (save-excursion
15707 (beginning-of-line (- 1 (or nlines 0)))
15708 (while (re-search-forward re eol t)
15709 (if (and (<= (match-beginning 0) pos)
15710 (>= (+ inc (match-end 0)) pos))
15711 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
15712
15713 (defun org-at-regexp-p (regexp)
15714 "Is point inside a match of REGEXP in the current line?"
15715 (catch 'exit
15716 (save-excursion
15717 (let ((pos (point)) (end (point-at-eol)))
15718 (beginning-of-line 1)
15719 (while (re-search-forward regexp end t)
15720 (if (and (<= (match-beginning 0) pos)
15721 (>= (match-end 0) pos))
15722 (throw 'exit t)))
15723 nil))))
15724
15725 (defun org-occur-in-agenda-files (regexp &optional nlines)
15726 "Call `multi-occur' with buffers for all agenda files."
15727 (interactive "sOrg-files matching: \np")
15728 (let* ((files (org-agenda-files))
15729 (tnames (mapcar 'file-truename files))
15730 (extra org-agenda-text-search-extra-files)
15731 f)
15732 (when (eq (car extra) 'agenda-archives)
15733 (setq extra (cdr extra))
15734 (setq files (org-add-archive-files files)))
15735 (while (setq f (pop extra))
15736 (unless (member (file-truename f) tnames)
15737 (add-to-list 'files f 'append)
15738 (add-to-list 'tnames (file-truename f) 'append)))
15739 (multi-occur
15740 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
15741 regexp)))
15742
15743 (if (boundp 'occur-mode-find-occurrence-hook)
15744 ;; Emacs 23
15745 (add-hook 'occur-mode-find-occurrence-hook
15746 (lambda ()
15747 (when (org-mode-p)
15748 (org-reveal))))
15749 ;; Emacs 22
15750 (defadvice occur-mode-goto-occurrence
15751 (after org-occur-reveal activate)
15752 (and (org-mode-p) (org-reveal)))
15753 (defadvice occur-mode-goto-occurrence-other-window
15754 (after org-occur-reveal activate)
15755 (and (org-mode-p) (org-reveal)))
15756 (defadvice occur-mode-display-occurrence
15757 (after org-occur-reveal activate)
15758 (when (org-mode-p)
15759 (let ((pos (occur-mode-find-occurrence)))
15760 (with-current-buffer (marker-buffer pos)
15761 (save-excursion
15762 (goto-char pos)
15763 (org-reveal)))))))
15764
15765 (defun org-occur-link-in-agenda-files ()
15766 "Create a link and search for it in the agendas.
15767 The link is not stored in `org-stored-links', it is just created
15768 for the search purpose."
15769 (interactive)
15770 (let ((link (condition-case nil
15771 (org-store-link nil)
15772 (error "Unable to create a link to here"))))
15773 (org-occur-in-agenda-files (regexp-quote link))))
15774
15775 (defun org-uniquify (list)
15776 "Remove duplicate elements from LIST."
15777 (let (res)
15778 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
15779 res))
15780
15781 (defun org-delete-all (elts list)
15782 "Remove all elements in ELTS from LIST."
15783 (while elts
15784 (setq list (delete (pop elts) list)))
15785 list)
15786
15787 (defun org-back-over-empty-lines ()
15788 "Move backwards over whitespace, to the beginning of the first empty line.
15789 Returns the number of empty lines passed."
15790 (let ((pos (point)))
15791 (skip-chars-backward " \t\n\r")
15792 (beginning-of-line 2)
15793 (goto-char (min (point) pos))
15794 (count-lines (point) pos)))
15795
15796 (defun org-skip-whitespace ()
15797 (skip-chars-forward " \t\n\r"))
15798
15799 (defun org-point-in-group (point group &optional context)
15800 "Check if POINT is in match-group GROUP.
15801 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
15802 match. If the match group does ot exist or point is not inside it,
15803 return nil."
15804 (and (match-beginning group)
15805 (>= point (match-beginning group))
15806 (<= point (match-end group))
15807 (if context
15808 (list context (match-beginning group) (match-end group))
15809 t)))
15810
15811 (defun org-switch-to-buffer-other-window (&rest args)
15812 "Switch to buffer in a second window on the current frame.
15813 In particular, do not allow pop-up frames."
15814 (let (pop-up-frames special-display-buffer-names special-display-regexps
15815 special-display-function)
15816 (apply 'switch-to-buffer-other-window args)))
15817
15818 (defun org-combine-plists (&rest plists)
15819 "Create a single property list from all plists in PLISTS.
15820 The process starts by copying the first list, and then setting properties
15821 from the other lists. Settings in the last list are the most significant
15822 ones and overrule settings in the other lists."
15823 (let ((rtn (copy-sequence (pop plists)))
15824 p v ls)
15825 (while plists
15826 (setq ls (pop plists))
15827 (while ls
15828 (setq p (pop ls) v (pop ls))
15829 (setq rtn (plist-put rtn p v))))
15830 rtn))
15831
15832 (defun org-move-line-down (arg)
15833 "Move the current line down. With prefix argument, move it past ARG lines."
15834 (interactive "p")
15835 (let ((col (current-column))
15836 beg end pos)
15837 (beginning-of-line 1) (setq beg (point))
15838 (beginning-of-line 2) (setq end (point))
15839 (beginning-of-line (+ 1 arg))
15840 (setq pos (move-marker (make-marker) (point)))
15841 (insert (delete-and-extract-region beg end))
15842 (goto-char pos)
15843 (org-move-to-column col)))
15844
15845 (defun org-move-line-up (arg)
15846 "Move the current line up. With prefix argument, move it past ARG lines."
15847 (interactive "p")
15848 (let ((col (current-column))
15849 beg end pos)
15850 (beginning-of-line 1) (setq beg (point))
15851 (beginning-of-line 2) (setq end (point))
15852 (beginning-of-line (- arg))
15853 (setq pos (move-marker (make-marker) (point)))
15854 (insert (delete-and-extract-region beg end))
15855 (goto-char pos)
15856 (org-move-to-column col)))
15857
15858 (defun org-replace-escapes (string table)
15859 "Replace %-escapes in STRING with values in TABLE.
15860 TABLE is an association list with keys like \"%a\" and string values.
15861 The sequences in STRING may contain normal field width and padding information,
15862 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
15863 so values can contain further %-escapes if they are define later in TABLE."
15864 (let ((case-fold-search nil)
15865 e re rpl)
15866 (while (setq e (pop table))
15867 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
15868 (while (string-match re string)
15869 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
15870 (cdr e)))
15871 (setq string (replace-match rpl t t string))))
15872 string))
15873
15874
15875 (defun org-sublist (list start end)
15876 "Return a section of LIST, from START to END.
15877 Counting starts at 1."
15878 (let (rtn (c start))
15879 (setq list (nthcdr (1- start) list))
15880 (while (and list (<= c end))
15881 (push (pop list) rtn)
15882 (setq c (1+ c)))
15883 (nreverse rtn)))
15884
15885 (defun org-find-base-buffer-visiting (file)
15886 "Like `find-buffer-visiting' but always return the base buffer and
15887 not an indirect buffer."
15888 (let ((buf (or (get-file-buffer file)
15889 (find-buffer-visiting file))))
15890 (if buf
15891 (or (buffer-base-buffer buf) buf)
15892 nil)))
15893
15894 (defun org-image-file-name-regexp (&optional extensions)
15895 "Return regexp matching the file names of images.
15896 If EXTENSIONS is given, only match these."
15897 (if (and (not extensions) (fboundp 'image-file-name-regexp))
15898 (image-file-name-regexp)
15899 (let ((image-file-name-extensions
15900 (or extensions
15901 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
15902 "xbm" "xpm" "pbm" "pgm" "ppm"))))
15903 (concat "\\."
15904 (regexp-opt (nconc (mapcar 'upcase
15905 image-file-name-extensions)
15906 image-file-name-extensions)
15907 t)
15908 "\\'"))))
15909
15910 (defun org-file-image-p (file &optional extensions)
15911 "Return non-nil if FILE is an image."
15912 (save-match-data
15913 (string-match (org-image-file-name-regexp extensions) file)))
15914
15915 (defun org-get-cursor-date ()
15916 "Return the date at cursor in as a time.
15917 This works in the calendar and in the agenda, anywhere else it just
15918 returns the current time."
15919 (let (date day defd)
15920 (cond
15921 ((eq major-mode 'calendar-mode)
15922 (setq date (calendar-cursor-to-date)
15923 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
15924 ((eq major-mode 'org-agenda-mode)
15925 (setq day (get-text-property (point) 'day))
15926 (if day
15927 (setq date (calendar-gregorian-from-absolute day)
15928 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
15929 (nth 2 date))))))
15930 (or defd (current-time))))
15931
15932 (defvar org-agenda-action-marker (make-marker)
15933 "Marker pointing to the entry for the next agenda action.")
15934
15935 (defun org-mark-entry-for-agenda-action ()
15936 "Mark the current entry as target of an agenda action.
15937 Agenda actions are actions executed from the agenda with the key `k',
15938 which make use of the date at the cursor."
15939 (interactive)
15940 (move-marker org-agenda-action-marker
15941 (save-excursion (org-back-to-heading t) (point))
15942 (current-buffer))
15943 (message
15944 "Entry marked for action; press `k' at desired date in agenda or calendar"))
15945
15946 ;;; Paragraph filling stuff.
15947 ;; We want this to be just right, so use the full arsenal.
15948
15949 (defun org-indent-line-function ()
15950 "Indent line like previous, but further if previous was headline or item."
15951 (interactive)
15952 (let* ((pos (point))
15953 (itemp (org-at-item-p))
15954 (case-fold-search t)
15955 (org-drawer-regexp (or org-drawer-regexp "\000"))
15956 column bpos bcol tpos tcol bullet btype bullet-type)
15957 ;; Find the previous relevant line
15958 (beginning-of-line 1)
15959 (cond
15960 ((looking-at "#") (setq column 0))
15961 ((looking-at "\\*+ ") (setq column 0))
15962 ((and (looking-at "[ \t]*:END:")
15963 (save-excursion (re-search-backward org-drawer-regexp nil t)))
15964 (save-excursion
15965 (goto-char (1- (match-beginning 1)))
15966 (setq column (current-column))))
15967 ((and (looking-at "[ \t]+#\\+end_\\([a-z]+\\)")
15968 (save-excursion
15969 (re-search-backward
15970 (concat "^[ \t]*#\\+begin_" (downcase (match-string 1))) nil t)))
15971 (setq column (org-get-indentation (match-string 0))))
15972 (t
15973 (beginning-of-line 0)
15974 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]")
15975 (not (looking-at "[ \t]*:END:"))
15976 (not (looking-at org-drawer-regexp)))
15977 (beginning-of-line 0))
15978 (cond
15979 ((looking-at "\\*+[ \t]+")
15980 (if (not org-adapt-indentation)
15981 (setq column 0)
15982 (goto-char (match-end 0))
15983 (setq column (current-column))))
15984 ((looking-at org-drawer-regexp)
15985 (goto-char (1- (match-beginning 1)))
15986 (setq column (current-column)))
15987 ((looking-at "\\([ \t]*\\):END:")
15988 (goto-char (match-end 1))
15989 (setq column (current-column)))
15990 ((org-in-item-p)
15991 (org-beginning-of-item)
15992 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
15993 (setq bpos (match-beginning 1) tpos (match-end 0)
15994 bcol (progn (goto-char bpos) (current-column))
15995 tcol (progn (goto-char tpos) (current-column))
15996 bullet (match-string 1)
15997 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
15998 (if (> tcol (+ bcol org-description-max-indent))
15999 (setq tcol (+ bcol 5)))
16000 (if (not itemp)
16001 (setq column tcol)
16002 (goto-char pos)
16003 (beginning-of-line 1)
16004 (if (looking-at "\\S-")
16005 (progn
16006 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
16007 (setq bullet (match-string 1)
16008 btype (if (string-match "[0-9]" bullet) "n" bullet))
16009 (setq column (if (equal btype bullet-type) bcol tcol)))
16010 (setq column (org-get-indentation)))))
16011 (t (setq column (org-get-indentation))))))
16012 (goto-char pos)
16013 (if (<= (current-column) (current-indentation))
16014 (org-indent-line-to column)
16015 (save-excursion (org-indent-line-to column)))
16016 (setq column (current-column))
16017 (beginning-of-line 1)
16018 (if (looking-at
16019 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
16020 (replace-match (concat "\\1" (format org-property-format
16021 (match-string 2) (match-string 3)))
16022 t nil))
16023 (org-move-to-column column)))
16024
16025 (defun org-set-autofill-regexps ()
16026 (interactive)
16027 ;; In the paragraph separator we include headlines, because filling
16028 ;; text in a line directly attached to a headline would otherwise
16029 ;; fill the headline as well.
16030 (org-set-local 'comment-start-skip "^#+[ \t]*")
16031 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
16032 ;; The paragraph starter includes hand-formatted lists.
16033 (org-set-local
16034 'paragraph-start
16035 (concat
16036 "\f" "\\|"
16037 "[ ]*$" "\\|"
16038 "\\*+ " "\\|"
16039 "[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)" "\\|"
16040 "[ \t]*[:|]" "\\|"
16041 "\\$\\$" "\\|"
16042 "\\\\\\(begin\\|end\\|[][]\\)"))
16043 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
16044 ;; But only if the user has not turned off tables or fixed-width regions
16045 (org-set-local
16046 'auto-fill-inhibit-regexp
16047 (concat "\\*+ \\|#\\+"
16048 "\\|[ \t]*" org-keyword-time-regexp
16049 (if (or org-enable-table-editor org-enable-fixed-width-editor)
16050 (concat
16051 "\\|[ \t]*["
16052 (if org-enable-table-editor "|" "")
16053 (if org-enable-fixed-width-editor ":" "")
16054 "]"))))
16055 ;; We use our own fill-paragraph function, to make sure that tables
16056 ;; and fixed-width regions are not wrapped. That function will pass
16057 ;; through to `fill-paragraph' when appropriate.
16058 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
16059 ; Adaptive filling: To get full control, first make sure that
16060 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
16061 (org-set-local 'adaptive-fill-regexp "\000")
16062 (org-set-local 'adaptive-fill-function
16063 'org-adaptive-fill-function)
16064 (org-set-local
16065 'align-mode-rules-list
16066 '((org-in-buffer-settings
16067 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
16068 (modes . '(org-mode))))))
16069
16070 (defun org-fill-paragraph (&optional justify)
16071 "Re-align a table, pass through to fill-paragraph if no table."
16072 (let ((table-p (org-at-table-p))
16073 (table.el-p (org-at-table.el-p)))
16074 (cond ((and (equal (char-after (point-at-bol)) ?*)
16075 (save-excursion (goto-char (point-at-bol))
16076 (looking-at outline-regexp)))
16077 t) ; skip headlines
16078 (table.el-p t) ; skip table.el tables
16079 (table-p (org-table-align) t) ; align org-mode tables
16080 (t nil)))) ; call paragraph-fill
16081
16082 ;; For reference, this is the default value of adaptive-fill-regexp
16083 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
16084
16085 (defun org-adaptive-fill-function ()
16086 "Return a fill prefix for org-mode files.
16087 In particular, this makes sure hanging paragraphs for hand-formatted lists
16088 work correctly."
16089 (cond ((looking-at "#[ \t]+")
16090 (match-string 0))
16091 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
16092 (save-excursion
16093 (if (> (match-end 1) (+ (match-beginning 1)
16094 org-description-max-indent))
16095 (goto-char (+ (match-beginning 1) 5))
16096 (goto-char (match-end 0)))
16097 (make-string (current-column) ?\ )))
16098 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
16099 (save-excursion
16100 (goto-char (match-end 0))
16101 (make-string (current-column) ?\ )))
16102 (t nil)))
16103
16104 ;;; Other stuff.
16105
16106 (defun org-toggle-fixed-width-section (arg)
16107 "Toggle the fixed-width export.
16108 If there is no active region, the QUOTE keyword at the current headline is
16109 inserted or removed. When present, it causes the text between this headline
16110 and the next to be exported as fixed-width text, and unmodified.
16111 If there is an active region, this command adds or removes a colon as the
16112 first character of this line. If the first character of a line is a colon,
16113 this line is also exported in fixed-width font."
16114 (interactive "P")
16115 (let* ((cc 0)
16116 (regionp (org-region-active-p))
16117 (beg (if regionp (region-beginning) (point)))
16118 (end (if regionp (region-end)))
16119 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
16120 (case-fold-search nil)
16121 (re "[ \t]*\\(: \\)")
16122 off)
16123 (if regionp
16124 (save-excursion
16125 (goto-char beg)
16126 (setq cc (current-column))
16127 (beginning-of-line 1)
16128 (setq off (looking-at re))
16129 (while (> nlines 0)
16130 (setq nlines (1- nlines))
16131 (beginning-of-line 1)
16132 (cond
16133 (arg
16134 (org-move-to-column cc t)
16135 (insert ": \n")
16136 (forward-line -1))
16137 ((and off (looking-at re))
16138 (replace-match "" t t nil 1))
16139 ((not off) (org-move-to-column cc t) (insert ": ")))
16140 (forward-line 1)))
16141 (save-excursion
16142 (org-back-to-heading)
16143 (if (looking-at (concat outline-regexp
16144 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
16145 (replace-match "" t t nil 1)
16146 (if (looking-at outline-regexp)
16147 (progn
16148 (goto-char (match-end 0))
16149 (insert org-quote-string " "))))))))
16150
16151 (defun org-reftex-citation ()
16152 "Use reftex-citation to insert a citation into the buffer.
16153 This looks for a line like
16154
16155 #+BIBLIOGRAPHY: foo plain option:-d
16156
16157 and derives from it that foo.bib is the bbliography file relevant
16158 for this document. It then installs the necessary environment for RefTeX
16159 to work in this buffer and calls `reftex-citation' to insert a citation
16160 into the buffer.
16161
16162 Export of such citations to both LaTeX and HTML is handled by the contributed
16163 package org-exp-bibtex by Taru Karttunen."
16164 (interactive)
16165 (let ((reftex-docstruct-symbol 'rds)
16166 (reftex-cite-format "\\cite{%l}")
16167 rds bib)
16168 (save-excursion
16169 (save-restriction
16170 (widen)
16171 (let ((case-fold-search t)
16172 (re "^#\\+bibliography:[ \t]+\\([^ \t\n]+\\)"))
16173 (if (not (save-excursion
16174 (or (re-search-forward re nil t)
16175 (re-search-backward re nil t))))
16176 (error "No bibliography defined in file")
16177 (setq bib (concat (match-string 1) ".bib")
16178 rds (list (list 'bib bib)))))))
16179 (call-interactively 'reftex-citation)))
16180
16181 ;;;; Functions extending outline functionality
16182
16183 (defun org-beginning-of-line (&optional arg)
16184 "Go to the beginning of the current line. If that is invisible, continue
16185 to a visible line beginning. This makes the function of C-a more intuitive.
16186 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16187 first attempt, and only move to after the tags when the cursor is already
16188 beyond the end of the headline."
16189 (interactive "P")
16190 (let ((pos (point))
16191 (special (if (consp org-special-ctrl-a/e)
16192 (car org-special-ctrl-a/e)
16193 org-special-ctrl-a/e))
16194 refpos)
16195 (if (org-bound-and-true-p line-move-visual)
16196 (beginning-of-visual-line 1)
16197 (beginning-of-line 1))
16198 (if (and arg (fboundp 'move-beginning-of-line))
16199 (call-interactively 'move-beginning-of-line)
16200 (if (bobp)
16201 nil
16202 (backward-char 1)
16203 (if (org-invisible-p)
16204 (while (and (not (bobp)) (org-invisible-p))
16205 (backward-char 1)
16206 (beginning-of-line 1))
16207 (forward-char 1))))
16208 (when special
16209 (cond
16210 ((and (looking-at org-complex-heading-regexp)
16211 (= (char-after (match-end 1)) ?\ ))
16212 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
16213 (point-at-eol)))
16214 (goto-char
16215 (if (eq special t)
16216 (cond ((> pos refpos) refpos)
16217 ((= pos (point)) refpos)
16218 (t (point)))
16219 (cond ((> pos (point)) (point))
16220 ((not (eq last-command this-command)) (point))
16221 (t refpos)))))
16222 ((org-at-item-p)
16223 (goto-char
16224 (if (eq special t)
16225 (cond ((> pos (match-end 4)) (match-end 4))
16226 ((= pos (point)) (match-end 4))
16227 (t (point)))
16228 (cond ((> pos (point)) (point))
16229 ((not (eq last-command this-command)) (point))
16230 (t (match-end 4))))))))
16231 (org-no-warnings
16232 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16233
16234 (defun org-end-of-line (&optional arg)
16235 "Go to the end of the line.
16236 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
16237 first attempt, and only move to after the tags when the cursor is already
16238 beyond the end of the headline."
16239 (interactive "P")
16240 (let ((special (if (consp org-special-ctrl-a/e)
16241 (cdr org-special-ctrl-a/e)
16242 org-special-ctrl-a/e)))
16243 (if (or (not special)
16244 (not (org-on-heading-p))
16245 arg)
16246 (call-interactively
16247 (cond ((org-bound-and-true-p line-move-visual) 'end-of-visual-line)
16248 ((fboundp 'move-end-of-line) 'move-end-of-line)
16249 (t 'end-of-line)))
16250 (let ((pos (point)))
16251 (beginning-of-line 1)
16252 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
16253 (if (eq special t)
16254 (if (or (< pos (match-beginning 1))
16255 (= pos (match-end 0)))
16256 (goto-char (match-beginning 1))
16257 (goto-char (match-end 0)))
16258 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
16259 (goto-char (match-end 0))
16260 (goto-char (match-beginning 1))))
16261 (call-interactively (if (fboundp 'move-end-of-line)
16262 'move-end-of-line
16263 'end-of-line)))))
16264 (org-no-warnings
16265 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
16266
16267 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
16268 (define-key org-mode-map "\C-e" 'org-end-of-line)
16269
16270 (defun org-backward-sentence (&optional arg)
16271 "Go to beginning of sentence, or beginning of table field.
16272 This will call `backward-sentence' or `org-table-beginning-of-field',
16273 depending on context."
16274 (interactive "P")
16275 (cond
16276 ((org-at-table-p) (call-interactively 'org-table-beginning-of-field))
16277 (t (call-interactively 'backward-sentence))))
16278
16279 (defun org-forward-sentence (&optional arg)
16280 "Go to end of sentence, or end of table field.
16281 This will call `forward-sentence' or `org-table-end-of-field',
16282 depending on context."
16283 (interactive "P")
16284 (cond
16285 ((org-at-table-p) (call-interactively 'org-table-end-of-field))
16286 (t (call-interactively 'forward-sentence))))
16287
16288 (define-key org-mode-map "\M-a" 'org-backward-sentence)
16289 (define-key org-mode-map "\M-e" 'org-forward-sentence)
16290
16291 (defun org-kill-line (&optional arg)
16292 "Kill line, to tags or end of line."
16293 (interactive "P")
16294 (cond
16295 ((or (not org-special-ctrl-k)
16296 (bolp)
16297 (not (org-on-heading-p)))
16298 (call-interactively 'kill-line))
16299 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
16300 (kill-region (point) (match-beginning 1))
16301 (org-set-tags nil t))
16302 (t (kill-region (point) (point-at-eol)))))
16303
16304 (define-key org-mode-map "\C-k" 'org-kill-line)
16305
16306 (defun org-yank (&optional arg)
16307 "Yank. If the kill is a subtree, treat it specially.
16308 This command will look at the current kill and check if is a single
16309 subtree, or a series of subtrees[1]. If it passes the test, and if the
16310 cursor is at the beginning of a line or after the stars of a currently
16311 empty headline, then the yank is handled specially. How exactly depends
16312 on the value of the following variables, both set by default.
16313
16314 org-yank-folded-subtrees
16315 When set, the subtree(s) will be folded after insertion, but only
16316 if doing so would now swallow text after the yanked text.
16317
16318 org-yank-adjusted-subtrees
16319 When set, the subtree will be promoted or demoted in order to
16320 fit into the local outline tree structure, which means that the level
16321 will be adjusted so that it becomes the smaller one of the two
16322 *visible* surrounding headings.
16323
16324 Any prefix to this command will cause `yank' to be called directly with
16325 no special treatment. In particular, a simple `C-u' prefix will just
16326 plainly yank the text as it is.
16327
16328 \[1] The test checks if the first non-white line is a heading
16329 and if there are no other headings with fewer stars."
16330 (interactive "P")
16331 (org-yank-generic 'yank arg))
16332
16333 (defun org-yank-generic (command arg)
16334 "Perform some yank-like command.
16335
16336 This function implements the behavior described in the `org-yank'
16337 documentation. However, it has been generalized to work for any
16338 interactive command with similar behavior."
16339
16340 ;; pretend to be command COMMAND
16341 (setq this-command command)
16342
16343 (if arg
16344 (call-interactively command)
16345
16346 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
16347 (and (org-kill-is-subtree-p)
16348 (or (bolp)
16349 (and (looking-at "[ \t]*$")
16350 (string-match
16351 "\\`\\*+\\'"
16352 (buffer-substring (point-at-bol) (point)))))))
16353 swallowp)
16354 (cond
16355 ((and subtreep org-yank-folded-subtrees)
16356 (let ((beg (point))
16357 end)
16358 (if (and subtreep org-yank-adjusted-subtrees)
16359 (org-paste-subtree nil nil 'for-yank)
16360 (call-interactively command))
16361
16362 (setq end (point))
16363 (goto-char beg)
16364 (when (and (bolp) subtreep
16365 (not (setq swallowp
16366 (org-yank-folding-would-swallow-text beg end))))
16367 (or (looking-at outline-regexp)
16368 (re-search-forward (concat "^" outline-regexp) end t))
16369 (while (and (< (point) end) (looking-at outline-regexp))
16370 (hide-subtree)
16371 (org-cycle-show-empty-lines 'folded)
16372 (condition-case nil
16373 (outline-forward-same-level 1)
16374 (error (goto-char end)))))
16375 (when swallowp
16376 (message
16377 "Inserted text not folded because that would swallow text"))
16378
16379 (goto-char end)
16380 (skip-chars-forward " \t\n\r")
16381 (beginning-of-line 1)
16382 (push-mark beg 'nomsg)))
16383 ((and subtreep org-yank-adjusted-subtrees)
16384 (let ((beg (point-at-bol)))
16385 (org-paste-subtree nil nil 'for-yank)
16386 (push-mark beg 'nomsg)))
16387 (t
16388 (call-interactively command))))))
16389
16390 (defun org-yank-folding-would-swallow-text (beg end)
16391 "Would hide-subtree at BEG swallow any text after END?"
16392 (let (level)
16393 (save-excursion
16394 (goto-char beg)
16395 (when (or (looking-at outline-regexp)
16396 (re-search-forward (concat "^" outline-regexp) end t))
16397 (setq level (org-outline-level)))
16398 (goto-char end)
16399 (skip-chars-forward " \t\r\n\v\f")
16400 (if (or (eobp)
16401 (and (bolp) (looking-at org-outline-regexp)
16402 (<= (org-outline-level) level)))
16403 nil ; Nothing would be swallowed
16404 t)))) ; something would swallow
16405
16406 (define-key org-mode-map "\C-y" 'org-yank)
16407
16408 (defun org-invisible-p ()
16409 "Check if point is at a character currently not visible."
16410 ;; Early versions of noutline don't have `outline-invisible-p'.
16411 (if (fboundp 'outline-invisible-p)
16412 (outline-invisible-p)
16413 (get-char-property (point) 'invisible)))
16414
16415 (defun org-invisible-p2 ()
16416 "Check if point is at a character currently not visible."
16417 (save-excursion
16418 (if (and (eolp) (not (bobp))) (backward-char 1))
16419 ;; Early versions of noutline don't have `outline-invisible-p'.
16420 (if (fboundp 'outline-invisible-p)
16421 (outline-invisible-p)
16422 (get-char-property (point) 'invisible))))
16423
16424 (defun org-back-to-heading (&optional invisible-ok)
16425 "Call `outline-back-to-heading', but provide a better error message."
16426 (condition-case nil
16427 (outline-back-to-heading invisible-ok)
16428 (error (error "Before first headline at position %d in buffer %s"
16429 (point) (current-buffer)))))
16430
16431 (defun org-before-first-heading-p ()
16432 "Before first heading?"
16433 (save-excursion
16434 (null (re-search-backward "^\\*+ " nil t))))
16435
16436 (defalias 'org-on-heading-p 'outline-on-heading-p)
16437 (defalias 'org-at-heading-p 'outline-on-heading-p)
16438 (defun org-at-heading-or-item-p ()
16439 (or (org-on-heading-p) (org-at-item-p)))
16440
16441 (defun org-on-target-p ()
16442 (or (org-in-regexp org-radio-target-regexp)
16443 (org-in-regexp org-target-regexp)))
16444
16445 (defun org-up-heading-all (arg)
16446 "Move to the heading line of which the present line is a subheading.
16447 This function considers both visible and invisible heading lines.
16448 With argument, move up ARG levels."
16449 (if (fboundp 'outline-up-heading-all)
16450 (outline-up-heading-all arg) ; emacs 21 version of outline.el
16451 (outline-up-heading arg t))) ; emacs 22 version of outline.el
16452
16453 (defun org-up-heading-safe ()
16454 "Move to the heading line of which the present line is a subheading.
16455 This version will not throw an error. It will return the level of the
16456 headline found, or nil if no higher level is found.
16457
16458 Also, this function will be a lot faster than `outline-up-heading',
16459 because it relies on stars being the outline starters. This can really
16460 make a significant difference in outlines with very many siblings."
16461 (let (start-level re)
16462 (org-back-to-heading t)
16463 (setq start-level (funcall outline-level))
16464 (if (equal start-level 1)
16465 nil
16466 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
16467 (if (re-search-backward re nil t)
16468 (funcall outline-level)))))
16469
16470 (defun org-first-sibling-p ()
16471 "Is this heading the first child of its parents?"
16472 (interactive)
16473 (let ((re (concat "^" outline-regexp))
16474 level l)
16475 (unless (org-at-heading-p t)
16476 (error "Not at a heading"))
16477 (setq level (funcall outline-level))
16478 (save-excursion
16479 (if (not (re-search-backward re nil t))
16480 t
16481 (setq l (funcall outline-level))
16482 (< l level)))))
16483
16484 (defun org-goto-sibling (&optional previous)
16485 "Goto the next sibling, even if it is invisible.
16486 When PREVIOUS is set, go to the previous sibling instead. Returns t
16487 when a sibling was found. When none is found, return nil and don't
16488 move point."
16489 (let ((fun (if previous 're-search-backward 're-search-forward))
16490 (pos (point))
16491 (re (concat "^" outline-regexp))
16492 level l)
16493 (when (condition-case nil (org-back-to-heading t) (error nil))
16494 (setq level (funcall outline-level))
16495 (catch 'exit
16496 (or previous (forward-char 1))
16497 (while (funcall fun re nil t)
16498 (setq l (funcall outline-level))
16499 (when (< l level) (goto-char pos) (throw 'exit nil))
16500 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
16501 (goto-char pos)
16502 nil))))
16503
16504 (defun org-show-siblings ()
16505 "Show all siblings of the current headline."
16506 (save-excursion
16507 (while (org-goto-sibling) (org-flag-heading nil)))
16508 (save-excursion
16509 (while (org-goto-sibling 'previous)
16510 (org-flag-heading nil))))
16511
16512 (defun org-show-hidden-entry ()
16513 "Show an entry where even the heading is hidden."
16514 (save-excursion
16515 (org-show-entry)))
16516
16517 (defun org-flag-heading (flag &optional entry)
16518 "Flag the current heading. FLAG non-nil means make invisible.
16519 When ENTRY is non-nil, show the entire entry."
16520 (save-excursion
16521 (org-back-to-heading t)
16522 ;; Check if we should show the entire entry
16523 (if entry
16524 (progn
16525 (org-show-entry)
16526 (save-excursion
16527 (and (outline-next-heading)
16528 (org-flag-heading nil))))
16529 (outline-flag-region (max (point-min) (1- (point)))
16530 (save-excursion (outline-end-of-heading) (point))
16531 flag))))
16532
16533 (defun org-get-next-sibling ()
16534 "Move to next heading of the same level, and return point.
16535 If there is no such heading, return nil.
16536 This is like outline-next-sibling, but invisible headings are ok."
16537 (let ((level (funcall outline-level)))
16538 (outline-next-heading)
16539 (while (and (not (eobp)) (> (funcall outline-level) level))
16540 (outline-next-heading))
16541 (if (or (eobp) (< (funcall outline-level) level))
16542 nil
16543 (point))))
16544
16545 (defun org-end-of-subtree (&optional invisible-OK to-heading)
16546 ;; This contains an exact copy of the original function, but it uses
16547 ;; `org-back-to-heading', to make it work also in invisible
16548 ;; trees. And is uses an invisible-OK argument.
16549 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
16550 ;; Furthermore, when used inside Org, finding the end of a large subtree
16551 ;; with many children and grandchildren etc, this can be much faster
16552 ;; than the outline version.
16553 (org-back-to-heading invisible-OK)
16554 (let ((first t)
16555 (level (funcall outline-level)))
16556 (if (and (org-mode-p) (< level 1000))
16557 ;; A true heading (not a plain list item), in Org-mode
16558 ;; This means we can easily find the end by looking
16559 ;; only for the right number of stars. Using a regexp to do
16560 ;; this is so much faster than using a Lisp loop.
16561 (let ((re (concat "^\\*\\{1," (int-to-string level) "\\} ")))
16562 (forward-char 1)
16563 (and (re-search-forward re nil 'move) (beginning-of-line 1)))
16564 ;; something else, do it the slow way
16565 (while (and (not (eobp))
16566 (or first (> (funcall outline-level) level)))
16567 (setq first nil)
16568 (outline-next-heading)))
16569 (unless to-heading
16570 (if (memq (preceding-char) '(?\n ?\^M))
16571 (progn
16572 ;; Go to end of line before heading
16573 (forward-char -1)
16574 (if (memq (preceding-char) '(?\n ?\^M))
16575 ;; leave blank line before heading
16576 (forward-char -1))))))
16577 (point))
16578
16579 (defadvice outline-end-of-subtree (around prefer-org-version activate compile)
16580 "Use Org version in org-mode, for dramatic speed-up."
16581 (if (eq major-mode 'org-mode)
16582 (progn
16583 (org-end-of-subtree nil t)
16584 (backward-char 1))
16585 ad-do-it))
16586
16587 (defun org-forward-same-level (arg &optional invisible-ok)
16588 "Move forward to the arg'th subheading at same level as this one.
16589 Stop at the first and last subheadings of a superior heading."
16590 (interactive "p")
16591 (org-back-to-heading invisible-ok)
16592 (org-on-heading-p)
16593 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16594 (re (format "^\\*\\{1,%d\\} " level))
16595 l)
16596 (forward-char 1)
16597 (while (> arg 0)
16598 (while (and (re-search-forward re nil 'move)
16599 (setq l (- (match-end 0) (match-beginning 0) 1))
16600 (= l level)
16601 (not invisible-ok)
16602 (org-invisible-p))
16603 (if (< l level) (setq arg 1)))
16604 (setq arg (1- arg)))
16605 (beginning-of-line 1)))
16606
16607 (defun org-backward-same-level (arg &optional invisible-ok)
16608 "Move backward to the arg'th subheading at same level as this one.
16609 Stop at the first and last subheadings of a superior heading."
16610 (interactive "p")
16611 (org-back-to-heading)
16612 (org-on-heading-p)
16613 (let* ((level (- (match-end 0) (match-beginning 0) 1))
16614 (re (format "^\\*\\{1,%d\\} " level))
16615 l)
16616 (while (> arg 0)
16617 (while (and (re-search-backward re nil 'move)
16618 (setq l (- (match-end 0) (match-beginning 0) 1))
16619 (= l level)
16620 (not invisible-ok)
16621 (org-invisible-p))
16622 (if (< l level) (setq arg 1)))
16623 (setq arg (1- arg)))))
16624
16625 (defun org-show-subtree ()
16626 "Show everything after this heading at deeper levels."
16627 (outline-flag-region
16628 (point)
16629 (save-excursion
16630 (outline-end-of-subtree) (outline-next-heading) (point))
16631 nil))
16632
16633 (defun org-show-entry ()
16634 "Show the body directly following this heading.
16635 Show the heading too, if it is currently invisible."
16636 (interactive)
16637 (save-excursion
16638 (condition-case nil
16639 (progn
16640 (org-back-to-heading t)
16641 (outline-flag-region
16642 (max (point-min) (1- (point)))
16643 (save-excursion
16644 (if (re-search-forward
16645 (concat "[\r\n]\\(" outline-regexp "\\)") nil t)
16646 (match-beginning 1)
16647 (point-max)))
16648 nil)
16649 (org-cycle-hide-drawers 'children))
16650 (error nil))))
16651
16652 (defun org-make-options-regexp (kwds &optional extra)
16653 "Make a regular expression for keyword lines."
16654 (concat
16655 "^"
16656 "#?[ \t]*\\+\\("
16657 (mapconcat 'regexp-quote kwds "\\|")
16658 (if extra (concat "\\|" extra))
16659 "\\):[ \t]*"
16660 "\\(.*\\)"))
16661
16662 ;; Make isearch reveal the necessary context
16663 (defun org-isearch-end ()
16664 "Reveal context after isearch exits."
16665 (when isearch-success ; only if search was successful
16666 (if (featurep 'xemacs)
16667 ;; Under XEmacs, the hook is run in the correct place,
16668 ;; we directly show the context.
16669 (org-show-context 'isearch)
16670 ;; In Emacs the hook runs *before* restoring the overlays.
16671 ;; So we have to use a one-time post-command-hook to do this.
16672 ;; (Emacs 22 has a special variable, see function `org-mode')
16673 (unless (and (boundp 'isearch-mode-end-hook-quit)
16674 isearch-mode-end-hook-quit)
16675 ;; Only when the isearch was not quitted.
16676 (org-add-hook 'post-command-hook 'org-isearch-post-command
16677 'append 'local)))))
16678
16679 (defun org-isearch-post-command ()
16680 "Remove self from hook, and show context."
16681 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
16682 (org-show-context 'isearch))
16683
16684
16685 ;;;; Integration with and fixes for other packages
16686
16687 ;;; Imenu support
16688
16689 (defvar org-imenu-markers nil
16690 "All markers currently used by Imenu.")
16691 (make-variable-buffer-local 'org-imenu-markers)
16692
16693 (defun org-imenu-new-marker (&optional pos)
16694 "Return a new marker for use by Imenu, and remember the marker."
16695 (let ((m (make-marker)))
16696 (move-marker m (or pos (point)))
16697 (push m org-imenu-markers)
16698 m))
16699
16700 (defun org-imenu-get-tree ()
16701 "Produce the index for Imenu."
16702 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
16703 (setq org-imenu-markers nil)
16704 (let* ((n org-imenu-depth)
16705 (re (concat "^" outline-regexp))
16706 (subs (make-vector (1+ n) nil))
16707 (last-level 0)
16708 m level head)
16709 (save-excursion
16710 (save-restriction
16711 (widen)
16712 (goto-char (point-max))
16713 (while (re-search-backward re nil t)
16714 (setq level (org-reduced-level (funcall outline-level)))
16715 (when (<= level n)
16716 (looking-at org-complex-heading-regexp)
16717 (setq head (org-link-display-format
16718 (org-match-string-no-properties 4))
16719 m (org-imenu-new-marker))
16720 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
16721 (if (>= level last-level)
16722 (push (cons head m) (aref subs level))
16723 (push (cons head (aref subs (1+ level))) (aref subs level))
16724 (loop for i from (1+ level) to n do (aset subs i nil)))
16725 (setq last-level level)))))
16726 (aref subs 1)))
16727
16728 (eval-after-load "imenu"
16729 '(progn
16730 (add-hook 'imenu-after-jump-hook
16731 (lambda ()
16732 (if (eq major-mode 'org-mode)
16733 (org-show-context 'org-goto))))))
16734
16735 (defun org-link-display-format (link)
16736 "Replace a link with either the description, or the link target
16737 if no description is present"
16738 (save-match-data
16739 (if (string-match org-bracket-link-analytic-regexp link)
16740 (replace-match (or (match-string 5 link)
16741 (concat (match-string 1 link)
16742 (match-string 3 link)))
16743 nil nil link)
16744 link)))
16745
16746 ;; Speedbar support
16747
16748 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
16749 "Overlay marking the agenda restriction line in speedbar.")
16750 (org-overlay-put org-speedbar-restriction-lock-overlay
16751 'face 'org-agenda-restriction-lock)
16752 (org-overlay-put org-speedbar-restriction-lock-overlay
16753 'help-echo "Agendas are currently limited to this item.")
16754 (org-detach-overlay org-speedbar-restriction-lock-overlay)
16755
16756 (defun org-speedbar-set-agenda-restriction ()
16757 "Restrict future agenda commands to the location at point in speedbar.
16758 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
16759 (interactive)
16760 (require 'org-agenda)
16761 (let (p m tp np dir txt)
16762 (cond
16763 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16764 'org-imenu t))
16765 (setq m (get-text-property p 'org-imenu-marker))
16766 (save-excursion
16767 (save-restriction
16768 (set-buffer (marker-buffer m))
16769 (goto-char m)
16770 (org-agenda-set-restriction-lock 'subtree))))
16771 ((setq p (text-property-any (point-at-bol) (point-at-eol)
16772 'speedbar-function 'speedbar-find-file))
16773 (setq tp (previous-single-property-change
16774 (1+ p) 'speedbar-function)
16775 np (next-single-property-change
16776 tp 'speedbar-function)
16777 dir (speedbar-line-directory)
16778 txt (buffer-substring-no-properties (or tp (point-min))
16779 (or np (point-max))))
16780 (save-excursion
16781 (save-restriction
16782 (set-buffer (find-file-noselect
16783 (let ((default-directory dir))
16784 (expand-file-name txt))))
16785 (unless (org-mode-p)
16786 (error "Cannot restrict to non-Org-mode file"))
16787 (org-agenda-set-restriction-lock 'file))))
16788 (t (error "Don't know how to restrict Org-mode's agenda")))
16789 (org-move-overlay org-speedbar-restriction-lock-overlay
16790 (point-at-bol) (point-at-eol))
16791 (setq current-prefix-arg nil)
16792 (org-agenda-maybe-redo)))
16793
16794 (eval-after-load "speedbar"
16795 '(progn
16796 (speedbar-add-supported-extension ".org")
16797 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
16798 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
16799 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
16800 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
16801 (add-hook 'speedbar-visiting-tag-hook
16802 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
16803
16804
16805 ;;; Fixes and Hacks for problems with other packages
16806
16807 ;; Make flyspell not check words in links, to not mess up our keymap
16808 (defun org-mode-flyspell-verify ()
16809 "Don't let flyspell put overlays at active buttons."
16810 (and (not (get-text-property (point) 'keymap))
16811 (not (get-text-property (point) 'org-no-flyspell))))
16812
16813 (defun org-remove-flyspell-overlays-in (beg end)
16814 "Remove flyspell overlays in region."
16815 (and (org-bound-and-true-p flyspell-mode)
16816 (fboundp 'flyspell-delete-region-overlays)
16817 (flyspell-delete-region-overlays beg end))
16818 (add-text-properties beg end '(org-no-flyspell t)))
16819
16820 ;; Make `bookmark-jump' show the jump location if it was hidden.
16821 (eval-after-load "bookmark"
16822 '(if (boundp 'bookmark-after-jump-hook)
16823 ;; We can use the hook
16824 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
16825 ;; Hook not available, use advice
16826 (defadvice bookmark-jump (after org-make-visible activate)
16827 "Make the position visible."
16828 (org-bookmark-jump-unhide))))
16829
16830 ;; Make sure saveplace show the location if it was hidden
16831 (eval-after-load "saveplace"
16832 '(defadvice save-place-find-file-hook (after org-make-visible activate)
16833 "Make the position visible."
16834 (org-bookmark-jump-unhide)))
16835
16836 (defun org-bookmark-jump-unhide ()
16837 "Unhide the current position, to show the bookmark location."
16838 (and (org-mode-p)
16839 (or (org-invisible-p)
16840 (save-excursion (goto-char (max (point-min) (1- (point))))
16841 (org-invisible-p)))
16842 (org-show-context 'bookmark-jump)))
16843
16844 ;; Make session.el ignore our circular variable
16845 (eval-after-load "session"
16846 '(add-to-list 'session-globals-exclude 'org-mark-ring))
16847
16848 ;;;; Experimental code
16849
16850 (defun org-closed-in-range ()
16851 "Sparse tree of items closed in a certain time range.
16852 Still experimental, may disappear in the future."
16853 (interactive)
16854 ;; Get the time interval from the user.
16855 (let* ((time1 (time-to-seconds
16856 (org-read-date nil 'to-time nil "Starting date: ")))
16857 (time2 (time-to-seconds
16858 (org-read-date nil 'to-time nil "End date:")))
16859 ;; callback function
16860 (callback (lambda ()
16861 (let ((time
16862 (time-to-seconds
16863 (apply 'encode-time
16864 (org-parse-time-string
16865 (match-string 1))))))
16866 ;; check if time in interval
16867 (and (>= time time1) (<= time time2))))))
16868 ;; make tree, check each match with the callback
16869 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
16870
16871 ;;;; Finish up
16872
16873 (provide 'org)
16874
16875 (run-hooks 'org-load-hook)
16876
16877 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
16878
16879 ;;; org.el ends here