Fix grammar in description of org-refile-targets
[org-mode.git] / lisp / org.el
blob82db6fcbfed082e1ec693ffb3a114ec240a0b88c
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.21trans
11 ;; This file is part of GNU Emacs.
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.
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.
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 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
27 ;;; Commentary:
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.
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.
47 ;; Installation and Activation
48 ;; ---------------------------
49 ;; See the corresponding sections in the manual at
51 ;; http://orgmode.org/org.html#Installation
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.
61 ;; A list of recent changes can be found at
62 ;; http://orgmode.org/Changes.html
64 ;;; Code:
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)
71 ;;;; Require other packages
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)
87 (require 'org-macs)
88 (require 'org-compat)
89 (require 'org-faces)
90 (require 'org-list)
91 (require 'org-footnote)
93 ;;;; Customization variables
95 ;;; Version
97 (defconst org-version "6.21trans"
98 "The version number of the file org.el.")
100 (defun org-version (&optional here)
101 "Show the org-mode version in the echo area.
102 With prefix arg HERE, insert it at point."
103 (interactive "P")
104 (let ((version (format "Org-mode version %s" org-version)))
105 (message version)
106 (if here
107 (insert version))))
109 ;;; Compatibility constants
111 ;;; The custom variables
113 (defgroup org nil
114 "Outline-based notes management and organizer."
115 :tag "Org"
116 :group 'outlines
117 :group 'hypermedia
118 :group 'calendar)
120 (defcustom org-load-hook nil
121 "Hook that is run after org.el has been loaded."
122 :group 'org
123 :type 'hook)
125 (defvar org-modules) ; defined below
126 (defvar org-modules-loaded nil
127 "Have the modules been loaded already?")
129 (defun org-load-modules-maybe (&optional force)
130 "Load all extensions listed in `org-modules'."
131 (when (or force (not org-modules-loaded))
132 (mapc (lambda (ext)
133 (condition-case nil (require ext)
134 (error (message "Problems while trying to load feature `%s'" ext))))
135 org-modules)
136 (setq org-modules-loaded t)))
138 (defun org-set-modules (var value)
139 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
140 (set var value)
141 (when (featurep 'org)
142 (org-load-modules-maybe 'force)))
144 (when (org-bound-and-true-p org-modules)
145 (let ((a (member 'org-infojs org-modules)))
146 (and a (setcar a 'org-jsinfo))))
148 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-w3m org-wl)
149 "Modules that should always be loaded together with org.el.
150 If a description starts with <C>, the file is not part of Emacs
151 and loading it will require that you have downloaded and properly installed
152 the org-mode distribution.
154 You can also use this system to load external packages (i.e. neither Org
155 core modules, not modules from the CONTRIB directory). Just add symbols
156 to the end of the list. If the package is called org-xyz.el, then you need
157 to add the symbol `xyz', and the package must have a call to
159 (provide 'org-xyz)"
160 :group 'org
161 :set 'org-set-modules
162 :type
163 '(set :greedy t
164 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
165 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
166 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
167 (const :tag " id: Global IDs for identifying entries" org-id)
168 (const :tag " info: Links to Info nodes" org-info)
169 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
170 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
171 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
172 (const :tag " mew Links to Mew folders/messages" org-mew)
173 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
174 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
175 (const :tag " vm: Links to VM folders/messages" org-vm)
176 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
177 (const :tag " w3m: Special cut/past from w3m to Org." org-w3m)
178 (const :tag " mouse: Additional mouse support" org-mouse)
180 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
181 (const :tag "C annotation-helper: Call Remember directly from Browser" org-annotation-helper)
182 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
183 (const :tag "C browser-url: Store link, directly from Browser" org-browser-url)
184 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
185 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
186 (const :tag "C eval: Include command output as text" org-eval)
187 (const :tag "C eval-light: Evaluate inbuffer-code on demand" org-eval-light)
188 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
189 (const :tag "C exp-blocks: Pre-process blocks for export" org-exp-blocks)
190 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
191 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
192 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
193 (const :tag "C mtags: Support for muse-like tags" org-mtags)
194 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
195 (const :tag "C registry: A registry for Org links" org-registry)
196 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
197 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
198 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
199 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
200 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
202 (defcustom org-support-shift-select nil
203 "Non-nil means, make shift-cursor commands select text when possible.
205 In Emacs 23, when `shift-select-mode' is on, shifted cursor keys start
206 selecting a region, or enlarge thusly regions started in this way.
207 In Org-mode, in special contexts, these same keys are used for other
208 purposes, important enough to compete with shift selection. Org tries
209 to balance these needs by supporting `shift-select-mode' outside these
210 special contexts, under control of this variable.
212 The default of this variable is nil, to avoid confusing behavior. Shifted
213 cursor keys will then execute Org commands in the following contexts:
214 - on a headline, changing TODO state (left/right) and priority (up/down)
215 - on a time stamp, changing the time
216 - in a plain list item, changing the bullet type
217 - in a property definition line, switching between allowed values
218 - in the BEGIN line of a clock table (changing the time block).
219 Outside these contexts, the commands will throw an error.
221 When this variable is t and the cursor is not in a special context,
222 Org-mode will support shift-selection for making and enlarging regions.
223 To make this more effective, the bullet cycling will no longer happen
224 anywhere in an item line, but only if the cursor is exactly on the bullet.
226 If you set this variable to the symbol `always', then the keys
227 will not be special in headlines, property lines, and item lines, to make
228 shift selection work there as well. If this is what you want, you can
229 use the following alternative commands: `C-c C-t' and `C-c ,' to
230 change TODO state and priority, `C-u C-u C-c C-t' can be used to switch
231 TODO sets, `C-c -' to cycle item bullet types, and properties can be
232 edited by hand or in column view.
234 However, when the cursor is on a timestamp, shift-cursor commands
235 will still edit the time stamp - this is just too good to give up.
237 XEmacs user should have this variable set to nil, because shift-select-mode
238 is Emacs 23 only."
239 :group 'org
240 :type '(choice
241 (const :tag "Never" nil)
242 (const :tag "When outside special context" t)
243 (const :tag "Everywhere except timestamps" always)))
245 (defgroup org-startup nil
246 "Options concerning startup of Org-mode."
247 :tag "Org Startup"
248 :group 'org)
250 (defcustom org-startup-folded t
251 "Non-nil means, entering Org-mode will switch to OVERVIEW.
252 This can also be configured on a per-file basis by adding one of
253 the following lines anywhere in the buffer:
255 #+STARTUP: fold
256 #+STARTUP: nofold
257 #+STARTUP: content"
258 :group 'org-startup
259 :type '(choice
260 (const :tag "nofold: show all" nil)
261 (const :tag "fold: overview" t)
262 (const :tag "content: all headlines" content)))
264 (defcustom org-startup-truncated t
265 "Non-nil means, entering Org-mode will set `truncate-lines'.
266 This is useful since some lines containing links can be very long and
267 uninteresting. Also tables look terrible when wrapped."
268 :group 'org-startup
269 :type 'boolean)
271 (defcustom org-startup-align-all-tables nil
272 "Non-nil means, align all tables when visiting a file.
273 This is useful when the column width in tables is forced with <N> cookies
274 in table fields. Such tables will look correct only after the first re-align.
275 This can also be configured on a per-file basis by adding one of
276 the following lines anywhere in the buffer:
277 #+STARTUP: align
278 #+STARTUP: noalign"
279 :group 'org-startup
280 :type 'boolean)
282 (defcustom org-insert-mode-line-in-empty-file nil
283 "Non-nil means insert the first line setting Org-mode in empty files.
284 When the function `org-mode' is called interactively in an empty file, this
285 normally means that the file name does not automatically trigger Org-mode.
286 To ensure that the file will always be in Org-mode in the future, a
287 line enforcing Org-mode will be inserted into the buffer, if this option
288 has been set."
289 :group 'org-startup
290 :type 'boolean)
292 (defcustom org-replace-disputed-keys nil
293 "Non-nil means use alternative key bindings for some keys.
294 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
295 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
296 If you want to use Org-mode together with one of these other modes,
297 or more generally if you would like to move some Org-mode commands to
298 other keys, set this variable and configure the keys with the variable
299 `org-disputed-keys'.
301 This option is only relevant at load-time of Org-mode, and must be set
302 *before* org.el is loaded. Changing it requires a restart of Emacs to
303 become effective."
304 :group 'org-startup
305 :type 'boolean)
307 (defcustom org-use-extra-keys nil
308 "Non-nil means use extra key sequence definitions for certain
309 commands. This happens automatically if you run XEmacs or if
310 window-system is nil. This variable lets you do the same
311 manually. You must set it before loading org.
313 Example: on Carbon Emacs 22 running graphically, with an external
314 keyboard on a Powerbook, the default way of setting M-left might
315 not work for either Alt or ESC. Setting this variable will make
316 it work for ESC."
317 :group 'org-startup
318 :type 'boolean)
320 (if (fboundp 'defvaralias)
321 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
323 (defcustom org-disputed-keys
324 '(([(shift up)] . [(meta p)])
325 ([(shift down)] . [(meta n)])
326 ([(shift left)] . [(meta -)])
327 ([(shift right)] . [(meta +)])
328 ([(control shift right)] . [(meta shift +)])
329 ([(control shift left)] . [(meta shift -)]))
330 "Keys for which Org-mode and other modes compete.
331 This is an alist, cars are the default keys, second element specifies
332 the alternative to use when `org-replace-disputed-keys' is t.
334 Keys can be specified in any syntax supported by `define-key'.
335 The value of this option takes effect only at Org-mode's startup,
336 therefore you'll have to restart Emacs to apply it after changing."
337 :group 'org-startup
338 :type 'alist)
340 (defun org-key (key)
341 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
342 Or return the original if not disputed."
343 (if org-replace-disputed-keys
344 (let* ((nkey (key-description key))
345 (x (org-find-if (lambda (x)
346 (equal (key-description (car x)) nkey))
347 org-disputed-keys)))
348 (if x (cdr x) key))
349 key))
351 (defun org-find-if (predicate seq)
352 (catch 'exit
353 (while seq
354 (if (funcall predicate (car seq))
355 (throw 'exit (car seq))
356 (pop seq)))))
358 (defun org-defkey (keymap key def)
359 "Define a key, possibly translated, as returned by `org-key'."
360 (define-key keymap (org-key key) def))
362 (defcustom org-ellipsis nil
363 "The ellipsis to use in the Org-mode outline.
364 When nil, just use the standard three dots. When a string, use that instead,
365 When a face, use the standard 3 dots, but with the specified face.
366 The change affects only Org-mode (which will then use its own display table).
367 Changing this requires executing `M-x org-mode' in a buffer to become
368 effective."
369 :group 'org-startup
370 :type '(choice (const :tag "Default" nil)
371 (face :tag "Face" :value org-warning)
372 (string :tag "String" :value "...#")))
374 (defvar org-display-table nil
375 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
377 (defgroup org-keywords nil
378 "Keywords in Org-mode."
379 :tag "Org Keywords"
380 :group 'org)
382 (defcustom org-deadline-string "DEADLINE:"
383 "String to mark deadline entries.
384 A deadline is this string, followed by a time stamp. Should be a word,
385 terminated by a colon. You can insert a schedule keyword and
386 a timestamp with \\[org-deadline].
387 Changes become only effective after restarting Emacs."
388 :group 'org-keywords
389 :type 'string)
391 (defcustom org-scheduled-string "SCHEDULED:"
392 "String to mark scheduled TODO entries.
393 A schedule is this string, followed by a time stamp. Should be a word,
394 terminated by a colon. You can insert a schedule keyword and
395 a timestamp with \\[org-schedule].
396 Changes become only effective after restarting Emacs."
397 :group 'org-keywords
398 :type 'string)
400 (defcustom org-closed-string "CLOSED:"
401 "String used as the prefix for timestamps logging closing a TODO entry."
402 :group 'org-keywords
403 :type 'string)
405 (defcustom org-clock-string "CLOCK:"
406 "String used as prefix for timestamps clocking work hours on an item."
407 :group 'org-keywords
408 :type 'string)
410 (defcustom org-comment-string "COMMENT"
411 "Entries starting with this keyword will never be exported.
412 An entry can be toggled between COMMENT and normal with
413 \\[org-toggle-comment].
414 Changes become only effective after restarting Emacs."
415 :group 'org-keywords
416 :type 'string)
418 (defcustom org-quote-string "QUOTE"
419 "Entries starting with this keyword will be exported in fixed-width font.
420 Quoting applies only to the text in the entry following the headline, and does
421 not extend beyond the next headline, even if that is lower level.
422 An entry can be toggled between QUOTE and normal with
423 \\[org-toggle-fixed-width-section]."
424 :group 'org-keywords
425 :type 'string)
427 (defconst org-repeat-re
428 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
429 "Regular expression for specifying repeated events.
430 After a match, group 1 contains the repeat expression.")
432 (defgroup org-structure nil
433 "Options concerning the general structure of Org-mode files."
434 :tag "Org Structure"
435 :group 'org)
437 (defgroup org-reveal-location nil
438 "Options about how to make context of a location visible."
439 :tag "Org Reveal Location"
440 :group 'org-structure)
442 (defconst org-context-choice
443 '(choice
444 (const :tag "Always" t)
445 (const :tag "Never" nil)
446 (repeat :greedy t :tag "Individual contexts"
447 (cons
448 (choice :tag "Context"
449 (const agenda)
450 (const org-goto)
451 (const occur-tree)
452 (const tags-tree)
453 (const link-search)
454 (const mark-goto)
455 (const bookmark-jump)
456 (const isearch)
457 (const default))
458 (boolean))))
459 "Contexts for the reveal options.")
461 (defcustom org-show-hierarchy-above '((default . t))
462 "Non-nil means, show full hierarchy when revealing a location.
463 Org-mode often shows locations in an org-mode file which might have
464 been invisible before. When this is set, the hierarchy of headings
465 above the exposed location is shown.
466 Turning this off for example for sparse trees makes them very compact.
467 Instead of t, this can also be an alist specifying this option for different
468 contexts. Valid contexts are
469 agenda when exposing an entry from the agenda
470 org-goto when using the command `org-goto' on key C-c C-j
471 occur-tree when using the command `org-occur' on key C-c /
472 tags-tree when constructing a sparse tree based on tags matches
473 link-search when exposing search matches associated with a link
474 mark-goto when exposing the jump goal of a mark
475 bookmark-jump when exposing a bookmark location
476 isearch when exiting from an incremental search
477 default default for all contexts not set explicitly"
478 :group 'org-reveal-location
479 :type org-context-choice)
481 (defcustom org-show-following-heading '((default . nil))
482 "Non-nil means, show following heading when revealing a location.
483 Org-mode often shows locations in an org-mode file which might have
484 been invisible before. When this is set, the heading following the
485 match is shown.
486 Turning this off for example for sparse trees makes them very compact,
487 but makes it harder to edit the location of the match. In such a case,
488 use the command \\[org-reveal] to show more context.
489 Instead of t, this can also be an alist specifying this option for different
490 contexts. See `org-show-hierarchy-above' for valid contexts."
491 :group 'org-reveal-location
492 :type org-context-choice)
494 (defcustom org-show-siblings '((default . nil) (isearch t))
495 "Non-nil means, show all sibling heading when revealing a location.
496 Org-mode often shows locations in an org-mode file which might have
497 been invisible before. When this is set, the sibling of the current entry
498 heading are all made visible. If `org-show-hierarchy-above' is t,
499 the same happens on each level of the hierarchy above the current entry.
501 By default this is on for the isearch context, off for all other contexts.
502 Turning this off for example for sparse trees makes them very compact,
503 but makes it harder to edit the location of the match. In such a case,
504 use the command \\[org-reveal] to show more context.
505 Instead of t, this can also be an alist specifying this option for different
506 contexts. See `org-show-hierarchy-above' for valid contexts."
507 :group 'org-reveal-location
508 :type org-context-choice)
510 (defcustom org-show-entry-below '((default . nil))
511 "Non-nil means, show the entry below a headline when revealing a location.
512 Org-mode often shows locations in an org-mode file which might have
513 been invisible before. When this is set, the text below the headline that is
514 exposed is also shown.
516 By default this is off for all contexts.
517 Instead of t, this can also be an alist specifying this option for different
518 contexts. See `org-show-hierarchy-above' for valid contexts."
519 :group 'org-reveal-location
520 :type org-context-choice)
522 (defcustom org-indirect-buffer-display 'other-window
523 "How should indirect tree buffers be displayed?
524 This applies to indirect buffers created with the commands
525 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
526 Valid values are:
527 current-window Display in the current window
528 other-window Just display in another window.
529 dedicated-frame Create one new frame, and re-use it each time.
530 new-frame Make a new frame each time. Note that in this case
531 previously-made indirect buffers are kept, and you need to
532 kill these buffers yourself."
533 :group 'org-structure
534 :group 'org-agenda-windows
535 :type '(choice
536 (const :tag "In current window" current-window)
537 (const :tag "In current frame, other window" other-window)
538 (const :tag "Each time a new frame" new-frame)
539 (const :tag "One dedicated frame" dedicated-frame)))
541 (defgroup org-cycle nil
542 "Options concerning visibility cycling in Org-mode."
543 :tag "Org Cycle"
544 :group 'org-structure)
546 (defcustom org-drawers '("PROPERTIES" "CLOCK")
547 "Names of drawers. Drawers are not opened by cycling on the headline above.
548 Drawers only open with a TAB on the drawer line itself. A drawer looks like
549 this:
550 :DRAWERNAME:
551 .....
552 :END:
553 The drawer \"PROPERTIES\" is special for capturing properties through
554 the property API.
556 Drawers can be defined on the per-file basis with a line like:
558 #+DRAWERS: HIDDEN STATE PROPERTIES"
559 :group 'org-structure
560 :type '(repeat (string :tag "Drawer Name")))
562 (defcustom org-cycle-global-at-bob nil
563 "Cycle globally if cursor is at beginning of buffer and not at a headline.
564 This makes it possible to do global cycling without having to use S-TAB or
565 C-u TAB. For this special case to work, the first line of the buffer
566 must not be a headline - it may be empty or some other text. When used in
567 this way, `org-cycle-hook' is disables temporarily, to make sure the
568 cursor stays at the beginning of the buffer.
569 When this option is nil, don't do anything special at the beginning
570 of the buffer."
571 :group 'org-cycle
572 :type 'boolean)
574 (defcustom org-cycle-emulate-tab t
575 "Where should `org-cycle' emulate TAB.
576 nil Never
577 white Only in completely white lines
578 whitestart Only at the beginning of lines, before the first non-white char
579 t Everywhere except in headlines
580 exc-hl-bol Everywhere except at the start of a headline
581 If TAB is used in a place where it does not emulate TAB, the current subtree
582 visibility is cycled."
583 :group 'org-cycle
584 :type '(choice (const :tag "Never" nil)
585 (const :tag "Only in completely white lines" white)
586 (const :tag "Before first char in a line" whitestart)
587 (const :tag "Everywhere except in headlines" t)
588 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
591 (defcustom org-cycle-separator-lines 2
592 "Number of empty lines needed to keep an empty line between collapsed trees.
593 If you leave an empty line between the end of a subtree and the following
594 headline, this empty line is hidden when the subtree is folded.
595 Org-mode will leave (exactly) one empty line visible if the number of
596 empty lines is equal or larger to the number given in this variable.
597 So the default 2 means, at least 2 empty lines after the end of a subtree
598 are needed to produce free space between a collapsed subtree and the
599 following headline.
601 Special case: when 0, never leave empty lines in collapsed view."
602 :group 'org-cycle
603 :type 'integer)
604 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
606 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
607 org-cycle-hide-drawers
608 org-cycle-show-empty-lines
609 org-optimize-window-after-visibility-change)
610 "Hook that is run after `org-cycle' has changed the buffer visibility.
611 The function(s) in this hook must accept a single argument which indicates
612 the new state that was set by the most recent `org-cycle' command. The
613 argument is a symbol. After a global state change, it can have the values
614 `overview', `content', or `all'. After a local state change, it can have
615 the values `folded', `children', or `subtree'."
616 :group 'org-cycle
617 :type 'hook)
619 (defgroup org-edit-structure nil
620 "Options concerning structure editing in Org-mode."
621 :tag "Org Edit Structure"
622 :group 'org-structure)
624 (defcustom org-odd-levels-only nil
625 "Non-nil means, skip even levels and only use odd levels for the outline.
626 This has the effect that two stars are being added/taken away in
627 promotion/demotion commands. It also influences how levels are
628 handled by the exporters.
629 Changing it requires restart of `font-lock-mode' to become effective
630 for fontification also in regions already fontified.
631 You may also set this on a per-file basis by adding one of the following
632 lines to the buffer:
634 #+STARTUP: odd
635 #+STARTUP: oddeven"
636 :group 'org-edit-structure
637 :group 'org-font-lock
638 :type 'boolean)
640 (defcustom org-adapt-indentation t
641 "Non-nil means, adapt indentation when promoting and demoting.
642 When this is set and the *entire* text in an entry is indented, the
643 indentation is increased by one space in a demotion command, and
644 decreased by one in a promotion command. If any line in the entry
645 body starts at column 0, indentation is not changed at all."
646 :group 'org-edit-structure
647 :type 'boolean)
649 (defcustom org-special-ctrl-a/e nil
650 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
651 When t, `C-a' will bring back the cursor to the beginning of the
652 headline text, i.e. after the stars and after a possible TODO keyword.
653 In an item, this will be the position after the bullet.
654 When the cursor is already at that position, another `C-a' will bring
655 it to the beginning of the line.
656 `C-e' will jump to the end of the headline, ignoring the presence of tags
657 in the headline. A second `C-e' will then jump to the true end of the
658 line, after any tags.
659 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
660 and only a directly following, identical keypress will bring the cursor
661 to the special positions."
662 :group 'org-edit-structure
663 :type '(choice
664 (const :tag "off" nil)
665 (const :tag "after bullet first" t)
666 (const :tag "border first" reversed)))
668 (if (fboundp 'defvaralias)
669 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
671 (defcustom org-special-ctrl-k nil
672 "Non-nil means `C-k' will behave specially in headlines.
673 When nil, `C-k' will call the default `kill-line' command.
674 When t, the following will happen while the cursor is in the headline:
676 - When the cursor is at the beginning of a headline, kill the entire
677 line and possible the folded subtree below the line.
678 - When in the middle of the headline text, kill the headline up to the tags.
679 - When after the headline text, kill the tags."
680 :group 'org-edit-structure
681 :type 'boolean)
683 (defcustom org-yank-folded-subtrees t
684 "Non-nil means, when yanking subtrees, fold them.
685 If the kill is a single subtree, or a sequence of subtrees, i.e. if
686 it starts with a heading and all other headings in it are either children
687 or siblings, then fold all the subtrees. However, do this only if no
688 text after the yank would be swallowed into a folded tree by this action."
689 :group 'org-edit-structure
690 :type 'boolean)
692 (defcustom org-yank-adjusted-subtrees nil
693 "Non-nil means, when yanking subtrees, adjust the level.
694 With this setting, `org-paste-subtree' is used to insert the subtree, see
695 this function for details."
696 :group 'org-edit-structure
697 :type 'boolean)
699 (defcustom org-M-RET-may-split-line '((default . t))
700 "Non-nil means, M-RET will split the line at the cursor position.
701 When nil, it will go to the end of the line before making a
702 new line.
703 You may also set this option in a different way for different
704 contexts. Valid contexts are:
706 headline when creating a new headline
707 item when creating a new item
708 table in a table field
709 default the value to be used for all contexts not explicitly
710 customized"
711 :group 'org-structure
712 :group 'org-table
713 :type '(choice
714 (const :tag "Always" t)
715 (const :tag "Never" nil)
716 (repeat :greedy t :tag "Individual contexts"
717 (cons
718 (choice :tag "Context"
719 (const headline)
720 (const item)
721 (const table)
722 (const default))
723 (boolean)))))
726 (defcustom org-insert-heading-respect-content nil
727 "Non-nil means, insert new headings after the current subtree.
728 When nil, the new heading is created directly after the current line.
729 The commands \\[org-insert-heading-respect-content] and
730 \\[org-insert-todo-heading-respect-content] turn this variable on
731 for the duration of the command."
732 :group 'org-structure
733 :type 'boolean)
735 (defcustom org-blank-before-new-entry '((heading . auto)
736 (plain-list-item . auto))
737 "Should `org-insert-heading' leave a blank line before new heading/item?
738 The value is an alist, with `heading' and `plain-list-item' as car,
739 and a boolean flag as cdr."
740 :group 'org-edit-structure
741 :type '(list
742 (cons (const heading)
743 (choice (const :tag "Never" nil)
744 (const :tag "Always" t)
745 (const :tag "Auto" auto)))
746 (cons (const plain-list-item)
747 (choice (const :tag "Never" nil)
748 (const :tag "Always" t)
749 (const :tag "Auto" auto)))))
751 (defcustom org-insert-heading-hook nil
752 "Hook being run after inserting a new heading."
753 :group 'org-edit-structure
754 :type 'hook)
756 (defcustom org-enable-fixed-width-editor t
757 "Non-nil means, lines starting with \":\" are treated as fixed-width.
758 This currently only means, they are never auto-wrapped.
759 When nil, such lines will be treated like ordinary lines.
760 See also the QUOTE keyword."
761 :group 'org-edit-structure
762 :type 'boolean)
764 (defcustom org-edit-src-region-extra nil
765 "Additional regexps to identify regions for editing with `org-edit-src-code'.
766 For examples see the function `org-edit-src-find-region-and-lang'.
767 The regular expression identifying the begin marker should end with a newline,
768 and the regexp marking the end line should start with a newline, to make sure
769 there are kept outside the narrowed region."
770 :group 'org-edit-structure
771 :type '(repeat
772 (list
773 (regexp :tag "begin regexp")
774 (regexp :tag "end regexp")
775 (choice :tag "language"
776 (string :tag "specify")
777 (integer :tag "from match group")
778 (const :tag "from `lang' element")
779 (const :tag "from `style' element")))))
781 (defcustom org-coderef-label-format "(ref:%s)"
782 "The default coderef format.
783 This format string will be used to search for coderef labels in literal
784 examples (EXAMPLE and SRC blocks). The format can be overwritten
785 an individual literal example with the -f option, like
787 #+BEGIN_SRC pascal +n -r -l \"((%s))\"
789 #+END_SRC
791 If you want to use this for HTML export, make sure that the format does
792 not introduce special font-locking, and avoid the HTML special
793 characters `<', `>', and `&'. The reason for this restriction is that
794 the labels are searched for only after htmlize has done its job."
795 :group 'org-edit-structure ; FIXME this is not in the right group
796 :type 'string)
798 (defcustom org-edit-fixed-width-region-mode 'artist-mode
799 "The mode that should be used to edit fixed-width regions.
800 These are the regions where each line starts with a colon."
801 :group 'org-edit-structure
802 :type '(choice
803 (const artist-mode)
804 (const picture-mode)
805 (const fundamental-mode)
806 (function :tag "Other (specify)")))
808 (defcustom org-goto-auto-isearch t
809 "Non-nil means, typing characters in org-goto starts incremental search."
810 :group 'org-edit-structure
811 :type 'boolean)
813 (defgroup org-sparse-trees nil
814 "Options concerning sparse trees in Org-mode."
815 :tag "Org Sparse Trees"
816 :group 'org-structure)
818 (defcustom org-highlight-sparse-tree-matches t
819 "Non-nil means, highlight all matches that define a sparse tree.
820 The highlights will automatically disappear the next time the buffer is
821 changed by an edit command."
822 :group 'org-sparse-trees
823 :type 'boolean)
825 (defcustom org-remove-highlights-with-change t
826 "Non-nil means, any change to the buffer will remove temporary highlights.
827 Such highlights are created by `org-occur' and `org-clock-display'.
828 When nil, `C-c C-c needs to be used to get rid of the highlights.
829 The highlights created by `org-preview-latex-fragment' always need
830 `C-c C-c' to be removed."
831 :group 'org-sparse-trees
832 :group 'org-time
833 :type 'boolean)
836 (defcustom org-occur-hook '(org-first-headline-recenter)
837 "Hook that is run after `org-occur' has constructed a sparse tree.
838 This can be used to recenter the window to show as much of the structure
839 as possible."
840 :group 'org-sparse-trees
841 :type 'hook)
843 (defgroup org-imenu-and-speedbar nil
844 "Options concerning imenu and speedbar in Org-mode."
845 :tag "Org Imenu and Speedbar"
846 :group 'org-structure)
848 (defcustom org-imenu-depth 2
849 "The maximum level for Imenu access to Org-mode headlines.
850 This also applied for speedbar access."
851 :group 'org-imenu-and-speedbar
852 :type 'number)
854 (defgroup org-table nil
855 "Options concerning tables in Org-mode."
856 :tag "Org Table"
857 :group 'org)
859 (defcustom org-enable-table-editor 'optimized
860 "Non-nil means, lines starting with \"|\" are handled by the table editor.
861 When nil, such lines will be treated like ordinary lines.
863 When equal to the symbol `optimized', the table editor will be optimized to
864 do the following:
865 - Automatic overwrite mode in front of whitespace in table fields.
866 This makes the structure of the table stay in tact as long as the edited
867 field does not exceed the column width.
868 - Minimize the number of realigns. Normally, the table is aligned each time
869 TAB or RET are pressed to move to another field. With optimization this
870 happens only if changes to a field might have changed the column width.
871 Optimization requires replacing the functions `self-insert-command',
872 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
873 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
874 very good at guessing when a re-align will be necessary, but you can always
875 force one with \\[org-ctrl-c-ctrl-c].
877 If you would like to use the optimized version in Org-mode, but the
878 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
880 This variable can be used to turn on and off the table editor during a session,
881 but in order to toggle optimization, a restart is required.
883 See also the variable `org-table-auto-blank-field'."
884 :group 'org-table
885 :type '(choice
886 (const :tag "off" nil)
887 (const :tag "on" t)
888 (const :tag "on, optimized" optimized)))
890 (defcustom org-table-tab-recognizes-table.el t
891 "Non-nil means, TAB will automatically notice a table.el table.
892 When it sees such a table, it moves point into it and - if necessary -
893 calls `table-recognize-table'."
894 :group 'org-table-editing
895 :type 'boolean)
897 (defgroup org-link nil
898 "Options concerning links in Org-mode."
899 :tag "Org Link"
900 :group 'org)
902 (defvar org-link-abbrev-alist-local nil
903 "Buffer-local version of `org-link-abbrev-alist', which see.
904 The value of this is taken from the #+LINK lines.")
905 (make-variable-buffer-local 'org-link-abbrev-alist-local)
907 (defcustom org-link-abbrev-alist nil
908 "Alist of link abbreviations.
909 The car of each element is a string, to be replaced at the start of a link.
910 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
911 links in Org-mode buffers can have an optional tag after a double colon, e.g.
913 [[linkkey:tag][description]]
915 If REPLACE is a string, the tag will simply be appended to create the link.
916 If the string contains \"%s\", the tag will be inserted there. Alternatively,
917 the placeholder \"%h\" will cause a url-encoded version of the tag to
918 be inserted at that point (see the function `url-hexify-string').
920 REPLACE may also be a function that will be called with the tag as the
921 only argument to create the link, which should be returned as a string.
923 See the manual for examples."
924 :group 'org-link
925 :type '(repeat
926 (cons
927 (string :tag "Protocol")
928 (choice
929 (string :tag "Format")
930 (function)))))
932 (defcustom org-descriptive-links t
933 "Non-nil means, hide link part and only show description of bracket links.
934 Bracket links are like [[link][description]]. This variable sets the initial
935 state in new org-mode buffers. The setting can then be toggled on a
936 per-buffer basis from the Org->Hyperlinks menu."
937 :group 'org-link
938 :type 'boolean)
940 (defcustom org-link-file-path-type 'adaptive
941 "How the path name in file links should be stored.
942 Valid values are:
944 relative Relative to the current directory, i.e. the directory of the file
945 into which the link is being inserted.
946 absolute Absolute path, if possible with ~ for home directory.
947 noabbrev Absolute path, no abbreviation of home directory.
948 adaptive Use relative path for files in the current directory and sub-
949 directories of it. For other files, use an absolute path."
950 :group 'org-link
951 :type '(choice
952 (const relative)
953 (const absolute)
954 (const noabbrev)
955 (const adaptive)))
957 (defcustom org-activate-links '(bracket angle plain radio tag date footnote)
958 "Types of links that should be activated in Org-mode files.
959 This is a list of symbols, each leading to the activation of a certain link
960 type. In principle, it does not hurt to turn on most link types - there may
961 be a small gain when turning off unused link types. The types are:
963 bracket The recommended [[link][description]] or [[link]] links with hiding.
964 angular Links in angular brackets that may contain whitespace like
965 <bbdb:Carsten Dominik>.
966 plain Plain links in normal text, no whitespace, like http://google.com.
967 radio Text that is matched by a radio target, see manual for details.
968 tag Tag settings in a headline (link to tag search).
969 date Time stamps (link to calendar).
970 footnote Footnote labels.
972 Changing this variable requires a restart of Emacs to become effective."
973 :group 'org-link
974 :type '(set :greedy t
975 (const :tag "Double bracket links (new style)" bracket)
976 (const :tag "Angular bracket links (old style)" angular)
977 (const :tag "Plain text links" plain)
978 (const :tag "Radio target matches" radio)
979 (const :tag "Tags" tag)
980 (const :tag "Timestamps" date)
981 (const :tag "Footnotes" footnote)))
983 (defcustom org-make-link-description-function nil
984 "Function to use to generate link descriptions from links. If
985 nil the link location will be used. This function must take two
986 parameters; the first is the link and the second the description
987 org-insert-link has generated, and should return the description
988 to use."
989 :group 'org-link
990 :type 'function)
992 (defgroup org-link-store nil
993 "Options concerning storing links in Org-mode."
994 :tag "Org Store Link"
995 :group 'org-link)
997 (defcustom org-email-link-description-format "Email %c: %.30s"
998 "Format of the description part of a link to an email or usenet message.
999 The following %-escapes will be replaced by corresponding information:
1001 %F full \"From\" field
1002 %f name, taken from \"From\" field, address if no name
1003 %T full \"To\" field
1004 %t first name in \"To\" field, address if no name
1005 %c correspondent. Usually \"from NAME\", but if you sent it yourself, it
1006 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
1007 %s subject
1008 %m message-id.
1010 You may use normal field width specification between the % and the letter.
1011 This is for example useful to limit the length of the subject.
1013 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
1014 :group 'org-link-store
1015 :type 'string)
1017 (defcustom org-from-is-user-regexp
1018 (let (r1 r2)
1019 (when (and user-mail-address (not (string= user-mail-address "")))
1020 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
1021 (when (and user-full-name (not (string= user-full-name "")))
1022 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
1023 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
1024 "Regexp matched against the \"From:\" header of an email or usenet message.
1025 It should match if the message is from the user him/herself."
1026 :group 'org-link-store
1027 :type 'regexp)
1029 (defcustom org-link-to-org-use-id 'create-if-interactive
1030 "Non-nil means, storing a link to an Org file will use entry IDs.
1032 Note that before this variable is even considered, org-id must be loaded,
1033 to please customize `org-modules' and turn it on.
1035 The variable can have the following values:
1037 t Create an ID if needed to make a link to the current entry.
1039 create-if-interactive
1040 If `org-store-link' is called directly (interactively, as a user
1041 command), do create an ID to support the link. But when doing the
1042 job for remember, only use the ID if it already exists. The
1043 purpose of this setting is to avoid proliferation of unwanted
1044 IDs, just because you happen to be in an Org file when you
1045 call `org-remember' that automatically and preemptively
1046 creates a link. If you do want to get an ID link in a remember
1047 template to an entry not having an ID, create it first by
1048 explicitly creating a link to it, using `C-c C-l' first.
1050 use-existing
1051 Use existing ID, do not create one.
1053 nil Never use an ID to make a link, instead link using a text search for
1054 the headline text."
1055 :group 'org-link-store
1056 :type '(choice
1057 (const :tag "Create ID to make link" t)
1058 (const :tag "Create if string link interactively"
1059 'create-if-interactive)
1060 (const :tag "Only use existing" 'use-existing)
1061 (const :tag "Do not use ID to create link" nil)))
1063 (defcustom org-context-in-file-links t
1064 "Non-nil means, file links from `org-store-link' contain context.
1065 A search string will be added to the file name with :: as separator and
1066 used to find the context when the link is activated by the command
1067 `org-open-at-point'.
1068 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
1069 negates this setting for the duration of the command."
1070 :group 'org-link-store
1071 :type 'boolean)
1073 (defcustom org-keep-stored-link-after-insertion nil
1074 "Non-nil means, keep link in list for entire session.
1076 The command `org-store-link' adds a link pointing to the current
1077 location to an internal list. These links accumulate during a session.
1078 The command `org-insert-link' can be used to insert links into any
1079 Org-mode file (offering completion for all stored links). When this
1080 option is nil, every link which has been inserted once using \\[org-insert-link]
1081 will be removed from the list, to make completing the unused links
1082 more efficient."
1083 :group 'org-link-store
1084 :type 'boolean)
1086 (defgroup org-link-follow nil
1087 "Options concerning following links in Org-mode."
1088 :tag "Org Follow Link"
1089 :group 'org-link)
1091 (defcustom org-link-translation-function nil
1092 "Function to translate links with different syntax to Org syntax.
1093 This can be used to translate links created for example by the Planner
1094 or emacs-wiki packages to Org syntax.
1095 The function must accept two parameters, a TYPE containing the link
1096 protocol name like \"rmail\" or \"gnus\" as a string, and the linked path,
1097 which is everything after the link protocol. It should return a cons
1098 with possibly modified values of type and path.
1099 Org contains a function for this, so if you set this variable to
1100 `org-translate-link-from-planner', you should be able follow many
1101 links created by planner."
1102 :group 'org-link-follow
1103 :type 'function)
1105 (defcustom org-follow-link-hook nil
1106 "Hook that is run after a link has been followed."
1107 :group 'org-link-follow
1108 :type 'hook)
1110 (defcustom org-tab-follows-link nil
1111 "Non-nil means, on links TAB will follow the link.
1112 Needs to be set before org.el is loaded."
1113 :group 'org-link-follow
1114 :type 'boolean)
1116 (defcustom org-return-follows-link nil
1117 "Non-nil means, on links RET will follow the link.
1118 Needs to be set before org.el is loaded."
1119 :group 'org-link-follow
1120 :type 'boolean)
1122 (defcustom org-mouse-1-follows-link
1123 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
1124 "Non-nil means, mouse-1 on a link will follow the link.
1125 A longer mouse click will still set point. Does not work on XEmacs.
1126 Needs to be set before org.el is loaded."
1127 :group 'org-link-follow
1128 :type 'boolean)
1130 (defcustom org-mark-ring-length 4
1131 "Number of different positions to be recorded in the ring
1132 Changing this requires a restart of Emacs to work correctly."
1133 :group 'org-link-follow
1134 :type 'integer)
1136 (defcustom org-link-frame-setup
1137 '((vm . vm-visit-folder-other-frame)
1138 (gnus . gnus-other-frame)
1139 (file . find-file-other-window))
1140 "Setup the frame configuration for following links.
1141 When following a link with Emacs, it may often be useful to display
1142 this link in another window or frame. This variable can be used to
1143 set this up for the different types of links.
1144 For VM, use any of
1145 `vm-visit-folder'
1146 `vm-visit-folder-other-frame'
1147 For Gnus, use any of
1148 `gnus'
1149 `gnus-other-frame'
1150 `org-gnus-no-new-news'
1151 For FILE, use any of
1152 `find-file'
1153 `find-file-other-window'
1154 `find-file-other-frame'
1155 For the calendar, use the variable `calendar-setup'.
1156 For BBDB, it is currently only possible to display the matches in
1157 another window."
1158 :group 'org-link-follow
1159 :type '(list
1160 (cons (const vm)
1161 (choice
1162 (const vm-visit-folder)
1163 (const vm-visit-folder-other-window)
1164 (const vm-visit-folder-other-frame)))
1165 (cons (const gnus)
1166 (choice
1167 (const gnus)
1168 (const gnus-other-frame)
1169 (const org-gnus-no-new-news)))
1170 (cons (const file)
1171 (choice
1172 (const find-file)
1173 (const find-file-other-window)
1174 (const find-file-other-frame)))))
1176 (defcustom org-display-internal-link-with-indirect-buffer nil
1177 "Non-nil means, use indirect buffer to display infile links.
1178 Activating internal links (from one location in a file to another location
1179 in the same file) normally just jumps to the location. When the link is
1180 activated with a C-u prefix (or with mouse-3), the link is displayed in
1181 another window. When this option is set, the other window actually displays
1182 an indirect buffer clone of the current buffer, to avoid any visibility
1183 changes to the current buffer."
1184 :group 'org-link-follow
1185 :type 'boolean)
1187 (defcustom org-open-non-existing-files nil
1188 "Non-nil means, `org-open-file' will open non-existing files.
1189 When nil, an error will be generated."
1190 :group 'org-link-follow
1191 :type 'boolean)
1193 (defcustom org-open-directory-means-index-dot-org nil
1194 "Non-nil means, a link to a directory really means to index.org.
1195 When nil, following a directory link will run dired or open a finder/explorer
1196 window on that directory."
1197 :group 'org-link-follow
1198 :type 'boolean)
1200 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1201 "Function and arguments to call for following mailto links.
1202 This is a list with the first element being a lisp function, and the
1203 remaining elements being arguments to the function. In string arguments,
1204 %a will be replaced by the address, and %s will be replaced by the subject
1205 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1206 :group 'org-link-follow
1207 :type '(choice
1208 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1209 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1210 (const :tag "message-mail" (message-mail "%a" "%s"))
1211 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1213 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1214 "Non-nil means, ask for confirmation before executing shell links.
1215 Shell links can be dangerous: just think about a link
1217 [[shell:rm -rf ~/*][Google Search]]
1219 This link would show up in your Org-mode document as \"Google Search\",
1220 but really it would remove your entire home directory.
1221 Therefore we advise against setting this variable to nil.
1222 Just change it to `y-or-n-p' of you want to confirm with a
1223 single keystroke rather than having to type \"yes\"."
1224 :group 'org-link-follow
1225 :type '(choice
1226 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1227 (const :tag "with y-or-n (faster)" y-or-n-p)
1228 (const :tag "no confirmation (dangerous)" nil)))
1230 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1231 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1232 Elisp links can be dangerous: just think about a link
1234 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1236 This link would show up in your Org-mode document as \"Google Search\",
1237 but really it would remove your entire home directory.
1238 Therefore we advise against setting this variable to nil.
1239 Just change it to `y-or-n-p' of you want to confirm with a
1240 single keystroke rather than having to type \"yes\"."
1241 :group 'org-link-follow
1242 :type '(choice
1243 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1244 (const :tag "with y-or-n (faster)" y-or-n-p)
1245 (const :tag "no confirmation (dangerous)" nil)))
1247 (defconst org-file-apps-defaults-gnu
1248 '((remote . emacs)
1249 (system . mailcap)
1250 (t . mailcap))
1251 "Default file applications on a UNIX or GNU/Linux system.
1252 See `org-file-apps'.")
1254 (defconst org-file-apps-defaults-macosx
1255 '((remote . emacs)
1256 (t . "open %s")
1257 (system . "open %s")
1258 ("ps.gz" . "gv %s")
1259 ("eps.gz" . "gv %s")
1260 ("dvi" . "xdvi %s")
1261 ("fig" . "xfig %s"))
1262 "Default file applications on a MacOS X system.
1263 The system \"open\" is known as a default, but we use X11 applications
1264 for some files for which the OS does not have a good default.
1265 See `org-file-apps'.")
1267 (defconst org-file-apps-defaults-windowsnt
1268 (list
1269 '(remote . emacs)
1270 (cons t
1271 (list (if (featurep 'xemacs)
1272 'mswindows-shell-execute
1273 'w32-shell-execute)
1274 "open" 'file))
1275 (cons 'system
1276 (list (if (featurep 'xemacs)
1277 'mswindows-shell-execute
1278 'w32-shell-execute)
1279 "open" 'file)))
1280 "Default file applications on a Windows NT system.
1281 The system \"open\" is used for most files.
1282 See `org-file-apps'.")
1284 (defcustom org-file-apps
1286 (auto-mode . emacs)
1287 ("\\.x?html?\\'" . default)
1288 ("\\.pdf\\'" . default)
1290 "External applications for opening `file:path' items in a document.
1291 Org-mode uses system defaults for different file types, but
1292 you can use this variable to set the application for a given file
1293 extension. The entries in this list are cons cells where the car identifies
1294 files and the cdr the corresponding command. Possible values for the
1295 file identifier are
1296 \"regex\" Regular expression matched against the file name. For backward
1297 compatibility, this can also be a string with only alphanumeric
1298 characters, which is then interpreted as an extension.
1299 `directory' Matches a directory
1300 `remote' Matches a remote file, accessible through tramp or efs.
1301 Remote files most likely should be visited through Emacs
1302 because external applications cannot handle such paths.
1303 `auto-mode' Matches files that are matched by any entry in `auto-mode-alist',
1304 so all files Emacs knows how to handle. Using this with
1305 command `emacs' will open most files in Emacs. Beware that this
1306 will also open html files inside Emacs, unless you add
1307 (\"html\" . default) to the list as well.
1308 t Default for files not matched by any of the other options.
1309 `system' The system command to open files, like `open' on Windows
1310 and Mac OS X, and mailcap under GNU/Linux. This is the command
1311 that will be selected if you call `C-c C-o' with a double
1312 `C-u C-u' prefix.
1314 Possible values for the command are:
1315 `emacs' The file will be visited by the current Emacs process.
1316 `default' Use the default application for this file type, which is the
1317 association for t in the list, most likely in the system-specific
1318 part.
1319 This can be used to overrule an unwanted setting in the
1320 system-specific variable.
1321 `system' Use the system command for opening files, like \"open\".
1322 This command is specified by the entry whose car is `system'.
1323 Most likely, the system-specific version of this variable
1324 does define this command, but you can overrule/replace it
1325 here.
1326 string A command to be executed by a shell; %s will be replaced
1327 by the path to the file.
1328 sexp A Lisp form which will be evaluated. The file path will
1329 be available in the Lisp variable `file'.
1330 For more examples, see the system specific constants
1331 `org-file-apps-defaults-macosx'
1332 `org-file-apps-defaults-windowsnt'
1333 `org-file-apps-defaults-gnu'."
1334 :group 'org-link-follow
1335 :type '(repeat
1336 (cons (choice :value ""
1337 (string :tag "Extension")
1338 (const :tag "System command to open files" system)
1339 (const :tag "Default for unrecognized files" t)
1340 (const :tag "Remote file" remote)
1341 (const :tag "Links to a directory" directory)
1342 (const :tag "Any files that have Emacs modes"
1343 auto-mode))
1344 (choice :value ""
1345 (const :tag "Visit with Emacs" emacs)
1346 (const :tag "Use default" default)
1347 (const :tag "Use the system command" system)
1348 (string :tag "Command")
1349 (sexp :tag "Lisp form")))))
1351 (defgroup org-refile nil
1352 "Options concerning refiling entries in Org-mode."
1353 :tag "Org Refile"
1354 :group 'org)
1356 (defcustom org-directory "~/org"
1357 "Directory with org files.
1358 This is just a default location to look for Org files. There is no need
1359 at all to put your files into this directory. It is only used in the
1360 following situations:
1362 1. When a remember template specifies a target file that is not an
1363 absolute path. The path will then be interpreted relative to
1364 `org-directory'
1365 2. When a remember note is filed away in an interactive way (when exiting the
1366 note buffer with `C-1 C-c C-c'. The the user is prompted for an org file,
1367 with `org-directory' as the default path."
1368 :group 'org-refile
1369 :group 'org-remember
1370 :type 'directory)
1372 (defcustom org-default-notes-file (convert-standard-filename "~/.notes")
1373 "Default target for storing notes.
1374 Used by the hooks for remember.el. This can be a string, or nil to mean
1375 the value of `remember-data-file'.
1376 You can set this on a per-template basis with the variable
1377 `org-remember-templates'."
1378 :group 'org-refile
1379 :group 'org-remember
1380 :type '(choice
1381 (const :tag "Default from remember-data-file" nil)
1382 file))
1384 (defcustom org-goto-interface 'outline
1385 "The default interface to be used for `org-goto'.
1386 Allowed values are:
1387 outline The interface shows an outline of the relevant file
1388 and the correct heading is found by moving through
1389 the outline or by searching with incremental search.
1390 outline-path-completion Headlines in the current buffer are offered via
1391 completion. This is the interface also used by
1392 the refile command."
1393 :group 'org-refile
1394 :type '(choice
1395 (const :tag "Outline" outline)
1396 (const :tag "Outline-path-completion" outline-path-completion)))
1398 (defcustom org-goto-max-level 5
1399 "Maximum level to be considered when running org-goto with refile interface."
1400 :group 'org-refile
1401 :type 'number)
1403 (defcustom org-reverse-note-order nil
1404 "Non-nil means, store new notes at the beginning of a file or entry.
1405 When nil, new notes will be filed to the end of a file or entry.
1406 This can also be a list with cons cells of regular expressions that
1407 are matched against file names, and values."
1408 :group 'org-remember
1409 :group 'org-refile
1410 :type '(choice
1411 (const :tag "Reverse always" t)
1412 (const :tag "Reverse never" nil)
1413 (repeat :tag "By file name regexp"
1414 (cons regexp boolean))))
1416 (defcustom org-refile-targets nil
1417 "Targets for refiling entries with \\[org-refile].
1418 This is list of cons cells. Each cell contains:
1419 - a specification of the files to be considered, either a list of files,
1420 or a symbol whose function or variable value will be used to retrieve
1421 a file name or a list of file names. If you use `org-agenda-files' for
1422 that, all agenda files will be scanned for targets. Nil means, consider
1423 headings in the current buffer.
1424 - A specification of how to find candidate refile targets. This may be
1425 any of:
1426 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1427 This tag has to be present in all target headlines, inheritance will
1428 not be considered.
1429 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1430 todo keyword.
1431 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1432 headlines that are refiling targets.
1433 - a cons cell (:level . N). Any headline of level N is considered a target.
1434 - a cons cell (:maxlevel . N). Any headline with level <= N is a target.
1436 When this variable is nil, all top-level headlines in the current buffer
1437 are used, equivalent to the value `((nil . (:level . 1))'."
1438 :group 'org-refile
1439 :type '(repeat
1440 (cons
1441 (choice :value org-agenda-files
1442 (const :tag "All agenda files" org-agenda-files)
1443 (const :tag "Current buffer" nil)
1444 (function) (variable) (file))
1445 (choice :tag "Identify target headline by"
1446 (cons :tag "Specific tag" (const :value :tag) (string))
1447 (cons :tag "TODO keyword" (const :value :todo) (string))
1448 (cons :tag "Regular expression" (const :value :regexp) (regexp))
1449 (cons :tag "Level number" (const :value :level) (integer))
1450 (cons :tag "Max Level number" (const :value :maxlevel) (integer))))))
1452 (defcustom org-refile-use-outline-path nil
1453 "Non-nil means, provide refile targets as paths.
1454 So a level 3 headline will be available as level1/level2/level3.
1455 When the value is `file', also include the file name (without directory)
1456 into the path. When `full-file-path', include the full file path."
1457 :group 'org-refile
1458 :type '(choice
1459 (const :tag "Not" nil)
1460 (const :tag "Yes" t)
1461 (const :tag "Start with file name" file)
1462 (const :tag "Start with full file path" full-file-path)))
1464 (defcustom org-outline-path-complete-in-steps t
1465 "Non-nil means, complete the outline path in hierarchical steps.
1466 When Org-mode uses the refile interface to select an outline path
1467 \(see variable `org-refile-use-outline-path'), the completion of
1468 the path can be done is a single go, or if can be done in steps down
1469 the headline hierarchy. Going in steps is probably the best if you
1470 do not use a special completion package like `ido' or `icicles'.
1471 However, when using these packages, going in one step can be very
1472 fast, while still showing the whole path to the entry."
1473 :group 'org-refile
1474 :type 'boolean)
1476 (defgroup org-todo nil
1477 "Options concerning TODO items in Org-mode."
1478 :tag "Org TODO"
1479 :group 'org)
1481 (defgroup org-progress nil
1482 "Options concerning Progress logging in Org-mode."
1483 :tag "Org Progress"
1484 :group 'org-time)
1486 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1487 "List of TODO entry keyword sequences and their interpretation.
1488 \\<org-mode-map>This is a list of sequences.
1490 Each sequence starts with a symbol, either `sequence' or `type',
1491 indicating if the keywords should be interpreted as a sequence of
1492 action steps, or as different types of TODO items. The first
1493 keywords are states requiring action - these states will select a headline
1494 for inclusion into the global TODO list Org-mode produces. If one of
1495 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1496 signify that no further action is necessary. If \"|\" is not found,
1497 the last keyword is treated as the only DONE state of the sequence.
1499 The command \\[org-todo] cycles an entry through these states, and one
1500 additional state where no keyword is present. For details about this
1501 cycling, see the manual.
1503 TODO keywords and interpretation can also be set on a per-file basis with
1504 the special #+SEQ_TODO and #+TYP_TODO lines.
1506 Each keyword can optionally specify a character for fast state selection
1507 \(in combination with the variable `org-use-fast-todo-selection')
1508 and specifiers for state change logging, using the same syntax
1509 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1510 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1511 indicates to record a time stamp each time this state is selected.
1513 Each keyword may also specify if a timestamp or a note should be
1514 recorded when entering or leaving the state, by adding additional
1515 characters in the parenthesis after the keyword. This looks like this:
1516 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1517 record only the time of the state change. With X and Y being either
1518 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1519 Y when leaving the state if and only if the *target* state does not
1520 define X. You may omit any of the fast-selection key or X or /Y,
1521 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1523 For backward compatibility, this variable may also be just a list
1524 of keywords - in this case the interpretation (sequence or type) will be
1525 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1526 :group 'org-todo
1527 :group 'org-keywords
1528 :type '(choice
1529 (repeat :tag "Old syntax, just keywords"
1530 (string :tag "Keyword"))
1531 (repeat :tag "New syntax"
1532 (cons
1533 (choice
1534 :tag "Interpretation"
1535 (const :tag "Sequence (cycling hits every state)" sequence)
1536 (const :tag "Type (cycling directly to DONE)" type))
1537 (repeat
1538 (string :tag "Keyword"))))))
1540 (defvar org-todo-keywords-1 nil
1541 "All TODO and DONE keywords active in a buffer.")
1542 (make-variable-buffer-local 'org-todo-keywords-1)
1543 (defvar org-todo-keywords-for-agenda nil)
1544 (defvar org-done-keywords-for-agenda nil)
1545 (defvar org-todo-keyword-alist-for-agenda nil)
1546 (defvar org-tag-alist-for-agenda nil)
1547 (defvar org-agenda-contributing-files nil)
1548 (defvar org-not-done-keywords nil)
1549 (make-variable-buffer-local 'org-not-done-keywords)
1550 (defvar org-done-keywords nil)
1551 (make-variable-buffer-local 'org-done-keywords)
1552 (defvar org-todo-heads nil)
1553 (make-variable-buffer-local 'org-todo-heads)
1554 (defvar org-todo-sets nil)
1555 (make-variable-buffer-local 'org-todo-sets)
1556 (defvar org-todo-log-states nil)
1557 (make-variable-buffer-local 'org-todo-log-states)
1558 (defvar org-todo-kwd-alist nil)
1559 (make-variable-buffer-local 'org-todo-kwd-alist)
1560 (defvar org-todo-key-alist nil)
1561 (make-variable-buffer-local 'org-todo-key-alist)
1562 (defvar org-todo-key-trigger nil)
1563 (make-variable-buffer-local 'org-todo-key-trigger)
1565 (defcustom org-todo-interpretation 'sequence
1566 "Controls how TODO keywords are interpreted.
1567 This variable is in principle obsolete and is only used for
1568 backward compatibility, if the interpretation of todo keywords is
1569 not given already in `org-todo-keywords'. See that variable for
1570 more information."
1571 :group 'org-todo
1572 :group 'org-keywords
1573 :type '(choice (const sequence)
1574 (const type)))
1576 (defcustom org-use-fast-todo-selection t
1577 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1578 This variable describes if and under what circumstances the cycling
1579 mechanism for TODO keywords will be replaced by a single-key, direct
1580 selection scheme.
1582 When nil, fast selection is never used.
1584 When the symbol `prefix', it will be used when `org-todo' is called with
1585 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1586 in an agenda buffer.
1588 When t, fast selection is used by default. In this case, the prefix
1589 argument forces cycling instead.
1591 In all cases, the special interface is only used if access keys have actually
1592 been assigned by the user, i.e. if keywords in the configuration are followed
1593 by a letter in parenthesis, like TODO(t)."
1594 :group 'org-todo
1595 :type '(choice
1596 (const :tag "Never" nil)
1597 (const :tag "By default" t)
1598 (const :tag "Only with C-u C-c C-t" prefix)))
1600 (defcustom org-provide-todo-statistics t
1601 "Non-nil means, update todo statistics after insert and toggle.
1602 When this is set, todo statistics is updated in the parent of the current
1603 entry each time a todo state is changed."
1604 :group 'org-todo
1605 :type 'boolean)
1607 (defcustom org-after-todo-state-change-hook nil
1608 "Hook which is run after the state of a TODO item was changed.
1609 The new state (a string with a TODO keyword, or nil) is available in the
1610 Lisp variable `state'."
1611 :group 'org-todo
1612 :type 'hook)
1614 (defvar org-blocker-hook nil
1615 "Hook for functions that are allowed to block a state change.
1617 Each function gets as its single argument a property list, see
1618 `org-trigger-hook' for more information about this list.
1620 If any of the functions in this hook returns nil, the state change
1621 is blocked.")
1623 (defvar org-trigger-hook nil
1624 "Hook for functions that are triggered by a state change.
1626 Each function gets as its single argument a property list with at least
1627 the following elements:
1629 (:type type-of-change :position pos-at-entry-start
1630 :from old-state :to new-state)
1632 Depending on the type, more properties may be present.
1634 This mechanism is currently implemented for:
1636 TODO state changes
1637 ------------------
1638 :type todo-state-change
1639 :from previous state (keyword as a string), or nil, or a symbol
1640 'todo' or 'done', to indicate the general type of state.
1641 :to new state, like in :from")
1643 (defcustom org-enforce-todo-dependencies nil
1644 "Non-nil means, undone TODO entries will block switching the parent to DONE.
1645 Also, if a parent has an :ORDERED: property, switching an entry to DONE will
1646 be blocked if any prior sibling is not yet done.
1647 This variable needs to be set before org.el is loaded, and you need to
1648 restart Emacs after a change to make the change effective. The only way
1649 to change is while Emacs is running is through the customize interface."
1650 :set (lambda (var val)
1651 (set var val)
1652 (if val
1653 (add-hook 'org-blocker-hook
1654 'org-block-todo-from-children-or-siblings)
1655 (remove-hook 'org-blocker-hook
1656 'org-block-todo-from-children-or-siblings)))
1657 :group 'org-todo
1658 :type 'boolean)
1660 (defcustom org-enforce-todo-checkbox-dependencies nil
1661 "Non-nil means, unchecked boxes will block switching the parent to DONE.
1662 When this is nil, checkboxes have no influence on switching TODO states.
1663 When non-nil, you first need to check off all check boxes before the TODO
1664 entry can be switched to DONE.
1665 This variable needs to be set before org.el is loaded, and you need to
1666 restart Emacs after a change to make the change effective. The only way
1667 to change is while Emacs is running is through the customize interface."
1668 :set (lambda (var val)
1669 (set var val)
1670 (if val
1671 (add-hook 'org-blocker-hook
1672 'org-block-todo-from-checkboxes)
1673 (remove-hook 'org-blocker-hook
1674 'org-block-todo-from-checkboxes)))
1675 :group 'org-todo
1676 :type 'boolean)
1678 (defcustom org-todo-state-tags-triggers nil
1679 "Tag changes that should be triggered by TODO state changes.
1680 This is a list. Each entry is
1682 (state-change (tag . flag) .......)
1684 State-change can be a string with a state, and empty string to indicate the
1685 state that has no TODO keyword, or it can be one of the symbols `todo'
1686 or `done', meaning any not-done or done state, respectively."
1687 :group 'org-todo
1688 :group 'org-tags
1689 :type '(repeat
1690 (cons (choice :tag "When changing to"
1691 (const :tag "Not-done state" todo)
1692 (const :tag "Done state" done)
1693 (string :tag "State"))
1694 (repeat
1695 (cons :tag "Tag action"
1696 (string :tag "Tag")
1697 (choice (const :tag "Add" t) (const :tag "Remove" nil)))))))
1699 (defcustom org-log-done nil
1700 "Information to record when a task moves to the DONE state.
1702 Possible values are:
1704 nil Don't add anything, just change the keyword
1705 time Add a time stamp to the task
1706 note Prompt a closing note and add it with template `org-log-note-headings'
1708 This option can also be set with on a per-file-basis with
1710 #+STARTUP: nologdone
1711 #+STARTUP: logdone
1712 #+STARTUP: lognotedone
1714 You can have local logging settings for a subtree by setting the LOGGING
1715 property to one or more of these keywords."
1716 :group 'org-todo
1717 :group 'org-progress
1718 :type '(choice
1719 (const :tag "No logging" nil)
1720 (const :tag "Record CLOSED timestamp" time)
1721 (const :tag "Record CLOSED timestamp with closing note." note)))
1723 ;; Normalize old uses of org-log-done.
1724 (cond
1725 ((eq org-log-done t) (setq org-log-done 'time))
1726 ((and (listp org-log-done) (memq 'done org-log-done))
1727 (setq org-log-done 'note)))
1729 (defcustom org-log-note-clock-out nil
1730 "Non-nil means, record a note when clocking out of an item.
1731 This can also be configured on a per-file basis by adding one of
1732 the following lines anywhere in the buffer:
1734 #+STARTUP: lognoteclock-out
1735 #+STARTUP: nolognoteclock-out"
1736 :group 'org-todo
1737 :group 'org-progress
1738 :type 'boolean)
1740 (defcustom org-log-done-with-time t
1741 "Non-nil means, the CLOSED time stamp will contain date and time.
1742 When nil, only the date will be recorded."
1743 :group 'org-progress
1744 :type 'boolean)
1746 (defcustom org-log-note-headings
1747 '((done . "CLOSING NOTE %t")
1748 (state . "State %-12s %t")
1749 (note . "Note taken on %t")
1750 (clock-out . ""))
1751 "Headings for notes added to entries.
1752 The value is an alist, with the car being a symbol indicating the note
1753 context, and the cdr is the heading to be used. The heading may also be the
1754 empty string.
1755 %t in the heading will be replaced by a time stamp.
1756 %s will be replaced by the new TODO state, in double quotes.
1757 %u will be replaced by the user name.
1758 %U will be replaced by the full user name."
1759 :group 'org-todo
1760 :group 'org-progress
1761 :type '(list :greedy t
1762 (cons (const :tag "Heading when closing an item" done) string)
1763 (cons (const :tag
1764 "Heading when changing todo state (todo sequence only)"
1765 state) string)
1766 (cons (const :tag "Heading when just taking a note" note) string)
1767 (cons (const :tag "Heading when clocking out" clock-out) string)))
1769 (unless (assq 'note org-log-note-headings)
1770 (push '(note . "%t") org-log-note-headings))
1772 (defcustom org-log-state-notes-insert-after-drawers nil
1773 "Non-nil means, insert state change notes after any drawers in entry.
1774 Only the drawers that *immediately* follow the headline and the
1775 deadline/scheduled line are skipped.
1776 When nil, insert notes right after the heading and perhaps the line
1777 with deadline/scheduling if present."
1778 :group 'org-todo
1779 :group 'org-progress
1780 :type 'boolean)
1782 (defcustom org-log-states-order-reversed t
1783 "Non-nil means, the latest state change note will be directly after heading.
1784 When nil, the notes will be orderer according to time."
1785 :group 'org-todo
1786 :group 'org-progress
1787 :type 'boolean)
1789 (defcustom org-log-repeat 'time
1790 "Non-nil means, record moving through the DONE state when triggering repeat.
1791 An auto-repeating tasks is immediately switched back to TODO when marked
1792 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1793 the TODO keyword definition, or recording a closing note by setting
1794 `org-log-done', there will be no record of the task moving through DONE.
1795 This variable forces taking a note anyway. Possible values are:
1797 nil Don't force a record
1798 time Record a time stamp
1799 note Record a note
1801 This option can also be set with on a per-file-basis with
1803 #+STARTUP: logrepeat
1804 #+STARTUP: lognoterepeat
1805 #+STARTUP: nologrepeat
1807 You can have local logging settings for a subtree by setting the LOGGING
1808 property to one or more of these keywords."
1809 :group 'org-todo
1810 :group 'org-progress
1811 :type '(choice
1812 (const :tag "Don't force a record" nil)
1813 (const :tag "Force recording the DONE state" time)
1814 (const :tag "Force recording a note with the DONE state" note)))
1817 (defgroup org-priorities nil
1818 "Priorities in Org-mode."
1819 :tag "Org Priorities"
1820 :group 'org-todo)
1822 (defcustom org-highest-priority ?A
1823 "The highest priority of TODO items. A character like ?A, ?B etc.
1824 Must have a smaller ASCII number than `org-lowest-priority'."
1825 :group 'org-priorities
1826 :type 'character)
1828 (defcustom org-lowest-priority ?C
1829 "The lowest priority of TODO items. A character like ?A, ?B etc.
1830 Must have a larger ASCII number than `org-highest-priority'."
1831 :group 'org-priorities
1832 :type 'character)
1834 (defcustom org-default-priority ?B
1835 "The default priority of TODO items.
1836 This is the priority an item get if no explicit priority is given."
1837 :group 'org-priorities
1838 :type 'character)
1840 (defcustom org-priority-start-cycle-with-default t
1841 "Non-nil means, start with default priority when starting to cycle.
1842 When this is nil, the first step in the cycle will be (depending on the
1843 command used) one higher or lower that the default priority."
1844 :group 'org-priorities
1845 :type 'boolean)
1847 (defgroup org-time nil
1848 "Options concerning time stamps and deadlines in Org-mode."
1849 :tag "Org Time"
1850 :group 'org)
1852 (defcustom org-insert-labeled-timestamps-at-point nil
1853 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1854 When nil, these labeled time stamps are forces into the second line of an
1855 entry, just after the headline. When scheduling from the global TODO list,
1856 the time stamp will always be forced into the second line."
1857 :group 'org-time
1858 :type 'boolean)
1860 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1861 "Formats for `format-time-string' which are used for time stamps.
1862 It is not recommended to change this constant.")
1864 (defcustom org-time-stamp-rounding-minutes '(0 5)
1865 "Number of minutes to round time stamps to.
1866 These are two values, the first applies when first creating a time stamp.
1867 The second applies when changing it with the commands `S-up' and `S-down'.
1868 When changing the time stamp, this means that it will change in steps
1869 of N minutes, as given by the second value.
1871 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1872 numbers should be factors of 60, so for example 5, 10, 15.
1874 When this is larger than 1, you can still force an exact time-stamp by using
1875 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1876 and by using a prefix arg to `S-up/down' to specify the exact number
1877 of minutes to shift."
1878 :group 'org-time
1879 :get '(lambda (var) ; Make sure all entries have 5 elements
1880 (if (integerp (default-value var))
1881 (list (default-value var) 5)
1882 (default-value var)))
1883 :type '(list
1884 (integer :tag "when inserting times")
1885 (integer :tag "when modifying times")))
1887 ;; Normalize old customizations of this variable.
1888 (when (integerp org-time-stamp-rounding-minutes)
1889 (setq org-time-stamp-rounding-minutes
1890 (list org-time-stamp-rounding-minutes
1891 org-time-stamp-rounding-minutes)))
1893 (defcustom org-display-custom-times nil
1894 "Non-nil means, overlay custom formats over all time stamps.
1895 The formats are defined through the variable `org-time-stamp-custom-formats'.
1896 To turn this on on a per-file basis, insert anywhere in the file:
1897 #+STARTUP: customtime"
1898 :group 'org-time
1899 :set 'set-default
1900 :type 'sexp)
1901 (make-variable-buffer-local 'org-display-custom-times)
1903 (defcustom org-time-stamp-custom-formats
1904 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1905 "Custom formats for time stamps. See `format-time-string' for the syntax.
1906 These are overlayed over the default ISO format if the variable
1907 `org-display-custom-times' is set. Time like %H:%M should be at the
1908 end of the second format."
1909 :group 'org-time
1910 :type 'sexp)
1912 (defun org-time-stamp-format (&optional long inactive)
1913 "Get the right format for a time string."
1914 (let ((f (if long (cdr org-time-stamp-formats)
1915 (car org-time-stamp-formats))))
1916 (if inactive
1917 (concat "[" (substring f 1 -1) "]")
1918 f)))
1920 (defcustom org-time-clocksum-format "%d:%02d"
1921 "The format string used when creating CLOCKSUM lines, or when
1922 org-mode generates a time duration."
1923 :group 'org-time
1924 :type 'string)
1926 (defcustom org-deadline-warning-days 14
1927 "No. of days before expiration during which a deadline becomes active.
1928 This variable governs the display in sparse trees and in the agenda.
1929 When 0 or negative, it means use this number (the absolute value of it)
1930 even if a deadline has a different individual lead time specified."
1931 :group 'org-time
1932 :group 'org-agenda-daily/weekly
1933 :type 'number)
1935 (defcustom org-read-date-prefer-future t
1936 "Non-nil means, assume future for incomplete date input from user.
1937 This affects the following situations:
1938 1. The user gives a day, but no month.
1939 For example, if today is the 15th, and you enter \"3\", Org-mode will
1940 read this as the third of *next* month. However, if you enter \"17\",
1941 it will be considered as *this* month.
1942 2. The user gives a month but not a year.
1943 For example, if it is april and you enter \"feb 2\", this will be read
1944 as feb 2, *next* year. \"May 5\", however, will be this year.
1946 Currently this does not work for ISO week specifications.
1948 When this option is nil, the current month and year will always be used
1949 as defaults."
1950 :group 'org-time
1951 :type 'boolean)
1953 (defcustom org-read-date-display-live t
1954 "Non-nil means, display current interpretation of date prompt live.
1955 This display will be in an overlay, in the minibuffer."
1956 :group 'org-time
1957 :type 'boolean)
1959 (defcustom org-read-date-popup-calendar t
1960 "Non-nil means, pop up a calendar when prompting for a date.
1961 In the calendar, the date can be selected with mouse-1. However, the
1962 minibuffer will also be active, and you can simply enter the date as well.
1963 When nil, only the minibuffer will be available."
1964 :group 'org-time
1965 :type 'boolean)
1966 (if (fboundp 'defvaralias)
1967 (defvaralias 'org-popup-calendar-for-date-prompt
1968 'org-read-date-popup-calendar))
1970 (defcustom org-extend-today-until 0
1971 "The hour when your day really ends. Must be an integer.
1972 This has influence for the following applications:
1973 - When switching the agenda to \"today\". It it is still earlier than
1974 the time given here, the day recognized as TODAY is actually yesterday.
1975 - When a date is read from the user and it is still before the time given
1976 here, the current date and time will be assumed to be yesterday, 23:59.
1977 Also, timestamps inserted in remember templates follow this rule.
1979 IMPORTANT: This is a feature whose implementation is and likely will
1980 remain incomplete. Really, it is only here because past midnight seems to
1981 be the favorite working time of John Wiegley :-)"
1982 :group 'org-time
1983 :type 'number)
1985 (defcustom org-edit-timestamp-down-means-later nil
1986 "Non-nil means, S-down will increase the time in a time stamp.
1987 When nil, S-up will increase."
1988 :group 'org-time
1989 :type 'boolean)
1991 (defcustom org-calendar-follow-timestamp-change t
1992 "Non-nil means, make the calendar window follow timestamp changes.
1993 When a timestamp is modified and the calendar window is visible, it will be
1994 moved to the new date."
1995 :group 'org-time
1996 :type 'boolean)
1998 (defgroup org-tags nil
1999 "Options concerning tags in Org-mode."
2000 :tag "Org Tags"
2001 :group 'org)
2003 (defcustom org-tag-alist nil
2004 "List of tags allowed in Org-mode files.
2005 When this list is nil, Org-mode will base TAG input on what is already in the
2006 buffer.
2007 The value of this variable is an alist, the car of each entry must be a
2008 keyword as a string, the cdr may be a character that is used to select
2009 that tag through the fast-tag-selection interface.
2010 See the manual for details."
2011 :group 'org-tags
2012 :type '(repeat
2013 (choice
2014 (cons (string :tag "Tag name")
2015 (character :tag "Access char"))
2016 (const :tag "Start radio group" (:startgroup))
2017 (const :tag "End radio group" (:endgroup)))))
2019 (defvar org-file-tags nil
2020 "List of tags that can be inherited by all entries in the file.
2021 The tags will be inherited if the variable `org-use-tag-inheritance'
2022 says they should be.
2023 This variable is populated from #+TAG lines.")
2025 (defcustom org-use-fast-tag-selection 'auto
2026 "Non-nil means, use fast tag selection scheme.
2027 This is a special interface to select and deselect tags with single keys.
2028 When nil, fast selection is never used.
2029 When the symbol `auto', fast selection is used if and only if selection
2030 characters for tags have been configured, either through the variable
2031 `org-tag-alist' or through a #+TAGS line in the buffer.
2032 When t, fast selection is always used and selection keys are assigned
2033 automatically if necessary."
2034 :group 'org-tags
2035 :type '(choice
2036 (const :tag "Always" t)
2037 (const :tag "Never" nil)
2038 (const :tag "When selection characters are configured" 'auto)))
2040 (defcustom org-fast-tag-selection-single-key nil
2041 "Non-nil means, fast tag selection exits after first change.
2042 When nil, you have to press RET to exit it.
2043 During fast tag selection, you can toggle this flag with `C-c'.
2044 This variable can also have the value `expert'. In this case, the window
2045 displaying the tags menu is not even shown, until you press C-c again."
2046 :group 'org-tags
2047 :type '(choice
2048 (const :tag "No" nil)
2049 (const :tag "Yes" t)
2050 (const :tag "Expert" expert)))
2052 (defvar org-fast-tag-selection-include-todo nil
2053 "Non-nil means, fast tags selection interface will also offer TODO states.
2054 This is an undocumented feature, you should not rely on it.")
2056 (defcustom org-tags-column (if (featurep 'xemacs) -76 -77)
2057 "The column to which tags should be indented in a headline.
2058 If this number is positive, it specifies the column. If it is negative,
2059 it means that the tags should be flushright to that column. For example,
2060 -80 works well for a normal 80 character screen."
2061 :group 'org-tags
2062 :type 'integer)
2064 (defcustom org-auto-align-tags t
2065 "Non-nil means, realign tags after pro/demotion of TODO state change.
2066 These operations change the length of a headline and therefore shift
2067 the tags around. With this options turned on, after each such operation
2068 the tags are again aligned to `org-tags-column'."
2069 :group 'org-tags
2070 :type 'boolean)
2072 (defcustom org-use-tag-inheritance t
2073 "Non-nil means, tags in levels apply also for sublevels.
2074 When nil, only the tags directly given in a specific line apply there.
2075 This may also be a list of tags that should be inherited, or a regexp that
2076 matches tags that should be inherited. Additional control is possible
2077 with the variable `org-tags-exclude-from-inheritance' which gives an
2078 explicit list of tags to be excluded from inheritance., even if the value of
2079 `org-use-tag-inheritance' would select it for inheritance.
2081 If this option is t, a match early-on in a tree can lead to a large
2082 number of matches in the subtree when constructing the agenda or creating
2083 a sparse tree. If you only want to see the first match in a tree during
2084 a search, check out the variable `org-tags-match-list-sublevels'."
2085 :group 'org-tags
2086 :type '(choice
2087 (const :tag "Not" nil)
2088 (const :tag "Always" t)
2089 (repeat :tag "Specific tags" (string :tag "Tag"))
2090 (regexp :tag "Tags matched by regexp")))
2092 (defcustom org-tags-exclude-from-inheritance nil
2093 "List of tags that should never be inherited.
2094 This is a way to exclude a few tags from inheritance. For way to do
2095 the opposite, to actively allow inheritance for selected tags,
2096 see the variable `org-use-tag-inheritance'."
2097 :group 'org-tags
2098 :type '(repeat (string :tag "Tag")))
2100 (defun org-tag-inherit-p (tag)
2101 "Check if TAG is one that should be inherited."
2102 (cond
2103 ((member tag org-tags-exclude-from-inheritance) nil)
2104 ((eq org-use-tag-inheritance t) t)
2105 ((not org-use-tag-inheritance) nil)
2106 ((stringp org-use-tag-inheritance)
2107 (string-match org-use-tag-inheritance tag))
2108 ((listp org-use-tag-inheritance)
2109 (member tag org-use-tag-inheritance))
2110 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
2112 (defcustom org-tags-match-list-sublevels t
2113 "Non-nil means list also sublevels of headlines matching tag search.
2114 Because of tag inheritance (see variable `org-use-tag-inheritance'),
2115 the sublevels of a headline matching a tag search often also match
2116 the same search. Listing all of them can create very long lists.
2117 Setting this variable to nil causes subtrees of a match to be skipped.
2118 This option is off by default, because inheritance in on. If you turn
2119 inheritance off, you very likely want to turn this option on.
2121 As a special case, if the tag search is restricted to TODO items, the
2122 value of this variable is ignored and sublevels are always checked, to
2123 make sure all corresponding TODO items find their way into the list.
2125 This variable is semi-obsolete and probably should always be true. It
2126 is better to limit inheritance to certain tags using the variables
2127 `org-use-tag-inheritance' and `org-tags-exclude-from-inheritance'."
2128 :group 'org-tags
2129 :type 'boolean)
2131 (defvar org-tags-history nil
2132 "History of minibuffer reads for tags.")
2133 (defvar org-last-tags-completion-table nil
2134 "The last used completion table for tags.")
2135 (defvar org-after-tags-change-hook nil
2136 "Hook that is run after the tags in a line have changed.")
2138 (defgroup org-properties nil
2139 "Options concerning properties in Org-mode."
2140 :tag "Org Properties"
2141 :group 'org)
2143 (defcustom org-property-format "%-10s %s"
2144 "How property key/value pairs should be formatted by `indent-line'.
2145 When `indent-line' hits a property definition, it will format the line
2146 according to this format, mainly to make sure that the values are
2147 lined-up with respect to each other."
2148 :group 'org-properties
2149 :type 'string)
2151 (defcustom org-use-property-inheritance nil
2152 "Non-nil means, properties apply also for sublevels.
2154 This setting is chiefly used during property searches. Turning it on can
2155 cause significant overhead when doing a search, which is why it is not
2156 on by default.
2158 When nil, only the properties directly given in the current entry count.
2159 When t, every property is inherited. The value may also be a list of
2160 properties that should have inheritance, or a regular expression matching
2161 properties that should be inherited.
2163 However, note that some special properties use inheritance under special
2164 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
2165 and the properties ending in \"_ALL\" when they are used as descriptor
2166 for valid values of a property.
2168 Note for programmers:
2169 When querying an entry with `org-entry-get', you can control if inheritance
2170 should be used. By default, `org-entry-get' looks only at the local
2171 properties. You can request inheritance by setting the inherit argument
2172 to t (to force inheritance) or to `selective' (to respect the setting
2173 in this variable)."
2174 :group 'org-properties
2175 :type '(choice
2176 (const :tag "Not" nil)
2177 (const :tag "Always" t)
2178 (repeat :tag "Specific properties" (string :tag "Property"))
2179 (regexp :tag "Properties matched by regexp")))
2181 (defun org-property-inherit-p (property)
2182 "Check if PROPERTY is one that should be inherited."
2183 (cond
2184 ((eq org-use-property-inheritance t) t)
2185 ((not org-use-property-inheritance) nil)
2186 ((stringp org-use-property-inheritance)
2187 (string-match org-use-property-inheritance property))
2188 ((listp org-use-property-inheritance)
2189 (member property org-use-property-inheritance))
2190 (t (error "Invalid setting of `org-use-property-inheritance'"))))
2192 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
2193 "The default column format, if no other format has been defined.
2194 This variable can be set on the per-file basis by inserting a line
2196 #+COLUMNS: %25ITEM ....."
2197 :group 'org-properties
2198 :type 'string)
2200 (defcustom org-columns-ellipses ".."
2201 "The ellipses to be used when a field in column view is truncated.
2202 When this is the empty string, as many characters as possible are shown,
2203 but then there will be no visual indication that the field has been truncated.
2204 When this is a string of length N, the last N characters of a truncated
2205 field are replaced by this string. If the column is narrower than the
2206 ellipses string, only part of the ellipses string will be shown."
2207 :group 'org-properties
2208 :type 'string)
2210 (defcustom org-columns-modify-value-for-display-function nil
2211 "Function that modifies values for display in column view.
2212 For example, it can be used to cut out a certain part from a time stamp.
2213 The function must take 2 arguments:
2215 column-title The title of the column (*not* the property name)
2216 value The value that should be modified.
2218 The function should return the value that should be displayed,
2219 or nil if the normal value should be used."
2220 :group 'org-properties
2221 :type 'function)
2223 (defcustom org-effort-property "Effort"
2224 "The property that is being used to keep track of effort estimates.
2225 Effort estimates given in this property need to have the format H:MM."
2226 :group 'org-properties
2227 :group 'org-progress
2228 :type '(string :tag "Property"))
2230 (defconst org-global-properties-fixed
2231 '(("VISIBILITY_ALL" . "folded children content all"))
2232 "List of property/value pairs that can be inherited by any entry.
2233 These are fixed values, for the preset properties.")
2236 (defcustom org-global-properties nil
2237 "List of property/value pairs that can be inherited by any entry.
2238 You can set buffer-local values for the same purpose in the variable
2239 `org-file-properties' this by adding lines like
2241 #+PROPERTY: NAME VALUE"
2242 :group 'org-properties
2243 :type '(repeat
2244 (cons (string :tag "Property")
2245 (string :tag "Value"))))
2247 (defvar org-file-properties nil
2248 "List of property/value pairs that can be inherited by any entry.
2249 Valid for the current buffer.
2250 This variable is populated from #+PROPERTY lines.")
2251 (make-variable-buffer-local 'org-file-properties)
2253 (defgroup org-agenda nil
2254 "Options concerning agenda views in Org-mode."
2255 :tag "Org Agenda"
2256 :group 'org)
2258 (defvar org-category nil
2259 "Variable used by org files to set a category for agenda display.
2260 Such files should use a file variable to set it, for example
2262 # -*- mode: org; org-category: \"ELisp\"
2264 or contain a special line
2266 #+CATEGORY: ELisp
2268 If the file does not specify a category, then file's base name
2269 is used instead.")
2270 (make-variable-buffer-local 'org-category)
2271 (put 'org-category 'safe-local-variable '(lambda (x) (or (symbolp x) (stringp x))))
2273 (defcustom org-agenda-files nil
2274 "The files to be used for agenda display.
2275 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
2276 \\[org-remove-file]. You can also use customize to edit the list.
2278 If an entry is a directory, all files in that directory that are matched by
2279 `org-agenda-file-regexp' will be part of the file list.
2281 If the value of the variable is not a list but a single file name, then
2282 the list of agenda files is actually stored and maintained in that file, one
2283 agenda file per line."
2284 :group 'org-agenda
2285 :type '(choice
2286 (repeat :tag "List of files and directories" file)
2287 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
2289 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
2290 "Regular expression to match files for `org-agenda-files'.
2291 If any element in the list in that variable contains a directory instead
2292 of a normal file, all files in that directory that are matched by this
2293 regular expression will be included."
2294 :group 'org-agenda
2295 :type 'regexp)
2297 (defcustom org-agenda-text-search-extra-files nil
2298 "List of extra files to be searched by text search commands.
2299 These files will be search in addition to the agenda files by the
2300 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
2301 Note that these files will only be searched for text search commands,
2302 not for the other agenda views like todo lists, tag searches or the weekly
2303 agenda. This variable is intended to list notes and possibly archive files
2304 that should also be searched by these two commands.
2305 In fact, if the first element in the list is the symbol `agenda-archives',
2306 than all archive files of all agenda files will be added to the search
2307 scope."
2308 :group 'org-agenda
2309 :type '(set :greedy t
2310 (const :tag "Agenda Archives" agenda-archives)
2311 (repeat :inline t (file))))
2313 (if (fboundp 'defvaralias)
2314 (defvaralias 'org-agenda-multi-occur-extra-files
2315 'org-agenda-text-search-extra-files))
2317 (defcustom org-agenda-skip-unavailable-files nil
2318 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
2319 A nil value means to remove them, after a query, from the list."
2320 :group 'org-agenda
2321 :type 'boolean)
2323 (defcustom org-calendar-to-agenda-key [?c]
2324 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2325 The command `org-calendar-goto-agenda' will be bound to this key. The
2326 default is the character `c' because then `c' can be used to switch back and
2327 forth between agenda and calendar."
2328 :group 'org-agenda
2329 :type 'sexp)
2331 (defcustom org-calendar-agenda-action-key [?k]
2332 "The key to be installed in `calendar-mode-map' for agenda-action.
2333 The command `org-agenda-action' will be bound to this key. The
2334 default is the character `k' because we use the same key in the agenda."
2335 :group 'org-agenda
2336 :type 'sexp)
2338 (eval-after-load "calendar"
2339 '(progn
2340 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2341 'org-calendar-goto-agenda)
2342 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2343 'org-agenda-action)))
2345 (defgroup org-latex nil
2346 "Options for embedding LaTeX code into Org-mode."
2347 :tag "Org LaTeX"
2348 :group 'org)
2350 (defcustom org-format-latex-options
2351 '(:foreground default :background default :scale 1.0
2352 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2353 :matchers ("begin" "$1" "$" "$$" "\\(" "\\["))
2354 "Options for creating images from LaTeX fragments.
2355 This is a property list with the following properties:
2356 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2357 `default' means use the foreground of the default face.
2358 :background the background color, or \"Transparent\".
2359 `default' means use the background of the default face.
2360 :scale a scaling factor for the size of the images.
2361 :html-foreground, :html-background, :html-scale
2362 the same numbers for HTML export.
2363 :matchers a list indicating which matchers should be used to
2364 find LaTeX fragments. Valid members of this list are:
2365 \"begin\" find environments
2366 \"$1\" find single characters surrounded by $.$
2367 \"$\" find math expressions surrounded by $...$
2368 \"$$\" find math expressions surrounded by $$....$$
2369 \"\\(\" find math expressions surrounded by \\(...\\)
2370 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2371 :group 'org-latex
2372 :type 'plist)
2374 (defcustom org-format-latex-header "\\documentclass{article}
2375 \\usepackage{fullpage} % do not remove
2376 \\usepackage{amssymb}
2377 \\usepackage[usenames]{color}
2378 \\usepackage{amsmath}
2379 \\usepackage{latexsym}
2380 \\usepackage[mathscr]{eucal}
2381 \\pagestyle{empty} % do not remove"
2382 "The document header used for processing LaTeX fragments."
2383 :group 'org-latex
2384 :type 'string)
2387 (defgroup org-font-lock nil
2388 "Font-lock settings for highlighting in Org-mode."
2389 :tag "Org Font Lock"
2390 :group 'org)
2392 (defcustom org-level-color-stars-only nil
2393 "Non-nil means fontify only the stars in each headline.
2394 When nil, the entire headline is fontified.
2395 Changing it requires restart of `font-lock-mode' to become effective
2396 also in regions already fontified."
2397 :group 'org-font-lock
2398 :type 'boolean)
2400 (defcustom org-hide-leading-stars nil
2401 "Non-nil means, hide the first N-1 stars in a headline.
2402 This works by using the face `org-hide' for these stars. This
2403 face is white for a light background, and black for a dark
2404 background. You may have to customize the face `org-hide' to
2405 make this work.
2406 Changing it requires restart of `font-lock-mode' to become effective
2407 also in regions already fontified.
2408 You may also set this on a per-file basis by adding one of the following
2409 lines to the buffer:
2411 #+STARTUP: hidestars
2412 #+STARTUP: showstars"
2413 :group 'org-font-lock
2414 :type 'boolean)
2416 (defcustom org-fontify-done-headline nil
2417 "Non-nil means, change the face of a headline if it is marked DONE.
2418 Normally, only the TODO/DONE keyword indicates the state of a headline.
2419 When this is non-nil, the headline after the keyword is set to the
2420 `org-headline-done' as an additional indication."
2421 :group 'org-font-lock
2422 :type 'boolean)
2424 (defcustom org-fontify-emphasized-text t
2425 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2426 Changing this variable requires a restart of Emacs to take effect."
2427 :group 'org-font-lock
2428 :type 'boolean)
2430 (defcustom org-highlight-latex-fragments-and-specials nil
2431 "Non-nil means, fontify what is treated specially by the exporters."
2432 :group 'org-font-lock
2433 :type 'boolean)
2435 (defcustom org-hide-emphasis-markers nil
2436 "Non-nil mean font-lock should hide the emphasis marker characters."
2437 :group 'org-font-lock
2438 :type 'boolean)
2440 (defvar org-emph-re nil
2441 "Regular expression for matching emphasis.")
2442 (defvar org-verbatim-re nil
2443 "Regular expression for matching verbatim text.")
2444 (defvar org-emphasis-regexp-components) ; defined just below
2445 (defvar org-emphasis-alist) ; defined just below
2446 (defun org-set-emph-re (var val)
2447 "Set variable and compute the emphasis regular expression."
2448 (set var val)
2449 (when (and (boundp 'org-emphasis-alist)
2450 (boundp 'org-emphasis-regexp-components)
2451 org-emphasis-alist org-emphasis-regexp-components)
2452 (let* ((e org-emphasis-regexp-components)
2453 (pre (car e))
2454 (post (nth 1 e))
2455 (border (nth 2 e))
2456 (body (nth 3 e))
2457 (nl (nth 4 e))
2458 (body1 (concat body "*?"))
2459 (markers (mapconcat 'car org-emphasis-alist ""))
2460 (vmarkers (mapconcat
2461 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2462 org-emphasis-alist "")))
2463 ;; make sure special characters appear at the right position in the class
2464 (if (string-match "\\^" markers)
2465 (setq markers (concat (replace-match "" t t markers) "^")))
2466 (if (string-match "-" markers)
2467 (setq markers (concat (replace-match "" t t markers) "-")))
2468 (if (string-match "\\^" vmarkers)
2469 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2470 (if (string-match "-" vmarkers)
2471 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2472 (if (> nl 0)
2473 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2474 (int-to-string nl) "\\}")))
2475 ;; Make the regexp
2476 (setq org-emph-re
2477 (concat "\\([" pre "]\\|^\\)"
2478 "\\("
2479 "\\([" markers "]\\)"
2480 "\\("
2481 "[^" border "]\\|"
2482 "[^" border "]"
2483 body1
2484 "[^" border "]"
2485 "\\)"
2486 "\\3\\)"
2487 "\\([" post "]\\|$\\)"))
2488 (setq org-verbatim-re
2489 (concat "\\([" pre "]\\|^\\)"
2490 "\\("
2491 "\\([" vmarkers "]\\)"
2492 "\\("
2493 "[^" border "]\\|"
2494 "[^" border "]"
2495 body1
2496 "[^" border "]"
2497 "\\)"
2498 "\\3\\)"
2499 "\\([" post "]\\|$\\)")))))
2501 (defcustom org-emphasis-regexp-components
2502 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2503 "Components used to build the regular expression for emphasis.
2504 This is a list with 6 entries. Terminology: In an emphasis string
2505 like \" *strong word* \", we call the initial space PREMATCH, the final
2506 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2507 and \"trong wor\" is the body. The different components in this variable
2508 specify what is allowed/forbidden in each part:
2510 pre Chars allowed as prematch. Beginning of line will be allowed too.
2511 post Chars allowed as postmatch. End of line will be allowed too.
2512 border The chars *forbidden* as border characters.
2513 body-regexp A regexp like \".\" to match a body character. Don't use
2514 non-shy groups here, and don't allow newline here.
2515 newline The maximum number of newlines allowed in an emphasis exp.
2517 Use customize to modify this, or restart Emacs after changing it."
2518 :group 'org-font-lock
2519 :set 'org-set-emph-re
2520 :type '(list
2521 (sexp :tag "Allowed chars in pre ")
2522 (sexp :tag "Allowed chars in post ")
2523 (sexp :tag "Forbidden chars in border ")
2524 (sexp :tag "Regexp for body ")
2525 (integer :tag "number of newlines allowed")
2526 (option (boolean :tag "Please ignore this button"))))
2528 (defcustom org-emphasis-alist
2529 `(("*" bold "<b>" "</b>")
2530 ("/" italic "<i>" "</i>")
2531 ("_" underline "<span style=\"text-decoration:underline;\">" "</span>")
2532 ("=" org-code "<code>" "</code>" verbatim)
2533 ("~" org-verbatim "<code>" "</code>" verbatim)
2534 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2535 "<del>" "</del>")
2537 "Special syntax for emphasized text.
2538 Text starting and ending with a special character will be emphasized, for
2539 example *bold*, _underlined_ and /italic/. This variable sets the marker
2540 characters, the face to be used by font-lock for highlighting in Org-mode
2541 Emacs buffers, and the HTML tags to be used for this.
2542 Use customize to modify this, or restart Emacs after changing it."
2543 :group 'org-font-lock
2544 :set 'org-set-emph-re
2545 :type '(repeat
2546 (list
2547 (string :tag "Marker character")
2548 (choice
2549 (face :tag "Font-lock-face")
2550 (plist :tag "Face property list"))
2551 (string :tag "HTML start tag")
2552 (string :tag "HTML end tag")
2553 (option (const verbatim)))))
2555 ;;; Miscellaneous options
2557 (defgroup org-completion nil
2558 "Completion in Org-mode."
2559 :tag "Org Completion"
2560 :group 'org)
2562 (defcustom org-completion-use-ido nil
2563 "Non-nil means, use ido completion wherever possible.
2564 Note that `ido-mode' must be active for this variable to be relevant.
2565 If you decide to turn this variable on, you might well want to turn off
2566 `org-outline-path-complete-in-steps'."
2567 :group 'org-completion
2568 :type 'boolean)
2570 (defcustom org-completion-fallback-command 'hippie-expand
2571 "The expansion command called by \\[org-complete] in normal context.
2572 Normal means, no org-mode-specific context."
2573 :group 'org-completion
2574 :type 'function)
2576 ;;; Functions and variables from ther packages
2577 ;; Declared here to avoid compiler warnings
2579 ;; XEmacs only
2580 (defvar outline-mode-menu-heading)
2581 (defvar outline-mode-menu-show)
2582 (defvar outline-mode-menu-hide)
2583 (defvar zmacs-regions) ; XEmacs regions
2585 ;; Emacs only
2586 (defvar mark-active)
2588 ;; Various packages
2589 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2590 (declare-function calendar-forward-day "cal-move" (arg))
2591 (declare-function calendar-goto-date "cal-move" (date))
2592 (declare-function calendar-goto-today "cal-move" ())
2593 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2594 (defvar calc-embedded-close-formula)
2595 (defvar calc-embedded-open-formula)
2596 (declare-function cdlatex-tab "ext:cdlatex" ())
2597 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2598 (defvar font-lock-unfontify-region-function)
2599 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2600 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2601 (defvar iswitchb-temp-buflist)
2602 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2603 (defvar org-agenda-tags-todo-honor-ignore-options)
2604 (declare-function org-agenda-skip "org-agenda" ())
2605 (declare-function org-format-agenda-item "org-agenda"
2606 (extra txt &optional category tags dotime noprefix remove-re))
2607 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2608 (declare-function org-agenda-change-all-lines "org-agenda"
2609 (newhead hdmarker &optional fixface just-this))
2610 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2611 (declare-function org-agenda-maybe-redo "org-agenda" ())
2612 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2613 (beg end))
2614 (declare-function org-agenda-copy-local-variable "org-agenda" (var))
2615 (declare-function org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item
2616 "org-agenda" (&optional end))
2618 (declare-function parse-time-string "parse-time" (string))
2619 (declare-function remember "remember" (&optional initial))
2620 (declare-function remember-buffer-desc "remember" ())
2621 (declare-function remember-finalize "remember" ())
2622 (defvar remember-save-after-remembering)
2623 (defvar remember-data-file)
2624 (defvar remember-register)
2625 (defvar remember-buffer)
2626 (defvar remember-handler-functions)
2627 (defvar remember-annotation-functions)
2628 (defvar texmathp-why)
2629 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2630 (declare-function table--at-cell-p "table" (position &optional object at-column))
2632 (defvar w3m-current-url)
2633 (defvar w3m-current-title)
2635 (defvar org-latex-regexps)
2637 ;;; Autoload and prepare some org modules
2639 ;; Some table stuff that needs to be defined here, because it is used
2640 ;; by the functions setting up org-mode or checking for table context.
2642 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2643 "Detects an org-type or table-type table.")
2644 (defconst org-table-line-regexp "^[ \t]*|"
2645 "Detects an org-type table line.")
2646 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2647 "Detects an org-type table line.")
2648 (defconst org-table-hline-regexp "^[ \t]*|-"
2649 "Detects an org-type table hline.")
2650 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2651 "Detects a table-type table hline.")
2652 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2653 "Searching from within a table (any type) this finds the first line
2654 outside the table.")
2656 ;; Autoload the functions in org-table.el that are needed by functions here.
2658 (eval-and-compile
2659 (org-autoload "org-table"
2660 '(org-table-align org-table-begin org-table-blank-field
2661 org-table-convert org-table-convert-region org-table-copy-down
2662 org-table-copy-region org-table-create
2663 org-table-create-or-convert-from-region
2664 org-table-create-with-table.el org-table-current-dline
2665 org-table-cut-region org-table-delete-column org-table-edit-field
2666 org-table-edit-formulas org-table-end org-table-eval-formula
2667 org-table-export org-table-field-info
2668 org-table-get-stored-formulas org-table-goto-column
2669 org-table-hline-and-move org-table-import org-table-insert-column
2670 org-table-insert-hline org-table-insert-row org-table-iterate
2671 org-table-justify-field-maybe org-table-kill-row
2672 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2673 org-table-move-column org-table-move-column-left
2674 org-table-move-column-right org-table-move-row
2675 org-table-move-row-down org-table-move-row-up
2676 org-table-next-field org-table-next-row org-table-paste-rectangle
2677 org-table-previous-field org-table-recalculate
2678 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2679 org-table-toggle-coordinate-overlays
2680 org-table-toggle-formula-debugger org-table-wrap-region
2681 orgtbl-mode turn-on-orgtbl org-table-to-lisp)))
2683 (defun org-at-table-p (&optional table-type)
2684 "Return t if the cursor is inside an org-type table.
2685 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2686 (if org-enable-table-editor
2687 (save-excursion
2688 (beginning-of-line 1)
2689 (looking-at (if table-type org-table-any-line-regexp
2690 org-table-line-regexp)))
2691 nil))
2692 (defsubst org-table-p () (org-at-table-p))
2694 (defun org-at-table.el-p ()
2695 "Return t if and only if we are at a table.el table."
2696 (and (org-at-table-p 'any)
2697 (save-excursion
2698 (goto-char (org-table-begin 'any))
2699 (looking-at org-table1-hline-regexp))))
2700 (defun org-table-recognize-table.el ()
2701 "If there is a table.el table nearby, recognize it and move into it."
2702 (if org-table-tab-recognizes-table.el
2703 (if (org-at-table.el-p)
2704 (progn
2705 (beginning-of-line 1)
2706 (if (looking-at org-table-dataline-regexp)
2708 (if (looking-at org-table1-hline-regexp)
2709 (progn
2710 (beginning-of-line 2)
2711 (if (looking-at org-table-any-border-regexp)
2712 (beginning-of-line -1)))))
2713 (if (re-search-forward "|" (org-table-end t) t)
2714 (progn
2715 (require 'table)
2716 (if (table--at-cell-p (point))
2718 (message "recognizing table.el table...")
2719 (table-recognize-table)
2720 (message "recognizing table.el table...done")))
2721 (error "This should not happen..."))
2723 nil)
2724 nil))
2726 (defun org-at-table-hline-p ()
2727 "Return t if the cursor is inside a hline in a table."
2728 (if org-enable-table-editor
2729 (save-excursion
2730 (beginning-of-line 1)
2731 (looking-at org-table-hline-regexp))
2732 nil))
2734 (defvar org-table-clean-did-remove-column nil)
2736 (defun org-table-map-tables (function)
2737 "Apply FUNCTION to the start of all tables in the buffer."
2738 (save-excursion
2739 (save-restriction
2740 (widen)
2741 (goto-char (point-min))
2742 (while (re-search-forward org-table-any-line-regexp nil t)
2743 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2744 (beginning-of-line 1)
2745 (if (looking-at org-table-line-regexp)
2746 (save-excursion (funcall function)))
2747 (re-search-forward org-table-any-border-regexp nil 1))))
2748 (message "Mapping tables: done"))
2750 ;; Declare and autoload functions from org-exp.el
2752 (declare-function org-default-export-plist "org-exp")
2753 (declare-function org-infile-export-plist "org-exp")
2754 (declare-function org-get-current-options "org-exp")
2755 (eval-and-compile
2756 (org-autoload "org-exp"
2757 '(org-export org-export-as-ascii org-export-visible
2758 org-insert-export-options-template org-export-as-html-and-open
2759 org-export-as-html-batch org-export-as-html-to-buffer
2760 org-replace-region-by-html org-export-region-as-html
2761 org-export-as-html org-export-icalendar-this-file
2762 org-export-icalendar-all-agenda-files
2763 org-table-clean-before-export
2764 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2766 ;; Declare and autoload functions from org-agenda.el
2768 (eval-and-compile
2769 (org-autoload "org-agenda"
2770 '(org-agenda org-agenda-list org-search-view
2771 org-todo-list org-tags-view org-agenda-list-stuck-projects
2772 org-diary org-agenda-to-appt
2773 org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))
2775 ;; Autoload org-remember
2777 (eval-and-compile
2778 (org-autoload "org-remember"
2779 '(org-remember-insinuate org-remember-annotation
2780 org-remember-apply-template org-remember org-remember-handler)))
2782 ;; Autoload org-clock.el
2785 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2786 (beg end))
2787 (declare-function org-clock-update-mode-line "org-clock" ())
2788 (defvar org-clock-start-time)
2789 (defvar org-clock-marker (make-marker)
2790 "Marker recording the last clock-in.")
2792 (eval-and-compile
2793 (org-autoload
2794 "org-clock"
2795 '(org-clock-in org-clock-out org-clock-cancel
2796 org-clock-goto org-clock-sum org-clock-display
2797 org-clock-remove-overlays org-clock-report
2798 org-clocktable-shift org-dblock-write:clocktable
2799 org-get-clocktable)))
2801 (defun org-clock-update-time-maybe ()
2802 "If this is a CLOCK line, update it and return t.
2803 Otherwise, return nil."
2804 (interactive)
2805 (save-excursion
2806 (beginning-of-line 1)
2807 (skip-chars-forward " \t")
2808 (when (looking-at org-clock-string)
2809 (let ((re (concat "[ \t]*" org-clock-string
2810 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2811 "\\([ \t]*=>.*\\)?\\)?"))
2812 ts te h m s neg)
2813 (cond
2814 ((not (looking-at re))
2815 nil)
2816 ((not (match-end 2))
2817 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2818 (> org-clock-marker (point))
2819 (<= org-clock-marker (point-at-eol)))
2820 ;; The clock is running here
2821 (setq org-clock-start-time
2822 (apply 'encode-time
2823 (org-parse-time-string (match-string 1))))
2824 (org-clock-update-mode-line)))
2826 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2827 (end-of-line 1)
2828 (setq ts (match-string 1)
2829 te (match-string 3))
2830 (setq s (- (time-to-seconds
2831 (apply 'encode-time (org-parse-time-string te)))
2832 (time-to-seconds
2833 (apply 'encode-time (org-parse-time-string ts))))
2834 neg (< s 0)
2835 s (abs s)
2836 h (floor (/ s 3600))
2837 s (- s (* 3600 h))
2838 m (floor (/ s 60))
2839 s (- s (* 60 s)))
2840 (insert " => " (format (if neg "-%d:%02d" "%2d:%02d") h m))
2841 t))))))
2843 (defun org-check-running-clock ()
2844 "Check if the current buffer contains the running clock.
2845 If yes, offer to stop it and to save the buffer with the changes."
2846 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2847 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2848 (buffer-name))))
2849 (org-clock-out)
2850 (when (y-or-n-p "Save changed buffer?")
2851 (save-buffer))))
2853 (defun org-clocktable-try-shift (dir n)
2854 "Check if this line starts a clock table, if yes, shift the time block."
2855 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2856 (org-clocktable-shift dir n)))
2858 ;; Autoload org-timer.el
2860 ;(declare-function org-timer "org-timer")
2862 (eval-and-compile
2863 (org-autoload
2864 "org-timer"
2865 '(org-timer-start org-timer org-timer-item
2866 org-timer-change-times-in-region)))
2869 ;; Autoload archiving code
2870 ;; The stuff that is needed for cycling and tags has to be defined here.
2872 (defgroup org-archive nil
2873 "Options concerning archiving in Org-mode."
2874 :tag "Org Archive"
2875 :group 'org-structure)
2877 (defcustom org-archive-location "%s_archive::"
2878 "The location where subtrees should be archived.
2880 The value of this variable is a string, consisting of two parts,
2881 separated by a double-colon. The first part is a filename and
2882 the second part is a headline.
2884 When the filename is omitted, archiving happens in the same file.
2885 %s in the filename will be replaced by the current file
2886 name (without the directory part). Archiving to a different file
2887 is useful to keep archived entries from contributing to the
2888 Org-mode Agenda.
2890 The archived entries will be filed as subtrees of the specified
2891 headline. When the headline is omitted, the subtrees are simply
2892 filed away at the end of the file, as top-level entries. Also in
2893 the heading you can use %s to represent the file name, this can be
2894 useful when using the same archive for a number of different files.
2896 Here are a few examples:
2897 \"%s_archive::\"
2898 If the current file is Projects.org, archive in file
2899 Projects.org_archive, as top-level trees. This is the default.
2901 \"::* Archived Tasks\"
2902 Archive in the current file, under the top-level headline
2903 \"* Archived Tasks\".
2905 \"~/org/archive.org::\"
2906 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2908 \"~/org/archive.org::From %s\"
2909 Archive in file ~/org/archive.org (absolute path), und headlines
2910 \"From FILENAME\" where file name is the current file name.
2912 \"basement::** Finished Tasks\"
2913 Archive in file ./basement (relative path), as level 3 trees
2914 below the level 2 heading \"** Finished Tasks\".
2916 You may set this option on a per-file basis by adding to the buffer a
2917 line like
2919 #+ARCHIVE: basement::** Finished Tasks
2921 You may also define it locally for a subtree by setting an ARCHIVE property
2922 in the entry. If such a property is found in an entry, or anywhere up
2923 the hierarchy, it will be used."
2924 :group 'org-archive
2925 :type 'string)
2927 (defcustom org-archive-tag "ARCHIVE"
2928 "The tag that marks a subtree as archived.
2929 An archived subtree does not open during visibility cycling, and does
2930 not contribute to the agenda listings.
2931 After changing this, font-lock must be restarted in the relevant buffers to
2932 get the proper fontification."
2933 :group 'org-archive
2934 :group 'org-keywords
2935 :type 'string)
2937 (defcustom org-agenda-skip-archived-trees t
2938 "Non-nil means, the agenda will skip any items located in archived trees.
2939 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2940 variable is no longer recommended, you should leave it at the value t.
2941 Instead, use the key `v' to cycle the archives-mode in the agenda."
2942 :group 'org-archive
2943 :group 'org-agenda-skip
2944 :type 'boolean)
2946 (defcustom org-cycle-open-archived-trees nil
2947 "Non-nil means, `org-cycle' will open archived trees.
2948 An archived tree is a tree marked with the tag ARCHIVE.
2949 When nil, archived trees will stay folded. You can still open them with
2950 normal outline commands like `show-all', but not with the cycling commands."
2951 :group 'org-archive
2952 :group 'org-cycle
2953 :type 'boolean)
2955 (defcustom org-sparse-tree-open-archived-trees nil
2956 "Non-nil means sparse tree construction shows matches in archived trees.
2957 When nil, matches in these trees are highlighted, but the trees are kept in
2958 collapsed state."
2959 :group 'org-archive
2960 :group 'org-sparse-trees
2961 :type 'boolean)
2963 (defun org-cycle-hide-archived-subtrees (state)
2964 "Re-hide all archived subtrees after a visibility state change."
2965 (when (and (not org-cycle-open-archived-trees)
2966 (not (memq state '(overview folded))))
2967 (save-excursion
2968 (let* ((globalp (memq state '(contents all)))
2969 (beg (if globalp (point-min) (point)))
2970 (end (if globalp (point-max) (org-end-of-subtree t))))
2971 (org-hide-archived-subtrees beg end)
2972 (goto-char beg)
2973 (if (looking-at (concat ".*:" org-archive-tag ":"))
2974 (message "%s" (substitute-command-keys
2975 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2977 (defun org-force-cycle-archived ()
2978 "Cycle subtree even if it is archived."
2979 (interactive)
2980 (setq this-command 'org-cycle)
2981 (let ((org-cycle-open-archived-trees t))
2982 (call-interactively 'org-cycle)))
2984 (defun org-hide-archived-subtrees (beg end)
2985 "Re-hide all archived subtrees after a visibility state change."
2986 (save-excursion
2987 (let* ((re (concat ":" org-archive-tag ":")))
2988 (goto-char beg)
2989 (while (re-search-forward re end t)
2990 (and (org-on-heading-p) (hide-subtree))
2991 (org-end-of-subtree t)))))
2993 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2995 (eval-and-compile
2996 (org-autoload "org-archive"
2997 '(org-add-archive-files org-archive-subtree
2998 org-archive-to-archive-sibling org-toggle-archive-tag)))
3000 ;; Autoload Column View Code
3002 (declare-function org-columns-number-to-string "org-colview")
3003 (declare-function org-columns-get-format-and-top-level "org-colview")
3004 (declare-function org-columns-compute "org-colview")
3006 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
3007 '(org-columns-number-to-string org-columns-get-format-and-top-level
3008 org-columns-compute org-agenda-columns org-columns-remove-overlays
3009 org-columns org-insert-columns-dblock org-dblock-write:columnview))
3011 ;; Autoload ID code
3013 (declare-function org-id-store-link "org-id")
3014 (org-autoload "org-id"
3015 '(org-id-get-create org-id-new org-id-copy org-id-get
3016 org-id-get-with-outline-path-completion
3017 org-id-get-with-outline-drilling
3018 org-id-goto org-id-find org-id-store-link))
3020 ;;; Variables for pre-computed regular expressions, all buffer local
3022 (defvar org-drawer-regexp nil
3023 "Matches first line of a hidden block.")
3024 (make-variable-buffer-local 'org-drawer-regexp)
3025 (defvar org-todo-regexp nil
3026 "Matches any of the TODO state keywords.")
3027 (make-variable-buffer-local 'org-todo-regexp)
3028 (defvar org-not-done-regexp nil
3029 "Matches any of the TODO state keywords except the last one.")
3030 (make-variable-buffer-local 'org-not-done-regexp)
3031 (defvar org-todo-line-regexp nil
3032 "Matches a headline and puts TODO state into group 2 if present.")
3033 (make-variable-buffer-local 'org-todo-line-regexp)
3034 (defvar org-complex-heading-regexp nil
3035 "Matches a headline and puts everything into groups:
3036 group 1: the stars
3037 group 2: The todo keyword, maybe
3038 group 3: Priority cookie
3039 group 4: True headline
3040 group 5: Tags")
3041 (make-variable-buffer-local 'org-complex-heading-regexp)
3042 (defvar org-todo-line-tags-regexp nil
3043 "Matches a headline and puts TODO state into group 2 if present.
3044 Also put tags into group 4 if tags are present.")
3045 (make-variable-buffer-local 'org-todo-line-tags-regexp)
3046 (defvar org-nl-done-regexp nil
3047 "Matches newline followed by a headline with the DONE keyword.")
3048 (make-variable-buffer-local 'org-nl-done-regexp)
3049 (defvar org-looking-at-done-regexp nil
3050 "Matches the DONE keyword a point.")
3051 (make-variable-buffer-local 'org-looking-at-done-regexp)
3052 (defvar org-ds-keyword-length 12
3053 "Maximum length of the Deadline and SCHEDULED keywords.")
3054 (make-variable-buffer-local 'org-ds-keyword-length)
3055 (defvar org-deadline-regexp nil
3056 "Matches the DEADLINE keyword.")
3057 (make-variable-buffer-local 'org-deadline-regexp)
3058 (defvar org-deadline-time-regexp nil
3059 "Matches the DEADLINE keyword together with a time stamp.")
3060 (make-variable-buffer-local 'org-deadline-time-regexp)
3061 (defvar org-deadline-line-regexp nil
3062 "Matches the DEADLINE keyword and the rest of the line.")
3063 (make-variable-buffer-local 'org-deadline-line-regexp)
3064 (defvar org-scheduled-regexp nil
3065 "Matches the SCHEDULED keyword.")
3066 (make-variable-buffer-local 'org-scheduled-regexp)
3067 (defvar org-scheduled-time-regexp nil
3068 "Matches the SCHEDULED keyword together with a time stamp.")
3069 (make-variable-buffer-local 'org-scheduled-time-regexp)
3070 (defvar org-closed-time-regexp nil
3071 "Matches the CLOSED keyword together with a time stamp.")
3072 (make-variable-buffer-local 'org-closed-time-regexp)
3074 (defvar org-keyword-time-regexp nil
3075 "Matches any of the 4 keywords, together with the time stamp.")
3076 (make-variable-buffer-local 'org-keyword-time-regexp)
3077 (defvar org-keyword-time-not-clock-regexp nil
3078 "Matches any of the 3 keywords, together with the time stamp.")
3079 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
3080 (defvar org-maybe-keyword-time-regexp nil
3081 "Matches a timestamp, possibly preceeded by a keyword.")
3082 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
3083 (defvar org-planning-or-clock-line-re nil
3084 "Matches a line with planning or clock info.")
3085 (make-variable-buffer-local 'org-planning-or-clock-line-re)
3087 (defconst org-plain-time-of-day-regexp
3088 (concat
3089 "\\(\\<[012]?[0-9]"
3090 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3091 "\\(--?"
3092 "\\(\\<[012]?[0-9]"
3093 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3094 "\\)?")
3095 "Regular expression to match a plain time or time range.
3096 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3097 groups carry important information:
3098 0 the full match
3099 1 the first time, range or not
3100 8 the second time, if it is a range.")
3102 (defconst org-plain-time-extension-regexp
3103 (concat
3104 "\\(\\<[012]?[0-9]"
3105 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
3106 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
3107 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
3108 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
3109 groups carry important information:
3110 0 the full match
3111 7 hours of duration
3112 9 minutes of duration")
3114 (defconst org-stamp-time-of-day-regexp
3115 (concat
3116 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
3117 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
3118 "\\(--?"
3119 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
3120 "Regular expression to match a timestamp time or time range.
3121 After a match, the following groups carry important information:
3122 0 the full match
3123 1 date plus weekday, for backreferencing to make sure both times on same day
3124 2 the first time, range or not
3125 4 the second time, if it is a range.")
3127 (defconst org-startup-options
3128 '(("fold" org-startup-folded t)
3129 ("overview" org-startup-folded t)
3130 ("nofold" org-startup-folded nil)
3131 ("showall" org-startup-folded nil)
3132 ("content" org-startup-folded content)
3133 ("hidestars" org-hide-leading-stars t)
3134 ("showstars" org-hide-leading-stars nil)
3135 ("odd" org-odd-levels-only t)
3136 ("oddeven" org-odd-levels-only nil)
3137 ("align" org-startup-align-all-tables t)
3138 ("noalign" org-startup-align-all-tables nil)
3139 ("customtime" org-display-custom-times t)
3140 ("logdone" org-log-done time)
3141 ("lognotedone" org-log-done note)
3142 ("nologdone" org-log-done nil)
3143 ("lognoteclock-out" org-log-note-clock-out t)
3144 ("nolognoteclock-out" org-log-note-clock-out nil)
3145 ("logrepeat" org-log-repeat state)
3146 ("lognoterepeat" org-log-repeat note)
3147 ("nologrepeat" org-log-repeat nil)
3148 ("fninline" org-footnote-define-inline t)
3149 ("nofninline" org-footnote-define-inline nil)
3150 ("fnlocal" org-footnote-section nil)
3151 ("fnauto" org-footnote-auto-label t)
3152 ("fnprompt" org-footnote-auto-label nil)
3153 ("fnconfirm" org-footnote-auto-label confirm)
3154 ("fnplain" org-footnote-auto-label plain)
3155 ("constcgs" constants-unit-system cgs)
3156 ("constSI" constants-unit-system SI))
3157 "Variable associated with STARTUP options for org-mode.
3158 Each element is a list of three items: The startup options as written
3159 in the #+STARTUP line, the corresponding variable, and the value to
3160 set this variable to if the option is found. An optional forth element PUSH
3161 means to push this value onto the list in the variable.")
3163 (defun org-set-regexps-and-options ()
3164 "Precompute regular expressions for current buffer."
3165 (when (org-mode-p)
3166 (org-set-local 'org-todo-kwd-alist nil)
3167 (org-set-local 'org-todo-key-alist nil)
3168 (org-set-local 'org-todo-key-trigger nil)
3169 (org-set-local 'org-todo-keywords-1 nil)
3170 (org-set-local 'org-done-keywords nil)
3171 (org-set-local 'org-todo-heads nil)
3172 (org-set-local 'org-todo-sets nil)
3173 (org-set-local 'org-todo-log-states nil)
3174 (org-set-local 'org-file-properties nil)
3175 (org-set-local 'org-file-tags nil)
3176 (let ((re (org-make-options-regexp
3177 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
3178 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
3179 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
3180 (splitre "[ \t]+")
3181 kwds kws0 kwsa key log value cat arch tags const links hw dws
3182 tail sep kws1 prio props ftags drawers
3183 ext-setup-or-nil setup-contents (start 0))
3184 (save-excursion
3185 (save-restriction
3186 (widen)
3187 (goto-char (point-min))
3188 (while (or (and ext-setup-or-nil
3189 (string-match re ext-setup-or-nil start)
3190 (setq start (match-end 0)))
3191 (and (setq ext-setup-or-nil nil start 0)
3192 (re-search-forward re nil t)))
3193 (setq key (upcase (match-string 1 ext-setup-or-nil))
3194 value (org-match-string-no-properties 2 ext-setup-or-nil))
3195 (cond
3196 ((equal key "CATEGORY")
3197 (if (string-match "[ \t]+$" value)
3198 (setq value (replace-match "" t t value)))
3199 (setq cat value))
3200 ((member key '("SEQ_TODO" "TODO"))
3201 (push (cons 'sequence (org-split-string value splitre)) kwds))
3202 ((equal key "TYP_TODO")
3203 (push (cons 'type (org-split-string value splitre)) kwds))
3204 ((equal key "TAGS")
3205 (setq tags (append tags (org-split-string value splitre))))
3206 ((equal key "COLUMNS")
3207 (org-set-local 'org-columns-default-format value))
3208 ((equal key "LINK")
3209 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
3210 (push (cons (match-string 1 value)
3211 (org-trim (match-string 2 value)))
3212 links)))
3213 ((equal key "PRIORITIES")
3214 (setq prio (org-split-string value " +")))
3215 ((equal key "PROPERTY")
3216 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
3217 (push (cons (match-string 1 value) (match-string 2 value))
3218 props)))
3219 ((equal key "FILETAGS")
3220 (when (string-match "\\S-" value)
3221 (setq ftags
3222 (append
3223 ftags
3224 (apply 'append
3225 (mapcar (lambda (x) (org-split-string x ":"))
3226 (org-split-string value)))))))
3227 ((equal key "DRAWERS")
3228 (setq drawers (org-split-string value splitre)))
3229 ((equal key "CONSTANTS")
3230 (setq const (append const (org-split-string value splitre))))
3231 ((equal key "STARTUP")
3232 (let ((opts (org-split-string value splitre))
3233 l var val)
3234 (while (setq l (pop opts))
3235 (when (setq l (assoc l org-startup-options))
3236 (setq var (nth 1 l) val (nth 2 l))
3237 (if (not (nth 3 l))
3238 (set (make-local-variable var) val)
3239 (if (not (listp (symbol-value var)))
3240 (set (make-local-variable var) nil))
3241 (set (make-local-variable var) (symbol-value var))
3242 (add-to-list var val))))))
3243 ((equal key "ARCHIVE")
3244 (string-match " *$" value)
3245 (setq arch (replace-match "" t t value))
3246 (remove-text-properties 0 (length arch)
3247 '(face t fontified t) arch))
3248 ((equal key "SETUPFILE")
3249 (setq setup-contents (org-file-contents
3250 (expand-file-name
3251 (org-remove-double-quotes value))
3252 'noerror))
3253 (if (not ext-setup-or-nil)
3254 (setq ext-setup-or-nil setup-contents start 0)
3255 (setq ext-setup-or-nil
3256 (concat (substring ext-setup-or-nil 0 start)
3257 "\n" setup-contents "\n"
3258 (substring ext-setup-or-nil start)))))
3259 ))))
3260 (when cat
3261 (org-set-local 'org-category (intern cat))
3262 (push (cons "CATEGORY" cat) props))
3263 (when prio
3264 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
3265 (setq prio (mapcar 'string-to-char prio))
3266 (org-set-local 'org-highest-priority (nth 0 prio))
3267 (org-set-local 'org-lowest-priority (nth 1 prio))
3268 (org-set-local 'org-default-priority (nth 2 prio)))
3269 (and props (org-set-local 'org-file-properties (nreverse props)))
3270 (and ftags (org-set-local 'org-file-tags ftags))
3271 (and drawers (org-set-local 'org-drawers drawers))
3272 (and arch (org-set-local 'org-archive-location arch))
3273 (and links (setq org-link-abbrev-alist-local (nreverse links)))
3274 ;; Process the TODO keywords
3275 (unless kwds
3276 ;; Use the global values as if they had been given locally.
3277 (setq kwds (default-value 'org-todo-keywords))
3278 (if (stringp (car kwds))
3279 (setq kwds (list (cons org-todo-interpretation
3280 (default-value 'org-todo-keywords)))))
3281 (setq kwds (reverse kwds)))
3282 (setq kwds (nreverse kwds))
3283 (let (inter kws kw)
3284 (while (setq kws (pop kwds))
3285 (setq inter (pop kws) sep (member "|" kws)
3286 kws0 (delete "|" (copy-sequence kws))
3287 kwsa nil
3288 kws1 (mapcar
3289 (lambda (x)
3290 ;; 1 2
3291 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
3292 (progn
3293 (setq kw (match-string 1 x)
3294 key (and (match-end 2) (match-string 2 x))
3295 log (org-extract-log-state-settings x))
3296 (push (cons kw (and key (string-to-char key))) kwsa)
3297 (and log (push log org-todo-log-states))
3299 (error "Invalid TODO keyword %s" x)))
3300 kws0)
3301 kwsa (if kwsa (append '((:startgroup))
3302 (nreverse kwsa)
3303 '((:endgroup))))
3304 hw (car kws1)
3305 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
3306 tail (list inter hw (car dws) (org-last dws)))
3307 (add-to-list 'org-todo-heads hw 'append)
3308 (push kws1 org-todo-sets)
3309 (setq org-done-keywords (append org-done-keywords dws nil))
3310 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
3311 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
3312 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
3313 (setq org-todo-sets (nreverse org-todo-sets)
3314 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
3315 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
3316 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
3317 ;; Process the constants
3318 (when const
3319 (let (e cst)
3320 (while (setq e (pop const))
3321 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
3322 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
3323 (setq org-table-formula-constants-local cst)))
3325 ;; Process the tags.
3326 (when tags
3327 (let (e tgs)
3328 (while (setq e (pop tags))
3329 (cond
3330 ((equal e "{") (push '(:startgroup) tgs))
3331 ((equal e "}") (push '(:endgroup) tgs))
3332 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
3333 (push (cons (match-string 1 e)
3334 (string-to-char (match-string 2 e)))
3335 tgs))
3336 (t (push (list e) tgs))))
3337 (org-set-local 'org-tag-alist nil)
3338 (while (setq e (pop tgs))
3339 (or (and (stringp (car e))
3340 (assoc (car e) org-tag-alist))
3341 (push e org-tag-alist)))))
3343 ;; Compute the regular expressions and other local variables
3344 (if (not org-done-keywords)
3345 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
3346 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
3347 (length org-scheduled-string)
3348 (length org-clock-string)
3349 (length org-closed-string)))
3350 org-drawer-regexp
3351 (concat "^[ \t]*:\\("
3352 (mapconcat 'regexp-quote org-drawers "\\|")
3353 "\\):[ \t]*$")
3354 org-not-done-keywords
3355 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
3356 org-todo-regexp
3357 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
3358 "\\|") "\\)\\>")
3359 org-not-done-regexp
3360 (concat "\\<\\("
3361 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
3362 "\\)\\>")
3363 org-todo-line-regexp
3364 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3365 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3366 "\\)\\>\\)?[ \t]*\\(.*\\)")
3367 org-complex-heading-regexp
3368 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3369 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3370 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3371 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3372 org-nl-done-regexp
3373 (concat "\n\\*+[ \t]+"
3374 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3375 "\\)" "\\>")
3376 org-todo-line-tags-regexp
3377 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3378 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3379 (org-re
3380 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3381 org-looking-at-done-regexp
3382 (concat "^" "\\(?:"
3383 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3384 "\\>")
3385 org-deadline-regexp (concat "\\<" org-deadline-string)
3386 org-deadline-time-regexp
3387 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3388 org-deadline-line-regexp
3389 (concat "\\<\\(" org-deadline-string "\\).*")
3390 org-scheduled-regexp
3391 (concat "\\<" org-scheduled-string)
3392 org-scheduled-time-regexp
3393 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3394 org-closed-time-regexp
3395 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3396 org-keyword-time-regexp
3397 (concat "\\<\\(" org-scheduled-string
3398 "\\|" org-deadline-string
3399 "\\|" org-closed-string
3400 "\\|" org-clock-string "\\)"
3401 " *[[<]\\([^]>]+\\)[]>]")
3402 org-keyword-time-not-clock-regexp
3403 (concat "\\<\\(" org-scheduled-string
3404 "\\|" org-deadline-string
3405 "\\|" org-closed-string
3406 "\\)"
3407 " *[[<]\\([^]>]+\\)[]>]")
3408 org-maybe-keyword-time-regexp
3409 (concat "\\(\\<\\(" org-scheduled-string
3410 "\\|" org-deadline-string
3411 "\\|" org-closed-string
3412 "\\|" org-clock-string "\\)\\)?"
3413 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3414 org-planning-or-clock-line-re
3415 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3416 "\\|" org-deadline-string
3417 "\\|" org-closed-string "\\|" org-clock-string
3418 "\\)\\>\\)")
3420 (org-compute-latex-and-specials-regexp)
3421 (org-set-font-lock-defaults))))
3423 (defun org-file-contents (file &optional noerror)
3424 "Return the contents of FILE, as a string."
3425 (if (or (not file)
3426 (not (file-readable-p file)))
3427 (if noerror
3428 (progn
3429 (message "Cannot read file %s" file)
3430 (ding) (sit-for 2)
3432 (error "Cannot read file %s" file))
3433 (with-temp-buffer
3434 (insert-file-contents file)
3435 (buffer-string))))
3437 (defun org-extract-log-state-settings (x)
3438 "Extract the log state setting from a TODO keyword string.
3439 This will extract info from a string like \"WAIT(w@/!)\"."
3440 (let (kw key log1 log2)
3441 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3442 (setq kw (match-string 1 x)
3443 key (and (match-end 2) (match-string 2 x))
3444 log1 (and (match-end 3) (match-string 3 x))
3445 log2 (and (match-end 4) (match-string 4 x)))
3446 (and (or log1 log2)
3447 (list kw
3448 (and log1 (if (equal log1 "!") 'time 'note))
3449 (and log2 (if (equal log2 "!") 'time 'note)))))))
3451 (defun org-remove-keyword-keys (list)
3452 "Remove a pair of parenthesis at the end of each string in LIST."
3453 (mapcar (lambda (x)
3454 (if (string-match "(.*)$" x)
3455 (substring x 0 (match-beginning 0))
3457 list))
3459 ;; FIXME: this could be done much better, using second characters etc.
3460 (defun org-assign-fast-keys (alist)
3461 "Assign fast keys to a keyword-key alist.
3462 Respect keys that are already there."
3463 (let (new e k c c1 c2 (char ?a))
3464 (while (setq e (pop alist))
3465 (cond
3466 ((equal e '(:startgroup)) (push e new))
3467 ((equal e '(:endgroup)) (push e new))
3469 (setq k (car e) c2 nil)
3470 (if (cdr e)
3471 (setq c (cdr e))
3472 ;; automatically assign a character.
3473 (setq c1 (string-to-char
3474 (downcase (substring
3475 k (if (= (string-to-char k) ?@) 1 0)))))
3476 (if (or (rassoc c1 new) (rassoc c1 alist))
3477 (while (or (rassoc char new) (rassoc char alist))
3478 (setq char (1+ char)))
3479 (setq c2 c1))
3480 (setq c (or c2 char)))
3481 (push (cons k c) new))))
3482 (nreverse new)))
3484 ;;; Some variables used in various places
3486 (defvar org-window-configuration nil
3487 "Used in various places to store a window configuration.")
3488 (defvar org-finish-function nil
3489 "Function to be called when `C-c C-c' is used.
3490 This is for getting out of special buffers like remember.")
3493 ;; FIXME: Occasionally check by commenting these, to make sure
3494 ;; no other functions uses these, forgetting to let-bind them.
3495 (defvar entry)
3496 (defvar state)
3497 (defvar last-state)
3498 (defvar date)
3499 (defvar description)
3501 ;; Defined somewhere in this file, but used before definition.
3502 (defvar org-html-entities)
3503 (defvar org-struct-menu)
3504 (defvar org-org-menu)
3505 (defvar org-tbl-menu)
3506 (defvar org-agenda-keymap)
3508 ;;;; Define the Org-mode
3510 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3511 (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."))
3514 ;; We use a before-change function to check if a table might need
3515 ;; an update.
3516 (defvar org-table-may-need-update t
3517 "Indicates that a table might need an update.
3518 This variable is set by `org-before-change-function'.
3519 `org-table-align' sets it back to nil.")
3520 (defun org-before-change-function (beg end)
3521 "Every change indicates that a table might need an update."
3522 (setq org-table-may-need-update t))
3523 (defvar org-mode-map)
3524 (defvar org-mode-hook nil
3525 "Mode hook for Org-mode, run after the mode was turned on.")
3526 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3527 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3528 (defvar org-table-buffer-is-an nil)
3529 (defconst org-outline-regexp "\\*+ ")
3531 ;;;###autoload
3532 (define-derived-mode org-mode outline-mode "Org"
3533 "Outline-based notes management and organizer, alias
3534 \"Carsten's outline-mode for keeping track of everything.\"
3536 Org-mode develops organizational tasks around a NOTES file which
3537 contains information about projects as plain text. Org-mode is
3538 implemented on top of outline-mode, which is ideal to keep the content
3539 of large files well structured. It supports ToDo items, deadlines and
3540 time stamps, which magically appear in the diary listing of the Emacs
3541 calendar. Tables are easily created with a built-in table editor.
3542 Plain text URL-like links connect to websites, emails (VM), Usenet
3543 messages (Gnus), BBDB entries, and any files related to the project.
3544 For printing and sharing of notes, an Org-mode file (or a part of it)
3545 can be exported as a structured ASCII or HTML file.
3547 The following commands are available:
3549 \\{org-mode-map}"
3551 ;; Get rid of Outline menus, they are not needed
3552 ;; Need to do this here because define-derived-mode sets up
3553 ;; the keymap so late. Still, it is a waste to call this each time
3554 ;; we switch another buffer into org-mode.
3555 (if (featurep 'xemacs)
3556 (when (boundp 'outline-mode-menu-heading)
3557 ;; Assume this is Greg's port, it used easymenu
3558 (easy-menu-remove outline-mode-menu-heading)
3559 (easy-menu-remove outline-mode-menu-show)
3560 (easy-menu-remove outline-mode-menu-hide))
3561 (define-key org-mode-map [menu-bar headings] 'undefined)
3562 (define-key org-mode-map [menu-bar hide] 'undefined)
3563 (define-key org-mode-map [menu-bar show] 'undefined))
3565 (org-load-modules-maybe)
3566 (easy-menu-add org-org-menu)
3567 (easy-menu-add org-tbl-menu)
3568 (org-install-agenda-files-menu)
3569 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3570 (org-add-to-invisibility-spec '(org-cwidth))
3571 (when (featurep 'xemacs)
3572 (org-set-local 'line-move-ignore-invisible t))
3573 (org-set-local 'outline-regexp org-outline-regexp)
3574 (org-set-local 'outline-level 'org-outline-level)
3575 (when (and org-ellipsis
3576 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3577 (fboundp 'make-glyph-code))
3578 (unless org-display-table
3579 (setq org-display-table (make-display-table)))
3580 (set-display-table-slot
3581 org-display-table 4
3582 (vconcat (mapcar
3583 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3584 org-ellipsis)))
3585 (if (stringp org-ellipsis) org-ellipsis "..."))))
3586 (setq buffer-display-table org-display-table))
3587 (org-set-regexps-and-options)
3588 (when (and org-tag-faces (not org-tags-special-faces-re))
3589 ;; tag faces set outside customize.... force initialization.
3590 (org-set-tag-faces 'org-tag-faces org-tag-faces))
3591 ;; Calc embedded
3592 (org-set-local 'calc-embedded-open-mode "# ")
3593 (modify-syntax-entry ?# "<")
3594 (modify-syntax-entry ?@ "w")
3595 (if org-startup-truncated (setq truncate-lines t))
3596 (org-set-local 'font-lock-unfontify-region-function
3597 'org-unfontify-region)
3598 ;; Activate before-change-function
3599 (org-set-local 'org-table-may-need-update t)
3600 (org-add-hook 'before-change-functions 'org-before-change-function nil
3601 'local)
3602 ;; Check for running clock before killing a buffer
3603 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3604 ;; Paragraphs and auto-filling
3605 (org-set-autofill-regexps)
3606 (setq indent-line-function 'org-indent-line-function)
3607 (org-update-radio-target-regexp)
3608 ;; Make sure dependence stuff works reliably, even for users who set it
3609 ;; too late :-(
3610 (if org-enforce-todo-dependencies
3611 (add-hook 'org-blocker-hook
3612 'org-block-todo-from-children-or-siblings)
3613 (remove-hook 'org-blocker-hook
3614 'org-block-todo-from-children-or-siblings))
3615 (if org-enforce-todo-checkbox-dependencies
3616 (add-hook 'org-blocker-hook
3617 'org-block-todo-from-checkboxes)
3618 (remove-hook 'org-blocker-hook
3619 'org-block-todo-from-checkboxes))
3621 ;; Comment characters
3622 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3623 (org-set-local 'comment-padding " ")
3625 ;; Align options lines
3626 (org-set-local
3627 'align-mode-rules-list
3628 '((org-in-buffer-settings
3629 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3630 (modes . '(org-mode)))))
3632 ;; Imenu
3633 (org-set-local 'imenu-create-index-function
3634 'org-imenu-get-tree)
3636 ;; Make isearch reveal context
3637 (if (or (featurep 'xemacs)
3638 (not (boundp 'outline-isearch-open-invisible-function)))
3639 ;; Emacs 21 and XEmacs make use of the hook
3640 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3641 ;; Emacs 22 deals with this through a special variable
3642 (org-set-local 'outline-isearch-open-invisible-function
3643 (lambda (&rest ignore) (org-show-context 'isearch))))
3645 ;; If empty file that did not turn on org-mode automatically, make it to.
3646 (if (and org-insert-mode-line-in-empty-file
3647 (interactive-p)
3648 (= (point-min) (point-max)))
3649 (insert "# -*- mode: org -*-\n\n"))
3651 (unless org-inhibit-startup
3652 (when org-startup-align-all-tables
3653 (let ((bmp (buffer-modified-p)))
3654 (org-table-map-tables 'org-table-align)
3655 (set-buffer-modified-p bmp)))
3656 (org-set-startup-visibility)))
3658 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3660 (defun org-current-time ()
3661 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3662 (if (> (car org-time-stamp-rounding-minutes) 1)
3663 (let ((r (car org-time-stamp-rounding-minutes))
3664 (time (decode-time)))
3665 (apply 'encode-time
3666 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3667 (nthcdr 2 time))))
3668 (current-time)))
3670 ;;;; Font-Lock stuff, including the activators
3672 (defvar org-mouse-map (make-sparse-keymap))
3673 (org-defkey org-mouse-map
3674 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3675 (org-defkey org-mouse-map
3676 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3677 (when org-mouse-1-follows-link
3678 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3679 (when org-tab-follows-link
3680 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3681 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3682 (when org-return-follows-link
3683 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3684 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3686 (require 'font-lock)
3688 (defconst org-non-link-chars "]\t\n\r<>")
3689 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3690 "shell" "elisp"))
3691 (defvar org-link-types-re nil
3692 "Matches a link that has a url-like prefix like \"http:\"")
3693 (defvar org-link-re-with-space nil
3694 "Matches a link with spaces, optional angular brackets around it.")
3695 (defvar org-link-re-with-space2 nil
3696 "Matches a link with spaces, optional angular brackets around it.")
3697 (defvar org-link-re-with-space3 nil
3698 "Matches a link with spaces, only for internal part in bracket links.")
3699 (defvar org-angle-link-re nil
3700 "Matches link with angular brackets, spaces are allowed.")
3701 (defvar org-plain-link-re nil
3702 "Matches plain link, without spaces.")
3703 (defvar org-bracket-link-regexp nil
3704 "Matches a link in double brackets.")
3705 (defvar org-bracket-link-analytic-regexp nil
3706 "Regular expression used to analyze links.
3707 Here is what the match groups contain after a match:
3708 1: http:
3709 2: http
3710 3: path
3711 4: [desc]
3712 5: desc")
3713 (defvar org-bracket-link-analytic-regexp++ nil
3714 "Like org-bracket-link-analytic-regexp, but include coderef internal type.")
3715 (defvar org-any-link-re nil
3716 "Regular expression matching any link.")
3718 (defun org-make-link-regexps ()
3719 "Update the link regular expressions.
3720 This should be called after the variable `org-link-types' has changed."
3721 (setq org-link-types-re
3722 (concat
3723 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3724 org-link-re-with-space
3725 (concat
3726 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3727 "\\([^" org-non-link-chars " ]"
3728 "[^" org-non-link-chars "]*"
3729 "[^" org-non-link-chars " ]\\)>?")
3730 org-link-re-with-space2
3731 (concat
3732 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3733 "\\([^" org-non-link-chars " ]"
3734 "[^\t\n\r]*"
3735 "[^" org-non-link-chars " ]\\)>?")
3736 org-link-re-with-space3
3737 (concat
3738 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3739 "\\([^" org-non-link-chars " ]"
3740 "[^\t\n\r]*\\)")
3741 org-angle-link-re
3742 (concat
3743 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3744 "\\([^" org-non-link-chars " ]"
3745 "[^" org-non-link-chars "]*"
3746 "\\)>")
3747 org-plain-link-re
3748 (concat
3749 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3750 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3751 org-bracket-link-regexp
3752 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3753 org-bracket-link-analytic-regexp
3754 (concat
3755 "\\[\\["
3756 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3757 "\\([^]]+\\)"
3758 "\\]"
3759 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3760 "\\]")
3761 org-bracket-link-analytic-regexp++
3762 (concat
3763 "\\[\\["
3764 "\\(\\(" (mapconcat 'identity (cons "coderef" org-link-types) "\\|") "\\):\\)?"
3765 "\\([^]]+\\)"
3766 "\\]"
3767 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3768 "\\]")
3769 org-any-link-re
3770 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3771 org-angle-link-re "\\)\\|\\("
3772 org-plain-link-re "\\)")))
3774 (org-make-link-regexps)
3776 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3777 "Regular expression for fast time stamp matching.")
3778 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3779 "Regular expression for fast time stamp matching.")
3780 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3781 "Regular expression matching time strings for analysis.
3782 This one does not require the space after the date, so it can be used
3783 on a string that terminates immediately after the date.")
3784 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3785 "Regular expression matching time strings for analysis.")
3786 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3787 "Regular expression matching time stamps, with groups.")
3788 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3789 "Regular expression matching time stamps (also [..]), with groups.")
3790 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3791 "Regular expression matching a time stamp range.")
3792 (defconst org-tr-regexp-both
3793 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3794 "Regular expression matching a time stamp range.")
3795 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3796 org-ts-regexp "\\)?")
3797 "Regular expression matching a time stamp or time stamp range.")
3798 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3799 org-ts-regexp-both "\\)?")
3800 "Regular expression matching a time stamp or time stamp range.
3801 The time stamps may be either active or inactive.")
3803 (defvar org-emph-face nil)
3805 (defun org-do-emphasis-faces (limit)
3806 "Run through the buffer and add overlays to links."
3807 (let (rtn)
3808 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3809 (if (not (= (char-after (match-beginning 3))
3810 (char-after (match-beginning 4))))
3811 (progn
3812 (setq rtn t)
3813 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3814 'face
3815 (nth 1 (assoc (match-string 3)
3816 org-emphasis-alist)))
3817 (add-text-properties (match-beginning 2) (match-end 2)
3818 '(font-lock-multiline t))
3819 (when org-hide-emphasis-markers
3820 (add-text-properties (match-end 4) (match-beginning 5)
3821 '(invisible org-link))
3822 (add-text-properties (match-beginning 3) (match-end 3)
3823 '(invisible org-link)))))
3824 (backward-char 1))
3825 rtn))
3827 (defun org-emphasize (&optional char)
3828 "Insert or change an emphasis, i.e. a font like bold or italic.
3829 If there is an active region, change that region to a new emphasis.
3830 If there is no region, just insert the marker characters and position
3831 the cursor between them.
3832 CHAR should be either the marker character, or the first character of the
3833 HTML tag associated with that emphasis. If CHAR is a space, the means
3834 to remove the emphasis of the selected region.
3835 If char is not given (for example in an interactive call) it
3836 will be prompted for."
3837 (interactive)
3838 (let ((eal org-emphasis-alist) e det
3839 (erc org-emphasis-regexp-components)
3840 (prompt "")
3841 (string "") beg end move tag c s)
3842 (if (org-region-active-p)
3843 (setq beg (region-beginning) end (region-end)
3844 string (buffer-substring beg end))
3845 (setq move t))
3847 (while (setq e (pop eal))
3848 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3849 c (aref tag 0))
3850 (push (cons c (string-to-char (car e))) det)
3851 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3852 (substring tag 1)))))
3853 (setq det (nreverse det))
3854 (unless char
3855 (message "%s" (concat "Emphasis marker or tag:" prompt))
3856 (setq char (read-char-exclusive)))
3857 (setq char (or (cdr (assoc char det)) char))
3858 (if (equal char ?\ )
3859 (setq s "" move nil)
3860 (unless (assoc (char-to-string char) org-emphasis-alist)
3861 (error "No such emphasis marker: \"%c\"" char))
3862 (setq s (char-to-string char)))
3863 (while (and (> (length string) 1)
3864 (equal (substring string 0 1) (substring string -1))
3865 (assoc (substring string 0 1) org-emphasis-alist))
3866 (setq string (substring string 1 -1)))
3867 (setq string (concat s string s))
3868 (if beg (delete-region beg end))
3869 (unless (or (bolp)
3870 (string-match (concat "[" (nth 0 erc) "\n]")
3871 (char-to-string (char-before (point)))))
3872 (insert " "))
3873 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3874 (char-to-string (char-after (point))))
3875 (insert " ") (backward-char 1))
3876 (insert string)
3877 (and move (backward-char 1))))
3879 (defconst org-nonsticky-props
3880 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3883 (defun org-activate-plain-links (limit)
3884 "Run through the buffer and add overlays to links."
3885 (catch 'exit
3886 (let (f)
3887 (while (re-search-forward org-plain-link-re limit t)
3888 (setq f (get-text-property (match-beginning 0) 'face))
3889 (if (or (eq f 'org-tag)
3890 (and (listp f) (memq 'org-tag f)))
3892 (add-text-properties (match-beginning 0) (match-end 0)
3893 (list 'mouse-face 'highlight
3894 'rear-nonsticky org-nonsticky-props
3895 'keymap org-mouse-map
3897 (throw 'exit t))))))
3899 (defun org-activate-code (limit)
3900 (if (re-search-forward "^[ \t]*\\(: .*\n?\\)" limit t)
3901 (progn
3902 (remove-text-properties (match-beginning 0) (match-end 0)
3903 '(display t invisible t intangible t))
3904 t)))
3906 (defun org-activate-angle-links (limit)
3907 "Run through the buffer and add overlays to links."
3908 (if (re-search-forward org-angle-link-re limit t)
3909 (progn
3910 (add-text-properties (match-beginning 0) (match-end 0)
3911 (list 'mouse-face 'highlight
3912 'rear-nonsticky org-nonsticky-props
3913 'keymap org-mouse-map
3915 t)))
3917 (defun org-activate-footnote-links (limit)
3918 "Run through the buffer and add overlays to links."
3919 (if (re-search-forward "\\(^\\|[^][]\\)\\(\\[\\([0-9]+\\]\\|fn:[^ \t\r\n:]+?[]:]\\)\\)"
3920 limit t)
3921 (progn
3922 (add-text-properties (match-beginning 2) (match-end 2)
3923 (list 'mouse-face 'highlight
3924 'rear-nonsticky org-nonsticky-props
3925 'keymap org-mouse-map
3926 'help-echo
3927 (if (= (point-at-bol) (match-beginning 2))
3928 "Footnote definition"
3929 "Footnote reference")
3931 t)))
3933 (defun org-activate-bracket-links (limit)
3934 "Run through the buffer and add overlays to bracketed links."
3935 (if (re-search-forward org-bracket-link-regexp limit t)
3936 (let* ((help (concat "LINK: "
3937 (org-match-string-no-properties 1)))
3938 ;; FIXME: above we should remove the escapes.
3939 ;; but that requires another match, protecting match data,
3940 ;; a lot of overhead for font-lock.
3941 (ip (org-maybe-intangible
3942 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3943 'keymap org-mouse-map 'mouse-face 'highlight
3944 'font-lock-multiline t 'help-echo help)))
3945 (vp (list 'rear-nonsticky org-nonsticky-props
3946 'keymap org-mouse-map 'mouse-face 'highlight
3947 ' font-lock-multiline t 'help-echo help)))
3948 ;; We need to remove the invisible property here. Table narrowing
3949 ;; may have made some of this invisible.
3950 (remove-text-properties (match-beginning 0) (match-end 0)
3951 '(invisible nil))
3952 (if (match-end 3)
3953 (progn
3954 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3955 (add-text-properties (match-beginning 3) (match-end 3) vp)
3956 (add-text-properties (match-end 3) (match-end 0) ip))
3957 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3958 (add-text-properties (match-beginning 1) (match-end 1) vp)
3959 (add-text-properties (match-end 1) (match-end 0) ip))
3960 t)))
3962 (defun org-activate-dates (limit)
3963 "Run through the buffer and add overlays to dates."
3964 (if (re-search-forward org-tsr-regexp-both limit t)
3965 (progn
3966 (add-text-properties (match-beginning 0) (match-end 0)
3967 (list 'mouse-face 'highlight
3968 'rear-nonsticky org-nonsticky-props
3969 'keymap org-mouse-map))
3970 (when org-display-custom-times
3971 (if (match-end 3)
3972 (org-display-custom-time (match-beginning 3) (match-end 3)))
3973 (org-display-custom-time (match-beginning 1) (match-end 1)))
3974 t)))
3976 (defvar org-target-link-regexp nil
3977 "Regular expression matching radio targets in plain text.")
3978 (make-variable-buffer-local 'org-target-link-regexp)
3979 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3980 "Regular expression matching a link target.")
3981 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3982 "Regular expression matching a radio target.")
3983 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3984 "Regular expression matching any target.")
3986 (defun org-activate-target-links (limit)
3987 "Run through the buffer and add overlays to target matches."
3988 (when org-target-link-regexp
3989 (let ((case-fold-search t))
3990 (if (re-search-forward org-target-link-regexp limit t)
3991 (progn
3992 (add-text-properties (match-beginning 0) (match-end 0)
3993 (list 'mouse-face 'highlight
3994 'rear-nonsticky org-nonsticky-props
3995 'keymap org-mouse-map
3996 'help-echo "Radio target link"
3997 'org-linked-text t))
3998 t)))))
4000 (defun org-update-radio-target-regexp ()
4001 "Find all radio targets in this file and update the regular expression."
4002 (interactive)
4003 (when (memq 'radio org-activate-links)
4004 (setq org-target-link-regexp
4005 (org-make-target-link-regexp (org-all-targets 'radio)))
4006 (org-restart-font-lock)))
4008 (defun org-hide-wide-columns (limit)
4009 (let (s e)
4010 (setq s (text-property-any (point) (or limit (point-max))
4011 'org-cwidth t))
4012 (when s
4013 (setq e (next-single-property-change s 'org-cwidth))
4014 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
4015 (goto-char e)
4016 t)))
4018 (defvar org-latex-and-specials-regexp nil
4019 "Regular expression for highlighting export special stuff.")
4020 (defvar org-match-substring-regexp)
4021 (defvar org-match-substring-with-braces-regexp)
4022 (defvar org-export-html-special-string-regexps)
4024 (defun org-compute-latex-and-specials-regexp ()
4025 "Compute regular expression for stuff treated specially by exporters."
4026 (if (not org-highlight-latex-fragments-and-specials)
4027 (org-set-local 'org-latex-and-specials-regexp nil)
4028 (require 'org-exp)
4029 (let*
4030 ((matchers (plist-get org-format-latex-options :matchers))
4031 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
4032 org-latex-regexps)))
4033 (options (org-combine-plists (org-default-export-plist)
4034 (org-infile-export-plist)))
4035 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
4036 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
4037 (org-export-with-TeX-macros (plist-get options :TeX-macros))
4038 (org-export-html-expand (plist-get options :expand-quoted-html))
4039 (org-export-with-special-strings (plist-get options :special-strings))
4040 (re-sub
4041 (cond
4042 ((equal org-export-with-sub-superscripts '{})
4043 (list org-match-substring-with-braces-regexp))
4044 (org-export-with-sub-superscripts
4045 (list org-match-substring-regexp))
4046 (t nil)))
4047 (re-latex
4048 (if org-export-with-LaTeX-fragments
4049 (mapcar (lambda (x) (nth 1 x)) latexs)))
4050 (re-macros
4051 (if org-export-with-TeX-macros
4052 (list (concat "\\\\"
4053 (regexp-opt
4054 (append (mapcar 'car org-html-entities)
4055 (if (boundp 'org-latex-entities)
4056 org-latex-entities nil))
4057 'words))) ; FIXME
4059 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
4060 (re-special (if org-export-with-special-strings
4061 (mapcar (lambda (x) (car x))
4062 org-export-html-special-string-regexps)))
4063 (re-rest
4064 (delq nil
4065 (list
4066 (if org-export-html-expand "@<[^>\n]+>")
4067 ))))
4068 (org-set-local
4069 'org-latex-and-specials-regexp
4070 (mapconcat 'identity (append re-latex re-sub re-macros re-special
4071 re-rest) "\\|")))))
4073 (defun org-do-latex-and-special-faces (limit)
4074 "Run through the buffer and add overlays to links."
4075 (when org-latex-and-specials-regexp
4076 (let (rtn d)
4077 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
4078 limit t))
4079 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
4080 'face))
4081 '(org-code org-verbatim underline)))
4082 (progn
4083 (setq rtn t
4084 d (cond ((member (char-after (1+ (match-beginning 0)))
4085 '(?_ ?^)) 1)
4086 (t 0)))
4087 (font-lock-prepend-text-property
4088 (+ d (match-beginning 0)) (match-end 0)
4089 'face 'org-latex-and-export-specials)
4090 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
4091 '(font-lock-multiline t)))))
4092 rtn)))
4094 (defun org-restart-font-lock ()
4095 "Restart font-lock-mode, to force refontification."
4096 (when (and (boundp 'font-lock-mode) font-lock-mode)
4097 (font-lock-mode -1)
4098 (font-lock-mode 1)))
4100 (defun org-all-targets (&optional radio)
4101 "Return a list of all targets in this file.
4102 With optional argument RADIO, only find radio targets."
4103 (let ((re (if radio org-radio-target-regexp org-target-regexp))
4104 rtn)
4105 (save-excursion
4106 (goto-char (point-min))
4107 (while (re-search-forward re nil t)
4108 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
4109 rtn)))
4111 (defun org-make-target-link-regexp (targets)
4112 "Make regular expression matching all strings in TARGETS.
4113 The regular expression finds the targets also if there is a line break
4114 between words."
4115 (and targets
4116 (concat
4117 "\\<\\("
4118 (mapconcat
4119 (lambda (x)
4120 (while (string-match " +" x)
4121 (setq x (replace-match "\\s-+" t t x)))
4123 targets
4124 "\\|")
4125 "\\)\\>")))
4127 (defun org-activate-tags (limit)
4128 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
4129 (progn
4130 (add-text-properties (match-beginning 1) (match-end 1)
4131 (list 'mouse-face 'highlight
4132 'rear-nonsticky org-nonsticky-props
4133 'keymap org-mouse-map))
4134 t)))
4136 (defun org-outline-level ()
4137 (save-excursion
4138 (looking-at outline-regexp)
4139 (if (match-beginning 1)
4140 (+ (org-get-string-indentation (match-string 1)) 1000)
4141 (1- (- (match-end 0) (match-beginning 0))))))
4143 (defvar org-font-lock-keywords nil)
4145 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
4146 "Regular expression matching a property line.")
4148 (defvar org-font-lock-hook nil
4149 "Functions to be called for special font lock stuff.")
4151 (defun org-font-lock-hook (limit)
4152 (run-hook-with-args 'org-font-lock-hook limit))
4154 (defun org-set-font-lock-defaults ()
4155 (let* ((em org-fontify-emphasized-text)
4156 (lk org-activate-links)
4157 (org-font-lock-extra-keywords
4158 (list
4159 ;; Call the hook
4160 '(org-font-lock-hook)
4161 ;; Headlines
4162 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
4163 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
4164 ;; Table lines
4165 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
4166 (1 'org-table t))
4167 ;; Table internals
4168 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
4169 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
4170 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
4171 ;; Drawers
4172 (list org-drawer-regexp '(0 'org-special-keyword t))
4173 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
4174 ;; Properties
4175 (list org-property-re
4176 '(1 'org-special-keyword t)
4177 '(3 'org-property-value t))
4178 (if org-format-transports-properties-p
4179 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
4180 ;; Links
4181 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
4182 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
4183 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
4184 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
4185 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
4186 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
4187 (if (memq 'footnote lk) '(org-activate-footnote-links
4188 (2 'org-footnote t)))
4189 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
4190 '(org-hide-wide-columns (0 nil append))
4191 ;; TODO lines
4192 (list (concat "^\\*+[ \t]+" org-todo-regexp)
4193 '(1 (org-get-todo-face 1) t))
4194 ;; DONE
4195 (if org-fontify-done-headline
4196 (list (concat "^[*]+ +\\<\\("
4197 (mapconcat 'regexp-quote org-done-keywords "\\|")
4198 "\\)\\(.*\\)")
4199 '(2 'org-headline-done t))
4200 nil)
4201 ;; Priorities
4202 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
4203 ;; Tags
4204 '(org-font-lock-add-tag-faces)
4205 ;; Special keywords
4206 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
4207 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
4208 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
4209 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
4210 ;; Emphasis
4211 (if em
4212 (if (featurep 'xemacs)
4213 '(org-do-emphasis-faces (0 nil append))
4214 '(org-do-emphasis-faces)))
4215 ;; Checkboxes
4216 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
4217 2 'bold prepend)
4218 (if org-provide-checkbox-statistics
4219 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
4220 (0 (org-get-checkbox-statistics-face) t)))
4221 ;; Description list items
4222 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
4223 2 'bold prepend)
4224 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
4225 '(1 'org-archived prepend))
4226 ;; Specials
4227 '(org-do-latex-and-special-faces)
4228 ;; Code
4229 '(org-activate-code (1 'org-code t))
4230 ;; COMMENT
4231 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
4232 "\\|" org-quote-string "\\)\\>")
4233 '(1 'org-special-keyword t))
4234 '("^#.*" (0 'font-lock-comment-face t))
4236 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
4237 ;; Now set the full font-lock-keywords
4238 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
4239 (org-set-local 'font-lock-defaults
4240 '(org-font-lock-keywords t nil nil backward-paragraph))
4241 (kill-local-variable 'font-lock-keywords) nil))
4243 (defvar org-m nil)
4244 (defvar org-l nil)
4245 (defvar org-f nil)
4246 (defun org-get-level-face (n)
4247 "Get the right face for match N in font-lock matching of headlines."
4248 (setq org-l (- (match-end 2) (match-beginning 1) 1))
4249 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
4250 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
4251 (cond
4252 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
4253 ((eq n 2) org-f)
4254 (t (if org-level-color-stars-only nil org-f))))
4256 (defun org-get-todo-face (kwd)
4257 "Get the right face for a TODO keyword KWD.
4258 If KWD is a number, get the corresponding match group."
4259 (if (numberp kwd) (setq kwd (match-string kwd)))
4260 (or (cdr (assoc kwd org-todo-keyword-faces))
4261 (and (member kwd org-done-keywords) 'org-done)
4262 'org-todo))
4264 (defun org-font-lock-add-tag-faces (limit)
4265 "Add the special tag faces."
4266 (when (and org-tag-faces org-tags-special-faces-re)
4267 (while (re-search-forward org-tags-special-faces-re limit t)
4268 (add-text-properties (match-beginning 1) (match-end 1)
4269 (list 'face (org-get-tag-face 1)
4270 'font-lock-fontified t))
4271 (backward-char 1))))
4273 (defun org-get-tag-face (kwd)
4274 "Get the right face for a TODO keyword KWD.
4275 If KWD is a number, get the corresponding match group."
4276 (if (numberp kwd) (setq kwd (match-string kwd)))
4277 (or (cdr (assoc kwd org-tag-faces))
4278 'org-tag))
4280 (defun org-unfontify-region (beg end &optional maybe_loudly)
4281 "Remove fontification and activation overlays from links."
4282 (font-lock-default-unfontify-region beg end)
4283 (let* ((buffer-undo-list t)
4284 (inhibit-read-only t) (inhibit-point-motion-hooks t)
4285 (inhibit-modification-hooks t)
4286 deactivate-mark buffer-file-name buffer-file-truename)
4287 (remove-text-properties beg end
4288 '(mouse-face t keymap t org-linked-text t
4289 invisible t intangible t))))
4291 ;;;; Visibility cycling, including org-goto and indirect buffer
4293 ;;; Cycling
4295 (defvar org-cycle-global-status nil)
4296 (make-variable-buffer-local 'org-cycle-global-status)
4297 (defvar org-cycle-subtree-status nil)
4298 (make-variable-buffer-local 'org-cycle-subtree-status)
4300 ;;;###autoload
4301 (defun org-cycle (&optional arg)
4302 "Visibility cycling for Org-mode.
4304 - When this function is called with a prefix argument, rotate the entire
4305 buffer through 3 states (global cycling)
4306 1. OVERVIEW: Show only top-level headlines.
4307 2. CONTENTS: Show all headlines of all levels, but no body text.
4308 3. SHOW ALL: Show everything.
4309 When called with two C-u C-u prefixes, switch to the startup visibility,
4310 determined by the variable `org-startup-folded', and by any VISIBILITY
4311 properties in the buffer.
4312 When called with three C-u C-u C-u prefixed, show the entire buffer,
4313 including drawers.
4315 - When point is at the beginning of a headline, rotate the subtree started
4316 by this line through 3 different states (local cycling)
4317 1. FOLDED: Only the main headline is shown.
4318 2. CHILDREN: The main headline and the direct children are shown.
4319 From this state, you can move to one of the children
4320 and zoom in further.
4321 3. SUBTREE: Show the entire subtree, including body text.
4323 - When there is a numeric prefix, go up to a heading with level ARG, do
4324 a `show-subtree' and return to the previous cursor position. If ARG
4325 is negative, go up that many levels.
4327 - When point is not at the beginning of a headline, execute the global
4328 binding for TAB, which is re-indenting the line. See the option
4329 `org-cycle-emulate-tab' for details.
4331 - Special case: if point is at the beginning of the buffer and there is
4332 no headline in line 1, this function will act as if called with prefix arg.
4333 But only if also the variable `org-cycle-global-at-bob' is t."
4334 (interactive "P")
4335 (org-load-modules-maybe)
4336 (let* ((outline-regexp
4337 (if (and (org-mode-p) org-cycle-include-plain-lists)
4338 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
4339 outline-regexp))
4340 (bob-special (and org-cycle-global-at-bob (bobp)
4341 (not (looking-at outline-regexp))))
4342 (org-cycle-hook
4343 (if bob-special
4344 (delq 'org-optimize-window-after-visibility-change
4345 (copy-sequence org-cycle-hook))
4346 org-cycle-hook))
4347 (pos (point)))
4349 (if (or bob-special (equal arg '(4)))
4350 ;; special case: use global cycling
4351 (setq arg t))
4353 (cond
4355 ((equal arg '(16))
4356 (org-set-startup-visibility)
4357 (message "Startup visibility, plus VISIBILITY properties"))
4359 ((equal arg '(64))
4360 (show-all)
4361 (message "Entire buffer visible, including drawers"))
4363 ((org-at-table-p 'any)
4364 ;; Enter the table or move to the next field in the table
4365 (or (org-table-recognize-table.el)
4366 (progn
4367 (if arg (org-table-edit-field t)
4368 (org-table-justify-field-maybe)
4369 (call-interactively 'org-table-next-field)))))
4371 ((eq arg t) ;; Global cycling
4373 (cond
4374 ((and (eq last-command this-command)
4375 (eq org-cycle-global-status 'overview))
4376 ;; We just created the overview - now do table of contents
4377 ;; This can be slow in very large buffers, so indicate action
4378 (message "CONTENTS...")
4379 (org-content)
4380 (message "CONTENTS...done")
4381 (setq org-cycle-global-status 'contents)
4382 (run-hook-with-args 'org-cycle-hook 'contents))
4384 ((and (eq last-command this-command)
4385 (eq org-cycle-global-status 'contents))
4386 ;; We just showed the table of contents - now show everything
4387 (show-all)
4388 (message "SHOW ALL")
4389 (setq org-cycle-global-status 'all)
4390 (run-hook-with-args 'org-cycle-hook 'all))
4393 ;; Default action: go to overview
4394 (org-overview)
4395 (message "OVERVIEW")
4396 (setq org-cycle-global-status 'overview)
4397 (run-hook-with-args 'org-cycle-hook 'overview))))
4399 ((and org-drawers org-drawer-regexp
4400 (save-excursion
4401 (beginning-of-line 1)
4402 (looking-at org-drawer-regexp)))
4403 ;; Toggle block visibility
4404 (org-flag-drawer
4405 (not (get-char-property (match-end 0) 'invisible))))
4407 ((integerp arg)
4408 ;; Show-subtree, ARG levels up from here.
4409 (save-excursion
4410 (org-back-to-heading)
4411 (outline-up-heading (if (< arg 0) (- arg)
4412 (- (funcall outline-level) arg)))
4413 (org-show-subtree)))
4415 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
4416 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
4417 ;; At a heading: rotate between three different views
4418 (org-back-to-heading)
4419 (let ((goal-column 0) eoh eol eos)
4420 ;; First, some boundaries
4421 (save-excursion
4422 (org-back-to-heading)
4423 (save-excursion
4424 (beginning-of-line 2)
4425 (while (and (not (eobp)) ;; this is like `next-line'
4426 (get-char-property (1- (point)) 'invisible))
4427 (beginning-of-line 2)) (setq eol (point)))
4428 (outline-end-of-heading) (setq eoh (point))
4429 (org-end-of-subtree t)
4430 (unless (eobp)
4431 (skip-chars-forward " \t\n")
4432 (beginning-of-line 1) ; in case this is an item
4434 (setq eos (1- (point))))
4435 ;; Find out what to do next and set `this-command'
4436 (cond
4437 ((= eos eoh)
4438 ;; Nothing is hidden behind this heading
4439 (message "EMPTY ENTRY")
4440 (setq org-cycle-subtree-status nil)
4441 (save-excursion
4442 (goto-char eos)
4443 (outline-next-heading)
4444 (if (org-invisible-p) (org-flag-heading nil))))
4445 ((or (>= eol eos)
4446 (not (string-match "\\S-" (buffer-substring eol eos))))
4447 ;; Entire subtree is hidden in one line: open it
4448 (org-show-entry)
4449 (show-children)
4450 (message "CHILDREN")
4451 (save-excursion
4452 (goto-char eos)
4453 (outline-next-heading)
4454 (if (org-invisible-p) (org-flag-heading nil)))
4455 (setq org-cycle-subtree-status 'children)
4456 (run-hook-with-args 'org-cycle-hook 'children))
4457 ((and (eq last-command this-command)
4458 (eq org-cycle-subtree-status 'children))
4459 ;; We just showed the children, now show everything.
4460 (org-show-subtree)
4461 (message "SUBTREE")
4462 (setq org-cycle-subtree-status 'subtree)
4463 (run-hook-with-args 'org-cycle-hook 'subtree))
4465 ;; Default action: hide the subtree.
4466 (hide-subtree)
4467 (message "FOLDED")
4468 (setq org-cycle-subtree-status 'folded)
4469 (run-hook-with-args 'org-cycle-hook 'folded)))))
4471 ;; TAB emulation and template completion
4472 (buffer-read-only (org-back-to-heading))
4474 ((org-try-structure-completion))
4476 ((org-try-cdlatex-tab))
4478 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4479 (or (not (bolp))
4480 (not (looking-at outline-regexp))))
4481 (call-interactively (global-key-binding "\t")))
4483 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4484 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4485 (or (and (eq org-cycle-emulate-tab 'white)
4486 (= (match-end 0) (point-at-eol)))
4487 (and (eq org-cycle-emulate-tab 'whitestart)
4488 (>= (match-end 0) pos))))
4490 (eq org-cycle-emulate-tab t))
4491 (call-interactively (global-key-binding "\t")))
4493 (t (save-excursion
4494 (org-back-to-heading)
4495 (org-cycle))))))
4497 ;;;###autoload
4498 (defun org-global-cycle (&optional arg)
4499 "Cycle the global visibility. For details see `org-cycle'.
4500 With C-u prefix arg, switch to startup visibility.
4501 With a numeric prefix, show all headlines up to that level."
4502 (interactive "P")
4503 (let ((org-cycle-include-plain-lists
4504 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4505 (cond
4506 ((integerp arg)
4507 (show-all)
4508 (hide-sublevels arg)
4509 (setq org-cycle-global-status 'contents))
4510 ((equal arg '(4))
4511 (org-set-startup-visibility)
4512 (message "Startup visibility, plus VISIBILITY properties."))
4514 (org-cycle '(4))))))
4516 (defun org-set-startup-visibility ()
4517 "Set the visibility required by startup options and properties."
4518 (cond
4519 ((eq org-startup-folded t)
4520 (org-cycle '(4)))
4521 ((eq org-startup-folded 'content)
4522 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4523 (org-cycle '(4)) (org-cycle '(4)))))
4524 (org-set-visibility-according-to-property 'no-cleanup)
4525 (org-cycle-hide-archived-subtrees 'all)
4526 (org-cycle-hide-drawers 'all)
4527 (org-cycle-show-empty-lines 'all))
4529 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4530 "Switch subtree visibilities according to :VISIBILITY: property."
4531 (interactive)
4532 (let (org-show-entry-below state)
4533 (save-excursion
4534 (goto-char (point-min))
4535 (while (re-search-forward
4536 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4537 nil t)
4538 (setq state (match-string 1))
4539 (save-excursion
4540 (org-back-to-heading t)
4541 (hide-subtree)
4542 (org-reveal)
4543 (cond
4544 ((equal state '("fold" "folded"))
4545 (hide-subtree))
4546 ((equal state "children")
4547 (org-show-hidden-entry)
4548 (show-children))
4549 ((equal state "content")
4550 (save-excursion
4551 (save-restriction
4552 (org-narrow-to-subtree)
4553 (org-content))))
4554 ((member state '("all" "showall"))
4555 (show-subtree)))))
4556 (unless no-cleanup
4557 (org-cycle-hide-archived-subtrees 'all)
4558 (org-cycle-hide-drawers 'all)
4559 (org-cycle-show-empty-lines 'all)))))
4561 (defun org-overview ()
4562 "Switch to overview mode, showing only top-level headlines.
4563 Really, this shows all headlines with level equal or greater than the level
4564 of the first headline in the buffer. This is important, because if the
4565 first headline is not level one, then (hide-sublevels 1) gives confusing
4566 results."
4567 (interactive)
4568 (let ((level (save-excursion
4569 (goto-char (point-min))
4570 (if (re-search-forward (concat "^" outline-regexp) nil t)
4571 (progn
4572 (goto-char (match-beginning 0))
4573 (funcall outline-level))))))
4574 (and level (hide-sublevels level))))
4576 (defun org-content (&optional arg)
4577 "Show all headlines in the buffer, like a table of contents.
4578 With numerical argument N, show content up to level N."
4579 (interactive "P")
4580 (save-excursion
4581 ;; Visit all headings and show their offspring
4582 (and (integerp arg) (org-overview))
4583 (goto-char (point-max))
4584 (catch 'exit
4585 (while (and (progn (condition-case nil
4586 (outline-previous-visible-heading 1)
4587 (error (goto-char (point-min))))
4589 (looking-at outline-regexp))
4590 (if (integerp arg)
4591 (show-children (1- arg))
4592 (show-branches))
4593 (if (bobp) (throw 'exit nil))))))
4596 (defun org-optimize-window-after-visibility-change (state)
4597 "Adjust the window after a change in outline visibility.
4598 This function is the default value of the hook `org-cycle-hook'."
4599 (when (get-buffer-window (current-buffer))
4600 (cond
4601 ; ((eq state 'overview) (org-first-headline-recenter 1))
4602 ; ((eq state 'overview) (org-beginning-of-line))
4603 ((eq state 'content) nil)
4604 ((eq state 'all) nil)
4605 ((eq state 'folded) nil)
4606 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4607 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4609 (defun org-compact-display-after-subtree-move ()
4610 "Show a compacter version of the tree of the entry's parent."
4611 (save-excursion
4612 (if (org-up-heading-safe)
4613 (progn
4614 (hide-subtree)
4615 (show-entry)
4616 (show-children)
4617 (org-cycle-show-empty-lines 'children)
4618 (org-cycle-hide-drawers 'children))
4619 (org-overview))))
4621 (defun org-cycle-show-empty-lines (state)
4622 "Show empty lines above all visible headlines.
4623 The region to be covered depends on STATE when called through
4624 `org-cycle-hook'. Lisp program can use t for STATE to get the
4625 entire buffer covered. Note that an empty line is only shown if there
4626 are at least `org-cycle-separator-lines' empty lines before the headline."
4627 (when (> org-cycle-separator-lines 0)
4628 (save-excursion
4629 (let* ((n org-cycle-separator-lines)
4630 (re (cond
4631 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4632 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4633 (t (let ((ns (number-to-string (- n 2))))
4634 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4635 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4636 beg end)
4637 (cond
4638 ((memq state '(overview contents t))
4639 (setq beg (point-min) end (point-max)))
4640 ((memq state '(children folded))
4641 (setq beg (point) end (progn (org-end-of-subtree t t)
4642 (beginning-of-line 2)
4643 (point)))))
4644 (when beg
4645 (goto-char beg)
4646 (while (re-search-forward re end t)
4647 (if (not (get-char-property (match-end 1) 'invisible))
4648 (outline-flag-region
4649 (match-beginning 1) (match-end 1) nil)))))))
4650 ;; Never hide empty lines at the end of the file.
4651 (save-excursion
4652 (goto-char (point-max))
4653 (outline-previous-heading)
4654 (outline-end-of-heading)
4655 (if (and (looking-at "[ \t\n]+")
4656 (= (match-end 0) (point-max)))
4657 (outline-flag-region (point) (match-end 0) nil))))
4659 (defun org-show-empty-lines-in-parent ()
4660 "Move to the parent and re-show empty lines before visible headlines."
4661 (save-excursion
4662 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4663 (org-cycle-show-empty-lines context))))
4665 (defun org-cycle-hide-drawers (state)
4666 "Re-hide all drawers after a visibility state change."
4667 (when (and (org-mode-p)
4668 (not (memq state '(overview folded))))
4669 (save-excursion
4670 (let* ((globalp (memq state '(contents all)))
4671 (beg (if globalp (point-min) (point)))
4672 (end (if globalp (point-max) (org-end-of-subtree t))))
4673 (goto-char beg)
4674 (while (re-search-forward org-drawer-regexp end t)
4675 (org-flag-drawer t))))))
4677 (defun org-flag-drawer (flag)
4678 (save-excursion
4679 (beginning-of-line 1)
4680 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4681 (let ((b (match-end 0))
4682 (outline-regexp org-outline-regexp))
4683 (if (re-search-forward
4684 "^[ \t]*:END:"
4685 (save-excursion (outline-next-heading) (point)) t)
4686 (outline-flag-region b (point-at-eol) flag)
4687 (error ":END: line missing"))))))
4689 (defun org-subtree-end-visible-p ()
4690 "Is the end of the current subtree visible?"
4691 (pos-visible-in-window-p
4692 (save-excursion (org-end-of-subtree t) (point))))
4694 (defun org-first-headline-recenter (&optional N)
4695 "Move cursor to the first headline and recenter the headline.
4696 Optional argument N means, put the headline into the Nth line of the window."
4697 (goto-char (point-min))
4698 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4699 (beginning-of-line)
4700 (recenter (prefix-numeric-value N))))
4702 ;;; Org-goto
4704 (defvar org-goto-window-configuration nil)
4705 (defvar org-goto-marker nil)
4706 (defvar org-goto-map
4707 (let ((map (make-sparse-keymap)))
4708 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4709 (while (setq cmd (pop cmds))
4710 (substitute-key-definition cmd cmd map global-map)))
4711 (suppress-keymap map)
4712 (org-defkey map "\C-m" 'org-goto-ret)
4713 (org-defkey map [(return)] 'org-goto-ret)
4714 (org-defkey map [(left)] 'org-goto-left)
4715 (org-defkey map [(right)] 'org-goto-right)
4716 (org-defkey map [(control ?g)] 'org-goto-quit)
4717 (org-defkey map "\C-i" 'org-cycle)
4718 (org-defkey map [(tab)] 'org-cycle)
4719 (org-defkey map [(down)] 'outline-next-visible-heading)
4720 (org-defkey map [(up)] 'outline-previous-visible-heading)
4721 (if org-goto-auto-isearch
4722 (if (fboundp 'define-key-after)
4723 (define-key-after map [t] 'org-goto-local-auto-isearch)
4724 nil)
4725 (org-defkey map "q" 'org-goto-quit)
4726 (org-defkey map "n" 'outline-next-visible-heading)
4727 (org-defkey map "p" 'outline-previous-visible-heading)
4728 (org-defkey map "f" 'outline-forward-same-level)
4729 (org-defkey map "b" 'outline-backward-same-level)
4730 (org-defkey map "u" 'outline-up-heading))
4731 (org-defkey map "/" 'org-occur)
4732 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4733 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4734 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4735 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4736 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4737 map))
4739 (defconst org-goto-help
4740 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4741 RET=jump to location [Q]uit and return to previous location
4742 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4744 (defvar org-goto-start-pos) ; dynamically scoped parameter
4746 ;; FIXME: Docstring doe not mention both interfaces
4747 (defun org-goto (&optional alternative-interface)
4748 "Look up a different location in the current file, keeping current visibility.
4750 When you want look-up or go to a different location in a document, the
4751 fastest way is often to fold the entire buffer and then dive into the tree.
4752 This method has the disadvantage, that the previous location will be folded,
4753 which may not be what you want.
4755 This command works around this by showing a copy of the current buffer
4756 in an indirect buffer, in overview mode. You can dive into the tree in
4757 that copy, use org-occur and incremental search to find a location.
4758 When pressing RET or `Q', the command returns to the original buffer in
4759 which the visibility is still unchanged. After RET is will also jump to
4760 the location selected in the indirect buffer and expose the
4761 the headline hierarchy above."
4762 (interactive "P")
4763 (let* ((org-refile-targets `((nil . (:maxlevel . ,org-goto-max-level))))
4764 (org-refile-use-outline-path t)
4765 (interface
4766 (if (not alternative-interface)
4767 org-goto-interface
4768 (if (eq org-goto-interface 'outline)
4769 'outline-path-completion
4770 'outline)))
4771 (org-goto-start-pos (point))
4772 (selected-point
4773 (if (eq interface 'outline)
4774 (car (org-get-location (current-buffer) org-goto-help))
4775 (nth 3 (org-refile-get-location "Goto: ")))))
4776 (if selected-point
4777 (progn
4778 (org-mark-ring-push org-goto-start-pos)
4779 (goto-char selected-point)
4780 (if (or (org-invisible-p) (org-invisible-p2))
4781 (org-show-context 'org-goto)))
4782 (message "Quit"))))
4784 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4785 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4786 (defvar org-goto-local-auto-isearch-map) ; defined below
4788 (defun org-get-location (buf help)
4789 "Let the user select a location in the Org-mode buffer BUF.
4790 This function uses a recursive edit. It returns the selected position
4791 or nil."
4792 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4793 (isearch-hide-immediately nil)
4794 (isearch-search-fun-function
4795 (lambda () 'org-goto-local-search-headings))
4796 (org-goto-selected-point org-goto-exit-command))
4797 (save-excursion
4798 (save-window-excursion
4799 (delete-other-windows)
4800 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4801 (switch-to-buffer
4802 (condition-case nil
4803 (make-indirect-buffer (current-buffer) "*org-goto*")
4804 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4805 (with-output-to-temp-buffer "*Help*"
4806 (princ help))
4807 (org-fit-window-to-buffer (get-buffer-window "*Help*"))
4808 (setq buffer-read-only nil)
4809 (let ((org-startup-truncated t)
4810 (org-startup-folded nil)
4811 (org-startup-align-all-tables nil))
4812 (org-mode)
4813 (org-overview))
4814 (setq buffer-read-only t)
4815 (if (and (boundp 'org-goto-start-pos)
4816 (integer-or-marker-p org-goto-start-pos))
4817 (let ((org-show-hierarchy-above t)
4818 (org-show-siblings t)
4819 (org-show-following-heading t))
4820 (goto-char org-goto-start-pos)
4821 (and (org-invisible-p) (org-show-context)))
4822 (goto-char (point-min)))
4823 (org-beginning-of-line)
4824 (message "Select location and press RET")
4825 (use-local-map org-goto-map)
4826 (recursive-edit)
4828 (kill-buffer "*org-goto*")
4829 (cons org-goto-selected-point org-goto-exit-command)))
4831 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4832 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4833 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4834 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4836 (defun org-goto-local-search-headings (string bound noerror)
4837 "Search and make sure that any matches are in headlines."
4838 (catch 'return
4839 (while (if isearch-forward
4840 (search-forward string bound noerror)
4841 (search-backward string bound noerror))
4842 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4843 (and (member :headline context)
4844 (not (member :tags context))))
4845 (throw 'return (point))))))
4847 (defun org-goto-local-auto-isearch ()
4848 "Start isearch."
4849 (interactive)
4850 (goto-char (point-min))
4851 (let ((keys (this-command-keys)))
4852 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4853 (isearch-mode t)
4854 (isearch-process-search-char (string-to-char keys)))))
4856 (defun org-goto-ret (&optional arg)
4857 "Finish `org-goto' by going to the new location."
4858 (interactive "P")
4859 (setq org-goto-selected-point (point)
4860 org-goto-exit-command 'return)
4861 (throw 'exit nil))
4863 (defun org-goto-left ()
4864 "Finish `org-goto' by going to the new location."
4865 (interactive)
4866 (if (org-on-heading-p)
4867 (progn
4868 (beginning-of-line 1)
4869 (setq org-goto-selected-point (point)
4870 org-goto-exit-command 'left)
4871 (throw 'exit nil))
4872 (error "Not on a heading")))
4874 (defun org-goto-right ()
4875 "Finish `org-goto' by going to the new location."
4876 (interactive)
4877 (if (org-on-heading-p)
4878 (progn
4879 (setq org-goto-selected-point (point)
4880 org-goto-exit-command 'right)
4881 (throw 'exit nil))
4882 (error "Not on a heading")))
4884 (defun org-goto-quit ()
4885 "Finish `org-goto' without cursor motion."
4886 (interactive)
4887 (setq org-goto-selected-point nil)
4888 (setq org-goto-exit-command 'quit)
4889 (throw 'exit nil))
4891 ;;; Indirect buffer display of subtrees
4893 (defvar org-indirect-dedicated-frame nil
4894 "This is the frame being used for indirect tree display.")
4895 (defvar org-last-indirect-buffer nil)
4897 (defun org-tree-to-indirect-buffer (&optional arg)
4898 "Create indirect buffer and narrow it to current subtree.
4899 With numerical prefix ARG, go up to this level and then take that tree.
4900 If ARG is negative, go up that many levels.
4901 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4902 indirect buffer previously made with this command, to avoid proliferation of
4903 indirect buffers. However, when you call the command with a `C-u' prefix, or
4904 when `org-indirect-buffer-display' is `new-frame', the last buffer
4905 is kept so that you can work with several indirect buffers at the same time.
4906 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4907 requests that a new frame be made for the new buffer, so that the dedicated
4908 frame is not changed."
4909 (interactive "P")
4910 (let ((cbuf (current-buffer))
4911 (cwin (selected-window))
4912 (pos (point))
4913 beg end level heading ibuf)
4914 (save-excursion
4915 (org-back-to-heading t)
4916 (when (numberp arg)
4917 (setq level (org-outline-level))
4918 (if (< arg 0) (setq arg (+ level arg)))
4919 (while (> (setq level (org-outline-level)) arg)
4920 (outline-up-heading 1 t)))
4921 (setq beg (point)
4922 heading (org-get-heading))
4923 (org-end-of-subtree t) (setq end (point)))
4924 (if (and (buffer-live-p org-last-indirect-buffer)
4925 (not (eq org-indirect-buffer-display 'new-frame))
4926 (not arg))
4927 (kill-buffer org-last-indirect-buffer))
4928 (setq ibuf (org-get-indirect-buffer cbuf)
4929 org-last-indirect-buffer ibuf)
4930 (cond
4931 ((or (eq org-indirect-buffer-display 'new-frame)
4932 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4933 (select-frame (make-frame))
4934 (delete-other-windows)
4935 (switch-to-buffer ibuf)
4936 (org-set-frame-title heading))
4937 ((eq org-indirect-buffer-display 'dedicated-frame)
4938 (raise-frame
4939 (select-frame (or (and org-indirect-dedicated-frame
4940 (frame-live-p org-indirect-dedicated-frame)
4941 org-indirect-dedicated-frame)
4942 (setq org-indirect-dedicated-frame (make-frame)))))
4943 (delete-other-windows)
4944 (switch-to-buffer ibuf)
4945 (org-set-frame-title (concat "Indirect: " heading)))
4946 ((eq org-indirect-buffer-display 'current-window)
4947 (switch-to-buffer ibuf))
4948 ((eq org-indirect-buffer-display 'other-window)
4949 (pop-to-buffer ibuf))
4950 (t (error "Invalid value.")))
4951 (if (featurep 'xemacs)
4952 (save-excursion (org-mode) (turn-on-font-lock)))
4953 (narrow-to-region beg end)
4954 (show-all)
4955 (goto-char pos)
4956 (and (window-live-p cwin) (select-window cwin))))
4958 (defun org-get-indirect-buffer (&optional buffer)
4959 (setq buffer (or buffer (current-buffer)))
4960 (let ((n 1) (base (buffer-name buffer)) bname)
4961 (while (buffer-live-p
4962 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4963 (setq n (1+ n)))
4964 (condition-case nil
4965 (make-indirect-buffer buffer bname 'clone)
4966 (error (make-indirect-buffer buffer bname)))))
4968 (defun org-set-frame-title (title)
4969 "Set the title of the current frame to the string TITLE."
4970 ;; FIXME: how to name a single frame in XEmacs???
4971 (unless (featurep 'xemacs)
4972 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4974 ;;;; Structure editing
4976 ;;; Inserting headlines
4978 (defun org-previous-line-empty-p ()
4979 (save-excursion
4980 (and (not (bobp))
4981 (or (beginning-of-line 0) t)
4982 (save-match-data
4983 (looking-at "[ \t]*$")))))
4985 (defun org-insert-heading (&optional force-heading)
4986 "Insert a new heading or item with same depth at point.
4987 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4988 If point is at the beginning of a headline, insert a sibling before the
4989 current headline. If point is not at the beginning, do not split the line,
4990 but create the new headline after the current line."
4991 (interactive "P")
4992 (if (= (buffer-size) 0)
4993 (insert "\n* ")
4994 (when (or force-heading (not (org-insert-item)))
4995 (let* ((empty-line-p nil)
4996 (head (save-excursion
4997 (condition-case nil
4998 (progn
4999 (org-back-to-heading)
5000 (setq empty-line-p (org-previous-line-empty-p))
5001 (match-string 0))
5002 (error "*"))))
5003 (blank-a (cdr (assq 'heading org-blank-before-new-entry)))
5004 (blank (if (eq blank-a 'auto) empty-line-p blank-a))
5005 pos hide-previous previous-pos)
5006 (cond
5007 ((and (org-on-heading-p) (bolp)
5008 (or (bobp)
5009 (save-excursion (backward-char 1) (not (org-invisible-p)))))
5010 ;; insert before the current line
5011 (open-line (if blank 2 1)))
5012 ((and (bolp)
5013 (or (bobp)
5014 (save-excursion
5015 (backward-char 1) (not (org-invisible-p)))))
5016 ;; insert right here
5017 nil)
5019 ;; somewhere in the line
5020 (save-excursion
5021 (setq previous-pos (point-at-bol))
5022 (end-of-line)
5023 (setq hide-previous (org-invisible-p)))
5024 (and org-insert-heading-respect-content (org-show-subtree))
5025 (let ((split
5026 (and (org-get-alist-option org-M-RET-may-split-line 'headline)
5027 (save-excursion
5028 (let ((p (point)))
5029 (goto-char (point-at-bol))
5030 (and (looking-at org-complex-heading-regexp)
5031 (> p (match-beginning 4)))))))
5032 tags pos)
5033 (cond
5034 (org-insert-heading-respect-content
5035 (org-end-of-subtree nil t)
5036 (or (bolp) (newline))
5037 (or (org-previous-line-empty-p)
5038 (and blank (newline)))
5039 (open-line 1))
5040 ((org-on-heading-p)
5041 (when hide-previous
5042 (show-children)
5043 (org-show-entry))
5044 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
5045 (setq tags (and (match-end 2) (match-string 2)))
5046 (and (match-end 1)
5047 (delete-region (match-beginning 1) (match-end 1)))
5048 (setq pos (point-at-bol))
5049 (or split (end-of-line 1))
5050 (delete-horizontal-space)
5051 (newline (if blank 2 1))
5052 (when tags
5053 (save-excursion
5054 (goto-char pos)
5055 (end-of-line 1)
5056 (insert " " tags)
5057 (org-set-tags nil 'align))))
5059 (or split (end-of-line 1))
5060 (newline (if blank 2 1)))))))
5061 (insert head) (just-one-space)
5062 (setq pos (point))
5063 (end-of-line 1)
5064 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
5065 (when (and org-insert-heading-respect-content hide-previous)
5066 (save-excursion
5067 (goto-char previous-pos)
5068 (hide-subtree)))
5069 (run-hooks 'org-insert-heading-hook)))))
5071 (defun org-get-heading (&optional no-tags)
5072 "Return the heading of the current entry, without the stars."
5073 (save-excursion
5074 (org-back-to-heading t)
5075 (if (looking-at
5076 (if no-tags
5077 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
5078 "\\*+[ \t]+\\([^\r\n]*\\)"))
5079 (match-string 1) "")))
5081 (defun org-heading-components ()
5082 "Return the components of the current heading.
5083 This is a list with the following elements:
5084 - the level as an integer
5085 - the reduced level, different if `org-odd-levels-only' is set.
5086 - the TODO keyword, or nil
5087 - the priority character, like ?A, or nil if no priority is given
5088 - the headline text itself, or the tags string if no headline text
5089 - the tags string, or nil."
5090 (save-excursion
5091 (org-back-to-heading t)
5092 (if (looking-at org-complex-heading-regexp)
5093 (list (length (match-string 1))
5094 (org-reduced-level (length (match-string 1)))
5095 (org-match-string-no-properties 2)
5096 (and (match-end 3) (aref (match-string 3) 2))
5097 (org-match-string-no-properties 4)
5098 (org-match-string-no-properties 5)))))
5100 (defun org-insert-heading-after-current ()
5101 "Insert a new heading with same level as current, after current subtree."
5102 (interactive)
5103 (org-back-to-heading)
5104 (org-insert-heading)
5105 (org-move-subtree-down)
5106 (end-of-line 1))
5108 (defun org-insert-heading-respect-content ()
5109 (interactive)
5110 (let ((org-insert-heading-respect-content t))
5111 (org-insert-heading t)))
5113 (defun org-insert-todo-heading-respect-content (&optional force-state)
5114 (interactive "P")
5115 (let ((org-insert-heading-respect-content t))
5116 (org-insert-todo-heading force-state t)))
5118 (defun org-insert-todo-heading (arg &optional force-heading)
5119 "Insert a new heading with the same level and TODO state as current heading.
5120 If the heading has no TODO state, or if the state is DONE, use the first
5121 state (TODO by default). Also with prefix arg, force first state."
5122 (interactive "P")
5123 (when (or force-heading (not (org-insert-item 'checkbox)))
5124 (org-insert-heading force-heading)
5125 (save-excursion
5126 (org-back-to-heading)
5127 (outline-previous-heading)
5128 (looking-at org-todo-line-regexp))
5129 (if (or arg
5130 (not (match-beginning 2))
5131 (member (match-string 2) org-done-keywords))
5132 (insert (car org-todo-keywords-1) " ")
5133 (insert (match-string 2) " "))
5134 (when org-provide-todo-statistics
5135 (org-update-parent-todo-statistics))))
5137 (defun org-insert-subheading (arg)
5138 "Insert a new subheading and demote it.
5139 Works for outline headings and for plain lists alike."
5140 (interactive "P")
5141 (org-insert-heading arg)
5142 (cond
5143 ((org-on-heading-p) (org-do-demote))
5144 ((org-at-item-p) (org-indent-item 1))))
5146 (defun org-insert-todo-subheading (arg)
5147 "Insert a new subheading with TODO keyword or checkbox and demote it.
5148 Works for outline headings and for plain lists alike."
5149 (interactive "P")
5150 (org-insert-todo-heading arg)
5151 (cond
5152 ((org-on-heading-p) (org-do-demote))
5153 ((org-at-item-p) (org-indent-item 1))))
5155 ;;; Promotion and Demotion
5157 (defun org-promote-subtree ()
5158 "Promote the entire subtree.
5159 See also `org-promote'."
5160 (interactive)
5161 (save-excursion
5162 (org-map-tree 'org-promote))
5163 (org-fix-position-after-promote))
5165 (defun org-demote-subtree ()
5166 "Demote the entire subtree. See `org-demote'.
5167 See also `org-promote'."
5168 (interactive)
5169 (save-excursion
5170 (org-map-tree 'org-demote))
5171 (org-fix-position-after-promote))
5174 (defun org-do-promote ()
5175 "Promote the current heading higher up the tree.
5176 If the region is active in `transient-mark-mode', promote all headings
5177 in the region."
5178 (interactive)
5179 (save-excursion
5180 (if (org-region-active-p)
5181 (org-map-region 'org-promote (region-beginning) (region-end))
5182 (org-promote)))
5183 (org-fix-position-after-promote))
5185 (defun org-do-demote ()
5186 "Demote the current heading lower down the tree.
5187 If the region is active in `transient-mark-mode', demote all headings
5188 in the region."
5189 (interactive)
5190 (save-excursion
5191 (if (org-region-active-p)
5192 (org-map-region 'org-demote (region-beginning) (region-end))
5193 (org-demote)))
5194 (org-fix-position-after-promote))
5196 (defun org-fix-position-after-promote ()
5197 "Make sure that after pro/demotion cursor position is right."
5198 (let ((pos (point)))
5199 (when (save-excursion
5200 (beginning-of-line 1)
5201 (looking-at org-todo-line-regexp)
5202 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
5203 (cond ((eobp) (insert " "))
5204 ((eolp) (insert " "))
5205 ((equal (char-after) ?\ ) (forward-char 1))))))
5207 (defun org-reduced-level (l)
5208 "Compute the effective level of a heading.
5209 This takes into account the setting of `org-odd-levels-only'."
5210 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
5212 (defun org-get-valid-level (level &optional change)
5213 "Rectify a level change under the influence of `org-odd-levels-only'
5214 LEVEL is a current level, CHANGE is by how much the level should be
5215 modified. Even if CHANGE is nil, LEVEL may be returned modified because
5216 even level numbers will become the next higher odd number."
5217 (if org-odd-levels-only
5218 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
5219 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
5220 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
5221 (max 1 (+ level change))))
5223 (if (boundp 'define-obsolete-function-alias)
5224 (if (or (featurep 'xemacs) (< emacs-major-version 23))
5225 (define-obsolete-function-alias 'org-get-legal-level
5226 'org-get-valid-level)
5227 (define-obsolete-function-alias 'org-get-legal-level
5228 'org-get-valid-level "23.1")))
5230 (defun org-promote ()
5231 "Promote the current heading higher up the tree.
5232 If the region is active in `transient-mark-mode', promote all headings
5233 in the region."
5234 (org-back-to-heading t)
5235 (let* ((level (save-match-data (funcall outline-level)))
5236 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
5237 (diff (abs (- level (length up-head) -1))))
5238 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
5239 (replace-match up-head nil t)
5240 ;; Fixup tag positioning
5241 (and org-auto-align-tags (org-set-tags nil t))
5242 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
5244 (defun org-demote ()
5245 "Demote the current heading lower down the tree.
5246 If the region is active in `transient-mark-mode', demote all headings
5247 in the region."
5248 (org-back-to-heading t)
5249 (let* ((level (save-match-data (funcall outline-level)))
5250 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
5251 (diff (abs (- level (length down-head) -1))))
5252 (replace-match down-head nil t)
5253 ;; Fixup tag positioning
5254 (and org-auto-align-tags (org-set-tags nil t))
5255 (if org-adapt-indentation (org-fixup-indentation diff))))
5257 (defun org-map-tree (fun)
5258 "Call FUN for every heading underneath the current one."
5259 (org-back-to-heading)
5260 (let ((level (funcall outline-level)))
5261 (save-excursion
5262 (funcall fun)
5263 (while (and (progn
5264 (outline-next-heading)
5265 (> (funcall outline-level) level))
5266 (not (eobp)))
5267 (funcall fun)))))
5269 (defun org-map-region (fun beg end)
5270 "Call FUN for every heading between BEG and END."
5271 (let ((org-ignore-region t))
5272 (save-excursion
5273 (setq end (copy-marker end))
5274 (goto-char beg)
5275 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
5276 (< (point) end))
5277 (funcall fun))
5278 (while (and (progn
5279 (outline-next-heading)
5280 (< (point) end))
5281 (not (eobp)))
5282 (funcall fun)))))
5284 (defun org-fixup-indentation (diff)
5285 "Change the indentation in the current entry by DIFF
5286 However, if any line in the current entry has no indentation, or if it
5287 would end up with no indentation after the change, nothing at all is done."
5288 (save-excursion
5289 (let ((end (save-excursion (outline-next-heading)
5290 (point-marker)))
5291 (prohibit (if (> diff 0)
5292 "^\\S-"
5293 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
5294 col)
5295 (unless (save-excursion (end-of-line 1)
5296 (re-search-forward prohibit end t))
5297 (while (and (< (point) end)
5298 (re-search-forward "^[ \t]+" end t))
5299 (goto-char (match-end 0))
5300 (setq col (current-column))
5301 (if (< diff 0) (replace-match ""))
5302 (org-indent-to-column (+ diff col))))
5303 (move-marker end nil))))
5305 (defun org-convert-to-odd-levels ()
5306 "Convert an org-mode file with all levels allowed to one with odd levels.
5307 This will leave level 1 alone, convert level 2 to level 3, level 3 to
5308 level 5 etc."
5309 (interactive)
5310 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
5311 (let ((org-odd-levels-only nil) n)
5312 (save-excursion
5313 (goto-char (point-min))
5314 (while (re-search-forward "^\\*\\*+ " nil t)
5315 (setq n (- (length (match-string 0)) 2))
5316 (while (>= (setq n (1- n)) 0)
5317 (org-demote))
5318 (end-of-line 1))))))
5321 (defun org-convert-to-oddeven-levels ()
5322 "Convert an org-mode file with only odd levels to one with odd and even levels.
5323 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
5324 section with an even level, conversion would destroy the structure of the file. An error
5325 is signaled in this case."
5326 (interactive)
5327 (goto-char (point-min))
5328 ;; First check if there are no even levels
5329 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
5330 (org-show-context t)
5331 (error "Not all levels are odd in this file. Conversion not possible."))
5332 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
5333 (let ((org-odd-levels-only nil) n)
5334 (save-excursion
5335 (goto-char (point-min))
5336 (while (re-search-forward "^\\*\\*+ " nil t)
5337 (setq n (/ (1- (length (match-string 0))) 2))
5338 (while (>= (setq n (1- n)) 0)
5339 (org-promote))
5340 (end-of-line 1))))))
5342 (defun org-tr-level (n)
5343 "Make N odd if required."
5344 (if org-odd-levels-only (1+ (/ n 2)) n))
5346 ;;; Vertical tree motion, cutting and pasting of subtrees
5348 (defun org-move-subtree-up (&optional arg)
5349 "Move the current subtree up past ARG headlines of the same level."
5350 (interactive "p")
5351 (org-move-subtree-down (- (prefix-numeric-value arg))))
5353 (defun org-move-subtree-down (&optional arg)
5354 "Move the current subtree down past ARG headlines of the same level."
5355 (interactive "p")
5356 (setq arg (prefix-numeric-value arg))
5357 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
5358 'outline-get-last-sibling))
5359 (ins-point (make-marker))
5360 (cnt (abs arg))
5361 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
5362 ;; Select the tree
5363 (org-back-to-heading)
5364 (setq beg0 (point))
5365 (save-excursion
5366 (setq ne-beg (org-back-over-empty-lines))
5367 (setq beg (point)))
5368 (save-match-data
5369 (save-excursion (outline-end-of-heading)
5370 (setq folded (org-invisible-p)))
5371 (outline-end-of-subtree))
5372 (outline-next-heading)
5373 (setq ne-end (org-back-over-empty-lines))
5374 (setq end (point))
5375 (goto-char beg0)
5376 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
5377 ;; include less whitespace
5378 (save-excursion
5379 (goto-char beg)
5380 (forward-line (- ne-beg ne-end))
5381 (setq beg (point))))
5382 ;; Find insertion point, with error handling
5383 (while (> cnt 0)
5384 (or (and (funcall movfunc) (looking-at outline-regexp))
5385 (progn (goto-char beg0)
5386 (error "Cannot move past superior level or buffer limit")))
5387 (setq cnt (1- cnt)))
5388 (if (> arg 0)
5389 ;; Moving forward - still need to move over subtree
5390 (progn (org-end-of-subtree t t)
5391 (save-excursion
5392 (org-back-over-empty-lines)
5393 (or (bolp) (newline)))))
5394 (setq ne-ins (org-back-over-empty-lines))
5395 (move-marker ins-point (point))
5396 (setq txt (buffer-substring beg end))
5397 (org-save-markers-in-region beg end)
5398 (delete-region beg end)
5399 (or (= beg (point-min)) (outline-flag-region (1- beg) beg nil))
5400 (or (bobp) (outline-flag-region (1- (point)) (point) nil))
5401 (let ((bbb (point)))
5402 (insert-before-markers txt)
5403 (org-reinstall-markers-in-region bbb)
5404 (move-marker ins-point bbb))
5405 (or (bolp) (insert "\n"))
5406 (setq ins-end (point))
5407 (goto-char ins-point)
5408 (org-skip-whitespace)
5409 (when (and (< arg 0)
5410 (org-first-sibling-p)
5411 (> ne-ins ne-beg))
5412 ;; Move whitespace back to beginning
5413 (save-excursion
5414 (goto-char ins-end)
5415 (let ((kill-whole-line t))
5416 (kill-line (- ne-ins ne-beg)) (point)))
5417 (insert (make-string (- ne-ins ne-beg) ?\n)))
5418 (move-marker ins-point nil)
5419 (org-compact-display-after-subtree-move)
5420 (org-show-empty-lines-in-parent)
5421 (unless folded
5422 (org-show-entry)
5423 (show-children)
5424 (org-cycle-hide-drawers 'children))))
5426 (defvar org-subtree-clip ""
5427 "Clipboard for cut and paste of subtrees.
5428 This is actually only a copy of the kill, because we use the normal kill
5429 ring. We need it to check if the kill was created by `org-copy-subtree'.")
5431 (defvar org-subtree-clip-folded nil
5432 "Was the last copied subtree folded?
5433 This is used to fold the tree back after pasting.")
5435 (defun org-cut-subtree (&optional n)
5436 "Cut the current subtree into the clipboard.
5437 With prefix arg N, cut this many sequential subtrees.
5438 This is a short-hand for marking the subtree and then cutting it."
5439 (interactive "p")
5440 (org-copy-subtree n 'cut))
5442 (defun org-copy-subtree (&optional n cut force-store-markers)
5443 "Cut the current subtree into the clipboard.
5444 With prefix arg N, cut this many sequential subtrees.
5445 This is a short-hand for marking the subtree and then copying it.
5446 If CUT is non-nil, actually cut the subtree.
5447 If FORCE-STORE-MARKERS is non-nil, store the relative locations
5448 of some markers in the region, even if CUT is non-nil. This is
5449 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
5450 (interactive "p")
5451 (let (beg end folded (beg0 (point)))
5452 (if (interactive-p)
5453 (org-back-to-heading nil) ; take what looks like a subtree
5454 (org-back-to-heading t)) ; take what is really there
5455 (org-back-over-empty-lines)
5456 (setq beg (point))
5457 (skip-chars-forward " \t\r\n")
5458 (save-match-data
5459 (save-excursion (outline-end-of-heading)
5460 (setq folded (org-invisible-p)))
5461 (condition-case nil
5462 (outline-forward-same-level (1- n))
5463 (error nil))
5464 (org-end-of-subtree t t))
5465 (org-back-over-empty-lines)
5466 (setq end (point))
5467 (goto-char beg0)
5468 (when (> end beg)
5469 (setq org-subtree-clip-folded folded)
5470 (when (or cut force-store-markers)
5471 (org-save-markers-in-region beg end))
5472 (if cut (kill-region beg end) (copy-region-as-kill beg end))
5473 (setq org-subtree-clip (current-kill 0))
5474 (message "%s: Subtree(s) with %d characters"
5475 (if cut "Cut" "Copied")
5476 (length org-subtree-clip)))))
5478 (defun org-paste-subtree (&optional level tree for-yank)
5479 "Paste the clipboard as a subtree, with modification of headline level.
5480 The entire subtree is promoted or demoted in order to match a new headline
5481 level.
5483 If the cursor is at the beginning of a headline, the same level as
5484 that headline is used to paste the tree
5486 If not, the new level is derived from the *visible* headings
5487 before and after the insertion point, and taken to be the inferior headline
5488 level of the two. So if the previous visible heading is level 3 and the
5489 next is level 4 (or vice versa), level 4 will be used for insertion.
5490 This makes sure that the subtree remains an independent subtree and does
5491 not swallow low level entries.
5493 You can also force a different level, either by using a numeric prefix
5494 argument, or by inserting the heading marker by hand. For example, if the
5495 cursor is after \"*****\", then the tree will be shifted to level 5.
5497 If optional TREE is given, use this text instead of the kill ring.
5499 When FOR-YANK is set, this is called by `org-yank'. In this case, do not
5500 move back over whitespace before inserting, and move point to the end of
5501 the inserted text when done."
5502 (interactive "P")
5503 (unless (org-kill-is-subtree-p tree)
5504 (error "%s"
5505 (substitute-command-keys
5506 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
5507 (let* ((visp (not (org-invisible-p)))
5508 (txt (or tree (and kill-ring (current-kill 0))))
5509 (^re (concat "^\\(" outline-regexp "\\)"))
5510 (re (concat "\\(" outline-regexp "\\)"))
5511 (^re_ (concat "\\(\\*+\\)[ \t]*"))
5513 (old-level (if (string-match ^re txt)
5514 (- (match-end 0) (match-beginning 0) 1)
5515 -1))
5516 (force-level (cond (level (prefix-numeric-value level))
5517 ((and (looking-at "[ \t]*$")
5518 (string-match
5519 ^re_ (buffer-substring
5520 (point-at-bol) (point))))
5521 (- (match-end 1) (match-beginning 1)))
5522 ((and (bolp)
5523 (looking-at org-outline-regexp))
5524 (- (match-end 0) (point) 1))
5525 (t nil)))
5526 (previous-level (save-excursion
5527 (condition-case nil
5528 (progn
5529 (outline-previous-visible-heading 1)
5530 (if (looking-at re)
5531 (- (match-end 0) (match-beginning 0) 1)
5533 (error 1))))
5534 (next-level (save-excursion
5535 (condition-case nil
5536 (progn
5537 (or (looking-at outline-regexp)
5538 (outline-next-visible-heading 1))
5539 (if (looking-at re)
5540 (- (match-end 0) (match-beginning 0) 1)
5542 (error 1))))
5543 (new-level (or force-level (max previous-level next-level)))
5544 (shift (if (or (= old-level -1)
5545 (= new-level -1)
5546 (= old-level new-level))
5548 (- new-level old-level)))
5549 (delta (if (> shift 0) -1 1))
5550 (func (if (> shift 0) 'org-demote 'org-promote))
5551 (org-odd-levels-only nil)
5552 beg end newend)
5553 ;; Remove the forced level indicator
5554 (if force-level
5555 (delete-region (point-at-bol) (point)))
5556 ;; Paste
5557 (beginning-of-line 1)
5558 (unless for-yank (org-back-over-empty-lines))
5559 (setq beg (point))
5560 (and (fboundp 'org-id-paste-tracker) (org-id-paste-tracker txt))
5561 (insert-before-markers txt)
5562 (unless (string-match "\n\\'" txt) (insert "\n"))
5563 (setq newend (point))
5564 (org-reinstall-markers-in-region beg)
5565 (setq end (point))
5566 (goto-char beg)
5567 (skip-chars-forward " \t\n\r")
5568 (setq beg (point))
5569 (if (and (org-invisible-p) visp)
5570 (save-excursion (outline-show-heading)))
5571 ;; Shift if necessary
5572 (unless (= shift 0)
5573 (save-restriction
5574 (narrow-to-region beg end)
5575 (while (not (= shift 0))
5576 (org-map-region func (point-min) (point-max))
5577 (setq shift (+ delta shift)))
5578 (goto-char (point-min))
5579 (setq newend (point-max))))
5580 (when (or (interactive-p) for-yank)
5581 (message "Clipboard pasted as level %d subtree" new-level))
5582 (if (and (not for-yank) ; in this case, org-yank will decide about folding
5583 kill-ring
5584 (eq org-subtree-clip (current-kill 0))
5585 org-subtree-clip-folded)
5586 ;; The tree was folded before it was killed/copied
5587 (hide-subtree))
5588 (and for-yank (goto-char newend))))
5590 (defun org-kill-is-subtree-p (&optional txt)
5591 "Check if the current kill is an outline subtree, or a set of trees.
5592 Returns nil if kill does not start with a headline, or if the first
5593 headline level is not the largest headline level in the tree.
5594 So this will actually accept several entries of equal levels as well,
5595 which is OK for `org-paste-subtree'.
5596 If optional TXT is given, check this string instead of the current kill."
5597 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5598 (start-level (and kill
5599 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5600 org-outline-regexp "\\)")
5601 kill)
5602 (- (match-end 2) (match-beginning 2) 1)))
5603 (re (concat "^" org-outline-regexp))
5604 (start (1+ (or (match-beginning 2) -1))))
5605 (if (not start-level)
5606 (progn
5607 nil) ;; does not even start with a heading
5608 (catch 'exit
5609 (while (setq start (string-match re kill (1+ start)))
5610 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5611 (throw 'exit nil)))
5612 t))))
5614 (defvar org-markers-to-move nil
5615 "Markers that should be moved with a cut-and-paste operation.
5616 Those markers are stored together with their positions relative to
5617 the start of the region.")
5619 (defun org-save-markers-in-region (beg end)
5620 "Check markers in region.
5621 If these markers are between BEG and END, record their position relative
5622 to BEG, so that after moving the block of text, we can put the markers back
5623 into place.
5624 This function gets called just before an entry or tree gets cut from the
5625 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5626 called immediately, to move the markers with the entries."
5627 (setq org-markers-to-move nil)
5628 (when (featurep 'org-clock)
5629 (org-clock-save-markers-for-cut-and-paste beg end))
5630 (when (featurep 'org-agenda)
5631 (org-agenda-save-markers-for-cut-and-paste beg end)))
5633 (defun org-check-and-save-marker (marker beg end)
5634 "Check if MARKER is between BEG and END.
5635 If yes, remember the marker and the distance to BEG."
5636 (when (and (marker-buffer marker)
5637 (equal (marker-buffer marker) (current-buffer)))
5638 (if (and (>= marker beg) (< marker end))
5639 (push (cons marker (- marker beg)) org-markers-to-move))))
5641 (defun org-reinstall-markers-in-region (beg)
5642 "Move all remembered markers to their position relative to BEG."
5643 (mapc (lambda (x)
5644 (move-marker (car x) (+ beg (cdr x))))
5645 org-markers-to-move)
5646 (setq org-markers-to-move nil))
5648 (defun org-narrow-to-subtree ()
5649 "Narrow buffer to the current subtree."
5650 (interactive)
5651 (save-excursion
5652 (save-match-data
5653 (narrow-to-region
5654 (progn (org-back-to-heading) (point))
5655 (progn (org-end-of-subtree t) (point))))))
5658 ;;; Outline Sorting
5660 (defun org-sort (with-case)
5661 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5662 Optional argument WITH-CASE means sort case-sensitively."
5663 (interactive "P")
5664 (if (org-at-table-p)
5665 (org-call-with-arg 'org-table-sort-lines with-case)
5666 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5668 (defun org-sort-remove-invisible (s)
5669 (remove-text-properties 0 (length s) org-rm-props s)
5670 (while (string-match org-bracket-link-regexp s)
5671 (setq s (replace-match (if (match-end 2)
5672 (match-string 3 s)
5673 (match-string 1 s)) t t s)))
5676 (defvar org-priority-regexp) ; defined later in the file
5678 (defun org-sort-entries-or-items
5679 (&optional with-case sorting-type getkey-func compare-func property)
5680 "Sort entries on a certain level of an outline tree.
5681 If there is an active region, the entries in the region are sorted.
5682 Else, if the cursor is before the first entry, sort the top-level items.
5683 Else, the children of the entry at point are sorted.
5685 Sorting can be alphabetically, numerically, and by date/time as given by
5686 the first time stamp in the entry. The command prompts for the sorting
5687 type unless it has been given to the function through the SORTING-TYPE
5688 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5689 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5690 called with point at the beginning of the record. It must return either
5691 a string or a number that should serve as the sorting key for that record.
5693 Comparing entries ignores case by default. However, with an optional argument
5694 WITH-CASE, the sorting considers case as well."
5695 (interactive "P")
5696 (let ((case-func (if with-case 'identity 'downcase))
5697 start beg end stars re re2
5698 txt what tmp plain-list-p)
5699 ;; Find beginning and end of region to sort
5700 (cond
5701 ((org-region-active-p)
5702 ;; we will sort the region
5703 (setq end (region-end)
5704 what "region")
5705 (goto-char (region-beginning))
5706 (if (not (org-on-heading-p)) (outline-next-heading))
5707 (setq start (point)))
5708 ((org-at-item-p)
5709 ;; we will sort this plain list
5710 (org-beginning-of-item-list) (setq start (point))
5711 (org-end-of-item-list) (setq end (point))
5712 (goto-char start)
5713 (setq plain-list-p t
5714 what "plain list"))
5715 ((or (org-on-heading-p)
5716 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5717 ;; we will sort the children of the current headline
5718 (org-back-to-heading)
5719 (setq start (point)
5720 end (progn (org-end-of-subtree t t)
5721 (org-back-over-empty-lines)
5722 (point))
5723 what "children")
5724 (goto-char start)
5725 (show-subtree)
5726 (outline-next-heading))
5728 ;; we will sort the top-level entries in this file
5729 (goto-char (point-min))
5730 (or (org-on-heading-p) (outline-next-heading))
5731 (setq start (point) end (point-max) what "top-level")
5732 (goto-char start)
5733 (show-all)))
5735 (setq beg (point))
5736 (if (>= beg end) (error "Nothing to sort"))
5738 (unless plain-list-p
5739 (looking-at "\\(\\*+\\)")
5740 (setq stars (match-string 1)
5741 re (concat "^" (regexp-quote stars) " +")
5742 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5743 txt (buffer-substring beg end))
5744 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5745 (if (and (not (equal stars "*")) (string-match re2 txt))
5746 (error "Region to sort contains a level above the first entry")))
5748 (unless sorting-type
5749 (message
5750 (if plain-list-p
5751 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5752 "Sort %s: [a]lpha [n]umeric [t]ime [p]riority p[r]operty todo[o]rder [f]unc A/N/T/P/O/F means reversed:")
5753 what)
5754 (setq sorting-type (read-char-exclusive))
5756 (and (= (downcase sorting-type) ?f)
5757 (setq getkey-func
5758 (org-ido-completing-read "Sort using function: "
5759 obarray 'fboundp t nil nil))
5760 (setq getkey-func (intern getkey-func)))
5762 (and (= (downcase sorting-type) ?r)
5763 (setq property
5764 (org-ido-completing-read "Property: "
5765 (mapcar 'list (org-buffer-property-keys t))
5766 nil t))))
5768 (message "Sorting entries...")
5770 (save-restriction
5771 (narrow-to-region start end)
5773 (let ((dcst (downcase sorting-type))
5774 (now (current-time)))
5775 (sort-subr
5776 (/= dcst sorting-type)
5777 ;; This function moves to the beginning character of the "record" to
5778 ;; be sorted.
5779 (if plain-list-p
5780 (lambda nil
5781 (if (org-at-item-p) t (goto-char (point-max))))
5782 (lambda nil
5783 (if (re-search-forward re nil t)
5784 (goto-char (match-beginning 0))
5785 (goto-char (point-max)))))
5786 ;; This function moves to the last character of the "record" being
5787 ;; sorted.
5788 (if plain-list-p
5789 'org-end-of-item
5790 (lambda nil
5791 (save-match-data
5792 (condition-case nil
5793 (outline-forward-same-level 1)
5794 (error
5795 (goto-char (point-max)))))))
5797 ;; This function returns the value that gets sorted against.
5798 (if plain-list-p
5799 (lambda nil
5800 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5801 (cond
5802 ((= dcst ?n)
5803 (string-to-number (buffer-substring (match-end 0)
5804 (point-at-eol))))
5805 ((= dcst ?a)
5806 (buffer-substring (match-end 0) (point-at-eol)))
5807 ((= dcst ?t)
5808 (if (re-search-forward org-ts-regexp
5809 (point-at-eol) t)
5810 (org-time-string-to-time (match-string 0))
5811 now))
5812 ((= dcst ?f)
5813 (if getkey-func
5814 (progn
5815 (setq tmp (funcall getkey-func))
5816 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5817 tmp)
5818 (error "Invalid key function `%s'" getkey-func)))
5819 (t (error "Invalid sorting type `%c'" sorting-type)))))
5820 (lambda nil
5821 (cond
5822 ((= dcst ?n)
5823 (if (looking-at org-complex-heading-regexp)
5824 (string-to-number (match-string 4))
5825 nil))
5826 ((= dcst ?a)
5827 (if (looking-at org-complex-heading-regexp)
5828 (funcall case-func (match-string 4))
5829 nil))
5830 ((= dcst ?t)
5831 (if (re-search-forward org-ts-regexp
5832 (save-excursion
5833 (forward-line 2)
5834 (point)) t)
5835 (org-time-string-to-time (match-string 0))
5836 now))
5837 ((= dcst ?p)
5838 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5839 (string-to-char (match-string 2))
5840 org-default-priority))
5841 ((= dcst ?r)
5842 (or (org-entry-get nil property) ""))
5843 ((= dcst ?o)
5844 (if (looking-at org-complex-heading-regexp)
5845 (- 9999 (length (member (match-string 2)
5846 org-todo-keywords-1)))))
5847 ((= dcst ?f)
5848 (if getkey-func
5849 (progn
5850 (setq tmp (funcall getkey-func))
5851 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5852 tmp)
5853 (error "Invalid key function `%s'" getkey-func)))
5854 (t (error "Invalid sorting type `%c'" sorting-type)))))
5856 (cond
5857 ((= dcst ?a) 'string<)
5858 ((= dcst ?t) 'time-less-p)
5859 ((= dcst ?f) compare-func)
5860 (t nil)))))
5861 (message "Sorting entries...done")))
5863 (defun org-do-sort (table what &optional with-case sorting-type)
5864 "Sort TABLE of WHAT according to SORTING-TYPE.
5865 The user will be prompted for the SORTING-TYPE if the call to this
5866 function does not specify it. WHAT is only for the prompt, to indicate
5867 what is being sorted. The sorting key will be extracted from
5868 the car of the elements of the table.
5869 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5870 (unless sorting-type
5871 (message
5872 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5873 what)
5874 (setq sorting-type (read-char-exclusive)))
5875 (let ((dcst (downcase sorting-type))
5876 extractfun comparefun)
5877 ;; Define the appropriate functions
5878 (cond
5879 ((= dcst ?n)
5880 (setq extractfun 'string-to-number
5881 comparefun (if (= dcst sorting-type) '< '>)))
5882 ((= dcst ?a)
5883 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5884 (lambda(x) (downcase (org-sort-remove-invisible x))))
5885 comparefun (if (= dcst sorting-type)
5886 'string<
5887 (lambda (a b) (and (not (string< a b))
5888 (not (string= a b)))))))
5889 ((= dcst ?t)
5890 (setq extractfun
5891 (lambda (x)
5892 (if (or (string-match org-ts-regexp x)
5893 (string-match org-ts-regexp-both x))
5894 (time-to-seconds
5895 (org-time-string-to-time (match-string 0 x)))
5897 comparefun (if (= dcst sorting-type) '< '>)))
5898 (t (error "Invalid sorting type `%c'" sorting-type)))
5900 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5901 table)
5902 (lambda (a b) (funcall comparefun (car a) (car b))))))
5904 ;;; Editing source examples
5906 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5907 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5908 (defvar org-edit-src-force-single-line nil)
5909 (defvar org-edit-src-from-org-mode nil)
5910 (defvar org-edit-src-picture nil)
5912 (define-minor-mode org-exit-edit-mode
5913 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5915 (defun org-edit-src-code ()
5916 "Edit the source code example at point.
5917 An indirect buffer is created, and that buffer is then narrowed to the
5918 example at point and switched to the correct language mode. When done,
5919 exit by killing the buffer with \\[org-edit-src-exit]."
5920 (interactive)
5921 (let ((line (org-current-line))
5922 (case-fold-search t)
5923 (msg (substitute-command-keys
5924 "Edit, then exit with C-c ' (C-c and single quote)"))
5925 (info (org-edit-src-find-region-and-lang))
5926 (org-mode-p (eq major-mode 'org-mode))
5927 beg end lang lang-f single lfmt)
5928 (if (not info)
5930 (setq beg (nth 0 info)
5931 end (nth 1 info)
5932 lang (nth 2 info)
5933 single (nth 3 info)
5934 lfmt (nth 4 info)
5935 lang-f (intern (concat lang "-mode")))
5936 (unless (functionp lang-f)
5937 (error "No such language mode: %s" lang-f))
5938 (goto-line line)
5939 (if (get-buffer "*Org Edit Src Example*")
5940 (kill-buffer "*Org Edit Src Example*"))
5941 (switch-to-buffer (make-indirect-buffer (current-buffer)
5942 "*Org Edit Src Example*"))
5943 (narrow-to-region beg end)
5944 (remove-text-properties beg end '(display nil invisible nil
5945 intangible nil))
5946 (let ((org-inhibit-startup t))
5947 (funcall lang-f))
5948 (set (make-local-variable 'org-edit-src-force-single-line) single)
5949 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5950 (when lfmt
5951 (set (make-local-variable 'org-coderef-label-format) lfmt))
5952 (when org-mode-p
5953 (goto-char (point-min))
5954 (while (re-search-forward "^," nil t)
5955 (replace-match "")))
5956 (goto-line line)
5957 (org-exit-edit-mode)
5958 (org-set-local 'header-line-format msg)
5959 (message "%s" msg)
5960 t)))
5962 (defun org-edit-fixed-width-region ()
5963 "Edit the fixed-width ascii drawing at point.
5964 This must be a region where each line starts with a colon followed by
5965 a space character.
5966 An indirect buffer is created, and that buffer is then narrowed to the
5967 example at point and switched to artist-mode. When done,
5968 exit by killing the buffer with \\[org-edit-src-exit]."
5969 (interactive)
5970 (let ((line (org-current-line))
5971 (case-fold-search t)
5972 (msg (substitute-command-keys
5973 "Edit, then exit with C-c ' (C-c and single quote)"))
5974 (org-mode-p (eq major-mode 'org-mode))
5975 beg end)
5976 (beginning-of-line 1)
5977 (if (looking-at "[ \t]*[^:\n \t]")
5979 (if (looking-at "[ \t]*\\(\n\\|\\'\\)")
5980 (setq beg (point) end beg)
5981 (save-excursion
5982 (if (re-search-backward "^[ \t]*[^:]" nil 'move)
5983 (setq beg (point-at-bol 2))
5984 (setq beg (point))))
5985 (save-excursion
5986 (if (re-search-forward "^[ \t]*[^:]" nil 'move)
5987 (setq end (1- (match-beginning 0)))
5988 (setq end (point))))
5989 (goto-line line))
5990 (if (get-buffer "*Org Edit Picture*")
5991 (kill-buffer "*Org Edit Picture*"))
5992 (switch-to-buffer (make-indirect-buffer (current-buffer)
5993 "*Org Edit Picture*"))
5994 (narrow-to-region beg end)
5995 (remove-text-properties beg end '(display nil invisible nil
5996 intangible nil))
5997 (when (fboundp 'font-lock-unfontify-region)
5998 (font-lock-unfontify-region (point-min) (point-max)))
5999 (cond
6000 ((eq org-edit-fixed-width-region-mode 'artist-mode)
6001 (fundamental-mode)
6002 (artist-mode 1))
6003 (t (funcall org-edit-fixed-width-region-mode)))
6004 (set (make-local-variable 'org-edit-src-force-single-line) nil)
6005 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
6006 (set (make-local-variable 'org-edit-src-picture) t)
6007 (goto-char (point-min))
6008 (while (re-search-forward "^[ \t]*: ?" nil t)
6009 (replace-match ""))
6010 (goto-line line)
6011 (org-exit-edit-mode)
6012 (org-set-local 'header-line-format msg)
6013 (message "%s" msg)
6014 t)))
6017 (defun org-edit-src-find-region-and-lang ()
6018 "Find the region and language for a local edit.
6019 Return a list with beginning and end of the region, a string representing
6020 the language, a switch telling of the content should be in a single line."
6021 (let ((re-list
6022 (append
6023 org-edit-src-region-extra
6025 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
6026 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
6027 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
6028 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
6029 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
6030 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
6031 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
6032 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
6033 ("^#\\+begin_example.*\n" "\n#\\+end_example" "fundamental")
6034 ("^#\\+html:" "\n" "html" single-line)
6035 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
6036 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
6037 ("^#\\+latex:" "\n" "latex" single-line)
6038 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
6039 ("^#\\+ascii:" "\n" "ascii" single-line)
6041 (pos (point))
6042 re1 re2 single beg end lang lfmt match-re1)
6043 (catch 'exit
6044 (while (setq entry (pop re-list))
6045 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
6046 single (nth 3 entry))
6047 (save-excursion
6048 (if (or (looking-at re1)
6049 (re-search-backward re1 nil t))
6050 (progn
6051 (setq match-re1 (match-string 0))
6052 (setq beg (match-end 0)
6053 lang (org-edit-src-get-lang lang)
6054 lfmt (org-edit-src-get-label-format match-re1))
6055 (if (and (re-search-forward re2 nil t)
6056 (>= (match-end 0) pos))
6057 (throw 'exit (list beg (match-beginning 0)
6058 lang single lfmt))))
6059 (if (or (looking-at re2)
6060 (re-search-forward re2 nil t))
6061 (progn
6062 (setq end (match-beginning 0))
6063 (if (and (re-search-backward re1 nil t)
6064 (<= (match-beginning 0) pos))
6065 (progn
6066 (setq lfmt (org-edit-src-get-label-format
6067 (match-string 0)))
6068 (throw 'exit
6069 (list (match-end 0) end
6070 (org-edit-src-get-lang lang)
6071 single lfmt))))))))))))
6073 (defun org-edit-src-get-lang (lang)
6074 "Extract the src language."
6075 (let ((m (match-string 0)))
6076 (cond
6077 ((stringp lang) lang)
6078 ((integerp lang) (match-string lang))
6079 ((and (eq lang 'lang)
6080 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
6081 (match-string 1 m))
6082 ((and (eq lang 'style)
6083 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
6084 (match-string 1 m))
6085 (t "fundamental"))))
6087 (defun org-edit-src-get-label-format (s)
6088 "Extract the label format."
6089 (save-match-data
6090 (if (string-match "-l[ \t]+\\\\?\"\\([^\t\r\n\"]+\\)\\\\?\"" s)
6091 (match-string 1 s))))
6093 (defun org-edit-src-exit ()
6094 "Exit special edit and protect problematic lines."
6095 (interactive)
6096 (unless (buffer-base-buffer (current-buffer))
6097 (error "This is not an indirect buffer, something is wrong..."))
6098 (unless (> (point-min) 1)
6099 (error "This buffer is not narrowed, something is wrong..."))
6100 (goto-char (point-min))
6101 (if (looking-at "[ \t\n]*\n") (replace-match ""))
6102 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
6103 (when (org-bound-and-true-p org-edit-src-force-single-line)
6104 (goto-char (point-min))
6105 (while (re-search-forward "\n" nil t)
6106 (replace-match " "))
6107 (goto-char (point-min))
6108 (if (looking-at "\\s-*") (replace-match " "))
6109 (if (re-search-forward "\\s-+\\'" nil t)
6110 (replace-match "")))
6111 (when (org-bound-and-true-p org-edit-src-from-org-mode)
6112 (goto-char (point-min))
6113 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
6114 (replace-match ",\\1"))
6115 (when font-lock-mode
6116 (font-lock-unfontify-region (point-min) (point-max)))
6117 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6118 (when (org-bound-and-true-p org-edit-src-picture)
6119 (untabify (point-min) (point-max))
6120 (goto-char (point-min))
6121 (while (re-search-forward "^" nil t)
6122 (replace-match ": "))
6123 (when font-lock-mode
6124 (font-lock-unfontify-region (point-min) (point-max)))
6125 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
6126 (kill-buffer (current-buffer))
6127 (and (org-mode-p) (org-restart-font-lock)))
6130 ;;; The orgstruct minor mode
6132 ;; Define a minor mode which can be used in other modes in order to
6133 ;; integrate the org-mode structure editing commands.
6135 ;; This is really a hack, because the org-mode structure commands use
6136 ;; keys which normally belong to the major mode. Here is how it
6137 ;; works: The minor mode defines all the keys necessary to operate the
6138 ;; structure commands, but wraps the commands into a function which
6139 ;; tests if the cursor is currently at a headline or a plain list
6140 ;; item. If that is the case, the structure command is used,
6141 ;; temporarily setting many Org-mode variables like regular
6142 ;; expressions for filling etc. However, when any of those keys is
6143 ;; used at a different location, function uses `key-binding' to look
6144 ;; up if the key has an associated command in another currently active
6145 ;; keymap (minor modes, major mode, global), and executes that
6146 ;; command. There might be problems if any of the keys is otherwise
6147 ;; used as a prefix key.
6149 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6150 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6151 ;; addresses this by checking explicitly for both bindings.
6153 (defvar orgstruct-mode-map (make-sparse-keymap)
6154 "Keymap for the minor `orgstruct-mode'.")
6156 (defvar org-local-vars nil
6157 "List of local variables, for use by `orgstruct-mode'")
6159 ;;;###autoload
6160 (define-minor-mode orgstruct-mode
6161 "Toggle the minor more `orgstruct-mode'.
6162 This mode is for using Org-mode structure commands in other modes.
6163 The following key behave as if Org-mode was active, if the cursor
6164 is on a headline, or on a plain list item (both in the definition
6165 of Org-mode).
6167 M-up Move entry/item up
6168 M-down Move entry/item down
6169 M-left Promote
6170 M-right Demote
6171 M-S-up Move entry/item up
6172 M-S-down Move entry/item down
6173 M-S-left Promote subtree
6174 M-S-right Demote subtree
6175 M-q Fill paragraph and items like in Org-mode
6176 C-c ^ Sort entries
6177 C-c - Cycle list bullet
6178 TAB Cycle item visibility
6179 M-RET Insert new heading/item
6180 S-M-RET Insert new TODO heading / Checkbox item
6181 C-c C-c Set tags / toggle checkbox"
6182 nil " OrgStruct" nil
6183 (org-load-modules-maybe)
6184 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6186 ;;;###autoload
6187 (defun turn-on-orgstruct ()
6188 "Unconditionally turn on `orgstruct-mode'."
6189 (orgstruct-mode 1))
6191 ;;;###autoload
6192 (defun turn-on-orgstruct++ ()
6193 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6194 In addition to setting orgstruct-mode, this also exports all indentation and
6195 autofilling variables from org-mode into the buffer. Note that turning
6196 off orgstruct-mode will *not* remove these additional settings."
6197 (orgstruct-mode 1)
6198 (let (var val)
6199 (mapc
6200 (lambda (x)
6201 (when (string-match
6202 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6203 (symbol-name (car x)))
6204 (setq var (car x) val (nth 1 x))
6205 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6206 org-local-vars)))
6208 (defun orgstruct-error ()
6209 "Error when there is no default binding for a structure key."
6210 (interactive)
6211 (error "This key has no function outside structure elements"))
6213 (defun orgstruct-setup ()
6214 "Setup orgstruct keymaps."
6215 (let ((nfunc 0)
6216 (bindings
6217 (list
6218 '([(meta up)] org-metaup)
6219 '([(meta down)] org-metadown)
6220 '([(meta left)] org-metaleft)
6221 '([(meta right)] org-metaright)
6222 '([(meta shift up)] org-shiftmetaup)
6223 '([(meta shift down)] org-shiftmetadown)
6224 '([(meta shift left)] org-shiftmetaleft)
6225 '([(meta shift right)] org-shiftmetaright)
6226 '([(shift up)] org-shiftup)
6227 '([(shift down)] org-shiftdown)
6228 '([(shift left)] org-shiftleft)
6229 '([(shift right)] org-shiftright)
6230 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6231 '("\M-q" fill-paragraph)
6232 '("\C-c^" org-sort)
6233 '("\C-c-" org-cycle-list-bullet)))
6234 elt key fun cmd)
6235 (while (setq elt (pop bindings))
6236 (setq nfunc (1+ nfunc))
6237 (setq key (org-key (car elt))
6238 fun (nth 1 elt)
6239 cmd (orgstruct-make-binding fun nfunc key))
6240 (org-defkey orgstruct-mode-map key cmd))
6242 ;; Special treatment needed for TAB and RET
6243 (org-defkey orgstruct-mode-map [(tab)]
6244 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6245 (org-defkey orgstruct-mode-map "\C-i"
6246 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6248 (org-defkey orgstruct-mode-map "\M-\C-m"
6249 (orgstruct-make-binding 'org-insert-heading 105
6250 "\M-\C-m" [(meta return)]))
6251 (org-defkey orgstruct-mode-map [(meta return)]
6252 (orgstruct-make-binding 'org-insert-heading 106
6253 [(meta return)] "\M-\C-m"))
6255 (org-defkey orgstruct-mode-map [(shift meta return)]
6256 (orgstruct-make-binding 'org-insert-todo-heading 107
6257 [(meta return)] "\M-\C-m"))
6259 (unless org-local-vars
6260 (setq org-local-vars (org-get-local-variables)))
6264 (defun orgstruct-make-binding (fun n &rest keys)
6265 "Create a function for binding in the structure minor mode.
6266 FUN is the command to call inside a table. N is used to create a unique
6267 command name. KEYS are keys that should be checked in for a command
6268 to execute outside of tables."
6269 (eval
6270 (list 'defun
6271 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6272 '(arg)
6273 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6274 "Outside of structure, run the binding of `"
6275 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6276 "'.")
6277 '(interactive "p")
6278 (list 'if
6279 '(org-context-p 'headline 'item)
6280 (list 'org-run-like-in-org-mode (list 'quote fun))
6281 (list 'let '(orgstruct-mode)
6282 (list 'call-interactively
6283 (append '(or)
6284 (mapcar (lambda (k)
6285 (list 'key-binding k))
6286 keys)
6287 '('orgstruct-error))))))))
6289 (defun org-context-p (&rest contexts)
6290 "Check if local context is any of CONTEXTS.
6291 Possible values in the list of contexts are `table', `headline', and `item'."
6292 (let ((pos (point)))
6293 (goto-char (point-at-bol))
6294 (prog1 (or (and (memq 'table contexts)
6295 (looking-at "[ \t]*|"))
6296 (and (memq 'headline contexts)
6297 ;;????????? (looking-at "\\*+"))
6298 (looking-at outline-regexp))
6299 (and (memq 'item contexts)
6300 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6301 (goto-char pos))))
6303 (defun org-get-local-variables ()
6304 "Return a list of all local variables in an org-mode buffer."
6305 (let (varlist)
6306 (with-current-buffer (get-buffer-create "*Org tmp*")
6307 (erase-buffer)
6308 (org-mode)
6309 (setq varlist (buffer-local-variables)))
6310 (kill-buffer "*Org tmp*")
6311 (delq nil
6312 (mapcar
6313 (lambda (x)
6314 (setq x
6315 (if (symbolp x)
6316 (list x)
6317 (list (car x) (list 'quote (cdr x)))))
6318 (if (string-match
6319 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6320 (symbol-name (car x)))
6321 x nil))
6322 varlist))))
6324 ;;;###autoload
6325 (defun org-run-like-in-org-mode (cmd)
6326 (org-load-modules-maybe)
6327 (unless org-local-vars
6328 (setq org-local-vars (org-get-local-variables)))
6329 (eval (list 'let org-local-vars
6330 (list 'call-interactively (list 'quote cmd)))))
6332 ;;;; Archiving
6334 (defun org-get-category (&optional pos)
6335 "Get the category applying to position POS."
6336 (get-text-property (or pos (point)) 'org-category))
6338 (defun org-refresh-category-properties ()
6339 "Refresh category text properties in the buffer."
6340 (let ((def-cat (cond
6341 ((null org-category)
6342 (if buffer-file-name
6343 (file-name-sans-extension
6344 (file-name-nondirectory buffer-file-name))
6345 "???"))
6346 ((symbolp org-category) (symbol-name org-category))
6347 (t org-category)))
6348 beg end cat pos optionp)
6349 (org-unmodified
6350 (save-excursion
6351 (save-restriction
6352 (widen)
6353 (goto-char (point-min))
6354 (put-text-property (point) (point-max) 'org-category def-cat)
6355 (while (re-search-forward
6356 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6357 (setq pos (match-end 0)
6358 optionp (equal (char-after (match-beginning 0)) ?#)
6359 cat (org-trim (match-string 2)))
6360 (if optionp
6361 (setq beg (point-at-bol) end (point-max))
6362 (org-back-to-heading t)
6363 (setq beg (point) end (org-end-of-subtree t t)))
6364 (put-text-property beg end 'org-category cat)
6365 (goto-char pos)))))))
6368 ;;;; Link Stuff
6370 ;;; Link abbreviations
6372 (defun org-link-expand-abbrev (link)
6373 "Apply replacements as defined in `org-link-abbrev-alist."
6374 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6375 (let* ((key (match-string 1 link))
6376 (as (or (assoc key org-link-abbrev-alist-local)
6377 (assoc key org-link-abbrev-alist)))
6378 (tag (and (match-end 2) (match-string 3 link)))
6379 rpl)
6380 (if (not as)
6381 link
6382 (setq rpl (cdr as))
6383 (cond
6384 ((symbolp rpl) (funcall rpl tag))
6385 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6386 ((string-match "%h" rpl)
6387 (replace-match (url-hexify-string (or tag "")) t t rpl))
6388 (t (concat rpl tag)))))
6389 link))
6391 ;;; Storing and inserting links
6393 (defvar org-insert-link-history nil
6394 "Minibuffer history for links inserted with `org-insert-link'.")
6396 (defvar org-stored-links nil
6397 "Contains the links stored with `org-store-link'.")
6399 (defvar org-store-link-plist nil
6400 "Plist with info about the most recently link created with `org-store-link'.")
6402 (defvar org-link-protocols nil
6403 "Link protocols added to Org-mode using `org-add-link-type'.")
6405 (defvar org-store-link-functions nil
6406 "List of functions that are called to create and store a link.
6407 Each function will be called in turn until one returns a non-nil
6408 value. Each function should check if it is responsible for creating
6409 this link (for example by looking at the major mode).
6410 If not, it must exit and return nil.
6411 If yes, it should return a non-nil value after a calling
6412 `org-store-link-props' with a list of properties and values.
6413 Special properties are:
6415 :type The link prefix. like \"http\". This must be given.
6416 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6417 This is obligatory as well.
6418 :description Optional default description for the second pair
6419 of brackets in an Org-mode link. The user can still change
6420 this when inserting this link into an Org-mode buffer.
6422 In addition to these, any additional properties can be specified
6423 and then used in remember templates.")
6425 (defun org-add-link-type (type &optional follow export)
6426 "Add TYPE to the list of `org-link-types'.
6427 Re-compute all regular expressions depending on `org-link-types'
6429 FOLLOW and EXPORT are two functions.
6431 FOLLOW should take the link path as the single argument and do whatever
6432 is necessary to follow the link, for example find a file or display
6433 a mail message.
6435 EXPORT should format the link path for export to one of the export formats.
6436 It should be a function accepting three arguments:
6438 path the path of the link, the text after the prefix (like \"http:\")
6439 desc the description of the link, if any, nil if there was no description
6440 format the export format, a symbol like `html' or `latex'.
6442 The function may use the FORMAT information to return different values
6443 depending on the format. The return value will be put literally into
6444 the exported file.
6445 Org-mode has a built-in default for exporting links. If you are happy with
6446 this default, there is no need to define an export function for the link
6447 type. For a simple example of an export function, see `org-bbdb.el'."
6448 (add-to-list 'org-link-types type t)
6449 (org-make-link-regexps)
6450 (if (assoc type org-link-protocols)
6451 (setcdr (assoc type org-link-protocols) (list follow export))
6452 (push (list type follow export) org-link-protocols)))
6454 ;;;###autoload
6455 (defun org-store-link (arg)
6456 "\\<org-mode-map>Store an org-link to the current location.
6457 This link is added to `org-stored-links' and can later be inserted
6458 into an org-buffer with \\[org-insert-link].
6460 For some link types, a prefix arg is interpreted:
6461 For links to usenet articles, arg negates `org-gnus-prefer-web-links'.
6462 For file links, arg negates `org-context-in-file-links'."
6463 (interactive "P")
6464 (org-load-modules-maybe)
6465 (setq org-store-link-plist nil) ; reset
6466 (let (link cpltxt desc description search txt)
6467 (cond
6469 ((run-hook-with-args-until-success 'org-store-link-functions)
6470 (setq link (plist-get org-store-link-plist :link)
6471 desc (or (plist-get org-store-link-plist :description) link)))
6473 ((equal (buffer-name) "*Org Edit Src Example*")
6474 (let (label gc)
6475 (while (or (not label)
6476 (save-excursion
6477 (save-restriction
6478 (widen)
6479 (goto-char (point-min))
6480 (re-search-forward
6481 (regexp-quote (format org-coderef-label-format label))
6482 nil t))))
6483 (when label (message "Label exists already") (sit-for 2))
6484 (setq label (read-string "Code line label: " label)))
6485 (end-of-line 1)
6486 (setq link (format org-coderef-label-format label))
6487 (setq gc (- 79 (length link)))
6488 (if (< (current-column) gc) (org-move-to-column gc t) (insert " "))
6489 (insert link)
6490 (setq link (concat "(" label ")") desc nil)))
6492 ((eq major-mode 'calendar-mode)
6493 (let ((cd (calendar-cursor-to-date)))
6494 (setq link
6495 (format-time-string
6496 (car org-time-stamp-formats)
6497 (apply 'encode-time
6498 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6499 nil nil nil))))
6500 (org-store-link-props :type "calendar" :date cd)))
6502 ((eq major-mode 'w3-mode)
6503 (setq cpltxt (url-view-url t)
6504 link (org-make-link cpltxt))
6505 (org-store-link-props :type "w3" :url (url-view-url t)))
6507 ((eq major-mode 'w3m-mode)
6508 (setq cpltxt (or w3m-current-title w3m-current-url)
6509 link (org-make-link w3m-current-url))
6510 (org-store-link-props :type "w3m" :url (url-view-url t)))
6512 ((setq search (run-hook-with-args-until-success
6513 'org-create-file-search-functions))
6514 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6515 "::" search))
6516 (setq cpltxt (or description link)))
6518 ((eq major-mode 'image-mode)
6519 (setq cpltxt (concat "file:"
6520 (abbreviate-file-name buffer-file-name))
6521 link (org-make-link cpltxt))
6522 (org-store-link-props :type "image" :file buffer-file-name))
6524 ((eq major-mode 'dired-mode)
6525 ;; link to the file in the current line
6526 (setq cpltxt (concat "file:"
6527 (abbreviate-file-name
6528 (expand-file-name
6529 (dired-get-filename nil t))))
6530 link (org-make-link cpltxt)))
6532 ((and buffer-file-name (org-mode-p))
6533 (cond
6534 ((org-in-regexp "<<\\(.*?\\)>>")
6535 (setq cpltxt
6536 (concat "file:"
6537 (abbreviate-file-name buffer-file-name)
6538 "::" (match-string 1))
6539 link (org-make-link cpltxt)))
6540 ((and (featurep 'org-id)
6541 (or (eq org-link-to-org-use-id t)
6542 (and (eq org-link-to-org-use-id 'create-if-interactive)
6543 (interactive-p))
6544 (and org-link-to-org-use-id
6545 (condition-case nil
6546 (org-entry-get nil "ID")
6547 (error nil)))))
6548 ;; We can make a link using the ID.
6549 (setq link (condition-case nil
6550 (prog1 (org-id-store-link)
6551 (setq desc (plist-get org-store-link-plist
6552 :description)))
6553 (error
6554 ;; probably before first headline, link to file only
6555 (concat "file:"
6556 (abbreviate-file-name buffer-file-name))))))
6558 ;; Just link to current headline
6559 (setq cpltxt (concat "file:"
6560 (abbreviate-file-name buffer-file-name)))
6561 ;; Add a context search string
6562 (when (org-xor org-context-in-file-links arg)
6563 (setq txt (cond
6564 ((org-on-heading-p) nil)
6565 ((org-region-active-p)
6566 (buffer-substring (region-beginning) (region-end)))
6567 (t nil)))
6568 (when (or (null txt) (string-match "\\S-" txt))
6569 (setq cpltxt
6570 (concat cpltxt "::"
6571 (condition-case nil
6572 (org-make-org-heading-search-string txt)
6573 (error "")))
6574 desc "NONE")))
6575 (if (string-match "::\\'" cpltxt)
6576 (setq cpltxt (substring cpltxt 0 -2)))
6577 (setq link (org-make-link cpltxt)))))
6579 ((buffer-file-name (buffer-base-buffer))
6580 ;; Just link to this file here.
6581 (setq cpltxt (concat "file:"
6582 (abbreviate-file-name
6583 (buffer-file-name (buffer-base-buffer)))))
6584 ;; Add a context string
6585 (when (org-xor org-context-in-file-links arg)
6586 (setq txt (if (org-region-active-p)
6587 (buffer-substring (region-beginning) (region-end))
6588 (buffer-substring (point-at-bol) (point-at-eol))))
6589 ;; Only use search option if there is some text.
6590 (when (string-match "\\S-" txt)
6591 (setq cpltxt
6592 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6593 desc "NONE")))
6594 (setq link (org-make-link cpltxt)))
6596 ((interactive-p)
6597 (error "Cannot link to a buffer which is not visiting a file"))
6599 (t (setq link nil)))
6601 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6602 (setq link (or link cpltxt)
6603 desc (or desc cpltxt))
6604 (if (equal desc "NONE") (setq desc nil))
6606 (if (and (interactive-p) link)
6607 (progn
6608 (setq org-stored-links
6609 (cons (list link desc) org-stored-links))
6610 (message "Stored: %s" (or desc link)))
6611 (and link (org-make-link-string link desc)))))
6613 (defun org-store-link-props (&rest plist)
6614 "Store link properties, extract names and addresses."
6615 (let (x adr)
6616 (when (setq x (plist-get plist :from))
6617 (setq adr (mail-extract-address-components x))
6618 (setq plist (plist-put plist :fromname (car adr)))
6619 (setq plist (plist-put plist :fromaddress (nth 1 adr))))
6620 (when (setq x (plist-get plist :to))
6621 (setq adr (mail-extract-address-components x))
6622 (setq plist (plist-put plist :toname (car adr)))
6623 (setq plist (plist-put plist :toaddress (nth 1 adr)))))
6624 (let ((from (plist-get plist :from))
6625 (to (plist-get plist :to)))
6626 (when (and from to org-from-is-user-regexp)
6627 (setq plist
6628 (plist-put plist :fromto
6629 (if (string-match org-from-is-user-regexp from)
6630 (concat "to %t")
6631 (concat "from %f"))))))
6632 (setq org-store-link-plist plist))
6634 (defun org-add-link-props (&rest plist)
6635 "Add these properties to the link property list."
6636 (let (key value)
6637 (while plist
6638 (setq key (pop plist) value (pop plist))
6639 (setq org-store-link-plist
6640 (plist-put org-store-link-plist key value)))))
6642 (defun org-email-link-description (&optional fmt)
6643 "Return the description part of an email link.
6644 This takes information from `org-store-link-plist' and formats it
6645 according to FMT (default from `org-email-link-description-format')."
6646 (setq fmt (or fmt org-email-link-description-format))
6647 (let* ((p org-store-link-plist)
6648 (to (plist-get p :toaddress))
6649 (from (plist-get p :fromaddress))
6650 (table
6651 (list
6652 (cons "%c" (plist-get p :fromto))
6653 (cons "%F" (plist-get p :from))
6654 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6655 (cons "%T" (plist-get p :to))
6656 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6657 (cons "%s" (plist-get p :subject))
6658 (cons "%m" (plist-get p :message-id)))))
6659 (when (string-match "%c" fmt)
6660 ;; Check if the user wrote this message
6661 (if (and org-from-is-user-regexp from to
6662 (save-match-data (string-match org-from-is-user-regexp from)))
6663 (setq fmt (replace-match "to %t" t t fmt))
6664 (setq fmt (replace-match "from %f" t t fmt))))
6665 (org-replace-escapes fmt table)))
6667 (defun org-make-org-heading-search-string (&optional string heading)
6668 "Make search string for STRING or current headline."
6669 (interactive)
6670 (let ((s (or string (org-get-heading))))
6671 (unless (and string (not heading))
6672 ;; We are using a headline, clean up garbage in there.
6673 (if (string-match org-todo-regexp s)
6674 (setq s (replace-match "" t t s)))
6675 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6676 (setq s (replace-match "" t t s)))
6677 (setq s (org-trim s))
6678 (if (string-match (concat "^\\(" org-quote-string "\\|"
6679 org-comment-string "\\)") s)
6680 (setq s (replace-match "" t t s)))
6681 (while (string-match org-ts-regexp s)
6682 (setq s (replace-match "" t t s))))
6683 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6684 (setq s (replace-match " " t t s)))
6685 (or string (setq s (concat "*" s))) ; Add * for headlines
6686 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6688 (defun org-make-link (&rest strings)
6689 "Concatenate STRINGS."
6690 (apply 'concat strings))
6692 (defun org-make-link-string (link &optional description)
6693 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6694 (unless (string-match "\\S-" link)
6695 (error "Empty link"))
6696 (when (stringp description)
6697 ;; Remove brackets from the description, they are fatal.
6698 (while (string-match "\\[" description)
6699 (setq description (replace-match "{" t t description)))
6700 (while (string-match "\\]" description)
6701 (setq description (replace-match "}" t t description))))
6702 (when (equal (org-link-escape link) description)
6703 ;; No description needed, it is identical
6704 (setq description nil))
6705 (when (and (not description)
6706 (not (equal link (org-link-escape link))))
6707 (setq description (org-extract-attributes link)))
6708 (concat "[[" (org-link-escape link) "]"
6709 (if description (concat "[" description "]") "")
6710 "]"))
6712 (defconst org-link-escape-chars
6713 '((?\ . "%20")
6714 (?\[ . "%5B")
6715 (?\] . "%5D")
6716 (?\340 . "%E0") ; `a
6717 (?\342 . "%E2") ; ^a
6718 (?\347 . "%E7") ; ,c
6719 (?\350 . "%E8") ; `e
6720 (?\351 . "%E9") ; 'e
6721 (?\352 . "%EA") ; ^e
6722 (?\356 . "%EE") ; ^i
6723 (?\364 . "%F4") ; ^o
6724 (?\371 . "%F9") ; `u
6725 (?\373 . "%FB") ; ^u
6726 (?\; . "%3B")
6727 (?? . "%3F")
6728 (?= . "%3D")
6729 (?+ . "%2B")
6731 "Association list of escapes for some characters problematic in links.
6732 This is the list that is used for internal purposes.")
6734 (defconst org-link-escape-chars-browser
6735 '((?\ . "%20")) ; 32 for the SPC char
6736 "Association list of escapes for some characters problematic in links.
6737 This is the list that is used before handing over to the browser.")
6739 (defun org-link-escape (text &optional table)
6740 "Escape characters in TEXT that are problematic for links."
6741 (setq table (or table org-link-escape-chars))
6742 (when text
6743 (let ((re (mapconcat (lambda (x) (regexp-quote
6744 (char-to-string (car x))))
6745 table "\\|")))
6746 (while (string-match re text)
6747 (setq text
6748 (replace-match
6749 (cdr (assoc (string-to-char (match-string 0 text))
6750 table))
6751 t t text)))
6752 text)))
6754 (defun org-link-unescape (text &optional table)
6755 "Reverse the action of `org-link-escape'."
6756 (setq table (or table org-link-escape-chars))
6757 (when text
6758 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6759 table "\\|")))
6760 (while (string-match re text)
6761 (setq text
6762 (replace-match
6763 (char-to-string (car (rassoc (match-string 0 text) table)))
6764 t t text)))
6765 text)))
6767 (defun org-xor (a b)
6768 "Exclusive or."
6769 (if a (not b) b))
6771 (defun org-fixup-message-id-for-http (s)
6772 "Replace special characters in a message id, so it can be used in an http query."
6773 (while (string-match "<" s)
6774 (setq s (replace-match "%3C" t t s)))
6775 (while (string-match ">" s)
6776 (setq s (replace-match "%3E" t t s)))
6777 (while (string-match "@" s)
6778 (setq s (replace-match "%40" t t s)))
6781 ;;;###autoload
6782 (defun org-insert-link-global ()
6783 "Insert a link like Org-mode does.
6784 This command can be called in any mode to insert a link in Org-mode syntax."
6785 (interactive)
6786 (org-load-modules-maybe)
6787 (org-run-like-in-org-mode 'org-insert-link))
6789 (defun org-insert-link (&optional complete-file link-location)
6790 "Insert a link. At the prompt, enter the link.
6792 Completion can be used to insert any of the link protocol prefixes like
6793 http or ftp in use.
6795 The history can be used to select a link previously stored with
6796 `org-store-link'. When the empty string is entered (i.e. if you just
6797 press RET at the prompt), the link defaults to the most recently
6798 stored link. As SPC triggers completion in the minibuffer, you need to
6799 use M-SPC or C-q SPC to force the insertion of a space character.
6801 You will also be prompted for a description, and if one is given, it will
6802 be displayed in the buffer instead of the link.
6804 If there is already a link at point, this command will allow you to edit link
6805 and description parts.
6807 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6808 be selected using completion. The path to the file will be relative to the
6809 current directory if the file is in the current directory or a subdirectory.
6810 Otherwise, the link will be the absolute path as completed in the minibuffer
6811 \(i.e. normally ~/path/to/file). You can configure this behavior using the
6812 option `org-link-file-path-type'.
6814 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6815 the current directory or below.
6817 With three \\[universal-argument] prefixes, negate the meaning of
6818 `org-keep-stored-link-after-insertion'.
6820 If `org-make-link-description-function' is non-nil, this function will be
6821 called with the link target, and the result will be the default
6822 link description.
6824 If the LINK-LOCATION parameter is non-nil, this value will be
6825 used as the link location instead of reading one interactively."
6826 (interactive "P")
6827 (let* ((wcf (current-window-configuration))
6828 (region (if (org-region-active-p)
6829 (buffer-substring (region-beginning) (region-end))))
6830 (remove (and region (list (region-beginning) (region-end))))
6831 (desc region)
6832 tmphist ; byte-compile incorrectly complains about this
6833 (link link-location)
6834 entry file)
6835 (cond
6836 (link-location) ; specified by arg, just use it.
6837 ((org-in-regexp org-bracket-link-regexp 1)
6838 ;; We do have a link at point, and we are going to edit it.
6839 (setq remove (list (match-beginning 0) (match-end 0)))
6840 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6841 (setq link (read-string "Link: "
6842 (org-link-unescape
6843 (org-match-string-no-properties 1)))))
6844 ((or (org-in-regexp org-angle-link-re)
6845 (org-in-regexp org-plain-link-re))
6846 ;; Convert to bracket link
6847 (setq remove (list (match-beginning 0) (match-end 0))
6848 link (read-string "Link: "
6849 (org-remove-angle-brackets (match-string 0)))))
6850 ((member complete-file '((4) (16)))
6851 ;; Completing read for file names.
6852 (setq file (read-file-name "File: "))
6853 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6854 (pwd1 (file-name-as-directory (abbreviate-file-name
6855 (expand-file-name ".")))))
6856 (cond
6857 ((equal complete-file '(16))
6858 (setq link (org-make-link
6859 "file:"
6860 (abbreviate-file-name (expand-file-name file)))))
6861 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6862 (setq link (org-make-link "file:" (match-string 1 file))))
6863 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6864 (expand-file-name file))
6865 (setq link (org-make-link
6866 "file:" (match-string 1 (expand-file-name file)))))
6867 (t (setq link (org-make-link "file:" file))))))
6869 ;; Read link, with completion for stored links.
6870 (with-output-to-temp-buffer "*Org Links*"
6871 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6872 (when org-stored-links
6873 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6874 (princ (mapconcat
6875 (lambda (x)
6876 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6877 (reverse org-stored-links) "\n"))))
6878 (let ((cw (selected-window)))
6879 (select-window (get-buffer-window "*Org Links*"))
6880 (setq truncate-lines t)
6881 (org-fit-window-to-buffer)
6882 (select-window cw))
6883 ;; Fake a link history, containing the stored links.
6884 (setq tmphist (append (mapcar 'car org-stored-links)
6885 org-insert-link-history))
6886 (unwind-protect
6887 (setq link
6888 (let ((org-completion-use-ido nil))
6889 (org-completing-read
6890 "Link: "
6891 (append
6892 (mapcar (lambda (x) (list (concat (car x) ":")))
6893 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6894 (mapcar (lambda (x) (list (concat x ":")))
6895 org-link-types))
6896 nil nil nil
6897 'tmphist
6898 (or (car (car org-stored-links))))))
6899 (set-window-configuration wcf)
6900 (kill-buffer "*Org Links*"))
6901 (setq entry (assoc link org-stored-links))
6902 (or entry (push link org-insert-link-history))
6903 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6904 (not org-keep-stored-link-after-insertion))
6905 (setq org-stored-links (delq (assoc link org-stored-links)
6906 org-stored-links)))
6907 (setq desc (or desc (nth 1 entry)))))
6909 (if (string-match org-plain-link-re link)
6910 ;; URL-like link, normalize the use of angular brackets.
6911 (setq link (org-make-link (org-remove-angle-brackets link))))
6913 ;; Check if we are linking to the current file with a search option
6914 ;; If yes, simplify the link by using only the search option.
6915 (when (and buffer-file-name
6916 (string-match "^file:\\(.+?\\)::\\([^>]+\\)" link))
6917 (let* ((path (match-string 1 link))
6918 (case-fold-search nil)
6919 (search (match-string 2 link)))
6920 (save-match-data
6921 (if (equal (file-truename buffer-file-name) (file-truename path))
6922 ;; We are linking to this same file, with a search option
6923 (setq link search)))))
6925 ;; Check if we can/should use a relative path. If yes, simplify the link
6926 (when (string-match "^file:\\(.*\\)" link)
6927 (let* ((path (match-string 1 link))
6928 (origpath path)
6929 (case-fold-search nil))
6930 (cond
6931 ((or (eq org-link-file-path-type 'absolute)
6932 (equal complete-file '(16)))
6933 (setq path (abbreviate-file-name (expand-file-name path))))
6934 ((eq org-link-file-path-type 'noabbrev)
6935 (setq path (expand-file-name path)))
6936 ((eq org-link-file-path-type 'relative)
6937 (setq path (file-relative-name path)))
6939 (save-match-data
6940 (if (string-match (concat "^" (regexp-quote
6941 (file-name-as-directory
6942 (expand-file-name "."))))
6943 (expand-file-name path))
6944 ;; We are linking a file with relative path name.
6945 (setq path (substring (expand-file-name path)
6946 (match-end 0)))
6947 (setq path (abbreviate-file-name (expand-file-name path)))))))
6948 (setq link (concat "file:" path))
6949 (if (equal desc origpath)
6950 (setq desc path))))
6952 (if org-make-link-description-function
6953 (setq desc (funcall org-make-link-description-function link desc)))
6955 (setq desc (read-string "Description: " desc))
6956 (unless (string-match "\\S-" desc) (setq desc nil))
6957 (if remove (apply 'delete-region remove))
6958 (insert (org-make-link-string link desc))))
6960 (defun org-completing-read (&rest args)
6961 "Completing-read with SPACE being a normal character."
6962 (let ((minibuffer-local-completion-map
6963 (copy-keymap minibuffer-local-completion-map)))
6964 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6965 (org-defkey minibuffer-local-completion-map "?" 'self-insert-command)
6966 (apply 'org-ido-completing-read args)))
6968 (defun org-ido-completing-read (&rest args)
6969 "Completing-read using `ido-mode' speedups if available"
6970 (if (and org-completion-use-ido
6971 (fboundp 'ido-completing-read)
6972 (boundp 'ido-mode) ido-mode
6973 (listp (second args)))
6974 (apply 'ido-completing-read (concat (car args)) (cdr args))
6975 (apply 'completing-read args)))
6977 (defun org-extract-attributes (s)
6978 "Extract the attributes cookie from a string and set as text property."
6979 (let (a attr (start 0) key value)
6980 (save-match-data
6981 (when (string-match "{{\\([^}]+\\)}}$" s)
6982 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
6983 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
6984 (setq key (match-string 1 a) value (match-string 2 a)
6985 start (match-end 0)
6986 attr (plist-put attr (intern key) value))))
6987 (org-add-props s nil 'org-attr attr))
6990 (defun org-attributes-to-string (plist)
6991 "Format a property list into an HTML attribute list."
6992 (let ((s "") key value)
6993 (while plist
6994 (setq key (pop plist) value (pop plist))
6995 (and value
6996 (setq s (concat s " " (symbol-name key) "=\"" value "\""))))
6999 ;;; Opening/following a link
7001 (defvar org-link-search-failed nil)
7003 (defun org-next-link ()
7004 "Move forward to the next link.
7005 If the link is in hidden text, expose it."
7006 (interactive)
7007 (when (and org-link-search-failed (eq this-command last-command))
7008 (goto-char (point-min))
7009 (message "Link search wrapped back to beginning of buffer"))
7010 (setq org-link-search-failed nil)
7011 (let* ((pos (point))
7012 (ct (org-context))
7013 (a (assoc :link ct)))
7014 (if a (goto-char (nth 2 a)))
7015 (if (re-search-forward org-any-link-re nil t)
7016 (progn
7017 (goto-char (match-beginning 0))
7018 (if (org-invisible-p) (org-show-context)))
7019 (goto-char pos)
7020 (setq org-link-search-failed t)
7021 (error "No further link found"))))
7023 (defun org-previous-link ()
7024 "Move backward to the previous link.
7025 If the link is in hidden text, expose it."
7026 (interactive)
7027 (when (and org-link-search-failed (eq this-command last-command))
7028 (goto-char (point-max))
7029 (message "Link search wrapped back to end of buffer"))
7030 (setq org-link-search-failed nil)
7031 (let* ((pos (point))
7032 (ct (org-context))
7033 (a (assoc :link ct)))
7034 (if a (goto-char (nth 1 a)))
7035 (if (re-search-backward org-any-link-re nil t)
7036 (progn
7037 (goto-char (match-beginning 0))
7038 (if (org-invisible-p) (org-show-context)))
7039 (goto-char pos)
7040 (setq org-link-search-failed t)
7041 (error "No further link found"))))
7043 (defun org-translate-link (s)
7044 "Translate a link string if a translation function has been defined."
7045 (if (and org-link-translation-function
7046 (fboundp org-link-translation-function)
7047 (string-match "\\([a-zA-Z0-9]+\\):\\(.*\\)" s))
7048 (progn
7049 (setq s (funcall org-link-translation-function
7050 (match-string 1) (match-string 2)))
7051 (concat (car s) ":" (cdr s)))
7054 (defun org-translate-link-from-planner (type path)
7055 "Translate a link from Emacs Planner syntax so that Org can follow it.
7056 This is still an experimental function, your mileage may vary."
7057 (cond
7058 ((member type '("http" "https" "news" "ftp"))
7059 ;; standard Internet links are the same.
7060 nil)
7061 ((and (equal type "irc") (string-match "^//" path))
7062 ;; Planner has two / at the beginning of an irc link, we have 1.
7063 ;; We should have zero, actually....
7064 (setq path (substring path 1)))
7065 ((and (equal type "lisp") (string-match "^/" path))
7066 ;; Planner has a slash, we do not.
7067 (setq type "elisp" path (substring path 1)))
7068 ((string-match "^//\\(.?*\\)/\\(<.*>\\)$" path)
7069 ;; A typical message link. Planner has the id after the fina slash,
7070 ;; we separate it with a hash mark
7071 (setq path (concat (match-string 1 path) "#"
7072 (org-remove-angle-brackets (match-string 2 path)))))
7074 (cons type path))
7076 (defun org-find-file-at-mouse (ev)
7077 "Open file link or URL at mouse."
7078 (interactive "e")
7079 (mouse-set-point ev)
7080 (org-open-at-point 'in-emacs))
7082 (defun org-open-at-mouse (ev)
7083 "Open file link or URL at mouse."
7084 (interactive "e")
7085 (mouse-set-point ev)
7086 (if (eq major-mode 'org-agenda-mode)
7087 (org-agenda-copy-local-variable 'org-link-abbrev-alist-local))
7088 (org-open-at-point))
7090 (defvar org-window-config-before-follow-link nil
7091 "The window configuration before following a link.
7092 This is saved in case the need arises to restore it.")
7094 (defvar org-open-link-marker (make-marker)
7095 "Marker pointing to the location where `org-open-at-point; was called.")
7097 ;;;###autoload
7098 (defun org-open-at-point-global ()
7099 "Follow a link like Org-mode does.
7100 This command can be called in any mode to follow a link that has
7101 Org-mode syntax."
7102 (interactive)
7103 (org-run-like-in-org-mode 'org-open-at-point))
7105 ;;;###autoload
7106 (defun org-open-link-from-string (s &optional arg)
7107 "Open a link in the string S, as if it was in Org-mode."
7108 (interactive "sLink: \nP")
7109 (with-temp-buffer
7110 (let ((org-inhibit-startup t))
7111 (org-mode)
7112 (insert s)
7113 (goto-char (point-min))
7114 (org-open-at-point arg))))
7116 (defun org-open-at-point (&optional in-emacs)
7117 "Open link at or after point.
7118 If there is no link at point, this function will search forward up to
7119 the end of the current subtree.
7120 Normally, files will be opened by an appropriate application. If the
7121 optional argument IN-EMACS is non-nil, Emacs will visit the file.
7122 With a double prefix argument, try to open outside of Emacs, in the
7123 application the system uses for this file type."
7124 (interactive "P")
7125 (org-load-modules-maybe)
7126 (move-marker org-open-link-marker (point))
7127 (setq org-window-config-before-follow-link (current-window-configuration))
7128 (org-remove-occur-highlights nil nil t)
7129 (cond
7130 ((org-at-timestamp-p t) (org-follow-timestamp-link))
7131 ((or (org-footnote-at-reference-p) (org-footnote-at-definition-p))
7132 (org-footnote-action))
7134 (let (type path link line search (pos (point)))
7135 (catch 'match
7136 (save-excursion
7137 (skip-chars-forward "^]\n\r")
7138 (when (org-in-regexp org-bracket-link-regexp)
7139 (setq link (org-extract-attributes
7140 (org-link-unescape (org-match-string-no-properties 1))))
7141 (while (string-match " *\n *" link)
7142 (setq link (replace-match " " t t link)))
7143 (setq link (org-link-expand-abbrev link))
7144 (cond
7145 ((or (file-name-absolute-p link)
7146 (string-match "^\\.\\.?/" link))
7147 (setq type "file" path link))
7148 ((string-match org-link-re-with-space3 link)
7149 (setq type (match-string 1 link) path (match-string 2 link)))
7150 (t (setq type "thisfile" path link)))
7151 (throw 'match t)))
7153 (when (get-text-property (point) 'org-linked-text)
7154 (setq type "thisfile"
7155 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7156 (1+ (point)) (point))
7157 path (buffer-substring
7158 (previous-single-property-change pos 'org-linked-text)
7159 (next-single-property-change pos 'org-linked-text)))
7160 (throw 'match t))
7162 (save-excursion
7163 (when (or (org-in-regexp org-angle-link-re)
7164 (org-in-regexp org-plain-link-re))
7165 (setq type (match-string 1) path (match-string 2))
7166 (throw 'match t)))
7167 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7168 (setq type "tree-match"
7169 path (match-string 1))
7170 (throw 'match t))
7171 (save-excursion
7172 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7173 (setq type "tags"
7174 path (match-string 1))
7175 (while (string-match ":" path)
7176 (setq path (replace-match "+" t t path)))
7177 (throw 'match t))))
7178 (unless path
7179 (error "No link found"))
7180 ;; Remove any trailing spaces in path
7181 (if (string-match " +\\'" path)
7182 (setq path (replace-match "" t t path)))
7183 (if (and org-link-translation-function
7184 (fboundp org-link-translation-function))
7185 ;; Check if we need to translate the link
7186 (let ((tmp (funcall org-link-translation-function type path)))
7187 (setq type (car tmp) path (cdr tmp))))
7189 (cond
7191 ((assoc type org-link-protocols)
7192 (funcall (nth 1 (assoc type org-link-protocols)) path))
7194 ((equal type "mailto")
7195 (let ((cmd (car org-link-mailto-program))
7196 (args (cdr org-link-mailto-program)) args1
7197 (address path) (subject "") a)
7198 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7199 (setq address (match-string 1 path)
7200 subject (org-link-escape (match-string 2 path))))
7201 (while args
7202 (cond
7203 ((not (stringp (car args))) (push (pop args) args1))
7204 (t (setq a (pop args))
7205 (if (string-match "%a" a)
7206 (setq a (replace-match address t t a)))
7207 (if (string-match "%s" a)
7208 (setq a (replace-match subject t t a)))
7209 (push a args1))))
7210 (apply cmd (nreverse args1))))
7212 ((member type '("http" "https" "ftp" "news"))
7213 (browse-url (concat type ":" (org-link-escape
7214 path org-link-escape-chars-browser))))
7216 ((member type '("message"))
7217 (browse-url (concat type ":" path)))
7219 ((string= type "tags")
7220 (org-tags-view in-emacs path))
7221 ((string= type "thisfile")
7222 (if in-emacs
7223 (switch-to-buffer-other-window
7224 (org-get-buffer-for-internal-link (current-buffer)))
7225 (org-mark-ring-push))
7226 (let ((cmd `(org-link-search
7227 ,path
7228 ,(cond ((equal in-emacs '(4)) 'occur)
7229 ((equal in-emacs '(16)) 'org-occur)
7230 (t nil))
7231 ,pos)))
7232 (condition-case nil (eval cmd)
7233 (error (progn (widen) (eval cmd))))))
7235 ((string= type "tree-match")
7236 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7238 ((string= type "file")
7239 (if (string-match "::\\([0-9]+\\)\\'" path)
7240 (setq line (string-to-number (match-string 1 path))
7241 path (substring path 0 (match-beginning 0)))
7242 (if (string-match "::\\(.+\\)\\'" path)
7243 (setq search (match-string 1 path)
7244 path (substring path 0 (match-beginning 0)))))
7245 (if (string-match "[*?{]" (file-name-nondirectory path))
7246 (dired path)
7247 (org-open-file path in-emacs line search)))
7249 ((string= type "news")
7250 (require 'org-gnus)
7251 (org-gnus-follow-link path))
7253 ((string= type "shell")
7254 (let ((cmd path))
7255 (if (or (not org-confirm-shell-link-function)
7256 (funcall org-confirm-shell-link-function
7257 (format "Execute \"%s\" in shell? "
7258 (org-add-props cmd nil
7259 'face 'org-warning))))
7260 (progn
7261 (message "Executing %s" cmd)
7262 (shell-command cmd))
7263 (error "Abort"))))
7265 ((string= type "elisp")
7266 (let ((cmd path))
7267 (if (or (not org-confirm-elisp-link-function)
7268 (funcall org-confirm-elisp-link-function
7269 (format "Execute \"%s\" as elisp? "
7270 (org-add-props cmd nil
7271 'face 'org-warning))))
7272 (message "%s => %s" cmd
7273 (if (equal (string-to-char cmd) ?\()
7274 (eval (read cmd))
7275 (call-interactively (read cmd))))
7276 (error "Abort"))))
7279 (browse-url-at-point))))))
7280 (move-marker org-open-link-marker nil)
7281 (run-hook-with-args 'org-follow-link-hook))
7283 ;;;; Time estimates
7285 (defun org-get-effort (&optional pom)
7286 "Get the effort estimate for the current entry."
7287 (org-entry-get pom org-effort-property))
7289 ;;; File search
7291 (defvar org-create-file-search-functions nil
7292 "List of functions to construct the right search string for a file link.
7293 These functions are called in turn with point at the location to
7294 which the link should point.
7296 A function in the hook should first test if it would like to
7297 handle this file type, for example by checking the major-mode or
7298 the file extension. If it decides not to handle this file, it
7299 should just return nil to give other functions a chance. If it
7300 does handle the file, it must return the search string to be used
7301 when following the link. The search string will be part of the
7302 file link, given after a double colon, and `org-open-at-point'
7303 will automatically search for it. If special measures must be
7304 taken to make the search successful, another function should be
7305 added to the companion hook `org-execute-file-search-functions',
7306 which see.
7308 A function in this hook may also use `setq' to set the variable
7309 `description' to provide a suggestion for the descriptive text to
7310 be used for this link when it gets inserted into an Org-mode
7311 buffer with \\[org-insert-link].")
7313 (defvar org-execute-file-search-functions nil
7314 "List of functions to execute a file search triggered by a link.
7316 Functions added to this hook must accept a single argument, the
7317 search string that was part of the file link, the part after the
7318 double colon. The function must first check if it would like to
7319 handle this search, for example by checking the major-mode or the
7320 file extension. If it decides not to handle this search, it
7321 should just return nil to give other functions a chance. If it
7322 does handle the search, it must return a non-nil value to keep
7323 other functions from trying.
7325 Each function can access the current prefix argument through the
7326 variable `current-prefix-argument'. Note that a single prefix is
7327 used to force opening a link in Emacs, so it may be good to only
7328 use a numeric or double prefix to guide the search function.
7330 In case this is needed, a function in this hook can also restore
7331 the window configuration before `org-open-at-point' was called using:
7333 (set-window-configuration org-window-config-before-follow-link)")
7335 (defun org-link-search (s &optional type avoid-pos)
7336 "Search for a link search option.
7337 If S is surrounded by forward slashes, it is interpreted as a
7338 regular expression. In org-mode files, this will create an `org-occur'
7339 sparse tree. In ordinary files, `occur' will be used to list matches.
7340 If the current buffer is in `dired-mode', grep will be used to search
7341 in all files. If AVOID-POS is given, ignore matches near that position."
7342 (let ((case-fold-search t)
7343 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7344 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7345 (append '(("") (" ") ("\t") ("\n"))
7346 org-emphasis-alist)
7347 "\\|") "\\)"))
7348 (pos (point))
7349 (pre nil) (post nil)
7350 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7351 (cond
7352 ;; First check if there are any special
7353 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7354 ;; Now try the builtin stuff
7355 ((save-excursion
7356 (goto-char (point-min))
7357 (and
7358 (re-search-forward
7359 (concat "<<" (regexp-quote s0) ">>") nil t)
7360 (setq type 'dedicated
7361 pos (match-beginning 0))))
7362 ;; There is an exact target for this
7363 (goto-char pos))
7364 ((and (string-match "^(\\(.*\\))$" s0)
7365 (save-excursion
7366 (goto-char (point-min))
7367 (and
7368 (re-search-forward
7369 (concat "[^[]" (regexp-quote
7370 (format org-coderef-label-format
7371 (match-string 1 s0))))
7372 nil t)
7373 (setq type 'dedicated
7374 pos (1+ (match-beginning 0))))))
7375 ;; There is a coderef target for this
7376 (goto-char pos))
7377 ((string-match "^/\\(.*\\)/$" s)
7378 ;; A regular expression
7379 (cond
7380 ((org-mode-p)
7381 (org-occur (match-string 1 s)))
7382 ;;((eq major-mode 'dired-mode)
7383 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7384 (t (org-do-occur (match-string 1 s)))))
7386 ;; A normal search strings
7387 (when (equal (string-to-char s) ?*)
7388 ;; Anchor on headlines, post may include tags.
7389 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7390 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7391 s (substring s 1)))
7392 (remove-text-properties
7393 0 (length s)
7394 '(face nil mouse-face nil keymap nil fontified nil) s)
7395 ;; Make a series of regular expressions to find a match
7396 (setq words (org-split-string s "[ \n\r\t]+")
7398 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7399 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7400 "\\)" markers)
7401 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7402 re2a (concat "[ \t\r\n]" re2a_)
7403 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7404 re4 (concat "[^a-zA-Z_]" re4_)
7406 re1 (concat pre re2 post)
7407 re3 (concat pre (if pre re4_ re4) post)
7408 re5 (concat pre ".*" re4)
7409 re2 (concat pre re2)
7410 re2a (concat pre (if pre re2a_ re2a))
7411 re4 (concat pre (if pre re4_ re4))
7412 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7413 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7414 re5 "\\)"
7416 (cond
7417 ((eq type 'org-occur) (org-occur reall))
7418 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7419 (t (goto-char (point-min))
7420 (setq type 'fuzzy)
7421 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7422 (org-search-not-self 1 re1 nil t)
7423 (org-search-not-self 1 re2 nil t)
7424 (org-search-not-self 1 re2a nil t)
7425 (org-search-not-self 1 re3 nil t)
7426 (org-search-not-self 1 re4 nil t)
7427 (org-search-not-self 1 re5 nil t)
7429 (goto-char (match-beginning 1))
7430 (goto-char pos)
7431 (error "No match")))))
7433 ;; Normal string-search
7434 (goto-char (point-min))
7435 (if (search-forward s nil t)
7436 (goto-char (match-beginning 0))
7437 (error "No match"))))
7438 (and (org-mode-p) (org-show-context 'link-search))
7439 type))
7441 (defun org-search-not-self (group &rest args)
7442 "Execute `re-search-forward', but only accept matches that do not
7443 enclose the position of `org-open-link-marker'."
7444 (let ((m org-open-link-marker))
7445 (catch 'exit
7446 (while (apply 're-search-forward args)
7447 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7448 (goto-char (match-end group))
7449 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7450 (> (match-beginning 0) (marker-position m))
7451 (< (match-end 0) (marker-position m)))
7452 (save-match-data
7453 (or (not (org-in-regexp
7454 org-bracket-link-analytic-regexp 1))
7455 (not (match-end 4)) ; no description
7456 (and (<= (match-beginning 4) (point))
7457 (>= (match-end 4) (point))))))
7458 (throw 'exit (point))))))))
7460 (defun org-get-buffer-for-internal-link (buffer)
7461 "Return a buffer to be used for displaying the link target of internal links."
7462 (cond
7463 ((not org-display-internal-link-with-indirect-buffer)
7464 buffer)
7465 ((string-match "(Clone)$" (buffer-name buffer))
7466 (message "Buffer is already a clone, not making another one")
7467 ;; we also do not modify visibility in this case
7468 buffer)
7469 (t ; make a new indirect buffer for displaying the link
7470 (let* ((bn (buffer-name buffer))
7471 (ibn (concat bn "(Clone)"))
7472 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7473 (with-current-buffer ib (org-overview))
7474 ib))))
7476 (defun org-do-occur (regexp &optional cleanup)
7477 "Call the Emacs command `occur'.
7478 If CLEANUP is non-nil, remove the printout of the regular expression
7479 in the *Occur* buffer. This is useful if the regex is long and not useful
7480 to read."
7481 (occur regexp)
7482 (when cleanup
7483 (let ((cwin (selected-window)) win beg end)
7484 (when (setq win (get-buffer-window "*Occur*"))
7485 (select-window win))
7486 (goto-char (point-min))
7487 (when (re-search-forward "match[a-z]+" nil t)
7488 (setq beg (match-end 0))
7489 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7490 (setq end (1- (match-beginning 0)))))
7491 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7492 (goto-char (point-min))
7493 (select-window cwin))))
7495 ;;; The mark ring for links jumps
7497 (defvar org-mark-ring nil
7498 "Mark ring for positions before jumps in Org-mode.")
7499 (defvar org-mark-ring-last-goto nil
7500 "Last position in the mark ring used to go back.")
7501 ;; Fill and close the ring
7502 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7503 (loop for i from 1 to org-mark-ring-length do
7504 (push (make-marker) org-mark-ring))
7505 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7506 org-mark-ring)
7508 (defun org-mark-ring-push (&optional pos buffer)
7509 "Put the current position or POS into the mark ring and rotate it."
7510 (interactive)
7511 (setq pos (or pos (point)))
7512 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7513 (move-marker (car org-mark-ring)
7514 (or pos (point))
7515 (or buffer (current-buffer)))
7516 (message "%s"
7517 (substitute-command-keys
7518 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7520 (defun org-mark-ring-goto (&optional n)
7521 "Jump to the previous position in the mark ring.
7522 With prefix arg N, jump back that many stored positions. When
7523 called several times in succession, walk through the entire ring.
7524 Org-mode commands jumping to a different position in the current file,
7525 or to another Org-mode file, automatically push the old position
7526 onto the ring."
7527 (interactive "p")
7528 (let (p m)
7529 (if (eq last-command this-command)
7530 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7531 (setq p org-mark-ring))
7532 (setq org-mark-ring-last-goto p)
7533 (setq m (car p))
7534 (switch-to-buffer (marker-buffer m))
7535 (goto-char m)
7536 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7538 (defun org-remove-angle-brackets (s)
7539 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7540 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7542 (defun org-add-angle-brackets (s)
7543 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7544 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7546 (defun org-remove-double-quotes (s)
7547 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7548 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7551 ;;; Following specific links
7553 (defun org-follow-timestamp-link ()
7554 (cond
7555 ((org-at-date-range-p t)
7556 (let ((org-agenda-start-on-weekday)
7557 (t1 (match-string 1))
7558 (t2 (match-string 2)))
7559 (setq t1 (time-to-days (org-time-string-to-time t1))
7560 t2 (time-to-days (org-time-string-to-time t2)))
7561 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7562 ((org-at-timestamp-p t)
7563 (org-agenda-list nil (time-to-days (org-time-string-to-time
7564 (substring (match-string 1) 0 10)))
7566 (t (error "This should not happen"))))
7569 ;;; Following file links
7570 (defvar org-wait nil)
7571 (defun org-open-file (path &optional in-emacs line search)
7572 "Open the file at PATH.
7573 First, this expands any special file name abbreviations. Then the
7574 configuration variable `org-file-apps' is checked if it contains an
7575 entry for this file type, and if yes, the corresponding command is launched.
7577 If no application is found, Emacs simply visits the file.
7579 With optional prefix argument IN-EMACS, Emacs will visit the file.
7580 With a double C-c C-u prefix arg, Org tries to avoid opening in Emacs
7581 and o use an external application to visit the file.
7583 Optional LINE specifies a line to go to, optional SEARCH a string to
7584 search for. If LINE or SEARCH is given, the file will always be
7585 opened in Emacs.
7586 If the file does not exist, an error is thrown."
7587 (setq in-emacs (or in-emacs line search))
7588 (let* ((file (if (equal path "")
7589 buffer-file-name
7590 (substitute-in-file-name (expand-file-name path))))
7591 (apps (append org-file-apps (org-default-apps)))
7592 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7593 (dirp (if remp nil (file-directory-p file)))
7594 (file (if (and dirp org-open-directory-means-index-dot-org)
7595 (concat (file-name-as-directory file) "index.org")
7596 file))
7597 (a-m-a-p (assq 'auto-mode apps))
7598 (dfile (downcase file))
7599 (old-buffer (current-buffer))
7600 (old-pos (point))
7601 (old-mode major-mode)
7602 ext cmd)
7603 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7604 (setq ext (match-string 1 dfile))
7605 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7606 (setq ext (match-string 1 dfile))))
7607 (cond
7608 ((equal in-emacs '(16))
7609 (setq cmd (cdr (assoc 'system apps))))
7610 (in-emacs (setq cmd 'emacs))
7612 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7613 (and dirp (cdr (assoc 'directory apps)))
7614 (assoc-default dfile (org-apps-regexp-alist apps a-m-a-p)
7615 'string-match)
7616 (cdr (assoc ext apps))
7617 (cdr (assoc t apps))))))
7618 (when (eq cmd 'system)
7619 (setq cmd (cdr (assoc 'system apps))))
7620 (when (eq cmd 'default)
7621 (setq cmd (cdr (assoc t apps))))
7622 (when (eq cmd 'mailcap)
7623 (require 'mailcap)
7624 (mailcap-parse-mailcaps)
7625 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7626 (command (mailcap-mime-info mime-type)))
7627 (if (stringp command)
7628 (setq cmd command)
7629 (setq cmd 'emacs))))
7630 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7631 (not (file-exists-p file))
7632 (not org-open-non-existing-files))
7633 (error "No such file: %s" file))
7634 (cond
7635 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7636 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7637 (while (string-match "['\"]%s['\"]" cmd)
7638 (setq cmd (replace-match "%s" t t cmd)))
7639 (while (string-match "%s" cmd)
7640 (setq cmd (replace-match
7641 (save-match-data
7642 (shell-quote-argument
7643 (convert-standard-filename file)))
7644 t t cmd)))
7645 (save-window-excursion
7646 (start-process-shell-command cmd nil cmd)
7647 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7649 ((or (stringp cmd)
7650 (eq cmd 'emacs))
7651 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7652 (widen)
7653 (if line (goto-line line)
7654 (if search (org-link-search search))))
7655 ((consp cmd)
7656 (let ((file (convert-standard-filename file)))
7657 (eval cmd)))
7658 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7659 (and (org-mode-p) (eq old-mode 'org-mode)
7660 (or (not (equal old-buffer (current-buffer)))
7661 (not (equal old-pos (point))))
7662 (org-mark-ring-push old-pos old-buffer))))
7664 (defun org-default-apps ()
7665 "Return the default applications for this operating system."
7666 (cond
7667 ((eq system-type 'darwin)
7668 org-file-apps-defaults-macosx)
7669 ((eq system-type 'windows-nt)
7670 org-file-apps-defaults-windowsnt)
7671 (t org-file-apps-defaults-gnu)))
7673 (defun org-apps-regexp-alist (list &optional add-auto-mode)
7674 "Convert extensions to regular expressions in the cars of LIST.
7675 Also, weed out any non-string entries, because the return value is used
7676 only for regexp matching.
7677 When ADD-AUTO-MODE is set, make all matches in `auto-mode-alist'
7678 point to the symbol `emacs', indicating that the file should
7679 be opened in Emacs."
7680 (append
7681 (delq nil
7682 (mapcar (lambda (x)
7683 (if (not (stringp (car x)))
7685 (if (string-match "\\W" (car x))
7687 (cons (concat "\\." (car x) "\\'") (cdr x)))))
7688 list))
7689 (if add-auto-mode
7690 (mapcar (lambda (x) (cons (car x) 'emacs)) auto-mode-alist))))
7692 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7693 (defun org-file-remote-p (file)
7694 "Test whether FILE specifies a location on a remote system.
7695 Return non-nil if the location is indeed remote.
7697 For example, the filename \"/user@host:/foo\" specifies a location
7698 on the system \"/user@host:\"."
7699 (cond ((fboundp 'file-remote-p)
7700 (file-remote-p file))
7701 ((fboundp 'tramp-handle-file-remote-p)
7702 (tramp-handle-file-remote-p file))
7703 ((and (boundp 'ange-ftp-name-format)
7704 (string-match (car ange-ftp-name-format) file))
7706 (t nil)))
7709 ;;;; Refiling
7711 (defun org-get-org-file ()
7712 "Read a filename, with default directory `org-directory'."
7713 (let ((default (or org-default-notes-file remember-data-file)))
7714 (read-file-name (format "File name [%s]: " default)
7715 (file-name-as-directory org-directory)
7716 default)))
7718 (defun org-notes-order-reversed-p ()
7719 "Check if the current file should receive notes in reversed order."
7720 (cond
7721 ((not org-reverse-note-order) nil)
7722 ((eq t org-reverse-note-order) t)
7723 ((not (listp org-reverse-note-order)) nil)
7724 (t (catch 'exit
7725 (let ((all org-reverse-note-order)
7726 entry)
7727 (while (setq entry (pop all))
7728 (if (string-match (car entry) buffer-file-name)
7729 (throw 'exit (cdr entry))))
7730 nil)))))
7732 (defvar org-refile-target-table nil
7733 "The list of refile targets, created by `org-refile'.")
7735 (defvar org-agenda-new-buffers nil
7736 "Buffers created to visit agenda files.")
7738 (defun org-get-refile-targets (&optional default-buffer)
7739 "Produce a table with refile targets."
7740 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7741 targets txt re files f desc descre fast-path-p level)
7742 (message "Getting targets...")
7743 (with-current-buffer (or default-buffer (current-buffer))
7744 (while (setq entry (pop entries))
7745 (setq files (car entry) desc (cdr entry))
7746 (setq fast-path-p nil)
7747 (cond
7748 ((null files) (setq files (list (current-buffer))))
7749 ((eq files 'org-agenda-files)
7750 (setq files (org-agenda-files 'unrestricted)))
7751 ((and (symbolp files) (fboundp files))
7752 (setq files (funcall files)))
7753 ((and (symbolp files) (boundp files))
7754 (setq files (symbol-value files))))
7755 (if (stringp files) (setq files (list files)))
7756 (cond
7757 ((eq (car desc) :tag)
7758 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7759 ((eq (car desc) :todo)
7760 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7761 ((eq (car desc) :regexp)
7762 (setq descre (cdr desc)))
7763 ((eq (car desc) :level)
7764 (setq descre (concat "^\\*\\{" (number-to-string
7765 (if org-odd-levels-only
7766 (1- (* 2 (cdr desc)))
7767 (cdr desc)))
7768 "\\}[ \t]")))
7769 ((eq (car desc) :maxlevel)
7770 (setq fast-path-p t)
7771 (setq descre (concat "^\\*\\{1," (number-to-string
7772 (if org-odd-levels-only
7773 (1- (* 2 (cdr desc)))
7774 (cdr desc)))
7775 "\\}[ \t]")))
7776 (t (error "Bad refiling target description %s" desc)))
7777 (while (setq f (pop files))
7778 (save-excursion
7779 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7780 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7781 (setq f (expand-file-name f))
7782 (save-excursion
7783 (save-restriction
7784 (widen)
7785 (goto-char (point-min))
7786 (while (re-search-forward descre nil t)
7787 (goto-char (point-at-bol))
7788 (when (looking-at org-complex-heading-regexp)
7789 (setq level (org-reduced-level (- (match-end 1) (match-beginning 1)))
7790 txt (org-link-display-format (match-string 4))
7791 re (concat "^" (regexp-quote
7792 (buffer-substring (match-beginning 1)
7793 (match-end 4)))))
7794 (if (match-end 5) (setq re (concat re "[ \t]+"
7795 (regexp-quote
7796 (match-string 5)))))
7797 (setq re (concat re "[ \t]*$"))
7798 (when org-refile-use-outline-path
7799 (setq txt (mapconcat 'org-protect-slash
7800 (append
7801 (if (eq org-refile-use-outline-path 'file)
7802 (list (file-name-nondirectory
7803 (buffer-file-name (buffer-base-buffer))))
7804 (if (eq org-refile-use-outline-path 'full-file-path)
7805 (list (buffer-file-name (buffer-base-buffer)))))
7806 (org-get-outline-path fast-path-p level txt)
7807 (list txt))
7808 "/")))
7809 (push (list txt f re (point)) targets))
7810 (goto-char (point-at-eol))))))))
7811 (message "Getting targets...done")
7812 (nreverse targets))))
7814 (defun org-protect-slash (s)
7815 (while (string-match "/" s)
7816 (setq s (replace-match "\\" t t s)))
7819 (defvar org-olpa (make-vector 20 nil))
7821 (defun org-get-outline-path (&optional fastp level heading)
7822 "Return the outline path to the current entry, as a list."
7823 (if fastp
7824 (progn
7825 (if (> level 19)
7826 (error "Outline path failure, more than 19 levels."))
7827 (loop for i from level upto 19 do
7828 (aset org-olpa i nil))
7829 (prog1
7830 (delq nil (append org-olpa nil))
7831 (aset org-olpa level heading)))
7832 (let (rtn)
7833 (save-excursion
7834 (while (org-up-heading-safe)
7835 (when (looking-at org-complex-heading-regexp)
7836 (push (org-match-string-no-properties 4) rtn)))
7837 rtn))))
7839 (defvar org-refile-history nil
7840 "History for refiling operations.")
7842 (defun org-refile (&optional goto default-buffer)
7843 "Move the entry at point to another heading.
7844 The list of target headings is compiled using the information in
7845 `org-refile-targets', which see. This list is created before each use
7846 and will therefore always be up-to-date.
7848 At the target location, the entry is filed as a subitem of the target heading.
7849 Depending on `org-reverse-note-order', the new subitem will either be the
7850 first or the last subitem.
7852 If there is an active region, all entries in that region will be moved.
7853 However, the region must fulfil the requirement that the first heading
7854 is the first one sets the top-level of the moved text - at most siblings
7855 below it are allowed.
7857 With prefix arg GOTO, the command will only visit the target location,
7858 not actually move anything.
7859 With a double prefix `C-u C-u', go to the location where the last refiling
7860 operation has put the subtree."
7861 (interactive "P")
7862 (let* ((cbuf (current-buffer))
7863 (regionp (org-region-active-p))
7864 (region-start (and regionp (region-beginning)))
7865 (region-end (and regionp (region-end)))
7866 (region-length (and regionp (- region-end region-start)))
7867 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7868 pos it nbuf file re level reversed)
7869 (when regionp (goto-char region-start)
7870 (unless (org-kill-is-subtree-p
7871 (buffer-substring region-start region-end))
7872 (error "The region is not a (sequence of) subtree(s)")))
7873 (if (equal goto '(16))
7874 (org-refile-goto-last-stored)
7875 (when (setq it (org-refile-get-location
7876 (if goto "Goto: " "Refile to: ") default-buffer))
7877 (setq file (nth 1 it)
7878 re (nth 2 it)
7879 pos (nth 3 it))
7880 (if (and (equal (buffer-file-name) file)
7881 (if regionp
7882 (and (>= pos region-start)
7883 (<= pos region-end))
7884 (and (>= pos (point))
7885 (< pos (save-excursion
7886 (org-end-of-subtree t t))))))
7887 (error "Cannot refile to position inside the tree or region"))
7889 (setq nbuf (or (find-buffer-visiting file)
7890 (find-file-noselect file)))
7891 (if goto
7892 (progn
7893 (switch-to-buffer nbuf)
7894 (goto-char pos)
7895 (org-show-context 'org-goto))
7896 (if regionp
7897 (progn
7898 (kill-new (buffer-substring region-start region-end))
7899 (org-save-markers-in-region region-start region-end))
7900 (org-copy-subtree 1 nil t))
7901 (save-excursion
7902 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7903 (find-file-noselect file))))
7904 (setq reversed (org-notes-order-reversed-p))
7905 (save-excursion
7906 (save-restriction
7907 (widen)
7908 (goto-char pos)
7909 (looking-at outline-regexp)
7910 (setq level (org-get-valid-level (funcall outline-level) 1))
7911 (goto-char
7912 (if reversed
7913 (or (outline-next-heading) (point-max))
7914 (or (save-excursion (outline-get-next-sibling))
7915 (org-end-of-subtree t t)
7916 (point-max))))
7917 (if (not (bolp)) (newline))
7918 (bookmark-set "org-refile-last-stored")
7919 (org-paste-subtree level))))
7920 (if regionp
7921 (delete-region (point) (+ (point) region-length))
7922 (org-cut-subtree))
7923 (setq org-markers-to-move nil)
7924 (message "Refiled to \"%s\"" (car it)))))))
7926 (defun org-refile-goto-last-stored ()
7927 "Go to the location where the last refile was stored."
7928 (interactive)
7929 (bookmark-jump "org-refile-last-stored")
7930 (message "This is the location of the last refile"))
7932 (defun org-refile-get-location (&optional prompt default-buffer)
7933 "Prompt the user for a refile location, using PROMPT."
7934 (let ((org-refile-targets org-refile-targets)
7935 (org-refile-use-outline-path org-refile-use-outline-path))
7936 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7937 (unless org-refile-target-table
7938 (error "No refile targets"))
7939 (let* ((cbuf (current-buffer))
7940 (cfn (buffer-file-name (buffer-base-buffer cbuf)))
7941 (cfunc (if (and org-refile-use-outline-path
7942 org-outline-path-complete-in-steps)
7943 'org-olpath-completing-read
7944 'org-ido-completing-read))
7945 (extra (if org-refile-use-outline-path "/" ""))
7946 (filename (and cfn (expand-file-name cfn)))
7947 (tbl (mapcar
7948 (lambda (x)
7949 (if (not (equal filename (nth 1 x)))
7950 (cons (concat (car x) extra " ("
7951 (file-name-nondirectory (nth 1 x)) ")")
7952 (cdr x))
7953 (cons (concat (car x) extra) (cdr x))))
7954 org-refile-target-table))
7955 (completion-ignore-case t))
7956 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7957 tbl)))
7959 (defun org-olpath-completing-read (prompt collection &rest args)
7960 "Read an outline path like a file name."
7961 (let ((thetable collection))
7962 (apply
7963 'org-ido-completing-read prompt
7964 (lambda (string predicate &optional flag)
7965 (let (rtn r f (l (length string)))
7966 (cond
7967 ((eq flag nil)
7968 ;; try completion
7969 (try-completion string thetable))
7970 ((eq flag t)
7971 ;; all-completions
7972 (setq rtn (all-completions string thetable predicate))
7973 (mapcar
7974 (lambda (x)
7975 (setq r (substring x l))
7976 (if (string-match " ([^)]*)$" x)
7977 (setq f (match-string 0 x))
7978 (setq f ""))
7979 (if (string-match "/" r)
7980 (concat string (substring r 0 (match-end 0)) f)
7982 rtn))
7983 ((eq flag 'lambda)
7984 ;; exact match?
7985 (assoc string thetable)))
7987 args)))
7989 ;;;; Dynamic blocks
7991 (defun org-find-dblock (name)
7992 "Find the first dynamic block with name NAME in the buffer.
7993 If not found, stay at current position and return nil."
7994 (let (pos)
7995 (save-excursion
7996 (goto-char (point-min))
7997 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7998 nil t)
7999 (match-beginning 0))))
8000 (if pos (goto-char pos))
8001 pos))
8003 (defconst org-dblock-start-re
8004 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
8005 "Matches the startline of a dynamic block, with parameters.")
8007 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
8008 "Matches the end of a dynamic block.")
8010 (defun org-create-dblock (plist)
8011 "Create a dynamic block section, with parameters taken from PLIST.
8012 PLIST must contain a :name entry which is used as name of the block."
8013 (unless (bolp) (newline))
8014 (let ((name (plist-get plist :name)))
8015 (insert "#+BEGIN: " name)
8016 (while plist
8017 (if (eq (car plist) :name)
8018 (setq plist (cddr plist))
8019 (insert " " (prin1-to-string (pop plist)))))
8020 (insert "\n\n#+END:\n")
8021 (beginning-of-line -2)))
8023 (defun org-prepare-dblock ()
8024 "Prepare dynamic block for refresh.
8025 This empties the block, puts the cursor at the insert position and returns
8026 the property list including an extra property :name with the block name."
8027 (unless (looking-at org-dblock-start-re)
8028 (error "Not at a dynamic block"))
8029 (let* ((begdel (1+ (match-end 0)))
8030 (name (org-no-properties (match-string 1)))
8031 (params (append (list :name name)
8032 (read (concat "(" (match-string 3) ")")))))
8033 (unless (re-search-forward org-dblock-end-re nil t)
8034 (error "Dynamic block not terminated"))
8035 (setq params
8036 (append params
8037 (list :content (buffer-substring
8038 begdel (match-beginning 0)))))
8039 (delete-region begdel (match-beginning 0))
8040 (goto-char begdel)
8041 (open-line 1)
8042 params))
8044 (defun org-map-dblocks (&optional command)
8045 "Apply COMMAND to all dynamic blocks in the current buffer.
8046 If COMMAND is not given, use `org-update-dblock'."
8047 (let ((cmd (or command 'org-update-dblock))
8048 pos)
8049 (save-excursion
8050 (goto-char (point-min))
8051 (while (re-search-forward org-dblock-start-re nil t)
8052 (goto-char (setq pos (match-beginning 0)))
8053 (condition-case nil
8054 (funcall cmd)
8055 (error (message "Error during update of dynamic block")))
8056 (goto-char pos)
8057 (unless (re-search-forward org-dblock-end-re nil t)
8058 (error "Dynamic block not terminated"))))))
8060 (defun org-dblock-update (&optional arg)
8061 "User command for updating dynamic blocks.
8062 Update the dynamic block at point. With prefix ARG, update all dynamic
8063 blocks in the buffer."
8064 (interactive "P")
8065 (if arg
8066 (org-update-all-dblocks)
8067 (or (looking-at org-dblock-start-re)
8068 (org-beginning-of-dblock))
8069 (org-update-dblock)))
8071 (defun org-update-dblock ()
8072 "Update the dynamic block at point
8073 This means to empty the block, parse for parameters and then call
8074 the correct writing function."
8075 (save-window-excursion
8076 (let* ((pos (point))
8077 (line (org-current-line))
8078 (params (org-prepare-dblock))
8079 (name (plist-get params :name))
8080 (cmd (intern (concat "org-dblock-write:" name))))
8081 (message "Updating dynamic block `%s' at line %d..." name line)
8082 (funcall cmd params)
8083 (message "Updating dynamic block `%s' at line %d...done" name line)
8084 (goto-char pos))))
8086 (defun org-beginning-of-dblock ()
8087 "Find the beginning of the dynamic block at point.
8088 Error if there is no such block at point."
8089 (let ((pos (point))
8090 beg)
8091 (end-of-line 1)
8092 (if (and (re-search-backward org-dblock-start-re nil t)
8093 (setq beg (match-beginning 0))
8094 (re-search-forward org-dblock-end-re nil t)
8095 (> (match-end 0) pos))
8096 (goto-char beg)
8097 (goto-char pos)
8098 (error "Not in a dynamic block"))))
8100 (defun org-update-all-dblocks ()
8101 "Update all dynamic blocks in the buffer.
8102 This function can be used in a hook."
8103 (when (org-mode-p)
8104 (org-map-dblocks 'org-update-dblock)))
8107 ;;;; Completion
8109 (defconst org-additional-option-like-keywords
8110 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8111 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8112 "BEGIN_EXAMPLE" "END_EXAMPLE"
8113 "BEGIN_QUOTE" "END_QUOTE"
8114 "BEGIN_VERSE" "END_VERSE"
8115 "BEGIN_SRC" "END_SRC"
8116 "CAPTION" "LABEL" "ATTR_HTML" "ATTR_LaTeX"))
8118 (defcustom org-structure-template-alist
8120 ("s" "#+begin_src ?\n\n#+end_src"
8121 "<src lang=\"?\">\n\n</src>")
8122 ("e" "#+begin_example\n?\n#+end_example"
8123 "<example>\n?\n</example>")
8124 ("q" "#+begin_quote\n?\n#+end_quote"
8125 "<quote>\n?\n</quote>")
8126 ("v" "#+begin_verse\n?\n#+end_verse"
8127 "<verse>\n?\n/verse>")
8128 ("l" "#+begin_latex\n?\n#+end_latex"
8129 "<literal style=\"latex\">\n?\n</literal>")
8130 ("L" "#+latex: "
8131 "<literal style=\"latex\">?</literal>")
8132 ("h" "#+begin_html\n?\n#+end_html"
8133 "<literal style=\"html\">\n?\n</literal>")
8134 ("H" "#+html: "
8135 "<literal style=\"html\">?</literal>")
8136 ("a" "#+begin_ascii\n?\n#+end_ascii")
8137 ("A" "#+ascii: ")
8138 ("i" "#+include %file ?"
8139 "<include file=%file markup=\"?\">")
8141 "Structure completion elements.
8142 This is a list of abbreviation keys and values. The value gets inserted
8143 it you type @samp{.} followed by the key and then the completion key,
8144 usually `M-TAB'. %file will be replaced by a file name after prompting
8145 for the file using completion.
8146 There are two templates for each key, the first uses the original Org syntax,
8147 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8148 the default when the /org-mtags.el/ module has been loaded. See also the
8149 variable `org-mtags-prefer-muse-templates'.
8150 This is an experimental feature, it is undecided if it is going to stay in."
8151 :group 'org-completion
8152 :type '(repeat
8153 (string :tag "Key")
8154 (string :tag "Template")
8155 (string :tag "Muse Template")))
8157 (defun org-try-structure-completion ()
8158 "Try to complete a structure template before point.
8159 This looks for strings like \"<e\" on an otherwise empty line and
8160 expands them."
8161 (let ((l (buffer-substring (point-at-bol) (point)))
8163 (when (and (looking-at "[ \t]*$")
8164 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8165 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8166 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8167 (match-beginning 1)) a)
8168 t)))
8170 (defun org-complete-expand-structure-template (start cell)
8171 "Expand a structure template."
8172 (let* ((musep (org-bound-and-true-p org-mtags-prefer-muse-templates))
8173 (rpl (nth (if musep 2 1) cell)))
8174 (delete-region start (point))
8175 (when (string-match "\\`#\\+" rpl)
8176 (cond
8177 ((bolp))
8178 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8179 (delete-region (point-at-bol) (point)))
8180 (t (newline))))
8181 (setq start (point))
8182 (if (string-match "%file" rpl)
8183 (setq rpl (replace-match
8184 (concat
8185 "\""
8186 (save-match-data
8187 (abbreviate-file-name (read-file-name "Include file: ")))
8188 "\"")
8189 t t rpl)))
8190 (insert rpl)
8191 (if (re-search-backward "\\?" start t) (delete-char 1))))
8194 (defun org-complete (&optional arg)
8195 "Perform completion on word at point.
8196 At the beginning of a headline, this completes TODO keywords as given in
8197 `org-todo-keywords'.
8198 If the current word is preceded by a backslash, completes the TeX symbols
8199 that are supported for HTML support.
8200 If the current word is preceded by \"#+\", completes special words for
8201 setting file options.
8202 In the line after \"#+STARTUP:, complete valid keywords.\"
8203 At all other locations, this simply calls the value of
8204 `org-completion-fallback-command'."
8205 (interactive "P")
8206 (org-without-partial-completion
8207 (catch 'exit
8208 (let* ((a nil)
8209 (end (point))
8210 (beg1 (save-excursion
8211 (skip-chars-backward (org-re "[:alnum:]_@"))
8212 (point)))
8213 (beg (save-excursion
8214 (skip-chars-backward "a-zA-Z0-9_:$")
8215 (point)))
8216 (confirm (lambda (x) (stringp (car x))))
8217 (searchhead (equal (char-before beg) ?*))
8218 (struct
8219 (when (and (member (char-before beg1) '(?. ?<))
8220 (setq a (assoc (buffer-substring beg1 (point))
8221 org-structure-template-alist)))
8222 (org-complete-expand-structure-template (1- beg1) a)
8223 (throw 'exit t)))
8224 (tag (and (equal (char-before beg1) ?:)
8225 (equal (char-after (point-at-bol)) ?*)))
8226 (prop (and (equal (char-before beg1) ?:)
8227 (not (equal (char-after (point-at-bol)) ?*))))
8228 (texp (equal (char-before beg) ?\\))
8229 (link (equal (char-before beg) ?\[))
8230 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8231 beg)
8232 "#+"))
8233 (startup (string-match "^#\\+STARTUP:.*"
8234 (buffer-substring (point-at-bol) (point))))
8235 (completion-ignore-case opt)
8236 (type nil)
8237 (tbl nil)
8238 (table (cond
8239 (opt
8240 (setq type :opt)
8241 (require 'org-exp)
8242 (append
8243 (mapcar
8244 (lambda (x)
8245 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8246 (cons (match-string 2 x) (match-string 1 x)))
8247 (org-split-string (org-get-current-options) "\n"))
8248 (mapcar 'list org-additional-option-like-keywords)))
8249 (startup
8250 (setq type :startup)
8251 org-startup-options)
8252 (link (append org-link-abbrev-alist-local
8253 org-link-abbrev-alist))
8254 (texp
8255 (setq type :tex)
8256 org-html-entities)
8257 ((string-match "\\`\\*+[ \t]+\\'"
8258 (buffer-substring (point-at-bol) beg))
8259 (setq type :todo)
8260 (mapcar 'list org-todo-keywords-1))
8261 (searchhead
8262 (setq type :searchhead)
8263 (save-excursion
8264 (goto-char (point-min))
8265 (while (re-search-forward org-todo-line-regexp nil t)
8266 (push (list
8267 (org-make-org-heading-search-string
8268 (match-string 3) t))
8269 tbl)))
8270 tbl)
8271 (tag (setq type :tag beg beg1)
8272 (or org-tag-alist (org-get-buffer-tags)))
8273 (prop (setq type :prop beg beg1)
8274 (mapcar 'list (org-buffer-property-keys nil t t)))
8275 (t (progn
8276 (call-interactively org-completion-fallback-command)
8277 (throw 'exit nil)))))
8278 (pattern (buffer-substring-no-properties beg end))
8279 (completion (try-completion pattern table confirm)))
8280 (cond ((eq completion t)
8281 (if (not (assoc (upcase pattern) table))
8282 (message "Already complete")
8283 (if (and (equal type :opt)
8284 (not (member (car (assoc (upcase pattern) table))
8285 org-additional-option-like-keywords)))
8286 (insert (substring (cdr (assoc (upcase pattern) table))
8287 (length pattern)))
8288 (if (memq type '(:tag :prop)) (insert ":")))))
8289 ((null completion)
8290 (message "Can't find completion for \"%s\"" pattern)
8291 (ding))
8292 ((not (string= pattern completion))
8293 (delete-region beg end)
8294 (if (string-match " +$" completion)
8295 (setq completion (replace-match "" t t completion)))
8296 (insert completion)
8297 (if (get-buffer-window "*Completions*")
8298 (delete-window (get-buffer-window "*Completions*")))
8299 (if (assoc completion table)
8300 (if (eq type :todo) (insert " ")
8301 (if (memq type '(:tag :prop)) (insert ":"))))
8302 (if (and (equal type :opt) (assoc completion table))
8303 (message "%s" (substitute-command-keys
8304 "Press \\[org-complete] again to insert example settings"))))
8306 (message "Making completion list...")
8307 (let ((list (sort (all-completions pattern table confirm)
8308 'string<)))
8309 (with-output-to-temp-buffer "*Completions*"
8310 (condition-case nil
8311 ;; Protection needed for XEmacs and emacs 21
8312 (display-completion-list list pattern)
8313 (error (display-completion-list list)))))
8314 (message "Making completion list...%s" "done")))))))
8316 ;;;; TODO, DEADLINE, Comments
8318 (defun org-toggle-comment ()
8319 "Change the COMMENT state of an entry."
8320 (interactive)
8321 (save-excursion
8322 (org-back-to-heading)
8323 (let (case-fold-search)
8324 (if (looking-at (concat outline-regexp
8325 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8326 (replace-match "" t t nil 1)
8327 (if (looking-at outline-regexp)
8328 (progn
8329 (goto-char (match-end 0))
8330 (insert org-comment-string " ")))))))
8332 (defvar org-last-todo-state-is-todo nil
8333 "This is non-nil when the last TODO state change led to a TODO state.
8334 If the last change removed the TODO tag or switched to DONE, then
8335 this is nil.")
8337 (defvar org-setting-tags nil) ; dynamically skipped
8339 (defun org-parse-local-options (string var)
8340 "Parse STRING for startup setting relevant for variable VAR."
8341 (let ((rtn (symbol-value var))
8342 e opts)
8343 (save-match-data
8344 (if (or (not string) (not (string-match "\\S-" string)))
8346 (setq opts (delq nil (mapcar (lambda (x)
8347 (setq e (assoc x org-startup-options))
8348 (if (eq (nth 1 e) var) e nil))
8349 (org-split-string string "[ \t]+"))))
8350 (if (not opts)
8352 (setq rtn nil)
8353 (while (setq e (pop opts))
8354 (if (not (nth 3 e))
8355 (setq rtn (nth 2 e))
8356 (if (not (listp rtn)) (setq rtn nil))
8357 (push (nth 2 e) rtn)))
8358 rtn)))))
8360 (defvar org-agenda-headline-snapshot-before-repeat)
8361 (defun org-todo (&optional arg)
8362 "Change the TODO state of an item.
8363 The state of an item is given by a keyword at the start of the heading,
8364 like
8365 *** TODO Write paper
8366 *** DONE Call mom
8368 The different keywords are specified in the variable `org-todo-keywords'.
8369 By default the available states are \"TODO\" and \"DONE\".
8370 So for this example: when the item starts with TODO, it is changed to DONE.
8371 When it starts with DONE, the DONE is removed. And when neither TODO nor
8372 DONE are present, add TODO at the beginning of the heading.
8374 With C-u prefix arg, use completion to determine the new state.
8375 With numeric prefix arg, switch to that state.
8376 With a double C-u prefix, switch to the next set of TODO keywords (nextset).
8377 With a tripple C-u prefix, circumvent any state blocking.
8379 For calling through lisp, arg is also interpreted in the following way:
8380 'none -> empty state
8381 \"\"(empty string) -> switch to empty state
8382 'done -> switch to DONE
8383 'nextset -> switch to the next set of keywords
8384 'previousset -> switch to the previous set of keywords
8385 \"WAITING\" -> switch to the specified keyword, but only if it
8386 really is a member of `org-todo-keywords'."
8387 (interactive "P")
8388 (if (equal arg '(16)) (setq arg 'nextset))
8389 (let ((org-blocker-hook org-blocker-hook))
8390 (when (equal arg '(64))
8391 (setq arg nil org-blocker-hook nil))
8392 (save-excursion
8393 (catch 'exit
8394 (org-back-to-heading)
8395 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8396 (or (looking-at (concat " +" org-todo-regexp " *"))
8397 (looking-at " *"))
8398 (let* ((match-data (match-data))
8399 (startpos (point-at-bol))
8400 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8401 (org-log-done org-log-done)
8402 (org-log-repeat org-log-repeat)
8403 (org-todo-log-states org-todo-log-states)
8404 (this (match-string 1))
8405 (hl-pos (match-beginning 0))
8406 (head (org-get-todo-sequence-head this))
8407 (ass (assoc head org-todo-kwd-alist))
8408 (interpret (nth 1 ass))
8409 (done-word (nth 3 ass))
8410 (final-done-word (nth 4 ass))
8411 (last-state (or this ""))
8412 (completion-ignore-case t)
8413 (member (member this org-todo-keywords-1))
8414 (tail (cdr member))
8415 (state (cond
8416 ((and org-todo-key-trigger
8417 (or (and (equal arg '(4))
8418 (eq org-use-fast-todo-selection 'prefix))
8419 (and (not arg) org-use-fast-todo-selection
8420 (not (eq org-use-fast-todo-selection
8421 'prefix)))))
8422 ;; Use fast selection
8423 (org-fast-todo-selection))
8424 ((and (equal arg '(4))
8425 (or (not org-use-fast-todo-selection)
8426 (not org-todo-key-trigger)))
8427 ;; Read a state with completion
8428 (org-ido-completing-read
8429 "State: " (mapcar (lambda(x) (list x))
8430 org-todo-keywords-1)
8431 nil t))
8432 ((eq arg 'right)
8433 (if this
8434 (if tail (car tail) nil)
8435 (car org-todo-keywords-1)))
8436 ((eq arg 'left)
8437 (if (equal member org-todo-keywords-1)
8439 (if this
8440 (nth (- (length org-todo-keywords-1)
8441 (length tail) 2)
8442 org-todo-keywords-1)
8443 (org-last org-todo-keywords-1))))
8444 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8445 (setq arg nil))) ; hack to fall back to cycling
8446 (arg
8447 ;; user or caller requests a specific state
8448 (cond
8449 ((equal arg "") nil)
8450 ((eq arg 'none) nil)
8451 ((eq arg 'done) (or done-word (car org-done-keywords)))
8452 ((eq arg 'nextset)
8453 (or (car (cdr (member head org-todo-heads)))
8454 (car org-todo-heads)))
8455 ((eq arg 'previousset)
8456 (let ((org-todo-heads (reverse org-todo-heads)))
8457 (or (car (cdr (member head org-todo-heads)))
8458 (car org-todo-heads))))
8459 ((car (member arg org-todo-keywords-1)))
8460 ((nth (1- (prefix-numeric-value arg))
8461 org-todo-keywords-1))))
8462 ((null member) (or head (car org-todo-keywords-1)))
8463 ((equal this final-done-word) nil) ;; -> make empty
8464 ((null tail) nil) ;; -> first entry
8465 ((eq interpret 'sequence)
8466 (car tail))
8467 ((memq interpret '(type priority))
8468 (if (eq this-command last-command)
8469 (car tail)
8470 (if (> (length tail) 0)
8471 (or done-word (car org-done-keywords))
8472 nil)))
8473 (t nil)))
8474 (next (if state (concat " " state " ") " "))
8475 (change-plist (list :type 'todo-state-change :from this :to state
8476 :position startpos))
8477 dolog now-done-p)
8478 (when org-blocker-hook
8479 (setq org-last-todo-state-is-todo
8480 (not (member this org-done-keywords)))
8481 (unless (save-excursion
8482 (save-match-data
8483 (run-hook-with-args-until-failure
8484 'org-blocker-hook change-plist)))
8485 (if (interactive-p)
8486 (error "TODO state change from %s to %s blocked" this state)
8487 ;; fail silently
8488 (message "TODO state change from %s to %s blocked" this state)
8489 (throw 'exit nil))))
8490 (store-match-data match-data)
8491 (replace-match next t t)
8492 (unless (pos-visible-in-window-p hl-pos)
8493 (message "TODO state changed to %s" (org-trim next)))
8494 (unless head
8495 (setq head (org-get-todo-sequence-head state)
8496 ass (assoc head org-todo-kwd-alist)
8497 interpret (nth 1 ass)
8498 done-word (nth 3 ass)
8499 final-done-word (nth 4 ass)))
8500 (when (memq arg '(nextset previousset))
8501 (message "Keyword-Set %d/%d: %s"
8502 (- (length org-todo-sets) -1
8503 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8504 (length org-todo-sets)
8505 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8506 (setq org-last-todo-state-is-todo
8507 (not (member state org-done-keywords)))
8508 (setq now-done-p (and (member state org-done-keywords)
8509 (not (member this org-done-keywords))))
8510 (and logging (org-local-logging logging))
8511 (when (and (or org-todo-log-states org-log-done)
8512 (not (memq arg '(nextset previousset))))
8513 ;; we need to look at recording a time and note
8514 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8515 (nth 2 (assoc this org-todo-log-states))))
8516 (when (and state
8517 (member state org-not-done-keywords)
8518 (not (member this org-not-done-keywords)))
8519 ;; This is now a todo state and was not one before
8520 ;; If there was a CLOSED time stamp, get rid of it.
8521 (org-add-planning-info nil nil 'closed))
8522 (when (and now-done-p org-log-done)
8523 ;; It is now done, and it was not done before
8524 (org-add-planning-info 'closed (org-current-time))
8525 (if (and (not dolog) (eq 'note org-log-done))
8526 (org-add-log-setup 'done state 'findpos 'note)))
8527 (when (and state dolog)
8528 ;; This is a non-nil state, and we need to log it
8529 (org-add-log-setup 'state state 'findpos dolog)))
8530 ;; Fixup tag positioning
8531 (org-todo-trigger-tag-changes state)
8532 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8533 (when org-provide-todo-statistics
8534 (org-update-parent-todo-statistics))
8535 (run-hooks 'org-after-todo-state-change-hook)
8536 (if (and arg (not (member state org-done-keywords)))
8537 (setq head (org-get-todo-sequence-head state)))
8538 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8539 ;; Do we need to trigger a repeat?
8540 (when now-done-p
8541 (when (boundp 'org-agenda-headline-snapshot-before-repeat)
8542 ;; This is for the agenda, take a snapshot of the headline.
8543 (save-match-data
8544 (setq org-agenda-headline-snapshot-before-repeat
8545 (org-get-heading))))
8546 (org-auto-repeat-maybe state))
8547 ;; Fixup cursor location if close to the keyword
8548 (if (and (outline-on-heading-p)
8549 (not (bolp))
8550 (save-excursion (beginning-of-line 1)
8551 (looking-at org-todo-line-regexp))
8552 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8553 (progn
8554 (goto-char (or (match-end 2) (match-end 1)))
8555 (just-one-space)))
8556 (when org-trigger-hook
8557 (save-excursion
8558 (run-hook-with-args 'org-trigger-hook change-plist))))))))
8560 (defun org-block-todo-from-children-or-siblings (change-plist)
8561 "Block turning an entry into a TODO, using the hierarchy.
8562 This checks whether the current task should be blocked from state
8563 changes. Such blocking occurs when:
8565 1. The task has children which are not all in a completed state.
8567 2. A task has a parent with the property :ORDERED:, and there
8568 are siblings prior to the current task with incomplete
8569 status."
8570 (catch 'dont-block
8571 ;; If this is not a todo state change, or if this entry is already DONE,
8572 ;; do not block
8573 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8574 (member (plist-get change-plist :from)
8575 (cons 'done org-done-keywords))
8576 (member (plist-get change-plist :to)
8577 (cons 'todo org-not-done-keywords)))
8578 (throw 'dont-block t))
8579 ;; If this task has children, and any are undone, it's blocked
8580 (save-excursion
8581 (org-back-to-heading t)
8582 (let ((this-level (funcall outline-level)))
8583 (outline-next-heading)
8584 (let ((child-level (funcall outline-level)))
8585 (while (and (not (eobp))
8586 (> child-level this-level))
8587 ;; this todo has children, check whether they are all
8588 ;; completed
8589 (if (and (not (org-entry-is-done-p))
8590 (org-entry-is-todo-p))
8591 (throw 'dont-block nil))
8592 (outline-next-heading)
8593 (setq child-level (funcall outline-level))))))
8594 ;; Otherwise, if the task's parent has the :ORDERED: property, and
8595 ;; any previous siblings are undone, it's blocked
8596 (save-excursion
8597 (org-back-to-heading t)
8598 (when (save-excursion
8599 (ignore-errors
8600 (outline-up-heading 1)
8601 (org-entry-get (point) "ORDERED")))
8602 (let* ((this-level (funcall outline-level))
8603 (current-level this-level))
8604 (while (and (not (bobp))
8605 (= current-level this-level))
8606 (outline-previous-heading)
8607 (setq current-level (funcall outline-level))
8608 (if (= current-level this-level)
8609 ;; this todo has children, check whether they are all
8610 ;; completed
8611 (if (and (not (org-entry-is-done-p))
8612 (org-entry-is-todo-p))
8613 (throw 'dont-block nil)))))))
8614 t)) ; don't block
8616 (defun org-toggle-ordered-property ()
8617 "Toggle the ORDERED property of the current entry."
8618 (interactive)
8619 (save-excursion
8620 (org-back-to-heading)
8621 (if (org-entry-get nil "ORDERED")
8622 (progn
8623 (org-delete-property "ORDERED")
8624 (message "Subtasks can be completed in arbitrary order or parallel"))
8625 (org-entry-put nil "ORDERED" "t")
8626 (message "Subtasks must be completed in sequence"))))
8628 (defun org-block-todo-from-checkboxes (change-plist)
8629 "Block turning an entry into a TODO, using checkboxes.
8630 This checks whether the current task should be blocked from state
8631 changes because there are uncheckd boxes in this entry."
8632 (catch 'dont-block
8633 ;; If this is not a todo state change, or if this entry is already DONE,
8634 ;; do not block
8635 (when (or (not (eq (plist-get change-plist :type) 'todo-state-change))
8636 (member (plist-get change-plist :from)
8637 (cons 'done org-done-keywords))
8638 (member (plist-get change-plist :to)
8639 (cons 'todo org-not-done-keywords)))
8640 (throw 'dont-block t))
8641 ;; If this task has checkboxes that are not checked, it's blocked
8642 (save-excursion
8643 (org-back-to-heading t)
8644 (let ((beg (point)) end)
8645 (outline-next-heading)
8646 (setq end (point))
8647 (goto-char beg)
8648 (if (re-search-forward "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\)[ \t]+\\[[- ]\\]"
8649 end t)
8650 (throw 'dont-block nil))))
8651 t)) ; do not block
8653 (defun org-update-parent-todo-statistics ()
8654 "Update any statistics cookie in the parent of the current headline."
8655 (interactive)
8656 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8657 level (cnt-all 0) (cnt-done 0) is-percent kwd cookie-present)
8658 (catch 'exit
8659 (save-excursion
8660 (setq level (org-up-heading-safe))
8661 (unless level
8662 (throw 'exit nil))
8663 (while (re-search-forward box-re (point-at-eol) t)
8664 (setq cnt-all 0 cnt-done 0 cookie-present t)
8665 (setq is-percent (match-end 2))
8666 (save-match-data
8667 (unless (outline-next-heading) (throw 'exit nil))
8668 (while (looking-at org-todo-line-regexp)
8669 (setq kwd (match-string 2))
8670 (and kwd (setq cnt-all (1+ cnt-all)))
8671 (and (member kwd org-done-keywords)
8672 (setq cnt-done (1+ cnt-done)))
8673 (condition-case nil
8674 (org-forward-same-level 1)
8675 (error (end-of-line 1)))))
8676 (replace-match
8677 (if is-percent
8678 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8679 (format "[%d/%d]" cnt-done cnt-all))))
8680 (when cookie-present
8681 (run-hook-with-args 'org-after-todo-statistics-hook
8682 cnt-done (- cnt-all cnt-done)))))))
8684 (defvar org-after-todo-statistics-hook nil
8685 "Hook that is called after a TODO statistics cookie has been updated.
8686 Each function is called with two arguments: the number of not-done entries
8687 and the number of done entries.
8689 For example, the following function, when added to this hook, will switch
8690 an entry to DONE when all children are done, and back to TODO when new
8691 entries are set to a TODO status. Note that this hook is only called
8692 when there is a statistics cookie in the headline!
8694 (defun org-summary-todo (n-done n-not-done)
8695 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8696 (let (org-log-done org-log-states) ; turn off logging
8697 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8700 (defun org-todo-trigger-tag-changes (state)
8701 "Apply the changes defined in `org-todo-state-tags-triggers'."
8702 (let ((l org-todo-state-tags-triggers)
8703 changes)
8704 (when (or (not state) (equal state ""))
8705 (setq changes (append changes (cdr (assoc "" l)))))
8706 (when (and (stringp state) (> (length state) 0))
8707 (setq changes (append changes (cdr (assoc state l)))))
8708 (when (member state org-not-done-keywords)
8709 (setq changes (append changes (cdr (assoc 'todo l)))))
8710 (when (member state org-done-keywords)
8711 (setq changes (append changes (cdr (assoc 'done l)))))
8712 (dolist (c changes)
8713 (org-toggle-tag (car c) (if (cdr c) 'on 'off)))))
8715 (defun org-local-logging (value)
8716 "Get logging settings from a property VALUE."
8717 (let* (words w a)
8718 ;; directly set the variables, they are already local.
8719 (setq org-log-done nil
8720 org-log-repeat nil
8721 org-todo-log-states nil)
8722 (setq words (org-split-string value))
8723 (while (setq w (pop words))
8724 (cond
8725 ((setq a (assoc w org-startup-options))
8726 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8727 (set (nth 1 a) (nth 2 a))))
8728 ((setq a (org-extract-log-state-settings w))
8729 (and (member (car a) org-todo-keywords-1)
8730 (push a org-todo-log-states)))))))
8732 (defun org-get-todo-sequence-head (kwd)
8733 "Return the head of the TODO sequence to which KWD belongs.
8734 If KWD is not set, check if there is a text property remembering the
8735 right sequence."
8736 (let (p)
8737 (cond
8738 ((not kwd)
8739 (or (get-text-property (point-at-bol) 'org-todo-head)
8740 (progn
8741 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8742 nil (point-at-eol)))
8743 (get-text-property p 'org-todo-head))))
8744 ((not (member kwd org-todo-keywords-1))
8745 (car org-todo-keywords-1))
8746 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8748 (defun org-fast-todo-selection ()
8749 "Fast TODO keyword selection with single keys.
8750 Returns the new TODO keyword, or nil if no state change should occur."
8751 (let* ((fulltable org-todo-key-alist)
8752 (done-keywords org-done-keywords) ;; needed for the faces.
8753 (maxlen (apply 'max (mapcar
8754 (lambda (x)
8755 (if (stringp (car x)) (string-width (car x)) 0))
8756 fulltable)))
8757 (expert nil)
8758 (fwidth (+ maxlen 3 1 3))
8759 (ncol (/ (- (window-width) 4) fwidth))
8760 tg cnt e c tbl
8761 groups ingroup)
8762 (save-excursion
8763 (save-window-excursion
8764 (if expert
8765 (set-buffer (get-buffer-create " *Org todo*"))
8766 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8767 (erase-buffer)
8768 (org-set-local 'org-done-keywords done-keywords)
8769 (setq tbl fulltable cnt 0)
8770 (while (setq e (pop tbl))
8771 (cond
8772 ((equal e '(:startgroup))
8773 (push '() groups) (setq ingroup t)
8774 (when (not (= cnt 0))
8775 (setq cnt 0)
8776 (insert "\n"))
8777 (insert "{ "))
8778 ((equal e '(:endgroup))
8779 (setq ingroup nil cnt 0)
8780 (insert "}\n"))
8782 (setq tg (car e) c (cdr e))
8783 (if ingroup (push tg (car groups)))
8784 (setq tg (org-add-props tg nil 'face
8785 (org-get-todo-face tg)))
8786 (if (and (= cnt 0) (not ingroup)) (insert " "))
8787 (insert "[" c "] " tg (make-string
8788 (- fwidth 4 (length tg)) ?\ ))
8789 (when (= (setq cnt (1+ cnt)) ncol)
8790 (insert "\n")
8791 (if ingroup (insert " "))
8792 (setq cnt 0)))))
8793 (insert "\n")
8794 (goto-char (point-min))
8795 (if (not expert) (org-fit-window-to-buffer))
8796 (message "[a-z..]:Set [SPC]:clear")
8797 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8798 (cond
8799 ((or (= c ?\C-g)
8800 (and (= c ?q) (not (rassoc c fulltable))))
8801 (setq quit-flag t))
8802 ((= c ?\ ) nil)
8803 ((setq e (rassoc c fulltable) tg (car e))
8805 (t (setq quit-flag t)))))))
8807 (defun org-entry-is-todo-p ()
8808 (member (org-get-todo-state) org-not-done-keywords))
8810 (defun org-entry-is-done-p ()
8811 (member (org-get-todo-state) org-done-keywords))
8813 (defun org-get-todo-state ()
8814 (save-excursion
8815 (org-back-to-heading t)
8816 (and (looking-at org-todo-line-regexp)
8817 (match-end 2)
8818 (match-string 2))))
8820 (defun org-at-date-range-p (&optional inactive-ok)
8821 "Is the cursor inside a date range?"
8822 (interactive)
8823 (save-excursion
8824 (catch 'exit
8825 (let ((pos (point)))
8826 (skip-chars-backward "^[<\r\n")
8827 (skip-chars-backward "<[")
8828 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8829 (>= (match-end 0) pos)
8830 (throw 'exit t))
8831 (skip-chars-backward "^<[\r\n")
8832 (skip-chars-backward "<[")
8833 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8834 (>= (match-end 0) pos)
8835 (throw 'exit t)))
8836 nil)))
8838 (defun org-get-repeat ()
8839 "Check if there is a deadline/schedule with repeater in this entry."
8840 (save-match-data
8841 (save-excursion
8842 (org-back-to-heading t)
8843 (if (re-search-forward
8844 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8845 (match-string 1)))))
8847 (defvar org-last-changed-timestamp)
8848 (defvar org-last-inserted-timestamp)
8849 (defvar org-log-post-message)
8850 (defvar org-log-note-purpose)
8851 (defvar org-log-note-how)
8852 (defvar org-log-note-extra)
8853 (defun org-auto-repeat-maybe (done-word)
8854 "Check if the current headline contains a repeated deadline/schedule.
8855 If yes, set TODO state back to what it was and change the base date
8856 of repeating deadline/scheduled time stamps to new date.
8857 This function is run automatically after each state change to a DONE state."
8858 ;; last-state is dynamically scoped into this function
8859 (let* ((repeat (org-get-repeat))
8860 (aa (assoc last-state org-todo-kwd-alist))
8861 (interpret (nth 1 aa))
8862 (head (nth 2 aa))
8863 (whata '(("d" . day) ("m" . month) ("y" . year)))
8864 (msg "Entry repeats: ")
8865 (org-log-done nil)
8866 (org-todo-log-states nil)
8867 (nshiftmax 10) (nshift 0)
8868 re type n what ts time)
8869 (when repeat
8870 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8871 (org-todo (if (eq interpret 'type) last-state head))
8872 (when org-log-repeat
8873 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8874 (memq 'org-add-log-note post-command-hook))
8875 ;; OK, we are already setup for some record
8876 (if (eq org-log-repeat 'note)
8877 ;; make sure we take a note, not only a time stamp
8878 (setq org-log-note-how 'note))
8879 ;; Set up for taking a record
8880 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8881 'findpos org-log-repeat)))
8882 (org-back-to-heading t)
8883 (org-add-planning-info nil nil 'closed)
8884 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8885 org-deadline-time-regexp "\\)\\|\\("
8886 org-ts-regexp "\\)"))
8887 (while (re-search-forward
8888 re (save-excursion (outline-next-heading) (point)) t)
8889 (setq type (if (match-end 1) org-scheduled-string
8890 (if (match-end 3) org-deadline-string "Plain:"))
8891 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0))))
8892 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8893 (setq n (string-to-number (match-string 2 ts))
8894 what (match-string 3 ts))
8895 (if (equal what "w") (setq n (* n 7) what "d"))
8896 ;; Preparation, see if we need to modify the start date for the change
8897 (when (match-end 1)
8898 (setq time (save-match-data (org-time-string-to-time ts)))
8899 (cond
8900 ((equal (match-string 1 ts) ".")
8901 ;; Shift starting date to today
8902 (org-timestamp-change
8903 (- (time-to-days (current-time)) (time-to-days time))
8904 'day))
8905 ((equal (match-string 1 ts) "+")
8906 (while (or (= nshift 0)
8907 (<= (time-to-days time) (time-to-days (current-time))))
8908 (when (= (incf nshift) nshiftmax)
8909 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8910 (error "Abort")))
8911 (org-timestamp-change n (cdr (assoc what whata)))
8912 (org-at-timestamp-p t)
8913 (setq ts (match-string 1))
8914 (setq time (save-match-data (org-time-string-to-time ts))))
8915 (org-timestamp-change (- n) (cdr (assoc what whata)))
8916 ;; rematch, so that we have everything in place for the real shift
8917 (org-at-timestamp-p t)
8918 (setq ts (match-string 1))
8919 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8920 (org-timestamp-change n (cdr (assoc what whata)))
8921 (setq msg (concat msg type " " org-last-changed-timestamp " "))))
8922 (setq org-log-post-message msg)
8923 (message "%s" msg))))
8925 (defun org-show-todo-tree (arg)
8926 "Make a compact tree which shows all headlines marked with TODO.
8927 The tree will show the lines where the regexp matches, and all higher
8928 headlines above the match.
8929 With a \\[universal-argument] prefix, also show the DONE entries.
8930 With a numeric prefix N, construct a sparse tree for the Nth element
8931 of `org-todo-keywords-1'."
8932 (interactive "P")
8933 (let ((case-fold-search nil)
8934 (kwd-re
8935 (cond ((null arg) org-not-done-regexp)
8936 ((equal arg '(4))
8937 (let ((kwd (org-ido-completing-read "Keyword (or KWD1|KWD2|...): "
8938 (mapcar 'list org-todo-keywords-1))))
8939 (concat "\\("
8940 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8941 "\\)\\>")))
8942 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8943 (regexp-quote (nth (1- (prefix-numeric-value arg))
8944 org-todo-keywords-1)))
8945 (t (error "Invalid prefix argument: %s" arg)))))
8946 (message "%d TODO entries found"
8947 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8949 (defun org-deadline (&optional remove time)
8950 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8951 With argument REMOVE, remove any deadline from the item.
8952 When TIME is set, it should be an internal time specification, and the
8953 scheduling will use the corresponding date."
8954 (interactive "P")
8955 (if remove
8956 (progn
8957 (org-remove-timestamp-with-keyword org-deadline-string)
8958 (message "Item no longer has a deadline."))
8959 (if (org-get-repeat)
8960 (error "Cannot change deadline on task with repeater, please do that by hand")
8961 (org-add-planning-info 'deadline time 'closed)
8962 (message "Deadline on %s" org-last-inserted-timestamp))))
8964 (defun org-schedule (&optional remove time)
8965 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8966 With argument REMOVE, remove any scheduling date from the item.
8967 When TIME is set, it should be an internal time specification, and the
8968 scheduling will use the corresponding date."
8969 (interactive "P")
8970 (if remove
8971 (progn
8972 (org-remove-timestamp-with-keyword org-scheduled-string)
8973 (message "Item is no longer scheduled."))
8974 (if (org-get-repeat)
8975 (error "Cannot reschedule task with repeater, please do that by hand")
8976 (org-add-planning-info 'scheduled time 'closed)
8977 (message "Scheduled to %s" org-last-inserted-timestamp))))
8979 (defun org-get-scheduled-time (pom &optional inherit)
8980 "Get the scheduled time as a time tuple, of a format suitable
8981 for calling org-schedule with, or if there is no scheduling,
8982 returns nil."
8983 (let ((time (org-entry-get pom "SCHEDULED" inherit)))
8984 (when time
8985 (apply 'encode-time (org-parse-time-string time)))))
8987 (defun org-get-deadline-time (pom &optional inherit)
8988 "Get the deadine as a time tuple, of a format suitable for
8989 calling org-deadlin with, or if there is no scheduling, returns
8990 nil."
8991 (let ((time (org-entry-get pom "DEADLINE" inherit)))
8992 (when time
8993 (apply 'encode-time (org-parse-time-string time)))))
8995 (defun org-remove-timestamp-with-keyword (keyword)
8996 "Remove all time stamps with KEYWORD in the current entry."
8997 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8998 beg)
8999 (save-excursion
9000 (org-back-to-heading t)
9001 (setq beg (point))
9002 (org-end-of-subtree t t)
9003 (while (re-search-backward re beg t)
9004 (replace-match "")
9005 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
9006 (equal (char-before) ?\ ))
9007 (backward-delete-char 1)
9008 (if (string-match "^[ \t]*$" (buffer-substring
9009 (point-at-bol) (point-at-eol)))
9010 (delete-region (point-at-bol)
9011 (min (point-max) (1+ (point-at-eol))))))))))
9013 (defun org-add-planning-info (what &optional time &rest remove)
9014 "Insert new timestamp with keyword in the line directly after the headline.
9015 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
9016 If non is given, the user is prompted for a date.
9017 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
9018 be removed."
9019 (interactive)
9020 (let (org-time-was-given org-end-time-was-given ts
9021 end default-time default-input)
9023 (when (and (not time) (memq what '(scheduled deadline)))
9024 ;; Try to get a default date/time from existing timestamp
9025 (save-excursion
9026 (org-back-to-heading t)
9027 (setq end (save-excursion (outline-next-heading) (point)))
9028 (when (re-search-forward (if (eq what 'scheduled)
9029 org-scheduled-time-regexp
9030 org-deadline-time-regexp)
9031 end t)
9032 (setq ts (match-string 1)
9033 default-time
9034 (apply 'encode-time (org-parse-time-string ts))
9035 default-input (and ts (org-get-compact-tod ts))))))
9036 (when what
9037 ;; If necessary, get the time from the user
9038 (setq time (or time (org-read-date nil 'to-time nil nil
9039 default-time default-input))))
9041 (when (and org-insert-labeled-timestamps-at-point
9042 (member what '(scheduled deadline)))
9043 (insert
9044 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
9045 (org-insert-time-stamp time org-time-was-given
9046 nil nil nil (list org-end-time-was-given))
9047 (setq what nil))
9048 (save-excursion
9049 (save-restriction
9050 (let (col list elt ts buffer-invisibility-spec)
9051 (org-back-to-heading t)
9052 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
9053 (goto-char (match-end 1))
9054 (setq col (current-column))
9055 (goto-char (match-end 0))
9056 (if (eobp) (insert "\n") (forward-char 1))
9057 (if (and (not (looking-at outline-regexp))
9058 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
9059 "[^\r\n]*"))
9060 (not (equal (match-string 1) org-clock-string)))
9061 (narrow-to-region (match-beginning 0) (match-end 0))
9062 (insert-before-markers "\n")
9063 (backward-char 1)
9064 (narrow-to-region (point) (point))
9065 (and org-adapt-indentation (org-indent-to-column col)))
9066 ;; Check if we have to remove something.
9067 (setq list (cons what remove))
9068 (while list
9069 (setq elt (pop list))
9070 (goto-char (point-min))
9071 (when (or (and (eq elt 'scheduled)
9072 (re-search-forward org-scheduled-time-regexp nil t))
9073 (and (eq elt 'deadline)
9074 (re-search-forward org-deadline-time-regexp nil t))
9075 (and (eq elt 'closed)
9076 (re-search-forward org-closed-time-regexp nil t)))
9077 (replace-match "")
9078 (if (looking-at "--+<[^>]+>") (replace-match ""))
9079 (if (looking-at " +") (replace-match ""))))
9080 (goto-char (point-max))
9081 (when what
9082 (insert
9083 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
9084 (cond ((eq what 'scheduled) org-scheduled-string)
9085 ((eq what 'deadline) org-deadline-string)
9086 ((eq what 'closed) org-closed-string))
9087 " ")
9088 (setq ts (org-insert-time-stamp
9089 time
9090 (or org-time-was-given
9091 (and (eq what 'closed) org-log-done-with-time))
9092 (eq what 'closed)
9093 nil nil (list org-end-time-was-given)))
9094 (end-of-line 1))
9095 (goto-char (point-min))
9096 (widen)
9097 (if (and (looking-at "[ \t]+\n")
9098 (equal (char-before) ?\n))
9099 (delete-region (1- (point)) (point-at-eol)))
9100 ts)))))
9102 (defvar org-log-note-marker (make-marker))
9103 (defvar org-log-note-purpose nil)
9104 (defvar org-log-note-state nil)
9105 (defvar org-log-note-how nil)
9106 (defvar org-log-note-extra nil)
9107 (defvar org-log-note-window-configuration nil)
9108 (defvar org-log-note-return-to (make-marker))
9109 (defvar org-log-post-message nil
9110 "Message to be displayed after a log note has been stored.
9111 The auto-repeater uses this.")
9113 (defun org-add-note ()
9114 "Add a note to the current entry.
9115 This is done in the same way as adding a state change note."
9116 (interactive)
9117 (org-add-log-setup 'note nil 'findpos nil))
9119 (defvar org-property-end-re)
9120 (defun org-add-log-setup (&optional purpose state findpos how &optional extra)
9121 "Set up the post command hook to take a note.
9122 If this is about to TODO state change, the new state is expected in STATE.
9123 When FINDPOS is non-nil, find the correct position for the note in
9124 the current entry. If not, assume that it can be inserted at point.
9125 HOW is an indicator what kind of note should be created.
9126 EXTRA is additional text that will be inserted into the notes buffer."
9127 (save-restriction
9128 (save-excursion
9129 (when findpos
9130 (org-back-to-heading t)
9131 (narrow-to-region (point) (save-excursion
9132 (outline-next-heading) (point)))
9133 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
9134 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
9135 "[^\r\n]*\\)?"))
9136 (goto-char (match-end 0))
9137 (when (and org-log-state-notes-insert-after-drawers
9138 (save-excursion
9139 (forward-line) (looking-at org-drawer-regexp)))
9140 (progn (forward-line)
9141 (while (looking-at org-drawer-regexp)
9142 (goto-char (match-end 0))
9143 (re-search-forward org-property-end-re (point-max) t)
9144 (forward-line))
9145 (forward-line -1)))
9146 (unless org-log-states-order-reversed
9147 (and (= (char-after) ?\n) (forward-char 1))
9148 (org-skip-over-state-notes)
9149 (skip-chars-backward " \t\n\r")))
9150 (move-marker org-log-note-marker (point))
9151 (setq org-log-note-purpose purpose
9152 org-log-note-state state
9153 org-log-note-how how
9154 org-log-note-extra extra)
9155 (add-hook 'post-command-hook 'org-add-log-note 'append))))
9157 (defun org-skip-over-state-notes ()
9158 "Skip past the list of State notes in an entry."
9159 (if (looking-at "\n[ \t]*- State") (forward-char 1))
9160 (while (looking-at "[ \t]*- State")
9161 (condition-case nil
9162 (org-next-item)
9163 (error (org-end-of-item)))))
9165 (defun org-add-log-note (&optional purpose)
9166 "Pop up a window for taking a note, and add this note later at point."
9167 (remove-hook 'post-command-hook 'org-add-log-note)
9168 (setq org-log-note-window-configuration (current-window-configuration))
9169 (delete-other-windows)
9170 (move-marker org-log-note-return-to (point))
9171 (switch-to-buffer (marker-buffer org-log-note-marker))
9172 (goto-char org-log-note-marker)
9173 (org-switch-to-buffer-other-window "*Org Note*")
9174 (erase-buffer)
9175 (if (memq org-log-note-how '(time state))
9176 (let (current-prefix-arg) (org-store-log-note))
9177 (let ((org-inhibit-startup t)) (org-mode))
9178 (insert (format "# Insert note for %s.
9179 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
9180 (cond
9181 ((eq org-log-note-purpose 'clock-out) "stopped clock")
9182 ((eq org-log-note-purpose 'done) "closed todo item")
9183 ((eq org-log-note-purpose 'state)
9184 (format "state change to \"%s\"" org-log-note-state))
9185 ((eq org-log-note-purpose 'note)
9186 "this entry")
9187 (t (error "This should not happen")))))
9188 (if org-log-note-extra (insert org-log-note-extra))
9189 (org-set-local 'org-finish-function 'org-store-log-note)))
9191 (defvar org-note-abort nil) ; dynamically scoped
9192 (defun org-store-log-note ()
9193 "Finish taking a log note, and insert it to where it belongs."
9194 (let ((txt (buffer-string))
9195 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
9196 lines ind)
9197 (kill-buffer (current-buffer))
9198 (while (string-match "\\`#.*\n[ \t\n]*" txt)
9199 (setq txt (replace-match "" t t txt)))
9200 (if (string-match "\\s-+\\'" txt)
9201 (setq txt (replace-match "" t t txt)))
9202 (setq lines (org-split-string txt "\n"))
9203 (when (and note (string-match "\\S-" note))
9204 (setq note
9205 (org-replace-escapes
9206 note
9207 (list (cons "%u" (user-login-name))
9208 (cons "%U" user-full-name)
9209 (cons "%t" (format-time-string
9210 (org-time-stamp-format 'long 'inactive)
9211 (current-time)))
9212 (cons "%s" (if org-log-note-state
9213 (concat "\"" org-log-note-state "\"")
9214 "")))))
9215 (if lines (setq note (concat note " \\\\")))
9216 (push note lines))
9217 (when (or current-prefix-arg org-note-abort) (setq lines nil))
9218 (when lines
9219 (save-excursion
9220 (set-buffer (marker-buffer org-log-note-marker))
9221 (save-excursion
9222 (goto-char org-log-note-marker)
9223 (move-marker org-log-note-marker nil)
9224 (end-of-line 1)
9225 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
9226 (indent-relative nil)
9227 (insert "- " (pop lines))
9228 (org-indent-line-function)
9229 (beginning-of-line 1)
9230 (looking-at "[ \t]*")
9231 (setq ind (concat (match-string 0) " "))
9232 (end-of-line 1)
9233 (while lines (insert "\n" ind (pop lines)))))))
9234 (set-window-configuration org-log-note-window-configuration)
9235 (with-current-buffer (marker-buffer org-log-note-return-to)
9236 (goto-char org-log-note-return-to))
9237 (move-marker org-log-note-return-to nil)
9238 (and org-log-post-message (message "%s" org-log-post-message)))
9240 (defun org-sparse-tree (&optional arg)
9241 "Create a sparse tree, prompt for the details.
9242 This command can create sparse trees. You first need to select the type
9243 of match used to create the tree:
9245 t Show entries with a specific TODO keyword.
9246 T Show entries selected by a tags match.
9247 p Enter a property name and its value (both with completion on existing
9248 names/values) and show entries with that property.
9249 r Show entries matching a regular expression
9250 d Show deadlines due within `org-deadline-warning-days'."
9251 (interactive "P")
9252 (let (ans kwd value)
9253 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9254 (setq ans (read-char-exclusive))
9255 (cond
9256 ((equal ans ?d)
9257 (call-interactively 'org-check-deadlines))
9258 ((equal ans ?b)
9259 (call-interactively 'org-check-before-date))
9260 ((equal ans ?t)
9261 (org-show-todo-tree '(4)))
9262 ((equal ans ?T)
9263 (call-interactively 'org-tags-sparse-tree))
9264 ((member ans '(?p ?P))
9265 (setq kwd (org-ido-completing-read "Property: "
9266 (mapcar 'list (org-buffer-property-keys))))
9267 (setq value (org-ido-completing-read "Value: "
9268 (mapcar 'list (org-property-values kwd))))
9269 (unless (string-match "\\`{.*}\\'" value)
9270 (setq value (concat "\"" value "\"")))
9271 (org-tags-sparse-tree arg (concat kwd "=" value)))
9272 ((member ans '(?r ?R ?/))
9273 (call-interactively 'org-occur))
9274 (t (error "No such sparse tree command \"%c\"" ans)))))
9276 (defvar org-occur-highlights nil
9277 "List of overlays used for occur matches.")
9278 (make-variable-buffer-local 'org-occur-highlights)
9279 (defvar org-occur-parameters nil
9280 "Parameters of the active org-occur calls.
9281 This is a list, each call to org-occur pushes as cons cell,
9282 containing the regular expression and the callback, onto the list.
9283 The list can contain several entries if `org-occur' has been called
9284 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9285 will only contain one set of parameters. When the highlights are
9286 removed (for example with `C-c C-c', or with the next edit (depending
9287 on `org-remove-highlights-with-change'), this variable is emptied
9288 as well.")
9289 (make-variable-buffer-local 'org-occur-parameters)
9291 (defun org-occur (regexp &optional keep-previous callback)
9292 "Make a compact tree which shows all matches of REGEXP.
9293 The tree will show the lines where the regexp matches, and all higher
9294 headlines above the match. It will also show the heading after the match,
9295 to make sure editing the matching entry is easy.
9296 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9297 call to `org-occur' will be kept, to allow stacking of calls to this
9298 command.
9299 If CALLBACK is non-nil, it is a function which is called to confirm
9300 that the match should indeed be shown."
9301 (interactive "sRegexp: \nP")
9302 (unless keep-previous
9303 (org-remove-occur-highlights nil nil t))
9304 (push (cons regexp callback) org-occur-parameters)
9305 (let ((cnt 0))
9306 (save-excursion
9307 (goto-char (point-min))
9308 (if (or (not keep-previous) ; do not want to keep
9309 (not org-occur-highlights)) ; no previous matches
9310 ;; hide everything
9311 (org-overview))
9312 (while (re-search-forward regexp nil t)
9313 (when (or (not callback)
9314 (save-match-data (funcall callback)))
9315 (setq cnt (1+ cnt))
9316 (when org-highlight-sparse-tree-matches
9317 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9318 (org-show-context 'occur-tree))))
9319 (when org-remove-highlights-with-change
9320 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9321 nil 'local))
9322 (unless org-sparse-tree-open-archived-trees
9323 (org-hide-archived-subtrees (point-min) (point-max)))
9324 (run-hooks 'org-occur-hook)
9325 (if (interactive-p)
9326 (message "%d match(es) for regexp %s" cnt regexp))
9327 cnt))
9329 (defun org-show-context (&optional key)
9330 "Make sure point and context and visible.
9331 How much context is shown depends upon the variables
9332 `org-show-hierarchy-above', `org-show-following-heading'. and
9333 `org-show-siblings'."
9334 (let ((heading-p (org-on-heading-p t))
9335 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9336 (following-p (org-get-alist-option org-show-following-heading key))
9337 (entry-p (org-get-alist-option org-show-entry-below key))
9338 (siblings-p (org-get-alist-option org-show-siblings key)))
9339 (catch 'exit
9340 ;; Show heading or entry text
9341 (if (and heading-p (not entry-p))
9342 (org-flag-heading nil) ; only show the heading
9343 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9344 (org-show-hidden-entry))) ; show entire entry
9345 (when following-p
9346 ;; Show next sibling, or heading below text
9347 (save-excursion
9348 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9349 (org-flag-heading nil))))
9350 (when siblings-p (org-show-siblings))
9351 (when hierarchy-p
9352 ;; show all higher headings, possibly with siblings
9353 (save-excursion
9354 (while (and (condition-case nil
9355 (progn (org-up-heading-all 1) t)
9356 (error nil))
9357 (not (bobp)))
9358 (org-flag-heading nil)
9359 (when siblings-p (org-show-siblings))))))))
9361 (defun org-reveal (&optional siblings)
9362 "Show current entry, hierarchy above it, and the following headline.
9363 This can be used to show a consistent set of context around locations
9364 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9365 not t for the search context.
9367 With optional argument SIBLINGS, on each level of the hierarchy all
9368 siblings are shown. This repairs the tree structure to what it would
9369 look like when opened with hierarchical calls to `org-cycle'."
9370 (interactive "P")
9371 (let ((org-show-hierarchy-above t)
9372 (org-show-following-heading t)
9373 (org-show-siblings (if siblings t org-show-siblings)))
9374 (org-show-context nil)))
9376 (defun org-highlight-new-match (beg end)
9377 "Highlight from BEG to END and mark the highlight is an occur headline."
9378 (let ((ov (org-make-overlay beg end)))
9379 (org-overlay-put ov 'face 'secondary-selection)
9380 (push ov org-occur-highlights)))
9382 (defun org-remove-occur-highlights (&optional beg end noremove)
9383 "Remove the occur highlights from the buffer.
9384 BEG and END are ignored. If NOREMOVE is nil, remove this function
9385 from the `before-change-functions' in the current buffer."
9386 (interactive)
9387 (unless org-inhibit-highlight-removal
9388 (mapc 'org-delete-overlay org-occur-highlights)
9389 (setq org-occur-highlights nil)
9390 (setq org-occur-parameters nil)
9391 (unless noremove
9392 (remove-hook 'before-change-functions
9393 'org-remove-occur-highlights 'local))))
9395 ;;;; Priorities
9397 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9398 "Regular expression matching the priority indicator.")
9400 (defvar org-remove-priority-next-time nil)
9402 (defun org-priority-up ()
9403 "Increase the priority of the current item."
9404 (interactive)
9405 (org-priority 'up))
9407 (defun org-priority-down ()
9408 "Decrease the priority of the current item."
9409 (interactive)
9410 (org-priority 'down))
9412 (defun org-priority (&optional action)
9413 "Change the priority of an item by ARG.
9414 ACTION can be `set', `up', `down', or a character."
9415 (interactive)
9416 (setq action (or action 'set))
9417 (let (current new news have remove)
9418 (save-excursion
9419 (org-back-to-heading)
9420 (if (looking-at org-priority-regexp)
9421 (setq current (string-to-char (match-string 2))
9422 have t)
9423 (setq current org-default-priority))
9424 (cond
9425 ((or (eq action 'set)
9426 (if (featurep 'xemacs) (characterp action) (integerp action)))
9427 (if (not (eq action 'set))
9428 (setq new action)
9429 (message "Priority %c-%c, SPC to remove: "
9430 org-highest-priority org-lowest-priority)
9431 (setq new (read-char-exclusive)))
9432 (if (and (= (upcase org-highest-priority) org-highest-priority)
9433 (= (upcase org-lowest-priority) org-lowest-priority))
9434 (setq new (upcase new)))
9435 (cond ((equal new ?\ ) (setq remove t))
9436 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9437 (error "Priority must be between `%c' and `%c'"
9438 org-highest-priority org-lowest-priority))))
9439 ((eq action 'up)
9440 (if (and (not have) (eq last-command this-command))
9441 (setq new org-lowest-priority)
9442 (setq new (if (and org-priority-start-cycle-with-default (not have))
9443 org-default-priority (1- current)))))
9444 ((eq action 'down)
9445 (if (and (not have) (eq last-command this-command))
9446 (setq new org-highest-priority)
9447 (setq new (if (and org-priority-start-cycle-with-default (not have))
9448 org-default-priority (1+ current)))))
9449 (t (error "Invalid action")))
9450 (if (or (< (upcase new) org-highest-priority)
9451 (> (upcase new) org-lowest-priority))
9452 (setq remove t))
9453 (setq news (format "%c" new))
9454 (if have
9455 (if remove
9456 (replace-match "" t t nil 1)
9457 (replace-match news t t nil 2))
9458 (if remove
9459 (error "No priority cookie found in line")
9460 (looking-at org-todo-line-regexp)
9461 (if (match-end 2)
9462 (progn
9463 (goto-char (match-end 2))
9464 (insert " [#" news "]"))
9465 (goto-char (match-beginning 3))
9466 (insert "[#" news "] ")))))
9467 (org-preserve-lc (org-set-tags nil 'align))
9468 (if remove
9469 (message "Priority removed")
9470 (message "Priority of current item set to %s" news))))
9473 (defun org-get-priority (s)
9474 "Find priority cookie and return priority."
9475 (save-match-data
9476 (if (not (string-match org-priority-regexp s))
9477 (* 1000 (- org-lowest-priority org-default-priority))
9478 (* 1000 (- org-lowest-priority
9479 (string-to-char (match-string 2 s)))))))
9481 ;;;; Tags
9483 (defvar org-agenda-archives-mode)
9484 (defun org-scan-tags (action matcher &optional todo-only)
9485 "Scan headline tags with inheritance and produce output ACTION.
9487 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9488 or `agenda' to produce an entry list for an agenda view. It can also be
9489 a Lisp form or a function that should be called at each matched headline, in
9490 this case the return value is a list of all return values from these calls.
9492 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9493 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9494 only lines with a TODO keyword are included in the output."
9495 (require 'org-agenda)
9496 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9497 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9498 (org-re
9499 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9500 (props (list 'face 'default
9501 'done-face 'org-done
9502 'undone-face 'default
9503 'mouse-face 'highlight
9504 'org-not-done-regexp org-not-done-regexp
9505 'org-todo-regexp org-todo-regexp
9506 'keymap org-agenda-keymap
9507 'help-echo
9508 (format "mouse-2 or RET jump to org file %s"
9509 (abbreviate-file-name
9510 (or (buffer-file-name (buffer-base-buffer))
9511 (buffer-name (buffer-base-buffer)))))))
9512 (case-fold-search nil)
9513 lspos tags tags-list
9514 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9515 (llast 0) rtn rtn1 level category i txt
9516 todo marker entry priority)
9517 (when (not (or (member action '(agenda sparse-tree)) (functionp action)))
9518 (setq action (list 'lambda nil action)))
9519 (save-excursion
9520 (goto-char (point-min))
9521 (when (eq action 'sparse-tree)
9522 (org-overview)
9523 (org-remove-occur-highlights))
9524 (while (re-search-forward re nil t)
9525 (catch :skip
9526 (setq todo (if (match-end 1) (match-string 2))
9527 tags (if (match-end 4) (match-string 4)))
9528 (goto-char (setq lspos (1+ (match-beginning 0))))
9529 (setq level (org-reduced-level (funcall outline-level))
9530 category (org-get-category))
9531 (setq i llast llast level)
9532 ;; remove tag lists from same and sublevels
9533 (while (>= i level)
9534 (when (setq entry (assoc i tags-alist))
9535 (setq tags-alist (delete entry tags-alist)))
9536 (setq i (1- i)))
9537 ;; add the next tags
9538 (when tags
9539 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9540 tags-alist
9541 (cons (cons level tags) tags-alist)))
9542 ;; compile tags for current headline
9543 (setq tags-list
9544 (if org-use-tag-inheritance
9545 (apply 'append (mapcar 'cdr (reverse tags-alist)))
9546 tags))
9547 (when org-use-tag-inheritance
9548 (setcdr (car tags-alist)
9549 (mapcar (lambda (x)
9550 (setq x (copy-sequence x))
9551 (org-add-prop-inherited x))
9552 (cdar tags-alist))))
9553 (when (and tags org-use-tag-inheritance
9554 (not (eq t org-use-tag-inheritance)))
9555 ;; selective inheritance, remove uninherited ones
9556 (setcdr (car tags-alist)
9557 (org-remove-uniherited-tags (cdar tags-alist))))
9558 (when (and (or (not todo-only)
9559 (and (member todo org-not-done-keywords)
9560 (or (not org-agenda-tags-todo-honor-ignore-options)
9561 (not (org-agenda-check-for-timestamp-as-reason-to-ignore-todo-item)))))
9562 (let ((case-fold-search t)) (eval matcher))
9564 (not (member org-archive-tag tags-list))
9565 ;; we have an archive tag, should we use this anyway?
9566 (or (not org-agenda-skip-archived-trees)
9567 (and (eq action 'agenda) org-agenda-archives-mode))))
9568 (unless (eq action 'sparse-tree) (org-agenda-skip))
9570 ;; select this headline
9572 (cond
9573 ((eq action 'sparse-tree)
9574 (and org-highlight-sparse-tree-matches
9575 (org-get-heading) (match-end 0)
9576 (org-highlight-new-match
9577 (match-beginning 0) (match-beginning 1)))
9578 (org-show-context 'tags-tree))
9579 ((eq action 'agenda)
9580 (setq txt (org-format-agenda-item
9582 (concat
9583 (if org-tags-match-list-sublevels
9584 (make-string (1- level) ?.) "")
9585 (org-get-heading))
9586 category (org-get-tags-at))
9587 priority (org-get-priority txt))
9588 (goto-char lspos)
9589 (setq marker (org-agenda-new-marker))
9590 (org-add-props txt props
9591 'org-marker marker 'org-hd-marker marker 'org-category category
9592 'priority priority 'type "tagsmatch")
9593 (push txt rtn))
9594 ((functionp action)
9595 (save-excursion
9596 (setq rtn1 (funcall action))
9597 (push rtn1 rtn))
9598 (goto-char (point-at-eol)))
9599 (t (error "Invalid action")))
9601 ;; if we are to skip sublevels, jump to end of subtree
9602 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9603 (when (and (eq action 'sparse-tree)
9604 (not org-sparse-tree-open-archived-trees))
9605 (org-hide-archived-subtrees (point-min) (point-max)))
9606 (nreverse rtn)))
9608 (defun org-remove-uniherited-tags (tags)
9609 "Remove all tags that are not inherited from the list TAGS."
9610 (cond
9611 ((eq org-use-tag-inheritance t)
9612 (if org-tags-exclude-from-inheritance
9613 (org-delete-all org-tags-exclude-from-inheritance tags)
9614 tags))
9615 ((not org-use-tag-inheritance) nil)
9616 ((stringp org-use-tag-inheritance)
9617 (delq nil (mapcar
9618 (lambda (x)
9619 (if (and (string-match org-use-tag-inheritance x)
9620 (not (member x org-tags-exclude-from-inheritance)))
9621 x nil))
9622 tags)))
9623 ((listp org-use-tag-inheritance)
9624 (delq nil (mapcar
9625 (lambda (x)
9626 (if (member x org-use-tag-inheritance) x nil))
9627 tags)))))
9629 (defvar todo-only) ;; dynamically scoped
9631 (defun org-tags-sparse-tree (&optional todo-only match)
9632 "Create a sparse tree according to tags string MATCH.
9633 MATCH can contain positive and negative selection of tags, like
9634 \"+WORK+URGENT-WITHBOSS\".
9635 If optional argument TODO-ONLY is non-nil, only select lines that are
9636 also TODO lines."
9637 (interactive "P")
9638 (org-prepare-agenda-buffers (list (current-buffer)))
9639 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9641 (defvar org-cached-props nil)
9642 (defun org-cached-entry-get (pom property)
9643 (if (or (eq t org-use-property-inheritance)
9644 (and (stringp org-use-property-inheritance)
9645 (string-match org-use-property-inheritance property))
9646 (and (listp org-use-property-inheritance)
9647 (member property org-use-property-inheritance)))
9648 ;; Caching is not possible, check it directly
9649 (org-entry-get pom property 'inherit)
9650 ;; Get all properties, so that we can do complicated checks easily
9651 (cdr (assoc property (or org-cached-props
9652 (setq org-cached-props
9653 (org-entry-properties pom)))))))
9655 (defun org-global-tags-completion-table (&optional files)
9656 "Return the list of all tags in all agenda buffer/files."
9657 (save-excursion
9658 (org-uniquify
9659 (delq nil
9660 (apply 'append
9661 (mapcar
9662 (lambda (file)
9663 (set-buffer (find-file-noselect file))
9664 (append (org-get-buffer-tags)
9665 (mapcar (lambda (x) (if (stringp (car-safe x))
9666 (list (car-safe x)) nil))
9667 org-tag-alist)))
9668 (if (and files (car files))
9669 files
9670 (org-agenda-files))))))))
9672 (defun org-make-tags-matcher (match)
9673 "Create the TAGS//TODO matcher form for the selection string MATCH."
9674 ;; todo-only is scoped dynamically into this function, and the function
9675 ;; may change it if the matcher asks for it.
9676 (unless match
9677 ;; Get a new match request, with completion
9678 (let ((org-last-tags-completion-table
9679 (org-global-tags-completion-table)))
9680 (setq match (org-completing-read
9681 "Match: " 'org-tags-completion-function nil nil nil
9682 'org-tags-history))))
9684 ;; Parse the string and create a lisp form
9685 (let ((match0 match)
9686 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9687 minus tag mm
9688 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9689 orterms term orlist re-p str-p level-p level-op time-p
9690 prop-p pn pv po cat-p gv rest)
9691 (if (string-match "/+" match)
9692 ;; match contains also a todo-matching request
9693 (progn
9694 (setq tagsmatch (substring match 0 (match-beginning 0))
9695 todomatch (substring match (match-end 0)))
9696 (if (string-match "^!" todomatch)
9697 (setq todo-only t todomatch (substring todomatch 1)))
9698 (if (string-match "^\\s-*$" todomatch)
9699 (setq todomatch nil)))
9700 ;; only matching tags
9701 (setq tagsmatch match todomatch nil))
9703 ;; Make the tags matcher
9704 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9705 (setq tagsmatcher t)
9706 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9707 (while (setq term (pop orterms))
9708 (while (and (equal (substring term -1) "\\") orterms)
9709 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9710 (while (string-match re term)
9711 (setq rest (substring term (match-end 0))
9712 minus (and (match-end 1)
9713 (equal (match-string 1 term) "-"))
9714 tag (match-string 2 term)
9715 re-p (equal (string-to-char tag) ?{)
9716 level-p (match-end 4)
9717 prop-p (match-end 5)
9718 mm (cond
9719 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9720 (level-p
9721 (setq level-op (org-op-to-function (match-string 3 term)))
9722 `(,level-op level ,(string-to-number
9723 (match-string 4 term))))
9724 (prop-p
9725 (setq pn (match-string 5 term)
9726 po (match-string 6 term)
9727 pv (match-string 7 term)
9728 cat-p (equal pn "CATEGORY")
9729 re-p (equal (string-to-char pv) ?{)
9730 str-p (equal (string-to-char pv) ?\")
9731 time-p (save-match-data
9732 (string-match "^\"[[<].*[]>]\"$" pv))
9733 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9734 (if time-p (setq pv (org-matcher-time pv)))
9735 (setq po (org-op-to-function po (if time-p 'time str-p)))
9736 (cond
9737 ((equal pn "CATEGORY")
9738 (setq gv '(get-text-property (point) 'org-category)))
9739 ((equal pn "TODO")
9740 (setq gv 'todo))
9742 (setq gv `(org-cached-entry-get nil ,pn))))
9743 (if re-p
9744 (if (eq po 'org<>)
9745 `(not (string-match ,pv (or ,gv "")))
9746 `(string-match ,pv (or ,gv "")))
9747 (if str-p
9748 `(,po (or ,gv "") ,pv)
9749 `(,po (string-to-number (or ,gv ""))
9750 ,(string-to-number pv) ))))
9751 (t `(member ,(downcase tag) tags-list)))
9752 mm (if minus (list 'not mm) mm)
9753 term rest)
9754 (push mm tagsmatcher))
9755 (push (if (> (length tagsmatcher) 1)
9756 (cons 'and tagsmatcher)
9757 (car tagsmatcher))
9758 orlist)
9759 (setq tagsmatcher nil))
9760 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9761 (setq tagsmatcher
9762 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9763 ;; Make the todo matcher
9764 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9765 (setq todomatcher t)
9766 (setq orterms (org-split-string todomatch "|") orlist nil)
9767 (while (setq term (pop orterms))
9768 (while (string-match re term)
9769 (setq minus (and (match-end 1)
9770 (equal (match-string 1 term) "-"))
9771 kwd (match-string 2 term)
9772 re-p (equal (string-to-char kwd) ?{)
9773 term (substring term (match-end 0))
9774 mm (if re-p
9775 `(string-match ,(substring kwd 1 -1) todo)
9776 (list 'equal 'todo kwd))
9777 mm (if minus (list 'not mm) mm))
9778 (push mm todomatcher))
9779 (push (if (> (length todomatcher) 1)
9780 (cons 'and todomatcher)
9781 (car todomatcher))
9782 orlist)
9783 (setq todomatcher nil))
9784 (setq todomatcher (if (> (length orlist) 1)
9785 (cons 'or orlist) (car orlist))))
9787 ;; Return the string and lisp forms of the matcher
9788 (setq matcher (if todomatcher
9789 (list 'and tagsmatcher todomatcher)
9790 tagsmatcher))
9791 (cons match0 matcher)))
9793 (defun org-op-to-function (op &optional stringp)
9794 "Turn an operator into the appropriate function."
9795 (setq op
9796 (cond
9797 ((equal op "<" ) '(< string< org-time<))
9798 ((equal op ">" ) '(> org-string> org-time>))
9799 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9800 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9801 ((member op '("=" "==")) '(= string= org-time=))
9802 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9803 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9805 (defun org<> (a b) (not (= a b)))
9806 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9807 (defun org-string>= (a b) (not (string< a b)))
9808 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9809 (defun org-string<> (a b) (not (string= a b)))
9810 (defun org-time= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (= a b)))
9811 (defun org-time< (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (< a b)))
9812 (defun org-time<= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (<= a b)))
9813 (defun org-time> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (> a b)))
9814 (defun org-time>= (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (>= a b)))
9815 (defun org-time<> (a b) (setq a (org-2ft a) b (org-2ft b)) (and (> a 0) (> b 0) (org<> a b)))
9816 (defun org-2ft (s)
9817 "Convert S to a floating point time.
9818 If S is already a number, just return it. If it is a string, parse
9819 it as a time string and apply `float-time' to it. If S is nil, just return 0."
9820 (cond
9821 ((numberp s) s)
9822 ((stringp s)
9823 (condition-case nil
9824 (float-time (apply 'encode-time (org-parse-time-string s)))
9825 (error 0.)))
9826 (t 0.)))
9828 (defun org-time-today ()
9829 "Time in seconds today at 0:00.
9830 Returns the float number of seconds since the beginning of the
9831 epoch to the beginning of today (00:00)."
9832 (float-time (apply 'encode-time
9833 (append '(0 0 0) (nthcdr 3 (decode-time))))))
9835 (defun org-matcher-time (s)
9836 "Interpret a time comparison value."
9837 (save-match-data
9838 (cond
9839 ((string= s "<now>") (float-time))
9840 ((string= s "<today>") (org-time-today))
9841 ((string= s "<tomorrow>") (+ 86400.0 (org-time-today)))
9842 ((string= s "<yesterday>") (- (org-time-today) 86400.0))
9843 ((string-match "^<\\([-+][0-9]+\\)\\([dwmy]\\)>$" s)
9844 (+ (org-time-today)
9845 (* (string-to-number (match-string 1 s))
9846 (cdr (assoc (match-string 2 s)
9847 '(("d" . 86400.0) ("w" . 604800.0)
9848 ("m" . 2678400.0) ("y" . 31557600.0)))))))
9849 (t (org-2ft s)))))
9851 (defun org-match-any-p (re list)
9852 "Does re match any element of list?"
9853 (setq list (mapcar (lambda (x) (string-match re x)) list))
9854 (delq nil list))
9856 (defvar org-add-colon-after-tag-completion nil) ;; dynamically scoped param
9857 (defvar org-tags-overlay (org-make-overlay 1 1))
9858 (org-detach-overlay org-tags-overlay)
9860 (defun org-get-local-tags-at (&optional pos)
9861 "Get a list of tags defined in the current headline."
9862 (org-get-tags-at pos 'local))
9864 (defun org-get-local-tags ()
9865 "Get a list of tags defined in the current headline."
9866 (org-get-tags-at nil 'local))
9868 (defun org-get-tags-at (&optional pos local)
9869 "Get a list of all headline tags applicable at POS.
9870 POS defaults to point. If tags are inherited, the list contains
9871 the targets in the same sequence as the headlines appear, i.e.
9872 the tags of the current headline come last.
9873 When LOCAL is non-nil, only return tags from the current headline,
9874 ignore inherited ones."
9875 (interactive)
9876 (let (tags ltags lastpos parent)
9877 (save-excursion
9878 (save-restriction
9879 (widen)
9880 (goto-char (or pos (point)))
9881 (save-match-data
9882 (catch 'done
9883 (condition-case nil
9884 (progn
9885 (org-back-to-heading t)
9886 (while (not (equal lastpos (point)))
9887 (setq lastpos (point))
9888 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9889 (setq ltags (org-split-string
9890 (org-match-string-no-properties 1) ":"))
9891 (when parent
9892 (setq ltags (mapcar 'org-add-prop-inherited ltags)))
9893 (setq tags (append
9894 (if parent
9895 (org-remove-uniherited-tags ltags)
9896 ltags)
9897 tags)))
9898 (or org-use-tag-inheritance (throw 'done t))
9899 (if local (throw 'done t))
9900 (org-up-heading-all 1)
9901 (setq parent t)))
9902 (error nil)))))
9903 (append (org-remove-uniherited-tags org-file-tags) tags))))
9905 (defun org-add-prop-inherited (s)
9906 (add-text-properties 0 (length s) '(inherited t) s)
9909 (defun org-toggle-tag (tag &optional onoff)
9910 "Toggle the tag TAG for the current line.
9911 If ONOFF is `on' or `off', don't toggle but set to this state."
9912 (let (res current)
9913 (save-excursion
9914 (org-back-to-heading t)
9915 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9916 (point-at-eol) t)
9917 (progn
9918 (setq current (match-string 1))
9919 (replace-match ""))
9920 (setq current ""))
9921 (setq current (nreverse (org-split-string current ":")))
9922 (cond
9923 ((eq onoff 'on)
9924 (setq res t)
9925 (or (member tag current) (push tag current)))
9926 ((eq onoff 'off)
9927 (or (not (member tag current)) (setq current (delete tag current))))
9928 (t (if (member tag current)
9929 (setq current (delete tag current))
9930 (setq res t)
9931 (push tag current))))
9932 (end-of-line 1)
9933 (if current
9934 (progn
9935 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9936 (org-set-tags nil t))
9937 (delete-horizontal-space))
9938 (run-hooks 'org-after-tags-change-hook))
9939 res))
9941 (defun org-align-tags-here (to-col)
9942 ;; Assumes that this is a headline
9943 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9944 (beginning-of-line 1)
9945 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9946 (< pos (match-beginning 2)))
9947 (progn
9948 (setq tags-l (- (match-end 2) (match-beginning 2)))
9949 (goto-char (match-beginning 1))
9950 (insert " ")
9951 (delete-region (point) (1+ (match-beginning 2)))
9952 (setq ncol (max (1+ (current-column))
9953 (1+ col)
9954 (if (> to-col 0)
9955 to-col
9956 (- (abs to-col) tags-l))))
9957 (setq p (point))
9958 (insert (make-string (- ncol (current-column)) ?\ ))
9959 (setq ncol (current-column))
9960 (when indent-tabs-mode (tabify p (point-at-eol)))
9961 (org-move-to-column (min ncol col) t))
9962 (goto-char pos))))
9964 (defun org-set-tags-command (&optional arg just-align)
9965 "Call the set-tags command for the current entry."
9966 (interactive "P")
9967 (if (org-on-heading-p)
9968 (org-set-tags arg just-align)
9969 (save-excursion
9970 (org-back-to-heading t)
9971 (org-set-tags arg just-align))))
9973 (defun org-set-tags (&optional arg just-align)
9974 "Set the tags for the current headline.
9975 With prefix ARG, realign all tags in headings in the current buffer."
9976 (interactive "P")
9977 (let* ((re (concat "^" outline-regexp))
9978 (current (org-get-tags-string))
9979 (col (current-column))
9980 (org-setting-tags t)
9981 table current-tags inherited-tags ; computed below when needed
9982 tags p0 c0 c1 rpl)
9983 (if arg
9984 (save-excursion
9985 (goto-char (point-min))
9986 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9987 (while (re-search-forward re nil t)
9988 (org-set-tags nil t)
9989 (end-of-line 1)))
9990 (message "All tags realigned to column %d" org-tags-column))
9991 (if just-align
9992 (setq tags current)
9993 ;; Get a new set of tags from the user
9994 (save-excursion
9995 (setq table (or org-tag-alist (org-get-buffer-tags))
9996 org-last-tags-completion-table table
9997 current-tags (org-split-string current ":")
9998 inherited-tags (nreverse
9999 (nthcdr (length current-tags)
10000 (nreverse (org-get-tags-at))))
10001 tags
10002 (if (or (eq t org-use-fast-tag-selection)
10003 (and org-use-fast-tag-selection
10004 (delq nil (mapcar 'cdr table))))
10005 (org-fast-tag-selection
10006 current-tags inherited-tags table
10007 (if org-fast-tag-selection-include-todo org-todo-key-alist))
10008 (let ((org-add-colon-after-tag-completion t))
10009 (org-trim
10010 (org-without-partial-completion
10011 (org-ido-completing-read "Tags: " 'org-tags-completion-function
10012 nil nil current 'org-tags-history)))))))
10013 (while (string-match "[-+&]+" tags)
10014 ;; No boolean logic, just a list
10015 (setq tags (replace-match ":" t t tags))))
10017 (if (string-match "\\`[\t ]*\\'" tags)
10018 (setq tags "")
10019 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
10020 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
10022 ;; Insert new tags at the correct column
10023 (beginning-of-line 1)
10024 (cond
10025 ((and (equal current "") (equal tags "")))
10026 ((re-search-forward
10027 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
10028 (point-at-eol) t)
10029 (if (equal tags "")
10030 (setq rpl "")
10031 (goto-char (match-beginning 0))
10032 (setq c0 (current-column) p0 (point)
10033 c1 (max (1+ c0) (if (> org-tags-column 0)
10034 org-tags-column
10035 (- (- org-tags-column) (length tags))))
10036 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
10037 (replace-match rpl t t)
10038 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
10039 tags)
10040 (t (error "Tags alignment failed")))
10041 (org-move-to-column col)
10042 (unless just-align
10043 (run-hooks 'org-after-tags-change-hook)))))
10045 (defun org-change-tag-in-region (beg end tag off)
10046 "Add or remove TAG for each entry in the region.
10047 This works in the agenda, and also in an org-mode buffer."
10048 (interactive
10049 (list (region-beginning) (region-end)
10050 (let ((org-last-tags-completion-table
10051 (if (org-mode-p)
10052 (org-get-buffer-tags)
10053 (org-global-tags-completion-table))))
10054 (org-ido-completing-read
10055 "Tag: " 'org-tags-completion-function nil nil nil
10056 'org-tags-history))
10057 (progn
10058 (message "[s]et or [r]emove? ")
10059 (equal (read-char-exclusive) ?r))))
10060 (if (fboundp 'deactivate-mark) (deactivate-mark))
10061 (let ((agendap (equal major-mode 'org-agenda-mode))
10062 l1 l2 m buf pos newhead (cnt 0))
10063 (goto-char end)
10064 (setq l2 (1- (org-current-line)))
10065 (goto-char beg)
10066 (setq l1 (org-current-line))
10067 (loop for l from l1 to l2 do
10068 (goto-line l)
10069 (setq m (get-text-property (point) 'org-hd-marker))
10070 (when (or (and (org-mode-p) (org-on-heading-p))
10071 (and agendap m))
10072 (setq buf (if agendap (marker-buffer m) (current-buffer))
10073 pos (if agendap m (point)))
10074 (with-current-buffer buf
10075 (save-excursion
10076 (save-restriction
10077 (goto-char pos)
10078 (setq cnt (1+ cnt))
10079 (org-toggle-tag tag (if off 'off 'on))
10080 (setq newhead (org-get-heading)))))
10081 (and agendap (org-agenda-change-all-lines newhead m))))
10082 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
10084 (defun org-tags-completion-function (string predicate &optional flag)
10085 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
10086 (confirm (lambda (x) (stringp (car x)))))
10087 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
10088 (setq s1 (match-string 1 string)
10089 s2 (match-string 2 string))
10090 (setq s1 "" s2 string))
10091 (cond
10092 ((eq flag nil)
10093 ;; try completion
10094 (setq rtn (try-completion s2 ctable confirm))
10095 (if (stringp rtn)
10096 (setq rtn
10097 (concat s1 s2 (substring rtn (length s2))
10098 (if (and org-add-colon-after-tag-completion
10099 (assoc rtn ctable))
10100 ":" ""))))
10101 rtn)
10102 ((eq flag t)
10103 ;; all-completions
10104 (all-completions s2 ctable confirm)
10106 ((eq flag 'lambda)
10107 ;; exact match?
10108 (assoc s2 ctable)))
10111 (defun org-fast-tag-insert (kwd tags face &optional end)
10112 "Insert KDW, and the TAGS, the latter with face FACE. Also insert END."
10113 (insert (format "%-12s" (concat kwd ":"))
10114 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
10115 (or end "")))
10117 (defun org-fast-tag-show-exit (flag)
10118 (save-excursion
10119 (goto-line 3)
10120 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
10121 (replace-match ""))
10122 (when flag
10123 (end-of-line 1)
10124 (org-move-to-column (- (window-width) 19) t)
10125 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
10127 (defun org-set-current-tags-overlay (current prefix)
10128 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
10129 (if (featurep 'xemacs)
10130 (org-overlay-display org-tags-overlay (concat prefix s)
10131 'secondary-selection)
10132 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
10133 (org-overlay-display org-tags-overlay (concat prefix s)))))
10135 (defun org-fast-tag-selection (current inherited table &optional todo-table)
10136 "Fast tag selection with single keys.
10137 CURRENT is the current list of tags in the headline, INHERITED is the
10138 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
10139 possibly with grouping information. TODO-TABLE is a similar table with
10140 TODO keywords, should these have keys assigned to them.
10141 If the keys are nil, a-z are automatically assigned.
10142 Returns the new tags string, or nil to not change the current settings."
10143 (let* ((fulltable (append table todo-table))
10144 (maxlen (apply 'max (mapcar
10145 (lambda (x)
10146 (if (stringp (car x)) (string-width (car x)) 0))
10147 fulltable)))
10148 (buf (current-buffer))
10149 (expert (eq org-fast-tag-selection-single-key 'expert))
10150 (buffer-tags nil)
10151 (fwidth (+ maxlen 3 1 3))
10152 (ncol (/ (- (window-width) 4) fwidth))
10153 (i-face 'org-done)
10154 (c-face 'org-todo)
10155 tg cnt e c char c1 c2 ntable tbl rtn
10156 ov-start ov-end ov-prefix
10157 (exit-after-next org-fast-tag-selection-single-key)
10158 (done-keywords org-done-keywords)
10159 groups ingroup)
10160 (save-excursion
10161 (beginning-of-line 1)
10162 (if (looking-at
10163 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10164 (setq ov-start (match-beginning 1)
10165 ov-end (match-end 1)
10166 ov-prefix "")
10167 (setq ov-start (1- (point-at-eol))
10168 ov-end (1+ ov-start))
10169 (skip-chars-forward "^\n\r")
10170 (setq ov-prefix
10171 (concat
10172 (buffer-substring (1- (point)) (point))
10173 (if (> (current-column) org-tags-column)
10175 (make-string (- org-tags-column (current-column)) ?\ ))))))
10176 (org-move-overlay org-tags-overlay ov-start ov-end)
10177 (save-window-excursion
10178 (if expert
10179 (set-buffer (get-buffer-create " *Org tags*"))
10180 (delete-other-windows)
10181 (split-window-vertically)
10182 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
10183 (erase-buffer)
10184 (org-set-local 'org-done-keywords done-keywords)
10185 (org-fast-tag-insert "Inherited" inherited i-face "\n")
10186 (org-fast-tag-insert "Current" current c-face "\n\n")
10187 (org-fast-tag-show-exit exit-after-next)
10188 (org-set-current-tags-overlay current ov-prefix)
10189 (setq tbl fulltable char ?a cnt 0)
10190 (while (setq e (pop tbl))
10191 (cond
10192 ((equal e '(:startgroup))
10193 (push '() groups) (setq ingroup t)
10194 (when (not (= cnt 0))
10195 (setq cnt 0)
10196 (insert "\n"))
10197 (insert "{ "))
10198 ((equal e '(:endgroup))
10199 (setq ingroup nil cnt 0)
10200 (insert "}\n"))
10202 (setq tg (car e) c2 nil)
10203 (if (cdr e)
10204 (setq c (cdr e))
10205 ;; automatically assign a character.
10206 (setq c1 (string-to-char
10207 (downcase (substring
10208 tg (if (= (string-to-char tg) ?@) 1 0)))))
10209 (if (or (rassoc c1 ntable) (rassoc c1 table))
10210 (while (or (rassoc char ntable) (rassoc char table))
10211 (setq char (1+ char)))
10212 (setq c2 c1))
10213 (setq c (or c2 char)))
10214 (if ingroup (push tg (car groups)))
10215 (setq tg (org-add-props tg nil 'face
10216 (cond
10217 ((not (assoc tg table))
10218 (org-get-todo-face tg))
10219 ((member tg current) c-face)
10220 ((member tg inherited) i-face)
10221 (t nil))))
10222 (if (and (= cnt 0) (not ingroup)) (insert " "))
10223 (insert "[" c "] " tg (make-string
10224 (- fwidth 4 (length tg)) ?\ ))
10225 (push (cons tg c) ntable)
10226 (when (= (setq cnt (1+ cnt)) ncol)
10227 (insert "\n")
10228 (if ingroup (insert " "))
10229 (setq cnt 0)))))
10230 (setq ntable (nreverse ntable))
10231 (insert "\n")
10232 (goto-char (point-min))
10233 (if (not expert) (org-fit-window-to-buffer))
10234 (setq rtn
10235 (catch 'exit
10236 (while t
10237 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
10238 (if groups " [!] no groups" " [!]groups")
10239 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
10240 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
10241 (cond
10242 ((= c ?\r) (throw 'exit t))
10243 ((= c ?!)
10244 (setq groups (not groups))
10245 (goto-char (point-min))
10246 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
10247 ((= c ?\C-c)
10248 (if (not expert)
10249 (org-fast-tag-show-exit
10250 (setq exit-after-next (not exit-after-next)))
10251 (setq expert nil)
10252 (delete-other-windows)
10253 (split-window-vertically)
10254 (org-switch-to-buffer-other-window " *Org tags*")
10255 (org-fit-window-to-buffer)))
10256 ((or (= c ?\C-g)
10257 (and (= c ?q) (not (rassoc c ntable))))
10258 (org-detach-overlay org-tags-overlay)
10259 (setq quit-flag t))
10260 ((= c ?\ )
10261 (setq current nil)
10262 (if exit-after-next (setq exit-after-next 'now)))
10263 ((= c ?\t)
10264 (condition-case nil
10265 (setq tg (org-ido-completing-read
10266 "Tag: "
10267 (or buffer-tags
10268 (with-current-buffer buf
10269 (org-get-buffer-tags)))))
10270 (quit (setq tg "")))
10271 (when (string-match "\\S-" tg)
10272 (add-to-list 'buffer-tags (list tg))
10273 (if (member tg current)
10274 (setq current (delete tg current))
10275 (push tg current)))
10276 (if exit-after-next (setq exit-after-next 'now)))
10277 ((setq e (rassoc c todo-table) tg (car e))
10278 (with-current-buffer buf
10279 (save-excursion (org-todo tg)))
10280 (if exit-after-next (setq exit-after-next 'now)))
10281 ((setq e (rassoc c ntable) tg (car e))
10282 (if (member tg current)
10283 (setq current (delete tg current))
10284 (loop for g in groups do
10285 (if (member tg g)
10286 (mapc (lambda (x)
10287 (setq current (delete x current)))
10288 g)))
10289 (push tg current))
10290 (if exit-after-next (setq exit-after-next 'now))))
10292 ;; Create a sorted list
10293 (setq current
10294 (sort current
10295 (lambda (a b)
10296 (assoc b (cdr (memq (assoc a ntable) ntable))))))
10297 (if (eq exit-after-next 'now) (throw 'exit t))
10298 (goto-char (point-min))
10299 (beginning-of-line 2)
10300 (delete-region (point) (point-at-eol))
10301 (org-fast-tag-insert "Current" current c-face)
10302 (org-set-current-tags-overlay current ov-prefix)
10303 (while (re-search-forward
10304 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10305 (setq tg (match-string 1))
10306 (add-text-properties
10307 (match-beginning 1) (match-end 1)
10308 (list 'face
10309 (cond
10310 ((member tg current) c-face)
10311 ((member tg inherited) i-face)
10312 (t (get-text-property (match-beginning 1) 'face))))))
10313 (goto-char (point-min)))))
10314 (org-detach-overlay org-tags-overlay)
10315 (if rtn
10316 (mapconcat 'identity current ":")
10317 nil))))
10319 (defun org-get-tags-string ()
10320 "Get the TAGS string in the current headline."
10321 (unless (org-on-heading-p t)
10322 (error "Not on a heading"))
10323 (save-excursion
10324 (beginning-of-line 1)
10325 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10326 (org-match-string-no-properties 1)
10327 "")))
10329 (defun org-get-tags ()
10330 "Get the list of tags specified in the current headline."
10331 (org-split-string (org-get-tags-string) ":"))
10333 (defun org-get-buffer-tags ()
10334 "Get a table of all tags used in the buffer, for completion."
10335 (let (tags)
10336 (save-excursion
10337 (goto-char (point-min))
10338 (while (re-search-forward
10339 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10340 (when (equal (char-after (point-at-bol 0)) ?*)
10341 (mapc (lambda (x) (add-to-list 'tags x))
10342 (org-split-string (org-match-string-no-properties 1) ":")))))
10343 (mapcar 'list tags)))
10345 ;;;; The mapping API
10347 ;;;###autoload
10348 (defun org-map-entries (func &optional match scope &rest skip)
10349 "Call FUNC at each headline selected by MATCH in SCOPE.
10351 FUNC is a function or a lisp form. The function will be called without
10352 arguments, with the cursor positioned at the beginning of the headline.
10353 The return values of all calls to the function will be collected and
10354 returned as a list.
10356 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10357 Only headlines that are matched by this query will be considered during
10358 the iteration. When MATCH is nil or t, all headlines will be
10359 visited by the iteration.
10361 SCOPE determines the scope of this command. It can be any of:
10363 nil The current buffer, respecting the restriction if any
10364 tree The subtree started with the entry at point
10365 file The current buffer, without restriction
10366 file-with-archives
10367 The current buffer, and any archives associated with it
10368 agenda All agenda files
10369 agenda-with-archives
10370 All agenda files with any archive files associated with them
10371 \(file1 file2 ...)
10372 If this is a list, all files in the list will be scanned
10374 The remaining args are treated as settings for the skipping facilities of
10375 the scanner. The following items can be given here:
10377 archive skip trees with the archive tag.
10378 comment skip trees with the COMMENT keyword
10379 function or Emacs Lisp form:
10380 will be used as value for `org-agenda-skip-function', so whenever
10381 the the function returns t, FUNC will not be called for that
10382 entry and search will continue from the point where the
10383 function leaves it."
10384 (let* ((org-agenda-archives-mode nil) ; just to make sure
10385 (org-agenda-skip-archived-trees (memq 'archive skip))
10386 (org-agenda-skip-comment-trees (memq 'comment skip))
10387 (org-agenda-skip-function
10388 (car (org-delete-all '(comment archive) skip)))
10389 (org-tags-match-list-sublevels t)
10390 matcher file res
10391 org-todo-keywords-for-agenda
10392 org-done-keywords-for-agenda
10393 org-todo-keyword-alist-for-agenda
10394 org-tag-alist-for-agenda)
10396 (cond
10397 ((eq match t) (setq matcher t))
10398 ((eq match nil) (setq matcher t))
10399 (t (setq matcher (if match (cdr (org-make-tags-matcher match)) t))))
10401 (save-excursion
10402 (save-restriction
10403 (when (eq scope 'tree)
10404 (org-back-to-heading t)
10405 (org-narrow-to-subtree)
10406 (setq scope nil))
10408 (if (not scope)
10409 (progn
10410 (org-prepare-agenda-buffers
10411 (list (buffer-file-name (current-buffer))))
10412 (setq res (org-scan-tags func matcher)))
10413 ;; Get the right scope
10414 (cond
10415 ((and scope (listp scope) (symbolp (car scope)))
10416 (setq scope (eval scope)))
10417 ((eq scope 'agenda)
10418 (setq scope (org-agenda-files t)))
10419 ((eq scope 'agenda-with-archives)
10420 (setq scope (org-agenda-files t))
10421 (setq scope (org-add-archive-files scope)))
10422 ((eq scope 'file)
10423 (setq scope (list (buffer-file-name))))
10424 ((eq scope 'file-with-archives)
10425 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10426 (org-prepare-agenda-buffers scope)
10427 (while (setq file (pop scope))
10428 (with-current-buffer (org-find-base-buffer-visiting file)
10429 (save-excursion
10430 (save-restriction
10431 (widen)
10432 (goto-char (point-min))
10433 (setq res (append res (org-scan-tags func matcher))))))))))
10434 res))
10436 ;;;; Properties
10438 ;;; Setting and retrieving properties
10440 (defconst org-special-properties
10441 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "CLOSED" "PRIORITY"
10442 "TIMESTAMP" "TIMESTAMP_IA")
10443 "The special properties valid in Org-mode.
10445 These are properties that are not defined in the property drawer,
10446 but in some other way.")
10448 (defconst org-default-properties
10449 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10450 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10451 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10452 "EXPORT_FILE_NAME" "EXPORT_TITLE" "ORDERED")
10453 "Some properties that are used by Org-mode for various purposes.
10454 Being in this list makes sure that they are offered for completion.")
10456 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10457 "Regular expression matching the first line of a property drawer.")
10459 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10460 "Regular expression matching the first line of a property drawer.")
10462 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10463 "Regular expression matching the first line of a property drawer.")
10465 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10466 "Regular expression matching the first line of a property drawer.")
10468 (defconst org-property-drawer-re
10469 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10470 org-property-end-re "\\)\n?")
10471 "Matches an entire property drawer.")
10473 (defconst org-clock-drawer-re
10474 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10475 org-property-end-re "\\)\n?")
10476 "Matches an entire clock drawer.")
10478 (defun org-property-action ()
10479 "Do an action on properties."
10480 (interactive)
10481 (let (c)
10482 (org-at-property-p)
10483 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10484 (setq c (read-char-exclusive))
10485 (cond
10486 ((equal c ?s)
10487 (call-interactively 'org-set-property))
10488 ((equal c ?d)
10489 (call-interactively 'org-delete-property))
10490 ((equal c ?D)
10491 (call-interactively 'org-delete-property-globally))
10492 ((equal c ?c)
10493 (call-interactively 'org-compute-property-at-point))
10494 (t (error "No such property action %c" c)))))
10496 (defun org-at-property-p ()
10497 "Is the cursor in a property line?"
10498 ;; FIXME: Does not check if we are actually in the drawer.
10499 ;; FIXME: also returns true on any drawers.....
10500 ;; This is used by C-c C-c for property action.
10501 (save-excursion
10502 (beginning-of-line 1)
10503 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10505 (defun org-get-property-block (&optional beg end force)
10506 "Return the (beg . end) range of the body of the property drawer.
10507 BEG and END can be beginning and end of subtree, if not given
10508 they will be found.
10509 If the drawer does not exist and FORCE is non-nil, create the drawer."
10510 (catch 'exit
10511 (save-excursion
10512 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10513 (end (or end (progn (outline-next-heading) (point)))))
10514 (goto-char beg)
10515 (if (re-search-forward org-property-start-re end t)
10516 (setq beg (1+ (match-end 0)))
10517 (if force
10518 (save-excursion
10519 (org-insert-property-drawer)
10520 (setq end (progn (outline-next-heading) (point))))
10521 (throw 'exit nil))
10522 (goto-char beg)
10523 (if (re-search-forward org-property-start-re end t)
10524 (setq beg (1+ (match-end 0)))))
10525 (if (re-search-forward org-property-end-re end t)
10526 (setq end (match-beginning 0))
10527 (or force (throw 'exit nil))
10528 (goto-char beg)
10529 (setq end beg)
10530 (org-indent-line-function)
10531 (insert ":END:\n"))
10532 (cons beg end)))))
10534 (defun org-entry-properties (&optional pom which)
10535 "Get all properties of the entry at point-or-marker POM.
10536 This includes the TODO keyword, the tags, time strings for deadline,
10537 scheduled, and clocking, and any additional properties defined in the
10538 entry. The return value is an alist, keys may occur multiple times
10539 if the property key was used several times.
10540 POM may also be nil, in which case the current entry is used.
10541 If WHICH is nil or `all', get all properties. If WHICH is
10542 `special' or `standard', only get that subclass."
10543 (setq which (or which 'all))
10544 (org-with-point-at pom
10545 (let ((clockstr (substring org-clock-string 0 -1))
10546 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10547 beg end range props sum-props key value string clocksum)
10548 (save-excursion
10549 (when (condition-case nil
10550 (and (org-mode-p) (org-back-to-heading t))
10551 (error nil))
10552 (setq beg (point))
10553 (setq sum-props (get-text-property (point) 'org-summaries))
10554 (setq clocksum (get-text-property (point) :org-clock-minutes))
10555 (outline-next-heading)
10556 (setq end (point))
10557 (when (memq which '(all special))
10558 ;; Get the special properties, like TODO and tags
10559 (goto-char beg)
10560 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10561 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10562 (when (looking-at org-priority-regexp)
10563 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10564 (when (and (setq value (org-get-tags-string))
10565 (string-match "\\S-" value))
10566 (push (cons "TAGS" value) props))
10567 (when (setq value (org-get-tags-at))
10568 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10569 props))
10570 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10571 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10572 string (if (equal key clockstr)
10573 (org-no-properties
10574 (org-trim
10575 (buffer-substring
10576 (match-beginning 3) (goto-char (point-at-eol)))))
10577 (substring (org-match-string-no-properties 3) 1 -1)))
10578 (unless key
10579 (if (= (char-after (match-beginning 3)) ?\[)
10580 (setq key "TIMESTAMP_IA")
10581 (setq key "TIMESTAMP")))
10582 (when (or (equal key clockstr) (not (assoc key props)))
10583 (push (cons key string) props)))
10587 (when (memq which '(all standard))
10588 ;; Get the standard properties, like :PORP: ...
10589 (setq range (org-get-property-block beg end))
10590 (when range
10591 (goto-char (car range))
10592 (while (re-search-forward
10593 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10594 (cdr range) t)
10595 (setq key (org-match-string-no-properties 1)
10596 value (org-trim (or (org-match-string-no-properties 2) "")))
10597 (unless (member key excluded)
10598 (push (cons key (or value "")) props)))))
10599 (if clocksum
10600 (push (cons "CLOCKSUM"
10601 (org-columns-number-to-string (/ (float clocksum) 60.)
10602 'add_times))
10603 props))
10604 (unless (assoc "CATEGORY" props)
10605 (setq value (or (org-get-category)
10606 (progn (org-refresh-category-properties)
10607 (org-get-category))))
10608 (push (cons "CATEGORY" value) props))
10609 (append sum-props (nreverse props)))))))
10611 (defun org-entry-get (pom property &optional inherit)
10612 "Get value of PROPERTY for entry at point-or-marker POM.
10613 If INHERIT is non-nil and the entry does not have the property,
10614 then also check higher levels of the hierarchy.
10615 If INHERIT is the symbol `selective', use inheritance only if the setting
10616 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10617 If the property is present but empty, the return value is the empty string.
10618 If the property is not present at all, nil is returned."
10619 (org-with-point-at pom
10620 (if (and inherit (if (eq inherit 'selective)
10621 (org-property-inherit-p property)
10623 (org-entry-get-with-inheritance property)
10624 (if (member property org-special-properties)
10625 ;; We need a special property. Use brute force, get all properties.
10626 (cdr (assoc property (org-entry-properties nil 'special)))
10627 (let ((range (org-get-property-block)))
10628 (if (and range
10629 (goto-char (car range))
10630 (re-search-forward
10631 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)?")
10632 (cdr range) t))
10633 ;; Found the property, return it.
10634 (if (match-end 1)
10635 (org-match-string-no-properties 1)
10636 "")))))))
10638 (defun org-property-or-variable-value (var &optional inherit)
10639 "Check if there is a property fixing the value of VAR.
10640 If yes, return this value. If not, return the current value of the variable."
10641 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10642 (if (and prop (stringp prop) (string-match "\\S-" prop))
10643 (read prop)
10644 (symbol-value var))))
10646 (defun org-entry-delete (pom property)
10647 "Delete the property PROPERTY from entry at point-or-marker POM."
10648 (org-with-point-at pom
10649 (if (member property org-special-properties)
10650 nil ; cannot delete these properties.
10651 (let ((range (org-get-property-block)))
10652 (if (and range
10653 (goto-char (car range))
10654 (re-search-forward
10655 (concat "^[ \t]*:" property ":[ \t]*\\(.*[^ \t\r\n\f\v]\\)")
10656 (cdr range) t))
10657 (progn
10658 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10660 nil)))))
10662 ;; Multi-values properties are properties that contain multiple values
10663 ;; These values are assumed to be single words, separated by whitespace.
10664 (defun org-entry-add-to-multivalued-property (pom property value)
10665 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10666 (let* ((old (org-entry-get pom property))
10667 (values (and old (org-split-string old "[ \t]"))))
10668 (setq value (org-entry-protect-space value))
10669 (unless (member value values)
10670 (setq values (cons value values))
10671 (org-entry-put pom property
10672 (mapconcat 'identity values " ")))))
10674 (defun org-entry-remove-from-multivalued-property (pom property value)
10675 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10676 (let* ((old (org-entry-get pom property))
10677 (values (and old (org-split-string old "[ \t]"))))
10678 (setq value (org-entry-protect-space value))
10679 (when (member value values)
10680 (setq values (delete value values))
10681 (org-entry-put pom property
10682 (mapconcat 'identity values " ")))))
10684 (defun org-entry-member-in-multivalued-property (pom property value)
10685 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10686 (let* ((old (org-entry-get pom property))
10687 (values (and old (org-split-string old "[ \t]"))))
10688 (setq value (org-entry-protect-space value))
10689 (member value values)))
10691 (defun org-entry-get-multivalued-property (pom property)
10692 "Return a list of values in a multivalued property."
10693 (let* ((value (org-entry-get pom property))
10694 (values (and value (org-split-string value "[ \t]"))))
10695 (mapcar 'org-entry-restore-space values)))
10697 (defun org-entry-put-multivalued-property (pom property &rest values)
10698 "Set multivalued PROPERTY at point-or-marker POM to VALUES.
10699 VALUES should be a list of strings. Spaces will be protected."
10700 (org-entry-put pom property
10701 (mapconcat 'org-entry-protect-space values " "))
10702 (let* ((value (org-entry-get pom property))
10703 (values (and value (org-split-string value "[ \t]"))))
10704 (mapcar 'org-entry-restore-space values)))
10706 (defun org-entry-protect-space (s)
10707 "Protect spaces and newline in string S."
10708 (while (string-match " " s)
10709 (setq s (replace-match "%20" t t s)))
10710 (while (string-match "\n" s)
10711 (setq s (replace-match "%0A" t t s)))
10714 (defun org-entry-restore-space (s)
10715 "Restore spaces and newline in string S."
10716 (while (string-match "%20" s)
10717 (setq s (replace-match " " t t s)))
10718 (while (string-match "%0A" s)
10719 (setq s (replace-match "\n" t t s)))
10722 (defvar org-entry-property-inherited-from (make-marker)
10723 "Marker pointing to the entry from where a property was inherited.
10724 Each call to `org-entry-get-with-inheritance' will set this marker to the
10725 location of the entry where the inheritance search matched. If there was
10726 no match, the marker will point nowhere.
10727 Note that also `org-entry-get' calls this function, if the INHERIT flag
10728 is set.")
10730 (defun org-entry-get-with-inheritance (property)
10731 "Get entry property, and search higher levels if not present."
10732 (move-marker org-entry-property-inherited-from nil)
10733 (let (tmp)
10734 (save-excursion
10735 (save-restriction
10736 (widen)
10737 (catch 'ex
10738 (while t
10739 (when (setq tmp (org-entry-get nil property))
10740 (org-back-to-heading t)
10741 (move-marker org-entry-property-inherited-from (point))
10742 (throw 'ex tmp))
10743 (or (org-up-heading-safe) (throw 'ex nil)))))
10744 (or tmp
10745 (cdr (assoc property org-file-properties))
10746 (cdr (assoc property org-global-properties))
10747 (cdr (assoc property org-global-properties-fixed))))))
10749 (defun org-entry-put (pom property value)
10750 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10751 (org-with-point-at pom
10752 (org-back-to-heading t)
10753 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10754 range)
10755 (cond
10756 ((equal property "TODO")
10757 (when (and (stringp value) (string-match "\\S-" value)
10758 (not (member value org-todo-keywords-1)))
10759 (error "\"%s\" is not a valid TODO state" value))
10760 (if (or (not value)
10761 (not (string-match "\\S-" value)))
10762 (setq value 'none))
10763 (org-todo value)
10764 (org-set-tags nil 'align))
10765 ((equal property "PRIORITY")
10766 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10767 (string-to-char value) ?\ ))
10768 (org-set-tags nil 'align))
10769 ((equal property "SCHEDULED")
10770 (if (re-search-forward org-scheduled-time-regexp end t)
10771 (cond
10772 ((eq value 'earlier) (org-timestamp-change -1 'day))
10773 ((eq value 'later) (org-timestamp-change 1 'day))
10774 (t (call-interactively 'org-schedule)))
10775 (call-interactively 'org-schedule)))
10776 ((equal property "DEADLINE")
10777 (if (re-search-forward org-deadline-time-regexp end t)
10778 (cond
10779 ((eq value 'earlier) (org-timestamp-change -1 'day))
10780 ((eq value 'later) (org-timestamp-change 1 'day))
10781 (t (call-interactively 'org-deadline)))
10782 (call-interactively 'org-deadline)))
10783 ((member property org-special-properties)
10784 (error "The %s property can not yet be set with `org-entry-put'"
10785 property))
10786 (t ; a non-special property
10787 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10788 (setq range (org-get-property-block beg end 'force))
10789 (goto-char (car range))
10790 (if (re-search-forward
10791 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10792 (progn
10793 (delete-region (match-beginning 1) (match-end 1))
10794 (goto-char (match-beginning 1)))
10795 (goto-char (cdr range))
10796 (insert "\n")
10797 (backward-char 1)
10798 (org-indent-line-function)
10799 (insert ":" property ":"))
10800 (and value (insert " " value))
10801 (org-indent-line-function)))))))
10803 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10804 "Get all property keys in the current buffer.
10805 With INCLUDE-SPECIALS, also list the special properties that reflect things
10806 like tags and TODO state.
10807 With INCLUDE-DEFAULTS, also include properties that has special meaning
10808 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10809 With INCLUDE-COLUMNS, also include property names given in COLUMN
10810 formats in the current buffer."
10811 (let (rtn range cfmt s p)
10812 (save-excursion
10813 (save-restriction
10814 (widen)
10815 (goto-char (point-min))
10816 (while (re-search-forward org-property-start-re nil t)
10817 (setq range (org-get-property-block))
10818 (goto-char (car range))
10819 (while (re-search-forward
10820 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10821 (cdr range) t)
10822 (add-to-list 'rtn (org-match-string-no-properties 1)))
10823 (outline-next-heading))))
10825 (when include-specials
10826 (setq rtn (append org-special-properties rtn)))
10828 (when include-defaults
10829 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10831 (when include-columns
10832 (save-excursion
10833 (save-restriction
10834 (widen)
10835 (goto-char (point-min))
10836 (while (re-search-forward
10837 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10838 nil t)
10839 (setq cfmt (match-string 2) s 0)
10840 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10841 cfmt s)
10842 (setq s (match-end 0)
10843 p (match-string 1 cfmt))
10844 (unless (or (equal p "ITEM")
10845 (member p org-special-properties))
10846 (add-to-list 'rtn (match-string 1 cfmt))))))))
10848 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10850 (defun org-property-values (key)
10851 "Return a list of all values of property KEY."
10852 (save-excursion
10853 (save-restriction
10854 (widen)
10855 (goto-char (point-min))
10856 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10857 values)
10858 (while (re-search-forward re nil t)
10859 (add-to-list 'values (org-trim (match-string 1))))
10860 (delete "" values)))))
10862 (defun org-insert-property-drawer ()
10863 "Insert a property drawer into the current entry."
10864 (interactive)
10865 (org-back-to-heading t)
10866 (looking-at outline-regexp)
10867 (let ((indent (- (match-end 0)(match-beginning 0)))
10868 (beg (point))
10869 (re (concat "^[ \t]*" org-keyword-time-regexp))
10870 end hiddenp)
10871 (outline-next-heading)
10872 (setq end (point))
10873 (goto-char beg)
10874 (while (re-search-forward re end t))
10875 (setq hiddenp (org-invisible-p))
10876 (end-of-line 1)
10877 (and (equal (char-after) ?\n) (forward-char 1))
10878 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10879 (beginning-of-line 2))
10880 (org-skip-over-state-notes)
10881 (skip-chars-backward " \t\n\r")
10882 (if (eq (char-before) ?*) (forward-char 1))
10883 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10884 (beginning-of-line 0)
10885 (org-indent-to-column indent)
10886 (beginning-of-line 2)
10887 (org-indent-to-column indent)
10888 (beginning-of-line 0)
10889 (if hiddenp
10890 (save-excursion
10891 (org-back-to-heading t)
10892 (hide-entry))
10893 (org-flag-drawer t))))
10895 (defun org-set-property (property value)
10896 "In the current entry, set PROPERTY to VALUE.
10897 When called interactively, this will prompt for a property name, offering
10898 completion on existing and default properties. And then it will prompt
10899 for a value, offering completion either on allowed values (via an inherited
10900 xxx_ALL property) or on existing values in other instances of this property
10901 in the current file."
10902 (interactive
10903 (let* ((completion-ignore-case t)
10904 (keys (org-buffer-property-keys nil t t))
10905 (prop0 (org-ido-completing-read "Property: " (mapcar 'list keys)))
10906 (prop (if (member prop0 keys)
10907 prop0
10908 (or (cdr (assoc (downcase prop0)
10909 (mapcar (lambda (x) (cons (downcase x) x))
10910 keys)))
10911 prop0)))
10912 (cur (org-entry-get nil prop))
10913 (allowed (org-property-get-allowed-values nil prop 'table))
10914 (existing (mapcar 'list (org-property-values prop)))
10915 (val (if allowed
10916 (org-completing-read "Value: " allowed nil 'req-match)
10917 (org-completing-read
10918 (concat "Value" (if (and cur (string-match "\\S-" cur))
10919 (concat "[" cur "]") "")
10920 ": ")
10921 existing nil nil "" nil cur))))
10922 (list prop (if (equal val "") cur val))))
10923 (unless (equal (org-entry-get nil property) value)
10924 (org-entry-put nil property value)))
10926 (defun org-delete-property (property)
10927 "In the current entry, delete PROPERTY."
10928 (interactive
10929 (let* ((completion-ignore-case t)
10930 (prop (org-ido-completing-read
10931 "Property: " (org-entry-properties nil 'standard))))
10932 (list prop)))
10933 (message "Property %s %s" property
10934 (if (org-entry-delete nil property)
10935 "deleted"
10936 "was not present in the entry")))
10938 (defun org-delete-property-globally (property)
10939 "Remove PROPERTY globally, from all entries."
10940 (interactive
10941 (let* ((completion-ignore-case t)
10942 (prop (org-ido-completing-read
10943 "Globally remove property: "
10944 (mapcar 'list (org-buffer-property-keys)))))
10945 (list prop)))
10946 (save-excursion
10947 (save-restriction
10948 (widen)
10949 (goto-char (point-min))
10950 (let ((cnt 0))
10951 (while (re-search-forward
10952 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10953 nil t)
10954 (setq cnt (1+ cnt))
10955 (replace-match ""))
10956 (message "Property \"%s\" removed from %d entries" property cnt)))))
10958 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10960 (defun org-compute-property-at-point ()
10961 "Compute the property at point.
10962 This looks for an enclosing column format, extracts the operator and
10963 then applies it to the property in the column format's scope."
10964 (interactive)
10965 (unless (org-at-property-p)
10966 (error "Not at a property"))
10967 (let ((prop (org-match-string-no-properties 2)))
10968 (org-columns-get-format-and-top-level)
10969 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10970 (error "No operator defined for property %s" prop))
10971 (org-columns-compute prop)))
10973 (defun org-property-get-allowed-values (pom property &optional table)
10974 "Get allowed values for the property PROPERTY.
10975 When TABLE is non-nil, return an alist that can directly be used for
10976 completion."
10977 (let (vals)
10978 (cond
10979 ((equal property "TODO")
10980 (setq vals (org-with-point-at pom
10981 (append org-todo-keywords-1 '("")))))
10982 ((equal property "PRIORITY")
10983 (let ((n org-lowest-priority))
10984 (while (>= n org-highest-priority)
10985 (push (char-to-string n) vals)
10986 (setq n (1- n)))))
10987 ((member property org-special-properties))
10989 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10991 (when (and vals (string-match "\\S-" vals))
10992 (setq vals (car (read-from-string (concat "(" vals ")"))))
10993 (setq vals (mapcar (lambda (x)
10994 (cond ((stringp x) x)
10995 ((numberp x) (number-to-string x))
10996 ((symbolp x) (symbol-name x))
10997 (t "???")))
10998 vals)))))
10999 (if table (mapcar 'list vals) vals)))
11001 (defun org-property-previous-allowed-value (&optional previous)
11002 "Switch to the next allowed value for this property."
11003 (interactive)
11004 (org-property-next-allowed-value t))
11006 (defun org-property-next-allowed-value (&optional previous)
11007 "Switch to the next allowed value for this property."
11008 (interactive)
11009 (unless (org-at-property-p)
11010 (error "Not at a property"))
11011 (let* ((key (match-string 2))
11012 (value (match-string 3))
11013 (allowed (or (org-property-get-allowed-values (point) key)
11014 (and (member value '("[ ]" "[-]" "[X]"))
11015 '("[ ]" "[X]"))))
11016 nval)
11017 (unless allowed
11018 (error "Allowed values for this property have not been defined"))
11019 (if previous (setq allowed (reverse allowed)))
11020 (if (member value allowed)
11021 (setq nval (car (cdr (member value allowed)))))
11022 (setq nval (or nval (car allowed)))
11023 (if (equal nval value)
11024 (error "Only one allowed value for this property"))
11025 (org-at-property-p)
11026 (replace-match (concat " :" key ": " nval) t t)
11027 (org-indent-line-function)
11028 (beginning-of-line 1)
11029 (skip-chars-forward " \t")))
11031 (defun org-find-entry-with-id (ident)
11032 "Locate the entry that contains the ID property with exact value IDENT.
11033 IDENT can be a string, a symbol or a number, this function will search for
11034 the string representation of it.
11035 Return the position where this entry starts, or nil if there is no such entry."
11036 (interactive "sID: ")
11037 (let ((id (cond
11038 ((stringp ident) ident)
11039 ((symbol-name ident) (symbol-name ident))
11040 ((numberp ident) (number-to-string ident))
11041 (t (error "IDENT %s must be a string, symbol or number" ident))))
11042 (case-fold-search nil))
11043 (save-excursion
11044 (save-restriction
11045 (widen)
11046 (goto-char (point-min))
11047 (when (re-search-forward
11048 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
11049 nil t)
11050 (org-back-to-heading)
11051 (point))))))
11053 ;;;; Timestamps
11055 (defvar org-last-changed-timestamp nil)
11056 (defvar org-last-inserted-timestamp nil
11057 "The last time stamp inserted with `org-insert-time-stamp'.")
11058 (defvar org-time-was-given) ; dynamically scoped parameter
11059 (defvar org-end-time-was-given) ; dynamically scoped parameter
11060 (defvar org-ts-what) ; dynamically scoped parameter
11062 (defun org-time-stamp (arg &optional inactive)
11063 "Prompt for a date/time and insert a time stamp.
11064 If the user specifies a time like HH:MM, or if this command is called
11065 with a prefix argument, the time stamp will contain date and time.
11066 Otherwise, only the date will be included. All parts of a date not
11067 specified by the user will be filled in from the current date/time.
11068 So if you press just return without typing anything, the time stamp
11069 will represent the current date/time. If there is already a timestamp
11070 at the cursor, it will be modified."
11071 (interactive "P")
11072 (let* ((ts nil)
11073 (default-time
11074 ;; Default time is either today, or, when entering a range,
11075 ;; the range start.
11076 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
11077 (save-excursion
11078 (re-search-backward
11079 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
11080 (- (point) 20) t)))
11081 (apply 'encode-time (org-parse-time-string (match-string 1)))
11082 (current-time)))
11083 (default-input (and ts (org-get-compact-tod ts)))
11084 org-time-was-given org-end-time-was-given time)
11085 (cond
11086 ((and (org-at-timestamp-p t)
11087 (memq last-command '(org-time-stamp org-time-stamp-inactive))
11088 (memq this-command '(org-time-stamp org-time-stamp-inactive)))
11089 (insert "--")
11090 (setq time (let ((this-command this-command))
11091 (org-read-date arg 'totime nil nil
11092 default-time default-input)))
11093 (org-insert-time-stamp time (or org-time-was-given arg) inactive))
11094 ((org-at-timestamp-p t)
11095 (setq time (let ((this-command this-command))
11096 (org-read-date arg 'totime nil nil default-time default-input)))
11097 (when (org-at-timestamp-p t) ; just to get the match data
11098 ; (setq inactive (eq (char-after (match-beginning 0)) ?\[))
11099 (replace-match "")
11100 (setq org-last-changed-timestamp
11101 (org-insert-time-stamp
11102 time (or org-time-was-given arg)
11103 inactive nil nil (list org-end-time-was-given))))
11104 (message "Timestamp updated"))
11106 (setq time (let ((this-command this-command))
11107 (org-read-date arg 'totime nil nil default-time default-input)))
11108 (org-insert-time-stamp time (or org-time-was-given arg) inactive
11109 nil nil (list org-end-time-was-given))))))
11111 ;; FIXME: can we use this for something else, like computing time differences?
11112 (defun org-get-compact-tod (s)
11113 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
11114 (let* ((t1 (match-string 1 s))
11115 (h1 (string-to-number (match-string 2 s)))
11116 (m1 (string-to-number (match-string 3 s)))
11117 (t2 (and (match-end 4) (match-string 5 s)))
11118 (h2 (and t2 (string-to-number (match-string 6 s))))
11119 (m2 (and t2 (string-to-number (match-string 7 s))))
11120 dh dm)
11121 (if (not t2)
11123 (setq dh (- h2 h1) dm (- m2 m1))
11124 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
11125 (concat t1 "+" (number-to-string dh)
11126 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
11128 (defun org-time-stamp-inactive (&optional arg)
11129 "Insert an inactive time stamp.
11130 An inactive time stamp is enclosed in square brackets instead of angle
11131 brackets. It is inactive in the sense that it does not trigger agenda entries,
11132 does not link to the calendar and cannot be changed with the S-cursor keys.
11133 So these are more for recording a certain time/date."
11134 (interactive "P")
11135 (org-time-stamp arg 'inactive))
11137 (defvar org-date-ovl (org-make-overlay 1 1))
11138 (org-overlay-put org-date-ovl 'face 'org-warning)
11139 (org-detach-overlay org-date-ovl)
11141 (defvar org-ans1) ; dynamically scoped parameter
11142 (defvar org-ans2) ; dynamically scoped parameter
11144 (defvar org-plain-time-of-day-regexp) ; defined below
11146 (defvar org-overriding-default-time nil) ; dynamically scoped
11147 (defvar org-read-date-overlay nil)
11148 (defvar org-dcst nil) ; dynamically scoped
11150 (defun org-read-date (&optional with-time to-time from-string prompt
11151 default-time default-input)
11152 "Read a date, possibly a time, and make things smooth for the user.
11153 The prompt will suggest to enter an ISO date, but you can also enter anything
11154 which will at least partially be understood by `parse-time-string'.
11155 Unrecognized parts of the date will default to the current day, month, year,
11156 hour and minute. If this command is called to replace a timestamp at point,
11157 of to enter the second timestamp of a range, the default time is taken from the
11158 existing stamp. For example,
11159 3-2-5 --> 2003-02-05
11160 feb 15 --> currentyear-02-15
11161 sep 12 9 --> 2009-09-12
11162 12:45 --> today 12:45
11163 22 sept 0:34 --> currentyear-09-22 0:34
11164 12 --> currentyear-currentmonth-12
11165 Fri --> nearest Friday (today or later)
11166 etc.
11168 Furthermore you can specify a relative date by giving, as the *first* thing
11169 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
11170 change in days weeks, months, years.
11171 With a single plus or minus, the date is relative to today. With a double
11172 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
11173 +4d --> four days from today
11174 +4 --> same as above
11175 +2w --> two weeks from today
11176 ++5 --> five days from default date
11178 The function understands only English month and weekday abbreviations,
11179 but this can be configured with the variables `parse-time-months' and
11180 `parse-time-weekdays'.
11182 While prompting, a calendar is popped up - you can also select the
11183 date with the mouse (button 1). The calendar shows a period of three
11184 months. To scroll it to other months, use the keys `>' and `<'.
11185 If you don't like the calendar, turn it off with
11186 \(setq org-read-date-popup-calendar nil)
11188 With optional argument TO-TIME, the date will immediately be converted
11189 to an internal time.
11190 With an optional argument WITH-TIME, the prompt will suggest to also
11191 insert a time. Note that when WITH-TIME is not set, you can still
11192 enter a time, and this function will inform the calling routine about
11193 this change. The calling routine may then choose to change the format
11194 used to insert the time stamp into the buffer to include the time.
11195 With optional argument FROM-STRING, read from this string instead from
11196 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
11197 the time/date that is used for everything that is not specified by the
11198 user."
11199 (require 'parse-time)
11200 (let* ((org-time-stamp-rounding-minutes
11201 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
11202 (org-dcst org-display-custom-times)
11203 (ct (org-current-time))
11204 (def (or org-overriding-default-time default-time ct))
11205 (defdecode (decode-time def))
11206 (dummy (progn
11207 (when (< (nth 2 defdecode) org-extend-today-until)
11208 (setcar (nthcdr 2 defdecode) -1)
11209 (setcar (nthcdr 1 defdecode) 59)
11210 (setq def (apply 'encode-time defdecode)
11211 defdecode (decode-time def)))))
11212 (calendar-move-hook nil)
11213 (calendar-view-diary-initially-flag nil)
11214 (view-diary-entries-initially nil)
11215 (calendar-view-holidays-initially-flag nil)
11216 (view-calendar-holidays-initially nil)
11217 (timestr (format-time-string
11218 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
11219 (prompt (concat (if prompt (concat prompt " ") "")
11220 (format "Date+time [%s]: " timestr)))
11221 ans (org-ans0 "") org-ans1 org-ans2 final)
11223 (cond
11224 (from-string (setq ans from-string))
11225 (org-read-date-popup-calendar
11226 (save-excursion
11227 (save-window-excursion
11228 (calendar)
11229 (calendar-forward-day (- (time-to-days def)
11230 (calendar-absolute-from-gregorian
11231 (calendar-current-date))))
11232 (org-eval-in-calendar nil t)
11233 (let* ((old-map (current-local-map))
11234 (map (copy-keymap calendar-mode-map))
11235 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
11236 (org-defkey map (kbd "RET") 'org-calendar-select)
11237 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
11238 'org-calendar-select-mouse)
11239 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
11240 'org-calendar-select-mouse)
11241 (org-defkey minibuffer-local-map [(meta shift left)]
11242 (lambda () (interactive)
11243 (org-eval-in-calendar '(calendar-backward-month 1))))
11244 (org-defkey minibuffer-local-map [(meta shift right)]
11245 (lambda () (interactive)
11246 (org-eval-in-calendar '(calendar-forward-month 1))))
11247 (org-defkey minibuffer-local-map [(meta shift up)]
11248 (lambda () (interactive)
11249 (org-eval-in-calendar '(calendar-backward-year 1))))
11250 (org-defkey minibuffer-local-map [(meta shift down)]
11251 (lambda () (interactive)
11252 (org-eval-in-calendar '(calendar-forward-year 1))))
11253 (org-defkey minibuffer-local-map [(shift up)]
11254 (lambda () (interactive)
11255 (org-eval-in-calendar '(calendar-backward-week 1))))
11256 (org-defkey minibuffer-local-map [(shift down)]
11257 (lambda () (interactive)
11258 (org-eval-in-calendar '(calendar-forward-week 1))))
11259 (org-defkey minibuffer-local-map [(shift left)]
11260 (lambda () (interactive)
11261 (org-eval-in-calendar '(calendar-backward-day 1))))
11262 (org-defkey minibuffer-local-map [(shift right)]
11263 (lambda () (interactive)
11264 (org-eval-in-calendar '(calendar-forward-day 1))))
11265 (org-defkey minibuffer-local-map ">"
11266 (lambda () (interactive)
11267 (org-eval-in-calendar '(scroll-calendar-left 1))))
11268 (org-defkey minibuffer-local-map "<"
11269 (lambda () (interactive)
11270 (org-eval-in-calendar '(scroll-calendar-right 1))))
11271 (unwind-protect
11272 (progn
11273 (use-local-map map)
11274 (add-hook 'post-command-hook 'org-read-date-display)
11275 (setq org-ans0 (read-string prompt default-input nil nil))
11276 ;; org-ans0: from prompt
11277 ;; org-ans1: from mouse click
11278 ;; org-ans2: from calendar motion
11279 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
11280 (remove-hook 'post-command-hook 'org-read-date-display)
11281 (use-local-map old-map)
11282 (when org-read-date-overlay
11283 (org-delete-overlay org-read-date-overlay)
11284 (setq org-read-date-overlay nil)))))))
11286 (t ; Naked prompt only
11287 (unwind-protect
11288 (setq ans (read-string prompt default-input nil timestr))
11289 (when org-read-date-overlay
11290 (org-delete-overlay org-read-date-overlay)
11291 (setq org-read-date-overlay nil)))))
11293 (setq final (org-read-date-analyze ans def defdecode))
11295 (if to-time
11296 (apply 'encode-time final)
11297 (if (and (boundp 'org-time-was-given) org-time-was-given)
11298 (format "%04d-%02d-%02d %02d:%02d"
11299 (nth 5 final) (nth 4 final) (nth 3 final)
11300 (nth 2 final) (nth 1 final))
11301 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
11302 (defvar def)
11303 (defvar defdecode)
11304 (defvar with-time)
11305 (defun org-read-date-display ()
11306 "Display the current date prompt interpretation in the minibuffer."
11307 (when org-read-date-display-live
11308 (when org-read-date-overlay
11309 (org-delete-overlay org-read-date-overlay))
11310 (let ((p (point)))
11311 (end-of-line 1)
11312 (while (not (equal (buffer-substring
11313 (max (point-min) (- (point) 4)) (point))
11314 " "))
11315 (insert " "))
11316 (goto-char p))
11317 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
11318 " " (or org-ans1 org-ans2)))
11319 (org-end-time-was-given nil)
11320 (f (org-read-date-analyze ans def defdecode))
11321 (fmts (if org-dcst
11322 org-time-stamp-custom-formats
11323 org-time-stamp-formats))
11324 (fmt (if (or with-time
11325 (and (boundp 'org-time-was-given) org-time-was-given))
11326 (cdr fmts)
11327 (car fmts)))
11328 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
11329 (when (and org-end-time-was-given
11330 (string-match org-plain-time-of-day-regexp txt))
11331 (setq txt (concat (substring txt 0 (match-end 0)) "-"
11332 org-end-time-was-given
11333 (substring txt (match-end 0)))))
11334 (setq org-read-date-overlay
11335 (org-make-overlay (1- (point-at-eol)) (point-at-eol)))
11336 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
11338 (defun org-read-date-analyze (ans def defdecode)
11339 "Analyse the combined answer of the date prompt."
11340 ;; FIXME: cleanup and comment
11341 (let (delta deltan deltaw deltadef year month day
11342 hour minute second wday pm h2 m2 tl wday1
11343 iso-year iso-weekday iso-week iso-year iso-date)
11345 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
11346 (setq ans "+0"))
11348 (when (setq delta (org-read-date-get-relative ans (current-time) def))
11349 (setq ans (replace-match "" t t ans)
11350 deltan (car delta)
11351 deltaw (nth 1 delta)
11352 deltadef (nth 2 delta)))
11354 ;; Check if there is an iso week date in there
11355 ;; If yes, sore the info and postpone interpreting it until the rest
11356 ;; of the parsing is done
11357 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11358 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11359 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11360 iso-week (string-to-number (match-string 2 ans)))
11361 (setq ans (replace-match "" t t ans)))
11363 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11364 (when (string-match
11365 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11366 (setq year (if (match-end 2)
11367 (string-to-number (match-string 2 ans))
11368 (string-to-number (format-time-string "%Y")))
11369 month (string-to-number (match-string 3 ans))
11370 day (string-to-number (match-string 4 ans)))
11371 (if (< year 100) (setq year (+ 2000 year)))
11372 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11373 t nil ans)))
11374 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11375 ;; If there is a time with am/pm, and *no* time without it, we convert
11376 ;; so that matching will be successful.
11377 (loop for i from 1 to 2 do ; twice, for end time as well
11378 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11379 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11380 (setq hour (string-to-number (match-string 1 ans))
11381 minute (if (match-end 3)
11382 (string-to-number (match-string 3 ans))
11384 pm (equal ?p
11385 (string-to-char (downcase (match-string 4 ans)))))
11386 (if (and (= hour 12) (not pm))
11387 (setq hour 0)
11388 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11389 (setq ans (replace-match (format "%02d:%02d" hour minute)
11390 t t ans))))
11392 ;; Check if a time range is given as a duration
11393 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11394 (setq hour (string-to-number (match-string 1 ans))
11395 h2 (+ hour (string-to-number (match-string 3 ans)))
11396 minute (string-to-number (match-string 2 ans))
11397 m2 (+ minute (if (match-end 5) (string-to-number
11398 (match-string 5 ans))0)))
11399 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11400 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11401 t t ans)))
11403 ;; Check if there is a time range
11404 (when (boundp 'org-end-time-was-given)
11405 (setq org-time-was-given nil)
11406 (when (and (string-match org-plain-time-of-day-regexp ans)
11407 (match-end 8))
11408 (setq org-end-time-was-given (match-string 8 ans))
11409 (setq ans (concat (substring ans 0 (match-beginning 7))
11410 (substring ans (match-end 7))))))
11412 (setq tl (parse-time-string ans)
11413 day (or (nth 3 tl) (nth 3 defdecode))
11414 month (or (nth 4 tl)
11415 (if (and org-read-date-prefer-future
11416 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11417 (1+ (nth 4 defdecode))
11418 (nth 4 defdecode)))
11419 year (or (nth 5 tl)
11420 (if (and org-read-date-prefer-future
11421 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11422 (1+ (nth 5 defdecode))
11423 (nth 5 defdecode)))
11424 hour (or (nth 2 tl) (nth 2 defdecode))
11425 minute (or (nth 1 tl) (nth 1 defdecode))
11426 second (or (nth 0 tl) 0)
11427 wday (nth 6 tl))
11429 ;; Special date definitions below
11430 (cond
11431 (iso-week
11432 ;; There was an iso week
11433 (setq year (or iso-year year)
11434 day (or iso-weekday wday 1)
11435 wday nil ; to make sure that the trigger below does not match
11436 iso-date (calendar-gregorian-from-absolute
11437 (calendar-absolute-from-iso
11438 (list iso-week day year))))
11439 ; FIXME: Should we also push ISO weeks into the future?
11440 ; (when (and org-read-date-prefer-future
11441 ; (not iso-year)
11442 ; (< (calendar-absolute-from-gregorian iso-date)
11443 ; (time-to-days (current-time))))
11444 ; (setq year (1+ year)
11445 ; iso-date (calendar-gregorian-from-absolute
11446 ; (calendar-absolute-from-iso
11447 ; (list iso-week day year)))))
11448 (setq month (car iso-date)
11449 year (nth 2 iso-date)
11450 day (nth 1 iso-date)))
11451 (deltan
11452 (unless deltadef
11453 (let ((now (decode-time (current-time))))
11454 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11455 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11456 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11457 ((equal deltaw "m") (setq month (+ month deltan)))
11458 ((equal deltaw "y") (setq year (+ year deltan)))))
11459 ((and wday (not (nth 3 tl)))
11460 ;; Weekday was given, but no day, so pick that day in the week
11461 ;; on or after the derived date.
11462 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11463 (unless (equal wday wday1)
11464 (setq day (+ day (% (- wday wday1 -7) 7))))))
11465 (if (and (boundp 'org-time-was-given)
11466 (nth 2 tl))
11467 (setq org-time-was-given t))
11468 (if (< year 100) (setq year (+ 2000 year)))
11469 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11470 (list second minute hour day month year)))
11472 (defvar parse-time-weekdays)
11474 (defun org-read-date-get-relative (s today default)
11475 "Check string S for special relative date string.
11476 TODAY and DEFAULT are internal times, for today and for a default.
11477 Return shift list (N what def-flag)
11478 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11479 N is the number of WHATs to shift.
11480 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11481 the DEFAULT date rather than TODAY."
11482 (when (and
11483 (string-match
11484 (concat
11485 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11486 "\\([0-9]+\\)?"
11487 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11488 "\\([ \t]\\|$\\)") s)
11489 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11490 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11491 (string-to-char (substring (match-string 1 s) -1))
11492 ?+))
11493 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11494 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11495 (what (if (match-end 3) (match-string 3 s) "d"))
11496 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11497 (date (if rel default today))
11498 (wday (nth 6 (decode-time date)))
11499 delta)
11500 (if wday1
11501 (progn
11502 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11503 (if (= dir ?-) (setq delta (- delta 7)))
11504 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11505 (list delta "d" rel))
11506 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11508 (defun org-eval-in-calendar (form &optional keepdate)
11509 "Eval FORM in the calendar window and return to current window.
11510 Also, store the cursor date in variable org-ans2."
11511 (let ((sw (selected-window)))
11512 (select-window (get-buffer-window "*Calendar*"))
11513 (eval form)
11514 (when (and (not keepdate) (calendar-cursor-to-date))
11515 (let* ((date (calendar-cursor-to-date))
11516 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11517 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11518 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11519 (select-window sw)))
11521 (defun org-calendar-select ()
11522 "Return to `org-read-date' with the date currently selected.
11523 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11524 (interactive)
11525 (when (calendar-cursor-to-date)
11526 (let* ((date (calendar-cursor-to-date))
11527 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11528 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11529 (if (active-minibuffer-window) (exit-minibuffer))))
11531 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11532 "Insert a date stamp for the date given by the internal TIME.
11533 WITH-HM means, use the stamp format that includes the time of the day.
11534 INACTIVE means use square brackets instead of angular ones, so that the
11535 stamp will not contribute to the agenda.
11536 PRE and POST are optional strings to be inserted before and after the
11537 stamp.
11538 The command returns the inserted time stamp."
11539 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11540 stamp)
11541 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11542 (insert-before-markers (or pre ""))
11543 (insert-before-markers (setq stamp (format-time-string fmt time)))
11544 (when (listp extra)
11545 (setq extra (car extra))
11546 (if (and (stringp extra)
11547 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11548 (setq extra (format "-%02d:%02d"
11549 (string-to-number (match-string 1 extra))
11550 (string-to-number (match-string 2 extra))))
11551 (setq extra nil)))
11552 (when extra
11553 (backward-char 1)
11554 (insert-before-markers extra)
11555 (forward-char 1))
11556 (insert-before-markers (or post ""))
11557 (setq org-last-inserted-timestamp stamp)))
11559 (defun org-toggle-time-stamp-overlays ()
11560 "Toggle the use of custom time stamp formats."
11561 (interactive)
11562 (setq org-display-custom-times (not org-display-custom-times))
11563 (unless org-display-custom-times
11564 (let ((p (point-min)) (bmp (buffer-modified-p)))
11565 (while (setq p (next-single-property-change p 'display))
11566 (if (and (get-text-property p 'display)
11567 (eq (get-text-property p 'face) 'org-date))
11568 (remove-text-properties
11569 p (setq p (next-single-property-change p 'display))
11570 '(display t))))
11571 (set-buffer-modified-p bmp)))
11572 (if (featurep 'xemacs)
11573 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11574 (org-restart-font-lock)
11575 (setq org-table-may-need-update t)
11576 (if org-display-custom-times
11577 (message "Time stamps are overlayed with custom format")
11578 (message "Time stamp overlays removed")))
11580 (defun org-display-custom-time (beg end)
11581 "Overlay modified time stamp format over timestamp between BEG and END."
11582 (let* ((ts (buffer-substring beg end))
11583 t1 w1 with-hm tf time str w2 (off 0))
11584 (save-match-data
11585 (setq t1 (org-parse-time-string ts t))
11586 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11587 (setq off (- (match-end 0) (match-beginning 0)))))
11588 (setq end (- end off))
11589 (setq w1 (- end beg)
11590 with-hm (and (nth 1 t1) (nth 2 t1))
11591 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11592 time (org-fix-decoded-time t1)
11593 str (org-add-props
11594 (format-time-string
11595 (substring tf 1 -1) (apply 'encode-time time))
11596 nil 'mouse-face 'highlight)
11597 w2 (length str))
11598 (if (not (= w2 w1))
11599 (add-text-properties (1+ beg) (+ 2 beg)
11600 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11601 (if (featurep 'xemacs)
11602 (progn
11603 (put-text-property beg end 'invisible t)
11604 (put-text-property beg end 'end-glyph (make-glyph str)))
11605 (put-text-property beg end 'display str))))
11607 (defun org-translate-time (string)
11608 "Translate all timestamps in STRING to custom format.
11609 But do this only if the variable `org-display-custom-times' is set."
11610 (when org-display-custom-times
11611 (save-match-data
11612 (let* ((start 0)
11613 (re org-ts-regexp-both)
11614 t1 with-hm inactive tf time str beg end)
11615 (while (setq start (string-match re string start))
11616 (setq beg (match-beginning 0)
11617 end (match-end 0)
11618 t1 (save-match-data
11619 (org-parse-time-string (substring string beg end) t))
11620 with-hm (and (nth 1 t1) (nth 2 t1))
11621 inactive (equal (substring string beg (1+ beg)) "[")
11622 tf (funcall (if with-hm 'cdr 'car)
11623 org-time-stamp-custom-formats)
11624 time (org-fix-decoded-time t1)
11625 str (format-time-string
11626 (concat
11627 (if inactive "[" "<") (substring tf 1 -1)
11628 (if inactive "]" ">"))
11629 (apply 'encode-time time))
11630 string (replace-match str t t string)
11631 start (+ start (length str)))))))
11632 string)
11634 (defun org-fix-decoded-time (time)
11635 "Set 0 instead of nil for the first 6 elements of time.
11636 Don't touch the rest."
11637 (let ((n 0))
11638 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11640 (defun org-days-to-time (timestamp-string)
11641 "Difference between TIMESTAMP-STRING and now in days."
11642 (- (time-to-days (org-time-string-to-time timestamp-string))
11643 (time-to-days (current-time))))
11645 (defun org-deadline-close (timestamp-string &optional ndays)
11646 "Is the time in TIMESTAMP-STRING close to the current date?"
11647 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11648 (and (< (org-days-to-time timestamp-string) ndays)
11649 (not (org-entry-is-done-p))))
11651 (defun org-get-wdays (ts)
11652 "Get the deadline lead time appropriate for timestring TS."
11653 (cond
11654 ((<= org-deadline-warning-days 0)
11655 ;; 0 or negative, enforce this value no matter what
11656 (- org-deadline-warning-days))
11657 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11658 ;; lead time is specified.
11659 (floor (* (string-to-number (match-string 1 ts))
11660 (cdr (assoc (match-string 2 ts)
11661 '(("d" . 1) ("w" . 7)
11662 ("m" . 30.4) ("y" . 365.25)))))))
11663 ;; go for the default.
11664 (t org-deadline-warning-days)))
11666 (defun org-calendar-select-mouse (ev)
11667 "Return to `org-read-date' with the date currently selected.
11668 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11669 (interactive "e")
11670 (mouse-set-point ev)
11671 (when (calendar-cursor-to-date)
11672 (let* ((date (calendar-cursor-to-date))
11673 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11674 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11675 (if (active-minibuffer-window) (exit-minibuffer))))
11677 (defun org-check-deadlines (ndays)
11678 "Check if there are any deadlines due or past due.
11679 A deadline is considered due if it happens within `org-deadline-warning-days'
11680 days from today's date. If the deadline appears in an entry marked DONE,
11681 it is not shown. The prefix arg NDAYS can be used to test that many
11682 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11683 (interactive "P")
11684 (let* ((org-warn-days
11685 (cond
11686 ((equal ndays '(4)) 100000)
11687 (ndays (prefix-numeric-value ndays))
11688 (t (abs org-deadline-warning-days))))
11689 (case-fold-search nil)
11690 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11691 (callback
11692 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11694 (message "%d deadlines past-due or due within %d days"
11695 (org-occur regexp nil callback)
11696 org-warn-days)))
11698 (defun org-check-before-date (date)
11699 "Check if there are deadlines or scheduled entries before DATE."
11700 (interactive (list (org-read-date)))
11701 (let ((case-fold-search nil)
11702 (regexp (concat "\\<\\(" org-deadline-string
11703 "\\|" org-scheduled-string
11704 "\\) *<\\([^>]+\\)>"))
11705 (callback
11706 (lambda () (time-less-p
11707 (org-time-string-to-time (match-string 2))
11708 (org-time-string-to-time date)))))
11709 (message "%d entries before %s"
11710 (org-occur regexp nil callback) date)))
11712 (defun org-evaluate-time-range (&optional to-buffer)
11713 "Evaluate a time range by computing the difference between start and end.
11714 Normally the result is just printed in the echo area, but with prefix arg
11715 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11716 If the time range is actually in a table, the result is inserted into the
11717 next column.
11718 For time difference computation, a year is assumed to be exactly 365
11719 days in order to avoid rounding problems."
11720 (interactive "P")
11722 (org-clock-update-time-maybe)
11723 (save-excursion
11724 (unless (org-at-date-range-p t)
11725 (goto-char (point-at-bol))
11726 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11727 (if (not (org-at-date-range-p t))
11728 (error "Not at a time-stamp range, and none found in current line")))
11729 (let* ((ts1 (match-string 1))
11730 (ts2 (match-string 2))
11731 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11732 (match-end (match-end 0))
11733 (time1 (org-time-string-to-time ts1))
11734 (time2 (org-time-string-to-time ts2))
11735 (t1 (time-to-seconds time1))
11736 (t2 (time-to-seconds time2))
11737 (diff (abs (- t2 t1)))
11738 (negative (< (- t2 t1) 0))
11739 ;; (ys (floor (* 365 24 60 60)))
11740 (ds (* 24 60 60))
11741 (hs (* 60 60))
11742 (fy "%dy %dd %02d:%02d")
11743 (fy1 "%dy %dd")
11744 (fd "%dd %02d:%02d")
11745 (fd1 "%dd")
11746 (fh "%02d:%02d")
11747 y d h m align)
11748 (if havetime
11749 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11751 d (floor (/ diff ds)) diff (mod diff ds)
11752 h (floor (/ diff hs)) diff (mod diff hs)
11753 m (floor (/ diff 60)))
11754 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11756 d (floor (+ (/ diff ds) 0.5))
11757 h 0 m 0))
11758 (if (not to-buffer)
11759 (message "%s" (org-make-tdiff-string y d h m))
11760 (if (org-at-table-p)
11761 (progn
11762 (goto-char match-end)
11763 (setq align t)
11764 (and (looking-at " *|") (goto-char (match-end 0))))
11765 (goto-char match-end))
11766 (if (looking-at
11767 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11768 (replace-match ""))
11769 (if negative (insert " -"))
11770 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11771 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11772 (insert " " (format fh h m))))
11773 (if align (org-table-align))
11774 (message "Time difference inserted")))))
11776 (defun org-make-tdiff-string (y d h m)
11777 (let ((fmt "")
11778 (l nil))
11779 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11780 l (push y l)))
11781 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11782 l (push d l)))
11783 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11784 l (push h l)))
11785 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11786 l (push m l)))
11787 (apply 'format fmt (nreverse l))))
11789 (defun org-time-string-to-time (s)
11790 (apply 'encode-time (org-parse-time-string s)))
11792 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11793 "Convert a time stamp to an absolute day number.
11794 If there is a specifyer for a cyclic time stamp, get the closest date to
11795 DAYNR.
11796 PREFER and SHOW-ALL are passed through to `org-closest-date'."
11797 (cond
11798 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11799 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11800 daynr
11801 (+ daynr 1000)))
11802 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11803 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11804 (time-to-days (current-time))) (match-string 0 s)
11805 prefer show-all))
11806 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11808 (defun org-days-to-iso-week (days)
11809 "Return the iso week number."
11810 (require 'cal-iso)
11811 (car (calendar-iso-from-absolute days)))
11813 (defun org-small-year-to-year (year)
11814 "Convert 2-digit years into 4-digit years.
11815 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11816 The year 2000 cannot be abbreviated. Any year larger than 99
11817 is returned unchanged."
11818 (if (< year 38)
11819 (setq year (+ 2000 year))
11820 (if (< year 100)
11821 (setq year (+ 1900 year))))
11822 year)
11824 (defun org-time-from-absolute (d)
11825 "Return the time corresponding to date D.
11826 D may be an absolute day number, or a calendar-type list (month day year)."
11827 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11828 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11830 (defun org-calendar-holiday ()
11831 "List of holidays, for Diary display in Org-mode."
11832 (require 'holidays)
11833 (let ((hl (funcall
11834 (if (fboundp 'calendar-check-holidays)
11835 'calendar-check-holidays 'check-calendar-holidays) date)))
11836 (if hl (mapconcat 'identity hl "; "))))
11838 (defun org-diary-sexp-entry (sexp entry date)
11839 "Process a SEXP diary ENTRY for DATE."
11840 (require 'diary-lib)
11841 (let ((result (if calendar-debug-sexp
11842 (let ((stack-trace-on-error t))
11843 (eval (car (read-from-string sexp))))
11844 (condition-case nil
11845 (eval (car (read-from-string sexp)))
11846 (error
11847 (beep)
11848 (message "Bad sexp at line %d in %s: %s"
11849 (org-current-line)
11850 (buffer-file-name) sexp)
11851 (sleep-for 2))))))
11852 (cond ((stringp result) result)
11853 ((and (consp result)
11854 (stringp (cdr result))) (cdr result))
11855 (result entry)
11856 (t nil))))
11858 (defun org-diary-to-ical-string (frombuf)
11859 "Get iCalendar entries from diary entries in buffer FROMBUF.
11860 This uses the icalendar.el library."
11861 (let* ((tmpdir (if (featurep 'xemacs)
11862 (temp-directory)
11863 temporary-file-directory))
11864 (tmpfile (make-temp-name
11865 (expand-file-name "orgics" tmpdir)))
11866 buf rtn b e)
11867 (save-excursion
11868 (set-buffer frombuf)
11869 (icalendar-export-region (point-min) (point-max) tmpfile)
11870 (setq buf (find-buffer-visiting tmpfile))
11871 (set-buffer buf)
11872 (goto-char (point-min))
11873 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11874 (setq b (match-beginning 0)))
11875 (goto-char (point-max))
11876 (if (re-search-backward "^END:VEVENT" nil t)
11877 (setq e (match-end 0)))
11878 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11879 (kill-buffer buf)
11880 (delete-file tmpfile)
11881 rtn))
11883 (defun org-closest-date (start current change prefer show-all)
11884 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11885 When PREFER is `past' return a date that is either CURRENT or past.
11886 When PREFER is `future', return a date that is either CURRENT or future.
11887 When SHOW-ALL is nil, only return the current occurrence of a time stamp."
11888 ;; Make the proper lists from the dates
11889 (catch 'exit
11890 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11891 dn dw sday cday n1 n2 n0
11892 d m y y1 y2 date1 date2 nmonths nm ny m2)
11894 (setq start (org-date-to-gregorian start)
11895 current (org-date-to-gregorian
11896 (if show-all
11897 current
11898 (time-to-days (current-time))))
11899 sday (calendar-absolute-from-gregorian start)
11900 cday (calendar-absolute-from-gregorian current))
11902 (if (<= cday sday) (throw 'exit sday))
11904 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11905 (setq dn (string-to-number (match-string 1 change))
11906 dw (cdr (assoc (match-string 2 change) a1)))
11907 (error "Invalid change specifyer: %s" change))
11908 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11909 (cond
11910 ((eq dw 'day)
11911 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11912 n2 (+ n1 dn)))
11913 ((eq dw 'year)
11914 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11915 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11916 (setq date1 (list m d y1)
11917 n1 (calendar-absolute-from-gregorian date1)
11918 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11919 n2 (calendar-absolute-from-gregorian date2)))
11920 ((eq dw 'month)
11921 ;; approx number of month between the two dates
11922 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11923 ;; How often does dn fit in there?
11924 (setq d (nth 1 start) m (car start) y (nth 2 start)
11925 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11926 m (+ m nm)
11927 ny (floor (/ m 12))
11928 y (+ y ny)
11929 m (- m (* ny 12)))
11930 (while (> m 12) (setq m (- m 12) y (1+ y)))
11931 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11932 (setq m2 (+ m dn) y2 y)
11933 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11934 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11935 (while (<= n2 cday)
11936 (setq n1 n2 m m2 y y2)
11937 (setq m2 (+ m dn) y2 y)
11938 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11939 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11940 ;; Make sure n1 is the earlier date
11941 (setq n0 n1 n1 (min n1 n2) n2 (max n0 n2))
11942 (if show-all
11943 (cond
11944 ((eq prefer 'past) n1)
11945 ((eq prefer 'future) (if (= cday n1) n1 n2))
11946 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11947 (cond
11948 ((eq prefer 'past) n1)
11949 ((eq prefer 'future) (if (= cday n1) n1 n2))
11950 (t (if (= cday n1) n1 n2)))))))
11952 (defun org-date-to-gregorian (date)
11953 "Turn any specification of DATE into a gregorian date for the calendar."
11954 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11955 ((and (listp date) (= (length date) 3)) date)
11956 ((stringp date)
11957 (setq date (org-parse-time-string date))
11958 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11959 ((listp date)
11960 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11962 (defun org-parse-time-string (s &optional nodefault)
11963 "Parse the standard Org-mode time string.
11964 This should be a lot faster than the normal `parse-time-string'.
11965 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11966 hour and minute fields will be nil if not given."
11967 (if (string-match org-ts-regexp0 s)
11968 (list 0
11969 (if (or (match-beginning 8) (not nodefault))
11970 (string-to-number (or (match-string 8 s) "0")))
11971 (if (or (match-beginning 7) (not nodefault))
11972 (string-to-number (or (match-string 7 s) "0")))
11973 (string-to-number (match-string 4 s))
11974 (string-to-number (match-string 3 s))
11975 (string-to-number (match-string 2 s))
11976 nil nil nil)
11977 (make-list 9 0)))
11979 (defun org-timestamp-up (&optional arg)
11980 "Increase the date item at the cursor by one.
11981 If the cursor is on the year, change the year. If it is on the month or
11982 the day, change that.
11983 With prefix ARG, change by that many units."
11984 (interactive "p")
11985 (org-timestamp-change (prefix-numeric-value arg)))
11987 (defun org-timestamp-down (&optional arg)
11988 "Decrease the date item at the cursor by one.
11989 If the cursor is on the year, change the year. If it is on the month or
11990 the day, change that.
11991 With prefix ARG, change by that many units."
11992 (interactive "p")
11993 (org-timestamp-change (- (prefix-numeric-value arg))))
11995 (defun org-timestamp-up-day (&optional arg)
11996 "Increase the date in the time stamp by one day.
11997 With prefix ARG, change that many days."
11998 (interactive "p")
11999 (if (and (not (org-at-timestamp-p t))
12000 (org-on-heading-p))
12001 (org-todo 'up)
12002 (org-timestamp-change (prefix-numeric-value arg) 'day)))
12004 (defun org-timestamp-down-day (&optional arg)
12005 "Decrease the date in the time stamp by one day.
12006 With prefix ARG, change that many days."
12007 (interactive "p")
12008 (if (and (not (org-at-timestamp-p t))
12009 (org-on-heading-p))
12010 (org-todo 'down)
12011 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
12013 (defun org-at-timestamp-p (&optional inactive-ok)
12014 "Determine if the cursor is in or at a timestamp."
12015 (interactive)
12016 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
12017 (pos (point))
12018 (ans (or (looking-at tsr)
12019 (save-excursion
12020 (skip-chars-backward "^[<\n\r\t")
12021 (if (> (point) (point-min)) (backward-char 1))
12022 (and (looking-at tsr)
12023 (> (- (match-end 0) pos) -1))))))
12024 (and ans
12025 (boundp 'org-ts-what)
12026 (setq org-ts-what
12027 (cond
12028 ((= pos (match-beginning 0)) 'bracket)
12029 ((= pos (1- (match-end 0))) 'bracket)
12030 ((org-pos-in-match-range pos 2) 'year)
12031 ((org-pos-in-match-range pos 3) 'month)
12032 ((org-pos-in-match-range pos 7) 'hour)
12033 ((org-pos-in-match-range pos 8) 'minute)
12034 ((or (org-pos-in-match-range pos 4)
12035 (org-pos-in-match-range pos 5)) 'day)
12036 ((and (> pos (or (match-end 8) (match-end 5)))
12037 (< pos (match-end 0)))
12038 (- pos (or (match-end 8) (match-end 5))))
12039 (t 'day))))
12040 ans))
12042 (defun org-toggle-timestamp-type ()
12043 "Toggle the type (<active> or [inactive]) of a time stamp."
12044 (interactive)
12045 (when (org-at-timestamp-p t)
12046 (let ((beg (match-beginning 0)) (end (match-end 0))
12047 (map '((?\[ . "<") (?\] . ">") (?< . "[") (?> . "]"))))
12048 (save-excursion
12049 (goto-char beg)
12050 (while (re-search-forward "[][<>]" end t)
12051 (replace-match (cdr (assoc (char-after (match-beginning 0)) map))
12052 t t)))
12053 (message "Timestamp is now %sactive"
12054 (if (equal (char-after beg) ?<) "" "in")))))
12056 (defun org-timestamp-change (n &optional what)
12057 "Change the date in the time stamp at point.
12058 The date will be changed by N times WHAT. WHAT can be `day', `month',
12059 `year', `minute', `second'. If WHAT is not given, the cursor position
12060 in the timestamp determines what will be changed."
12061 (let ((pos (point))
12062 with-hm inactive
12063 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
12064 org-ts-what
12065 extra rem
12066 ts time time0)
12067 (if (not (org-at-timestamp-p t))
12068 (error "Not at a timestamp"))
12069 (if (and (not what) (eq org-ts-what 'bracket))
12070 (org-toggle-timestamp-type)
12071 (if (and (not what) (not (eq org-ts-what 'day))
12072 org-display-custom-times
12073 (get-text-property (point) 'display)
12074 (not (get-text-property (1- (point)) 'display)))
12075 (setq org-ts-what 'day))
12076 (setq org-ts-what (or what org-ts-what)
12077 inactive (= (char-after (match-beginning 0)) ?\[)
12078 ts (match-string 0))
12079 (replace-match "")
12080 (if (string-match
12081 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
12083 (setq extra (match-string 1 ts)))
12084 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
12085 (setq with-hm t))
12086 (setq time0 (org-parse-time-string ts))
12087 (when (and (eq org-ts-what 'minute)
12088 (eq current-prefix-arg nil))
12089 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
12090 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
12091 (setcar (cdr time0) (+ (nth 1 time0)
12092 (if (> n 0) (- rem) (- dm rem))))))
12093 (setq time
12094 (encode-time (or (car time0) 0)
12095 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
12096 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
12097 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
12098 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
12099 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
12100 (nthcdr 6 time0)))
12101 (when (integerp org-ts-what)
12102 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
12103 (if (eq what 'calendar)
12104 (let ((cal-date (org-get-date-from-calendar)))
12105 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
12106 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
12107 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
12108 (setcar time0 (or (car time0) 0))
12109 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
12110 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
12111 (setq time (apply 'encode-time time0))))
12112 (setq org-last-changed-timestamp
12113 (org-insert-time-stamp time with-hm inactive nil nil extra))
12114 (org-clock-update-time-maybe)
12115 (goto-char pos)
12116 ;; Try to recenter the calendar window, if any
12117 (if (and org-calendar-follow-timestamp-change
12118 (get-buffer-window "*Calendar*" t)
12119 (memq org-ts-what '(day month year)))
12120 (org-recenter-calendar (time-to-days time))))))
12122 (defun org-modify-ts-extra (s pos n dm)
12123 "Change the different parts of the lead-time and repeat fields in timestamp."
12124 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
12125 ng h m new rem)
12126 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
12127 (cond
12128 ((or (org-pos-in-match-range pos 2)
12129 (org-pos-in-match-range pos 3))
12130 (setq m (string-to-number (match-string 3 s))
12131 h (string-to-number (match-string 2 s)))
12132 (if (org-pos-in-match-range pos 2)
12133 (setq h (+ h n))
12134 (setq n (* dm (org-no-warnings (signum n))))
12135 (when (not (= 0 (setq rem (% m dm))))
12136 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
12137 (setq m (+ m n)))
12138 (if (< m 0) (setq m (+ m 60) h (1- h)))
12139 (if (> m 59) (setq m (- m 60) h (1+ h)))
12140 (setq h (min 24 (max 0 h)))
12141 (setq ng 1 new (format "-%02d:%02d" h m)))
12142 ((org-pos-in-match-range pos 6)
12143 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
12144 ((org-pos-in-match-range pos 5)
12145 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
12147 ((org-pos-in-match-range pos 9)
12148 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
12149 ((org-pos-in-match-range pos 8)
12150 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
12152 (when ng
12153 (setq s (concat
12154 (substring s 0 (match-beginning ng))
12156 (substring s (match-end ng))))))
12159 (defun org-recenter-calendar (date)
12160 "If the calendar is visible, recenter it to DATE."
12161 (let* ((win (selected-window))
12162 (cwin (get-buffer-window "*Calendar*" t))
12163 (calendar-move-hook nil))
12164 (when cwin
12165 (select-window cwin)
12166 (calendar-goto-date (if (listp date) date
12167 (calendar-gregorian-from-absolute date)))
12168 (select-window win))))
12170 (defun org-goto-calendar (&optional arg)
12171 "Go to the Emacs calendar at the current date.
12172 If there is a time stamp in the current line, go to that date.
12173 A prefix ARG can be used to force the current date."
12174 (interactive "P")
12175 (let ((tsr org-ts-regexp) diff
12176 (calendar-move-hook nil)
12177 (calendar-view-holidays-initially-flag nil)
12178 (view-calendar-holidays-initially nil)
12179 (calendar-view-diary-initially-flag nil)
12180 (view-diary-entries-initially nil))
12181 (if (or (org-at-timestamp-p)
12182 (save-excursion
12183 (beginning-of-line 1)
12184 (looking-at (concat ".*" tsr))))
12185 (let ((d1 (time-to-days (current-time)))
12186 (d2 (time-to-days
12187 (org-time-string-to-time (match-string 1)))))
12188 (setq diff (- d2 d1))))
12189 (calendar)
12190 (calendar-goto-today)
12191 (if (and diff (not arg)) (calendar-forward-day diff))))
12193 (defun org-get-date-from-calendar ()
12194 "Return a list (month day year) of date at point in calendar."
12195 (with-current-buffer "*Calendar*"
12196 (save-match-data
12197 (calendar-cursor-to-date))))
12199 (defun org-date-from-calendar ()
12200 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
12201 If there is already a time stamp at the cursor position, update it."
12202 (interactive)
12203 (if (org-at-timestamp-p t)
12204 (org-timestamp-change 0 'calendar)
12205 (let ((cal-date (org-get-date-from-calendar)))
12206 (org-insert-time-stamp
12207 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
12209 (defun org-minutes-to-hh:mm-string (m)
12210 "Compute H:MM from a number of minutes."
12211 (let ((h (/ m 60)))
12212 (setq m (- m (* 60 h)))
12213 (format org-time-clocksum-format h m)))
12215 (defun org-hh:mm-string-to-minutes (s)
12216 "Convert a string H:MM to a number of minutes."
12217 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
12218 (+ (* (string-to-number (match-string 1 s)) 60)
12219 (string-to-number (match-string 2 s)))
12222 ;;;; Agenda files
12224 ;;;###autoload
12225 (defun org-iswitchb (&optional arg)
12226 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
12227 With a prefix argument, restrict available to files.
12228 With two prefix arguments, restrict available buffers to agenda files.
12230 Due to some yet unresolved reason, the global function
12231 `iswitchb-mode' needs to be active for this function to work."
12232 (interactive "P")
12233 (require 'iswitchb)
12234 (let ((enabled iswitchb-mode) blist)
12235 (or enabled (iswitchb-mode 1))
12236 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12237 ((equal arg '(16)) (org-buffer-list 'agenda))
12238 (t (org-buffer-list))))
12239 (unwind-protect
12240 (let ((iswitchb-make-buflist-hook
12241 (lambda ()
12242 (setq iswitchb-temp-buflist
12243 (mapcar 'buffer-name blist)))))
12244 (switch-to-buffer
12245 (iswitchb-read-buffer
12246 "Switch-to: " nil t))
12247 (or enabled (iswitchb-mode -1))))))
12249 ;;;###autoload
12250 (defun org-ido-switchb (&optional arg)
12251 "Use `org-ido-completing-read' to prompt for an Org buffer to switch to.
12252 With a prefix argument, restrict available to files.
12253 With two prefix arguments, restrict available buffers to agenda files."
12254 (interactive "P")
12255 (let ((blist (cond ((equal arg '(4)) (org-buffer-list 'files))
12256 ((equal arg '(16)) (org-buffer-list 'agenda))
12257 (t (org-buffer-list)))))
12258 (switch-to-buffer
12259 (org-ido-completing-read "Org buffer: "
12260 (mapcar 'buffer-name blist)
12261 nil t))))
12263 (defun org-buffer-list (&optional predicate exclude-tmp)
12264 "Return a list of Org buffers.
12265 PREDICATE can be `export', `files' or `agenda'.
12267 export restrict the list to Export buffers.
12268 files restrict the list to buffers visiting Org files.
12269 agenda restrict the list to buffers visiting agenda files.
12271 If EXCLUDE-TMP is non-nil, ignore temporary buffers."
12272 (let* ((bfn nil)
12273 (agenda-files (and (eq predicate 'agenda)
12274 (mapcar 'file-truename (org-agenda-files t))))
12275 (filter
12276 (cond
12277 ((eq predicate 'files)
12278 (lambda (b) (with-current-buffer b (eq major-mode 'org-mode))))
12279 ((eq predicate 'export)
12280 (lambda (b) (string-match "\*Org .*Export" (buffer-name b))))
12281 ((eq predicate 'agenda)
12282 (lambda (b)
12283 (with-current-buffer b
12284 (and (eq major-mode 'org-mode)
12285 (setq bfn (buffer-file-name b))
12286 (member (file-truename bfn) agenda-files)))))
12287 (t (lambda (b) (with-current-buffer b
12288 (or (eq major-mode 'org-mode)
12289 (string-match "\*Org .*Export"
12290 (buffer-name b)))))))))
12291 (delq nil
12292 (mapcar
12293 (lambda(b)
12294 (if (and (funcall filter b)
12295 (or (not exclude-tmp)
12296 (not (string-match "tmp" (buffer-name b)))))
12298 nil))
12299 (buffer-list)))))
12301 (defun org-agenda-files (&optional unrestricted archives)
12302 "Get the list of agenda files.
12303 Optional UNRESTRICTED means return the full list even if a restriction
12304 is currently in place.
12305 When ARCHIVES is t, include all archive files hat are really being
12306 used by the agenda files. If ARCHIVE is `ifmode', do this only if
12307 `org-agenda-archives-mode' is t."
12308 (let ((files
12309 (cond
12310 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
12311 ((stringp org-agenda-files) (org-read-agenda-file-list))
12312 ((listp org-agenda-files) org-agenda-files)
12313 (t (error "Invalid value of `org-agenda-files'")))))
12314 (setq files (apply 'append
12315 (mapcar (lambda (f)
12316 (if (file-directory-p f)
12317 (directory-files
12318 f t org-agenda-file-regexp)
12319 (list f)))
12320 files)))
12321 (when org-agenda-skip-unavailable-files
12322 (setq files (delq nil
12323 (mapcar (function
12324 (lambda (file)
12325 (and (file-readable-p file) file)))
12326 files))))
12327 (when (or (eq archives t)
12328 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
12329 (setq files (org-add-archive-files files)))
12330 files))
12332 (defun org-edit-agenda-file-list ()
12333 "Edit the list of agenda files.
12334 Depending on setup, this either uses customize to edit the variable
12335 `org-agenda-files', or it visits the file that is holding the list. In the
12336 latter case, the buffer is set up in a way that saving it automatically kills
12337 the buffer and restores the previous window configuration."
12338 (interactive)
12339 (if (stringp org-agenda-files)
12340 (let ((cw (current-window-configuration)))
12341 (find-file org-agenda-files)
12342 (org-set-local 'org-window-configuration cw)
12343 (org-add-hook 'after-save-hook
12344 (lambda ()
12345 (set-window-configuration
12346 (prog1 org-window-configuration
12347 (kill-buffer (current-buffer))))
12348 (org-install-agenda-files-menu)
12349 (message "New agenda file list installed"))
12350 nil 'local)
12351 (message "%s" (substitute-command-keys
12352 "Edit list and finish with \\[save-buffer]")))
12353 (customize-variable 'org-agenda-files)))
12355 (defun org-store-new-agenda-file-list (list)
12356 "Set new value for the agenda file list and save it correctly."
12357 (if (stringp org-agenda-files)
12358 (let ((f org-agenda-files) b)
12359 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
12360 (with-temp-file f
12361 (insert (mapconcat 'identity list "\n") "\n")))
12362 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
12363 (setq org-agenda-files list)
12364 (customize-save-variable 'org-agenda-files org-agenda-files))))
12366 (defun org-read-agenda-file-list ()
12367 "Read the list of agenda files from a file."
12368 (when (file-directory-p org-agenda-files)
12369 (error "`org-agenda-files' cannot be a single directory"))
12370 (when (stringp org-agenda-files)
12371 (with-temp-buffer
12372 (insert-file-contents org-agenda-files)
12373 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12376 ;;;###autoload
12377 (defun org-cycle-agenda-files ()
12378 "Cycle through the files in `org-agenda-files'.
12379 If the current buffer visits an agenda file, find the next one in the list.
12380 If the current buffer does not, find the first agenda file."
12381 (interactive)
12382 (let* ((fs (org-agenda-files t))
12383 (files (append fs (list (car fs))))
12384 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12385 file)
12386 (unless files (error "No agenda files"))
12387 (catch 'exit
12388 (while (setq file (pop files))
12389 (if (equal (file-truename file) tcf)
12390 (when (car files)
12391 (find-file (car files))
12392 (throw 'exit t))))
12393 (find-file (car fs)))
12394 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12396 (defun org-agenda-file-to-front (&optional to-end)
12397 "Move/add the current file to the top of the agenda file list.
12398 If the file is not present in the list, it is added to the front. If it is
12399 present, it is moved there. With optional argument TO-END, add/move to the
12400 end of the list."
12401 (interactive "P")
12402 (let ((org-agenda-skip-unavailable-files nil)
12403 (file-alist (mapcar (lambda (x)
12404 (cons (file-truename x) x))
12405 (org-agenda-files t)))
12406 (ctf (file-truename buffer-file-name))
12407 x had)
12408 (setq x (assoc ctf file-alist) had x)
12410 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12411 (if to-end
12412 (setq file-alist (append (delq x file-alist) (list x)))
12413 (setq file-alist (cons x (delq x file-alist))))
12414 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12415 (org-install-agenda-files-menu)
12416 (message "File %s to %s of agenda file list"
12417 (if had "moved" "added") (if to-end "end" "front"))))
12419 (defun org-remove-file (&optional file)
12420 "Remove current file from the list of files in variable `org-agenda-files'.
12421 These are the files which are being checked for agenda entries.
12422 Optional argument FILE means, use this file instead of the current."
12423 (interactive)
12424 (let* ((org-agenda-skip-unavailable-files nil)
12425 (file (or file buffer-file-name))
12426 (true-file (file-truename file))
12427 (afile (abbreviate-file-name file))
12428 (files (delq nil (mapcar
12429 (lambda (x)
12430 (if (equal true-file
12431 (file-truename x))
12432 nil x))
12433 (org-agenda-files t)))))
12434 (if (not (= (length files) (length (org-agenda-files t))))
12435 (progn
12436 (org-store-new-agenda-file-list files)
12437 (org-install-agenda-files-menu)
12438 (message "Removed file: %s" afile))
12439 (message "File was not in list: %s (not removed)" afile))))
12441 (defun org-file-menu-entry (file)
12442 (vector file (list 'find-file file) t))
12444 (defun org-check-agenda-file (file)
12445 "Make sure FILE exists. If not, ask user what to do."
12446 (when (not (file-exists-p file))
12447 (message "non-existent file %s. [R]emove from list or [A]bort?"
12448 (abbreviate-file-name file))
12449 (let ((r (downcase (read-char-exclusive))))
12450 (cond
12451 ((equal r ?r)
12452 (org-remove-file file)
12453 (throw 'nextfile t))
12454 (t (error "Abort"))))))
12456 (defun org-get-agenda-file-buffer (file)
12457 "Get a buffer visiting FILE. If the buffer needs to be created, add
12458 it to the list of buffers which might be released later."
12459 (let ((buf (org-find-base-buffer-visiting file)))
12460 (if buf
12461 buf ; just return it
12462 ;; Make a new buffer and remember it
12463 (setq buf (find-file-noselect file))
12464 (if buf (push buf org-agenda-new-buffers))
12465 buf)))
12467 (defun org-release-buffers (blist)
12468 "Release all buffers in list, asking the user for confirmation when needed.
12469 When a buffer is unmodified, it is just killed. When modified, it is saved
12470 \(if the user agrees) and then killed."
12471 (let (buf file)
12472 (while (setq buf (pop blist))
12473 (setq file (buffer-file-name buf))
12474 (when (and (buffer-modified-p buf)
12475 file
12476 (y-or-n-p (format "Save file %s? " file)))
12477 (with-current-buffer buf (save-buffer)))
12478 (kill-buffer buf))))
12480 (defun org-prepare-agenda-buffers (files)
12481 "Create buffers for all agenda files, protect archived trees and comments."
12482 (interactive)
12483 (let ((pa '(:org-archived t))
12484 (pc '(:org-comment t))
12485 (pall '(:org-archived t :org-comment t))
12486 (inhibit-read-only t)
12487 (rea (concat ":" org-archive-tag ":"))
12488 bmp file re)
12489 (save-excursion
12490 (save-restriction
12491 (while (setq file (pop files))
12492 (if (bufferp file)
12493 (set-buffer file)
12494 (org-check-agenda-file file)
12495 (set-buffer (org-get-agenda-file-buffer file)))
12496 (widen)
12497 (setq bmp (buffer-modified-p))
12498 (org-refresh-category-properties)
12499 (setq org-todo-keywords-for-agenda
12500 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12501 (setq org-done-keywords-for-agenda
12502 (append org-done-keywords-for-agenda org-done-keywords))
12503 (setq org-todo-keyword-alist-for-agenda
12504 (append org-todo-keyword-alist-for-agenda org-todo-key-alist))
12505 (setq org-tag-alist-for-agenda
12506 (append org-tag-alist-for-agenda org-tag-alist))
12508 (save-excursion
12509 (remove-text-properties (point-min) (point-max) pall)
12510 (when org-agenda-skip-archived-trees
12511 (goto-char (point-min))
12512 (while (re-search-forward rea nil t)
12513 (if (org-on-heading-p t)
12514 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12515 (goto-char (point-min))
12516 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12517 (while (re-search-forward re nil t)
12518 (add-text-properties
12519 (match-beginning 0) (org-end-of-subtree t) pc)))
12520 (set-buffer-modified-p bmp))))
12521 (setq org-todo-keyword-alist-for-agenda
12522 (org-uniquify org-todo-keyword-alist-for-agenda)
12523 org-tag-alist-for-agenda (org-uniquify org-tag-alist-for-agenda))))
12525 ;;;; Embedded LaTeX
12527 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12528 "Keymap for the minor `org-cdlatex-mode'.")
12530 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12531 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12532 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12533 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12534 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12536 (defvar org-cdlatex-texmathp-advice-is-done nil
12537 "Flag remembering if we have applied the advice to texmathp already.")
12539 (define-minor-mode org-cdlatex-mode
12540 "Toggle the minor `org-cdlatex-mode'.
12541 This mode supports entering LaTeX environment and math in LaTeX fragments
12542 in Org-mode.
12543 \\{org-cdlatex-mode-map}"
12544 nil " OCDL" nil
12545 (when org-cdlatex-mode (require 'cdlatex))
12546 (unless org-cdlatex-texmathp-advice-is-done
12547 (setq org-cdlatex-texmathp-advice-is-done t)
12548 (defadvice texmathp (around org-math-always-on activate)
12549 "Always return t in org-mode buffers.
12550 This is because we want to insert math symbols without dollars even outside
12551 the LaTeX math segments. If Orgmode thinks that point is actually inside
12552 an embedded LaTeX fragment, let texmathp do its job.
12553 \\[org-cdlatex-mode-map]"
12554 (interactive)
12555 (let (p)
12556 (cond
12557 ((not (org-mode-p)) ad-do-it)
12558 ((eq this-command 'cdlatex-math-symbol)
12559 (setq ad-return-value t
12560 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12562 (let ((p (org-inside-LaTeX-fragment-p)))
12563 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12564 (setq ad-return-value t
12565 texmathp-why '("Org-mode embedded math" . 0))
12566 (if p ad-do-it)))))))))
12568 (defun turn-on-org-cdlatex ()
12569 "Unconditionally turn on `org-cdlatex-mode'."
12570 (org-cdlatex-mode 1))
12572 (defun org-inside-LaTeX-fragment-p ()
12573 "Test if point is inside a LaTeX fragment.
12574 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12575 sequence appearing also before point.
12576 Even though the matchers for math are configurable, this function assumes
12577 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12578 delimiters are skipped when they have been removed by customization.
12579 The return value is nil, or a cons cell with the delimiter and
12580 and the position of this delimiter.
12582 This function does a reasonably good job, but can locally be fooled by
12583 for example currency specifications. For example it will assume being in
12584 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12585 fragments that are properly closed, but during editing, we have to live
12586 with the uncertainty caused by missing closing delimiters. This function
12587 looks only before point, not after."
12588 (catch 'exit
12589 (let ((pos (point))
12590 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12591 (lim (progn
12592 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12593 (point)))
12594 dd-on str (start 0) m re)
12595 (goto-char pos)
12596 (when dodollar
12597 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12598 re (nth 1 (assoc "$" org-latex-regexps)))
12599 (while (string-match re str start)
12600 (cond
12601 ((= (match-end 0) (length str))
12602 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12603 ((= (match-end 0) (- (length str) 5))
12604 (throw 'exit nil))
12605 (t (setq start (match-end 0))))))
12606 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12607 (goto-char pos)
12608 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12609 (and (match-beginning 2) (throw 'exit nil))
12610 ;; count $$
12611 (while (re-search-backward "\\$\\$" lim t)
12612 (setq dd-on (not dd-on)))
12613 (goto-char pos)
12614 (if dd-on (cons "$$" m))))))
12617 (defun org-try-cdlatex-tab ()
12618 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12619 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12620 - inside a LaTeX fragment, or
12621 - after the first word in a line, where an abbreviation expansion could
12622 insert a LaTeX environment."
12623 (when org-cdlatex-mode
12624 (cond
12625 ((save-excursion
12626 (skip-chars-backward "a-zA-Z0-9*")
12627 (skip-chars-backward " \t")
12628 (bolp))
12629 (cdlatex-tab) t)
12630 ((org-inside-LaTeX-fragment-p)
12631 (cdlatex-tab) t)
12632 (t nil))))
12634 (defun org-cdlatex-underscore-caret (&optional arg)
12635 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12636 Revert to the normal definition outside of these fragments."
12637 (interactive "P")
12638 (if (org-inside-LaTeX-fragment-p)
12639 (call-interactively 'cdlatex-sub-superscript)
12640 (let (org-cdlatex-mode)
12641 (call-interactively (key-binding (vector last-input-event))))))
12643 (defun org-cdlatex-math-modify (&optional arg)
12644 "Execute `cdlatex-math-modify' in LaTeX fragments.
12645 Revert to the normal definition outside of these fragments."
12646 (interactive "P")
12647 (if (org-inside-LaTeX-fragment-p)
12648 (call-interactively 'cdlatex-math-modify)
12649 (let (org-cdlatex-mode)
12650 (call-interactively (key-binding (vector last-input-event))))))
12652 (defvar org-latex-fragment-image-overlays nil
12653 "List of overlays carrying the images of latex fragments.")
12654 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12656 (defun org-remove-latex-fragment-image-overlays ()
12657 "Remove all overlays with LaTeX fragment images in current buffer."
12658 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12659 (setq org-latex-fragment-image-overlays nil))
12661 (defun org-preview-latex-fragment (&optional subtree)
12662 "Preview the LaTeX fragment at point, or all locally or globally.
12663 If the cursor is in a LaTeX fragment, create the image and overlay
12664 it over the source code. If there is no fragment at point, display
12665 all fragments in the current text, from one headline to the next. With
12666 prefix SUBTREE, display all fragments in the current subtree. With a
12667 double prefix `C-u C-u', or when the cursor is before the first headline,
12668 display all fragments in the buffer.
12669 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12670 (interactive "P")
12671 (org-remove-latex-fragment-image-overlays)
12672 (save-excursion
12673 (save-restriction
12674 (let (beg end at msg)
12675 (cond
12676 ((or (equal subtree '(16))
12677 (not (save-excursion
12678 (re-search-backward (concat "^" outline-regexp) nil t))))
12679 (setq beg (point-min) end (point-max)
12680 msg "Creating images for buffer...%s"))
12681 ((equal subtree '(4))
12682 (org-back-to-heading)
12683 (setq beg (point) end (org-end-of-subtree t)
12684 msg "Creating images for subtree...%s"))
12686 (if (setq at (org-inside-LaTeX-fragment-p))
12687 (goto-char (max (point-min) (- (cdr at) 2)))
12688 (org-back-to-heading))
12689 (setq beg (point) end (progn (outline-next-heading) (point))
12690 msg (if at "Creating image...%s"
12691 "Creating images for entry...%s"))))
12692 (message msg "")
12693 (narrow-to-region beg end)
12694 (goto-char beg)
12695 (org-format-latex
12696 (concat "ltxpng/" (file-name-sans-extension
12697 (file-name-nondirectory
12698 buffer-file-name)))
12699 default-directory 'overlays msg at 'forbuffer)
12700 (message msg "done. Use `C-c C-c' to remove images.")))))
12702 (defvar org-latex-regexps
12703 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12704 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12705 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12706 ("$1" "\\([^$]\\)\\(\\$[^ \r\n,;.$]\\$\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12707 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([- .,?;:'\")\000]\\|$\\)" 2 nil)
12708 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12709 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12710 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12711 "Regular expressions for matching embedded LaTeX.")
12713 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12714 "Replace LaTeX fragments with links to an image, and produce images."
12715 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12716 (let* ((prefixnodir (file-name-nondirectory prefix))
12717 (absprefix (expand-file-name prefix dir))
12718 (todir (file-name-directory absprefix))
12719 (opt org-format-latex-options)
12720 (matchers (plist-get opt :matchers))
12721 (re-list org-latex-regexps)
12722 (cnt 0) txt link beg end re e checkdir
12723 m n block linkfile movefile ov)
12724 ;; Check if there are old images files with this prefix, and remove them
12725 (when (file-directory-p todir)
12726 (mapc 'delete-file
12727 (directory-files
12728 todir 'full
12729 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12730 ;; Check the different regular expressions
12731 (while (setq e (pop re-list))
12732 (setq m (car e) re (nth 1 e) n (nth 2 e)
12733 block (if (nth 3 e) "\n\n" ""))
12734 (when (member m matchers)
12735 (goto-char (point-min))
12736 (while (re-search-forward re nil t)
12737 (when (and (or (not at) (equal (cdr at) (match-beginning n)))
12738 (not (get-text-property (match-beginning n)
12739 'org-protected)))
12740 (setq txt (match-string n)
12741 beg (match-beginning n) end (match-end n)
12742 cnt (1+ cnt)
12743 linkfile (format "%s_%04d.png" prefix cnt)
12744 movefile (format "%s_%04d.png" absprefix cnt)
12745 link (concat block "[[file:" linkfile "]]" block))
12746 (if msg (message msg cnt))
12747 (goto-char beg)
12748 (unless checkdir ; make sure the directory exists
12749 (setq checkdir t)
12750 (or (file-directory-p todir) (make-directory todir)))
12751 (org-create-formula-image
12752 txt movefile opt forbuffer)
12753 (if overlays
12754 (progn
12755 (setq ov (org-make-overlay beg end))
12756 (if (featurep 'xemacs)
12757 (progn
12758 (org-overlay-put ov 'invisible t)
12759 (org-overlay-put
12760 ov 'end-glyph
12761 (make-glyph (vector 'png :file movefile))))
12762 (org-overlay-put
12763 ov 'display
12764 (list 'image :type 'png :file movefile :ascent 'center)))
12765 (push ov org-latex-fragment-image-overlays)
12766 (goto-char end))
12767 (delete-region beg end)
12768 (insert link))))))))
12770 ;; This function borrows from Ganesh Swami's latex2png.el
12771 (defun org-create-formula-image (string tofile options buffer)
12772 (let* ((tmpdir (if (featurep 'xemacs)
12773 (temp-directory)
12774 temporary-file-directory))
12775 (texfilebase (make-temp-name
12776 (expand-file-name "orgtex" tmpdir)))
12777 (texfile (concat texfilebase ".tex"))
12778 (dvifile (concat texfilebase ".dvi"))
12779 (pngfile (concat texfilebase ".png"))
12780 (fnh (if (featurep 'xemacs)
12781 (font-height (get-face-font 'default))
12782 (face-attribute 'default :height nil)))
12783 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12784 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12785 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12786 "Black"))
12787 (bg (or (plist-get options (if buffer :background :html-background))
12788 "Transparent")))
12789 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12790 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12791 (with-temp-file texfile
12792 (insert org-format-latex-header
12793 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12794 (let ((dir default-directory))
12795 (condition-case nil
12796 (progn
12797 (cd tmpdir)
12798 (call-process "latex" nil nil nil texfile))
12799 (error nil))
12800 (cd dir))
12801 (if (not (file-exists-p dvifile))
12802 (progn (message "Failed to create dvi file from %s" texfile) nil)
12803 (condition-case nil
12804 (call-process "dvipng" nil nil nil
12805 "-E" "-fg" fg "-bg" bg
12806 "-D" dpi
12807 ;;"-x" scale "-y" scale
12808 "-T" "tight"
12809 "-o" pngfile
12810 dvifile)
12811 (error nil))
12812 (if (not (file-exists-p pngfile))
12813 (progn (message "Failed to create png file from %s" texfile) nil)
12814 ;; Use the requested file name and clean up
12815 (copy-file pngfile tofile 'replace)
12816 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12817 (delete-file (concat texfilebase e)))
12818 pngfile))))
12820 (defun org-dvipng-color (attr)
12821 "Return an rgb color specification for dvipng."
12822 (apply 'format "rgb %s %s %s"
12823 (mapcar 'org-normalize-color
12824 (color-values (face-attribute 'default attr nil)))))
12826 (defun org-normalize-color (value)
12827 "Return string to be used as color value for an RGB component."
12828 (format "%g" (/ value 65535.0)))
12830 ;;;; Key bindings
12832 ;; Make `C-c C-x' a prefix key
12833 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12835 ;; TAB key with modifiers
12836 (org-defkey org-mode-map "\C-i" 'org-cycle)
12837 (org-defkey org-mode-map [(tab)] 'org-cycle)
12838 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12839 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12840 (org-defkey org-mode-map "\M-\t" 'org-complete)
12841 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12842 ;; The following line is necessary under Suse GNU/Linux
12843 (unless (featurep 'xemacs)
12844 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12845 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12846 (define-key org-mode-map [backtab] 'org-shifttab)
12848 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12849 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12850 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12852 ;; Cursor keys with modifiers
12853 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12854 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12855 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12856 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12858 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12859 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12860 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12861 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12863 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12864 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12865 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12866 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12868 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12869 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12871 ;;; Extra keys for tty access.
12872 ;; We only set them when really needed because otherwise the
12873 ;; menus don't show the simple keys
12875 (when (or org-use-extra-keys
12876 (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12877 (not window-system))
12878 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12879 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12880 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12881 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12882 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12883 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12884 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12885 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12886 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12887 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12888 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12889 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12890 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12891 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12892 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12893 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12894 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12895 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12896 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12897 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12898 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12899 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12901 ;; All the other keys
12903 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12904 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12905 (if (boundp 'narrow-map)
12906 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12907 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12908 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12909 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12910 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12911 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12912 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12913 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12914 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12915 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12916 (org-defkey org-mode-map "\C-c\C-q" 'org-set-tags-command)
12917 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12918 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12919 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12920 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12921 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12922 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12923 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12924 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12925 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12926 (org-defkey org-mode-map [(control return)] 'org-insert-heading-respect-content)
12927 (org-defkey org-mode-map [(shift control return)] 'org-insert-todo-heading-respect-content)
12928 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12929 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12930 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12931 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12932 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12933 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12934 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12935 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12936 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12937 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12938 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12939 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12940 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12941 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12942 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12943 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12944 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12945 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12946 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12947 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12948 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12949 (org-defkey org-mode-map "\C-c^" 'org-sort)
12950 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12951 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12952 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12953 (org-defkey org-mode-map "\C-m" 'org-return)
12954 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12955 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12956 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12957 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12958 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12959 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12960 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12961 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12962 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12963 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12964 (org-defkey org-mode-map "\C-c\C-a" 'org-attach)
12965 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12966 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12967 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12968 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12969 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12970 (org-defkey org-mode-map "\C-c\C-xf" 'org-footnote-action)
12972 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12973 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12974 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12975 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12977 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12978 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12979 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12980 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12981 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12982 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12983 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12984 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12985 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12986 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12987 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12988 (org-defkey org-mode-map "\C-c\C-xo" 'org-toggle-ordered-property)
12989 (org-defkey org-mode-map "\C-c\C-xi" 'org-insert-columns-dblock)
12991 (org-defkey org-mode-map "\C-c\C-x." 'org-timer)
12992 (org-defkey org-mode-map "\C-c\C-x-" 'org-timer-item)
12993 (org-defkey org-mode-map "\C-c\C-x0" 'org-timer-start)
12994 (org-defkey org-mode-map "\C-c\C-x," 'org-timer-pause-or-continue)
12996 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12998 (when (featurep 'xemacs)
12999 (org-defkey org-mode-map 'button3 'popup-mode-menu))
13001 (defvar org-table-auto-blank-field) ; defined in org-table.el
13002 (defun org-self-insert-command (N)
13003 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
13004 If the cursor is in a table looking at whitespace, the whitespace is
13005 overwritten, and the table is not marked as requiring realignment."
13006 (interactive "p")
13007 (if (and (org-table-p)
13008 (progn
13009 ;; check if we blank the field, and if that triggers align
13010 (and (featurep 'org-table) org-table-auto-blank-field
13011 (member last-command
13012 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
13013 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
13014 ;; got extra space, this field does not determine column width
13015 (let (org-table-may-need-update) (org-table-blank-field))
13016 ;; no extra space, this field may determine column width
13017 (org-table-blank-field)))
13019 (eq N 1)
13020 (looking-at "[^|\n]* |"))
13021 (let (org-table-may-need-update)
13022 (goto-char (1- (match-end 0)))
13023 (delete-backward-char 1)
13024 (goto-char (match-beginning 0))
13025 (self-insert-command N))
13026 (setq org-table-may-need-update t)
13027 (self-insert-command N)
13028 (org-fix-tags-on-the-fly)))
13030 (defun org-fix-tags-on-the-fly ()
13031 (when (and (equal (char-after (point-at-bol)) ?*)
13032 (org-on-heading-p))
13033 (org-align-tags-here org-tags-column)))
13035 (defun org-delete-backward-char (N)
13036 "Like `delete-backward-char', insert whitespace at field end in tables.
13037 When deleting backwards, in tables this function will insert whitespace in
13038 front of the next \"|\" separator, to keep the table aligned. The table will
13039 still be marked for re-alignment if the field did fill the entire column,
13040 because, in this case the deletion might narrow the column."
13041 (interactive "p")
13042 (if (and (org-table-p)
13043 (eq N 1)
13044 (string-match "|" (buffer-substring (point-at-bol) (point)))
13045 (looking-at ".*?|"))
13046 (let ((pos (point))
13047 (noalign (looking-at "[^|\n\r]* |"))
13048 (c org-table-may-need-update))
13049 (backward-delete-char N)
13050 (skip-chars-forward "^|")
13051 (insert " ")
13052 (goto-char (1- pos))
13053 ;; noalign: if there were two spaces at the end, this field
13054 ;; does not determine the width of the column.
13055 (if noalign (setq org-table-may-need-update c)))
13056 (backward-delete-char N)
13057 (org-fix-tags-on-the-fly)))
13059 (defun org-delete-char (N)
13060 "Like `delete-char', but insert whitespace at field end in tables.
13061 When deleting characters, in tables this function will insert whitespace in
13062 front of the next \"|\" separator, to keep the table aligned. The table will
13063 still be marked for re-alignment if the field did fill the entire column,
13064 because, in this case the deletion might narrow the column."
13065 (interactive "p")
13066 (if (and (org-table-p)
13067 (not (bolp))
13068 (not (= (char-after) ?|))
13069 (eq N 1))
13070 (if (looking-at ".*?|")
13071 (let ((pos (point))
13072 (noalign (looking-at "[^|\n\r]* |"))
13073 (c org-table-may-need-update))
13074 (replace-match (concat
13075 (substring (match-string 0) 1 -1)
13076 " |"))
13077 (goto-char pos)
13078 ;; noalign: if there were two spaces at the end, this field
13079 ;; does not determine the width of the column.
13080 (if noalign (setq org-table-may-need-update c)))
13081 (delete-char N))
13082 (delete-char N)
13083 (org-fix-tags-on-the-fly)))
13085 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
13086 (put 'org-self-insert-command 'delete-selection t)
13087 (put 'orgtbl-self-insert-command 'delete-selection t)
13088 (put 'org-delete-char 'delete-selection 'supersede)
13089 (put 'org-delete-backward-char 'delete-selection 'supersede)
13090 (put 'org-yank 'delete-selection 'yank)
13092 ;; Make `flyspell-mode' delay after some commands
13093 (put 'org-self-insert-command 'flyspell-delayed t)
13094 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
13095 (put 'org-delete-char 'flyspell-delayed t)
13096 (put 'org-delete-backward-char 'flyspell-delayed t)
13098 ;; Make pabbrev-mode expand after org-mode commands
13099 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
13100 (put 'orgtbl-self-insert-command 'pabbrev-expand-after-command t)
13102 ;; How to do this: Measure non-white length of current string
13103 ;; If equal to column width, we should realign.
13105 (defun org-remap (map &rest commands)
13106 "In MAP, remap the functions given in COMMANDS.
13107 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
13108 (let (new old)
13109 (while commands
13110 (setq old (pop commands) new (pop commands))
13111 (if (fboundp 'command-remapping)
13112 (org-defkey map (vector 'remap old) new)
13113 (substitute-key-definition old new map global-map)))))
13115 (when (eq org-enable-table-editor 'optimized)
13116 ;; If the user wants maximum table support, we need to hijack
13117 ;; some standard editing functions
13118 (org-remap org-mode-map
13119 'self-insert-command 'org-self-insert-command
13120 'delete-char 'org-delete-char
13121 'delete-backward-char 'org-delete-backward-char)
13122 (org-defkey org-mode-map "|" 'org-force-self-insert))
13124 (defun org-modifier-cursor-error ()
13125 "Throw an error, a modified cursor command was applied in wrong context."
13126 (error "This command is active in special context like tables, headlines or items"))
13128 (defun org-shiftselect-error ()
13129 "Throw an error because Shift-Cursor command was applied in wrong context."
13130 (if (and (boundp 'shift-select-mode) shift-select-mode)
13131 (error "To use shift-selection with Org-mode, customize `org-support-shift-select'.")
13132 (error "This command works only in special context like headlines or timestamps.")))
13134 (defun org-call-for-shift-select (cmd)
13135 (let ((this-command-keys-shift-translated t))
13136 (call-interactively cmd)))
13138 (defun org-shifttab (&optional arg)
13139 "Global visibility cycling or move to previous table field.
13140 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
13141 on context.
13142 See the individual commands for more information."
13143 (interactive "P")
13144 (cond
13145 ((org-at-table-p) (call-interactively 'org-table-previous-field))
13146 ((integerp arg)
13147 (message "Content view to level: %d" arg)
13148 (org-content (prefix-numeric-value arg))
13149 (setq org-cycle-global-status 'overview))
13150 (t (call-interactively 'org-global-cycle))))
13152 (defun org-shiftmetaleft ()
13153 "Promote subtree or delete table column.
13154 Calls `org-promote-subtree', `org-outdent-item',
13155 or `org-table-delete-column', depending on context.
13156 See the individual commands for more information."
13157 (interactive)
13158 (cond
13159 ((org-at-table-p) (call-interactively 'org-table-delete-column))
13160 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
13161 ((org-at-item-p) (call-interactively 'org-outdent-item))
13162 (t (org-modifier-cursor-error))))
13164 (defun org-shiftmetaright ()
13165 "Demote subtree or insert table column.
13166 Calls `org-demote-subtree', `org-indent-item',
13167 or `org-table-insert-column', depending on context.
13168 See the individual commands for more information."
13169 (interactive)
13170 (cond
13171 ((org-at-table-p) (call-interactively 'org-table-insert-column))
13172 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
13173 ((org-at-item-p) (call-interactively 'org-indent-item))
13174 (t (org-modifier-cursor-error))))
13176 (defun org-shiftmetaup (&optional arg)
13177 "Move subtree up or kill table row.
13178 Calls `org-move-subtree-up' or `org-table-kill-row' or
13179 `org-move-item-up' depending on context. See the individual commands
13180 for more information."
13181 (interactive "P")
13182 (cond
13183 ((org-at-table-p) (call-interactively 'org-table-kill-row))
13184 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13185 ((org-at-item-p) (call-interactively 'org-move-item-up))
13186 (t (org-modifier-cursor-error))))
13187 (defun org-shiftmetadown (&optional arg)
13188 "Move subtree down or insert table row.
13189 Calls `org-move-subtree-down' or `org-table-insert-row' or
13190 `org-move-item-down', depending on context. See the individual
13191 commands for more information."
13192 (interactive "P")
13193 (cond
13194 ((org-at-table-p) (call-interactively 'org-table-insert-row))
13195 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13196 ((org-at-item-p) (call-interactively 'org-move-item-down))
13197 (t (org-modifier-cursor-error))))
13199 (defun org-metaleft (&optional arg)
13200 "Promote heading or move table column to left.
13201 Calls `org-do-promote' or `org-table-move-column', depending on context.
13202 With no specific context, calls the Emacs default `backward-word'.
13203 See the individual commands for more information."
13204 (interactive "P")
13205 (cond
13206 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
13207 ((or (org-on-heading-p) (org-region-active-p))
13208 (call-interactively 'org-do-promote))
13209 ((org-at-item-p) (call-interactively 'org-outdent-item))
13210 (t (call-interactively 'backward-word))))
13212 (defun org-metaright (&optional arg)
13213 "Demote subtree or move table column to right.
13214 Calls `org-do-demote' or `org-table-move-column', depending on context.
13215 With no specific context, calls the Emacs default `forward-word'.
13216 See the individual commands for more information."
13217 (interactive "P")
13218 (cond
13219 ((org-at-table-p) (call-interactively 'org-table-move-column))
13220 ((or (org-on-heading-p) (org-region-active-p))
13221 (call-interactively 'org-do-demote))
13222 ((org-at-item-p) (call-interactively 'org-indent-item))
13223 (t (call-interactively 'forward-word))))
13225 (defun org-metaup (&optional arg)
13226 "Move subtree up or move table row up.
13227 Calls `org-move-subtree-up' or `org-table-move-row' or
13228 `org-move-item-up', depending on context. See the individual commands
13229 for more information."
13230 (interactive "P")
13231 (cond
13232 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
13233 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
13234 ((org-at-item-p) (call-interactively 'org-move-item-up))
13235 (t (transpose-lines 1) (beginning-of-line -1))))
13237 (defun org-metadown (&optional arg)
13238 "Move subtree down or move table row down.
13239 Calls `org-move-subtree-down' or `org-table-move-row' or
13240 `org-move-item-down', depending on context. See the individual
13241 commands for more information."
13242 (interactive "P")
13243 (cond
13244 ((org-at-table-p) (call-interactively 'org-table-move-row))
13245 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
13246 ((org-at-item-p) (call-interactively 'org-move-item-down))
13247 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
13249 (defun org-shiftup (&optional arg)
13250 "Increase item in timestamp or increase priority of current headline.
13251 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
13252 depending on context. See the individual commands for more information."
13253 (interactive "P")
13254 (cond
13255 ((and org-support-shift-select (org-region-active-p))
13256 (org-call-for-shift-select 'previous-line))
13257 ((org-at-timestamp-p t)
13258 (call-interactively (if org-edit-timestamp-down-means-later
13259 'org-timestamp-down 'org-timestamp-up)))
13260 ((and (not (eq org-support-shift-select 'always))
13261 (org-on-heading-p))
13262 (call-interactively 'org-priority-up))
13263 ((and (not org-support-shift-select) (org-at-item-p))
13264 (call-interactively 'org-previous-item))
13265 ((org-clocktable-try-shift 'up arg))
13266 (org-support-shift-select
13267 (org-call-for-shift-select 'previous-line))
13268 (t (org-shiftselect-error))))
13270 (defun org-shiftdown (&optional arg)
13271 "Decrease item in timestamp or decrease priority of current headline.
13272 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
13273 depending on context. See the individual commands for more information."
13274 (interactive "P")
13275 (cond
13276 ((and org-support-shift-select (org-region-active-p))
13277 (org-call-for-shift-select 'next-line))
13278 ((org-at-timestamp-p t)
13279 (call-interactively (if org-edit-timestamp-down-means-later
13280 'org-timestamp-up 'org-timestamp-down)))
13281 ((and (not (eq org-support-shift-select 'always))
13282 (org-on-heading-p))
13283 (call-interactively 'org-priority-down))
13284 ((and (not org-support-shift-select) (org-at-item-p))
13285 (call-interactively 'org-next-item))
13286 ((org-clocktable-try-shift 'down arg))
13287 (org-support-shift-select
13288 (org-call-for-shift-select 'next-line))
13289 (t (org-shiftselect-error))))
13291 (defun org-shiftright (&optional arg)
13292 "Cycle the thing at point or in the current line, depending on context.
13293 Depending on context, this does one of the following:
13295 - switch a timestamp at point one day into the future
13296 - on a headline, switch to the next TODO keyword.
13297 - on an item, switch entire list to the next bullet type
13298 - on a property line, switch to the next allowed value
13299 - on a clocktable definition line, move time block into the future"
13300 (interactive "P")
13301 (cond
13302 ((and org-support-shift-select (org-region-active-p))
13303 (org-call-for-shift-select 'forward-char))
13304 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
13305 ((and (not (eq org-support-shift-select 'always))
13306 (org-on-heading-p))
13307 (org-call-with-arg 'org-todo 'right))
13308 ((or (and org-support-shift-select
13309 (not (eq org-support-shift-select 'always))
13310 (org-at-item-bullet-p))
13311 (and (not org-support-shift-select) (org-at-item-p)))
13312 (org-call-with-arg 'org-cycle-list-bullet nil))
13313 ((and (not (eq org-support-shift-select 'always))
13314 (org-at-property-p))
13315 (call-interactively 'org-property-next-allowed-value))
13316 ((org-clocktable-try-shift 'right arg))
13317 (org-support-shift-select
13318 (org-call-for-shift-select 'forward-char))
13319 (t (org-shiftselect-error))))
13321 (defun org-shiftleft (&optional arg)
13322 "Cycle the thing at point or in the current line, depending on context.
13323 Depending on context, this does one of the following:
13325 - switch a timestamp at point one day into the past
13326 - on a headline, switch to the previous TODO keyword.
13327 - on an item, switch entire list to the previous bullet type
13328 - on a property line, switch to the previous allowed value
13329 - on a clocktable definition line, move time block into the past"
13330 (interactive "P")
13331 (cond
13332 ((and org-support-shift-select (org-region-active-p))
13333 (org-call-for-shift-select 'backward-char))
13334 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
13335 ((and (not (eq org-support-shift-select 'always))
13336 (org-on-heading-p))
13337 (org-call-with-arg 'org-todo 'left))
13338 ((or (and org-support-shift-select
13339 (not (eq org-support-shift-select 'always))
13340 (org-at-item-bullet-p))
13341 (and (not org-support-shift-select) (org-at-item-p)))
13342 (org-call-with-arg 'org-cycle-list-bullet 'previous))
13343 ((and (not (eq org-support-shift-select 'always))
13344 (org-at-property-p))
13345 (call-interactively 'org-property-previous-allowed-value))
13346 ((org-clocktable-try-shift 'left arg))
13347 (org-support-shift-select
13348 (org-call-for-shift-select 'backward-char))
13349 (t (org-shiftselect-error))))
13351 (defun org-shiftcontrolright ()
13352 "Switch to next TODO set."
13353 (interactive)
13354 (cond
13355 ((and org-support-shift-select (org-region-active-p))
13356 (org-call-for-shift-select 'forward-word))
13357 ((and (not (eq org-support-shift-select 'always))
13358 (org-on-heading-p))
13359 (org-call-with-arg 'org-todo 'nextset))
13360 (org-support-shift-select
13361 (org-call-for-shift-select 'forward-word))
13362 (t (org-shiftselect-error))))
13364 (defun org-shiftcontrolleft ()
13365 "Switch to previous TODO set."
13366 (interactive)
13367 (cond
13368 ((and org-support-shift-select (org-region-active-p))
13369 (org-call-for-shift-select 'backward-word))
13370 ((and (not (eq org-support-shift-select 'always))
13371 (org-on-heading-p))
13372 (org-call-with-arg 'org-todo 'previousset))
13373 (org-support-shift-select
13374 (org-call-for-shift-select 'backward-word))
13375 (t (org-shiftselect-error))))
13377 (defun org-ctrl-c-ret ()
13378 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
13379 (interactive)
13380 (cond
13381 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
13382 (t (call-interactively 'org-insert-heading))))
13384 (defun org-copy-special ()
13385 "Copy region in table or copy current subtree.
13386 Calls `org-table-copy' or `org-copy-subtree', depending on context.
13387 See the individual commands for more information."
13388 (interactive)
13389 (call-interactively
13390 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
13392 (defun org-cut-special ()
13393 "Cut region in table or cut current subtree.
13394 Calls `org-table-copy' or `org-cut-subtree', depending on context.
13395 See the individual commands for more information."
13396 (interactive)
13397 (call-interactively
13398 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
13400 (defun org-paste-special (arg)
13401 "Paste rectangular region into table, or past subtree relative to level.
13402 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
13403 See the individual commands for more information."
13404 (interactive "P")
13405 (if (org-at-table-p)
13406 (org-table-paste-rectangle)
13407 (org-paste-subtree arg)))
13409 (defun org-edit-special ()
13410 "Call a special editor for the stuff at point.
13411 When at a table, call the formula editor with `org-table-edit-formulas'.
13412 When at the first line of an src example, call `org-edit-src-code'.
13413 When in an #+include line, visit the include file. Otherwise call
13414 `ffap' to visit the file at point."
13415 (interactive)
13416 (cond
13417 ((org-at-table-p)
13418 (call-interactively 'org-table-edit-formulas))
13419 ((save-excursion
13420 (beginning-of-line 1)
13421 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
13422 (find-file (org-trim (match-string 1))))
13423 ((org-edit-src-code))
13424 ((org-edit-fixed-width-region))
13425 (t (call-interactively 'ffap))))
13427 (defun org-ctrl-c-ctrl-c (&optional arg)
13428 "Set tags in headline, or update according to changed information at point.
13430 This command does many different things, depending on context:
13432 - If the cursor is in a headline, prompt for tags and insert them
13433 into the current line, aligned to `org-tags-column'. When called
13434 with prefix arg, realign all tags in the current buffer.
13436 - If the cursor is in one of the special #+KEYWORD lines, this
13437 triggers scanning the buffer for these lines and updating the
13438 information.
13440 - If the cursor is inside a table, realign the table. This command
13441 works even if the automatic table editor has been turned off.
13443 - If the cursor is on a #+TBLFM line, re-apply the formulas to
13444 the entire table.
13446 - If the cursor is at a footnote reference or definition, jump to
13447 the corresponding definition or references, respectively.
13449 - If the cursor is a the beginning of a dynamic block, update it.
13451 - If the cursor is inside a table created by the table.el package,
13452 activate that table.
13454 - If the current buffer is a remember buffer, close note and file
13455 it. A prefix argument of 1 files to the default location
13456 without further interaction. A prefix argument of 2 files to
13457 the currently clocking task.
13459 - If the cursor is on a <<<target>>>, update radio targets and corresponding
13460 links in this buffer.
13462 - If the cursor is on a numbered item in a plain list, renumber the
13463 ordered list.
13465 - If the cursor is on a checkbox, toggle it."
13466 (interactive "P")
13467 (let ((org-enable-table-editor t))
13468 (cond
13469 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
13470 org-occur-highlights
13471 org-latex-fragment-image-overlays)
13472 (and (boundp 'org-clock-overlays) (org-clock-remove-overlays))
13473 (org-remove-occur-highlights)
13474 (org-remove-latex-fragment-image-overlays)
13475 (message "Temporary highlights/overlays removed from current buffer"))
13476 ((and (local-variable-p 'org-finish-function (current-buffer))
13477 (fboundp org-finish-function))
13478 (funcall org-finish-function))
13479 ((org-at-property-p)
13480 (call-interactively 'org-property-action))
13481 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13482 ((org-on-heading-p) (call-interactively 'org-set-tags))
13483 ((org-at-table.el-p)
13484 (require 'table)
13485 (beginning-of-line 1)
13486 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13487 (call-interactively 'table-recognize-table))
13488 ((org-at-table-p)
13489 (org-table-maybe-eval-formula)
13490 (if arg
13491 (call-interactively 'org-table-recalculate)
13492 (org-table-maybe-recalculate-line))
13493 (call-interactively 'org-table-align))
13494 ((or (org-footnote-at-reference-p)
13495 (org-footnote-at-definition-p))
13496 (call-interactively 'org-footnote-action))
13497 ((org-at-item-checkbox-p)
13498 (call-interactively 'org-toggle-checkbox))
13499 ((org-at-item-p)
13500 (call-interactively 'org-maybe-renumber-ordered-list))
13501 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13502 ;; Dynamic block
13503 (beginning-of-line 1)
13504 (save-excursion (org-update-dblock)))
13505 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13506 (cond
13507 ((equal (match-string 1) "TBLFM")
13508 ;; Recalculate the table before this line
13509 (save-excursion
13510 (beginning-of-line 1)
13511 (skip-chars-backward " \r\n\t")
13512 (if (org-at-table-p)
13513 (org-call-with-arg 'org-table-recalculate t))))
13515 ; (org-set-regexps-and-options)
13516 ; (org-restart-font-lock)
13517 (let ((org-inhibit-startup t)) (org-mode-restart))
13518 (message "Local setup has been refreshed"))))
13519 (t (error "C-c C-c can do nothing useful at this location.")))))
13521 (defun org-mode-restart ()
13522 "Restart Org-mode, to scan again for special lines.
13523 Also updates the keyword regular expressions."
13524 (interactive)
13525 (org-mode)
13526 (message "Org-mode restarted"))
13528 (defun org-kill-note-or-show-branches ()
13529 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13530 (interactive)
13531 (if (not org-finish-function)
13532 (call-interactively 'show-branches)
13533 (let ((org-note-abort t))
13534 (funcall org-finish-function))))
13536 (defun org-return (&optional indent)
13537 "Goto next table row or insert a newline.
13538 Calls `org-table-next-row' or `newline', depending on context.
13539 See the individual commands for more information."
13540 (interactive)
13541 (cond
13542 ((bobp) (if indent (newline-and-indent) (newline)))
13543 ((and (org-at-heading-p)
13544 (looking-at
13545 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13546 (org-show-entry)
13547 (end-of-line 1)
13548 (newline))
13549 ((org-at-table-p)
13550 (org-table-justify-field-maybe)
13551 (call-interactively 'org-table-next-row))
13552 (t (if indent (newline-and-indent) (newline)))))
13554 (defun org-return-indent ()
13555 "Goto next table row or insert a newline and indent.
13556 Calls `org-table-next-row' or `newline-and-indent', depending on
13557 context. See the individual commands for more information."
13558 (interactive)
13559 (org-return t))
13561 (defun org-ctrl-c-star ()
13562 "Compute table, or change heading status of lines.
13563 Calls `org-table-recalculate' or `org-toggle-heading',
13564 depending on context."
13565 (interactive)
13566 (cond
13567 ((org-at-table-p)
13568 (call-interactively 'org-table-recalculate))
13570 ;; Convert all lines in region to list items
13571 (call-interactively 'org-toggle-heading))))
13573 (defun org-ctrl-c-minus ()
13574 "Insert separator line in table or modify bullet status of line.
13575 Also turns a plain line or a region of lines into list items.
13576 Calls `org-table-insert-hline', `org-toggle-item', or
13577 `org-cycle-list-bullet', depending on context."
13578 (interactive)
13579 (cond
13580 ((org-at-table-p)
13581 (call-interactively 'org-table-insert-hline))
13582 ((org-region-active-p)
13583 (call-interactively 'org-toggle-item))
13584 ((org-in-item-p)
13585 (call-interactively 'org-cycle-list-bullet))
13587 (call-interactively 'org-toggle-item))))
13589 (defun org-toggle-item ()
13590 "Convert headings or normal lines to items, items to normal lines.
13591 If there is no active region, only the current line is considered.
13593 If the first line in the region is a headline, convert all headlines to items.
13595 If the first line in the region is an item, convert all items to normal lines.
13597 If the first line is normal text, add an item bullet to each line."
13598 (interactive)
13599 (let (l2 l beg end)
13600 (if (org-region-active-p)
13601 (setq beg (region-beginning) end (region-end))
13602 (setq beg (point-at-bol)
13603 end (min (1+ (point-at-eol)) (point-max))))
13604 (save-excursion
13605 (goto-char end)
13606 (setq l2 (org-current-line))
13607 (goto-char beg)
13608 (beginning-of-line 1)
13609 (setq l (1- (org-current-line)))
13610 (if (org-at-item-p)
13611 ;; We already have items, de-itemize
13612 (while (< (setq l (1+ l)) l2)
13613 (when (org-at-item-p)
13614 (goto-char (match-beginning 2))
13615 (delete-region (match-beginning 2) (match-end 2))
13616 (and (looking-at "[ \t]+") (replace-match "")))
13617 (beginning-of-line 2))
13618 (if (org-on-heading-p)
13619 ;; Headings, convert to items
13620 (while (< (setq l (1+ l)) l2)
13621 (if (looking-at org-outline-regexp)
13622 (replace-match "- " t t))
13623 (beginning-of-line 2))
13624 ;; normal lines, turn them into items
13625 (while (< (setq l (1+ l)) l2)
13626 (unless (org-at-item-p)
13627 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13628 (replace-match "\\1- \\2")))
13629 (beginning-of-line 2)))))))
13631 (defun org-toggle-heading (&optional nstars)
13632 "Convert headings to normal text, or items or text to headings.
13633 If there is no active region, only the current line is considered.
13635 If the first line is a heading, remove the stars from all headlines
13636 in the region.
13638 If the first line is a plain list item, turn all plain list items into
13639 headings.
13641 If the first line is a normal line, turn each and every line in the region
13642 into a heading.
13644 When converting a line into a heading, the number of stars is chosen
13645 such that the lines become children of the current entry. However, when
13646 a prefix argument is given, its value determines the number of stars to add."
13647 (interactive "P")
13648 (let (l2 l itemp beg end)
13649 (if (org-region-active-p)
13650 (setq beg (region-beginning) end (region-end))
13651 (setq beg (point-at-bol)
13652 end (min (1+ (point-at-eol)) (point-max))))
13653 (save-excursion
13654 (goto-char end)
13655 (setq l2 (org-current-line))
13656 (goto-char beg)
13657 (beginning-of-line 1)
13658 (setq l (1- (org-current-line)))
13659 (if (org-on-heading-p)
13660 ;; We already have headlines, de-star them
13661 (while (< (setq l (1+ l)) l2)
13662 (when (org-on-heading-p t)
13663 (and (looking-at outline-regexp) (replace-match "")))
13664 (beginning-of-line 2))
13665 (setq itemp (org-at-item-p))
13666 (let* ((stars
13667 (if nstars
13668 (make-string (prefix-numeric-value current-prefix-arg)
13670 (save-excursion
13671 (re-search-backward org-complex-heading-regexp nil t)
13672 (or (match-string 1) "*"))))
13673 (add-stars (if nstars "" (if org-odd-levels-only "**" "*")))
13674 (rpl (concat stars add-stars " ")))
13675 (while (< (setq l (1+ l)) l2)
13676 (if itemp
13677 (and (org-at-item-p) (replace-match rpl t t))
13678 (unless (org-on-heading-p)
13679 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13680 (replace-match (concat rpl (match-string 2))))))
13681 (beginning-of-line 2)))))))
13683 (defun org-meta-return (&optional arg)
13684 "Insert a new heading or wrap a region in a table.
13685 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13686 See the individual commands for more information."
13687 (interactive "P")
13688 (cond
13689 ((org-at-table-p)
13690 (call-interactively 'org-table-wrap-region))
13691 (t (call-interactively 'org-insert-heading))))
13693 ;;; Menu entries
13695 ;; Define the Org-mode menus
13696 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13697 '("Tbl"
13698 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13699 ["Next Field" org-cycle (org-at-table-p)]
13700 ["Previous Field" org-shifttab (org-at-table-p)]
13701 ["Next Row" org-return (org-at-table-p)]
13702 "--"
13703 ["Blank Field" org-table-blank-field (org-at-table-p)]
13704 ["Edit Field" org-table-edit-field (org-at-table-p)]
13705 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13706 "--"
13707 ("Column"
13708 ["Move Column Left" org-metaleft (org-at-table-p)]
13709 ["Move Column Right" org-metaright (org-at-table-p)]
13710 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13711 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13712 ("Row"
13713 ["Move Row Up" org-metaup (org-at-table-p)]
13714 ["Move Row Down" org-metadown (org-at-table-p)]
13715 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13716 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13717 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13718 "--"
13719 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13720 ("Rectangle"
13721 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13722 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13723 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13724 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13725 "--"
13726 ("Calculate"
13727 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13728 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13729 ["Edit Formulas" org-edit-special (org-at-table-p)]
13730 "--"
13731 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13732 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13733 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13734 "--"
13735 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13736 "--"
13737 ["Sum Column/Rectangle" org-table-sum
13738 (or (org-at-table-p) (org-region-active-p))]
13739 ["Which Column?" org-table-current-column (org-at-table-p)])
13740 ["Debug Formulas"
13741 org-table-toggle-formula-debugger
13742 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13743 ["Show Col/Row Numbers"
13744 org-table-toggle-coordinate-overlays
13745 :style toggle
13746 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13747 "--"
13748 ["Create" org-table-create (and (not (org-at-table-p))
13749 org-enable-table-editor)]
13750 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13751 ["Import from File" org-table-import (not (org-at-table-p))]
13752 ["Export to File" org-table-export (org-at-table-p)]
13753 "--"
13754 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13756 (easy-menu-define org-org-menu org-mode-map "Org menu"
13757 '("Org"
13758 ("Show/Hide"
13759 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13760 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13761 ["Sparse Tree..." org-sparse-tree t]
13762 ["Reveal Context" org-reveal t]
13763 ["Show All" show-all t]
13764 "--"
13765 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13766 "--"
13767 ["New Heading" org-insert-heading t]
13768 ("Navigate Headings"
13769 ["Up" outline-up-heading t]
13770 ["Next" outline-next-visible-heading t]
13771 ["Previous" outline-previous-visible-heading t]
13772 ["Next Same Level" outline-forward-same-level t]
13773 ["Previous Same Level" outline-backward-same-level t]
13774 "--"
13775 ["Jump" org-goto t])
13776 ("Edit Structure"
13777 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13778 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13779 "--"
13780 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13781 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13782 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13783 "--"
13784 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13785 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13786 ["Demote Heading" org-metaright (not (org-at-table-p))]
13787 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13788 "--"
13789 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13790 "--"
13791 ["Convert to odd levels" org-convert-to-odd-levels t]
13792 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13793 ("Editing"
13794 ["Emphasis..." org-emphasize t]
13795 ["Edit Source Example" org-edit-special t]
13796 "--"
13797 ["Footnote new/jump" org-footnote-action t]
13798 ["Footnote extra" (org-footnote-action t) :active t :keys "C-u C-c C-x f"])
13799 ("Archive"
13800 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13801 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13802 ; :active t :keys "C-u C-c C-x C-a"]
13803 ["Sparse trees open ARCHIVE trees"
13804 (setq org-sparse-tree-open-archived-trees
13805 (not org-sparse-tree-open-archived-trees))
13806 :style toggle :selected org-sparse-tree-open-archived-trees]
13807 ["Cycling opens ARCHIVE trees"
13808 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13809 :style toggle :selected org-cycle-open-archived-trees]
13810 "--"
13811 ["Move subtree to archive sibling" org-archive-to-archive-sibling t]
13812 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13813 ; ["Check and Move Children" (org-archive-subtree '(4))
13814 ; :active t :keys "C-u C-c C-x C-s"]
13816 "--"
13817 ("TODO Lists"
13818 ["TODO/DONE/-" org-todo t]
13819 ("Select keyword"
13820 ["Next keyword" org-shiftright (org-on-heading-p)]
13821 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13822 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13823 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13824 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13825 ["Show TODO Tree" org-show-todo-tree t]
13826 ["Global TODO list" org-todo-list t]
13827 "--"
13828 ["Enforce dependencies" (customize-variable 'org-enforce-todo-dependencies)
13829 :selected org-enforce-todo-dependencies :style toggle :active t]
13830 "Settings for tree at point"
13831 ["Do Children sequentially" org-toggle-ordered-property :style radio
13832 :selected (ignore-errors (org-entry-get nil "ORDERED"))
13833 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
13834 ["Do Children parallel" org-toggle-ordered-property :style radio
13835 :selected (ignore-errors (not (org-entry-get nil "ORDERED")))
13836 :active org-enforce-todo-dependencies :keys "C-c C-x o"]
13837 "--"
13838 ["Set Priority" org-priority t]
13839 ["Priority Up" org-shiftup t]
13840 ["Priority Down" org-shiftdown t])
13841 ("TAGS and Properties"
13842 ["Set Tags" org-set-tags-command t]
13843 ["Change tag in region" org-change-tag-in-region (org-region-active-p)]
13844 "--"
13845 ["Set property" org-set-property t]
13846 ["Column view of properties" org-columns t]
13847 ["Insert Column View DBlock" org-insert-columns-dblock t])
13848 ("Dates and Scheduling"
13849 ["Timestamp" org-time-stamp t]
13850 ["Timestamp (inactive)" org-time-stamp-inactive t]
13851 ("Change Date"
13852 ["1 Day Later" org-shiftright t]
13853 ["1 Day Earlier" org-shiftleft t]
13854 ["1 ... Later" org-shiftup t]
13855 ["1 ... Earlier" org-shiftdown t])
13856 ["Compute Time Range" org-evaluate-time-range t]
13857 ["Schedule Item" org-schedule t]
13858 ["Deadline" org-deadline t]
13859 "--"
13860 ["Custom time format" org-toggle-time-stamp-overlays
13861 :style radio :selected org-display-custom-times]
13862 "--"
13863 ["Goto Calendar" org-goto-calendar t]
13864 ["Date from Calendar" org-date-from-calendar t]
13865 "--"
13866 ["Start/Restart Timer" org-timer-start t]
13867 ["Pause/Continue Timer" org-timer-pause-or-continue t]
13868 ["Stop Timer" org-timer-pause-or-continue :active t :keys "C-u C-c C-x ,"]
13869 ["Insert Timer String" org-timer t]
13870 ["Insert Timer Item" org-timer-item t])
13871 ("Logging work"
13872 ["Clock in" org-clock-in t]
13873 ["Clock out" org-clock-out t]
13874 ["Clock cancel" org-clock-cancel t]
13875 ["Goto running clock" org-clock-goto t]
13876 ["Display times" org-clock-display t]
13877 ["Create clock table" org-clock-report t]
13878 "--"
13879 ["Record DONE time"
13880 (progn (setq org-log-done (not org-log-done))
13881 (message "Switching to %s will %s record a timestamp"
13882 (car org-done-keywords)
13883 (if org-log-done "automatically" "not")))
13884 :style toggle :selected org-log-done])
13885 "--"
13886 ["Agenda Command..." org-agenda t]
13887 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13888 ("File List for Agenda")
13889 ("Special views current file"
13890 ["TODO Tree" org-show-todo-tree t]
13891 ["Check Deadlines" org-check-deadlines t]
13892 ["Timeline" org-timeline t]
13893 ["Tags Tree" org-tags-sparse-tree t])
13894 "--"
13895 ("Hyperlinks"
13896 ["Store Link (Global)" org-store-link t]
13897 ["Insert Link" org-insert-link t]
13898 ["Follow Link" org-open-at-point t]
13899 "--"
13900 ["Next link" org-next-link t]
13901 ["Previous link" org-previous-link t]
13902 "--"
13903 ["Descriptive Links"
13904 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13905 :style radio
13906 :selected (member '(org-link) buffer-invisibility-spec)]
13907 ["Literal Links"
13908 (progn
13909 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13910 :style radio
13911 :selected (not (member '(org-link) buffer-invisibility-spec))])
13912 "--"
13913 ["Export/Publish..." org-export t]
13914 ("LaTeX"
13915 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13916 :selected org-cdlatex-mode]
13917 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13918 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13919 ["Modify math symbol" org-cdlatex-math-modify
13920 (org-inside-LaTeX-fragment-p)]
13921 ["Export LaTeX fragments as images"
13922 (if (featurep 'org-exp)
13923 (setq org-export-with-LaTeX-fragments
13924 (not org-export-with-LaTeX-fragments))
13925 (require 'org-exp))
13926 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13927 org-export-with-LaTeX-fragments)])
13928 "--"
13929 ("Documentation"
13930 ["Show Version" org-version t]
13931 ["Info Documentation" org-info t])
13932 ("Customize"
13933 ["Browse Org Group" org-customize t]
13934 "--"
13935 ["Expand This Menu" org-create-customize-menu
13936 (fboundp 'customize-menu-create)])
13937 "--"
13938 ["Refresh setup" org-mode-restart t]
13941 (defun org-info (&optional node)
13942 "Read documentation for Org-mode in the info system.
13943 With optional NODE, go directly to that node."
13944 (interactive)
13945 (info (format "(org)%s" (or node ""))))
13947 (defun org-install-agenda-files-menu ()
13948 (let ((bl (buffer-list)))
13949 (save-excursion
13950 (while bl
13951 (set-buffer (pop bl))
13952 (if (org-mode-p) (setq bl nil)))
13953 (when (org-mode-p)
13954 (easy-menu-change
13955 '("Org") "File List for Agenda"
13956 (append
13957 (list
13958 ["Edit File List" (org-edit-agenda-file-list) t]
13959 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13960 ["Remove Current File from List" org-remove-file t]
13961 ["Cycle through agenda files" org-cycle-agenda-files t]
13962 ["Occur in all agenda files" org-occur-in-agenda-files t]
13963 "--")
13964 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13966 ;;;; Documentation
13968 ;;;###autoload
13969 (defun org-require-autoloaded-modules ()
13970 (interactive)
13971 (mapc 'require
13972 '(org-agenda org-archive org-attach org-clock org-colview
13973 org-exp org-id org-export-latex org-publish
13974 org-remember org-table org-timer)))
13976 ;;;###autoload
13977 (defun org-customize ()
13978 "Call the customize function with org as argument."
13979 (interactive)
13980 (org-load-modules-maybe)
13981 (org-require-autoloaded-modules)
13982 (customize-browse 'org))
13984 (defun org-create-customize-menu ()
13985 "Create a full customization menu for Org-mode, insert it into the menu."
13986 (interactive)
13987 (org-load-modules-maybe)
13988 (org-require-autoloaded-modules)
13989 (if (fboundp 'customize-menu-create)
13990 (progn
13991 (easy-menu-change
13992 '("Org") "Customize"
13993 `(["Browse Org group" org-customize t]
13994 "--"
13995 ,(customize-menu-create 'org)
13996 ["Set" Custom-set t]
13997 ["Save" Custom-save t]
13998 ["Reset to Current" Custom-reset-current t]
13999 ["Reset to Saved" Custom-reset-saved t]
14000 ["Reset to Standard Settings" Custom-reset-standard t]))
14001 (message "\"Org\"-menu now contains full customization menu"))
14002 (error "Cannot expand menu (outdated version of cus-edit.el)")))
14004 ;;;; Miscellaneous stuff
14006 ;;; Generally useful functions
14008 (defun org-find-text-property-in-string (prop s)
14009 "Return the first non-nil value of property PROP in string S."
14010 (or (get-text-property 0 prop s)
14011 (get-text-property (or (next-single-property-change 0 prop s) 0)
14012 prop s)))
14014 (defun org-display-warning (message) ;; Copied from Emacs-Muse
14015 "Display the given MESSAGE as a warning."
14016 (if (fboundp 'display-warning)
14017 (display-warning 'org message
14018 (if (featurep 'xemacs)
14019 'warning
14020 :warning))
14021 (let ((buf (get-buffer-create "*Org warnings*")))
14022 (with-current-buffer buf
14023 (goto-char (point-max))
14024 (insert "Warning (Org): " message)
14025 (unless (bolp)
14026 (newline)))
14027 (display-buffer buf)
14028 (sit-for 0))))
14030 (defun org-goto-marker-or-bmk (marker &optional bookmark)
14031 "Go to MARKER, widen if necessary. When marker is not live, try BOOKMARK."
14032 (if (and marker (marker-buffer marker)
14033 (buffer-live-p (marker-buffer marker)))
14034 (progn
14035 (switch-to-buffer (marker-buffer marker))
14036 (if (or (> marker (point-max)) (< marker (point-min)))
14037 (widen))
14038 (goto-char marker)
14039 (org-show-context 'org-goto))
14040 (if bookmark
14041 (bookmark-jump bookmark)
14042 (error "Cannot find location"))))
14044 (defun org-quote-csv-field (s)
14045 "Quote field for inclusion in CSV material."
14046 (if (string-match "[\",]" s)
14047 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
14050 (defun org-plist-delete (plist property)
14051 "Delete PROPERTY from PLIST.
14052 This is in contrast to merely setting it to 0."
14053 (let (p)
14054 (while plist
14055 (if (not (eq property (car plist)))
14056 (setq p (plist-put p (car plist) (nth 1 plist))))
14057 (setq plist (cddr plist)))
14060 (defun org-force-self-insert (N)
14061 "Needed to enforce self-insert under remapping."
14062 (interactive "p")
14063 (self-insert-command N))
14065 (defun org-string-width (s)
14066 "Compute width of string, ignoring invisible characters.
14067 This ignores character with invisibility property `org-link', and also
14068 characters with property `org-cwidth', because these will become invisible
14069 upon the next fontification round."
14070 (let (b l)
14071 (when (or (eq t buffer-invisibility-spec)
14072 (assq 'org-link buffer-invisibility-spec))
14073 (while (setq b (text-property-any 0 (length s)
14074 'invisible 'org-link s))
14075 (setq s (concat (substring s 0 b)
14076 (substring s (or (next-single-property-change
14077 b 'invisible s) (length s)))))))
14078 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
14079 (setq s (concat (substring s 0 b)
14080 (substring s (or (next-single-property-change
14081 b 'org-cwidth s) (length s))))))
14082 (setq l (string-width s) b -1)
14083 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
14084 (setq l (- l (get-text-property b 'org-dwidth-n s))))
14087 (defun org-get-indentation (&optional line)
14088 "Get the indentation of the current line, interpreting tabs.
14089 When LINE is given, assume it represents a line and compute its indentation."
14090 (if line
14091 (if (string-match "^ *" (org-remove-tabs line))
14092 (match-end 0))
14093 (save-excursion
14094 (beginning-of-line 1)
14095 (skip-chars-forward " \t")
14096 (current-column))))
14098 (defun org-remove-tabs (s &optional width)
14099 "Replace tabulators in S with spaces.
14100 Assumes that s is a single line, starting in column 0."
14101 (setq width (or width tab-width))
14102 (while (string-match "\t" s)
14103 (setq s (replace-match
14104 (make-string
14105 (- (* width (/ (+ (match-beginning 0) width) width))
14106 (match-beginning 0)) ?\ )
14107 t t s)))
14110 (defun org-fix-indentation (line ind)
14111 "Fix indentation in LINE.
14112 IND is a cons cell with target and minimum indentation.
14113 If the current indentation in LINE is smaller than the minimum,
14114 leave it alone. If it is larger than ind, set it to the target."
14115 (let* ((l (org-remove-tabs line))
14116 (i (org-get-indentation l))
14117 (i1 (car ind)) (i2 (cdr ind)))
14118 (if (>= i i2) (setq l (substring line i2)))
14119 (if (> i1 0)
14120 (concat (make-string i1 ?\ ) l)
14121 l)))
14123 (defun org-base-buffer (buffer)
14124 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
14125 (if (not buffer)
14126 buffer
14127 (or (buffer-base-buffer buffer)
14128 buffer)))
14130 (defun org-trim (s)
14131 "Remove whitespace at beginning and end of string."
14132 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
14133 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
14136 (defun org-wrap (string &optional width lines)
14137 "Wrap string to either a number of lines, or a width in characters.
14138 If WIDTH is non-nil, the string is wrapped to that width, however many lines
14139 that costs. If there is a word longer than WIDTH, the text is actually
14140 wrapped to the length of that word.
14141 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
14142 many lines, whatever width that takes.
14143 The return value is a list of lines, without newlines at the end."
14144 (let* ((words (org-split-string string "[ \t\n]+"))
14145 (maxword (apply 'max (mapcar 'org-string-width words)))
14146 w ll)
14147 (cond (width
14148 (org-do-wrap words (max maxword width)))
14149 (lines
14150 (setq w maxword)
14151 (setq ll (org-do-wrap words maxword))
14152 (if (<= (length ll) lines)
14154 (setq ll words)
14155 (while (> (length ll) lines)
14156 (setq w (1+ w))
14157 (setq ll (org-do-wrap words w)))
14158 ll))
14159 (t (error "Cannot wrap this")))))
14161 (defun org-do-wrap (words width)
14162 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
14163 (let (lines line)
14164 (while words
14165 (setq line (pop words))
14166 (while (and words (< (+ (length line) (length (car words))) width))
14167 (setq line (concat line " " (pop words))))
14168 (setq lines (push line lines)))
14169 (nreverse lines)))
14171 (defun org-split-string (string &optional separators)
14172 "Splits STRING into substrings at SEPARATORS.
14173 No empty strings are returned if there are matches at the beginning
14174 and end of string."
14175 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
14176 (start 0)
14177 notfirst
14178 (list nil))
14179 (while (and (string-match rexp string
14180 (if (and notfirst
14181 (= start (match-beginning 0))
14182 (< start (length string)))
14183 (1+ start) start))
14184 (< (match-beginning 0) (length string)))
14185 (setq notfirst t)
14186 (or (eq (match-beginning 0) 0)
14187 (and (eq (match-beginning 0) (match-end 0))
14188 (eq (match-beginning 0) start))
14189 (setq list
14190 (cons (substring string start (match-beginning 0))
14191 list)))
14192 (setq start (match-end 0)))
14193 (or (eq start (length string))
14194 (setq list
14195 (cons (substring string start)
14196 list)))
14197 (nreverse list)))
14199 (defun org-context ()
14200 "Return a list of contexts of the current cursor position.
14201 If several contexts apply, all are returned.
14202 Each context entry is a list with a symbol naming the context, and
14203 two positions indicating start and end of the context. Possible
14204 contexts are:
14206 :headline anywhere in a headline
14207 :headline-stars on the leading stars in a headline
14208 :todo-keyword on a TODO keyword (including DONE) in a headline
14209 :tags on the TAGS in a headline
14210 :priority on the priority cookie in a headline
14211 :item on the first line of a plain list item
14212 :item-bullet on the bullet/number of a plain list item
14213 :checkbox on the checkbox in a plain list item
14214 :table in an org-mode table
14215 :table-special on a special filed in a table
14216 :table-table in a table.el table
14217 :link on a hyperlink
14218 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
14219 :target on a <<target>>
14220 :radio-target on a <<<radio-target>>>
14221 :latex-fragment on a LaTeX fragment
14222 :latex-preview on a LaTeX fragment with overlayed preview image
14224 This function expects the position to be visible because it uses font-lock
14225 faces as a help to recognize the following contexts: :table-special, :link,
14226 and :keyword."
14227 (let* ((f (get-text-property (point) 'face))
14228 (faces (if (listp f) f (list f)))
14229 (p (point)) clist o)
14230 ;; First the large context
14231 (cond
14232 ((org-on-heading-p t)
14233 (push (list :headline (point-at-bol) (point-at-eol)) clist)
14234 (when (progn
14235 (beginning-of-line 1)
14236 (looking-at org-todo-line-tags-regexp))
14237 (push (org-point-in-group p 1 :headline-stars) clist)
14238 (push (org-point-in-group p 2 :todo-keyword) clist)
14239 (push (org-point-in-group p 4 :tags) clist))
14240 (goto-char p)
14241 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
14242 (if (looking-at "\\[#[A-Z0-9]\\]")
14243 (push (org-point-in-group p 0 :priority) clist)))
14245 ((org-at-item-p)
14246 (push (org-point-in-group p 2 :item-bullet) clist)
14247 (push (list :item (point-at-bol)
14248 (save-excursion (org-end-of-item) (point)))
14249 clist)
14250 (and (org-at-item-checkbox-p)
14251 (push (org-point-in-group p 0 :checkbox) clist)))
14253 ((org-at-table-p)
14254 (push (list :table (org-table-begin) (org-table-end)) clist)
14255 (if (memq 'org-formula faces)
14256 (push (list :table-special
14257 (previous-single-property-change p 'face)
14258 (next-single-property-change p 'face)) clist)))
14259 ((org-at-table-p 'any)
14260 (push (list :table-table) clist)))
14261 (goto-char p)
14263 ;; Now the small context
14264 (cond
14265 ((org-at-timestamp-p)
14266 (push (org-point-in-group p 0 :timestamp) clist))
14267 ((memq 'org-link faces)
14268 (push (list :link
14269 (previous-single-property-change p 'face)
14270 (next-single-property-change p 'face)) clist))
14271 ((memq 'org-special-keyword faces)
14272 (push (list :keyword
14273 (previous-single-property-change p 'face)
14274 (next-single-property-change p 'face)) clist))
14275 ((org-on-target-p)
14276 (push (org-point-in-group p 0 :target) clist)
14277 (goto-char (1- (match-beginning 0)))
14278 (if (looking-at org-radio-target-regexp)
14279 (push (org-point-in-group p 0 :radio-target) clist))
14280 (goto-char p))
14281 ((setq o (car (delq nil
14282 (mapcar
14283 (lambda (x)
14284 (if (memq x org-latex-fragment-image-overlays) x))
14285 (org-overlays-at (point))))))
14286 (push (list :latex-fragment
14287 (org-overlay-start o) (org-overlay-end o)) clist)
14288 (push (list :latex-preview
14289 (org-overlay-start o) (org-overlay-end o)) clist))
14290 ((org-inside-LaTeX-fragment-p)
14291 ;; FIXME: positions wrong.
14292 (push (list :latex-fragment (point) (point)) clist)))
14294 (setq clist (nreverse (delq nil clist)))
14295 clist))
14297 ;; FIXME: Compare with at-regexp-p Do we need both?
14298 (defun org-in-regexp (re &optional nlines visually)
14299 "Check if point is inside a match of regexp.
14300 Normally only the current line is checked, but you can include NLINES extra
14301 lines both before and after point into the search.
14302 If VISUALLY is set, require that the cursor is not after the match but
14303 really on, so that the block visually is on the match."
14304 (catch 'exit
14305 (let ((pos (point))
14306 (eol (point-at-eol (+ 1 (or nlines 0))))
14307 (inc (if visually 1 0)))
14308 (save-excursion
14309 (beginning-of-line (- 1 (or nlines 0)))
14310 (while (re-search-forward re eol t)
14311 (if (and (<= (match-beginning 0) pos)
14312 (>= (+ inc (match-end 0)) pos))
14313 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
14315 (defun org-at-regexp-p (regexp)
14316 "Is point inside a match of REGEXP in the current line?"
14317 (catch 'exit
14318 (save-excursion
14319 (let ((pos (point)) (end (point-at-eol)))
14320 (beginning-of-line 1)
14321 (while (re-search-forward regexp end t)
14322 (if (and (<= (match-beginning 0) pos)
14323 (>= (match-end 0) pos))
14324 (throw 'exit t)))
14325 nil))))
14327 (defun org-occur-in-agenda-files (regexp &optional nlines)
14328 "Call `multi-occur' with buffers for all agenda files."
14329 (interactive "sOrg-files matching: \np")
14330 (let* ((files (org-agenda-files))
14331 (tnames (mapcar 'file-truename files))
14332 (extra org-agenda-text-search-extra-files)
14334 (when (eq (car extra) 'agenda-archives)
14335 (setq extra (cdr extra))
14336 (setq files (org-add-archive-files files)))
14337 (while (setq f (pop extra))
14338 (unless (member (file-truename f) tnames)
14339 (add-to-list 'files f 'append)
14340 (add-to-list 'tnames (file-truename f) 'append)))
14341 (multi-occur
14342 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
14343 regexp)))
14345 (if (boundp 'occur-mode-find-occurrence-hook)
14346 ;; Emacs 23
14347 (add-hook 'occur-mode-find-occurrence-hook
14348 (lambda ()
14349 (when (org-mode-p)
14350 (org-reveal))))
14351 ;; Emacs 22
14352 (defadvice occur-mode-goto-occurrence
14353 (after org-occur-reveal activate)
14354 (and (org-mode-p) (org-reveal)))
14355 (defadvice occur-mode-goto-occurrence-other-window
14356 (after org-occur-reveal activate)
14357 (and (org-mode-p) (org-reveal)))
14358 (defadvice occur-mode-display-occurrence
14359 (after org-occur-reveal activate)
14360 (when (org-mode-p)
14361 (let ((pos (occur-mode-find-occurrence)))
14362 (with-current-buffer (marker-buffer pos)
14363 (save-excursion
14364 (goto-char pos)
14365 (org-reveal)))))))
14367 (defun org-uniquify (list)
14368 "Remove duplicate elements from LIST."
14369 (let (res)
14370 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
14371 res))
14373 (defun org-delete-all (elts list)
14374 "Remove all elements in ELTS from LIST."
14375 (while elts
14376 (setq list (delete (pop elts) list)))
14377 list)
14379 (defun org-back-over-empty-lines ()
14380 "Move backwards over whitespace, to the beginning of the first empty line.
14381 Returns the number of empty lines passed."
14382 (let ((pos (point)))
14383 (skip-chars-backward " \t\n\r")
14384 (beginning-of-line 2)
14385 (goto-char (min (point) pos))
14386 (count-lines (point) pos)))
14388 (defun org-skip-whitespace ()
14389 (skip-chars-forward " \t\n\r"))
14391 (defun org-point-in-group (point group &optional context)
14392 "Check if POINT is in match-group GROUP.
14393 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
14394 match. If the match group does ot exist or point is not inside it,
14395 return nil."
14396 (and (match-beginning group)
14397 (>= point (match-beginning group))
14398 (<= point (match-end group))
14399 (if context
14400 (list context (match-beginning group) (match-end group))
14401 t)))
14403 (defun org-switch-to-buffer-other-window (&rest args)
14404 "Switch to buffer in a second window on the current frame.
14405 In particular, do not allow pop-up frames."
14406 (let (pop-up-frames special-display-buffer-names special-display-regexps
14407 special-display-function)
14408 (apply 'switch-to-buffer-other-window args)))
14410 (defun org-combine-plists (&rest plists)
14411 "Create a single property list from all plists in PLISTS.
14412 The process starts by copying the first list, and then setting properties
14413 from the other lists. Settings in the last list are the most significant
14414 ones and overrule settings in the other lists."
14415 (let ((rtn (copy-sequence (pop plists)))
14416 p v ls)
14417 (while plists
14418 (setq ls (pop plists))
14419 (while ls
14420 (setq p (pop ls) v (pop ls))
14421 (setq rtn (plist-put rtn p v))))
14422 rtn))
14424 (defun org-move-line-down (arg)
14425 "Move the current line down. With prefix argument, move it past ARG lines."
14426 (interactive "p")
14427 (let ((col (current-column))
14428 beg end pos)
14429 (beginning-of-line 1) (setq beg (point))
14430 (beginning-of-line 2) (setq end (point))
14431 (beginning-of-line (+ 1 arg))
14432 (setq pos (move-marker (make-marker) (point)))
14433 (insert (delete-and-extract-region beg end))
14434 (goto-char pos)
14435 (org-move-to-column col)))
14437 (defun org-move-line-up (arg)
14438 "Move the current line up. With prefix argument, move it past ARG lines."
14439 (interactive "p")
14440 (let ((col (current-column))
14441 beg end pos)
14442 (beginning-of-line 1) (setq beg (point))
14443 (beginning-of-line 2) (setq end (point))
14444 (beginning-of-line (- arg))
14445 (setq pos (move-marker (make-marker) (point)))
14446 (insert (delete-and-extract-region beg end))
14447 (goto-char pos)
14448 (org-move-to-column col)))
14450 (defun org-replace-escapes (string table)
14451 "Replace %-escapes in STRING with values in TABLE.
14452 TABLE is an association list with keys like \"%a\" and string values.
14453 The sequences in STRING may contain normal field width and padding information,
14454 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
14455 so values can contain further %-escapes if they are define later in TABLE."
14456 (let ((case-fold-search nil)
14457 e re rpl)
14458 (while (setq e (pop table))
14459 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
14460 (while (string-match re string)
14461 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
14462 (cdr e)))
14463 (setq string (replace-match rpl t t string))))
14464 string))
14467 (defun org-sublist (list start end)
14468 "Return a section of LIST, from START to END.
14469 Counting starts at 1."
14470 (let (rtn (c start))
14471 (setq list (nthcdr (1- start) list))
14472 (while (and list (<= c end))
14473 (push (pop list) rtn)
14474 (setq c (1+ c)))
14475 (nreverse rtn)))
14477 (defun org-find-base-buffer-visiting (file)
14478 "Like `find-buffer-visiting' but alway return the base buffer and
14479 not an indirect buffer."
14480 (let ((buf (find-buffer-visiting file)))
14481 (if buf
14482 (or (buffer-base-buffer buf) buf)
14483 nil)))
14485 (defun org-image-file-name-regexp (&optional extensions)
14486 "Return regexp matching the file names of images.
14487 If EXTENSIONS is given, only match these."
14488 (if (and (not extensions) (fboundp 'image-file-name-regexp))
14489 (image-file-name-regexp)
14490 (let ((image-file-name-extensions
14491 (or extensions
14492 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
14493 "xbm" "xpm" "pbm" "pgm" "ppm"))))
14494 (concat "\\."
14495 (regexp-opt (nconc (mapcar 'upcase
14496 image-file-name-extensions)
14497 image-file-name-extensions)
14499 "\\'"))))
14501 (defun org-file-image-p (file &optional extensions)
14502 "Return non-nil if FILE is an image."
14503 (save-match-data
14504 (string-match (org-image-file-name-regexp extensions) file)))
14506 (defun org-get-cursor-date ()
14507 "Return the date at cursor in as a time.
14508 This works in the calendar and in the agenda, anywhere else it just
14509 returns the current time."
14510 (let (date day defd)
14511 (cond
14512 ((eq major-mode 'calendar-mode)
14513 (setq date (calendar-cursor-to-date)
14514 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
14515 ((eq major-mode 'org-agenda-mode)
14516 (setq day (get-text-property (point) 'day))
14517 (if day
14518 (setq date (calendar-gregorian-from-absolute day)
14519 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
14520 (nth 2 date))))))
14521 (or defd (current-time))))
14523 (defvar org-agenda-action-marker (make-marker)
14524 "Marker pointing to the entry for the next agenda action.")
14526 (defun org-mark-entry-for-agenda-action ()
14527 "Mark the current entry as target of an agenda action.
14528 Agenda actions are actions executed from the agenda with the key `k',
14529 which make use of the date at the cursor."
14530 (interactive)
14531 (move-marker org-agenda-action-marker
14532 (save-excursion (org-back-to-heading t) (point))
14533 (current-buffer))
14534 (message
14535 "Entry marked for action; press `k' at desired date in agenda or calendar"))
14537 ;;; Paragraph filling stuff.
14538 ;; We want this to be just right, so use the full arsenal.
14540 (defun org-indent-line-function ()
14541 "Indent line like previous, but further if previous was headline or item."
14542 (interactive)
14543 (let* ((pos (point))
14544 (itemp (org-at-item-p))
14545 column bpos bcol tpos tcol bullet btype bullet-type)
14546 ;; Find the previous relevant line
14547 (beginning-of-line 1)
14548 (cond
14549 ((looking-at "#") (setq column 0))
14550 ((looking-at "\\*+ ") (setq column 0))
14552 (beginning-of-line 0)
14553 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
14554 (beginning-of-line 0))
14555 (cond
14556 ((looking-at "\\*+[ \t]+")
14557 (if (not org-adapt-indentation)
14558 (setq column 0)
14559 (goto-char (match-end 0))
14560 (setq column (current-column))))
14561 ((org-in-item-p)
14562 (org-beginning-of-item)
14563 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14564 (setq bpos (match-beginning 1) tpos (match-end 0)
14565 bcol (progn (goto-char bpos) (current-column))
14566 tcol (progn (goto-char tpos) (current-column))
14567 bullet (match-string 1)
14568 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14569 (if (> tcol (+ bcol org-description-max-indent))
14570 (setq tcol (+ bcol 5)))
14571 (if (not itemp)
14572 (setq column tcol)
14573 (goto-char pos)
14574 (beginning-of-line 1)
14575 (if (looking-at "\\S-")
14576 (progn
14577 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14578 (setq bullet (match-string 1)
14579 btype (if (string-match "[0-9]" bullet) "n" bullet))
14580 (setq column (if (equal btype bullet-type) bcol tcol)))
14581 (setq column (org-get-indentation)))))
14582 (t (setq column (org-get-indentation))))))
14583 (goto-char pos)
14584 (if (<= (current-column) (current-indentation))
14585 (org-indent-line-to column)
14586 (save-excursion (org-indent-line-to column)))
14587 (setq column (current-column))
14588 (beginning-of-line 1)
14589 (if (looking-at
14590 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14591 (replace-match (concat "\\1" (format org-property-format
14592 (match-string 2) (match-string 3)))
14593 t nil))
14594 (org-move-to-column column)))
14596 (defun org-set-autofill-regexps ()
14597 (interactive)
14598 ;; In the paragraph separator we include headlines, because filling
14599 ;; text in a line directly attached to a headline would otherwise
14600 ;; fill the headline as well.
14601 (org-set-local 'comment-start-skip "^#+[ \t]*")
14602 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14603 ;; The paragraph starter includes hand-formatted lists.
14604 (org-set-local 'paragraph-start
14605 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14606 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14607 ;; But only if the user has not turned off tables or fixed-width regions
14608 (org-set-local
14609 'auto-fill-inhibit-regexp
14610 (concat "\\*+ \\|#\\+"
14611 "\\|[ \t]*" org-keyword-time-regexp
14612 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14613 (concat
14614 "\\|[ \t]*["
14615 (if org-enable-table-editor "|" "")
14616 (if org-enable-fixed-width-editor ":" "")
14617 "]"))))
14618 ;; We use our own fill-paragraph function, to make sure that tables
14619 ;; and fixed-width regions are not wrapped. That function will pass
14620 ;; through to `fill-paragraph' when appropriate.
14621 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14622 ; Adaptive filling: To get full control, first make sure that
14623 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14624 (org-set-local 'adaptive-fill-regexp "\000")
14625 (org-set-local 'adaptive-fill-function
14626 'org-adaptive-fill-function)
14627 (org-set-local
14628 'align-mode-rules-list
14629 '((org-in-buffer-settings
14630 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14631 (modes . '(org-mode))))))
14633 (defun org-fill-paragraph (&optional justify)
14634 "Re-align a table, pass through to fill-paragraph if no table."
14635 (let ((table-p (org-at-table-p))
14636 (table.el-p (org-at-table.el-p)))
14637 (cond ((and (equal (char-after (point-at-bol)) ?*)
14638 (save-excursion (goto-char (point-at-bol))
14639 (looking-at outline-regexp)))
14640 t) ; skip headlines
14641 (table.el-p t) ; skip table.el tables
14642 (table-p (org-table-align) t) ; align org-mode tables
14643 (t nil)))) ; call paragraph-fill
14645 ;; For reference, this is the default value of adaptive-fill-regexp
14646 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14648 (defun org-adaptive-fill-function ()
14649 "Return a fill prefix for org-mode files.
14650 In particular, this makes sure hanging paragraphs for hand-formatted lists
14651 work correctly."
14652 (cond ((looking-at "#[ \t]+")
14653 (match-string 0))
14654 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14655 (save-excursion
14656 (if (> (match-end 1) (+ (match-beginning 1)
14657 org-description-max-indent))
14658 (goto-char (+ (match-beginning 1) 5))
14659 (goto-char (match-end 0)))
14660 (make-string (current-column) ?\ )))
14661 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] ?\\)?")
14662 (save-excursion
14663 (goto-char (match-end 0))
14664 (make-string (current-column) ?\ )))
14665 (t nil)))
14667 ;;; Other stuff.
14669 (defun org-toggle-fixed-width-section (arg)
14670 "Toggle the fixed-width export.
14671 If there is no active region, the QUOTE keyword at the current headline is
14672 inserted or removed. When present, it causes the text between this headline
14673 and the next to be exported as fixed-width text, and unmodified.
14674 If there is an active region, this command adds or removes a colon as the
14675 first character of this line. If the first character of a line is a colon,
14676 this line is also exported in fixed-width font."
14677 (interactive "P")
14678 (let* ((cc 0)
14679 (regionp (org-region-active-p))
14680 (beg (if regionp (region-beginning) (point)))
14681 (end (if regionp (region-end)))
14682 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14683 (case-fold-search nil)
14684 (re "[ \t]*\\(:\\)")
14685 off)
14686 (if regionp
14687 (save-excursion
14688 (goto-char beg)
14689 (setq cc (current-column))
14690 (beginning-of-line 1)
14691 (setq off (looking-at re))
14692 (while (> nlines 0)
14693 (setq nlines (1- nlines))
14694 (beginning-of-line 1)
14695 (cond
14696 (arg
14697 (org-move-to-column cc t)
14698 (insert ":\n")
14699 (forward-line -1))
14700 ((and off (looking-at re))
14701 (replace-match "" t t nil 1))
14702 ((not off) (org-move-to-column cc t) (insert ":")))
14703 (forward-line 1)))
14704 (save-excursion
14705 (org-back-to-heading)
14706 (if (looking-at (concat outline-regexp
14707 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14708 (replace-match "" t t nil 1)
14709 (if (looking-at outline-regexp)
14710 (progn
14711 (goto-char (match-end 0))
14712 (insert org-quote-string " "))))))))
14714 ;;;; Functions extending outline functionality
14716 (defun org-beginning-of-line (&optional arg)
14717 "Go to the beginning of the current line. If that is invisible, continue
14718 to a visible line beginning. This makes the function of C-a more intuitive.
14719 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14720 first attempt, and only move to after the tags when the cursor is already
14721 beyond the end of the headline."
14722 (interactive "P")
14723 (let ((pos (point)) refpos)
14724 (beginning-of-line 1)
14725 (if (bobp)
14727 (backward-char 1)
14728 (if (org-invisible-p)
14729 (while (and (not (bobp)) (org-invisible-p))
14730 (backward-char 1)
14731 (beginning-of-line 1))
14732 (forward-char 1)))
14733 (when org-special-ctrl-a/e
14734 (cond
14735 ((and (looking-at org-complex-heading-regexp)
14736 (= (char-after (match-end 1)) ?\ ))
14737 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14738 (point-at-eol)))
14739 (goto-char
14740 (if (eq org-special-ctrl-a/e t)
14741 (cond ((> pos refpos) refpos)
14742 ((= pos (point)) refpos)
14743 (t (point)))
14744 (cond ((> pos (point)) (point))
14745 ((not (eq last-command this-command)) (point))
14746 (t refpos)))))
14747 ((org-at-item-p)
14748 (goto-char
14749 (if (eq org-special-ctrl-a/e t)
14750 (cond ((> pos (match-end 4)) (match-end 4))
14751 ((= pos (point)) (match-end 4))
14752 (t (point)))
14753 (cond ((> pos (point)) (point))
14754 ((not (eq last-command this-command)) (point))
14755 (t (match-end 4))))))))
14756 (org-no-warnings
14757 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14759 (defun org-end-of-line (&optional arg)
14760 "Go to the end of the line.
14761 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14762 first attempt, and only move to after the tags when the cursor is already
14763 beyond the end of the headline."
14764 (interactive "P")
14765 (if (or (not org-special-ctrl-a/e)
14766 (not (org-on-heading-p)))
14767 (end-of-line arg)
14768 (let ((pos (point)))
14769 (beginning-of-line 1)
14770 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14771 (if (eq org-special-ctrl-a/e t)
14772 (if (or (< pos (match-beginning 1))
14773 (= pos (match-end 0)))
14774 (goto-char (match-beginning 1))
14775 (goto-char (match-end 0)))
14776 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14777 (goto-char (match-end 0))
14778 (goto-char (match-beginning 1))))
14779 (end-of-line arg))))
14780 (org-no-warnings
14781 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14784 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14785 (define-key org-mode-map "\C-e" 'org-end-of-line)
14787 (defun org-kill-line (&optional arg)
14788 "Kill line, to tags or end of line."
14789 (interactive "P")
14790 (cond
14791 ((or (not org-special-ctrl-k)
14792 (bolp)
14793 (not (org-on-heading-p)))
14794 (call-interactively 'kill-line))
14795 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14796 (kill-region (point) (match-beginning 1))
14797 (org-set-tags nil t))
14798 (t (kill-region (point) (point-at-eol)))))
14800 (define-key org-mode-map "\C-k" 'org-kill-line)
14802 (defun org-yank (&optional arg)
14803 "Yank. If the kill is a subtree, treat it specially.
14804 This command will look at the current kill and check if is a single
14805 subtree, or a series of subtrees[1]. If it passes the test, and if the
14806 cursor is at the beginning of a line or after the stars of a currently
14807 empty headline, then the yank is handled specially. How exactly depends
14808 on the value of the following variables, both set by default.
14810 org-yank-folded-subtrees
14811 When set, the subtree(s) will be folded after insertion, but only
14812 if doing so would now swallow text after the yanked text.
14814 org-yank-adjusted-subtrees
14815 When set, the subtree will be promoted or demoted in order to
14816 fit into the local outline tree structure, which means that the level
14817 will be adjusted so that it becomes the smaller one of the two
14818 *visible* surrounding headings.
14820 Any prefix to this command will cause `yank' to be called directly with
14821 no special treatment. In particular, a simple `C-u' prefix will just
14822 plainly yank the text as it is.
14824 \[1] Basically, the test checks if the first non-white line is a heading
14825 and if there are no other headings with fewer stars."
14826 (interactive "P")
14827 (setq this-command 'yank)
14828 (if arg
14829 (call-interactively 'yank)
14830 (let ((subtreep ; is kill a subtree, and the yank position appropriate?
14831 (and (org-kill-is-subtree-p)
14832 (or (bolp)
14833 (and (looking-at "[ \t]*$")
14834 (string-match
14835 "\\`\\*+\\'"
14836 (buffer-substring (point-at-bol) (point)))))))
14837 swallowp)
14838 (cond
14839 ((and subtreep org-yank-folded-subtrees)
14840 (let ((beg (point))
14841 end)
14842 (if (and subtreep org-yank-adjusted-subtrees)
14843 (org-paste-subtree nil nil 'for-yank)
14844 (call-interactively 'yank))
14845 (setq end (point))
14846 (goto-char beg)
14847 (when (and (bolp) subtreep
14848 (not (setq swallowp
14849 (org-yank-folding-would-swallow-text beg end))))
14850 (or (looking-at outline-regexp)
14851 (re-search-forward (concat "^" outline-regexp) end t))
14852 (while (and (< (point) end) (looking-at outline-regexp))
14853 (hide-subtree)
14854 (org-cycle-show-empty-lines 'folded)
14855 (condition-case nil
14856 (outline-forward-same-level 1)
14857 (error (goto-char end)))))
14858 (when swallowp
14859 (message
14860 "Yanked text not folded because that would swallow text"))
14861 (goto-char end)
14862 (skip-chars-forward " \t\n\r")
14863 (beginning-of-line 1)
14864 (push-mark beg 'nomsg)))
14865 ((and subtreep org-yank-adjusted-subtrees)
14866 (let ((beg (point-at-bol)))
14867 (org-paste-subtree nil nil 'for-yank)
14868 (push-mark beg 'nomsg)))
14870 (call-interactively 'yank))))))
14872 (defun org-yank-folding-would-swallow-text (beg end)
14873 "Would hide-subtree at BEG swallow any text after END?"
14874 (let (level)
14875 (save-excursion
14876 (goto-char beg)
14877 (when (or (looking-at outline-regexp)
14878 (re-search-forward (concat "^" outline-regexp) end t))
14879 (setq level (org-outline-level)))
14880 (goto-char end)
14881 (skip-chars-forward " \t\r\n\v\f")
14882 (if (or (eobp)
14883 (and (bolp) (looking-at org-outline-regexp)
14884 (<= (org-outline-level) level)))
14885 nil ; Nothing would be swallowed
14886 t)))) ; something would swallow
14888 (define-key org-mode-map "\C-y" 'org-yank)
14890 (defun org-invisible-p ()
14891 "Check if point is at a character currently not visible."
14892 ;; Early versions of noutline don't have `outline-invisible-p'.
14893 (if (fboundp 'outline-invisible-p)
14894 (outline-invisible-p)
14895 (get-char-property (point) 'invisible)))
14897 (defun org-invisible-p2 ()
14898 "Check if point is at a character currently not visible."
14899 (save-excursion
14900 (if (and (eolp) (not (bobp))) (backward-char 1))
14901 ;; Early versions of noutline don't have `outline-invisible-p'.
14902 (if (fboundp 'outline-invisible-p)
14903 (outline-invisible-p)
14904 (get-char-property (point) 'invisible))))
14906 (defun org-back-to-heading (&optional invisible-ok)
14907 "Call `outline-back-to-heading', but provide a better error message."
14908 (condition-case nil
14909 (outline-back-to-heading invisible-ok)
14910 (error (error "Before first headline at position %d in buffer %s"
14911 (point) (current-buffer)))))
14913 (defun org-before-first-heading-p ()
14914 "Before first heading?"
14915 (save-excursion
14916 (null (re-search-backward "^\\*+ " nil t))))
14918 (defalias 'org-on-heading-p 'outline-on-heading-p)
14919 (defalias 'org-at-heading-p 'outline-on-heading-p)
14920 (defun org-at-heading-or-item-p ()
14921 (or (org-on-heading-p) (org-at-item-p)))
14923 (defun org-on-target-p ()
14924 (or (org-in-regexp org-radio-target-regexp)
14925 (org-in-regexp org-target-regexp)))
14927 (defun org-up-heading-all (arg)
14928 "Move to the heading line of which the present line is a subheading.
14929 This function considers both visible and invisible heading lines.
14930 With argument, move up ARG levels."
14931 (if (fboundp 'outline-up-heading-all)
14932 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14933 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14935 (defun org-up-heading-safe ()
14936 "Move to the heading line of which the present line is a subheading.
14937 This version will not throw an error. It will return the level of the
14938 headline found, or nil if no higher level is found."
14939 (let (start-level re)
14940 (org-back-to-heading t)
14941 (setq start-level (funcall outline-level))
14942 (if (equal start-level 1)
14944 (setq re (concat "^\\*\\{1," (number-to-string (1- start-level)) "\\} "))
14945 (if (re-search-backward re nil t)
14946 (funcall outline-level)))))
14948 (defun org-first-sibling-p ()
14949 "Is this heading the first child of its parents?"
14950 (interactive)
14951 (let ((re (concat "^" outline-regexp))
14952 level l)
14953 (unless (org-at-heading-p t)
14954 (error "Not at a heading"))
14955 (setq level (funcall outline-level))
14956 (save-excursion
14957 (if (not (re-search-backward re nil t))
14959 (setq l (funcall outline-level))
14960 (< l level)))))
14962 (defun org-goto-sibling (&optional previous)
14963 "Goto the next sibling, even if it is invisible.
14964 When PREVIOUS is set, go to the previous sibling instead. Returns t
14965 when a sibling was found. When none is found, return nil and don't
14966 move point."
14967 (let ((fun (if previous 're-search-backward 're-search-forward))
14968 (pos (point))
14969 (re (concat "^" outline-regexp))
14970 level l)
14971 (when (condition-case nil (org-back-to-heading t) (error nil))
14972 (setq level (funcall outline-level))
14973 (catch 'exit
14974 (or previous (forward-char 1))
14975 (while (funcall fun re nil t)
14976 (setq l (funcall outline-level))
14977 (when (< l level) (goto-char pos) (throw 'exit nil))
14978 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14979 (goto-char pos)
14980 nil))))
14982 (defun org-show-siblings ()
14983 "Show all siblings of the current headline."
14984 (save-excursion
14985 (while (org-goto-sibling) (org-flag-heading nil)))
14986 (save-excursion
14987 (while (org-goto-sibling 'previous)
14988 (org-flag-heading nil))))
14990 (defun org-show-hidden-entry ()
14991 "Show an entry where even the heading is hidden."
14992 (save-excursion
14993 (org-show-entry)))
14995 (defun org-flag-heading (flag &optional entry)
14996 "Flag the current heading. FLAG non-nil means make invisible.
14997 When ENTRY is non-nil, show the entire entry."
14998 (save-excursion
14999 (org-back-to-heading t)
15000 ;; Check if we should show the entire entry
15001 (if entry
15002 (progn
15003 (org-show-entry)
15004 (save-excursion
15005 (and (outline-next-heading)
15006 (org-flag-heading nil))))
15007 (outline-flag-region (max (point-min) (1- (point)))
15008 (save-excursion (outline-end-of-heading) (point))
15009 flag))))
15011 (defun org-forward-same-level (arg)
15012 "Move forward to the ARG'th subheading at same level as this one.
15013 Stop at the first and last subheadings of a superior heading.
15014 This is like outline-forward-same-level, but invisible headings are ok."
15015 (interactive "p")
15016 (org-back-to-heading t)
15017 (while (> arg 0)
15018 (let ((point-to-move-to (save-excursion
15019 (org-get-next-sibling))))
15020 (if point-to-move-to
15021 (progn
15022 (goto-char point-to-move-to)
15023 (setq arg (1- arg)))
15024 (progn
15025 (setq arg 0)
15026 (error "No following same-level heading"))))))
15028 (defun org-get-next-sibling ()
15029 "Move to next heading of the same level, and return point.
15030 If there is no such heading, return nil.
15031 This is like outline-next-sibling, but invisible headings are ok."
15032 (let ((level (funcall outline-level)))
15033 (outline-next-heading)
15034 (while (and (not (eobp)) (> (funcall outline-level) level))
15035 (outline-next-heading))
15036 (if (or (eobp) (< (funcall outline-level) level))
15038 (point))))
15040 (defun org-end-of-subtree (&optional invisible-OK to-heading)
15041 ;; This is an exact copy of the original function, but it uses
15042 ;; `org-back-to-heading', to make it work also in invisible
15043 ;; trees. And is uses an invisible-OK argument.
15044 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
15045 (org-back-to-heading invisible-OK)
15046 (let ((first t)
15047 (level (funcall outline-level)))
15048 (while (and (not (eobp))
15049 (or first (> (funcall outline-level) level)))
15050 (setq first nil)
15051 (outline-next-heading))
15052 (unless to-heading
15053 (if (memq (preceding-char) '(?\n ?\^M))
15054 (progn
15055 ;; Go to end of line before heading
15056 (forward-char -1)
15057 (if (memq (preceding-char) '(?\n ?\^M))
15058 ;; leave blank line before heading
15059 (forward-char -1))))))
15060 (point))
15062 (defun org-show-subtree ()
15063 "Show everything after this heading at deeper levels."
15064 (outline-flag-region
15065 (point)
15066 (save-excursion
15067 (outline-end-of-subtree) (outline-next-heading) (point))
15068 nil))
15070 (defun org-show-entry ()
15071 "Show the body directly following this heading.
15072 Show the heading too, if it is currently invisible."
15073 (interactive)
15074 (save-excursion
15075 (condition-case nil
15076 (progn
15077 (org-back-to-heading t)
15078 (outline-flag-region
15079 (max (point-min) (1- (point)))
15080 (save-excursion
15081 (re-search-forward
15082 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
15083 (or (match-beginning 1) (point-max)))
15084 nil))
15085 (error nil))))
15087 (defun org-make-options-regexp (kwds)
15088 "Make a regular expression for keyword lines."
15089 (concat
15091 "#?[ \t]*\\+\\("
15092 (mapconcat 'regexp-quote kwds "\\|")
15093 "\\):[ \t]*"
15094 "\\(.+\\)"))
15096 ;; Make isearch reveal the necessary context
15097 (defun org-isearch-end ()
15098 "Reveal context after isearch exits."
15099 (when isearch-success ; only if search was successful
15100 (if (featurep 'xemacs)
15101 ;; Under XEmacs, the hook is run in the correct place,
15102 ;; we directly show the context.
15103 (org-show-context 'isearch)
15104 ;; In Emacs the hook runs *before* restoring the overlays.
15105 ;; So we have to use a one-time post-command-hook to do this.
15106 ;; (Emacs 22 has a special variable, see function `org-mode')
15107 (unless (and (boundp 'isearch-mode-end-hook-quit)
15108 isearch-mode-end-hook-quit)
15109 ;; Only when the isearch was not quitted.
15110 (org-add-hook 'post-command-hook 'org-isearch-post-command
15111 'append 'local)))))
15113 (defun org-isearch-post-command ()
15114 "Remove self from hook, and show context."
15115 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
15116 (org-show-context 'isearch))
15119 ;;;; Integration with and fixes for other packages
15121 ;;; Imenu support
15123 (defvar org-imenu-markers nil
15124 "All markers currently used by Imenu.")
15125 (make-variable-buffer-local 'org-imenu-markers)
15127 (defun org-imenu-new-marker (&optional pos)
15128 "Return a new marker for use by Imenu, and remember the marker."
15129 (let ((m (make-marker)))
15130 (move-marker m (or pos (point)))
15131 (push m org-imenu-markers)
15134 (defun org-imenu-get-tree ()
15135 "Produce the index for Imenu."
15136 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
15137 (setq org-imenu-markers nil)
15138 (let* ((n org-imenu-depth)
15139 (re (concat "^" outline-regexp))
15140 (subs (make-vector (1+ n) nil))
15141 (last-level 0)
15142 m level head)
15143 (save-excursion
15144 (save-restriction
15145 (widen)
15146 (goto-char (point-max))
15147 (while (re-search-backward re nil t)
15148 (setq level (org-reduced-level (funcall outline-level)))
15149 (when (<= level n)
15150 (looking-at org-complex-heading-regexp)
15151 (setq head (org-link-display-format
15152 (org-match-string-no-properties 4))
15153 m (org-imenu-new-marker))
15154 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
15155 (if (>= level last-level)
15156 (push (cons head m) (aref subs level))
15157 (push (cons head (aref subs (1+ level))) (aref subs level))
15158 (loop for i from (1+ level) to n do (aset subs i nil)))
15159 (setq last-level level)))))
15160 (aref subs 1)))
15162 (eval-after-load "imenu"
15163 '(progn
15164 (add-hook 'imenu-after-jump-hook
15165 (lambda ()
15166 (if (eq major-mode 'org-mode)
15167 (org-show-context 'org-goto))))))
15169 (defun org-link-display-format (link)
15170 "Replace a link with either the description, or the link target
15171 if no description is present"
15172 (save-match-data
15173 (if (string-match org-bracket-link-analytic-regexp link)
15174 (replace-match (or (match-string 5 link)
15175 (concat (match-string 1 link)
15176 (match-string 3 link)))
15177 nil nil link)
15178 link)))
15180 ;; Speedbar support
15182 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
15183 "Overlay marking the agenda restriction line in speedbar.")
15184 (org-overlay-put org-speedbar-restriction-lock-overlay
15185 'face 'org-agenda-restriction-lock)
15186 (org-overlay-put org-speedbar-restriction-lock-overlay
15187 'help-echo "Agendas are currently limited to this item.")
15188 (org-detach-overlay org-speedbar-restriction-lock-overlay)
15190 (defun org-speedbar-set-agenda-restriction ()
15191 "Restrict future agenda commands to the location at point in speedbar.
15192 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
15193 (interactive)
15194 (require 'org-agenda)
15195 (let (p m tp np dir txt)
15196 (cond
15197 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15198 'org-imenu t))
15199 (setq m (get-text-property p 'org-imenu-marker))
15200 (save-excursion
15201 (save-restriction
15202 (set-buffer (marker-buffer m))
15203 (goto-char m)
15204 (org-agenda-set-restriction-lock 'subtree))))
15205 ((setq p (text-property-any (point-at-bol) (point-at-eol)
15206 'speedbar-function 'speedbar-find-file))
15207 (setq tp (previous-single-property-change
15208 (1+ p) 'speedbar-function)
15209 np (next-single-property-change
15210 tp 'speedbar-function)
15211 dir (speedbar-line-directory)
15212 txt (buffer-substring-no-properties (or tp (point-min))
15213 (or np (point-max))))
15214 (save-excursion
15215 (save-restriction
15216 (set-buffer (find-file-noselect
15217 (let ((default-directory dir))
15218 (expand-file-name txt))))
15219 (unless (org-mode-p)
15220 (error "Cannot restrict to non-Org-mode file"))
15221 (org-agenda-set-restriction-lock 'file))))
15222 (t (error "Don't know how to restrict Org-mode's agenda")))
15223 (org-move-overlay org-speedbar-restriction-lock-overlay
15224 (point-at-bol) (point-at-eol))
15225 (setq current-prefix-arg nil)
15226 (org-agenda-maybe-redo)))
15228 (eval-after-load "speedbar"
15229 '(progn
15230 (speedbar-add-supported-extension ".org")
15231 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
15232 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
15233 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
15234 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
15235 (add-hook 'speedbar-visiting-tag-hook
15236 (lambda () (and (org-mode-p) (org-show-context 'org-goto))))))
15239 ;;; Fixes and Hacks for problems with other packages
15241 ;; Make flyspell not check words in links, to not mess up our keymap
15242 (defun org-mode-flyspell-verify ()
15243 "Don't let flyspell put overlays at active buttons."
15244 (not (get-text-property (point) 'keymap)))
15246 ;; Make `bookmark-jump' show the jump location if it was hidden.
15247 (eval-after-load "bookmark"
15248 '(if (boundp 'bookmark-after-jump-hook)
15249 ;; We can use the hook
15250 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
15251 ;; Hook not available, use advice
15252 (defadvice bookmark-jump (after org-make-visible activate)
15253 "Make the position visible."
15254 (org-bookmark-jump-unhide))))
15256 ;; Make sure saveplace show the location if it was hidden
15257 (eval-after-load "saveplace"
15258 '(defadvice save-place-find-file-hook (after org-make-visible activate)
15259 "Make the position visible."
15260 (org-bookmark-jump-unhide)))
15262 (defun org-bookmark-jump-unhide ()
15263 "Unhide the current position, to show the bookmark location."
15264 (and (org-mode-p)
15265 (or (org-invisible-p)
15266 (save-excursion (goto-char (max (point-min) (1- (point))))
15267 (org-invisible-p)))
15268 (org-show-context 'bookmark-jump)))
15270 ;; Make session.el ignore our circular variable
15271 (eval-after-load "session"
15272 '(add-to-list 'session-globals-exclude 'org-mark-ring))
15274 ;;;; Experimental code
15276 (defun org-closed-in-range ()
15277 "Sparse tree of items closed in a certain time range.
15278 Still experimental, may disappear in the future."
15279 (interactive)
15280 ;; Get the time interval from the user.
15281 (let* ((time1 (time-to-seconds
15282 (org-read-date nil 'to-time nil "Starting date: ")))
15283 (time2 (time-to-seconds
15284 (org-read-date nil 'to-time nil "End date:")))
15285 ;; callback function
15286 (callback (lambda ()
15287 (let ((time
15288 (time-to-seconds
15289 (apply 'encode-time
15290 (org-parse-time-string
15291 (match-string 1))))))
15292 ;; check if time in interval
15293 (and (>= time time1) (<= time time2))))))
15294 ;; make tree, check each match with the callback
15295 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
15298 ;;;; Finish up
15300 (provide 'org)
15302 (run-hooks 'org-load-hook)
15304 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
15306 ;;; org.el ends here