Make sure LaTeX export works in the presence of link attributes.
[org-mode.git] / lisp / org.el
blobedc8a7dc004a6c974e34dbd053b60681ebc86882
1 ;;; org.el --- Outline-based notes management and organizer
2 ;; Carstens outline-mode for keeping track of everything.
3 ;; Copyright (C) 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc.
4 ;;
5 ;; Author: Carsten Dominik <carsten at orgmode dot org>
6 ;; Keywords: outlines, hypermedia, calendar, wp
7 ;; Homepage: http://orgmode.org
8 ;; Version: 6.06pre01
9 ;;
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
24 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
26 ;;; Commentary:
28 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
29 ;; project planning with a fast and effective plain-text system.
31 ;; Org-mode develops organizational tasks around NOTES files that contain
32 ;; information about projects as plain text. Org-mode is implemented on
33 ;; top of outline-mode, which makes it possible to keep the content of
34 ;; large files well structured. Visibility cycling and structure editing
35 ;; help to work with the tree. Tables are easily created with a built-in
36 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
37 ;; and scheduling. It dynamically compiles entries into an agenda that
38 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
39 ;; Plain text URL-like links connect to websites, emails, Usenet
40 ;; messages, BBDB entries, and any files related to the projects. For
41 ;; printing and sharing of notes, an Org-mode file can be exported as a
42 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
43 ;; iCalendar file. It can also serve as a publishing tool for a set of
44 ;; linked webpages.
46 ;; Installation and Activation
47 ;; ---------------------------
48 ;; See the corresponding sections in the manual at
50 ;; http://orgmode.org/org.html#Installation
52 ;; Documentation
53 ;; -------------
54 ;; The documentation of Org-mode can be found in the TeXInfo file. The
55 ;; distribution also contains a PDF version of it. At the homepage of
56 ;; Org-mode, you can read the same text online as HTML. There is also an
57 ;; excellent reference card made by Philip Rooke. This card can be found
58 ;; in the etc/ directory of Emacs 22.
60 ;; A list of recent changes can be found at
61 ;; http://orgmode.org/Changes.html
63 ;;; Code:
65 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
66 (defvar org-table-formula-constants-local nil
67 "Local version of `org-table-formula-constants'.")
68 (make-variable-buffer-local 'org-table-formula-constants-local)
70 ;;;; Require other packages
72 (eval-when-compile
73 (require 'cl)
74 (require 'gnus-sum)
75 (require 'calendar))
76 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
77 ;; the file noutline.el being loaded.
78 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
79 ;; We require noutline, which might be provided in outline.el
80 (require 'outline) (require 'noutline)
81 ;; Other stuff we need.
82 (require 'time-date)
83 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
84 (require 'easymenu)
86 (require 'org-macs)
87 (require 'org-compat)
88 (require 'org-faces)
90 ;;;; Customization variables
92 ;;; Version
94 (defconst org-version "6.06pre01"
95 "The version number of the file org.el.")
97 (defun org-version (&optional here)
98 "Show the org-mode version in the echo area.
99 With prefix arg HERE, insert it at point."
100 (interactive "P")
101 (let ((version (format "Org-mode version %s" org-version)))
102 (message version)
103 (if here
104 (insert version))))
106 ;;; Compatibility constants
108 ;;; The custom variables
110 (defgroup org nil
111 "Outline-based notes management and organizer."
112 :tag "Org"
113 :group 'outlines
114 :group 'hypermedia
115 :group 'calendar)
117 (defcustom org-load-hook nil
118 "Hook that is run after org.el has been loaded."
119 :group 'org
120 :type 'hook)
122 (defvar org-modules) ; defined below
123 (defvar org-modules-loaded nil
124 "Have the modules been loaded already?")
126 (defun org-load-modules-maybe (&optional force)
127 "Load all extensions listed in `org-default-extensions'."
128 (when (or force (not org-modules-loaded))
129 (mapc (lambda (ext)
130 (condition-case nil (require ext)
131 (error (message "Problems while trying to load feature `%s'" ext))))
132 org-modules)
133 (setq org-modules-loaded t)))
135 (defun org-set-modules (var value)
136 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
137 (set var value)
138 (when (featurep 'org)
139 (org-load-modules-maybe 'force)))
141 (when (org-bound-and-true-p org-modules)
142 (let ((a (member 'org-infojs org-modules)))
143 (and a (setcar a 'org-jsinfo))))
145 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-jsinfo org-irc org-mew org-mhe org-rmail org-vm org-wl)
146 "Modules that should always be loaded together with org.el.
147 If a description starts with <C>, the file is not part of Emacs
148 and loading it will require that you have downloaded and properly installed
149 the org-mode distribution.
151 You can also use this system to load external packages (i.e. neither Org
152 core modules, not modules from the CONTRIB directory). Just add symbols
153 to the end of the list. If the package is called org-xyz.el, then you need
154 to add the symbol `xyz', and the package must have a call to
156 (provide 'org-xyz)"
157 :group 'org
158 :set 'org-set-modules
159 :type
160 '(set :greedy t
161 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
162 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
163 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
164 (const :tag " id: Global id's for identifying entries" org-id)
165 (const :tag " info: Links to Info nodes" org-info)
166 (const :tag " jsinfo: Set up Sebastian Rose's JavaScript org-info.js" org-jsinfo)
167 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
168 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
169 (const :tag " mew Links to Mew folders/messages" org-mew)
170 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
171 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
172 (const :tag " vm: Links to VM folders/messages" org-vm)
173 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
174 (const :tag " mouse: Additional mouse support" org-mouse)
176 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
177 (const :tag "C annotation-helper: Call Remeber directly from Browser" org-annotation-helper)
178 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
179 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
180 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
181 (const :tag "C eval: Include command output as text" org-eval)
182 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
183 (const :tag "C id: Global id's for identifying entries" org-id)
184 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
185 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
186 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
187 (const :tag "C mtags: Support for muse-like tags" org-mtags)
188 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
189 (const :tag "C registry: A registry for Org links" org-registry)
190 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
191 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
192 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
193 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
194 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
197 (defgroup org-startup nil
198 "Options concerning startup of Org-mode."
199 :tag "Org Startup"
200 :group 'org)
202 (defcustom org-startup-folded t
203 "Non-nil means, entering Org-mode will switch to OVERVIEW.
204 This can also be configured on a per-file basis by adding one of
205 the following lines anywhere in the buffer:
207 #+STARTUP: fold
208 #+STARTUP: nofold
209 #+STARTUP: content"
210 :group 'org-startup
211 :type '(choice
212 (const :tag "nofold: show all" nil)
213 (const :tag "fold: overview" t)
214 (const :tag "content: all headlines" content)))
216 (defcustom org-startup-truncated t
217 "Non-nil means, entering Org-mode will set `truncate-lines'.
218 This is useful since some lines containing links can be very long and
219 uninteresting. Also tables look terrible when wrapped."
220 :group 'org-startup
221 :type 'boolean)
223 (defcustom org-startup-indented nil
224 "Non-nil means, turn on `org-indent-mode' on startup.
225 This can also be configured on a per-file basis by adding one of
226 the following lines anywhere in the buffer:
228 #+STARTUP: localindent
229 #+STARTUP: indent
230 #+STARTUP: noindent"
231 :group 'org-structure
232 :type '(choice
233 (const :tag "Not" nil)
234 (const :tag "Locally" local)
235 (const :tag "Globally (slow on startup in large files)" t)))
237 (defcustom org-startup-align-all-tables nil
238 "Non-nil means, align all tables when visiting a file.
239 This is useful when the column width in tables is forced with <N> cookies
240 in table fields. Such tables will look correct only after the first re-align.
241 This can also be configured on a per-file basis by adding one of
242 the following lines anywhere in the buffer:
243 #+STARTUP: align
244 #+STARTUP: noalign"
245 :group 'org-startup
246 :type 'boolean)
248 (defcustom org-insert-mode-line-in-empty-file nil
249 "Non-nil means insert the first line setting Org-mode in empty files.
250 When the function `org-mode' is called interactively in an empty file, this
251 normally means that the file name does not automatically trigger Org-mode.
252 To ensure that the file will always be in Org-mode in the future, a
253 line enforcing Org-mode will be inserted into the buffer, if this option
254 has been set."
255 :group 'org-startup
256 :type 'boolean)
258 (defcustom org-replace-disputed-keys nil
259 "Non-nil means use alternative key bindings for some keys.
260 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
261 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
262 If you want to use Org-mode together with one of these other modes,
263 or more generally if you would like to move some Org-mode commands to
264 other keys, set this variable and configure the keys with the variable
265 `org-disputed-keys'.
267 This option is only relevant at load-time of Org-mode, and must be set
268 *before* org.el is loaded. Changing it requires a restart of Emacs to
269 become effective."
270 :group 'org-startup
271 :type 'boolean)
273 (if (fboundp 'defvaralias)
274 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
276 (defcustom org-disputed-keys
277 '(([(shift up)] . [(meta p)])
278 ([(shift down)] . [(meta n)])
279 ([(shift left)] . [(meta -)])
280 ([(shift right)] . [(meta +)])
281 ([(control shift right)] . [(meta shift +)])
282 ([(control shift left)] . [(meta shift -)]))
283 "Keys for which Org-mode and other modes compete.
284 This is an alist, cars are the default keys, second element specifies
285 the alternative to use when `org-replace-disputed-keys' is t.
287 Keys can be specified in any syntax supported by `define-key'.
288 The value of this option takes effect only at Org-mode's startup,
289 therefore you'll have to restart Emacs to apply it after changing."
290 :group 'org-startup
291 :type 'alist)
293 (defun org-key (key)
294 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
295 Or return the original if not disputed."
296 (if org-replace-disputed-keys
297 (let* ((nkey (key-description key))
298 (x (org-find-if (lambda (x)
299 (equal (key-description (car x)) nkey))
300 org-disputed-keys)))
301 (if x (cdr x) key))
302 key))
304 (defun org-find-if (predicate seq)
305 (catch 'exit
306 (while seq
307 (if (funcall predicate (car seq))
308 (throw 'exit (car seq))
309 (pop seq)))))
311 (defun org-defkey (keymap key def)
312 "Define a key, possibly translated, as returned by `org-key'."
313 (define-key keymap (org-key key) def))
315 (defcustom org-ellipsis nil
316 "The ellipsis to use in the Org-mode outline.
317 When nil, just use the standard three dots. When a string, use that instead,
318 When a face, use the standart 3 dots, but with the specified face.
319 The change affects only Org-mode (which will then use its own display table).
320 Changing this requires executing `M-x org-mode' in a buffer to become
321 effective."
322 :group 'org-startup
323 :type '(choice (const :tag "Default" nil)
324 (face :tag "Face" :value org-warning)
325 (string :tag "String" :value "...#")))
327 (defvar org-display-table nil
328 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
330 (defgroup org-keywords nil
331 "Keywords in Org-mode."
332 :tag "Org Keywords"
333 :group 'org)
335 (defcustom org-deadline-string "DEADLINE:"
336 "String to mark deadline entries.
337 A deadline is this string, followed by a time stamp. Should be a word,
338 terminated by a colon. You can insert a schedule keyword and
339 a timestamp with \\[org-deadline].
340 Changes become only effective after restarting Emacs."
341 :group 'org-keywords
342 :type 'string)
344 (defcustom org-scheduled-string "SCHEDULED:"
345 "String to mark scheduled TODO entries.
346 A schedule is this string, followed by a time stamp. Should be a word,
347 terminated by a colon. You can insert a schedule keyword and
348 a timestamp with \\[org-schedule].
349 Changes become only effective after restarting Emacs."
350 :group 'org-keywords
351 :type 'string)
353 (defcustom org-closed-string "CLOSED:"
354 "String used as the prefix for timestamps logging closing a TODO entry."
355 :group 'org-keywords
356 :type 'string)
358 (defcustom org-clock-string "CLOCK:"
359 "String used as prefix for timestamps clocking work hours on an item."
360 :group 'org-keywords
361 :type 'string)
363 (defcustom org-comment-string "COMMENT"
364 "Entries starting with this keyword will never be exported.
365 An entry can be toggled between COMMENT and normal with
366 \\[org-toggle-comment].
367 Changes become only effective after restarting Emacs."
368 :group 'org-keywords
369 :type 'string)
371 (defcustom org-quote-string "QUOTE"
372 "Entries starting with this keyword will be exported in fixed-width font.
373 Quoting applies only to the text in the entry following the headline, and does
374 not extend beyond the next headline, even if that is lower level.
375 An entry can be toggled between QUOTE and normal with
376 \\[org-toggle-fixed-width-section]."
377 :group 'org-keywords
378 :type 'string)
380 (defconst org-repeat-re
381 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
382 "Regular expression for specifying repeated events.
383 After a match, group 1 contains the repeat expression.")
385 (defgroup org-structure nil
386 "Options concerning the general structure of Org-mode files."
387 :tag "Org Structure"
388 :group 'org)
390 (defgroup org-reveal-location nil
391 "Options about how to make context of a location visible."
392 :tag "Org Reveal Location"
393 :group 'org-structure)
395 (defconst org-context-choice
396 '(choice
397 (const :tag "Always" t)
398 (const :tag "Never" nil)
399 (repeat :greedy t :tag "Individual contexts"
400 (cons
401 (choice :tag "Context"
402 (const agenda)
403 (const org-goto)
404 (const occur-tree)
405 (const tags-tree)
406 (const link-search)
407 (const mark-goto)
408 (const bookmark-jump)
409 (const isearch)
410 (const default))
411 (boolean))))
412 "Contexts for the reveal options.")
414 (defcustom org-show-hierarchy-above '((default . t))
415 "Non-nil means, show full hierarchy when revealing a location.
416 Org-mode often shows locations in an org-mode file which might have
417 been invisible before. When this is set, the hierarchy of headings
418 above the exposed location is shown.
419 Turning this off for example for sparse trees makes them very compact.
420 Instead of t, this can also be an alist specifying this option for different
421 contexts. Valid contexts are
422 agenda when exposing an entry from the agenda
423 org-goto when using the command `org-goto' on key C-c C-j
424 occur-tree when using the command `org-occur' on key C-c /
425 tags-tree when constructing a sparse tree based on tags matches
426 link-search when exposing search matches associated with a link
427 mark-goto when exposing the jump goal of a mark
428 bookmark-jump when exposing a bookmark location
429 isearch when exiting from an incremental search
430 default default for all contexts not set explicitly"
431 :group 'org-reveal-location
432 :type org-context-choice)
434 (defcustom org-show-following-heading '((default . nil))
435 "Non-nil means, show following heading when revealing a location.
436 Org-mode often shows locations in an org-mode file which might have
437 been invisible before. When this is set, the heading following the
438 match is shown.
439 Turning this off for example for sparse trees makes them very compact,
440 but makes it harder to edit the location of the match. In such a case,
441 use the command \\[org-reveal] to show more context.
442 Instead of t, this can also be an alist specifying this option for different
443 contexts. See `org-show-hierarchy-above' for valid contexts."
444 :group 'org-reveal-location
445 :type org-context-choice)
447 (defcustom org-show-siblings '((default . nil) (isearch t))
448 "Non-nil means, show all sibling heading when revealing a location.
449 Org-mode often shows locations in an org-mode file which might have
450 been invisible before. When this is set, the sibling of the current entry
451 heading are all made visible. If `org-show-hierarchy-above' is t,
452 the same happens on each level of the hierarchy above the current entry.
454 By default this is on for the isearch context, off for all other contexts.
455 Turning this off for example for sparse trees makes them very compact,
456 but makes it harder to edit the location of the match. In such a case,
457 use the command \\[org-reveal] to show more context.
458 Instead of t, this can also be an alist specifying this option for different
459 contexts. See `org-show-hierarchy-above' for valid contexts."
460 :group 'org-reveal-location
461 :type org-context-choice)
463 (defcustom org-show-entry-below '((default . nil))
464 "Non-nil means, show the entry below a headline when revealing a location.
465 Org-mode often shows locations in an org-mode file which might have
466 been invisible before. When this is set, the text below the headline that is
467 exposed is also shown.
469 By default this is off for all contexts.
470 Instead of t, this can also be an alist specifying this option for different
471 contexts. See `org-show-hierarchy-above' for valid contexts."
472 :group 'org-reveal-location
473 :type org-context-choice)
475 (defcustom org-indirect-buffer-display 'other-window
476 "How should indirect tree buffers be displayed?
477 This applies to indirect buffers created with the commands
478 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
479 Valid values are:
480 current-window Display in the current window
481 other-window Just display in another window.
482 dedicated-frame Create one new frame, and re-use it each time.
483 new-frame Make a new frame each time. Note that in this case
484 previously-made indirect buffers are kept, and you need to
485 kill these buffers yourself."
486 :group 'org-structure
487 :group 'org-agenda-windows
488 :type '(choice
489 (const :tag "In current window" current-window)
490 (const :tag "In current frame, other window" other-window)
491 (const :tag "Each time a new frame" new-frame)
492 (const :tag "One dedicated frame" dedicated-frame)))
494 (defgroup org-cycle nil
495 "Options concerning visibility cycling in Org-mode."
496 :tag "Org Cycle"
497 :group 'org-structure)
499 (defcustom org-drawers '("PROPERTIES" "CLOCK")
500 "Names of drawers. Drawers are not opened by cycling on the headline above.
501 Drawers only open with a TAB on the drawer line itself. A drawer looks like
502 this:
503 :DRAWERNAME:
504 .....
505 :END:
506 The drawer \"PROPERTIES\" is special for capturing properties through
507 the property API.
509 Drawers can be defined on the per-file basis with a line like:
511 #+DRAWERS: HIDDEN STATE PROPERTIES"
512 :group 'org-structure
513 :type '(repeat (string :tag "Drawer Name")))
515 (defcustom org-cycle-global-at-bob nil
516 "Cycle globally if cursor is at beginning of buffer and not at a headline.
517 This makes it possible to do global cycling without having to use S-TAB or
518 C-u TAB. For this special case to work, the first line of the buffer
519 must not be a headline - it may be empty ot some other text. When used in
520 this way, `org-cycle-hook' is disables temporarily, to make sure the
521 cursor stays at the beginning of the buffer.
522 When this option is nil, don't do anything special at the beginning
523 of the buffer."
524 :group 'org-cycle
525 :type 'boolean)
527 (defcustom org-cycle-emulate-tab t
528 "Where should `org-cycle' emulate TAB.
529 nil Never
530 white Only in completely white lines
531 whitestart Only at the beginning of lines, before the first non-white char
532 t Everywhere except in headlines
533 exc-hl-bol Everywhere except at the start of a headline
534 If TAB is used in a place where it does not emulate TAB, the current subtree
535 visibility is cycled."
536 :group 'org-cycle
537 :type '(choice (const :tag "Never" nil)
538 (const :tag "Only in completely white lines" white)
539 (const :tag "Before first char in a line" whitestart)
540 (const :tag "Everywhere except in headlines" t)
541 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
544 (defcustom org-cycle-separator-lines 2
545 "Number of empty lines needed to keep an empty line between collapsed trees.
546 If you leave an empty line between the end of a subtree and the following
547 headline, this empty line is hidden when the subtree is folded.
548 Org-mode will leave (exactly) one empty line visible if the number of
549 empty lines is equal or larger to the number given in this variable.
550 So the default 2 means, at least 2 empty lines after the end of a subtree
551 are needed to produce free space between a collapsed subtree and the
552 following headline.
554 Special case: when 0, never leave empty lines in collapsed view."
555 :group 'org-cycle
556 :type 'integer)
558 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
559 org-cycle-hide-drawers
560 org-cycle-show-empty-lines
561 org-optimize-window-after-visibility-change)
562 "Hook that is run after `org-cycle' has changed the buffer visibility.
563 The function(s) in this hook must accept a single argument which indicates
564 the new state that was set by the most recent `org-cycle' command. The
565 argument is a symbol. After a global state change, it can have the values
566 `overview', `content', or `all'. After a local state change, it can have
567 the values `folded', `children', or `subtree'."
568 :group 'org-cycle
569 :type 'hook)
571 (defgroup org-edit-structure nil
572 "Options concerning structure editing in Org-mode."
573 :tag "Org Edit Structure"
574 :group 'org-structure)
576 (defcustom org-odd-levels-only nil
577 "Non-nil means, skip even levels and only use odd levels for the outline.
578 This has the effect that two stars are being added/taken away in
579 promotion/demotion commands. It also influences how levels are
580 handled by the exporters.
581 Changing it requires restart of `font-lock-mode' to become effective
582 for fontification also in regions already fontified.
583 You may also set this on a per-file basis by adding one of the following
584 lines to the buffer:
586 #+STARTUP: odd
587 #+STARTUP: oddeven"
588 :group 'org-edit-structure
589 :group 'org-font-lock
590 :type 'boolean)
592 (defcustom org-adapt-indentation t
593 "Non-nil means, adapt indentation when promoting and demoting.
594 When this is set and the *entire* text in an entry is indented, the
595 indentation is increased by one space in a demotion command, and
596 decreased by one in a promotion command. If any line in the entry
597 body starts at column 0, indentation is not changed at all."
598 :group 'org-edit-structure
599 :type 'boolean)
601 (defcustom org-special-ctrl-a/e nil
602 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
603 When t, `C-a' will bring back the cursor to the beginning of the
604 headline text, i.e. after the stars and after a possible TODO keyword.
605 In an item, this will be the position after the bullet.
606 When the cursor is already at that position, another `C-a' will bring
607 it to the beginning of the line.
608 `C-e' will jump to the end of the headline, ignoring the presence of tags
609 in the headline. A second `C-e' will then jump to the true end of the
610 line, after any tags.
611 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
612 and only a directly following, identical keypress will bring the cursor
613 to the special positions."
614 :group 'org-edit-structure
615 :type '(choice
616 (const :tag "off" nil)
617 (const :tag "after bullet first" t)
618 (const :tag "border first" reversed)))
620 (if (fboundp 'defvaralias)
621 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
623 (defcustom org-special-ctrl-k nil
624 "Non-nil means `C-k' will behave specially in headlines.
625 When nil, `C-k' will call the default `kill-line' command.
626 When t, the following will happen while the cursor is in the headline:
628 - When the cursor is at the beginning of a headline, kill the entire
629 line and possible the folded subtree below the line.
630 - When in the middle of the headline text, kill the headline up to the tags.
631 - When after the headline text, kill the tags."
632 :group 'org-edit-structure
633 :type 'boolean)
635 (defcustom org-M-RET-may-split-line '((default . t))
636 "Non-nil means, M-RET will split the line at the cursor position.
637 When nil, it will go to the end of the line before making a
638 new line.
639 You may also set this option in a different way for different
640 contexts. Valid contexts are:
642 headline when creating a new headline
643 item when creating a new item
644 table in a table field
645 default the value to be used for all contexts not explicitly
646 customized"
647 :group 'org-structure
648 :group 'org-table
649 :type '(choice
650 (const :tag "Always" t)
651 (const :tag "Never" nil)
652 (repeat :greedy t :tag "Individual contexts"
653 (cons
654 (choice :tag "Context"
655 (const headline)
656 (const item)
657 (const table)
658 (const default))
659 (boolean)))))
662 (defcustom org-blank-before-new-entry '((heading . nil)
663 (plain-list-item . nil))
664 "Should `org-insert-heading' leave a blank line before new heading/item?
665 The value is an alist, with `heading' and `plain-list-item' as car,
666 and a boolean flag as cdr."
667 :group 'org-edit-structure
668 :type '(list
669 (cons (const heading) (boolean))
670 (cons (const plain-list-item) (boolean))))
672 (defcustom org-insert-heading-hook nil
673 "Hook being run after inserting a new heading."
674 :group 'org-edit-structure
675 :type 'hook)
677 (defcustom org-enable-fixed-width-editor t
678 "Non-nil means, lines starting with \":\" are treated as fixed-width.
679 This currently only means, they are never auto-wrapped.
680 When nil, such lines will be treated like ordinary lines.
681 See also the QUOTE keyword."
682 :group 'org-edit-structure
683 :type 'boolean)
685 (defcustom org-goto-auto-isearch t
686 "Non-nil means, typing characters in org-goto starts incremental search."
687 :group 'org-edit-structure
688 :type 'boolean)
690 (defgroup org-sparse-trees nil
691 "Options concerning sparse trees in Org-mode."
692 :tag "Org Sparse Trees"
693 :group 'org-structure)
695 (defcustom org-highlight-sparse-tree-matches t
696 "Non-nil means, highlight all matches that define a sparse tree.
697 The highlights will automatically disappear the next time the buffer is
698 changed by an edit command."
699 :group 'org-sparse-trees
700 :type 'boolean)
702 (defcustom org-remove-highlights-with-change t
703 "Non-nil means, any change to the buffer will remove temporary highlights.
704 Such highlights are created by `org-occur' and `org-clock-display'.
705 When nil, `C-c C-c needs to be used to get rid of the highlights.
706 The highlights created by `org-preview-latex-fragment' always need
707 `C-c C-c' to be removed."
708 :group 'org-sparse-trees
709 :group 'org-time
710 :type 'boolean)
713 (defcustom org-occur-hook '(org-first-headline-recenter)
714 "Hook that is run after `org-occur' has constructed a sparse tree.
715 This can be used to recenter the window to show as much of the structure
716 as possible."
717 :group 'org-sparse-trees
718 :type 'hook)
720 (defgroup org-plain-lists nil
721 "Options concerning plain lists in Org-mode."
722 :tag "Org Plain lists"
723 :group 'org-structure)
725 (defcustom org-cycle-include-plain-lists nil
726 "Non-nil means, include plain lists into visibility cycling.
727 This means that during cycling, plain list items will *temporarily* be
728 interpreted as outline headlines with a level given by 1000+i where i is the
729 indentation of the bullet. In all other operations, plain list items are
730 not seen as headlines. For example, you cannot assign a TODO keyword to
731 such an item."
732 :group 'org-plain-lists
733 :type 'boolean)
735 (defcustom org-plain-list-ordered-item-terminator t
736 "The character that makes a line with leading number an ordered list item.
737 Valid values are ?. and ?\). To get both terminators, use t. While
738 ?. may look nicer, it creates the danger that a line with leading
739 number may be incorrectly interpreted as an item. ?\) therefore is
740 the safe choice."
741 :group 'org-plain-lists
742 :type '(choice (const :tag "dot like in \"2.\"" ?.)
743 (const :tag "paren like in \"2)\"" ?\))
744 (const :tab "both" t)))
746 (defcustom org-empty-line-terminates-plain-lists nil
747 "Non-nil means, an empty line ends all plain list levels.
748 When nil, empty lines are part of the preceeding item."
749 :group 'org-plain-lists
750 :type 'boolean)
752 (defcustom org-auto-renumber-ordered-lists t
753 "Non-nil means, automatically renumber ordered plain lists.
754 Renumbering happens when the sequence have been changed with
755 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
756 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
757 :group 'org-plain-lists
758 :type 'boolean)
760 (defcustom org-provide-checkbox-statistics t
761 "Non-nil means, update checkbox statistics after insert and toggle.
762 When this is set, checkbox statistics is updated each time you either insert
763 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
764 with \\[org-ctrl-c-ctrl-c\\]."
765 :group 'org-plain-lists
766 :type 'boolean)
768 (defcustom org-description-max-indent 20
769 "Maximum indentation for the second line of a description list.
770 When the indentation would be larger than this, it will become
771 5 characters instead."
772 :group 'org-plain-lists
773 :type 'integer)
775 (defgroup org-imenu-and-speedbar nil
776 "Options concerning imenu and speedbar in Org-mode."
777 :tag "Org Imenu and Speedbar"
778 :group 'org-structure)
780 (defcustom org-imenu-depth 2
781 "The maximum level for Imenu access to Org-mode headlines.
782 This also applied for speedbar access."
783 :group 'org-imenu-and-speedbar
784 :type 'number)
786 (defgroup org-table nil
787 "Options concerning tables in Org-mode."
788 :tag "Org Table"
789 :group 'org)
791 (defcustom org-enable-table-editor 'optimized
792 "Non-nil means, lines starting with \"|\" are handled by the table editor.
793 When nil, such lines will be treated like ordinary lines.
795 When equal to the symbol `optimized', the table editor will be optimized to
796 do the following:
797 - Automatic overwrite mode in front of whitespace in table fields.
798 This makes the structure of the table stay in tact as long as the edited
799 field does not exceed the column width.
800 - Minimize the number of realigns. Normally, the table is aligned each time
801 TAB or RET are pressed to move to another field. With optimization this
802 happens only if changes to a field might have changed the column width.
803 Optimization requires replacing the functions `self-insert-command',
804 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
805 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
806 very good at guessing when a re-align will be necessary, but you can always
807 force one with \\[org-ctrl-c-ctrl-c].
809 If you would like to use the optimized version in Org-mode, but the
810 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
812 This variable can be used to turn on and off the table editor during a session,
813 but in order to toggle optimization, a restart is required.
815 See also the variable `org-table-auto-blank-field'."
816 :group 'org-table
817 :type '(choice
818 (const :tag "off" nil)
819 (const :tag "on" t)
820 (const :tag "on, optimized" optimized)))
822 (defcustom org-table-tab-recognizes-table.el t
823 "Non-nil means, TAB will automatically notice a table.el table.
824 When it sees such a table, it moves point into it and - if necessary -
825 calls `table-recognize-table'."
826 :group 'org-table-editing
827 :type 'boolean)
829 (defgroup org-link nil
830 "Options concerning links in Org-mode."
831 :tag "Org Link"
832 :group 'org)
834 (defvar org-link-abbrev-alist-local nil
835 "Buffer-local version of `org-link-abbrev-alist', which see.
836 The value of this is taken from the #+LINK lines.")
837 (make-variable-buffer-local 'org-link-abbrev-alist-local)
839 (defcustom org-link-abbrev-alist nil
840 "Alist of link abbreviations.
841 The car of each element is a string, to be replaced at the start of a link.
842 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
843 links in Org-mode buffers can have an optional tag after a double colon, e.g.
845 [[linkkey:tag][description]]
847 If REPLACE is a string, the tag will simply be appended to create the link.
848 If the string contains \"%s\", the tag will be inserted there.
850 REPLACE may also be a function that will be called with the tag as the
851 only argument to create the link, which should be returned as a string.
853 See the manual for examples."
854 :group 'org-link
855 :type 'alist)
857 (defcustom org-descriptive-links t
858 "Non-nil means, hide link part and only show description of bracket links.
859 Bracket links are like [[link][descritpion]]. This variable sets the initial
860 state in new org-mode buffers. The setting can then be toggled on a
861 per-buffer basis from the Org->Hyperlinks menu."
862 :group 'org-link
863 :type 'boolean)
865 (defcustom org-link-file-path-type 'adaptive
866 "How the path name in file links should be stored.
867 Valid values are:
869 relative Relative to the current directory, i.e. the directory of the file
870 into which the link is being inserted.
871 absolute Absolute path, if possible with ~ for home directory.
872 noabbrev Absolute path, no abbreviation of home directory.
873 adaptive Use relative path for files in the current directory and sub-
874 directories of it. For other files, use an absolute path."
875 :group 'org-link
876 :type '(choice
877 (const relative)
878 (const absolute)
879 (const noabbrev)
880 (const adaptive)))
882 (defcustom org-activate-links '(bracket angle plain radio tag date)
883 "Types of links that should be activated in Org-mode files.
884 This is a list of symbols, each leading to the activation of a certain link
885 type. In principle, it does not hurt to turn on most link types - there may
886 be a small gain when turning off unused link types. The types are:
888 bracket The recommended [[link][description]] or [[link]] links with hiding.
889 angular Links in angular brackes that may contain whitespace like
890 <bbdb:Carsten Dominik>.
891 plain Plain links in normal text, no whitespace, like http://google.com.
892 radio Text that is matched by a radio target, see manual for details.
893 tag Tag settings in a headline (link to tag search).
894 date Time stamps (link to calendar).
896 Changing this variable requires a restart of Emacs to become effective."
897 :group 'org-link
898 :type '(set (const :tag "Double bracket links (new style)" bracket)
899 (const :tag "Angular bracket links (old style)" angular)
900 (const :tag "Plain text links" plain)
901 (const :tag "Radio target matches" radio)
902 (const :tag "Tags" tag)
903 (const :tag "Timestamps" date)))
905 (defcustom org-make-link-description-function nil
906 "Function to use to generate link descriptions from links. If
907 nil the link location will be used. This function must take two
908 parameters; the first is the link and the second the description
909 org-insert-link has generated, and should return the description
910 to use."
911 :group 'org-link
912 :type 'function)
914 (defgroup org-link-store nil
915 "Options concerning storing links in Org-mode."
916 :tag "Org Store Link"
917 :group 'org-link)
919 (defcustom org-email-link-description-format "Email %c: %.30s"
920 "Format of the description part of a link to an email or usenet message.
921 The following %-excapes will be replaced by corresponding information:
923 %F full \"From\" field
924 %f name, taken from \"From\" field, address if no name
925 %T full \"To\" field
926 %t first name in \"To\" field, address if no name
927 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
928 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
929 %s subject
930 %m message-id.
932 You may use normal field width specification between the % and the letter.
933 This is for example useful to limit the length of the subject.
935 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
936 :group 'org-link-store
937 :type 'string)
939 (defcustom org-from-is-user-regexp
940 (let (r1 r2)
941 (when (and user-mail-address (not (string= user-mail-address "")))
942 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
943 (when (and user-full-name (not (string= user-full-name "")))
944 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
945 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
946 "Regexp mached against the \"From:\" header of an email or usenet message.
947 It should match if the message is from the user him/herself."
948 :group 'org-link-store
949 :type 'regexp)
951 (defcustom org-context-in-file-links t
952 "Non-nil means, file links from `org-store-link' contain context.
953 A search string will be added to the file name with :: as separator and
954 used to find the context when the link is activated by the command
955 `org-open-at-point'.
956 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
957 negates this setting for the duration of the command."
958 :group 'org-link-store
959 :type 'boolean)
961 (defcustom org-keep-stored-link-after-insertion nil
962 "Non-nil means, keep link in list for entire session.
964 The command `org-store-link' adds a link pointing to the current
965 location to an internal list. These links accumulate during a session.
966 The command `org-insert-link' can be used to insert links into any
967 Org-mode file (offering completion for all stored links). When this
968 option is nil, every link which has been inserted once using \\[org-insert-link]
969 will be removed from the list, to make completing the unused links
970 more efficient."
971 :group 'org-link-store
972 :type 'boolean)
974 (defgroup org-link-follow nil
975 "Options concerning following links in Org-mode."
976 :tag "Org Follow Link"
977 :group 'org-link)
979 (defcustom org-follow-link-hook nil
980 "Hook that is run after a link has been followed."
981 :group 'org-link-follow
982 :type 'hook)
984 (defcustom org-tab-follows-link nil
985 "Non-nil means, on links TAB will follow the link.
986 Needs to be set before org.el is loaded."
987 :group 'org-link-follow
988 :type 'boolean)
990 (defcustom org-return-follows-link nil
991 "Non-nil means, on links RET will follow the link.
992 Needs to be set before org.el is loaded."
993 :group 'org-link-follow
994 :type 'boolean)
996 (defcustom org-mouse-1-follows-link
997 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
998 "Non-nil means, mouse-1 on a link will follow the link.
999 A longer mouse click will still set point. Does not work on XEmacs.
1000 Needs to be set before org.el is loaded."
1001 :group 'org-link-follow
1002 :type 'boolean)
1004 (defcustom org-mark-ring-length 4
1005 "Number of different positions to be recorded in the ring
1006 Changing this requires a restart of Emacs to work correctly."
1007 :group 'org-link-follow
1008 :type 'interger)
1010 (defcustom org-link-frame-setup
1011 '((vm . vm-visit-folder-other-frame)
1012 (gnus . gnus-other-frame)
1013 (file . find-file-other-window))
1014 "Setup the frame configuration for following links.
1015 When following a link with Emacs, it may often be useful to display
1016 this link in another window or frame. This variable can be used to
1017 set this up for the different types of links.
1018 For VM, use any of
1019 `vm-visit-folder'
1020 `vm-visit-folder-other-frame'
1021 For Gnus, use any of
1022 `gnus'
1023 `gnus-other-frame'
1024 For FILE, use any of
1025 `find-file'
1026 `find-file-other-window'
1027 `find-file-other-frame'
1028 For the calendar, use the variable `calendar-setup'.
1029 For BBDB, it is currently only possible to display the matches in
1030 another window."
1031 :group 'org-link-follow
1032 :type '(list
1033 (cons (const vm)
1034 (choice
1035 (const vm-visit-folder)
1036 (const vm-visit-folder-other-window)
1037 (const vm-visit-folder-other-frame)))
1038 (cons (const gnus)
1039 (choice
1040 (const gnus)
1041 (const gnus-other-frame)))
1042 (cons (const file)
1043 (choice
1044 (const find-file)
1045 (const find-file-other-window)
1046 (const find-file-other-frame)))))
1048 (defcustom org-display-internal-link-with-indirect-buffer nil
1049 "Non-nil means, use indirect buffer to display infile links.
1050 Activating internal links (from one location in a file to another location
1051 in the same file) normally just jumps to the location. When the link is
1052 activated with a C-u prefix (or with mouse-3), the link is displayed in
1053 another window. When this option is set, the other window actually displays
1054 an indirect buffer clone of the current buffer, to avoid any visibility
1055 changes to the current buffer."
1056 :group 'org-link-follow
1057 :type 'boolean)
1059 (defcustom org-open-non-existing-files nil
1060 "Non-nil means, `org-open-file' will open non-existing files.
1061 When nil, an error will be generated."
1062 :group 'org-link-follow
1063 :type 'boolean)
1065 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1066 "Function and arguments to call for following mailto links.
1067 This is a list with the first element being a lisp function, and the
1068 remaining elements being arguments to the function. In string arguments,
1069 %a will be replaced by the address, and %s will be replaced by the subject
1070 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1071 :group 'org-link-follow
1072 :type '(choice
1073 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1074 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1075 (const :tag "message-mail" (message-mail "%a" "%s"))
1076 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1078 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1079 "Non-nil means, ask for confirmation before executing shell links.
1080 Shell links can be dangerous: just think about a link
1082 [[shell:rm -rf ~/*][Google Search]]
1084 This link would show up in your Org-mode document as \"Google Search\",
1085 but really it would remove your entire home directory.
1086 Therefore we advise against setting this variable to nil.
1087 Just change it to `y-or-n-p' of you want to confirm with a
1088 single keystroke rather than having to type \"yes\"."
1089 :group 'org-link-follow
1090 :type '(choice
1091 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1092 (const :tag "with y-or-n (faster)" y-or-n-p)
1093 (const :tag "no confirmation (dangerous)" nil)))
1095 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1096 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1097 Elisp links can be dangerous: just think about a link
1099 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1101 This link would show up in your Org-mode document as \"Google Search\",
1102 but really it would remove your entire home directory.
1103 Therefore we advise against setting this variable to nil.
1104 Just change it to `y-or-n-p' of you want to confirm with a
1105 single keystroke rather than having to type \"yes\"."
1106 :group 'org-link-follow
1107 :type '(choice
1108 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1109 (const :tag "with y-or-n (faster)" y-or-n-p)
1110 (const :tag "no confirmation (dangerous)" nil)))
1112 (defconst org-file-apps-defaults-gnu
1113 '((remote . emacs)
1114 (t . mailcap))
1115 "Default file applications on a UNIX or GNU/Linux system.
1116 See `org-file-apps'.")
1118 (defconst org-file-apps-defaults-macosx
1119 '((remote . emacs)
1120 (t . "open %s")
1121 ("ps" . "gv %s")
1122 ("ps.gz" . "gv %s")
1123 ("eps" . "gv %s")
1124 ("eps.gz" . "gv %s")
1125 ("dvi" . "xdvi %s")
1126 ("fig" . "xfig %s"))
1127 "Default file applications on a MacOS X system.
1128 The system \"open\" is known as a default, but we use X11 applications
1129 for some files for which the OS does not have a good default.
1130 See `org-file-apps'.")
1132 (defconst org-file-apps-defaults-windowsnt
1133 (list
1134 '(remote . emacs)
1135 (cons t
1136 (list (if (featurep 'xemacs)
1137 'mswindows-shell-execute
1138 'w32-shell-execute)
1139 "open" 'file)))
1140 "Default file applications on a Windows NT system.
1141 The system \"open\" is used for most files.
1142 See `org-file-apps'.")
1144 (defcustom org-file-apps
1146 ("txt" . emacs)
1147 ("tex" . emacs)
1148 ("ltx" . emacs)
1149 ("org" . emacs)
1150 ("el" . emacs)
1151 ("bib" . emacs)
1153 "External applications for opening `file:path' items in a document.
1154 Org-mode uses system defaults for different file types, but
1155 you can use this variable to set the application for a given file
1156 extension. The entries in this list are cons cells where the car identifies
1157 files and the cdr the corresponding command. Possible values for the
1158 file identifier are
1159 \"ext\" A string identifying an extension
1160 `directory' Matches a directory
1161 `remote' Matches a remote file, accessible through tramp or efs.
1162 Remote files most likely should be visited through Emacs
1163 because external applications cannot handle such paths.
1164 t Default for all remaining files
1166 Possible values for the command are:
1167 `emacs' The file will be visited by the current Emacs process.
1168 `default' Use the default application for this file type.
1169 string A command to be executed by a shell; %s will be replaced
1170 by the path to the file.
1171 sexp A Lisp form which will be evaluated. The file path will
1172 be available in the Lisp variable `file'.
1173 For more examples, see the system specific constants
1174 `org-file-apps-defaults-macosx'
1175 `org-file-apps-defaults-windowsnt'
1176 `org-file-apps-defaults-gnu'."
1177 :group 'org-link-follow
1178 :type '(repeat
1179 (cons (choice :value ""
1180 (string :tag "Extension")
1181 (const :tag "Default for unrecognized files" t)
1182 (const :tag "Remote file" remote)
1183 (const :tag "Links to a directory" directory))
1184 (choice :value ""
1185 (const :tag "Visit with Emacs" emacs)
1186 (const :tag "Use system default" default)
1187 (string :tag "Command")
1188 (sexp :tag "Lisp form")))))
1190 (defgroup org-refile nil
1191 "Options concerning refiling entries in Org-mode."
1192 :tag "Org Remember"
1193 :group 'org)
1195 (defcustom org-directory "~/org"
1196 "Directory with org files.
1197 This directory will be used as default to prompt for org files.
1198 Used by the hooks for remember.el."
1199 :group 'org-refile
1200 :group 'org-remember
1201 :type 'directory)
1203 (defcustom org-default-notes-file "~/.notes"
1204 "Default target for storing notes.
1205 Used by the hooks for remember.el. This can be a string, or nil to mean
1206 the value of `remember-data-file'.
1207 You can set this on a per-template basis with the variable
1208 `org-remember-templates'."
1209 :group 'org-refile
1210 :group 'org-remember
1211 :type '(choice
1212 (const :tag "Default from remember-data-file" nil)
1213 file))
1215 (defcustom org-goto-interface 'outline
1216 "The default interface to be used for `org-goto'.
1217 Allowed vaues are:
1218 outline The interface shows an outline of the relevant file
1219 and the correct heading is found by moving through
1220 the outline or by searching with incremental search.
1221 outline-path-completion Headlines in the current buffer are offered via
1222 completion."
1223 :group 'org-refile
1224 :type '(choice
1225 (const :tag "Outline" outline)
1226 (const :tag "Outline-path-completion" outline-path-completion)))
1228 (defcustom org-reverse-note-order nil
1229 "Non-nil means, store new notes at the beginning of a file or entry.
1230 When nil, new notes will be filed to the end of a file or entry.
1231 This can also be a list with cons cells of regular expressions that
1232 are matched against file names, and values."
1233 :group 'org-remember
1234 :type '(choice
1235 (const :tag "Reverse always" t)
1236 (const :tag "Reverse never" nil)
1237 (repeat :tag "By file name regexp"
1238 (cons regexp boolean))))
1240 (defcustom org-refile-targets nil
1241 "Targets for refiling entries with \\[org-refile].
1242 This is list of cons cells. Each cell contains:
1243 - a specification of the files to be considered, either a list of files,
1244 or a symbol whose function or variable value will be used to retrieve
1245 a file name or a list of file names. Nil means, refile to a different
1246 heading in the current buffer.
1247 - A specification of how to find candidate refile targets. This may be
1248 any of
1249 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1250 This tag has to be present in all target headlines, inheritance will
1251 not be considered.
1252 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1253 todo keyword.
1254 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1255 headlines that are refiling targets.
1256 - a cons cell (:level . N). Any headline of level N is considered a target.
1257 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1258 :group 'org-remember
1259 :type '(repeat
1260 (cons
1261 (choice :value org-agenda-files
1262 (const :tag "All agenda files" org-agenda-files)
1263 (const :tag "Current buffer" nil)
1264 (function) (variable) (file))
1265 (choice :tag "Identify target headline by"
1266 (cons :tag "Specific tag" (const :tag) (string))
1267 (cons :tag "TODO keyword" (const :todo) (string))
1268 (cons :tag "Regular expression" (const :regexp) (regexp))
1269 (cons :tag "Level number" (const :level) (integer))
1270 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1272 (defcustom org-refile-use-outline-path nil
1273 "Non-nil means, provide refile targets as paths.
1274 So a level 3 headline will be available as level1/level2/level3.
1275 When the value is `file', also include the file name (without directory)
1276 into the path. When `full-file-path', include the full file path."
1277 :group 'org-remember
1278 :type '(choice
1279 (const :tag "Not" nil)
1280 (const :tag "Yes" t)
1281 (const :tag "Start with file name" file)
1282 (const :tag "Start with full file path" full-file-path)))
1284 (defgroup org-todo nil
1285 "Options concerning TODO items in Org-mode."
1286 :tag "Org TODO"
1287 :group 'org)
1289 (defgroup org-progress nil
1290 "Options concerning Progress logging in Org-mode."
1291 :tag "Org Progress"
1292 :group 'org-time)
1294 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1295 "List of TODO entry keyword sequences and their interpretation.
1296 \\<org-mode-map>This is a list of sequences.
1298 Each sequence starts with a symbol, either `sequence' or `type',
1299 indicating if the keywords should be interpreted as a sequence of
1300 action steps, or as different types of TODO items. The first
1301 keywords are states requiring action - these states will select a headline
1302 for inclusion into the global TODO list Org-mode produces. If one of
1303 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1304 signify that no further action is necessary. If \"|\" is not found,
1305 the last keyword is treated as the only DONE state of the sequence.
1307 The command \\[org-todo] cycles an entry through these states, and one
1308 additional state where no keyword is present. For details about this
1309 cycling, see the manual.
1311 TODO keywords and interpretation can also be set on a per-file basis with
1312 the special #+SEQ_TODO and #+TYP_TODO lines.
1314 Each keyword can optionally specify a character for fast state selection
1315 \(in combination with the variable `org-use-fast-todo-selection')
1316 and specifiers for state change logging, using the same syntax
1317 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1318 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1319 indicates to record a time stamp each time this state is selected.
1321 Each keyword may also specify if a timestamp or a note should be
1322 recorded when entering or leaving the state, by adding additional
1323 characters in the parenthesis after the keyword. This looks like this:
1324 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1325 record only the time of the state change. With X and Y being either
1326 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1327 Y when leaving the state if and only if the *target* state does not
1328 define X. You may omit any of the fast-selection key or X or /Y,
1329 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1331 For backward compatibility, this variable may also be just a list
1332 of keywords - in this case the interptetation (sequence or type) will be
1333 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1334 :group 'org-todo
1335 :group 'org-keywords
1336 :type '(choice
1337 (repeat :tag "Old syntax, just keywords"
1338 (string :tag "Keyword"))
1339 (repeat :tag "New syntax"
1340 (cons
1341 (choice
1342 :tag "Interpretation"
1343 (const :tag "Sequence (cycling hits every state)" sequence)
1344 (const :tag "Type (cycling directly to DONE)" type))
1345 (repeat
1346 (string :tag "Keyword"))))))
1348 (defvar org-todo-keywords-1 nil
1349 "All TODO and DONE keywords active in a buffer.")
1350 (make-variable-buffer-local 'org-todo-keywords-1)
1351 (defvar org-todo-keywords-for-agenda nil)
1352 (defvar org-done-keywords-for-agenda nil)
1353 (defvar org-agenda-contributing-files nil)
1354 (defvar org-not-done-keywords nil)
1355 (make-variable-buffer-local 'org-not-done-keywords)
1356 (defvar org-done-keywords nil)
1357 (make-variable-buffer-local 'org-done-keywords)
1358 (defvar org-todo-heads nil)
1359 (make-variable-buffer-local 'org-todo-heads)
1360 (defvar org-todo-sets nil)
1361 (make-variable-buffer-local 'org-todo-sets)
1362 (defvar org-todo-log-states nil)
1363 (make-variable-buffer-local 'org-todo-log-states)
1364 (defvar org-todo-kwd-alist nil)
1365 (make-variable-buffer-local 'org-todo-kwd-alist)
1366 (defvar org-todo-key-alist nil)
1367 (make-variable-buffer-local 'org-todo-key-alist)
1368 (defvar org-todo-key-trigger nil)
1369 (make-variable-buffer-local 'org-todo-key-trigger)
1371 (defcustom org-todo-interpretation 'sequence
1372 "Controls how TODO keywords are interpreted.
1373 This variable is in principle obsolete and is only used for
1374 backward compatibility, if the interpretation of todo keywords is
1375 not given already in `org-todo-keywords'. See that variable for
1376 more information."
1377 :group 'org-todo
1378 :group 'org-keywords
1379 :type '(choice (const sequence)
1380 (const type)))
1382 (defcustom org-use-fast-todo-selection 'prefix
1383 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1384 This variable describes if and under what circumstances the cycling
1385 mechanism for TODO keywords will be replaced by a single-key, direct
1386 selection scheme.
1388 When nil, fast selection is never used.
1390 When the symbol `prefix', it will be used when `org-todo' is called with
1391 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1392 in an agenda buffer.
1394 When t, fast selection is used by default. In this case, the prefix
1395 argument forces cycling instead.
1397 In all cases, the special interface is only used if access keys have actually
1398 been assigned by the user, i.e. if keywords in the configuration are followed
1399 by a letter in parenthesis, like TODO(t)."
1400 :group 'org-todo
1401 :type '(choice
1402 (const :tag "Never" nil)
1403 (const :tag "By default" t)
1404 (const :tag "Only with C-u C-c C-t" prefix)))
1406 (defcustom org-provide-todo-statistics t
1407 "Non-nil means, update todo statistics after insert and toggle.
1408 When this is set, todo statistics is updated in the parent of the current
1409 entry each time a todo state is changed."
1410 :group 'org-todo
1411 :type 'boolean)
1413 (defcustom org-after-todo-state-change-hook nil
1414 "Hook which is run after the state of a TODO item was changed.
1415 The new state (a string with a TODO keyword, or nil) is available in the
1416 Lisp variable `state'."
1417 :group 'org-todo
1418 :type 'hook)
1420 (defcustom org-log-done nil
1421 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1422 When equal to the list (done), also prompt for a closing note.
1423 This can also be configured on a per-file basis by adding one of
1424 the following lines anywhere in the buffer:
1426 #+STARTUP: logdone
1427 #+STARTUP: lognotedone
1428 #+STARTUP: nologdone"
1429 :group 'org-todo
1430 :group 'org-progress
1431 :type '(choice
1432 (const :tag "No logging" nil)
1433 (const :tag "Record CLOSED timestamp" time)
1434 (const :tag "Record CLOSED timestamp with closing note." note)))
1436 ;; Normalize old uses of org-log-done.
1437 (cond
1438 ((eq org-log-done t) (setq org-log-done 'time))
1439 ((and (listp org-log-done) (memq 'done org-log-done))
1440 (setq org-log-done 'note)))
1442 (defcustom org-log-note-clock-out nil
1443 "Non-nil means, recored a note when clocking out of an item.
1444 This can also be configured on a per-file basis by adding one of
1445 the following lines anywhere in the buffer:
1447 #+STARTUP: lognoteclock-out
1448 #+STARTUP: nolognoteclock-out"
1449 :group 'org-todo
1450 :group 'org-progress
1451 :type 'boolean)
1453 (defcustom org-log-done-with-time t
1454 "Non-nil means, the CLOSED time stamp will contain date and time.
1455 When nil, only the date will be recorded."
1456 :group 'org-progress
1457 :type 'boolean)
1459 (defcustom org-log-note-headings
1460 '((done . "CLOSING NOTE %t")
1461 (state . "State %-12s %t")
1462 (note . "Note taken on %t")
1463 (clock-out . ""))
1464 "Headings for notes added to entries.
1465 The value is an alist, with the car being a symbol indicating the note
1466 context, and the cdr is the heading to be used. The heading may also be the
1467 empty string.
1468 %t in the heading will be replaced by a time stamp.
1469 %s will be replaced by the new TODO state, in double quotes.
1470 %u will be replaced by the user name.
1471 %U will be replaced by the full user name."
1472 :group 'org-todo
1473 :group 'org-progress
1474 :type '(list :greedy t
1475 (cons (const :tag "Heading when closing an item" done) string)
1476 (cons (const :tag
1477 "Heading when changing todo state (todo sequence only)"
1478 state) string)
1479 (cons (const :tag "Heading when just taking a note" note) string)
1480 (cons (const :tag "Heading when clocking out" clock-out) string)))
1482 (unless (assq 'note org-log-note-headings)
1483 (push '(note . "%t") org-log-note-headings))
1485 (defcustom org-log-states-order-reversed t
1486 "Non-nil means, the latest state change note will be directly after heading.
1487 When nil, the notes will be orderer according to time."
1488 :group 'org-todo
1489 :group 'org-progress
1490 :type 'boolean)
1492 (defcustom org-log-repeat 'time
1493 "Non-nil means, record moving through the DONE state when triggering repeat.
1494 An auto-repeating tasks is immediately switched back to TODO when marked
1495 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1496 the TODO keyword definition, or recording a closing note by setting
1497 `org-log-done', there will be no record of the task moving through DONE.
1498 This variable forces taking a note anyway. Possible values are:
1500 nil Don't force a record
1501 time Record a time stamp
1502 note Record a note
1504 This option can also be set with on a per-file-basis with
1506 #+STARTUP: logrepeat
1507 #+STARTUP: lognoterepeat
1508 #+STARTUP: nologrepeat
1510 You can have local logging settings for a subtree by setting the LOGGING
1511 property to one or more of these keywords."
1512 :group 'org-todo
1513 :group 'org-progress
1514 :type '(choice
1515 (const :tag "Don't force a record" nil)
1516 (const :tag "Force recording the DONE state" time)
1517 (const :tag "Force recording a note with the DONE state" note)))
1520 (defgroup org-priorities nil
1521 "Priorities in Org-mode."
1522 :tag "Org Priorities"
1523 :group 'org-todo)
1525 (defcustom org-highest-priority ?A
1526 "The highest priority of TODO items. A character like ?A, ?B etc.
1527 Must have a smaller ASCII number than `org-lowest-priority'."
1528 :group 'org-priorities
1529 :type 'character)
1531 (defcustom org-lowest-priority ?C
1532 "The lowest priority of TODO items. A character like ?A, ?B etc.
1533 Must have a larger ASCII number than `org-highest-priority'."
1534 :group 'org-priorities
1535 :type 'character)
1537 (defcustom org-default-priority ?B
1538 "The default priority of TODO items.
1539 This is the priority an item get if no explicit priority is given."
1540 :group 'org-priorities
1541 :type 'character)
1543 (defcustom org-priority-start-cycle-with-default t
1544 "Non-nil means, start with default priority when starting to cycle.
1545 When this is nil, the first step in the cycle will be (depending on the
1546 command used) one higher or lower that the default priority."
1547 :group 'org-priorities
1548 :type 'boolean)
1550 (defgroup org-time nil
1551 "Options concerning time stamps and deadlines in Org-mode."
1552 :tag "Org Time"
1553 :group 'org)
1555 (defcustom org-insert-labeled-timestamps-at-point nil
1556 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1557 When nil, these labeled time stamps are forces into the second line of an
1558 entry, just after the headline. When scheduling from the global TODO list,
1559 the time stamp will always be forced into the second line."
1560 :group 'org-time
1561 :type 'boolean)
1563 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1564 "Formats for `format-time-string' which are used for time stamps.
1565 It is not recommended to change this constant.")
1567 (defcustom org-time-stamp-rounding-minutes '(0 5)
1568 "Number of minutes to round time stamps to.
1569 These are two values, the first applies when first creating a time stamp.
1570 The second applies when changing it with the commands `S-up' and `S-down'.
1571 When changing the time stamp, this means that it will change in steps
1572 of N minutes, as given by the second value.
1574 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1575 numbers should be factors of 60, so for example 5, 10, 15.
1577 When this is larger than 1, you can still force an exact time-stamp by using
1578 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1579 and by using a prefix arg to `S-up/down' to specify the exact number
1580 of minutes to shift."
1581 :group 'org-time
1582 :get '(lambda (var) ; Make sure all entries have 5 elements
1583 (if (integerp (default-value var))
1584 (list (default-value var) 5)
1585 (default-value var)))
1586 :type '(list
1587 (integer :tag "when inserting times")
1588 (integer :tag "when modifying times")))
1590 ;; Normalize old customizations of this variable.
1591 (when (integerp org-time-stamp-rounding-minutes)
1592 (setq org-time-stamp-rounding-minutes
1593 (list org-time-stamp-rounding-minutes
1594 org-time-stamp-rounding-minutes)))
1596 (defcustom org-display-custom-times nil
1597 "Non-nil means, overlay custom formats over all time stamps.
1598 The formats are defined through the variable `org-time-stamp-custom-formats'.
1599 To turn this on on a per-file basis, insert anywhere in the file:
1600 #+STARTUP: customtime"
1601 :group 'org-time
1602 :set 'set-default
1603 :type 'sexp)
1604 (make-variable-buffer-local 'org-display-custom-times)
1606 (defcustom org-time-stamp-custom-formats
1607 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1608 "Custom formats for time stamps. See `format-time-string' for the syntax.
1609 These are overlayed over the default ISO format if the variable
1610 `org-display-custom-times' is set. Time like %H:%M should be at the
1611 end of the second format."
1612 :group 'org-time
1613 :type 'sexp)
1615 (defun org-time-stamp-format (&optional long inactive)
1616 "Get the right format for a time string."
1617 (let ((f (if long (cdr org-time-stamp-formats)
1618 (car org-time-stamp-formats))))
1619 (if inactive
1620 (concat "[" (substring f 1 -1) "]")
1621 f)))
1623 (defcustom org-time-clocksum-format "%d:%02d"
1624 "The format string used when creating CLOCKSUM lines, or when
1625 org-mode generates a time duration."
1626 :group 'org-time
1627 :type 'string)
1629 (defcustom org-deadline-warning-days 14
1630 "No. of days before expiration during which a deadline becomes active.
1631 This variable governs the display in sparse trees and in the agenda.
1632 When 0 or negative, it means use this number (the absolute value of it)
1633 even if a deadline has a different individual lead time specified."
1634 :group 'org-time
1635 :group 'org-agenda-daily/weekly
1636 :type 'number)
1638 (defcustom org-read-date-prefer-future t
1639 "Non-nil means, assume future for incomplete date input from user.
1640 This affects the following situations:
1641 1. The user gives a day, but no month.
1642 For example, if today is the 15th, and you enter \"3\", Org-mode will
1643 read this as the third of *next* month. However, if you enter \"17\",
1644 it will be considered as *this* month.
1645 2. The user gives a month but not a year.
1646 For example, if it is april and you enter \"feb 2\", this will be read
1647 as feb 2, *next* year. \"May 5\", however, will be this year.
1649 Currently this does not work for ISO week specifications.
1651 When this option is nil, the current month and year will always be used
1652 as defaults."
1653 :group 'org-time
1654 :type 'boolean)
1656 (defcustom org-read-date-display-live t
1657 "Non-nil means, display current interpretation of date prompt live.
1658 This display will be in an overlay, in the minibuffer."
1659 :group 'org-time
1660 :type 'boolean)
1662 (defcustom org-read-date-popup-calendar t
1663 "Non-nil means, pop up a calendar when prompting for a date.
1664 In the calendar, the date can be selected with mouse-1. However, the
1665 minibuffer will also be active, and you can simply enter the date as well.
1666 When nil, only the minibuffer will be available."
1667 :group 'org-time
1668 :type 'boolean)
1669 (if (fboundp 'defvaralias)
1670 (defvaralias 'org-popup-calendar-for-date-prompt
1671 'org-read-date-popup-calendar))
1673 (defcustom org-extend-today-until 0
1674 "The hour when your day really ends.
1675 This has influence for the following applications:
1676 - When switching the agenda to \"today\". It it is still earlier than
1677 the time given here, the day recognized as TODAY is actually yesterday.
1678 - When a date is read from the user and it is still before the time given
1679 here, the current date and time will be assumed to be yesterday, 23:59.
1681 FIXME:
1682 IMPORTANT: This is still a very experimental feature, it may disappear
1683 again or it may be extended to mean more things."
1684 :group 'org-time
1685 :type 'number)
1687 (defcustom org-edit-timestamp-down-means-later nil
1688 "Non-nil means, S-down will increase the time in a time stamp.
1689 When nil, S-up will increase."
1690 :group 'org-time
1691 :type 'boolean)
1693 (defcustom org-calendar-follow-timestamp-change t
1694 "Non-nil means, make the calendar window follow timestamp changes.
1695 When a timestamp is modified and the calendar window is visible, it will be
1696 moved to the new date."
1697 :group 'org-time
1698 :type 'boolean)
1700 (defgroup org-tags nil
1701 "Options concerning tags in Org-mode."
1702 :tag "Org Tags"
1703 :group 'org)
1705 (defcustom org-tag-alist nil
1706 "List of tags allowed in Org-mode files.
1707 When this list is nil, Org-mode will base TAG input on what is already in the
1708 buffer.
1709 The value of this variable is an alist, the car of each entry must be a
1710 keyword as a string, the cdr may be a character that is used to select
1711 that tag through the fast-tag-selection interface.
1712 See the manual for details."
1713 :group 'org-tags
1714 :type '(repeat
1715 (choice
1716 (cons (string :tag "Tag name")
1717 (character :tag "Access char"))
1718 (const :tag "Start radio group" (:startgroup))
1719 (const :tag "End radio group" (:endgroup)))))
1721 (defvar org-file-tags nil
1722 "List of tags that can be inherited by all entries in the file.
1723 The tags will be inherited if the variable `org-use-tag-inheritance'
1724 says they should be.
1725 This variable is populated from #+TAG lines.")
1727 (defcustom org-use-fast-tag-selection 'auto
1728 "Non-nil means, use fast tag selection scheme.
1729 This is a special interface to select and deselect tags with single keys.
1730 When nil, fast selection is never used.
1731 When the symbol `auto', fast selection is used if and only if selection
1732 characters for tags have been configured, either through the variable
1733 `org-tag-alist' or through a #+TAGS line in the buffer.
1734 When t, fast selection is always used and selection keys are assigned
1735 automatically if necessary."
1736 :group 'org-tags
1737 :type '(choice
1738 (const :tag "Always" t)
1739 (const :tag "Never" nil)
1740 (const :tag "When selection characters are configured" 'auto)))
1742 (defcustom org-fast-tag-selection-single-key nil
1743 "Non-nil means, fast tag selection exits after first change.
1744 When nil, you have to press RET to exit it.
1745 During fast tag selection, you can toggle this flag with `C-c'.
1746 This variable can also have the value `expert'. In this case, the window
1747 displaying the tags menu is not even shown, until you press C-c again."
1748 :group 'org-tags
1749 :type '(choice
1750 (const :tag "No" nil)
1751 (const :tag "Yes" t)
1752 (const :tag "Expert" expert)))
1754 (defvar org-fast-tag-selection-include-todo nil
1755 "Non-nil means, fast tags selection interface will also offer TODO states.
1756 This is an undocumented feature, you should not rely on it.")
1758 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1759 "The column to which tags should be indented in a headline.
1760 If this number is positive, it specifies the column. If it is negative,
1761 it means that the tags should be flushright to that column. For example,
1762 -80 works well for a normal 80 character screen."
1763 :group 'org-tags
1764 :type 'integer)
1766 (defcustom org-auto-align-tags t
1767 "Non-nil means, realign tags after pro/demotion of TODO state change.
1768 These operations change the length of a headline and therefore shift
1769 the tags around. With this options turned on, after each such operation
1770 the tags are again aligned to `org-tags-column'."
1771 :group 'org-tags
1772 :type 'boolean)
1774 (defcustom org-use-tag-inheritance t
1775 "Non-nil means, tags in levels apply also for sublevels.
1776 When nil, only the tags directly given in a specific line apply there.
1777 If this option is t, a match early-on in a tree can lead to a large
1778 number of matches in the subtree. If you only want to see the first
1779 match in a tree during a search, check out the variable
1780 `org-tags-match-list-sublevels'.
1782 This may also be a list of tags that should be inherited, or a regexp that
1783 matches tags that should be inherited."
1784 :group 'org-tags
1785 :type '(choice
1786 (const :tag "Not" nil)
1787 (const :tag "Always" t)
1788 (repeat :tag "Specific tags" (string :tag "Tag"))
1789 (regexp :tag "Tags matched by regexp")))
1791 (defun org-tag-inherit-p (tag)
1792 "Check if TAG is one that should be inherited."
1793 (cond
1794 ((eq org-use-tag-inheritance t) t)
1795 ((not org-use-tag-inheritance) nil)
1796 ((stringp org-use-tag-inheritance)
1797 (string-match org-use-tag-inheritance tag))
1798 ((listp org-use-tag-inheritance)
1799 (member tag org-use-tag-inheritance))
1800 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1802 (defcustom org-tags-match-list-sublevels t
1803 "Non-nil means list also sublevels of headlines matching tag search.
1804 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1805 the sublevels of a headline matching a tag search often also match
1806 the same search. Listing all of them can create very long lists.
1807 Setting this variable to nil causes subtrees of a match to be skipped.
1808 This option is off by default, because inheritance in on. If you turn
1809 inheritance off, you very likely want to turn this option on.
1811 As a special case, if the tag search is restricted to TODO items, the
1812 value of this variable is ignored and sublevels are always checked, to
1813 make sure all corresponding TODO items find their way into the list."
1814 :group 'org-tags
1815 :type 'boolean)
1817 (defvar org-tags-history nil
1818 "History of minibuffer reads for tags.")
1819 (defvar org-last-tags-completion-table nil
1820 "The last used completion table for tags.")
1821 (defvar org-after-tags-change-hook nil
1822 "Hook that is run after the tags in a line have changed.")
1824 (defgroup org-properties nil
1825 "Options concerning properties in Org-mode."
1826 :tag "Org Properties"
1827 :group 'org)
1829 (defcustom org-property-format "%-10s %s"
1830 "How property key/value pairs should be formatted by `indent-line'.
1831 When `indent-line' hits a property definition, it will format the line
1832 according to this format, mainly to make sure that the values are
1833 lined-up with respect to each other."
1834 :group 'org-properties
1835 :type 'string)
1837 (defcustom org-use-property-inheritance nil
1838 "Non-nil means, properties apply also for sublevels.
1840 This setting is chiefly used during property searches. Turning it on can
1841 cause significant overhead when doing a search, which is why it is not
1842 on by default.
1844 When nil, only the properties directly given in the current entry count.
1845 When t, every property is inherited. The value may also be a list of
1846 properties that should have inheritance, or a regular expression matching
1847 properties that should be inherited.
1849 However, note that some special properties use inheritance under special
1850 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1851 and the properties ending in \"_ALL\" when they are used as descriptor
1852 for valid values of a property.
1854 Note for programmers:
1855 When querying an entry with `org-entry-get', you can control if inheritance
1856 should be used. By default, `org-entry-get' looks only at the local
1857 properties. You can request inheritance by setting the inherit argument
1858 to t (to force inheritance) or to `selective' (to respect the setting
1859 in this variable)."
1860 :group 'org-properties
1861 :type '(choice
1862 (const :tag "Not" nil)
1863 (const :tag "Always" t)
1864 (repeat :tag "Specific properties" (string :tag "Property"))
1865 (regexp :tag "Properties matched by regexp")))
1867 (defun org-property-inherit-p (property)
1868 "Check if PROPERTY is one that should be inherited."
1869 (cond
1870 ((eq org-use-property-inheritance t) t)
1871 ((not org-use-property-inheritance) nil)
1872 ((stringp org-use-property-inheritance)
1873 (string-match org-use-property-inheritance property))
1874 ((listp org-use-property-inheritance)
1875 (member property org-use-property-inheritance))
1876 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1878 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1879 "The default column format, if no other format has been defined.
1880 This variable can be set on the per-file basis by inserting a line
1882 #+COLUMNS: %25ITEM ....."
1883 :group 'org-properties
1884 :type 'string)
1886 (defcustom org-columns-ellipses ".."
1887 "The ellipses to be used when a field in column view is truncated.
1888 When this is the empty string, as many characters as possible are shown,
1889 but then there will be no visual indication that the field has been truncated.
1890 When this is a string of length N, the last N characters of a truncated
1891 field are replaced by this string. If the column is narrower than the
1892 ellipses string, only part of the ellipses string will be shown."
1893 :group 'org-properties
1894 :type 'string)
1897 (defcustom org-effort-property "Effort"
1898 "The property that is being used to keep track of effort estimates.
1899 Effort estimates given in this property need to have the format H:MM."
1900 :group 'org-properties
1901 :group 'org-progress
1902 :type '(string :tag "Property"))
1904 (defconst org-global-properties-fixed
1905 '(("VISIBILITY_ALL" . "folded children content all"))
1906 "List of property/value pairs that can be inherited by any entry.
1907 These are fixed values, for the preset properties.")
1910 (defcustom org-global-properties nil
1911 "List of property/value pairs that can be inherited by any entry.
1912 You can set buffer-local values for this by adding lines like
1914 #+PROPERTY: NAME VALUE"
1915 :group 'org-properties
1916 :type '(repeat
1917 (cons (string :tag "Property")
1918 (string :tag "Value"))))
1920 (defvar org-file-properties nil
1921 "List of property/value pairs that can be inherited by any entry.
1922 Valid for the current buffer.
1923 This variable is populated from #+PROPERTY lines.")
1924 (make-variable-buffer-local 'org-file-properties)
1926 (defgroup org-agenda nil
1927 "Options concerning agenda views in Org-mode."
1928 :tag "Org Agenda"
1929 :group 'org)
1931 (defvar org-category nil
1932 "Variable used by org files to set a category for agenda display.
1933 Such files should use a file variable to set it, for example
1935 # -*- mode: org; org-category: \"ELisp\"
1937 or contain a special line
1939 #+CATEGORY: ELisp
1941 If the file does not specify a category, then file's base name
1942 is used instead.")
1943 (make-variable-buffer-local 'org-category)
1945 (defcustom org-agenda-files nil
1946 "The files to be used for agenda display.
1947 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1948 \\[org-remove-file]. You can also use customize to edit the list.
1950 If an entry is a directory, all files in that directory that are matched by
1951 `org-agenda-file-regexp' will be part of the file list.
1953 If the value of the variable is not a list but a single file name, then
1954 the list of agenda files is actually stored and maintained in that file, one
1955 agenda file per line."
1956 :group 'org-agenda
1957 :type '(choice
1958 (repeat :tag "List of files and directories" file)
1959 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1961 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1962 "Regular expression to match files for `org-agenda-files'.
1963 If any element in the list in that variable contains a directory instead
1964 of a normal file, all files in that directory that are matched by this
1965 regular expression will be included."
1966 :group 'org-agenda
1967 :type 'regexp)
1969 (defcustom org-agenda-text-search-extra-files nil
1970 "List of extra files to be searched by text search commands.
1971 These files will be search in addition to the agenda files by the
1972 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1973 Note that these files will only be searched for text search commands,
1974 not for the other agenda views like todo lists, tag searches or the weekly
1975 agenda. This variable is intended to list notes and possibly archive files
1976 that should also be searched by these two commands.
1977 In fact, if the first element in the list is the symbol `agenda-archives',
1978 than all archive files of all agenda files will be added to the search
1979 scope."
1980 :group 'org-agenda
1981 :type '(set :greedy t
1982 (const :tag "Agenda Archives" agenda-archives)
1983 (repeat :inline t (file))))
1985 (if (fboundp 'defvaralias)
1986 (defvaralias 'org-agenda-multi-occur-extra-files
1987 'org-agenda-text-search-extra-files))
1989 (defcustom org-agenda-skip-unavailable-files nil
1990 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
1991 A nil value means to remove them, after a query, from the list."
1992 :group 'org-agenda
1993 :type 'boolean)
1995 (defcustom org-calendar-to-agenda-key [?c]
1996 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1997 The command `org-calendar-goto-agenda' will be bound to this key. The
1998 default is the character `c' because then `c' can be used to switch back and
1999 forth between agenda and calendar."
2000 :group 'org-agenda
2001 :type 'sexp)
2003 (defcustom org-calendar-agenda-action-key [?k]
2004 "The key to be installed in `calendar-mode-map' for agenda-action.
2005 The command `org-agenda-action' will be bound to this key. The
2006 default is the character `k' because we use the same key in the agenda."
2007 :group 'org-agenda
2008 :type 'sexp)
2010 (eval-after-load "calendar"
2011 '(progn
2012 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2013 'org-calendar-goto-agenda)
2014 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2015 'org-agenda-action)))
2017 (defgroup org-latex nil
2018 "Options for embedding LaTeX code into Org-mode."
2019 :tag "Org LaTeX"
2020 :group 'org)
2022 (defcustom org-format-latex-options
2023 '(:foreground default :background default :scale 1.0
2024 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2025 :matchers ("begin" "$" "$$" "\\(" "\\["))
2026 "Options for creating images from LaTeX fragments.
2027 This is a property list with the following properties:
2028 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2029 `default' means use the foreground of the default face.
2030 :background the background color, or \"Transparent\".
2031 `default' means use the background of the default face.
2032 :scale a scaling factor for the size of the images.
2033 :html-foreground, :html-background, :html-scale
2034 the same numbers for HTML export.
2035 :matchers a list indicating which matchers should be used to
2036 find LaTeX fragments. Valid members of this list are:
2037 \"begin\" find environments
2038 \"$\" find math expressions surrounded by $...$
2039 \"$$\" find math expressions surrounded by $$....$$
2040 \"\\(\" find math expressions surrounded by \\(...\\)
2041 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2042 :group 'org-latex
2043 :type 'plist)
2045 (defcustom org-format-latex-header "\\documentclass{article}
2046 \\usepackage{fullpage} % do not remove
2047 \\usepackage{amssymb}
2048 \\usepackage[usenames]{color}
2049 \\usepackage{amsmath}
2050 \\usepackage{latexsym}
2051 \\usepackage[mathscr]{eucal}
2052 \\pagestyle{empty} % do not remove"
2053 "The document header used for processing LaTeX fragments."
2054 :group 'org-latex
2055 :type 'string)
2058 (defgroup org-font-lock nil
2059 "Font-lock settings for highlighting in Org-mode."
2060 :tag "Org Font Lock"
2061 :group 'org)
2063 (defcustom org-level-color-stars-only nil
2064 "Non-nil means fontify only the stars in each headline.
2065 When nil, the entire headline is fontified.
2066 Changing it requires restart of `font-lock-mode' to become effective
2067 also in regions already fontified."
2068 :group 'org-font-lock
2069 :type 'boolean)
2071 (defcustom org-hide-leading-stars nil
2072 "Non-nil means, hide the first N-1 stars in a headline.
2073 This works by using the face `org-hide' for these stars. This
2074 face is white for a light background, and black for a dark
2075 background. You may have to customize the face `org-hide' to
2076 make this work.
2077 Changing it requires restart of `font-lock-mode' to become effective
2078 also in regions already fontified.
2079 You may also set this on a per-file basis by adding one of the following
2080 lines to the buffer:
2082 #+STARTUP: hidestars
2083 #+STARTUP: showstars"
2084 :group 'org-font-lock
2085 :type 'boolean)
2087 (defcustom org-fontify-done-headline nil
2088 "Non-nil means, change the face of a headline if it is marked DONE.
2089 Normally, only the TODO/DONE keyword indicates the state of a headline.
2090 When this is non-nil, the headline after the keyword is set to the
2091 `org-headline-done' as an additional indication."
2092 :group 'org-font-lock
2093 :type 'boolean)
2095 (defcustom org-fontify-emphasized-text t
2096 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2097 Changing this variable requires a restart of Emacs to take effect."
2098 :group 'org-font-lock
2099 :type 'boolean)
2101 (defcustom org-highlight-latex-fragments-and-specials nil
2102 "Non-nil means, fontify what is treated specially by the exporters."
2103 :group 'org-font-lock
2104 :type 'boolean)
2106 (defcustom org-hide-emphasis-markers nil
2107 "Non-nil mean font-lock should hide the emphasis marker characters."
2108 :group 'org-font-lock
2109 :type 'boolean)
2111 (defvar org-emph-re nil
2112 "Regular expression for matching emphasis.")
2113 (defvar org-verbatim-re nil
2114 "Regular expression for matching verbatim text.")
2115 (defvar org-emphasis-regexp-components) ; defined just below
2116 (defvar org-emphasis-alist) ; defined just below
2117 (defun org-set-emph-re (var val)
2118 "Set variable and compute the emphasis regular expression."
2119 (set var val)
2120 (when (and (boundp 'org-emphasis-alist)
2121 (boundp 'org-emphasis-regexp-components)
2122 org-emphasis-alist org-emphasis-regexp-components)
2123 (let* ((e org-emphasis-regexp-components)
2124 (pre (car e))
2125 (post (nth 1 e))
2126 (border (nth 2 e))
2127 (body (nth 3 e))
2128 (nl (nth 4 e))
2129 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2130 (body1 (concat body "*?"))
2131 (markers (mapconcat 'car org-emphasis-alist ""))
2132 (vmarkers (mapconcat
2133 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2134 org-emphasis-alist "")))
2135 ;; make sure special characters appear at the right position in the class
2136 (if (string-match "\\^" markers)
2137 (setq markers (concat (replace-match "" t t markers) "^")))
2138 (if (string-match "-" markers)
2139 (setq markers (concat (replace-match "" t t markers) "-")))
2140 (if (string-match "\\^" vmarkers)
2141 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2142 (if (string-match "-" vmarkers)
2143 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2144 (if (> nl 0)
2145 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2146 (int-to-string nl) "\\}")))
2147 ;; Make the regexp
2148 (setq org-emph-re
2149 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2150 "\\("
2151 "\\([" markers "]\\)"
2152 "\\("
2153 "[^" border "]\\|"
2154 "[^" border (if (and nil stacked) markers) "]"
2155 body1
2156 "[^" border (if (and nil stacked) markers) "]"
2157 "\\)"
2158 "\\3\\)"
2159 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2160 (setq org-verbatim-re
2161 (concat "\\([" pre "]\\|^\\)"
2162 "\\("
2163 "\\([" vmarkers "]\\)"
2164 "\\("
2165 "[^" border "]\\|"
2166 "[^" border "]"
2167 body1
2168 "[^" border "]"
2169 "\\)"
2170 "\\3\\)"
2171 "\\([" post "]\\|$\\)")))))
2173 (defcustom org-emphasis-regexp-components
2174 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2175 "Components used to build the regular expression for emphasis.
2176 This is a list with 6 entries. Terminology: In an emphasis string
2177 like \" *strong word* \", we call the initial space PREMATCH, the final
2178 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2179 and \"trong wor\" is the body. The different components in this variable
2180 specify what is allowed/forbidden in each part:
2182 pre Chars allowed as prematch. Beginning of line will be allowed too.
2183 post Chars allowed as postmatch. End of line will be allowed too.
2184 border The chars *forbidden* as border characters.
2185 body-regexp A regexp like \".\" to match a body character. Don't use
2186 non-shy groups here, and don't allow newline here.
2187 newline The maximum number of newlines allowed in an emphasis exp.
2189 Use customize to modify this, or restart Emacs after changing it."
2190 :group 'org-font-lock
2191 :set 'org-set-emph-re
2192 :type '(list
2193 (sexp :tag "Allowed chars in pre ")
2194 (sexp :tag "Allowed chars in post ")
2195 (sexp :tag "Forbidden chars in border ")
2196 (sexp :tag "Regexp for body ")
2197 (integer :tag "number of newlines allowed")
2198 (option (boolean :tag "Please ignore this button"))))
2200 (defcustom org-emphasis-alist
2201 `(("*" bold "<b>" "</b>")
2202 ("/" italic "<i>" "</i>")
2203 ("_" underline "<u>" "</u>")
2204 ("=" org-code "<code>" "</code>" verbatim)
2205 ("~" org-verbatim "" "" verbatim)
2206 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2207 "<del>" "</del>")
2209 "Special syntax for emphasized text.
2210 Text starting and ending with a special character will be emphasized, for
2211 example *bold*, _underlined_ and /italic/. This variable sets the marker
2212 characters, the face to be used by font-lock for highlighting in Org-mode
2213 Emacs buffers, and the HTML tags to be used for this.
2214 Use customize to modify this, or restart Emacs after changing it."
2215 :group 'org-font-lock
2216 :set 'org-set-emph-re
2217 :type '(repeat
2218 (list
2219 (string :tag "Marker character")
2220 (choice
2221 (face :tag "Font-lock-face")
2222 (plist :tag "Face property list"))
2223 (string :tag "HTML start tag")
2224 (string :tag "HTML end tag")
2225 (option (const verbatim)))))
2227 ;;; Miscellaneous options
2229 (defgroup org-completion nil
2230 "Completion in Org-mode."
2231 :tag "Org Completion"
2232 :group 'org)
2234 (defcustom org-completion-fallback-command 'hippie-expand
2235 "The expansion command called by \\[org-complete] in normal context.
2236 Normal means, no org-mode-specific context."
2237 :group 'org-completion
2238 :type 'function)
2240 ;;; Functions and variables from ther packages
2241 ;; Declared here to avoid compiler warnings
2243 ;; XEmacs only
2244 (defvar outline-mode-menu-heading)
2245 (defvar outline-mode-menu-show)
2246 (defvar outline-mode-menu-hide)
2247 (defvar zmacs-regions) ; XEmacs regions
2249 ;; Emacs only
2250 (defvar mark-active)
2252 ;; Various packages
2253 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2254 (declare-function calendar-forward-day "cal-move" (arg))
2255 (declare-function calendar-goto-date "cal-move" (date))
2256 (declare-function calendar-goto-today "cal-move" ())
2257 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2258 (defvar calc-embedded-close-formula)
2259 (defvar calc-embedded-open-formula)
2260 (declare-function cdlatex-tab "ext:cdlatex" ())
2261 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2262 (defvar font-lock-unfontify-region-function)
2263 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2264 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2265 (defvar iswitchb-temp-buflist)
2266 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2267 (declare-function org-agenda-skip "org-agenda" ())
2268 (declare-function org-format-agenda-item "org-agenda"
2269 (extra txt &optional category tags dotime noprefix remove-re))
2270 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2271 (declare-function org-agenda-change-all-lines "org-agenda"
2272 (newhead hdmarker &optional fixface))
2273 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2274 (declare-function org-agenda-maybe-redo "org-agenda" ())
2275 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2276 (beg end))
2277 (declare-function parse-time-string "parse-time" (string))
2278 (declare-function remember "remember" (&optional initial))
2279 (declare-function remember-buffer-desc "remember" ())
2280 (declare-function remember-finalize "remember" ())
2281 (defvar remember-save-after-remembering)
2282 (defvar remember-data-file)
2283 (defvar remember-register)
2284 (defvar remember-buffer)
2285 (defvar remember-handler-functions)
2286 (defvar remember-annotation-functions)
2287 (defvar texmathp-why)
2288 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2289 (declare-function table--at-cell-p "table" (position &optional object at-column))
2291 (defvar w3m-current-url)
2292 (defvar w3m-current-title)
2294 (defvar org-latex-regexps)
2296 ;;; Autoload and prepare some org modules
2298 ;; Some table stuff that needs to be defined here, because it is used
2299 ;; by the functions setting up org-mode or checking for table context.
2301 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2302 "Detects an org-type or table-type table.")
2303 (defconst org-table-line-regexp "^[ \t]*|"
2304 "Detects an org-type table line.")
2305 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2306 "Detects an org-type table line.")
2307 (defconst org-table-hline-regexp "^[ \t]*|-"
2308 "Detects an org-type table hline.")
2309 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2310 "Detects a table-type table hline.")
2311 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2312 "Searching from within a table (any type) this finds the first line
2313 outside the table.")
2315 ;; Autoload the functions in org-table.el that are needed by functions here.
2317 (eval-and-compile
2318 (org-autoload "org-table"
2319 '(org-table-align org-table-begin org-table-blank-field
2320 org-table-convert org-table-convert-region org-table-copy-down
2321 org-table-copy-region org-table-create
2322 org-table-create-or-convert-from-region
2323 org-table-create-with-table.el org-table-current-dline
2324 org-table-cut-region org-table-delete-column org-table-edit-field
2325 org-table-edit-formulas org-table-end org-table-eval-formula
2326 org-table-export org-table-field-info
2327 org-table-get-stored-formulas org-table-goto-column
2328 org-table-hline-and-move org-table-import org-table-insert-column
2329 org-table-insert-hline org-table-insert-row org-table-iterate
2330 org-table-justify-field-maybe org-table-kill-row
2331 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2332 org-table-move-column org-table-move-column-left
2333 org-table-move-column-right org-table-move-row
2334 org-table-move-row-down org-table-move-row-up
2335 org-table-next-field org-table-next-row org-table-paste-rectangle
2336 org-table-previous-field org-table-recalculate
2337 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2338 org-table-toggle-coordinate-overlays
2339 org-table-toggle-formula-debugger org-table-wrap-region
2340 orgtbl-mode turn-on-orgtbl)))
2342 (defun org-at-table-p (&optional table-type)
2343 "Return t if the cursor is inside an org-type table.
2344 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2345 (if org-enable-table-editor
2346 (save-excursion
2347 (beginning-of-line 1)
2348 (looking-at (if table-type org-table-any-line-regexp
2349 org-table-line-regexp)))
2350 nil))
2351 (defsubst org-table-p () (org-at-table-p))
2353 (defun org-at-table.el-p ()
2354 "Return t if and only if we are at a table.el table."
2355 (and (org-at-table-p 'any)
2356 (save-excursion
2357 (goto-char (org-table-begin 'any))
2358 (looking-at org-table1-hline-regexp))))
2359 (defun org-table-recognize-table.el ()
2360 "If there is a table.el table nearby, recognize it and move into it."
2361 (if org-table-tab-recognizes-table.el
2362 (if (org-at-table.el-p)
2363 (progn
2364 (beginning-of-line 1)
2365 (if (looking-at org-table-dataline-regexp)
2367 (if (looking-at org-table1-hline-regexp)
2368 (progn
2369 (beginning-of-line 2)
2370 (if (looking-at org-table-any-border-regexp)
2371 (beginning-of-line -1)))))
2372 (if (re-search-forward "|" (org-table-end t) t)
2373 (progn
2374 (require 'table)
2375 (if (table--at-cell-p (point))
2377 (message "recognizing table.el table...")
2378 (table-recognize-table)
2379 (message "recognizing table.el table...done")))
2380 (error "This should not happen..."))
2382 nil)
2383 nil))
2385 (defun org-at-table-hline-p ()
2386 "Return t if the cursor is inside a hline in a table."
2387 (if org-enable-table-editor
2388 (save-excursion
2389 (beginning-of-line 1)
2390 (looking-at org-table-hline-regexp))
2391 nil))
2393 (defvar org-table-clean-did-remove-column nil)
2395 (defun org-table-map-tables (function)
2396 "Apply FUNCTION to the start of all tables in the buffer."
2397 (save-excursion
2398 (save-restriction
2399 (widen)
2400 (goto-char (point-min))
2401 (while (re-search-forward org-table-any-line-regexp nil t)
2402 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2403 (beginning-of-line 1)
2404 (if (looking-at org-table-line-regexp)
2405 (save-excursion (funcall function)))
2406 (re-search-forward org-table-any-border-regexp nil 1))))
2407 (message "Mapping tables: done"))
2409 ;; Declare and autoload functions from org-exp.el
2411 (declare-function org-default-export-plist "org-exp")
2412 (declare-function org-infile-export-plist "org-exp")
2413 (declare-function org-get-current-options "org-exp")
2414 (eval-and-compile
2415 (org-autoload "org-exp"
2416 '(org-export org-export-as-ascii org-export-visible
2417 org-insert-export-options-template org-export-as-html-and-open
2418 org-export-as-html-batch org-export-as-html-to-buffer
2419 org-replace-region-by-html org-export-region-as-html
2420 org-export-as-html org-export-icalendar-this-file
2421 org-export-icalendar-all-agenda-files
2422 org-table-clean-before-export
2423 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2425 ;; Declare and autoload functions from org-exp.el
2427 (eval-and-compile
2428 (org-autoload "org-exp"
2429 '(org-agenda org-agenda-list org-search-view
2430 org-todo-list org-tags-view org-agenda-list-stuck-projects
2431 org-diary org-agenda-to-appt)))
2433 ;; Autoload org-remember
2435 (eval-and-compile
2436 (org-autoload "org-remember"
2437 '(org-remember-insinuate org-remember-annotation
2438 org-remember-apply-template org-remember org-remember-handler)))
2440 ;; Autoload org-clock.el
2443 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2444 (beg end))
2445 (declare-function org-update-mode-line "org-clock" ())
2446 (defvar org-clock-start-time)
2447 (defvar org-clock-marker (make-marker)
2448 "Marker recording the last clock-in.")
2450 (eval-and-compile
2451 (org-autoload
2452 "org-clock"
2453 '(org-clock-in org-clock-out org-clock-cancel
2454 org-clock-goto org-clock-sum org-clock-display
2455 org-remove-clock-overlays org-clock-report
2456 org-clocktable-shift org-dblock-write:clocktable
2457 org-get-clocktable)))
2459 (defun org-clock-update-time-maybe ()
2460 "If this is a CLOCK line, update it and return t.
2461 Otherwise, return nil."
2462 (interactive)
2463 (save-excursion
2464 (beginning-of-line 1)
2465 (skip-chars-forward " \t")
2466 (when (looking-at org-clock-string)
2467 (let ((re (concat "[ \t]*" org-clock-string
2468 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2469 "\\([ \t]*=>.*\\)?\\)?"))
2470 ts te h m s)
2471 (cond
2472 ((not (looking-at re))
2473 nil)
2474 ((not (match-end 2))
2475 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2476 (> org-clock-marker (point))
2477 (<= org-clock-marker (point-at-eol)))
2478 ;; The clock is running here
2479 (setq org-clock-start-time
2480 (apply 'encode-time
2481 (org-parse-time-string (match-string 1))))
2482 (org-update-mode-line)))
2484 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2485 (end-of-line 1)
2486 (setq ts (match-string 1)
2487 te (match-string 3))
2488 (setq s (- (time-to-seconds
2489 (apply 'encode-time (org-parse-time-string te)))
2490 (time-to-seconds
2491 (apply 'encode-time (org-parse-time-string ts))))
2492 h (floor (/ s 3600))
2493 s (- s (* 3600 h))
2494 m (floor (/ s 60))
2495 s (- s (* 60 s)))
2496 (insert " => " (format "%2d:%02d" h m))
2497 t))))))
2499 (defun org-check-running-clock ()
2500 "Check if the current buffer contains the running clock.
2501 If yes, offer to stop it and to save the buffer with the changes."
2502 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2503 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2504 (buffer-name))))
2505 (org-clock-out)
2506 (when (y-or-n-p "Save changed buffer?")
2507 (save-buffer))))
2509 (defun org-clocktable-try-shift (dir n)
2510 "Check if this line starts a clock table, if yes, shift the time block."
2511 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2512 (org-clocktable-shift dir n)))
2514 ;; Autoload archiving code
2515 ;; The stuff that is needed for cycling and tags has to be defined here.
2517 (defgroup org-archive nil
2518 "Options concerning archiving in Org-mode."
2519 :tag "Org Archive"
2520 :group 'org-structure)
2522 (defcustom org-archive-location "%s_archive::"
2523 "The location where subtrees should be archived.
2525 Otherwise, the value of this variable is a string, consisting of two
2526 parts, separated by a double-colon.
2528 The first part is a file name - when omitted, archiving happens in the same
2529 file. %s will be replaced by the current file name (without directory part).
2530 Archiving to a different file is useful to keep archived entries from
2531 contributing to the Org-mode Agenda.
2533 The part after the double colon is a headline. The archived entries will be
2534 filed under that headline. When omitted, the subtrees are simply filed away
2535 at the end of the file, as top-level entries.
2537 Here are a few examples:
2538 \"%s_archive::\"
2539 If the current file is Projects.org, archive in file
2540 Projects.org_archive, as top-level trees. This is the default.
2542 \"::* Archived Tasks\"
2543 Archive in the current file, under the top-level headline
2544 \"* Archived Tasks\".
2546 \"~/org/archive.org::\"
2547 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2549 \"basement::** Finished Tasks\"
2550 Archive in file ./basement (relative path), as level 3 trees
2551 below the level 2 heading \"** Finished Tasks\".
2553 You may set this option on a per-file basis by adding to the buffer a
2554 line like
2556 #+ARCHIVE: basement::** Finished Tasks
2558 You may also define it locally for a subtree by setting an ARCHIVE property
2559 in the entry. If such a property is found in an entry, or anywhere up
2560 the hierarchy, it will be used."
2561 :group 'org-archive
2562 :type 'string)
2564 (defcustom org-archive-tag "ARCHIVE"
2565 "The tag that marks a subtree as archived.
2566 An archived subtree does not open during visibility cycling, and does
2567 not contribute to the agenda listings.
2568 After changing this, font-lock must be restarted in the relevant buffers to
2569 get the proper fontification."
2570 :group 'org-archive
2571 :group 'org-keywords
2572 :type 'string)
2574 (defcustom org-agenda-skip-archived-trees t
2575 "Non-nil means, the agenda will skip any items located in archived trees.
2576 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2577 variable is no longer recommended, you should leave it at the value t.
2578 Instead, use the key `v' to cycle the archives-mode in the agenda."
2579 :group 'org-archive
2580 :group 'org-agenda-skip
2581 :type 'boolean)
2583 (defcustom org-cycle-open-archived-trees nil
2584 "Non-nil means, `org-cycle' will open archived trees.
2585 An archived tree is a tree marked with the tag ARCHIVE.
2586 When nil, archived trees will stay folded. You can still open them with
2587 normal outline commands like `show-all', but not with the cycling commands."
2588 :group 'org-archive
2589 :group 'org-cycle
2590 :type 'boolean)
2592 (defcustom org-sparse-tree-open-archived-trees nil
2593 "Non-nil means sparse tree construction shows matches in archived trees.
2594 When nil, matches in these trees are highlighted, but the trees are kept in
2595 collapsed state."
2596 :group 'org-archive
2597 :group 'org-sparse-trees
2598 :type 'boolean)
2600 (defun org-cycle-hide-archived-subtrees (state)
2601 "Re-hide all archived subtrees after a visibility state change."
2602 (when (and (not org-cycle-open-archived-trees)
2603 (not (memq state '(overview folded))))
2604 (save-excursion
2605 (let* ((globalp (memq state '(contents all)))
2606 (beg (if globalp (point-min) (point)))
2607 (end (if globalp (point-max) (org-end-of-subtree t))))
2608 (org-hide-archived-subtrees beg end)
2609 (goto-char beg)
2610 (if (looking-at (concat ".*:" org-archive-tag ":"))
2611 (message "%s" (substitute-command-keys
2612 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2614 (defun org-force-cycle-archived ()
2615 "Cycle subtree even if it is archived."
2616 (interactive)
2617 (setq this-command 'org-cycle)
2618 (let ((org-cycle-open-archived-trees t))
2619 (call-interactively 'org-cycle)))
2621 (defun org-hide-archived-subtrees (beg end)
2622 "Re-hide all archived subtrees after a visibility state change."
2623 (save-excursion
2624 (let* ((re (concat ":" org-archive-tag ":")))
2625 (goto-char beg)
2626 (while (re-search-forward re end t)
2627 (and (org-on-heading-p) (hide-subtree))
2628 (org-end-of-subtree t)))))
2630 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2632 (eval-and-compile
2633 (org-autoload "org-archive"
2634 '(org-add-archive-files org-archive-subtree
2635 org-archive-to-archive-sibling org-toggle-archive-tag)))
2637 ;; Autoload Column View Code
2639 (declare-function org-columns-number-to-string "org-colview")
2640 (declare-function org-columns-get-format-and-top-level "org-colview")
2641 (declare-function org-columns-compute "org-colview")
2643 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2644 '(org-columns-number-to-string org-columns-get-format-and-top-level
2645 org-columns-compute org-agenda-columns org-columns-remove-overlays
2646 org-columns org-insert-columns-dblock))
2648 ;; Autoload ID code
2650 (org-autoload "org-id"
2651 '(org-id-get-create org-id-new org-id-copy org-id-get
2652 org-id-get-with-outline-path-completion
2653 org-id-get-with-outline-drilling
2654 org-id-goto org-id-find))
2656 ;;; Variables for pre-computed regular expressions, all buffer local
2658 (defvar org-drawer-regexp nil
2659 "Matches first line of a hidden block.")
2660 (make-variable-buffer-local 'org-drawer-regexp)
2661 (defvar org-todo-regexp nil
2662 "Matches any of the TODO state keywords.")
2663 (make-variable-buffer-local 'org-todo-regexp)
2664 (defvar org-not-done-regexp nil
2665 "Matches any of the TODO state keywords except the last one.")
2666 (make-variable-buffer-local 'org-not-done-regexp)
2667 (defvar org-todo-line-regexp nil
2668 "Matches a headline and puts TODO state into group 2 if present.")
2669 (make-variable-buffer-local 'org-todo-line-regexp)
2670 (defvar org-complex-heading-regexp nil
2671 "Matches a headline and puts everything into groups:
2672 group 1: the stars
2673 group 2: The todo keyword, maybe
2674 group 3: Priority cookie
2675 group 4: True headline
2676 group 5: Tags")
2677 (make-variable-buffer-local 'org-complex-heading-regexp)
2678 (defvar org-todo-line-tags-regexp nil
2679 "Matches a headline and puts TODO state into group 2 if present.
2680 Also put tags into group 4 if tags are present.")
2681 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2682 (defvar org-nl-done-regexp nil
2683 "Matches newline followed by a headline with the DONE keyword.")
2684 (make-variable-buffer-local 'org-nl-done-regexp)
2685 (defvar org-looking-at-done-regexp nil
2686 "Matches the DONE keyword a point.")
2687 (make-variable-buffer-local 'org-looking-at-done-regexp)
2688 (defvar org-ds-keyword-length 12
2689 "Maximum length of the Deadline and SCHEDULED keywords.")
2690 (make-variable-buffer-local 'org-ds-keyword-length)
2691 (defvar org-deadline-regexp nil
2692 "Matches the DEADLINE keyword.")
2693 (make-variable-buffer-local 'org-deadline-regexp)
2694 (defvar org-deadline-time-regexp nil
2695 "Matches the DEADLINE keyword together with a time stamp.")
2696 (make-variable-buffer-local 'org-deadline-time-regexp)
2697 (defvar org-deadline-line-regexp nil
2698 "Matches the DEADLINE keyword and the rest of the line.")
2699 (make-variable-buffer-local 'org-deadline-line-regexp)
2700 (defvar org-scheduled-regexp nil
2701 "Matches the SCHEDULED keyword.")
2702 (make-variable-buffer-local 'org-scheduled-regexp)
2703 (defvar org-scheduled-time-regexp nil
2704 "Matches the SCHEDULED keyword together with a time stamp.")
2705 (make-variable-buffer-local 'org-scheduled-time-regexp)
2706 (defvar org-closed-time-regexp nil
2707 "Matches the CLOSED keyword together with a time stamp.")
2708 (make-variable-buffer-local 'org-closed-time-regexp)
2710 (defvar org-keyword-time-regexp nil
2711 "Matches any of the 4 keywords, together with the time stamp.")
2712 (make-variable-buffer-local 'org-keyword-time-regexp)
2713 (defvar org-keyword-time-not-clock-regexp nil
2714 "Matches any of the 3 keywords, together with the time stamp.")
2715 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2716 (defvar org-maybe-keyword-time-regexp nil
2717 "Matches a timestamp, possibly preceeded by a keyword.")
2718 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2719 (defvar org-planning-or-clock-line-re nil
2720 "Matches a line with planning or clock info.")
2721 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2723 (defconst org-plain-time-of-day-regexp
2724 (concat
2725 "\\(\\<[012]?[0-9]"
2726 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2727 "\\(--?"
2728 "\\(\\<[012]?[0-9]"
2729 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2730 "\\)?")
2731 "Regular expression to match a plain time or time range.
2732 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2733 groups carry important information:
2734 0 the full match
2735 1 the first time, range or not
2736 8 the second time, if it is a range.")
2738 (defconst org-plain-time-extension-regexp
2739 (concat
2740 "\\(\\<[012]?[0-9]"
2741 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2742 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2743 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2744 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2745 groups carry important information:
2746 0 the full match
2747 7 hours of duration
2748 9 minutes of duration")
2750 (defconst org-stamp-time-of-day-regexp
2751 (concat
2752 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2753 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2754 "\\(--?"
2755 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2756 "Regular expression to match a timestamp time or time range.
2757 After a match, the following groups carry important information:
2758 0 the full match
2759 1 date plus weekday, for backreferencing to make sure both times on same day
2760 2 the first time, range or not
2761 4 the second time, if it is a range.")
2763 (defconst org-startup-options
2764 '(("fold" org-startup-folded t)
2765 ("overview" org-startup-folded t)
2766 ("nofold" org-startup-folded nil)
2767 ("showall" org-startup-folded nil)
2768 ("content" org-startup-folded content)
2769 ("hidestars" org-hide-leading-stars t)
2770 ("showstars" org-hide-leading-stars nil)
2771 ("odd" org-odd-levels-only t)
2772 ("oddeven" org-odd-levels-only nil)
2773 ("align" org-startup-align-all-tables t)
2774 ("noalign" org-startup-align-all-tables nil)
2775 ("customtime" org-display-custom-times t)
2776 ("logdone" org-log-done time)
2777 ("lognotedone" org-log-done note)
2778 ("nologdone" org-log-done nil)
2779 ("lognoteclock-out" org-log-note-clock-out t)
2780 ("nolognoteclock-out" org-log-note-clock-out nil)
2781 ("logrepeat" org-log-repeat state)
2782 ("lognoterepeat" org-log-repeat note)
2783 ("nologrepeat" org-log-repeat nil)
2784 ("constcgs" constants-unit-system cgs)
2785 ("constSI" constants-unit-system SI))
2786 "Variable associated with STARTUP options for org-mode.
2787 Each element is a list of three items: The startup options as written
2788 in the #+STARTUP line, the corresponding variable, and the value to
2789 set this variable to if the option is found. An optional forth element PUSH
2790 means to push this value onto the list in the variable.")
2792 (defun org-set-regexps-and-options ()
2793 "Precompute regular expressions for current buffer."
2794 (when (org-mode-p)
2795 (org-set-local 'org-todo-kwd-alist nil)
2796 (org-set-local 'org-todo-key-alist nil)
2797 (org-set-local 'org-todo-key-trigger nil)
2798 (org-set-local 'org-todo-keywords-1 nil)
2799 (org-set-local 'org-done-keywords nil)
2800 (org-set-local 'org-todo-heads nil)
2801 (org-set-local 'org-todo-sets nil)
2802 (org-set-local 'org-todo-log-states nil)
2803 (org-set-local 'org-file-properties nil)
2804 (org-set-local 'org-file-tags nil)
2805 (let ((re (org-make-options-regexp
2806 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2807 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2808 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2809 (splitre "[ \t]+")
2810 kwds kws0 kwsa key log value cat arch tags const links hw dws
2811 tail sep kws1 prio props ftags drawers
2812 ext-setup-or-nil setup-contents (start 0))
2813 (save-excursion
2814 (save-restriction
2815 (widen)
2816 (goto-char (point-min))
2817 (while (or (and ext-setup-or-nil
2818 (string-match re ext-setup-or-nil start)
2819 (setq start (match-end 0)))
2820 (and (setq ext-setup-or-nil nil start 0)
2821 (re-search-forward re nil t)))
2822 (setq key (upcase (match-string 1 ext-setup-or-nil))
2823 value (org-match-string-no-properties 2 ext-setup-or-nil))
2824 (cond
2825 ((equal key "CATEGORY")
2826 (if (string-match "[ \t]+$" value)
2827 (setq value (replace-match "" t t value)))
2828 (setq cat value))
2829 ((member key '("SEQ_TODO" "TODO"))
2830 (push (cons 'sequence (org-split-string value splitre)) kwds))
2831 ((equal key "TYP_TODO")
2832 (push (cons 'type (org-split-string value splitre)) kwds))
2833 ((equal key "TAGS")
2834 (setq tags (append tags (org-split-string value splitre))))
2835 ((equal key "COLUMNS")
2836 (org-set-local 'org-columns-default-format value))
2837 ((equal key "LINK")
2838 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2839 (push (cons (match-string 1 value)
2840 (org-trim (match-string 2 value)))
2841 links)))
2842 ((equal key "PRIORITIES")
2843 (setq prio (org-split-string value " +")))
2844 ((equal key "PROPERTY")
2845 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2846 (push (cons (match-string 1 value) (match-string 2 value))
2847 props)))
2848 ((equal key "FILETAGS")
2849 (when (string-match "\\S-" value)
2850 (setq ftags
2851 (append
2852 ftags
2853 (apply 'append
2854 (mapcar (lambda (x) (org-split-string x ":"))
2855 (org-split-string value)))))))
2856 ((equal key "DRAWERS")
2857 (setq drawers (org-split-string value splitre)))
2858 ((equal key "CONSTANTS")
2859 (setq const (append const (org-split-string value splitre))))
2860 ((equal key "STARTUP")
2861 (let ((opts (org-split-string value splitre))
2862 l var val)
2863 (while (setq l (pop opts))
2864 (when (setq l (assoc l org-startup-options))
2865 (setq var (nth 1 l) val (nth 2 l))
2866 (if (not (nth 3 l))
2867 (set (make-local-variable var) val)
2868 (if (not (listp (symbol-value var)))
2869 (set (make-local-variable var) nil))
2870 (set (make-local-variable var) (symbol-value var))
2871 (add-to-list var val))))))
2872 ((equal key "ARCHIVE")
2873 (string-match " *$" value)
2874 (setq arch (replace-match "" t t value))
2875 (remove-text-properties 0 (length arch)
2876 '(face t fontified t) arch))
2877 ((equal key "SETUPFILE")
2878 (setq setup-contents (org-file-contents
2879 (expand-file-name
2880 (org-remove-double-quotes value))
2881 'noerror))
2882 (if (not ext-setup-or-nil)
2883 (setq ext-setup-or-nil setup-contents start 0)
2884 (setq ext-setup-or-nil
2885 (concat (substring ext-setup-or-nil 0 start)
2886 "\n" setup-contents "\n"
2887 (substring ext-setup-or-nil start)))))
2888 ))))
2889 (when cat
2890 (org-set-local 'org-category (intern cat))
2891 (push (cons "CATEGORY" cat) props))
2892 (when prio
2893 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2894 (setq prio (mapcar 'string-to-char prio))
2895 (org-set-local 'org-highest-priority (nth 0 prio))
2896 (org-set-local 'org-lowest-priority (nth 1 prio))
2897 (org-set-local 'org-default-priority (nth 2 prio)))
2898 (and props (org-set-local 'org-file-properties (nreverse props)))
2899 (and ftags (org-set-local 'org-file-tags ftags))
2900 (and drawers (org-set-local 'org-drawers drawers))
2901 (and arch (org-set-local 'org-archive-location arch))
2902 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2903 ;; Process the TODO keywords
2904 (unless kwds
2905 ;; Use the global values as if they had been given locally.
2906 (setq kwds (default-value 'org-todo-keywords))
2907 (if (stringp (car kwds))
2908 (setq kwds (list (cons org-todo-interpretation
2909 (default-value 'org-todo-keywords)))))
2910 (setq kwds (reverse kwds)))
2911 (setq kwds (nreverse kwds))
2912 (let (inter kws kw)
2913 (while (setq kws (pop kwds))
2914 (setq inter (pop kws) sep (member "|" kws)
2915 kws0 (delete "|" (copy-sequence kws))
2916 kwsa nil
2917 kws1 (mapcar
2918 (lambda (x)
2919 ;; 1 2
2920 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2921 (progn
2922 (setq kw (match-string 1 x)
2923 key (and (match-end 2) (match-string 2 x))
2924 log (org-extract-log-state-settings x))
2925 (push (cons kw (and key (string-to-char key))) kwsa)
2926 (and log (push log org-todo-log-states))
2928 (error "Invalid TODO keyword %s" x)))
2929 kws0)
2930 kwsa (if kwsa (append '((:startgroup))
2931 (nreverse kwsa)
2932 '((:endgroup))))
2933 hw (car kws1)
2934 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2935 tail (list inter hw (car dws) (org-last dws)))
2936 (add-to-list 'org-todo-heads hw 'append)
2937 (push kws1 org-todo-sets)
2938 (setq org-done-keywords (append org-done-keywords dws nil))
2939 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2940 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2941 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2942 (setq org-todo-sets (nreverse org-todo-sets)
2943 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2944 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2945 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2946 ;; Process the constants
2947 (when const
2948 (let (e cst)
2949 (while (setq e (pop const))
2950 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2951 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2952 (setq org-table-formula-constants-local cst)))
2954 ;; Process the tags.
2955 (when tags
2956 (let (e tgs)
2957 (while (setq e (pop tags))
2958 (cond
2959 ((equal e "{") (push '(:startgroup) tgs))
2960 ((equal e "}") (push '(:endgroup) tgs))
2961 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2962 (push (cons (match-string 1 e)
2963 (string-to-char (match-string 2 e)))
2964 tgs))
2965 (t (push (list e) tgs))))
2966 (org-set-local 'org-tag-alist nil)
2967 (while (setq e (pop tgs))
2968 (or (and (stringp (car e))
2969 (assoc (car e) org-tag-alist))
2970 (push e org-tag-alist)))))
2972 ;; Compute the regular expressions and other local variables
2973 (if (not org-done-keywords)
2974 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2975 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2976 (length org-scheduled-string)
2977 (length org-clock-string)
2978 (length org-closed-string)))
2979 org-drawer-regexp
2980 (concat "^[ \t]*:\\("
2981 (mapconcat 'regexp-quote org-drawers "\\|")
2982 "\\):[ \t]*$")
2983 org-not-done-keywords
2984 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2985 org-todo-regexp
2986 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2987 "\\|") "\\)\\>")
2988 org-not-done-regexp
2989 (concat "\\<\\("
2990 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2991 "\\)\\>")
2992 org-todo-line-regexp
2993 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2994 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2995 "\\)\\>\\)?[ \t]*\\(.*\\)")
2996 org-complex-heading-regexp
2997 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2998 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2999 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3000 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3001 org-nl-done-regexp
3002 (concat "\n\\*+[ \t]+"
3003 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3004 "\\)" "\\>")
3005 org-todo-line-tags-regexp
3006 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3007 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3008 (org-re
3009 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3010 org-looking-at-done-regexp
3011 (concat "^" "\\(?:"
3012 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3013 "\\>")
3014 org-deadline-regexp (concat "\\<" org-deadline-string)
3015 org-deadline-time-regexp
3016 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3017 org-deadline-line-regexp
3018 (concat "\\<\\(" org-deadline-string "\\).*")
3019 org-scheduled-regexp
3020 (concat "\\<" org-scheduled-string)
3021 org-scheduled-time-regexp
3022 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3023 org-closed-time-regexp
3024 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3025 org-keyword-time-regexp
3026 (concat "\\<\\(" org-scheduled-string
3027 "\\|" org-deadline-string
3028 "\\|" org-closed-string
3029 "\\|" org-clock-string "\\)"
3030 " *[[<]\\([^]>]+\\)[]>]")
3031 org-keyword-time-not-clock-regexp
3032 (concat "\\<\\(" org-scheduled-string
3033 "\\|" org-deadline-string
3034 "\\|" org-closed-string
3035 "\\)"
3036 " *[[<]\\([^]>]+\\)[]>]")
3037 org-maybe-keyword-time-regexp
3038 (concat "\\(\\<\\(" org-scheduled-string
3039 "\\|" org-deadline-string
3040 "\\|" org-closed-string
3041 "\\|" org-clock-string "\\)\\)?"
3042 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3043 org-planning-or-clock-line-re
3044 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3045 "\\|" org-deadline-string
3046 "\\|" org-closed-string "\\|" org-clock-string
3047 "\\)\\>\\)")
3049 (org-compute-latex-and-specials-regexp)
3050 (org-set-font-lock-defaults))))
3052 (defun org-file-contents (file &optional noerror)
3053 "Return the contents of FILE, as a string."
3054 (if (or (not file)
3055 (not (file-readable-p file)))
3056 (if noerror
3057 (progn
3058 (message "Cannot read file %s" file)
3059 (ding) (sit-for 2)
3061 (error "Cannot read file %s" file))
3062 (with-temp-buffer
3063 (insert-file-contents file)
3064 (buffer-string))))
3066 (defun org-extract-log-state-settings (x)
3067 "Extract the log state setting from a TODO keyword string.
3068 This will extract info from a string like \"WAIT(w@/!)\"."
3069 (let (kw key log1 log2)
3070 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3071 (setq kw (match-string 1 x)
3072 key (and (match-end 2) (match-string 2 x))
3073 log1 (and (match-end 3) (match-string 3 x))
3074 log2 (and (match-end 4) (match-string 4 x)))
3075 (and (or log1 log2)
3076 (list kw
3077 (and log1 (if (equal log1 "!") 'time 'note))
3078 (and log2 (if (equal log2 "!") 'time 'note)))))))
3080 (defun org-remove-keyword-keys (list)
3081 "Remove a pair of parenthesis at the end of each string in LIST."
3082 (mapcar (lambda (x)
3083 (if (string-match "(.*)$" x)
3084 (substring x 0 (match-beginning 0))
3086 list))
3088 ;; FIXME: this could be done much better, using second characters etc.
3089 (defun org-assign-fast-keys (alist)
3090 "Assign fast keys to a keyword-key alist.
3091 Respect keys that are already there."
3092 (let (new e k c c1 c2 (char ?a))
3093 (while (setq e (pop alist))
3094 (cond
3095 ((equal e '(:startgroup)) (push e new))
3096 ((equal e '(:endgroup)) (push e new))
3098 (setq k (car e) c2 nil)
3099 (if (cdr e)
3100 (setq c (cdr e))
3101 ;; automatically assign a character.
3102 (setq c1 (string-to-char
3103 (downcase (substring
3104 k (if (= (string-to-char k) ?@) 1 0)))))
3105 (if (or (rassoc c1 new) (rassoc c1 alist))
3106 (while (or (rassoc char new) (rassoc char alist))
3107 (setq char (1+ char)))
3108 (setq c2 c1))
3109 (setq c (or c2 char)))
3110 (push (cons k c) new))))
3111 (nreverse new)))
3113 ;;; Some variables used in various places
3115 (defvar org-window-configuration nil
3116 "Used in various places to store a window configuration.")
3117 (defvar org-finish-function nil
3118 "Function to be called when `C-c C-c' is used.
3119 This is for getting out of special buffers like remember.")
3122 ;; FIXME: Occasionally check by commenting these, to make sure
3123 ;; no other functions uses these, forgetting to let-bind them.
3124 (defvar entry)
3125 (defvar state)
3126 (defvar last-state)
3127 (defvar date)
3128 (defvar description)
3130 ;; Defined somewhere in this file, but used before definition.
3131 (defvar org-html-entities)
3132 (defvar org-struct-menu)
3133 (defvar org-org-menu)
3134 (defvar org-tbl-menu)
3135 (defvar org-agenda-keymap)
3137 ;;;; Define the Org-mode
3139 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3140 (error "Conflict with outdated version of allout.el. Load org.el before allout.el, or ugrade to newer allout, for example by switching to Emacs 22."))
3143 ;; We use a before-change function to check if a table might need
3144 ;; an update.
3145 (defvar org-table-may-need-update t
3146 "Indicates that a table might need an update.
3147 This variable is set by `org-before-change-function'.
3148 `org-table-align' sets it back to nil.")
3149 (defun org-before-change-function (beg end)
3150 "Every change indicates that a table might need an update."
3151 (setq org-table-may-need-update t))
3152 (defvar org-mode-map)
3153 (defvar org-mode-hook nil)
3154 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3155 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3156 (defvar org-table-buffer-is-an nil)
3157 (defconst org-outline-regexp "\\*+ ")
3159 ;;;###autoload
3160 (define-derived-mode org-mode outline-mode "Org"
3161 "Outline-based notes management and organizer, alias
3162 \"Carsten's outline-mode for keeping track of everything.\"
3164 Org-mode develops organizational tasks around a NOTES file which
3165 contains information about projects as plain text. Org-mode is
3166 implemented on top of outline-mode, which is ideal to keep the content
3167 of large files well structured. It supports ToDo items, deadlines and
3168 time stamps, which magically appear in the diary listing of the Emacs
3169 calendar. Tables are easily created with a built-in table editor.
3170 Plain text URL-like links connect to websites, emails (VM), Usenet
3171 messages (Gnus), BBDB entries, and any files related to the project.
3172 For printing and sharing of notes, an Org-mode file (or a part of it)
3173 can be exported as a structured ASCII or HTML file.
3175 The following commands are available:
3177 \\{org-mode-map}"
3179 ;; Get rid of Outline menus, they are not needed
3180 ;; Need to do this here because define-derived-mode sets up
3181 ;; the keymap so late. Still, it is a waste to call this each time
3182 ;; we switch another buffer into org-mode.
3183 (if (featurep 'xemacs)
3184 (when (boundp 'outline-mode-menu-heading)
3185 ;; Assume this is Greg's port, it used easymenu
3186 (easy-menu-remove outline-mode-menu-heading)
3187 (easy-menu-remove outline-mode-menu-show)
3188 (easy-menu-remove outline-mode-menu-hide))
3189 (define-key org-mode-map [menu-bar headings] 'undefined)
3190 (define-key org-mode-map [menu-bar hide] 'undefined)
3191 (define-key org-mode-map [menu-bar show] 'undefined))
3193 (org-load-modules-maybe)
3194 (easy-menu-add org-org-menu)
3195 (easy-menu-add org-tbl-menu)
3196 (org-install-agenda-files-menu)
3197 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3198 (org-add-to-invisibility-spec '(org-cwidth))
3199 (when (featurep 'xemacs)
3200 (org-set-local 'line-move-ignore-invisible t))
3201 (org-set-local 'outline-regexp org-outline-regexp)
3202 (org-set-local 'outline-level 'org-outline-level)
3203 (when (and org-ellipsis
3204 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3205 (fboundp 'make-glyph-code))
3206 (unless org-display-table
3207 (setq org-display-table (make-display-table)))
3208 (set-display-table-slot
3209 org-display-table 4
3210 (vconcat (mapcar
3211 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3212 org-ellipsis)))
3213 (if (stringp org-ellipsis) org-ellipsis "..."))))
3214 (setq buffer-display-table org-display-table))
3215 (org-set-regexps-and-options)
3216 ;; Calc embedded
3217 (org-set-local 'calc-embedded-open-mode "# ")
3218 (modify-syntax-entry ?# "<")
3219 (modify-syntax-entry ?@ "w")
3220 (if org-startup-truncated (setq truncate-lines t))
3221 (org-set-local 'font-lock-unfontify-region-function
3222 'org-unfontify-region)
3223 ;; Activate before-change-function
3224 (org-set-local 'org-table-may-need-update t)
3225 (org-add-hook 'before-change-functions 'org-before-change-function nil
3226 'local)
3227 ;; Check for running clock before killing a buffer
3228 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3229 ;; Paragraphs and auto-filling
3230 (org-set-autofill-regexps)
3231 (setq indent-line-function 'org-indent-line-function)
3232 (org-update-radio-target-regexp)
3234 ;; Comment characters
3235 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3236 (org-set-local 'comment-padding " ")
3238 ;; Align options lines
3239 (org-set-local
3240 'align-mode-rules-list
3241 '((org-in-buffer-settings
3242 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3243 (modes . '(org-mode)))))
3245 ;; Imenu
3246 (org-set-local 'imenu-create-index-function
3247 'org-imenu-get-tree)
3249 ;; Make isearch reveal context
3250 (if (or (featurep 'xemacs)
3251 (not (boundp 'outline-isearch-open-invisible-function)))
3252 ;; Emacs 21 and XEmacs make use of the hook
3253 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3254 ;; Emacs 22 deals with this through a special variable
3255 (org-set-local 'outline-isearch-open-invisible-function
3256 (lambda (&rest ignore) (org-show-context 'isearch))))
3258 ;; If empty file that did not turn on org-mode automatically, make it to.
3259 (if (and org-insert-mode-line-in-empty-file
3260 (interactive-p)
3261 (= (point-min) (point-max)))
3262 (insert "# -*- mode: org -*-\n\n"))
3264 (unless org-inhibit-startup
3265 (when org-startup-align-all-tables
3266 (let ((bmp (buffer-modified-p)))
3267 (org-table-map-tables 'org-table-align)
3268 (set-buffer-modified-p bmp)))
3269 (org-set-startup-visibility)))
3271 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3273 (defun org-current-time ()
3274 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3275 (if (> (car org-time-stamp-rounding-minutes) 1)
3276 (let ((r (car org-time-stamp-rounding-minutes))
3277 (time (decode-time)))
3278 (apply 'encode-time
3279 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3280 (nthcdr 2 time))))
3281 (current-time)))
3283 ;;;; Font-Lock stuff, including the activators
3285 (defvar org-mouse-map (make-sparse-keymap))
3286 (org-defkey org-mouse-map
3287 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3288 (org-defkey org-mouse-map
3289 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3290 (when org-mouse-1-follows-link
3291 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3292 (when org-tab-follows-link
3293 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3294 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3295 (when org-return-follows-link
3296 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3297 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3299 (require 'font-lock)
3301 (defconst org-non-link-chars "]\t\n\r<>")
3302 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3303 "shell" "elisp"))
3304 (defvar org-link-types-re nil
3305 "Matches a link that has a url-like prefix like \"http:\"")
3306 (defvar org-link-re-with-space nil
3307 "Matches a link with spaces, optional angular brackets around it.")
3308 (defvar org-link-re-with-space2 nil
3309 "Matches a link with spaces, optional angular brackets around it.")
3310 (defvar org-angle-link-re nil
3311 "Matches link with angular brackets, spaces are allowed.")
3312 (defvar org-plain-link-re nil
3313 "Matches plain link, without spaces.")
3314 (defvar org-bracket-link-regexp nil
3315 "Matches a link in double brackets.")
3316 (defvar org-bracket-link-analytic-regexp nil
3317 "Regular expression used to analyze links.
3318 Here is what the match groups contain after a match:
3319 1: http:
3320 2: http
3321 3: path
3322 4: [desc]
3323 5: desc")
3324 (defvar org-any-link-re nil
3325 "Regular expression matching any link.")
3327 (defun org-make-link-regexps ()
3328 "Update the link regular expressions.
3329 This should be called after the variable `org-link-types' has changed."
3330 (setq org-link-types-re
3331 (concat
3332 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3333 org-link-re-with-space
3334 (concat
3335 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3336 "\\([^" org-non-link-chars " ]"
3337 "[^" org-non-link-chars "]*"
3338 "[^" org-non-link-chars " ]\\)>?")
3339 org-link-re-with-space2
3340 (concat
3341 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3342 "\\([^" org-non-link-chars " ]"
3343 "[^]\t\n\r]*"
3344 "[^" org-non-link-chars " ]\\)>?")
3345 org-angle-link-re
3346 (concat
3347 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3348 "\\([^" org-non-link-chars " ]"
3349 "[^" org-non-link-chars "]*"
3350 "\\)>")
3351 org-plain-link-re
3352 (concat
3353 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3354 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3355 org-bracket-link-regexp
3356 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3357 org-bracket-link-analytic-regexp
3358 (concat
3359 "\\[\\["
3360 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3361 "\\([^]]+\\)"
3362 "\\]"
3363 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3364 "\\]")
3365 org-any-link-re
3366 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3367 org-angle-link-re "\\)\\|\\("
3368 org-plain-link-re "\\)")))
3370 (org-make-link-regexps)
3372 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3373 "Regular expression for fast time stamp matching.")
3374 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3375 "Regular expression for fast time stamp matching.")
3376 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3377 "Regular expression matching time strings for analysis.
3378 This one does not require the space after the date, so it can be used
3379 on a string that terminates immediately after the date.")
3380 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3381 "Regular expression matching time strings for analysis.")
3382 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3383 "Regular expression matching time stamps, with groups.")
3384 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3385 "Regular expression matching time stamps (also [..]), with groups.")
3386 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3387 "Regular expression matching a time stamp range.")
3388 (defconst org-tr-regexp-both
3389 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3390 "Regular expression matching a time stamp range.")
3391 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3392 org-ts-regexp "\\)?")
3393 "Regular expression matching a time stamp or time stamp range.")
3394 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3395 org-ts-regexp-both "\\)?")
3396 "Regular expression matching a time stamp or time stamp range.
3397 The time stamps may be either active or inactive.")
3399 (defvar org-emph-face nil)
3401 (defun org-do-emphasis-faces (limit)
3402 "Run through the buffer and add overlays to links."
3403 (let (rtn)
3404 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3405 (if (not (= (char-after (match-beginning 3))
3406 (char-after (match-beginning 4))))
3407 (progn
3408 (setq rtn t)
3409 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3410 'face
3411 (nth 1 (assoc (match-string 3)
3412 org-emphasis-alist)))
3413 (add-text-properties (match-beginning 2) (match-end 2)
3414 '(font-lock-multiline t))
3415 (when org-hide-emphasis-markers
3416 (add-text-properties (match-end 4) (match-beginning 5)
3417 '(invisible org-link))
3418 (add-text-properties (match-beginning 3) (match-end 3)
3419 '(invisible org-link)))))
3420 (backward-char 1))
3421 rtn))
3423 (defun org-emphasize (&optional char)
3424 "Insert or change an emphasis, i.e. a font like bold or italic.
3425 If there is an active region, change that region to a new emphasis.
3426 If there is no region, just insert the marker characters and position
3427 the cursor between them.
3428 CHAR should be either the marker character, or the first character of the
3429 HTML tag associated with that emphasis. If CHAR is a space, the means
3430 to remove the emphasis of the selected region.
3431 If char is not given (for example in an interactive call) it
3432 will be prompted for."
3433 (interactive)
3434 (let ((eal org-emphasis-alist) e det
3435 (erc org-emphasis-regexp-components)
3436 (prompt "")
3437 (string "") beg end move tag c s)
3438 (if (org-region-active-p)
3439 (setq beg (region-beginning) end (region-end)
3440 string (buffer-substring beg end))
3441 (setq move t))
3443 (while (setq e (pop eal))
3444 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3445 c (aref tag 0))
3446 (push (cons c (string-to-char (car e))) det)
3447 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3448 (substring tag 1)))))
3449 (unless char
3450 (message "%s" (concat "Emphasis marker or tag:" prompt))
3451 (setq char (read-char-exclusive)))
3452 (setq char (or (cdr (assoc char det)) char))
3453 (if (equal char ?\ )
3454 (setq s "" move nil)
3455 (unless (assoc (char-to-string char) org-emphasis-alist)
3456 (error "No such emphasis marker: \"%c\"" char))
3457 (setq s (char-to-string char)))
3458 (while (and (> (length string) 1)
3459 (equal (substring string 0 1) (substring string -1))
3460 (assoc (substring string 0 1) org-emphasis-alist))
3461 (setq string (substring string 1 -1)))
3462 (setq string (concat s string s))
3463 (if beg (delete-region beg end))
3464 (unless (or (bolp)
3465 (string-match (concat "[" (nth 0 erc) "\n]")
3466 (char-to-string (char-before (point)))))
3467 (insert " "))
3468 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3469 (char-to-string (char-after (point))))
3470 (insert " ") (backward-char 1))
3471 (insert string)
3472 (and move (backward-char 1))))
3474 (defconst org-nonsticky-props
3475 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3478 (defun org-activate-plain-links (limit)
3479 "Run through the buffer and add overlays to links."
3480 (catch 'exit
3481 (let (f)
3482 (while (re-search-forward org-plain-link-re limit t)
3483 (setq f (get-text-property (match-beginning 0) 'face))
3484 (if (or (eq f 'org-tag)
3485 (and (listp f) (memq 'org-tag f)))
3487 (add-text-properties (match-beginning 0) (match-end 0)
3488 (list 'mouse-face 'highlight
3489 'rear-nonsticky org-nonsticky-props
3490 'keymap org-mouse-map
3492 (throw 'exit t))))))
3494 (defun org-activate-code (limit)
3495 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3496 (unless (get-text-property (match-beginning 1) 'face)
3497 (remove-text-properties (match-beginning 0) (match-end 0)
3498 '(display t invisible t intangible t))
3499 t)))
3501 (defun org-activate-angle-links (limit)
3502 "Run through the buffer and add overlays to links."
3503 (if (re-search-forward org-angle-link-re limit t)
3504 (progn
3505 (add-text-properties (match-beginning 0) (match-end 0)
3506 (list 'mouse-face 'highlight
3507 'rear-nonsticky org-nonsticky-props
3508 'keymap org-mouse-map
3510 t)))
3512 (defun org-activate-bracket-links (limit)
3513 "Run through the buffer and add overlays to bracketed links."
3514 (if (re-search-forward org-bracket-link-regexp limit t)
3515 (let* ((help (concat "LINK: "
3516 (org-match-string-no-properties 1)))
3517 ;; FIXME: above we should remove the escapes.
3518 ;; but that requires another match, protecting match data,
3519 ;; a lot of overhead for font-lock.
3520 (ip (org-maybe-intangible
3521 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3522 'keymap org-mouse-map 'mouse-face 'highlight
3523 'font-lock-multiline t 'help-echo help)))
3524 (vp (list 'rear-nonsticky org-nonsticky-props
3525 'keymap org-mouse-map 'mouse-face 'highlight
3526 ' font-lock-multiline t 'help-echo help)))
3527 ;; We need to remove the invisible property here. Table narrowing
3528 ;; may have made some of this invisible.
3529 (remove-text-properties (match-beginning 0) (match-end 0)
3530 '(invisible nil))
3531 (if (match-end 3)
3532 (progn
3533 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3534 (add-text-properties (match-beginning 3) (match-end 3) vp)
3535 (add-text-properties (match-end 3) (match-end 0) ip))
3536 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3537 (add-text-properties (match-beginning 1) (match-end 1) vp)
3538 (add-text-properties (match-end 1) (match-end 0) ip))
3539 t)))
3541 (defun org-activate-dates (limit)
3542 "Run through the buffer and add overlays to dates."
3543 (if (re-search-forward org-tsr-regexp-both limit t)
3544 (progn
3545 (add-text-properties (match-beginning 0) (match-end 0)
3546 (list 'mouse-face 'highlight
3547 'rear-nonsticky org-nonsticky-props
3548 'keymap org-mouse-map))
3549 (when org-display-custom-times
3550 (if (match-end 3)
3551 (org-display-custom-time (match-beginning 3) (match-end 3)))
3552 (org-display-custom-time (match-beginning 1) (match-end 1)))
3553 t)))
3555 (defvar org-target-link-regexp nil
3556 "Regular expression matching radio targets in plain text.")
3557 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3558 "Regular expression matching a link target.")
3559 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3560 "Regular expression matching a radio target.")
3561 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3562 "Regular expression matching any target.")
3564 (defun org-activate-target-links (limit)
3565 "Run through the buffer and add overlays to target matches."
3566 (when org-target-link-regexp
3567 (let ((case-fold-search t))
3568 (if (re-search-forward org-target-link-regexp limit t)
3569 (progn
3570 (add-text-properties (match-beginning 0) (match-end 0)
3571 (list 'mouse-face 'highlight
3572 'rear-nonsticky org-nonsticky-props
3573 'keymap org-mouse-map
3574 'help-echo "Radio target link"
3575 'org-linked-text t))
3576 t)))))
3578 (defun org-update-radio-target-regexp ()
3579 "Find all radio targets in this file and update the regular expression."
3580 (interactive)
3581 (when (memq 'radio org-activate-links)
3582 (setq org-target-link-regexp
3583 (org-make-target-link-regexp (org-all-targets 'radio)))
3584 (org-restart-font-lock)))
3586 (defun org-hide-wide-columns (limit)
3587 (let (s e)
3588 (setq s (text-property-any (point) (or limit (point-max))
3589 'org-cwidth t))
3590 (when s
3591 (setq e (next-single-property-change s 'org-cwidth))
3592 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3593 (goto-char e)
3594 t)))
3596 (defvar org-latex-and-specials-regexp nil
3597 "Regular expression for highlighting export special stuff.")
3598 (defvar org-match-substring-regexp)
3599 (defvar org-match-substring-with-braces-regexp)
3600 (defvar org-export-html-special-string-regexps)
3602 (defun org-compute-latex-and-specials-regexp ()
3603 "Compute regular expression for stuff treated specially by exporters."
3604 (if (not org-highlight-latex-fragments-and-specials)
3605 (org-set-local 'org-latex-and-specials-regexp nil)
3606 (require 'org-exp)
3607 (let*
3608 ((matchers (plist-get org-format-latex-options :matchers))
3609 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3610 org-latex-regexps)))
3611 (options (org-combine-plists (org-default-export-plist)
3612 (org-infile-export-plist)))
3613 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3614 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3615 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3616 (org-export-html-expand (plist-get options :expand-quoted-html))
3617 (org-export-with-special-strings (plist-get options :special-strings))
3618 (re-sub
3619 (cond
3620 ((equal org-export-with-sub-superscripts '{})
3621 (list org-match-substring-with-braces-regexp))
3622 (org-export-with-sub-superscripts
3623 (list org-match-substring-regexp))
3624 (t nil)))
3625 (re-latex
3626 (if org-export-with-LaTeX-fragments
3627 (mapcar (lambda (x) (nth 1 x)) latexs)))
3628 (re-macros
3629 (if org-export-with-TeX-macros
3630 (list (concat "\\\\"
3631 (regexp-opt
3632 (append (mapcar 'car org-html-entities)
3633 (if (boundp 'org-latex-entities)
3634 org-latex-entities nil))
3635 'words))) ; FIXME
3637 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3638 (re-special (if org-export-with-special-strings
3639 (mapcar (lambda (x) (car x))
3640 org-export-html-special-string-regexps)))
3641 (re-rest
3642 (delq nil
3643 (list
3644 (if org-export-html-expand "@<[^>\n]+>")
3645 ))))
3646 (org-set-local
3647 'org-latex-and-specials-regexp
3648 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3649 re-rest) "\\|")))))
3651 (defun org-do-latex-and-special-faces (limit)
3652 "Run through the buffer and add overlays to links."
3653 (when org-latex-and-specials-regexp
3654 (let (rtn d)
3655 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3656 limit t))
3657 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3658 'face))
3659 '(org-code org-verbatim underline)))
3660 (progn
3661 (setq rtn t
3662 d (cond ((member (char-after (1+ (match-beginning 0)))
3663 '(?_ ?^)) 1)
3664 (t 0)))
3665 (font-lock-prepend-text-property
3666 (+ d (match-beginning 0)) (match-end 0)
3667 'face 'org-latex-and-export-specials)
3668 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3669 '(font-lock-multiline t)))))
3670 rtn)))
3672 (defun org-restart-font-lock ()
3673 "Restart font-lock-mode, to force refontification."
3674 (when (and (boundp 'font-lock-mode) font-lock-mode)
3675 (font-lock-mode -1)
3676 (font-lock-mode 1)))
3678 (defun org-all-targets (&optional radio)
3679 "Return a list of all targets in this file.
3680 With optional argument RADIO, only find radio targets."
3681 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3682 rtn)
3683 (save-excursion
3684 (goto-char (point-min))
3685 (while (re-search-forward re nil t)
3686 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3687 rtn)))
3689 (defun org-make-target-link-regexp (targets)
3690 "Make regular expression matching all strings in TARGETS.
3691 The regular expression finds the targets also if there is a line break
3692 between words."
3693 (and targets
3694 (concat
3695 "\\<\\("
3696 (mapconcat
3697 (lambda (x)
3698 (while (string-match " +" x)
3699 (setq x (replace-match "\\s-+" t t x)))
3701 targets
3702 "\\|")
3703 "\\)\\>")))
3705 (defun org-activate-tags (limit)
3706 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3707 (progn
3708 (add-text-properties (match-beginning 1) (match-end 1)
3709 (list 'mouse-face 'highlight
3710 'rear-nonsticky org-nonsticky-props
3711 'keymap org-mouse-map))
3712 t)))
3714 (defun org-outline-level ()
3715 (save-excursion
3716 (looking-at outline-regexp)
3717 (if (match-beginning 1)
3718 (+ (org-get-string-indentation (match-string 1)) 1000)
3719 (1- (- (match-end 0) (match-beginning 0))))))
3721 (defvar org-font-lock-keywords nil)
3723 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3724 "Regular expression matching a property line.")
3726 (defvar org-font-lock-hook nil
3727 "Functions to be called for special font lock stuff.")
3729 (defun org-font-lock-hook (limit)
3730 (run-hook-with-args 'org-font-lock-hook limit))
3732 (defun org-set-font-lock-defaults ()
3733 (let* ((em org-fontify-emphasized-text)
3734 (lk org-activate-links)
3735 (org-font-lock-extra-keywords
3736 (list
3737 ;; Call the hook
3738 '(org-font-lock-hook)
3739 ;; Headlines
3740 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3741 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3742 ;; Table lines
3743 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3744 (1 'org-table t))
3745 ;; Table internals
3746 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3747 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3748 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3749 ;; Drawers
3750 (list org-drawer-regexp '(0 'org-special-keyword t))
3751 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3752 ;; Properties
3753 (list org-property-re
3754 '(1 'org-special-keyword t)
3755 '(3 'org-property-value t))
3756 (if org-format-transports-properties-p
3757 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3758 ;; Links
3759 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3760 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3761 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3762 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3763 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3764 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3765 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3766 '(org-hide-wide-columns (0 nil append))
3767 ;; TODO lines
3768 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3769 '(1 (org-get-todo-face 1) t))
3770 ;; DONE
3771 (if org-fontify-done-headline
3772 (list (concat "^[*]+ +\\<\\("
3773 (mapconcat 'regexp-quote org-done-keywords "\\|")
3774 "\\)\\(.*\\)")
3775 '(2 'org-headline-done t))
3776 nil)
3777 ;; Priorities
3778 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3779 ;; Special keywords
3780 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3781 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3782 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3783 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3784 ;; Emphasis
3785 (if em
3786 (if (featurep 'xemacs)
3787 '(org-do-emphasis-faces (0 nil append))
3788 '(org-do-emphasis-faces)))
3789 ;; Checkboxes
3790 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3791 2 'bold prepend)
3792 (if org-provide-checkbox-statistics
3793 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3794 (0 (org-get-checkbox-statistics-face) t)))
3795 ;; Description list items
3796 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3797 2 'bold prepend)
3798 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3799 '(1 'org-archived prepend))
3800 ;; Specials
3801 '(org-do-latex-and-special-faces)
3802 ;; Code
3803 '(org-activate-code (1 'org-code t))
3804 ;; COMMENT
3805 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3806 "\\|" org-quote-string "\\)\\>")
3807 '(1 'org-special-keyword t))
3808 '("^#.*" (0 'font-lock-comment-face t))
3810 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3811 ;; Now set the full font-lock-keywords
3812 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3813 (org-set-local 'font-lock-defaults
3814 '(org-font-lock-keywords t nil nil backward-paragraph))
3815 (kill-local-variable 'font-lock-keywords) nil))
3817 (defvar org-m nil)
3818 (defvar org-l nil)
3819 (defvar org-f nil)
3820 (defun org-get-level-face (n)
3821 "Get the right face for match N in font-lock matching of healdines."
3822 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3823 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3824 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3825 (cond
3826 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3827 ((eq n 2) org-f)
3828 (t (if org-level-color-stars-only nil org-f))))
3830 (defun org-get-todo-face (kwd)
3831 "Get the right face for a TODO keyword KWD.
3832 If KWD is a number, get the corresponding match group."
3833 (if (numberp kwd) (setq kwd (match-string kwd)))
3834 (or (cdr (assoc kwd org-todo-keyword-faces))
3835 (and (member kwd org-done-keywords) 'org-done)
3836 'org-todo))
3838 (defun org-unfontify-region (beg end &optional maybe_loudly)
3839 "Remove fontification and activation overlays from links."
3840 (font-lock-default-unfontify-region beg end)
3841 (let* ((buffer-undo-list t)
3842 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3843 (inhibit-modification-hooks t)
3844 deactivate-mark buffer-file-name buffer-file-truename)
3845 (remove-text-properties beg end
3846 '(mouse-face t keymap t org-linked-text t
3847 invisible t intangible t))))
3849 ;;;; Visibility cycling, including org-goto and indirect buffer
3851 ;;; Cycling
3853 (defvar org-cycle-global-status nil)
3854 (make-variable-buffer-local 'org-cycle-global-status)
3855 (defvar org-cycle-subtree-status nil)
3856 (make-variable-buffer-local 'org-cycle-subtree-status)
3858 ;;;###autoload
3859 (defun org-cycle (&optional arg)
3860 "Visibility cycling for Org-mode.
3862 - When this function is called with a prefix argument, rotate the entire
3863 buffer through 3 states (global cycling)
3864 1. OVERVIEW: Show only top-level headlines.
3865 2. CONTENTS: Show all headlines of all levels, but no body text.
3866 3. SHOW ALL: Show everything.
3867 When called with two C-c C-u prefixes, switch to the startup visibility,
3868 determined by the variable `org-startup-folded', and by any VISIBILITY
3869 properties in the buffer.
3871 - When point is at the beginning of a headline, rotate the subtree started
3872 by this line through 3 different states (local cycling)
3873 1. FOLDED: Only the main headline is shown.
3874 2. CHILDREN: The main headline and the direct children are shown.
3875 From this state, you can move to one of the children
3876 and zoom in further.
3877 3. SUBTREE: Show the entire subtree, including body text.
3879 - When there is a numeric prefix, go up to a heading with level ARG, do
3880 a `show-subtree' and return to the previous cursor position. If ARG
3881 is negative, go up that many levels.
3883 - When point is not at the beginning of a headline, execute the global
3884 binding for TAB, which is re-indenting the line. See the option
3885 `org-cycle-emulate-tab' for details.
3887 - Special case: if point is at the beginning of the buffer and there is
3888 no headline in line 1, this function will act as if called with prefix arg.
3889 But only if also the variable `org-cycle-global-at-bob' is t."
3890 (interactive "P")
3891 (org-load-modules-maybe)
3892 (let* ((outline-regexp
3893 (if (and (org-mode-p) org-cycle-include-plain-lists)
3894 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3895 outline-regexp))
3896 (bob-special (and org-cycle-global-at-bob (bobp)
3897 (not (looking-at outline-regexp))))
3898 (org-cycle-hook
3899 (if bob-special
3900 (delq 'org-optimize-window-after-visibility-change
3901 (copy-sequence org-cycle-hook))
3902 org-cycle-hook))
3903 (pos (point)))
3905 (if (or bob-special (equal arg '(4)))
3906 ;; special case: use global cycling
3907 (setq arg t))
3909 (cond
3911 ((equal arg '(16))
3912 (org-set-startup-visibility)
3913 (message "Startup visibility, plus VISIBILITY properties."))
3915 ((org-at-table-p 'any)
3916 ;; Enter the table or move to the next field in the table
3917 (or (org-table-recognize-table.el)
3918 (progn
3919 (if arg (org-table-edit-field t)
3920 (org-table-justify-field-maybe)
3921 (call-interactively 'org-table-next-field)))))
3923 ((eq arg t) ;; Global cycling
3925 (cond
3926 ((and (eq last-command this-command)
3927 (eq org-cycle-global-status 'overview))
3928 ;; We just created the overview - now do table of contents
3929 ;; This can be slow in very large buffers, so indicate action
3930 (message "CONTENTS...")
3931 (org-content)
3932 (message "CONTENTS...done")
3933 (setq org-cycle-global-status 'contents)
3934 (run-hook-with-args 'org-cycle-hook 'contents))
3936 ((and (eq last-command this-command)
3937 (eq org-cycle-global-status 'contents))
3938 ;; We just showed the table of contents - now show everything
3939 (show-all)
3940 (message "SHOW ALL")
3941 (setq org-cycle-global-status 'all)
3942 (run-hook-with-args 'org-cycle-hook 'all))
3945 ;; Default action: go to overview
3946 (org-overview)
3947 (message "OVERVIEW")
3948 (setq org-cycle-global-status 'overview)
3949 (run-hook-with-args 'org-cycle-hook 'overview))))
3951 ((and org-drawers org-drawer-regexp
3952 (save-excursion
3953 (beginning-of-line 1)
3954 (looking-at org-drawer-regexp)))
3955 ;; Toggle block visibility
3956 (org-flag-drawer
3957 (not (get-char-property (match-end 0) 'invisible))))
3959 ((integerp arg)
3960 ;; Show-subtree, ARG levels up from here.
3961 (save-excursion
3962 (org-back-to-heading)
3963 (outline-up-heading (if (< arg 0) (- arg)
3964 (- (funcall outline-level) arg)))
3965 (org-show-subtree)))
3967 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3968 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3969 ;; At a heading: rotate between three different views
3970 (org-back-to-heading)
3971 (let ((goal-column 0) eoh eol eos)
3972 ;; First, some boundaries
3973 (save-excursion
3974 (org-back-to-heading)
3975 (save-excursion
3976 (beginning-of-line 2)
3977 (while (and (not (eobp)) ;; this is like `next-line'
3978 (get-char-property (1- (point)) 'invisible))
3979 (beginning-of-line 2)) (setq eol (point)))
3980 (outline-end-of-heading) (setq eoh (point))
3981 (org-end-of-subtree t)
3982 (unless (eobp)
3983 (skip-chars-forward " \t\n")
3984 (beginning-of-line 1) ; in case this is an item
3986 (setq eos (1- (point))))
3987 ;; Find out what to do next and set `this-command'
3988 (cond
3989 ((= eos eoh)
3990 ;; Nothing is hidden behind this heading
3991 (message "EMPTY ENTRY")
3992 (setq org-cycle-subtree-status nil)
3993 (save-excursion
3994 (goto-char eos)
3995 (outline-next-heading)
3996 (if (org-invisible-p) (org-flag-heading nil))))
3997 ((or (>= eol eos)
3998 (not (string-match "\\S-" (buffer-substring eol eos))))
3999 ;; Entire subtree is hidden in one line: open it
4000 (org-show-entry)
4001 (show-children)
4002 (message "CHILDREN")
4003 (save-excursion
4004 (goto-char eos)
4005 (outline-next-heading)
4006 (if (org-invisible-p) (org-flag-heading nil)))
4007 (setq org-cycle-subtree-status 'children)
4008 (run-hook-with-args 'org-cycle-hook 'children))
4009 ((and (eq last-command this-command)
4010 (eq org-cycle-subtree-status 'children))
4011 ;; We just showed the children, now show everything.
4012 (org-show-subtree)
4013 (message "SUBTREE")
4014 (setq org-cycle-subtree-status 'subtree)
4015 (run-hook-with-args 'org-cycle-hook 'subtree))
4017 ;; Default action: hide the subtree.
4018 (hide-subtree)
4019 (message "FOLDED")
4020 (setq org-cycle-subtree-status 'folded)
4021 (run-hook-with-args 'org-cycle-hook 'folded)))))
4023 ;; TAB emulation and template completion
4024 (buffer-read-only (org-back-to-heading))
4026 ((org-try-structure-completion))
4028 ((org-try-cdlatex-tab))
4030 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4031 (or (not (bolp))
4032 (not (looking-at outline-regexp))))
4033 (call-interactively (global-key-binding "\t")))
4035 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4036 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4037 (or (and (eq org-cycle-emulate-tab 'white)
4038 (= (match-end 0) (point-at-eol)))
4039 (and (eq org-cycle-emulate-tab 'whitestart)
4040 (>= (match-end 0) pos))))
4042 (eq org-cycle-emulate-tab t))
4043 (call-interactively (global-key-binding "\t")))
4045 (t (save-excursion
4046 (org-back-to-heading)
4047 (org-cycle))))))
4049 ;;;###autoload
4050 (defun org-global-cycle (&optional arg)
4051 "Cycle the global visibility. For details see `org-cycle'.
4052 With C-u prefix arg, switch to startup visibility.
4053 With a numeric prefix, show all headlines up to that level."
4054 (interactive "P")
4055 (let ((org-cycle-include-plain-lists
4056 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4057 (cond
4058 ((integerp arg)
4059 (show-all)
4060 (hide-sublevels arg)
4061 (setq org-cycle-global-status 'contents))
4062 ((equal arg '(4))
4063 (org-set-startup-visibility)
4064 (message "Startup visibility, plus VISIBILITY properties."))
4066 (org-cycle '(4))))))
4068 (defun org-set-startup-visibility ()
4069 "Set the visibility required by startup options and properties."
4070 (cond
4071 ((eq org-startup-folded t)
4072 (org-cycle '(4)))
4073 ((eq org-startup-folded 'content)
4074 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4075 (org-cycle '(4)) (org-cycle '(4)))))
4076 (org-set-visibility-according-to-property 'no-cleanup)
4077 (org-cycle-hide-archived-subtrees 'all)
4078 (org-cycle-hide-drawers 'all)
4079 (org-cycle-show-empty-lines 'all))
4081 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4082 "Switch subtree visibilities according to :VISIBILITY: property."
4083 (interactive)
4084 (let (state)
4085 (save-excursion
4086 (goto-char (point-min))
4087 (while (re-search-forward
4088 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4089 nil t)
4090 (setq state (match-string 1))
4091 (save-excursion
4092 (org-back-to-heading t)
4093 (hide-subtree)
4094 (org-reveal)
4095 (cond
4096 ((equal state '("fold" "folded"))
4097 (hide-subtree))
4098 ((equal state "children")
4099 (org-show-hidden-entry)
4100 (show-children))
4101 ((equal state "content")
4102 (save-excursion
4103 (save-restriction
4104 (org-narrow-to-subtree)
4105 (org-content))))
4106 ((member state '("all" "showall"))
4107 (show-subtree)))))
4108 (unless no-cleanup
4109 (org-cycle-hide-archived-subtrees 'all)
4110 (org-cycle-hide-drawers 'all)
4111 (org-cycle-show-empty-lines 'all)))))
4113 (defun org-overview ()
4114 "Switch to overview mode, shoing only top-level headlines.
4115 Really, this shows all headlines with level equal or greater than the level
4116 of the first headline in the buffer. This is important, because if the
4117 first headline is not level one, then (hide-sublevels 1) gives confusing
4118 results."
4119 (interactive)
4120 (let ((level (save-excursion
4121 (goto-char (point-min))
4122 (if (re-search-forward (concat "^" outline-regexp) nil t)
4123 (progn
4124 (goto-char (match-beginning 0))
4125 (funcall outline-level))))))
4126 (and level (hide-sublevels level))))
4128 (defun org-content (&optional arg)
4129 "Show all headlines in the buffer, like a table of contents.
4130 With numerical argument N, show content up to level N."
4131 (interactive "P")
4132 (save-excursion
4133 ;; Visit all headings and show their offspring
4134 (and (integerp arg) (org-overview))
4135 (goto-char (point-max))
4136 (catch 'exit
4137 (while (and (progn (condition-case nil
4138 (outline-previous-visible-heading 1)
4139 (error (goto-char (point-min))))
4141 (looking-at outline-regexp))
4142 (if (integerp arg)
4143 (show-children (1- arg))
4144 (show-branches))
4145 (if (bobp) (throw 'exit nil))))))
4148 (defun org-optimize-window-after-visibility-change (state)
4149 "Adjust the window after a change in outline visibility.
4150 This function is the default value of the hook `org-cycle-hook'."
4151 (when (get-buffer-window (current-buffer))
4152 (cond
4153 ; ((eq state 'overview) (org-first-headline-recenter 1))
4154 ; ((eq state 'overview) (org-beginning-of-line))
4155 ((eq state 'content) nil)
4156 ((eq state 'all) nil)
4157 ((eq state 'folded) nil)
4158 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4159 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4161 (defun org-compact-display-after-subtree-move ()
4162 (let (beg end)
4163 (save-excursion
4164 (if (org-up-heading-safe)
4165 (progn
4166 (hide-subtree)
4167 (show-entry)
4168 (show-children)
4169 (org-cycle-show-empty-lines 'children)
4170 (org-cycle-hide-drawers 'children))
4171 (org-overview)))))
4173 (defun org-cycle-show-empty-lines (state)
4174 "Show empty lines above all visible headlines.
4175 The region to be covered depends on STATE when called through
4176 `org-cycle-hook'. Lisp program can use t for STATE to get the
4177 entire buffer covered. Note that an empty line is only shown if there
4178 are at least `org-cycle-separator-lines' empty lines before the headeline."
4179 (when (> org-cycle-separator-lines 0)
4180 (save-excursion
4181 (let* ((n org-cycle-separator-lines)
4182 (re (cond
4183 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4184 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4185 (t (let ((ns (number-to-string (- n 2))))
4186 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4187 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4188 beg end)
4189 (cond
4190 ((memq state '(overview contents t))
4191 (setq beg (point-min) end (point-max)))
4192 ((memq state '(children folded))
4193 (setq beg (point) end (progn (org-end-of-subtree t t)
4194 (beginning-of-line 2)
4195 (point)))))
4196 (when beg
4197 (goto-char beg)
4198 (while (re-search-forward re end t)
4199 (if (not (get-char-property (match-end 1) 'invisible))
4200 (outline-flag-region
4201 (match-beginning 1) (match-end 1) nil)))))))
4202 ;; Never hide empty lines at the end of the file.
4203 (save-excursion
4204 (goto-char (point-max))
4205 (outline-previous-heading)
4206 (outline-end-of-heading)
4207 (if (and (looking-at "[ \t\n]+")
4208 (= (match-end 0) (point-max)))
4209 (outline-flag-region (point) (match-end 0) nil))))
4211 (defun org-show-empty-lines-in-parent ()
4212 "Move to the parent and re-show empty lines before visible headlines."
4213 (save-excursion
4214 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4215 (org-cycle-show-empty-lines context))))
4217 (defun org-cycle-hide-drawers (state)
4218 "Re-hide all drawers after a visibility state change."
4219 (when (and (org-mode-p)
4220 (not (memq state '(overview folded))))
4221 (save-excursion
4222 (let* ((globalp (memq state '(contents all)))
4223 (beg (if globalp (point-min) (point)))
4224 (end (if globalp (point-max) (org-end-of-subtree t))))
4225 (goto-char beg)
4226 (while (re-search-forward org-drawer-regexp end t)
4227 (org-flag-drawer t))))))
4229 (defun org-flag-drawer (flag)
4230 (save-excursion
4231 (beginning-of-line 1)
4232 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4233 (let ((b (match-end 0))
4234 (outline-regexp org-outline-regexp))
4235 (if (re-search-forward
4236 "^[ \t]*:END:"
4237 (save-excursion (outline-next-heading) (point)) t)
4238 (outline-flag-region b (point-at-eol) flag)
4239 (error ":END: line missing"))))))
4241 (defun org-subtree-end-visible-p ()
4242 "Is the end of the current subtree visible?"
4243 (pos-visible-in-window-p
4244 (save-excursion (org-end-of-subtree t) (point))))
4246 (defun org-first-headline-recenter (&optional N)
4247 "Move cursor to the first headline and recenter the headline.
4248 Optional argument N means, put the headline into the Nth line of the window."
4249 (goto-char (point-min))
4250 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4251 (beginning-of-line)
4252 (recenter (prefix-numeric-value N))))
4254 ;;; Org-goto
4256 (defvar org-goto-window-configuration nil)
4257 (defvar org-goto-marker nil)
4258 (defvar org-goto-map
4259 (let ((map (make-sparse-keymap)))
4260 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4261 (while (setq cmd (pop cmds))
4262 (substitute-key-definition cmd cmd map global-map)))
4263 (suppress-keymap map)
4264 (org-defkey map "\C-m" 'org-goto-ret)
4265 (org-defkey map [(return)] 'org-goto-ret)
4266 (org-defkey map [(left)] 'org-goto-left)
4267 (org-defkey map [(right)] 'org-goto-right)
4268 (org-defkey map [(control ?g)] 'org-goto-quit)
4269 (org-defkey map "\C-i" 'org-cycle)
4270 (org-defkey map [(tab)] 'org-cycle)
4271 (org-defkey map [(down)] 'outline-next-visible-heading)
4272 (org-defkey map [(up)] 'outline-previous-visible-heading)
4273 (if org-goto-auto-isearch
4274 (if (fboundp 'define-key-after)
4275 (define-key-after map [t] 'org-goto-local-auto-isearch)
4276 nil)
4277 (org-defkey map "q" 'org-goto-quit)
4278 (org-defkey map "n" 'outline-next-visible-heading)
4279 (org-defkey map "p" 'outline-previous-visible-heading)
4280 (org-defkey map "f" 'outline-forward-same-level)
4281 (org-defkey map "b" 'outline-backward-same-level)
4282 (org-defkey map "u" 'outline-up-heading))
4283 (org-defkey map "/" 'org-occur)
4284 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4285 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4286 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4287 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4288 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4289 map))
4291 (defconst org-goto-help
4292 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4293 RET=jump to location [Q]uit and return to previous location
4294 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4296 (defvar org-goto-start-pos) ; dynamically scoped parameter
4298 ;; FIXME: Docstring doe not mention both interfaces
4299 (defun org-goto (&optional alternative-interface)
4300 "Look up a different location in the current file, keeping current visibility.
4302 When you want look-up or go to a different location in a document, the
4303 fastest way is often to fold the entire buffer and then dive into the tree.
4304 This method has the disadvantage, that the previous location will be folded,
4305 which may not be what you want.
4307 This command works around this by showing a copy of the current buffer
4308 in an indirect buffer, in overview mode. You can dive into the tree in
4309 that copy, use org-occur and incremental search to find a location.
4310 When pressing RET or `Q', the command returns to the original buffer in
4311 which the visibility is still unchanged. After RET is will also jump to
4312 the location selected in the indirect buffer and expose the
4313 the headline hierarchy above."
4314 (interactive "P")
4315 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4316 (org-refile-use-outline-path t)
4317 (interface
4318 (if (not alternative-interface)
4319 org-goto-interface
4320 (if (eq org-goto-interface 'outline)
4321 'outline-path-completion
4322 'outline)))
4323 (org-goto-start-pos (point))
4324 (selected-point
4325 (if (eq interface 'outline)
4326 (car (org-get-location (current-buffer) org-goto-help))
4327 (nth 3 (org-refile-get-location "Goto: ")))))
4328 (if selected-point
4329 (progn
4330 (org-mark-ring-push org-goto-start-pos)
4331 (goto-char selected-point)
4332 (if (or (org-invisible-p) (org-invisible-p2))
4333 (org-show-context 'org-goto)))
4334 (message "Quit"))))
4336 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4337 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4338 (defvar org-goto-local-auto-isearch-map) ; defined below
4340 (defun org-get-location (buf help)
4341 "Let the user select a location in the Org-mode buffer BUF.
4342 This function uses a recursive edit. It returns the selected position
4343 or nil."
4344 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4345 (isearch-hide-immediately nil)
4346 (isearch-search-fun-function
4347 (lambda () 'org-goto-local-search-forward-headings))
4348 (org-goto-selected-point org-goto-exit-command))
4349 (save-excursion
4350 (save-window-excursion
4351 (delete-other-windows)
4352 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4353 (switch-to-buffer
4354 (condition-case nil
4355 (make-indirect-buffer (current-buffer) "*org-goto*")
4356 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4357 (with-output-to-temp-buffer "*Help*"
4358 (princ help))
4359 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4360 (setq buffer-read-only nil)
4361 (let ((org-startup-truncated t)
4362 (org-startup-folded nil)
4363 (org-startup-align-all-tables nil))
4364 (org-mode)
4365 (org-overview))
4366 (setq buffer-read-only t)
4367 (if (and (boundp 'org-goto-start-pos)
4368 (integer-or-marker-p org-goto-start-pos))
4369 (let ((org-show-hierarchy-above t)
4370 (org-show-siblings t)
4371 (org-show-following-heading t))
4372 (goto-char org-goto-start-pos)
4373 (and (org-invisible-p) (org-show-context)))
4374 (goto-char (point-min)))
4375 (org-beginning-of-line)
4376 (message "Select location and press RET")
4377 (use-local-map org-goto-map)
4378 (recursive-edit)
4380 (kill-buffer "*org-goto*")
4381 (cons org-goto-selected-point org-goto-exit-command)))
4383 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4384 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4385 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4386 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4388 (defun org-goto-local-search-forward-headings (string bound noerror)
4389 "Search and make sure that anu matches are in headlines."
4390 (catch 'return
4391 (while (search-forward string bound noerror)
4392 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4393 (and (member :headline context)
4394 (not (member :tags context))))
4395 (throw 'return (point))))))
4397 (defun org-goto-local-auto-isearch ()
4398 "Start isearch."
4399 (interactive)
4400 (goto-char (point-min))
4401 (let ((keys (this-command-keys)))
4402 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4403 (isearch-mode t)
4404 (isearch-process-search-char (string-to-char keys)))))
4406 (defun org-goto-ret (&optional arg)
4407 "Finish `org-goto' by going to the new location."
4408 (interactive "P")
4409 (setq org-goto-selected-point (point)
4410 org-goto-exit-command 'return)
4411 (throw 'exit nil))
4413 (defun org-goto-left ()
4414 "Finish `org-goto' by going to the new location."
4415 (interactive)
4416 (if (org-on-heading-p)
4417 (progn
4418 (beginning-of-line 1)
4419 (setq org-goto-selected-point (point)
4420 org-goto-exit-command 'left)
4421 (throw 'exit nil))
4422 (error "Not on a heading")))
4424 (defun org-goto-right ()
4425 "Finish `org-goto' by going to the new location."
4426 (interactive)
4427 (if (org-on-heading-p)
4428 (progn
4429 (setq org-goto-selected-point (point)
4430 org-goto-exit-command 'right)
4431 (throw 'exit nil))
4432 (error "Not on a heading")))
4434 (defun org-goto-quit ()
4435 "Finish `org-goto' without cursor motion."
4436 (interactive)
4437 (setq org-goto-selected-point nil)
4438 (setq org-goto-exit-command 'quit)
4439 (throw 'exit nil))
4441 ;;; Indirect buffer display of subtrees
4443 (defvar org-indirect-dedicated-frame nil
4444 "This is the frame being used for indirect tree display.")
4445 (defvar org-last-indirect-buffer nil)
4447 (defun org-tree-to-indirect-buffer (&optional arg)
4448 "Create indirect buffer and narrow it to current subtree.
4449 With numerical prefix ARG, go up to this level and then take that tree.
4450 If ARG is negative, go up that many levels.
4451 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4452 indirect buffer previously made with this command, to avoid proliferation of
4453 indirect buffers. However, when you call the command with a `C-u' prefix, or
4454 when `org-indirect-buffer-display' is `new-frame', the last buffer
4455 is kept so that you can work with several indirect buffers at the same time.
4456 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4457 requests that a new frame be made for the new buffer, so that the dedicated
4458 frame is not changed."
4459 (interactive "P")
4460 (let ((cbuf (current-buffer))
4461 (cwin (selected-window))
4462 (pos (point))
4463 beg end level heading ibuf)
4464 (save-excursion
4465 (org-back-to-heading t)
4466 (when (numberp arg)
4467 (setq level (org-outline-level))
4468 (if (< arg 0) (setq arg (+ level arg)))
4469 (while (> (setq level (org-outline-level)) arg)
4470 (outline-up-heading 1 t)))
4471 (setq beg (point)
4472 heading (org-get-heading))
4473 (org-end-of-subtree t) (setq end (point)))
4474 (if (and (buffer-live-p org-last-indirect-buffer)
4475 (not (eq org-indirect-buffer-display 'new-frame))
4476 (not arg))
4477 (kill-buffer org-last-indirect-buffer))
4478 (setq ibuf (org-get-indirect-buffer cbuf)
4479 org-last-indirect-buffer ibuf)
4480 (cond
4481 ((or (eq org-indirect-buffer-display 'new-frame)
4482 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4483 (select-frame (make-frame))
4484 (delete-other-windows)
4485 (switch-to-buffer ibuf)
4486 (org-set-frame-title heading))
4487 ((eq org-indirect-buffer-display 'dedicated-frame)
4488 (raise-frame
4489 (select-frame (or (and org-indirect-dedicated-frame
4490 (frame-live-p org-indirect-dedicated-frame)
4491 org-indirect-dedicated-frame)
4492 (setq org-indirect-dedicated-frame (make-frame)))))
4493 (delete-other-windows)
4494 (switch-to-buffer ibuf)
4495 (org-set-frame-title (concat "Indirect: " heading)))
4496 ((eq org-indirect-buffer-display 'current-window)
4497 (switch-to-buffer ibuf))
4498 ((eq org-indirect-buffer-display 'other-window)
4499 (pop-to-buffer ibuf))
4500 (t (error "Invalid value.")))
4501 (if (featurep 'xemacs)
4502 (save-excursion (org-mode) (turn-on-font-lock)))
4503 (narrow-to-region beg end)
4504 (show-all)
4505 (goto-char pos)
4506 (and (window-live-p cwin) (select-window cwin))))
4508 (defun org-get-indirect-buffer (&optional buffer)
4509 (setq buffer (or buffer (current-buffer)))
4510 (let ((n 1) (base (buffer-name buffer)) bname)
4511 (while (buffer-live-p
4512 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4513 (setq n (1+ n)))
4514 (condition-case nil
4515 (make-indirect-buffer buffer bname 'clone)
4516 (error (make-indirect-buffer buffer bname)))))
4518 (defun org-set-frame-title (title)
4519 "Set the title of the current frame to the string TITLE."
4520 ;; FIXME: how to name a single frame in XEmacs???
4521 (unless (featurep 'xemacs)
4522 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4524 ;;;; Structure editing
4526 ;;; Inserting headlines
4528 (defun org-insert-heading (&optional force-heading)
4529 "Insert a new heading or item with same depth at point.
4530 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4531 If point is at the beginning of a headline, insert a sibling before the
4532 current headline. If point is not at the beginning, do not split the line,
4533 but create the new hedline after the current line."
4534 (interactive "P")
4535 (if (= (buffer-size) 0)
4536 (insert "\n* ")
4537 (when (or force-heading (not (org-insert-item)))
4538 (let* ((head (save-excursion
4539 (condition-case nil
4540 (progn
4541 (org-back-to-heading)
4542 (match-string 0))
4543 (error "*"))))
4544 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4545 pos)
4546 (cond
4547 ((and (org-on-heading-p) (bolp)
4548 (or (bobp)
4549 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4550 ;; insert before the current line
4551 (open-line (if blank 2 1)))
4552 ((and (bolp)
4553 (or (bobp)
4554 (save-excursion
4555 (backward-char 1) (not (org-invisible-p)))))
4556 ;; insert right here
4557 nil)
4559 ;; in the middle of the line
4560 (org-show-entry)
4561 (let ((split
4562 (org-get-alist-option org-M-RET-may-split-line 'headline))
4563 tags pos)
4564 (if (org-on-heading-p)
4565 (progn
4566 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4567 (setq tags (and (match-end 2) (match-string 2)))
4568 (and (match-end 1)
4569 (delete-region (match-beginning 1) (match-end 1)))
4570 (setq pos (point-at-bol))
4571 (or split (end-of-line 1))
4572 (delete-horizontal-space)
4573 (newline (if blank 2 1))
4574 (when tags
4575 (save-excursion
4576 (goto-char pos)
4577 (end-of-line 1)
4578 (insert " " tags)
4579 (org-set-tags nil 'align))))
4580 (or split (end-of-line 1))
4581 (newline (if blank 2 1))))))
4582 (insert head) (just-one-space)
4583 (setq pos (point))
4584 (end-of-line 1)
4585 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4586 (run-hooks 'org-insert-heading-hook)))))
4588 (defun org-get-heading (&optional no-tags)
4589 "Return the heading of the current entry, without the stars."
4590 (save-excursion
4591 (org-back-to-heading t)
4592 (if (looking-at
4593 (if no-tags
4594 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4595 "\\*+[ \t]+\\([^\r\n]*\\)"))
4596 (match-string 1) "")))
4598 (defun org-insert-heading-after-current ()
4599 "Insert a new heading with same level as current, after current subtree."
4600 (interactive)
4601 (org-back-to-heading)
4602 (org-insert-heading)
4603 (org-move-subtree-down)
4604 (end-of-line 1))
4606 (defun org-insert-todo-heading (arg)
4607 "Insert a new heading with the same level and TODO state as current heading.
4608 If the heading has no TODO state, or if the state is DONE, use the first
4609 state (TODO by default). Also with prefix arg, force first state."
4610 (interactive "P")
4611 (when (not (org-insert-item 'checkbox))
4612 (org-insert-heading)
4613 (save-excursion
4614 (org-back-to-heading)
4615 (outline-previous-heading)
4616 (looking-at org-todo-line-regexp))
4617 (if (or arg
4618 (not (match-beginning 2))
4619 (member (match-string 2) org-done-keywords))
4620 (insert (car org-todo-keywords-1) " ")
4621 (insert (match-string 2) " "))
4622 (when org-provide-todo-statistics
4623 (org-update-parent-todo-statistics))))
4625 (defun org-insert-subheading (arg)
4626 "Insert a new subheading and demote it.
4627 Works for outline headings and for plain lists alike."
4628 (interactive "P")
4629 (org-insert-heading arg)
4630 (cond
4631 ((org-on-heading-p) (org-do-demote))
4632 ((org-at-item-p) (org-indent-item 1))))
4634 (defun org-insert-todo-subheading (arg)
4635 "Insert a new subheading with TODO keyword or checkbox and demote it.
4636 Works for outline headings and for plain lists alike."
4637 (interactive "P")
4638 (org-insert-todo-heading arg)
4639 (cond
4640 ((org-on-heading-p) (org-do-demote))
4641 ((org-at-item-p) (org-indent-item 1))))
4643 ;;; Promotion and Demotion
4645 (defun org-promote-subtree ()
4646 "Promote the entire subtree.
4647 See also `org-promote'."
4648 (interactive)
4649 (save-excursion
4650 (org-map-tree 'org-promote))
4651 (org-fix-position-after-promote))
4653 (defun org-demote-subtree ()
4654 "Demote the entire subtree. See `org-demote'.
4655 See also `org-promote'."
4656 (interactive)
4657 (save-excursion
4658 (org-map-tree 'org-demote))
4659 (org-fix-position-after-promote))
4662 (defun org-do-promote ()
4663 "Promote the current heading higher up the tree.
4664 If the region is active in `transient-mark-mode', promote all headings
4665 in the region."
4666 (interactive)
4667 (save-excursion
4668 (if (org-region-active-p)
4669 (org-map-region 'org-promote (region-beginning) (region-end))
4670 (org-promote)))
4671 (org-fix-position-after-promote))
4673 (defun org-do-demote ()
4674 "Demote the current heading lower down the tree.
4675 If the region is active in `transient-mark-mode', demote all headings
4676 in the region."
4677 (interactive)
4678 (save-excursion
4679 (if (org-region-active-p)
4680 (org-map-region 'org-demote (region-beginning) (region-end))
4681 (org-demote)))
4682 (org-fix-position-after-promote))
4684 (defun org-fix-position-after-promote ()
4685 "Make sure that after pro/demotion cursor position is right."
4686 (let ((pos (point)))
4687 (when (save-excursion
4688 (beginning-of-line 1)
4689 (looking-at org-todo-line-regexp)
4690 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4691 (cond ((eobp) (insert " "))
4692 ((eolp) (insert " "))
4693 ((equal (char-after) ?\ ) (forward-char 1))))))
4695 (defun org-reduced-level (l)
4696 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4698 (defun org-get-valid-level (level &optional change)
4699 "Rectify a level change under the influence of `org-odd-levels-only'
4700 LEVEL is a current level, CHANGE is by how much the level should be
4701 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4702 even level numbers will become the next higher odd number."
4703 (if org-odd-levels-only
4704 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4705 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4706 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4707 (max 1 (+ level change))))
4709 (if (boundp 'define-obsolete-function-alias)
4710 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4711 (define-obsolete-function-alias 'org-get-legal-level
4712 'org-get-valid-level)
4713 (define-obsolete-function-alias 'org-get-legal-level
4714 'org-get-valid-level "23.1")))
4716 (defun org-promote ()
4717 "Promote the current heading higher up the tree.
4718 If the region is active in `transient-mark-mode', promote all headings
4719 in the region."
4720 (org-back-to-heading t)
4721 (let* ((level (save-match-data (funcall outline-level)))
4722 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4723 (diff (abs (- level (length up-head) -1))))
4724 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4725 (replace-match up-head nil t)
4726 ;; Fixup tag positioning
4727 (and org-auto-align-tags (org-set-tags nil t))
4728 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4730 (defun org-demote ()
4731 "Demote the current heading lower down the tree.
4732 If the region is active in `transient-mark-mode', demote all headings
4733 in the region."
4734 (org-back-to-heading t)
4735 (let* ((level (save-match-data (funcall outline-level)))
4736 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4737 (diff (abs (- level (length down-head) -1))))
4738 (replace-match down-head nil t)
4739 ;; Fixup tag positioning
4740 (and org-auto-align-tags (org-set-tags nil t))
4741 (if org-adapt-indentation (org-fixup-indentation diff))))
4743 (defun org-map-tree (fun)
4744 "Call FUN for every heading underneath the current one."
4745 (org-back-to-heading)
4746 (let ((level (funcall outline-level)))
4747 (save-excursion
4748 (funcall fun)
4749 (while (and (progn
4750 (outline-next-heading)
4751 (> (funcall outline-level) level))
4752 (not (eobp)))
4753 (funcall fun)))))
4755 (defun org-map-region (fun beg end)
4756 "Call FUN for every heading between BEG and END."
4757 (let ((org-ignore-region t))
4758 (save-excursion
4759 (setq end (copy-marker end))
4760 (goto-char beg)
4761 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4762 (< (point) end))
4763 (funcall fun))
4764 (while (and (progn
4765 (outline-next-heading)
4766 (< (point) end))
4767 (not (eobp)))
4768 (funcall fun)))))
4770 (defun org-fixup-indentation (diff)
4771 "Change the indentation in the current entry by DIFF
4772 However, if any line in the current entry has no indentation, or if it
4773 would end up with no indentation after the change, nothing at all is done."
4774 (save-excursion
4775 (let ((end (save-excursion (outline-next-heading)
4776 (point-marker)))
4777 (prohibit (if (> diff 0)
4778 "^\\S-"
4779 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4780 col)
4781 (unless (save-excursion (end-of-line 1)
4782 (re-search-forward prohibit end t))
4783 (while (and (< (point) end)
4784 (re-search-forward "^[ \t]+" end t))
4785 (goto-char (match-end 0))
4786 (setq col (current-column))
4787 (if (< diff 0) (replace-match ""))
4788 (indent-to (+ diff col))))
4789 (move-marker end nil))))
4791 (defun org-convert-to-odd-levels ()
4792 "Convert an org-mode file with all levels allowed to one with odd levels.
4793 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4794 level 5 etc."
4795 (interactive)
4796 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4797 (let ((org-odd-levels-only nil) n)
4798 (save-excursion
4799 (goto-char (point-min))
4800 (while (re-search-forward "^\\*\\*+ " nil t)
4801 (setq n (- (length (match-string 0)) 2))
4802 (while (>= (setq n (1- n)) 0)
4803 (org-demote))
4804 (end-of-line 1))))))
4807 (defun org-convert-to-oddeven-levels ()
4808 "Convert an org-mode file with only odd levels to one with odd and even levels.
4809 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4810 section with an even level, conversion would destroy the structure of the file. An error
4811 is signaled in this case."
4812 (interactive)
4813 (goto-char (point-min))
4814 ;; First check if there are no even levels
4815 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4816 (org-show-context t)
4817 (error "Not all levels are odd in this file. Conversion not possible."))
4818 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4819 (let ((org-odd-levels-only nil) n)
4820 (save-excursion
4821 (goto-char (point-min))
4822 (while (re-search-forward "^\\*\\*+ " nil t)
4823 (setq n (/ (1- (length (match-string 0))) 2))
4824 (while (>= (setq n (1- n)) 0)
4825 (org-promote))
4826 (end-of-line 1))))))
4828 (defun org-tr-level (n)
4829 "Make N odd if required."
4830 (if org-odd-levels-only (1+ (/ n 2)) n))
4832 ;;; Vertical tree motion, cutting and pasting of subtrees
4834 (defun org-move-subtree-up (&optional arg)
4835 "Move the current subtree up past ARG headlines of the same level."
4836 (interactive "p")
4837 (org-move-subtree-down (- (prefix-numeric-value arg))))
4839 (defun org-move-subtree-down (&optional arg)
4840 "Move the current subtree down past ARG headlines of the same level."
4841 (interactive "p")
4842 (setq arg (prefix-numeric-value arg))
4843 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4844 'outline-get-last-sibling))
4845 (ins-point (make-marker))
4846 (cnt (abs arg))
4847 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4848 ;; Select the tree
4849 (org-back-to-heading)
4850 (setq beg0 (point))
4851 (save-excursion
4852 (setq ne-beg (org-back-over-empty-lines))
4853 (setq beg (point)))
4854 (save-match-data
4855 (save-excursion (outline-end-of-heading)
4856 (setq folded (org-invisible-p)))
4857 (outline-end-of-subtree))
4858 (outline-next-heading)
4859 (setq ne-end (org-back-over-empty-lines))
4860 (setq end (point))
4861 (goto-char beg0)
4862 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4863 ;; include less whitespace
4864 (save-excursion
4865 (goto-char beg)
4866 (forward-line (- ne-beg ne-end))
4867 (setq beg (point))))
4868 ;; Find insertion point, with error handling
4869 (while (> cnt 0)
4870 (or (and (funcall movfunc) (looking-at outline-regexp))
4871 (progn (goto-char beg0)
4872 (error "Cannot move past superior level or buffer limit")))
4873 (setq cnt (1- cnt)))
4874 (if (> arg 0)
4875 ;; Moving forward - still need to move over subtree
4876 (progn (org-end-of-subtree t t)
4877 (save-excursion
4878 (org-back-over-empty-lines)
4879 (or (bolp) (newline)))))
4880 (setq ne-ins (org-back-over-empty-lines))
4881 (move-marker ins-point (point))
4882 (setq txt (buffer-substring beg end))
4883 (org-save-markers-in-region beg end)
4884 (delete-region beg end)
4885 (outline-flag-region (1- beg) beg nil)
4886 (outline-flag-region (1- (point)) (point) nil)
4887 (let ((bbb (point)))
4888 (insert-before-markers txt)
4889 (org-reinstall-markers-in-region bbb)
4890 (move-marker ins-point bbb))
4891 (or (bolp) (insert "\n"))
4892 (setq ins-end (point))
4893 (goto-char ins-point)
4894 (org-skip-whitespace)
4895 (when (and (< arg 0)
4896 (org-first-sibling-p)
4897 (> ne-ins ne-beg))
4898 ;; Move whitespace back to beginning
4899 (save-excursion
4900 (goto-char ins-end)
4901 (let ((kill-whole-line t))
4902 (kill-line (- ne-ins ne-beg)) (point)))
4903 (insert (make-string (- ne-ins ne-beg) ?\n)))
4904 (move-marker ins-point nil)
4905 (org-compact-display-after-subtree-move)
4906 (org-show-empty-lines-in-parent)
4907 (unless folded
4908 (org-show-entry)
4909 (show-children)
4910 (org-cycle-hide-drawers 'children))))
4912 (defvar org-subtree-clip ""
4913 "Clipboard for cut and paste of subtrees.
4914 This is actually only a copy of the kill, because we use the normal kill
4915 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4917 (defvar org-subtree-clip-folded nil
4918 "Was the last copied subtree folded?
4919 This is used to fold the tree back after pasting.")
4921 (defun org-cut-subtree (&optional n)
4922 "Cut the current subtree into the clipboard.
4923 With prefix arg N, cut this many sequential subtrees.
4924 This is a short-hand for marking the subtree and then cutting it."
4925 (interactive "p")
4926 (org-copy-subtree n 'cut))
4928 (defun org-copy-subtree (&optional n cut force-store-markers)
4929 "Cut the current subtree into the clipboard.
4930 With prefix arg N, cut this many sequential subtrees.
4931 This is a short-hand for marking the subtree and then copying it.
4932 If CUT is non-nil, actually cut the subtree.
4933 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4934 of some markers in the region, even if CUT is non-nil. This is
4935 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4936 (interactive "p")
4937 (let (beg end folded (beg0 (point)))
4938 (if (interactive-p)
4939 (org-back-to-heading nil) ; take what looks like a subtree
4940 (org-back-to-heading t)) ; take what is really there
4941 (org-back-over-empty-lines)
4942 (setq beg (point))
4943 (skip-chars-forward " \t\r\n")
4944 (save-match-data
4945 (save-excursion (outline-end-of-heading)
4946 (setq folded (org-invisible-p)))
4947 (condition-case nil
4948 (outline-forward-same-level (1- n))
4949 (error nil))
4950 (org-end-of-subtree t t))
4951 (org-back-over-empty-lines)
4952 (setq end (point))
4953 (goto-char beg0)
4954 (when (> end beg)
4955 (setq org-subtree-clip-folded folded)
4956 (when (or cut force-store-markers)
4957 (org-save-markers-in-region beg end))
4958 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4959 (setq org-subtree-clip (current-kill 0))
4960 (message "%s: Subtree(s) with %d characters"
4961 (if cut "Cut" "Copied")
4962 (length org-subtree-clip)))))
4964 (defun org-paste-subtree (&optional level tree)
4965 "Paste the clipboard as a subtree, with modification of headline level.
4966 The entire subtree is promoted or demoted in order to match a new headline
4967 level. By default, the new level is derived from the visible headings
4968 before and after the insertion point, and taken to be the inferior headline
4969 level of the two. So if the previous visible heading is level 3 and the
4970 next is level 4 (or vice versa), level 4 will be used for insertion.
4971 This makes sure that the subtree remains an independent subtree and does
4972 not swallow low level entries.
4974 You can also force a different level, either by using a numeric prefix
4975 argument, or by inserting the heading marker by hand. For example, if the
4976 cursor is after \"*****\", then the tree will be shifted to level 5.
4978 If you want to insert the tree as is, just use \\[yank].
4980 If optional TREE is given, use this text instead of the kill ring."
4981 (interactive "P")
4982 (unless (org-kill-is-subtree-p tree)
4983 (error "%s"
4984 (substitute-command-keys
4985 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4986 (let* ((visp (not (org-invisible-p)))
4987 (txt (or tree (and kill-ring (current-kill 0))))
4988 (^re (concat "^\\(" outline-regexp "\\)"))
4989 (re (concat "\\(" outline-regexp "\\)"))
4990 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4992 (old-level (if (string-match ^re txt)
4993 (- (match-end 0) (match-beginning 0) 1)
4994 -1))
4995 (force-level (cond (level (prefix-numeric-value level))
4996 ((string-match
4997 ^re_ (buffer-substring (point-at-bol) (point)))
4998 (- (match-end 1) (match-beginning 1)))
4999 (t nil)))
5000 (previous-level (save-excursion
5001 (condition-case nil
5002 (progn
5003 (outline-previous-visible-heading 1)
5004 (if (looking-at re)
5005 (- (match-end 0) (match-beginning 0) 1)
5007 (error 1))))
5008 (next-level (save-excursion
5009 (condition-case nil
5010 (progn
5011 (or (looking-at outline-regexp)
5012 (outline-next-visible-heading 1))
5013 (if (looking-at re)
5014 (- (match-end 0) (match-beginning 0) 1)
5016 (error 1))))
5017 (new-level (or force-level (max previous-level next-level)))
5018 (shift (if (or (= old-level -1)
5019 (= new-level -1)
5020 (= old-level new-level))
5022 (- new-level old-level)))
5023 (delta (if (> shift 0) -1 1))
5024 (func (if (> shift 0) 'org-demote 'org-promote))
5025 (org-odd-levels-only nil)
5026 beg end)
5027 ;; Remove the forced level indicator
5028 (if force-level
5029 (delete-region (point-at-bol) (point)))
5030 ;; Paste
5031 (beginning-of-line 1)
5032 (org-back-over-empty-lines)
5033 (setq beg (point))
5034 (insert-before-markers txt)
5035 (unless (string-match "\n\\'" txt) (insert "\n"))
5036 (org-reinstall-markers-in-region beg)
5037 (setq end (point))
5038 (goto-char beg)
5039 (skip-chars-forward " \t\n\r")
5040 (setq beg (point))
5041 (if (and (org-invisible-p) visp)
5042 (save-excursion (outline-show-heading)))
5043 ;; Shift if necessary
5044 (unless (= shift 0)
5045 (save-restriction
5046 (narrow-to-region beg end)
5047 (while (not (= shift 0))
5048 (org-map-region func (point-min) (point-max))
5049 (setq shift (+ delta shift)))
5050 (goto-char (point-min))))
5051 (when (interactive-p)
5052 (message "Clipboard pasted as level %d subtree" new-level))
5053 (if (and kill-ring
5054 (eq org-subtree-clip (current-kill 0))
5055 org-subtree-clip-folded)
5056 ;; The tree was folded before it was killed/copied
5057 (hide-subtree))))
5059 (defun org-kill-is-subtree-p (&optional txt)
5060 "Check if the current kill is an outline subtree, or a set of trees.
5061 Returns nil if kill does not start with a headline, or if the first
5062 headline level is not the largest headline level in the tree.
5063 So this will actually accept several entries of equal levels as well,
5064 which is OK for `org-paste-subtree'.
5065 If optional TXT is given, check this string instead of the current kill."
5066 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5067 (start-level (and kill
5068 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5069 org-outline-regexp "\\)")
5070 kill)
5071 (- (match-end 2) (match-beginning 2) 1)))
5072 (re (concat "^" org-outline-regexp))
5073 (start (1+ (match-beginning 2))))
5074 (if (not start-level)
5075 (progn
5076 nil) ;; does not even start with a heading
5077 (catch 'exit
5078 (while (setq start (string-match re kill (1+ start)))
5079 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5080 (throw 'exit nil)))
5081 t))))
5083 (defvar org-markers-to-move nil
5084 "Markers that should be moved with a cut-and-paste operation.
5085 Those markers are stored together with their positions relative to
5086 the start of the region.")
5088 (defun org-save-markers-in-region (beg end)
5089 "Check markers in region.
5090 If these markers are between BEG and END, record their position relative
5091 to BEG, so that after moving the block of text, we can put the markers back
5092 into place.
5093 This function gets called just before an entry or tree gets cut from the
5094 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5095 called immediately, to move the markers with the entries."
5096 (setq org-markers-to-move nil)
5097 (when (featurep 'org-clock)
5098 (org-clock-save-markers-for-cut-and-paste beg end))
5099 (when (featurep 'org-agenda)
5100 (org-agenda-save-markers-for-cut-and-paste beg end)))
5102 (defun org-check-and-save-marker (marker beg end)
5103 "Check if MARKER is between BEG and END.
5104 If yes, remember the marker and the distance to BEG."
5105 (when (and (marker-buffer marker)
5106 (equal (marker-buffer marker) (current-buffer)))
5107 (if (and (>= marker beg) (< marker end))
5108 (push (cons marker (- marker beg)) org-markers-to-move))))
5110 (defun org-reinstall-markers-in-region (beg)
5111 "Move all remembered markers to their position relative to BEG."
5112 (mapc (lambda (x)
5113 (move-marker (car x) (+ beg (cdr x))))
5114 org-markers-to-move)
5115 (setq org-markers-to-move nil))
5117 (defun org-narrow-to-subtree ()
5118 "Narrow buffer to the current subtree."
5119 (interactive)
5120 (save-excursion
5121 (save-match-data
5122 (narrow-to-region
5123 (progn (org-back-to-heading) (point))
5124 (progn (org-end-of-subtree t) (point))))))
5127 ;;; Outline Sorting
5129 (defun org-sort (with-case)
5130 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5131 Optional argument WITH-CASE means sort case-sensitively."
5132 (interactive "P")
5133 (if (org-at-table-p)
5134 (org-call-with-arg 'org-table-sort-lines with-case)
5135 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5137 (defun org-sort-remove-invisible (s)
5138 (remove-text-properties 0 (length s) org-rm-props s)
5139 (while (string-match org-bracket-link-regexp s)
5140 (setq s (replace-match (if (match-end 2)
5141 (match-string 3 s)
5142 (match-string 1 s)) t t s)))
5145 (defvar org-priority-regexp) ; defined later in the file
5147 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5148 "Sort entries on a certain level of an outline tree.
5149 If there is an active region, the entries in the region are sorted.
5150 Else, if the cursor is before the first entry, sort the top-level items.
5151 Else, the children of the entry at point are sorted.
5153 Sorting can be alphabetically, numerically, and by date/time as given by
5154 the first time stamp in the entry. The command prompts for the sorting
5155 type unless it has been given to the function through the SORTING-TYPE
5156 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5157 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5158 called with point at the beginning of the record. It must return either
5159 a string or a number that should serve as the sorting key for that record.
5161 Comparing entries ignores case by default. However, with an optional argument
5162 WITH-CASE, the sorting considers case as well."
5163 (interactive "P")
5164 (let ((case-func (if with-case 'identity 'downcase))
5165 start beg end stars re re2
5166 txt what tmp plain-list-p)
5167 ;; Find beginning and end of region to sort
5168 (cond
5169 ((org-region-active-p)
5170 ;; we will sort the region
5171 (setq end (region-end)
5172 what "region")
5173 (goto-char (region-beginning))
5174 (if (not (org-on-heading-p)) (outline-next-heading))
5175 (setq start (point)))
5176 ((org-at-item-p)
5177 ;; we will sort this plain list
5178 (org-beginning-of-item-list) (setq start (point))
5179 (org-end-of-item-list) (setq end (point))
5180 (goto-char start)
5181 (setq plain-list-p t
5182 what "plain list"))
5183 ((or (org-on-heading-p)
5184 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5185 ;; we will sort the children of the current headline
5186 (org-back-to-heading)
5187 (setq start (point)
5188 end (progn (org-end-of-subtree t t)
5189 (org-back-over-empty-lines)
5190 (point))
5191 what "children")
5192 (goto-char start)
5193 (show-subtree)
5194 (outline-next-heading))
5196 ;; we will sort the top-level entries in this file
5197 (goto-char (point-min))
5198 (or (org-on-heading-p) (outline-next-heading))
5199 (setq start (point) end (point-max) what "top-level")
5200 (goto-char start)
5201 (show-all)))
5203 (setq beg (point))
5204 (if (>= beg end) (error "Nothing to sort"))
5206 (unless plain-list-p
5207 (looking-at "\\(\\*+\\)")
5208 (setq stars (match-string 1)
5209 re (concat "^" (regexp-quote stars) " +")
5210 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5211 txt (buffer-substring beg end))
5212 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5213 (if (and (not (equal stars "*")) (string-match re2 txt))
5214 (error "Region to sort contains a level above the first entry")))
5216 (unless sorting-type
5217 (message
5218 (if plain-list-p
5219 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5220 "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:")
5221 what)
5222 (setq sorting-type (read-char-exclusive))
5224 (and (= (downcase sorting-type) ?f)
5225 (setq getkey-func
5226 (completing-read "Sort using function: "
5227 obarray 'fboundp t nil nil))
5228 (setq getkey-func (intern getkey-func)))
5230 (and (= (downcase sorting-type) ?r)
5231 (setq property
5232 (completing-read "Property: "
5233 (mapcar 'list (org-buffer-property-keys t))
5234 nil t))))
5236 (message "Sorting entries...")
5238 (save-restriction
5239 (narrow-to-region start end)
5241 (let ((dcst (downcase sorting-type))
5242 (now (current-time)))
5243 (sort-subr
5244 (/= dcst sorting-type)
5245 ;; This function moves to the beginning character of the "record" to
5246 ;; be sorted.
5247 (if plain-list-p
5248 (lambda nil
5249 (if (org-at-item-p) t (goto-char (point-max))))
5250 (lambda nil
5251 (if (re-search-forward re nil t)
5252 (goto-char (match-beginning 0))
5253 (goto-char (point-max)))))
5254 ;; This function moves to the last character of the "record" being
5255 ;; sorted.
5256 (if plain-list-p
5257 'org-end-of-item
5258 (lambda nil
5259 (save-match-data
5260 (condition-case nil
5261 (outline-forward-same-level 1)
5262 (error
5263 (goto-char (point-max)))))))
5265 ;; This function returns the value that gets sorted against.
5266 (if plain-list-p
5267 (lambda nil
5268 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5269 (cond
5270 ((= dcst ?n)
5271 (string-to-number (buffer-substring (match-end 0)
5272 (point-at-eol))))
5273 ((= dcst ?a)
5274 (buffer-substring (match-end 0) (point-at-eol)))
5275 ((= dcst ?t)
5276 (if (re-search-forward org-ts-regexp
5277 (point-at-eol) t)
5278 (org-time-string-to-time (match-string 0))
5279 now))
5280 ((= dcst ?f)
5281 (if getkey-func
5282 (progn
5283 (setq tmp (funcall getkey-func))
5284 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5285 tmp)
5286 (error "Invalid key function `%s'" getkey-func)))
5287 (t (error "Invalid sorting type `%c'" sorting-type)))))
5288 (lambda nil
5289 (cond
5290 ((= dcst ?n)
5291 (if (looking-at outline-regexp)
5292 (string-to-number (buffer-substring (match-end 0)
5293 (point-at-eol)))
5294 nil))
5295 ((= dcst ?a)
5296 (funcall case-func (buffer-substring (point-at-bol)
5297 (point-at-eol))))
5298 ((= dcst ?t)
5299 (if (re-search-forward org-ts-regexp
5300 (save-excursion
5301 (forward-line 2)
5302 (point)) t)
5303 (org-time-string-to-time (match-string 0))
5304 now))
5305 ((= dcst ?p)
5306 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5307 (string-to-char (match-string 2))
5308 org-default-priority))
5309 ((= dcst ?r)
5310 (or (org-entry-get nil property) ""))
5311 ((= dcst ?o)
5312 (if (looking-at org-complex-heading-regexp)
5313 (- 9999 (length (member (match-string 2)
5314 org-todo-keywords-1)))))
5315 ((= dcst ?f)
5316 (if getkey-func
5317 (progn
5318 (setq tmp (funcall getkey-func))
5319 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5320 tmp)
5321 (error "Invalid key function `%s'" getkey-func)))
5322 (t (error "Invalid sorting type `%c'" sorting-type)))))
5324 (cond
5325 ((= dcst ?a) 'string<)
5326 ((= dcst ?t) 'time-less-p)
5327 (t nil)))))
5328 (message "Sorting entries...done")))
5330 (defun org-do-sort (table what &optional with-case sorting-type)
5331 "Sort TABLE of WHAT according to SORTING-TYPE.
5332 The user will be prompted for the SORTING-TYPE if the call to this
5333 function does not specify it. WHAT is only for the prompt, to indicate
5334 what is being sorted. The sorting key will be extracted from
5335 the car of the elements of the table.
5336 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5337 (unless sorting-type
5338 (message
5339 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5340 what)
5341 (setq sorting-type (read-char-exclusive)))
5342 (let ((dcst (downcase sorting-type))
5343 extractfun comparefun)
5344 ;; Define the appropriate functions
5345 (cond
5346 ((= dcst ?n)
5347 (setq extractfun 'string-to-number
5348 comparefun (if (= dcst sorting-type) '< '>)))
5349 ((= dcst ?a)
5350 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5351 (lambda(x) (downcase (org-sort-remove-invisible x))))
5352 comparefun (if (= dcst sorting-type)
5353 'string<
5354 (lambda (a b) (and (not (string< a b))
5355 (not (string= a b)))))))
5356 ((= dcst ?t)
5357 (setq extractfun
5358 (lambda (x)
5359 (if (string-match org-ts-regexp x)
5360 (time-to-seconds
5361 (org-time-string-to-time (match-string 0 x)))
5363 comparefun (if (= dcst sorting-type) '< '>)))
5364 (t (error "Invalid sorting type `%c'" sorting-type)))
5366 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5367 table)
5368 (lambda (a b) (funcall comparefun (car a) (car b))))))
5370 ;;; Editing source examples
5372 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5373 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5374 (defvar org-edit-src-force-single-line nil)
5375 (defvar org-edit-src-from-org-mode nil)
5377 (define-minor-mode org-exit-edit-mode
5378 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5380 (defun org-edit-src-code ()
5381 "Edit the source code example at point.
5382 An indirect buffer is created, and that buffer is then narrowed to the
5383 example at point and switched to the correct language mode. When done,
5384 exit by killing the buffer with \\[org-edit-src-exit]."
5385 (interactive)
5386 (let ((line (org-current-line))
5387 (case-fold-search t)
5388 (msg (substitute-command-keys
5389 "Edit, then exit with C-c ' (C-c and single quote)"))
5390 (info (org-edit-src-find-region-and-lang))
5391 (org-mode-p (eq major-mode 'org-mode))
5392 beg end lang lang-f single)
5393 (if (not info)
5395 (setq beg (nth 0 info)
5396 end (nth 1 info)
5397 lang (nth 2 info)
5398 single (nth 3 info)
5399 lang-f (intern (concat lang "-mode")))
5400 (unless (functionp lang-f)
5401 (error "No such language mode: %s" lang-f))
5402 (goto-line line)
5403 (if (get-buffer "*Org Edit Src Example*")
5404 (kill-buffer "*Org Edit Src Example*"))
5405 (switch-to-buffer (make-indirect-buffer (current-buffer)
5406 "*Org Edit Src Example*"))
5407 (narrow-to-region beg end)
5408 (remove-text-properties beg end '(display nil invisible nil
5409 intangible nil))
5410 (let ((org-inhibit-startup t))
5411 (funcall lang-f))
5412 (set (make-local-variable 'org-edit-src-force-single-line) single)
5413 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5414 (when org-mode-p
5415 (goto-char (point-min))
5416 (while (re-search-forward "^," nil t)
5417 (replace-match "")))
5418 (goto-line line)
5419 (org-exit-edit-mode)
5420 (org-set-local 'header-line-format msg)
5421 (message "%s" msg)
5422 t)))
5424 (defun org-edit-src-find-region-and-lang ()
5425 "Find the region and language for a local edit.
5426 Return a list with beginning and end of the region, a string representing
5427 the language, a switch telling of the content should be in a single line."
5428 (let ((re-list
5430 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5431 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5432 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5433 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5434 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5435 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5436 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5437 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5438 ("^#\\+begin_example.*\n" "^#\\+end_example" "fundamental")
5439 ("^#\\+html:" "\n" "html" single-line)
5440 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5441 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5442 ("^#\\+latex:" "\n" "latex" single-line)
5443 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5444 ("^#\\+ascii:" "\n" "ascii" single-line)
5446 (pos (point))
5447 re re1 re2 single beg end lang)
5448 (catch 'exit
5449 (while (setq entry (pop re-list))
5450 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5451 single (nth 3 entry))
5452 (save-excursion
5453 (if (or (looking-at re1)
5454 (re-search-backward re1 nil t))
5455 (progn
5456 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5457 (if (and (re-search-forward re2 nil t)
5458 (>= (match-end 0) pos))
5459 (throw 'exit (list beg (match-beginning 0) lang single))))
5460 (if (or (looking-at re2)
5461 (re-search-forward re2 nil t))
5462 (progn
5463 (setq end (match-beginning 0))
5464 (if (and (re-search-backward re1 nil t)
5465 (<= (match-beginning 0) pos))
5466 (throw 'exit
5467 (list (match-end 0) end
5468 (org-edit-src-get-lang lang) single)))))))))))
5470 (defun org-edit-src-get-lang (lang)
5471 "Extract the src language."
5472 (let ((m (match-string 0)))
5473 (cond
5474 ((stringp lang) lang)
5475 ((integerp lang) (match-string lang))
5476 ((and (eq lang lang)
5477 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5478 (match-string 1 m))
5479 ((and (eq lang lang)
5480 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5481 (match-string 1 m))
5482 (t "fundamental"))))
5484 (defun org-edit-src-exit ()
5485 "Exit special edit and protect problematic lines."
5486 (interactive)
5487 (unless (buffer-base-buffer (current-buffer))
5488 (error "This is not an indirect buffer, something is wrong..."))
5489 (unless (> (point-min) 1)
5490 (error "This buffer is not narrowed, something is wrong..."))
5491 (goto-char (point-min))
5492 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5493 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5494 (when (org-bound-and-true-p org-edit-src-force-single-line)
5495 (goto-char (point-min))
5496 (while (re-search-forward "\n" nil t)
5497 (replace-match " "))
5498 (goto-char (point-min))
5499 (if (looking-at "\\s-*") (replace-match " "))
5500 (if (re-search-forward "\\s-+\\'" nil t)
5501 (replace-match "")))
5502 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5503 (goto-char (point-min))
5504 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5505 (replace-match ",\\1"))
5506 (when font-lock-mode
5507 (font-lock-unfontify-region (point-min) (point-max)))
5508 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5509 (kill-buffer (current-buffer)))
5511 ;;;; Plain list items, including checkboxes
5513 ;;; Plain list items
5515 (defun org-at-item-p ()
5516 "Is point in a line starting a hand-formatted item?"
5517 (let ((llt org-plain-list-ordered-item-terminator))
5518 (save-excursion
5519 (goto-char (point-at-bol))
5520 (looking-at
5521 (cond
5522 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5523 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5524 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5525 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5527 (defun org-in-item-p ()
5528 "It the cursor inside a plain list item.
5529 Does not have to be the first line."
5530 (save-excursion
5531 (condition-case nil
5532 (progn
5533 (org-beginning-of-item)
5534 (org-at-item-p)
5536 (error nil))))
5538 (defun org-insert-item (&optional checkbox)
5539 "Insert a new item at the current level.
5540 Return t when things worked, nil when we are not in an item."
5541 (when (save-excursion
5542 (condition-case nil
5543 (progn
5544 (org-beginning-of-item)
5545 (org-at-item-p)
5546 (if (org-invisible-p) (error "Invisible item"))
5548 (error nil)))
5549 (let* ((bul (match-string 0))
5550 (descp (save-excursion (goto-char (match-beginning 0))
5551 (beginning-of-line 1)
5552 (save-match-data
5553 (looking-at "[ \t]*.*? ::"))))
5554 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5555 (match-end 0)))
5556 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5557 pos)
5558 (if descp (setq checkbox nil))
5559 (cond
5560 ((and (org-at-item-p) (<= (point) eow))
5561 ;; before the bullet
5562 (beginning-of-line 1)
5563 (open-line (if blank 2 1)))
5564 ((<= (point) eow)
5565 (beginning-of-line 1))
5567 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5568 (end-of-line 1)
5569 (delete-horizontal-space))
5570 (newline (if blank 2 1))))
5571 (insert bul
5572 (if checkbox "[ ]" "")
5573 (if descp (concat (if checkbox " " "")
5574 (read-string "Term: ") " :: ") ""))
5575 (just-one-space)
5576 (setq pos (point))
5577 (end-of-line 1)
5578 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5579 (org-maybe-renumber-ordered-list)
5580 (and checkbox (org-update-checkbox-count-maybe))
5583 ;;; Checkboxes
5585 (defun org-at-item-checkbox-p ()
5586 "Is point at a line starting a plain-list item with a checklet?"
5587 (and (org-at-item-p)
5588 (save-excursion
5589 (goto-char (match-end 0))
5590 (skip-chars-forward " \t")
5591 (looking-at "\\[[- X]\\]"))))
5593 (defun org-toggle-checkbox (&optional arg)
5594 "Toggle the checkbox in the current line."
5595 (interactive "P")
5596 (catch 'exit
5597 (let (beg end status (firstnew 'unknown))
5598 (cond
5599 ((org-region-active-p)
5600 (setq beg (region-beginning) end (region-end)))
5601 ((org-on-heading-p)
5602 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5603 ((org-at-item-checkbox-p)
5604 (let ((pos (point)))
5605 (replace-match
5606 (cond (arg "[-]")
5607 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5608 (t "[ ]"))
5609 t t)
5610 (goto-char pos))
5611 (throw 'exit t))
5612 (t (error "Not at a checkbox or heading, and no active region")))
5613 (save-excursion
5614 (goto-char beg)
5615 (while (< (point) end)
5616 (when (org-at-item-checkbox-p)
5617 (setq status (equal (match-string 0) "[X]"))
5618 (when (eq firstnew 'unknown)
5619 (setq firstnew (not status)))
5620 (replace-match
5621 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5622 (beginning-of-line 2)))))
5623 (org-update-checkbox-count-maybe))
5625 (defun org-update-checkbox-count-maybe ()
5626 "Update checkbox statistics unless turned off by user."
5627 (when org-provide-checkbox-statistics
5628 (org-update-checkbox-count)))
5630 (defun org-update-checkbox-count (&optional all)
5631 "Update the checkbox statistics in the current section.
5632 This will find all statistic cookies like [57%] and [6/12] and update them
5633 with the current numbers. With optional prefix argument ALL, do this for
5634 the whole buffer."
5635 (interactive "P")
5636 (save-excursion
5637 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5638 (beg (condition-case nil
5639 (progn (outline-back-to-heading) (point))
5640 (error (point-min))))
5641 (end (move-marker (make-marker)
5642 (progn (outline-next-heading) (point))))
5643 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5644 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5645 (re-find (concat re "\\|" re-box))
5646 beg-cookie end-cookie is-percent c-on c-off lim
5647 eline curr-ind next-ind continue-from startsearch
5648 (cstat 0)
5650 (when all
5651 (goto-char (point-min))
5652 (outline-next-heading)
5653 (setq beg (point) end (point-max)))
5654 (goto-char end)
5655 ;; find each statistic cookie
5656 (while (re-search-backward re-find beg t)
5657 (setq beg-cookie (match-beginning 1)
5658 end-cookie (match-end 1)
5659 cstat (+ cstat (if end-cookie 1 0))
5660 startsearch (point-at-eol)
5661 continue-from (point-at-bol)
5662 is-percent (match-beginning 2)
5663 lim (cond
5664 ((org-on-heading-p) (outline-next-heading) (point))
5665 ((org-at-item-p) (org-end-of-item) (point))
5666 (t nil))
5667 c-on 0
5668 c-off 0)
5669 (when lim
5670 ;; find first checkbox for this cookie and gather
5671 ;; statistics from all that are at this indentation level
5672 (goto-char startsearch)
5673 (if (re-search-forward re-box lim t)
5674 (progn
5675 (org-beginning-of-item)
5676 (setq curr-ind (org-get-indentation))
5677 (setq next-ind curr-ind)
5678 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5679 (save-excursion (end-of-line) (setq eline (point)))
5680 (if (re-search-forward re-box eline t)
5681 (if (member (match-string 2) '("[ ]" "[-]"))
5682 (setq c-off (1+ c-off))
5683 (setq c-on (1+ c-on))
5686 (org-end-of-item)
5687 (setq next-ind (org-get-indentation))
5689 (goto-char continue-from)
5690 ;; update cookie
5691 (when end-cookie
5692 (delete-region beg-cookie end-cookie)
5693 (goto-char beg-cookie)
5694 (insert
5695 (if is-percent
5696 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5697 (format "[%d/%d]" c-on (+ c-on c-off)))))
5698 ;; update items checkbox if it has one
5699 (when (org-at-item-p)
5700 (org-beginning-of-item)
5701 (when (and (> (+ c-on c-off) 0)
5702 (re-search-forward re-box (point-at-eol) t))
5703 (setq beg-cookie (match-beginning 2)
5704 end-cookie (match-end 2))
5705 (delete-region beg-cookie end-cookie)
5706 (goto-char beg-cookie)
5707 (cond ((= c-off 0) (insert "[X]"))
5708 ((= c-on 0) (insert "[ ]"))
5709 (t (insert "[-]")))
5711 (goto-char continue-from))
5712 (when (interactive-p)
5713 (message "Checkbox satistics updated %s (%d places)"
5714 (if all "in entire file" "in current outline entry") cstat)))))
5716 (defun org-get-checkbox-statistics-face ()
5717 "Select the face for checkbox statistics.
5718 The face will be `org-done' when all relevant boxes are checked. Otherwise
5719 it will be `org-todo'."
5720 (if (match-end 1)
5721 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5722 (if (and (> (match-end 2) (match-beginning 2))
5723 (equal (match-string 2) (match-string 3)))
5724 'org-done
5725 'org-todo)))
5727 (defun org-get-indentation (&optional line)
5728 "Get the indentation of the current line, interpreting tabs.
5729 When LINE is given, assume it represents a line and compute its indentation."
5730 (if line
5731 (if (string-match "^ *" (org-remove-tabs line))
5732 (match-end 0))
5733 (save-excursion
5734 (beginning-of-line 1)
5735 (skip-chars-forward " \t")
5736 (current-column))))
5738 (defun org-remove-tabs (s &optional width)
5739 "Replace tabulators in S with spaces.
5740 Assumes that s is a single line, starting in column 0."
5741 (setq width (or width tab-width))
5742 (while (string-match "\t" s)
5743 (setq s (replace-match
5744 (make-string
5745 (- (* width (/ (+ (match-beginning 0) width) width))
5746 (match-beginning 0)) ?\ )
5747 t t s)))
5750 (defun org-fix-indentation (line ind)
5751 "Fix indentation in LINE.
5752 IND is a cons cell with target and minimum indentation.
5753 If the current indenation in LINE is smaller than the minimum,
5754 leave it alone. If it is larger than ind, set it to the target."
5755 (let* ((l (org-remove-tabs line))
5756 (i (org-get-indentation l))
5757 (i1 (car ind)) (i2 (cdr ind)))
5758 (if (>= i i2) (setq l (substring line i2)))
5759 (if (> i1 0)
5760 (concat (make-string i1 ?\ ) l)
5761 l)))
5763 (defun org-beginning-of-item ()
5764 "Go to the beginning of the current hand-formatted item.
5765 If the cursor is not in an item, throw an error."
5766 (interactive)
5767 (let ((pos (point))
5768 (limit (save-excursion
5769 (condition-case nil
5770 (progn
5771 (org-back-to-heading)
5772 (beginning-of-line 2) (point))
5773 (error (point-min)))))
5774 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5775 ind ind1)
5776 (if (org-at-item-p)
5777 (beginning-of-line 1)
5778 (beginning-of-line 1)
5779 (skip-chars-forward " \t")
5780 (setq ind (current-column))
5781 (if (catch 'exit
5782 (while t
5783 (beginning-of-line 0)
5784 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5786 (if (looking-at "[ \t]*$")
5787 (setq ind1 ind-empty)
5788 (skip-chars-forward " \t")
5789 (setq ind1 (current-column)))
5790 (if (< ind1 ind)
5791 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5793 (goto-char pos)
5794 (error "Not in an item")))))
5796 (defun org-end-of-item ()
5797 "Go to the end of the current hand-formatted item.
5798 If the cursor is not in an item, throw an error."
5799 (interactive)
5800 (let* ((pos (point))
5801 ind1
5802 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5803 (limit (save-excursion (outline-next-heading) (point)))
5804 (ind (save-excursion
5805 (org-beginning-of-item)
5806 (skip-chars-forward " \t")
5807 (current-column)))
5808 (end (catch 'exit
5809 (while t
5810 (beginning-of-line 2)
5811 (if (eobp) (throw 'exit (point)))
5812 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5813 (if (looking-at "[ \t]*$")
5814 (setq ind1 ind-empty)
5815 (skip-chars-forward " \t")
5816 (setq ind1 (current-column)))
5817 (if (<= ind1 ind)
5818 (throw 'exit (point-at-bol)))))))
5819 (if end
5820 (goto-char end)
5821 (goto-char pos)
5822 (error "Not in an item"))))
5824 (defun org-next-item ()
5825 "Move to the beginning of the next item in the current plain list.
5826 Error if not at a plain list, or if this is the last item in the list."
5827 (interactive)
5828 (let (ind ind1 (pos (point)))
5829 (org-beginning-of-item)
5830 (setq ind (org-get-indentation))
5831 (org-end-of-item)
5832 (setq ind1 (org-get-indentation))
5833 (unless (and (org-at-item-p) (= ind ind1))
5834 (goto-char pos)
5835 (error "On last item"))))
5837 (defun org-previous-item ()
5838 "Move to the beginning of the previous item in the current plain list.
5839 Error if not at a plain list, or if this is the first item in the list."
5840 (interactive)
5841 (let (beg ind ind1 (pos (point)))
5842 (org-beginning-of-item)
5843 (setq beg (point))
5844 (setq ind (org-get-indentation))
5845 (goto-char beg)
5846 (catch 'exit
5847 (while t
5848 (beginning-of-line 0)
5849 (if (looking-at "[ \t]*$")
5851 (if (<= (setq ind1 (org-get-indentation)) ind)
5852 (throw 'exit t)))))
5853 (condition-case nil
5854 (if (or (not (org-at-item-p))
5855 (< ind1 (1- ind)))
5856 (error "")
5857 (org-beginning-of-item))
5858 (error (goto-char pos)
5859 (error "On first item")))))
5861 (defun org-first-list-item-p ()
5862 "Is this heading the item in a plain list?"
5863 (unless (org-at-item-p)
5864 (error "Not at a plain list item"))
5865 (org-beginning-of-item)
5866 (= (point) (save-excursion (org-beginning-of-item-list))))
5868 (defun org-move-item-down ()
5869 "Move the plain list item at point down, i.e. swap with following item.
5870 Subitems (items with larger indentation) are considered part of the item,
5871 so this really moves item trees."
5872 (interactive)
5873 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5874 (org-beginning-of-item)
5875 (setq beg0 (point))
5876 (save-excursion
5877 (setq ne-beg (org-back-over-empty-lines))
5878 (setq beg (point)))
5879 (goto-char beg0)
5880 (setq ind (org-get-indentation))
5881 (org-end-of-item)
5882 (setq end0 (point))
5883 (setq ind1 (org-get-indentation))
5884 (setq ne-end (org-back-over-empty-lines))
5885 (setq end (point))
5886 (goto-char beg0)
5887 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5888 ;; include less whitespace
5889 (save-excursion
5890 (goto-char beg)
5891 (forward-line (- ne-beg ne-end))
5892 (setq beg (point))))
5893 (goto-char end0)
5894 (if (and (org-at-item-p) (= ind ind1))
5895 (progn
5896 (org-end-of-item)
5897 (org-back-over-empty-lines)
5898 (setq txt (buffer-substring beg end))
5899 (save-excursion
5900 (delete-region beg end))
5901 (setq pos (point))
5902 (insert txt)
5903 (goto-char pos) (org-skip-whitespace)
5904 (org-maybe-renumber-ordered-list))
5905 (goto-char pos)
5906 (error "Cannot move this item further down"))))
5908 (defun org-move-item-up (arg)
5909 "Move the plain list item at point up, i.e. swap with previous item.
5910 Subitems (items with larger indentation) are considered part of the item,
5911 so this really moves item trees."
5912 (interactive "p")
5913 (let (beg beg0 end ind ind1 (pos (point)) txt
5914 ne-beg ne-ins ins-end)
5915 (org-beginning-of-item)
5916 (setq beg0 (point))
5917 (setq ind (org-get-indentation))
5918 (save-excursion
5919 (setq ne-beg (org-back-over-empty-lines))
5920 (setq beg (point)))
5921 (goto-char beg0)
5922 (org-end-of-item)
5923 (org-back-over-empty-lines)
5924 (setq end (point))
5925 (goto-char beg0)
5926 (catch 'exit
5927 (while t
5928 (beginning-of-line 0)
5929 (if (looking-at "[ \t]*$")
5930 (if org-empty-line-terminates-plain-lists
5931 (progn
5932 (goto-char pos)
5933 (error "Cannot move this item further up"))
5934 nil)
5935 (if (<= (setq ind1 (org-get-indentation)) ind)
5936 (throw 'exit t)))))
5937 (condition-case nil
5938 (org-beginning-of-item)
5939 (error (goto-char beg0)
5940 (error "Cannot move this item further up")))
5941 (setq ind1 (org-get-indentation))
5942 (if (and (org-at-item-p) (= ind ind1))
5943 (progn
5944 (setq ne-ins (org-back-over-empty-lines))
5945 (setq txt (buffer-substring beg end))
5946 (save-excursion
5947 (delete-region beg end))
5948 (setq pos (point))
5949 (insert txt)
5950 (setq ins-end (point))
5951 (goto-char pos) (org-skip-whitespace)
5953 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5954 ;; Move whitespace back to beginning
5955 (save-excursion
5956 (goto-char ins-end)
5957 (let ((kill-whole-line t))
5958 (kill-line (- ne-ins ne-beg)) (point)))
5959 (insert (make-string (- ne-ins ne-beg) ?\n)))
5961 (org-maybe-renumber-ordered-list))
5962 (goto-char pos)
5963 (error "Cannot move this item further up"))))
5965 (defun org-maybe-renumber-ordered-list ()
5966 "Renumber the ordered list at point if setup allows it.
5967 This tests the user option `org-auto-renumber-ordered-lists' before
5968 doing the renumbering."
5969 (interactive)
5970 (when (and org-auto-renumber-ordered-lists
5971 (org-at-item-p))
5972 (if (match-beginning 3)
5973 (org-renumber-ordered-list 1)
5974 (org-fix-bullet-type))))
5976 (defun org-maybe-renumber-ordered-list-safe ()
5977 (condition-case nil
5978 (save-excursion
5979 (org-maybe-renumber-ordered-list))
5980 (error nil)))
5982 (defun org-cycle-list-bullet (&optional which)
5983 "Cycle through the different itemize/enumerate bullets.
5984 This cycle the entire list level through the sequence:
5986 `-' -> `+' -> `*' -> `1.' -> `1)'
5988 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5989 0 meand `-', 1 means `+' etc."
5990 (interactive "P")
5991 (org-preserve-lc
5992 (org-beginning-of-item-list)
5993 (org-at-item-p)
5994 (beginning-of-line 1)
5995 (let ((current (match-string 0))
5996 (prevp (eq which 'previous))
5997 new)
5998 (setq new (cond
5999 ((and (numberp which)
6000 (nth (1- which) '("-" "+" "*" "1." "1)"))))
6001 ((string-match "-" current) (if prevp "1)" "+"))
6002 ((string-match "\\+" current)
6003 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
6004 ((string-match "\\*" current) (if prevp "+" "1."))
6005 ((string-match "\\." current) (if prevp "*" "1)"))
6006 ((string-match ")" current) (if prevp "1." "-"))
6007 (t (error "This should not happen"))))
6008 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6009 (org-fix-bullet-type)
6010 (org-maybe-renumber-ordered-list))))
6012 (defun org-get-string-indentation (s)
6013 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6014 (let ((n -1) (i 0) (w tab-width) c)
6015 (catch 'exit
6016 (while (< (setq n (1+ n)) (length s))
6017 (setq c (aref s n))
6018 (cond ((= c ?\ ) (setq i (1+ i)))
6019 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6020 (t (throw 'exit t)))))
6023 (defun org-renumber-ordered-list (arg)
6024 "Renumber an ordered plain list.
6025 Cursor needs to be in the first line of an item, the line that starts
6026 with something like \"1.\" or \"2)\"."
6027 (interactive "p")
6028 (unless (and (org-at-item-p)
6029 (match-beginning 3))
6030 (error "This is not an ordered list"))
6031 (let ((line (org-current-line))
6032 (col (current-column))
6033 (ind (org-get-string-indentation
6034 (buffer-substring (point-at-bol) (match-beginning 3))))
6035 ;; (term (substring (match-string 3) -1))
6036 ind1 (n (1- arg))
6037 fmt bob)
6038 ;; find where this list begins
6039 (org-beginning-of-item-list)
6040 (setq bobp (bobp))
6041 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6042 (setq fmt (concat "%d" (match-string 1)))
6043 (beginning-of-line 0)
6044 ;; walk forward and replace these numbers
6045 (catch 'exit
6046 (while t
6047 (catch 'next
6048 (if bobp (setq bobp nil) (beginning-of-line 2))
6049 (if (eobp) (throw 'exit nil))
6050 (if (looking-at "[ \t]*$") (throw 'next nil))
6051 (skip-chars-forward " \t") (setq ind1 (current-column))
6052 (if (> ind1 ind) (throw 'next t))
6053 (if (< ind1 ind) (throw 'exit t))
6054 (if (not (org-at-item-p)) (throw 'exit nil))
6055 (delete-region (match-beginning 2) (match-end 2))
6056 (goto-char (match-beginning 2))
6057 (insert (format fmt (setq n (1+ n)))))))
6058 (goto-line line)
6059 (org-move-to-column col)))
6061 (defun org-fix-bullet-type ()
6062 "Make sure all items in this list have the same bullet as the firsst item."
6063 (interactive)
6064 (unless (org-at-item-p) (error "This is not a list"))
6065 (let ((line (org-current-line))
6066 (col (current-column))
6067 (ind (current-indentation))
6068 ind1 bullet)
6069 ;; find where this list begins
6070 (org-beginning-of-item-list)
6071 (beginning-of-line 1)
6072 ;; find out what the bullet type is
6073 (looking-at "[ \t]*\\(\\S-+\\)")
6074 (setq bullet (match-string 1))
6075 ;; walk forward and replace these numbers
6076 (beginning-of-line 0)
6077 (catch 'exit
6078 (while t
6079 (catch 'next
6080 (beginning-of-line 2)
6081 (if (eobp) (throw 'exit nil))
6082 (if (looking-at "[ \t]*$") (throw 'next nil))
6083 (skip-chars-forward " \t") (setq ind1 (current-column))
6084 (if (> ind1 ind) (throw 'next t))
6085 (if (< ind1 ind) (throw 'exit t))
6086 (if (not (org-at-item-p)) (throw 'exit nil))
6087 (skip-chars-forward " \t")
6088 (looking-at "\\S-+")
6089 (replace-match bullet))))
6090 (goto-line line)
6091 (org-move-to-column col)
6092 (if (string-match "[0-9]" bullet)
6093 (org-renumber-ordered-list 1))))
6095 (defun org-beginning-of-item-list ()
6096 "Go to the beginning of the current item list.
6097 I.e. to the first item in this list."
6098 (interactive)
6099 (org-beginning-of-item)
6100 (let ((pos (point-at-bol))
6101 (ind (org-get-indentation))
6102 ind1)
6103 ;; find where this list begins
6104 (catch 'exit
6105 (while t
6106 (catch 'next
6107 (beginning-of-line 0)
6108 (if (looking-at "[ \t]*$")
6109 (throw (if (bobp) 'exit 'next) t))
6110 (skip-chars-forward " \t") (setq ind1 (current-column))
6111 (if (or (< ind1 ind)
6112 (and (= ind1 ind)
6113 (not (org-at-item-p)))
6114 (and (= (point-at-bol) (point-min))
6115 (setq pos (point-min))))
6116 (throw 'exit t)
6117 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6118 (goto-char pos)))
6121 (defun org-end-of-item-list ()
6122 "Go to the end of the current item list.
6123 I.e. to the text after the last item."
6124 (interactive)
6125 (org-beginning-of-item)
6126 (let ((pos (point-at-bol))
6127 (ind (org-get-indentation))
6128 ind1)
6129 ;; find where this list begins
6130 (catch 'exit
6131 (while t
6132 (catch 'next
6133 (beginning-of-line 2)
6134 (if (looking-at "[ \t]*$")
6135 (throw (if (eobp) 'exit 'next) t))
6136 (skip-chars-forward " \t") (setq ind1 (current-column))
6137 (if (or (< ind1 ind)
6138 (and (= ind1 ind)
6139 (not (org-at-item-p)))
6140 (eobp))
6141 (progn
6142 (setq pos (point-at-bol))
6143 (throw 'exit t))))))
6144 (goto-char pos)))
6147 (defvar org-last-indent-begin-marker (make-marker))
6148 (defvar org-last-indent-end-marker (make-marker))
6150 (defun org-outdent-item (arg)
6151 "Outdent a local list item."
6152 (interactive "p")
6153 (org-indent-item (- arg)))
6155 (defun org-indent-item (arg)
6156 "Indent a local list item."
6157 (interactive "p")
6158 (unless (org-at-item-p)
6159 (error "Not on an item"))
6160 (save-excursion
6161 (let (beg end ind ind1 tmp delta ind-down ind-up)
6162 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6163 (setq beg org-last-indent-begin-marker
6164 end org-last-indent-end-marker)
6165 (org-beginning-of-item)
6166 (setq beg (move-marker org-last-indent-begin-marker (point)))
6167 (org-end-of-item)
6168 (setq end (move-marker org-last-indent-end-marker (point))))
6169 (goto-char beg)
6170 (setq tmp (org-item-indent-positions)
6171 ind (car tmp)
6172 ind-down (nth 2 tmp)
6173 ind-up (nth 1 tmp)
6174 delta (if (> arg 0)
6175 (if ind-down (- ind-down ind) 2)
6176 (if ind-up (- ind-up ind) -2)))
6177 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6178 (while (< (point) end)
6179 (beginning-of-line 1)
6180 (skip-chars-forward " \t") (setq ind1 (current-column))
6181 (delete-region (point-at-bol) (point))
6182 (or (eolp) (org-indent-to-column (+ ind1 delta)))
6183 (beginning-of-line 2))))
6184 (org-fix-bullet-type)
6185 (org-maybe-renumber-ordered-list-safe)
6186 (save-excursion
6187 (beginning-of-line 0)
6188 (condition-case nil (org-beginning-of-item) (error nil))
6189 (org-maybe-renumber-ordered-list-safe)))
6191 (defun org-item-indent-positions ()
6192 "Return indentation for plain list items.
6193 This returns a list with three values: The current indentation, the
6194 parent indentation and the indentation a child should habe.
6195 Assumes cursor in item line."
6196 (let* ((bolpos (point-at-bol))
6197 (ind (org-get-indentation))
6198 ind-down ind-up pos)
6199 (save-excursion
6200 (org-beginning-of-item-list)
6201 (skip-chars-backward "\n\r \t")
6202 (when (org-in-item-p)
6203 (org-beginning-of-item)
6204 (setq ind-up (org-get-indentation))))
6205 (setq pos (point))
6206 (save-excursion
6207 (cond
6208 ((and (condition-case nil (progn (org-previous-item) t)
6209 (error nil))
6210 (or (forward-char 1) t)
6211 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6212 (setq ind-down (org-get-indentation)))
6213 ((and (goto-char pos)
6214 (org-at-item-p))
6215 (goto-char (match-end 0))
6216 (skip-chars-forward " \t")
6217 (setq ind-down (current-column)))))
6218 (list ind ind-up ind-down)))
6220 ;;; The orgstruct minor mode
6222 ;; Define a minor mode which can be used in other modes in order to
6223 ;; integrate the org-mode structure editing commands.
6225 ;; This is really a hack, because the org-mode structure commands use
6226 ;; keys which normally belong to the major mode. Here is how it
6227 ;; works: The minor mode defines all the keys necessary to operate the
6228 ;; structure commands, but wraps the commands into a function which
6229 ;; tests if the cursor is currently at a headline or a plain list
6230 ;; item. If that is the case, the structure command is used,
6231 ;; temporarily setting many Org-mode variables like regular
6232 ;; expressions for filling etc. However, when any of those keys is
6233 ;; used at a different location, function uses `key-binding' to look
6234 ;; up if the key has an associated command in another currently active
6235 ;; keymap (minor modes, major mode, global), and executes that
6236 ;; command. There might be problems if any of the keys is otherwise
6237 ;; used as a prefix key.
6239 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6240 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6241 ;; addresses this by checking explicitly for both bindings.
6243 (defvar orgstruct-mode-map (make-sparse-keymap)
6244 "Keymap for the minor `orgstruct-mode'.")
6246 (defvar org-local-vars nil
6247 "List of local variables, for use by `orgstruct-mode'")
6249 ;;;###autoload
6250 (define-minor-mode orgstruct-mode
6251 "Toggle the minor more `orgstruct-mode'.
6252 This mode is for using Org-mode structure commands in other modes.
6253 The following key behave as if Org-mode was active, if the cursor
6254 is on a headline, or on a plain list item (both in the definition
6255 of Org-mode).
6257 M-up Move entry/item up
6258 M-down Move entry/item down
6259 M-left Promote
6260 M-right Demote
6261 M-S-up Move entry/item up
6262 M-S-down Move entry/item down
6263 M-S-left Promote subtree
6264 M-S-right Demote subtree
6265 M-q Fill paragraph and items like in Org-mode
6266 C-c ^ Sort entries
6267 C-c - Cycle list bullet
6268 TAB Cycle item visibility
6269 M-RET Insert new heading/item
6270 S-M-RET Insert new TODO heading / Chekbox item
6271 C-c C-c Set tags / toggle checkbox"
6272 nil " OrgStruct" nil
6273 (org-load-modules-maybe)
6274 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6276 ;;;###autoload
6277 (defun turn-on-orgstruct ()
6278 "Unconditionally turn on `orgstruct-mode'."
6279 (orgstruct-mode 1))
6281 ;;;###autoload
6282 (defun turn-on-orgstruct++ ()
6283 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6284 In addition to setting orgstruct-mode, this also exports all indentation and
6285 autofilling variables from org-mode into the buffer. Note that turning
6286 off orgstruct-mode will *not* remove these additional settings."
6287 (orgstruct-mode 1)
6288 (let (var val)
6289 (mapc
6290 (lambda (x)
6291 (when (string-match
6292 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6293 (symbol-name (car x)))
6294 (setq var (car x) val (nth 1 x))
6295 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6296 org-local-vars)))
6298 (defun orgstruct-error ()
6299 "Error when there is no default binding for a structure key."
6300 (interactive)
6301 (error "This key has no function outside structure elements"))
6303 (defun orgstruct-setup ()
6304 "Setup orgstruct keymaps."
6305 (let ((nfunc 0)
6306 (bindings
6307 (list
6308 '([(meta up)] org-metaup)
6309 '([(meta down)] org-metadown)
6310 '([(meta left)] org-metaleft)
6311 '([(meta right)] org-metaright)
6312 '([(meta shift up)] org-shiftmetaup)
6313 '([(meta shift down)] org-shiftmetadown)
6314 '([(meta shift left)] org-shiftmetaleft)
6315 '([(meta shift right)] org-shiftmetaright)
6316 '([(shift up)] org-shiftup)
6317 '([(shift down)] org-shiftdown)
6318 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6319 '("\M-q" fill-paragraph)
6320 '("\C-c^" org-sort)
6321 '("\C-c-" org-cycle-list-bullet)))
6322 elt key fun cmd)
6323 (while (setq elt (pop bindings))
6324 (setq nfunc (1+ nfunc))
6325 (setq key (org-key (car elt))
6326 fun (nth 1 elt)
6327 cmd (orgstruct-make-binding fun nfunc key))
6328 (org-defkey orgstruct-mode-map key cmd))
6330 ;; Special treatment needed for TAB and RET
6331 (org-defkey orgstruct-mode-map [(tab)]
6332 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6333 (org-defkey orgstruct-mode-map "\C-i"
6334 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6336 (org-defkey orgstruct-mode-map "\M-\C-m"
6337 (orgstruct-make-binding 'org-insert-heading 105
6338 "\M-\C-m" [(meta return)]))
6339 (org-defkey orgstruct-mode-map [(meta return)]
6340 (orgstruct-make-binding 'org-insert-heading 106
6341 [(meta return)] "\M-\C-m"))
6343 (org-defkey orgstruct-mode-map [(shift meta return)]
6344 (orgstruct-make-binding 'org-insert-todo-heading 107
6345 [(meta return)] "\M-\C-m"))
6347 (unless org-local-vars
6348 (setq org-local-vars (org-get-local-variables)))
6352 (defun orgstruct-make-binding (fun n &rest keys)
6353 "Create a function for binding in the structure minor mode.
6354 FUN is the command to call inside a table. N is used to create a unique
6355 command name. KEYS are keys that should be checked in for a command
6356 to execute outside of tables."
6357 (eval
6358 (list 'defun
6359 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6360 '(arg)
6361 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6362 "Outside of structure, run the binding of `"
6363 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6364 "'.")
6365 '(interactive "p")
6366 (list 'if
6367 '(org-context-p 'headline 'item)
6368 (list 'org-run-like-in-org-mode (list 'quote fun))
6369 (list 'let '(orgstruct-mode)
6370 (list 'call-interactively
6371 (append '(or)
6372 (mapcar (lambda (k)
6373 (list 'key-binding k))
6374 keys)
6375 '('orgstruct-error))))))))
6377 (defun org-context-p (&rest contexts)
6378 "Check if local context is and of CONTEXTS.
6379 Possible values in the list of contexts are `table', `headline', and `item'."
6380 (let ((pos (point)))
6381 (goto-char (point-at-bol))
6382 (prog1 (or (and (memq 'table contexts)
6383 (looking-at "[ \t]*|"))
6384 (and (memq 'headline contexts)
6385 (looking-at "\\*+"))
6386 (and (memq 'item contexts)
6387 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6388 (goto-char pos))))
6390 (defun org-get-local-variables ()
6391 "Return a list of all local variables in an org-mode buffer."
6392 (let (varlist)
6393 (with-current-buffer (get-buffer-create "*Org tmp*")
6394 (erase-buffer)
6395 (org-mode)
6396 (setq varlist (buffer-local-variables)))
6397 (kill-buffer "*Org tmp*")
6398 (delq nil
6399 (mapcar
6400 (lambda (x)
6401 (setq x
6402 (if (symbolp x)
6403 (list x)
6404 (list (car x) (list 'quote (cdr x)))))
6405 (if (string-match
6406 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6407 (symbol-name (car x)))
6408 x nil))
6409 varlist))))
6411 ;;;###autoload
6412 (defun org-run-like-in-org-mode (cmd)
6413 (org-load-modules-maybe)
6414 (unless org-local-vars
6415 (setq org-local-vars (org-get-local-variables)))
6416 (eval (list 'let org-local-vars
6417 (list 'call-interactively (list 'quote cmd)))))
6419 ;;;; Archiving
6421 (defun org-get-category (&optional pos)
6422 "Get the category applying to position POS."
6423 (get-text-property (or pos (point)) 'org-category))
6425 (defun org-refresh-category-properties ()
6426 "Refresh category text properties in the buffer."
6427 (let ((def-cat (cond
6428 ((null org-category)
6429 (if buffer-file-name
6430 (file-name-sans-extension
6431 (file-name-nondirectory buffer-file-name))
6432 "???"))
6433 ((symbolp org-category) (symbol-name org-category))
6434 (t org-category)))
6435 beg end cat pos optionp)
6436 (org-unmodified
6437 (save-excursion
6438 (save-restriction
6439 (widen)
6440 (goto-char (point-min))
6441 (put-text-property (point) (point-max) 'org-category def-cat)
6442 (while (re-search-forward
6443 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6444 (setq pos (match-end 0)
6445 optionp (equal (char-after (match-beginning 0)) ?#)
6446 cat (org-trim (match-string 2)))
6447 (if optionp
6448 (setq beg (point-at-bol) end (point-max))
6449 (org-back-to-heading t)
6450 (setq beg (point) end (org-end-of-subtree t t)))
6451 (put-text-property beg end 'org-category cat)
6452 (goto-char pos)))))))
6455 ;;;; Link Stuff
6457 ;;; Link abbreviations
6459 (defun org-link-expand-abbrev (link)
6460 "Apply replacements as defined in `org-link-abbrev-alist."
6461 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6462 (let* ((key (match-string 1 link))
6463 (as (or (assoc key org-link-abbrev-alist-local)
6464 (assoc key org-link-abbrev-alist)))
6465 (tag (and (match-end 2) (match-string 3 link)))
6466 rpl)
6467 (if (not as)
6468 link
6469 (setq rpl (cdr as))
6470 (cond
6471 ((symbolp rpl) (funcall rpl tag))
6472 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6473 (t (concat rpl tag)))))
6474 link))
6476 ;;; Storing and inserting links
6478 (defvar org-insert-link-history nil
6479 "Minibuffer history for links inserted with `org-insert-link'.")
6481 (defvar org-stored-links nil
6482 "Contains the links stored with `org-store-link'.")
6484 (defvar org-store-link-plist nil
6485 "Plist with info about the most recently link created with `org-store-link'.")
6487 (defvar org-link-protocols nil
6488 "Link protocols added to Org-mode using `org-add-link-type'.")
6490 (defvar org-store-link-functions nil
6491 "List of functions that are called to create and store a link.
6492 Each function will be called in turn until one returns a non-nil
6493 value. Each function should check if it is responsible for creating
6494 this link (for example by looking at the major mode).
6495 If not, it must exit and return nil.
6496 If yes, it should return a non-nil value after a calling
6497 `org-store-link-props' with a list of properties and values.
6498 Special properties are:
6500 :type The link prefix. like \"http\". This must be given.
6501 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6502 This is obligatory as well.
6503 :description Optional default description for the second pair
6504 of brackets in an Org-mode link. The user can still change
6505 this when inserting this link into an Org-mode buffer.
6507 In addition to these, any additional properties can be specified
6508 and then used in remember templates.")
6510 (defun org-add-link-type (type &optional follow export)
6511 "Add TYPE to the list of `org-link-types'.
6512 Re-compute all regular expressions depending on `org-link-types'
6514 FOLLOW and EXPORT are two functions.
6516 FOLLOW should take the link path as the single argument and do whatever
6517 is necessary to follow the link, for example find a file or display
6518 a mail message.
6520 EXPORT should format the link path for export to one of the export formats.
6521 It should be a function accepting three arguments:
6523 path the path of the link, the text after the prefix (like \"http:\")
6524 desc the description of the link, if any, nil if there was no descripton
6525 format the export format, a symbol like `html' or `latex'.
6527 The function may use the FORMAT information to return different values
6528 depending on the format. The return value will be put literally into
6529 the exported file.
6530 Org-mode has a built-in default for exporting links. If you are happy with
6531 this default, there is no need to define an export function for the link
6532 type. For a simple example of an export function, see `org-bbdb.el'."
6533 (add-to-list 'org-link-types type t)
6534 (org-make-link-regexps)
6535 (if (assoc type org-link-protocols)
6536 (setcdr (assoc type org-link-protocols) (list follow export))
6537 (push (list type follow export) org-link-protocols)))
6540 ;;;###autoload
6541 (defun org-store-link (arg)
6542 "\\<org-mode-map>Store an org-link to the current location.
6543 This link is added to `org-stored-links' and can later be inserted
6544 into an org-buffer with \\[org-insert-link].
6546 For some link types, a prefix arg is interpreted:
6547 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6548 For file links, arg negates `org-context-in-file-links'."
6549 (interactive "P")
6550 (org-load-modules-maybe)
6551 (setq org-store-link-plist nil) ; reset
6552 (let (link cpltxt desc description search txt)
6553 (cond
6555 ((run-hook-with-args-until-success 'org-store-link-functions)
6556 (setq link (plist-get org-store-link-plist :link)
6557 desc (or (plist-get org-store-link-plist :description) link)))
6559 ((eq major-mode 'calendar-mode)
6560 (let ((cd (calendar-cursor-to-date)))
6561 (setq link
6562 (format-time-string
6563 (car org-time-stamp-formats)
6564 (apply 'encode-time
6565 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6566 nil nil nil))))
6567 (org-store-link-props :type "calendar" :date cd)))
6569 ((eq major-mode 'w3-mode)
6570 (setq cpltxt (url-view-url t)
6571 link (org-make-link cpltxt))
6572 (org-store-link-props :type "w3" :url (url-view-url t)))
6574 ((eq major-mode 'w3m-mode)
6575 (setq cpltxt (or w3m-current-title w3m-current-url)
6576 link (org-make-link w3m-current-url))
6577 (org-store-link-props :type "w3m" :url (url-view-url t)))
6579 ((setq search (run-hook-with-args-until-success
6580 'org-create-file-search-functions))
6581 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6582 "::" search))
6583 (setq cpltxt (or description link)))
6585 ((eq major-mode 'image-mode)
6586 (setq cpltxt (concat "file:"
6587 (abbreviate-file-name buffer-file-name))
6588 link (org-make-link cpltxt))
6589 (org-store-link-props :type "image" :file buffer-file-name))
6591 ((eq major-mode 'dired-mode)
6592 ;; link to the file in the current line
6593 (setq cpltxt (concat "file:"
6594 (abbreviate-file-name
6595 (expand-file-name
6596 (dired-get-filename nil t))))
6597 link (org-make-link cpltxt)))
6599 ((and buffer-file-name (org-mode-p))
6600 ;; Just link to current headline
6601 (setq cpltxt (concat "file:"
6602 (abbreviate-file-name buffer-file-name)))
6603 ;; Add a context search string
6604 (when (org-xor org-context-in-file-links arg)
6605 ;; Check if we are on a target
6606 (if (org-in-regexp "<<\\(.*?\\)>>")
6607 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6608 (setq txt (cond
6609 ((org-on-heading-p) nil)
6610 ((org-region-active-p)
6611 (buffer-substring (region-beginning) (region-end)))
6612 (t nil)))
6613 (when (or (null txt) (string-match "\\S-" txt))
6614 (setq cpltxt
6615 (concat cpltxt "::"
6616 (condition-case nil
6617 (org-make-org-heading-search-string txt)
6618 (error "")))
6619 desc "NONE"))))
6620 (if (string-match "::\\'" cpltxt)
6621 (setq cpltxt (substring cpltxt 0 -2)))
6622 (setq link (org-make-link cpltxt)))
6624 ((buffer-file-name (buffer-base-buffer))
6625 ;; Just link to this file here.
6626 (setq cpltxt (concat "file:"
6627 (abbreviate-file-name
6628 (buffer-file-name (buffer-base-buffer)))))
6629 ;; Add a context string
6630 (when (org-xor org-context-in-file-links arg)
6631 (setq txt (if (org-region-active-p)
6632 (buffer-substring (region-beginning) (region-end))
6633 (buffer-substring (point-at-bol) (point-at-eol))))
6634 ;; Only use search option if there is some text.
6635 (when (string-match "\\S-" txt)
6636 (setq cpltxt
6637 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6638 desc "NONE")))
6639 (setq link (org-make-link cpltxt)))
6641 ((interactive-p)
6642 (error "Cannot link to a buffer which is not visiting a file"))
6644 (t (setq link nil)))
6646 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6647 (setq link (or link cpltxt)
6648 desc (or desc cpltxt))
6649 (if (equal desc "NONE") (setq desc nil))
6651 (if (and (interactive-p) link)
6652 (progn
6653 (setq org-stored-links
6654 (cons (list link desc) org-stored-links))
6655 (message "Stored: %s" (or desc link)))
6656 (and link (org-make-link-string link desc)))))
6658 (defun org-store-link-props (&rest plist)
6659 "Store link properties, extract names and addresses."
6660 (let (x adr)
6661 (when (setq x (plist-get plist :from))
6662 (setq adr (mail-extract-address-components x))
6663 (plist-put plist :fromname (car adr))
6664 (plist-put plist :fromaddress (nth 1 adr)))
6665 (when (setq x (plist-get plist :to))
6666 (setq adr (mail-extract-address-components x))
6667 (plist-put plist :toname (car adr))
6668 (plist-put plist :toaddress (nth 1 adr))))
6669 (let ((from (plist-get plist :from))
6670 (to (plist-get plist :to)))
6671 (when (and from to org-from-is-user-regexp)
6672 (plist-put plist :fromto
6673 (if (string-match org-from-is-user-regexp from)
6674 (concat "to %t")
6675 (concat "from %f")))))
6676 (setq org-store-link-plist plist))
6678 (defun org-add-link-props (&rest plist)
6679 "Add these properties to the link property list."
6680 (let (key value)
6681 (while plist
6682 (setq key (pop plist) value (pop plist))
6683 (setq org-store-link-plist
6684 (plist-put org-store-link-plist key value)))))
6686 (defun org-email-link-description (&optional fmt)
6687 "Return the description part of an email link.
6688 This takes information from `org-store-link-plist' and formats it
6689 according to FMT (default from `org-email-link-description-format')."
6690 (setq fmt (or fmt org-email-link-description-format))
6691 (let* ((p org-store-link-plist)
6692 (to (plist-get p :toaddress))
6693 (from (plist-get p :fromaddress))
6694 (table
6695 (list
6696 (cons "%c" (plist-get p :fromto))
6697 (cons "%F" (plist-get p :from))
6698 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6699 (cons "%T" (plist-get p :to))
6700 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6701 (cons "%s" (plist-get p :subject))
6702 (cons "%m" (plist-get p :message-id)))))
6703 (when (string-match "%c" fmt)
6704 ;; Check if the user wrote this message
6705 (if (and org-from-is-user-regexp from to
6706 (save-match-data (string-match org-from-is-user-regexp from)))
6707 (setq fmt (replace-match "to %t" t t fmt))
6708 (setq fmt (replace-match "from %f" t t fmt))))
6709 (org-replace-escapes fmt table)))
6711 (defun org-make-org-heading-search-string (&optional string heading)
6712 "Make search string for STRING or current headline."
6713 (interactive)
6714 (let ((s (or string (org-get-heading))))
6715 (unless (and string (not heading))
6716 ;; We are using a headline, clean up garbage in there.
6717 (if (string-match org-todo-regexp s)
6718 (setq s (replace-match "" t t s)))
6719 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6720 (setq s (replace-match "" t t s)))
6721 (setq s (org-trim s))
6722 (if (string-match (concat "^\\(" org-quote-string "\\|"
6723 org-comment-string "\\)") s)
6724 (setq s (replace-match "" t t s)))
6725 (while (string-match org-ts-regexp s)
6726 (setq s (replace-match "" t t s))))
6727 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6728 (setq s (replace-match " " t t s)))
6729 (or string (setq s (concat "*" s))) ; Add * for headlines
6730 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6732 (defun org-make-link (&rest strings)
6733 "Concatenate STRINGS."
6734 (apply 'concat strings))
6736 (defun org-make-link-string (link &optional description)
6737 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6738 (unless (string-match "\\S-" link)
6739 (error "Empty link"))
6740 (when (stringp description)
6741 ;; Remove brackets from the description, they are fatal.
6742 (while (string-match "\\[" description)
6743 (setq description (replace-match "{" t t description)))
6744 (while (string-match "\\]" description)
6745 (setq description (replace-match "}" t t description))))
6746 (when (equal (org-link-escape link) description)
6747 ;; No description needed, it is identical
6748 (setq description nil))
6749 (when (and (not description)
6750 (not (equal link (org-link-escape link))))
6751 (setq description (org-extract-attributes link)))
6752 (concat "[[" (org-link-escape link) "]"
6753 (if description (concat "[" description "]") "")
6754 "]"))
6756 (defconst org-link-escape-chars
6757 '((?\ . "%20")
6758 (?\[ . "%5B")
6759 (?\] . "%5D")
6760 (?\340 . "%E0") ; `a
6761 (?\342 . "%E2") ; ^a
6762 (?\347 . "%E7") ; ,c
6763 (?\350 . "%E8") ; `e
6764 (?\351 . "%E9") ; 'e
6765 (?\352 . "%EA") ; ^e
6766 (?\356 . "%EE") ; ^i
6767 (?\364 . "%F4") ; ^o
6768 (?\371 . "%F9") ; `u
6769 (?\373 . "%FB") ; ^u
6770 (?\; . "%3B")
6771 (?? . "%3F")
6772 (?= . "%3D")
6773 (?+ . "%2B")
6775 "Association list of escapes for some characters problematic in links.
6776 This is the list that is used for internal purposes.")
6778 (defconst org-link-escape-chars-browser
6779 '((?\ . "%20")) ; 32 for the SPC char
6780 "Association list of escapes for some characters problematic in links.
6781 This is the list that is used before handing over to the browser.")
6783 (defun org-link-escape (text &optional table)
6784 "Escape charaters in TEXT that are problematic for links."
6785 (setq table (or table org-link-escape-chars))
6786 (when text
6787 (let ((re (mapconcat (lambda (x) (regexp-quote
6788 (char-to-string (car x))))
6789 table "\\|")))
6790 (while (string-match re text)
6791 (setq text
6792 (replace-match
6793 (cdr (assoc (string-to-char (match-string 0 text))
6794 table))
6795 t t text)))
6796 text)))
6798 (defun org-link-unescape (text &optional table)
6799 "Reverse the action of `org-link-escape'."
6800 (setq table (or table org-link-escape-chars))
6801 (when text
6802 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6803 table "\\|")))
6804 (while (string-match re text)
6805 (setq text
6806 (replace-match
6807 (char-to-string (car (rassoc (match-string 0 text) table)))
6808 t t text)))
6809 text)))
6811 (defun org-xor (a b)
6812 "Exclusive or."
6813 (if a (not b) b))
6815 (defun org-get-header (header)
6816 "Find a header field in the current buffer."
6817 (save-excursion
6818 (goto-char (point-min))
6819 (let ((case-fold-search t) s)
6820 (cond
6821 ((eq header 'from)
6822 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6823 (setq s (match-string 1)))
6824 (while (string-match "\"" s)
6825 (setq s (replace-match "" t t s)))
6826 (if (string-match "[<(].*" s)
6827 (setq s (replace-match "" t t s))))
6828 ((eq header 'message-id)
6829 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6830 (setq s (match-string 1))))
6831 ((eq header 'subject)
6832 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6833 (setq s (match-string 1)))))
6834 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6835 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6836 s)))
6839 (defun org-fixup-message-id-for-http (s)
6840 "Replace special characters in a message id, so it can be used in an http query."
6841 (while (string-match "<" s)
6842 (setq s (replace-match "%3C" t t s)))
6843 (while (string-match ">" s)
6844 (setq s (replace-match "%3E" t t s)))
6845 (while (string-match "@" s)
6846 (setq s (replace-match "%40" t t s)))
6849 ;;;###autoload
6850 (defun org-insert-link-global ()
6851 "Insert a link like Org-mode does.
6852 This command can be called in any mode to insert a link in Org-mode syntax."
6853 (interactive)
6854 (org-load-modules-maybe)
6855 (org-run-like-in-org-mode 'org-insert-link))
6857 (defun org-insert-link (&optional complete-file link-location)
6858 "Insert a link. At the prompt, enter the link.
6860 Completion can be used to select a link previously stored with
6861 `org-store-link'. When the empty string is entered (i.e. if you just
6862 press RET at the prompt), the link defaults to the most recently
6863 stored link. As SPC triggers completion in the minibuffer, you need to
6864 use M-SPC or C-q SPC to force the insertion of a space character.
6866 You will also be prompted for a description, and if one is given, it will
6867 be displayed in the buffer instead of the link.
6869 If there is already a link at point, this command will allow you to edit link
6870 and description parts.
6872 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6873 be selected using completion. The path to the file will be relative to the
6874 current directory if the file is in the current directory or a subdirectory.
6875 Otherwise, the link will be the absolute path as completed in the minibuffer
6876 \(i.e. normally ~/path/to/file).
6878 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6879 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6880 of `org-keep-stored-link-after-insertion'.
6882 If `org-make-link-description-function' is non-nil, this function will be
6883 called with the link target, and the result will be the default
6884 link description.
6886 If the LINK-LOCATION parameter is non-nil, this value will be
6887 used as the link location instead of reading one interactively."
6888 (interactive "P")
6889 (let* ((wcf (current-window-configuration))
6890 (region (if (org-region-active-p)
6891 (buffer-substring (region-beginning) (region-end))))
6892 (remove (and region (list (region-beginning) (region-end))))
6893 (desc region)
6894 tmphist ; byte-compile incorrectly complains about this
6895 (link link-location)
6896 entry file)
6897 (cond
6898 (link-location) ; specified by arg, just use it.
6899 ((org-in-regexp org-bracket-link-regexp 1)
6900 ;; We do have a link at point, and we are going to edit it.
6901 (setq remove (list (match-beginning 0) (match-end 0)))
6902 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6903 (setq link (read-string "Link: "
6904 (org-link-unescape
6905 (org-match-string-no-properties 1)))))
6906 ((or (org-in-regexp org-angle-link-re)
6907 (org-in-regexp org-plain-link-re))
6908 ;; Convert to bracket link
6909 (setq remove (list (match-beginning 0) (match-end 0))
6910 link (read-string "Link: "
6911 (org-remove-angle-brackets (match-string 0)))))
6912 ((equal complete-file '(4))
6913 ;; Completing read for file names.
6914 (setq file (read-file-name "File: "))
6915 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6916 (pwd1 (file-name-as-directory (abbreviate-file-name
6917 (expand-file-name ".")))))
6918 (cond
6919 ((equal complete-file '(16))
6920 (setq link (org-make-link
6921 "file:"
6922 (abbreviate-file-name (expand-file-name file)))))
6923 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6924 (setq link (org-make-link "file:" (match-string 1 file))))
6925 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6926 (expand-file-name file))
6927 (setq link (org-make-link
6928 "file:" (match-string 1 (expand-file-name file)))))
6929 (t (setq link (org-make-link "file:" file))))))
6931 ;; Read link, with completion for stored links.
6932 (with-output-to-temp-buffer "*Org Links*"
6933 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6934 (when org-stored-links
6935 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6936 (princ (mapconcat
6937 (lambda (x)
6938 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6939 (reverse org-stored-links) "\n"))))
6940 (let ((cw (selected-window)))
6941 (select-window (get-buffer-window "*Org Links*"))
6942 (shrink-window-if-larger-than-buffer)
6943 (setq truncate-lines t)
6944 (select-window cw))
6945 ;; Fake a link history, containing the stored links.
6946 (setq tmphist (append (mapcar 'car org-stored-links)
6947 org-insert-link-history))
6948 (unwind-protect
6949 (setq link (org-completing-read
6950 "Link: "
6951 (append
6952 (mapcar (lambda (x) (list (concat (car x) ":")))
6953 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6954 (mapcar (lambda (x) (list (concat x ":")))
6955 org-link-types))
6956 nil nil nil
6957 'tmphist
6958 (or (car (car org-stored-links)))))
6959 (set-window-configuration wcf)
6960 (kill-buffer "*Org Links*"))
6961 (setq entry (assoc link org-stored-links))
6962 (or entry (push link org-insert-link-history))
6963 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6964 (not org-keep-stored-link-after-insertion))
6965 (setq org-stored-links (delq (assoc link org-stored-links)
6966 org-stored-links)))
6967 (setq desc (or desc (nth 1 entry)))))
6969 (if (string-match org-plain-link-re link)
6970 ;; URL-like link, normalize the use of angular brackets.
6971 (setq link (org-make-link (org-remove-angle-brackets link))))
6973 ;; Check if we are linking to the current file with a search option
6974 ;; If yes, simplify the link by using only the search option.
6975 (when (and buffer-file-name
6976 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6977 (let* ((path (match-string 1 link))
6978 (case-fold-search nil)
6979 (search (match-string 2 link)))
6980 (save-match-data
6981 (if (equal (file-truename buffer-file-name) (file-truename path))
6982 ;; We are linking to this same file, with a search option
6983 (setq link search)))))
6985 ;; Check if we can/should use a relative path. If yes, simplify the link
6986 (when (string-match "\\<file:\\(.*\\)" link)
6987 (let* ((path (match-string 1 link))
6988 (origpath path)
6989 (case-fold-search nil))
6990 (cond
6991 ((eq org-link-file-path-type 'absolute)
6992 (setq path (abbreviate-file-name (expand-file-name path))))
6993 ((eq org-link-file-path-type 'noabbrev)
6994 (setq path (expand-file-name path)))
6995 ((eq org-link-file-path-type 'relative)
6996 (setq path (file-relative-name path)))
6998 (save-match-data
6999 (if (string-match (concat "^" (regexp-quote
7000 (file-name-as-directory
7001 (expand-file-name "."))))
7002 (expand-file-name path))
7003 ;; We are linking a file with relative path name.
7004 (setq path (substring (expand-file-name path)
7005 (match-end 0)))))))
7006 (setq link (concat "file:" path))
7007 (if (equal desc origpath)
7008 (setq desc path))))
7010 (if org-make-link-description-function
7011 (setq desc (funcall org-make-link-description-function link desc)))
7013 (setq desc (read-string "Description: " desc))
7014 (unless (string-match "\\S-" desc) (setq desc nil))
7015 (if remove (apply 'delete-region remove))
7016 (insert (org-make-link-string link desc))))
7018 (defun org-completing-read (&rest args)
7019 (let ((minibuffer-local-completion-map
7020 (copy-keymap minibuffer-local-completion-map)))
7021 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7022 (apply 'completing-read args)))
7024 (defun org-extract-attributes (s)
7025 "Extract the attributes cookie from a string and set as text property."
7026 (let (a attr (start 0))
7027 (save-match-data
7028 (when (string-match "{{\\([^}]+\\)}}$" s)
7029 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7030 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7031 (setq key (match-string 1 a) value (match-string 2 a)
7032 start (match-end 0)
7033 attr (plist-put attr (intern key) value))))
7034 (org-add-props s nil 'org-attributes attr))
7037 (defun org-attributes-to-string (plist)
7038 "Format a property list into an HTML attribute list."
7039 (let ((s "") key value)
7040 (while plist
7041 (setq key (pop plist) value (pop plist))
7042 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
7045 ;;; Opening/following a link
7047 (defvar org-link-search-failed nil)
7049 (defun org-next-link ()
7050 "Move forward to the next link.
7051 If the link is in hidden text, expose it."
7052 (interactive)
7053 (when (and org-link-search-failed (eq this-command last-command))
7054 (goto-char (point-min))
7055 (message "Link search wrapped back to beginning of buffer"))
7056 (setq org-link-search-failed nil)
7057 (let* ((pos (point))
7058 (ct (org-context))
7059 (a (assoc :link ct)))
7060 (if a (goto-char (nth 2 a)))
7061 (if (re-search-forward org-any-link-re nil t)
7062 (progn
7063 (goto-char (match-beginning 0))
7064 (if (org-invisible-p) (org-show-context)))
7065 (goto-char pos)
7066 (setq org-link-search-failed t)
7067 (error "No further link found"))))
7069 (defun org-previous-link ()
7070 "Move backward to the previous link.
7071 If the link is in hidden text, expose it."
7072 (interactive)
7073 (when (and org-link-search-failed (eq this-command last-command))
7074 (goto-char (point-max))
7075 (message "Link search wrapped back to end of buffer"))
7076 (setq org-link-search-failed nil)
7077 (let* ((pos (point))
7078 (ct (org-context))
7079 (a (assoc :link ct)))
7080 (if a (goto-char (nth 1 a)))
7081 (if (re-search-backward org-any-link-re nil t)
7082 (progn
7083 (goto-char (match-beginning 0))
7084 (if (org-invisible-p) (org-show-context)))
7085 (goto-char pos)
7086 (setq org-link-search-failed t)
7087 (error "No further link found"))))
7089 (defun org-find-file-at-mouse (ev)
7090 "Open file link or URL at mouse."
7091 (interactive "e")
7092 (mouse-set-point ev)
7093 (org-open-at-point 'in-emacs))
7095 (defun org-open-at-mouse (ev)
7096 "Open file link or URL at mouse."
7097 (interactive "e")
7098 (mouse-set-point ev)
7099 (org-open-at-point))
7101 (defvar org-window-config-before-follow-link nil
7102 "The window configuration before following a link.
7103 This is saved in case the need arises to restore it.")
7105 (defvar org-open-link-marker (make-marker)
7106 "Marker pointing to the location where `org-open-at-point; was called.")
7108 ;;;###autoload
7109 (defun org-open-at-point-global ()
7110 "Follow a link like Org-mode does.
7111 This command can be called in any mode to follow a link that has
7112 Org-mode syntax."
7113 (interactive)
7114 (org-run-like-in-org-mode 'org-open-at-point))
7116 ;;;###autoload
7117 (defun org-open-link-from-string (s &optional arg)
7118 "Open a link in the string S, as if it was in Org-mode."
7119 (interactive "sLink: \nP")
7120 (with-temp-buffer
7121 (let ((org-inhibit-startup t))
7122 (org-mode)
7123 (insert s)
7124 (goto-char (point-min))
7125 (org-open-at-point arg))))
7127 (defun org-open-at-point (&optional in-emacs)
7128 "Open link at or after point.
7129 If there is no link at point, this function will search forward up to
7130 the end of the current subtree.
7131 Normally, files will be opened by an appropriate application. If the
7132 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7133 (interactive "P")
7134 (org-load-modules-maybe)
7135 (move-marker org-open-link-marker (point))
7136 (setq org-window-config-before-follow-link (current-window-configuration))
7137 (org-remove-occur-highlights nil nil t)
7138 (if (org-at-timestamp-p t)
7139 (org-follow-timestamp-link)
7140 (let (type path link line search (pos (point)))
7141 (catch 'match
7142 (save-excursion
7143 (skip-chars-forward "^]\n\r")
7144 (when (org-in-regexp org-bracket-link-regexp)
7145 (setq link (org-extract-attributes
7146 (org-link-unescape (org-match-string-no-properties 1))))
7147 (while (string-match " *\n *" link)
7148 (setq link (replace-match " " t t link)))
7149 (setq link (org-link-expand-abbrev link))
7150 (cond
7151 ((or (file-name-absolute-p link)
7152 (string-match "^\\.\\.?/" link))
7153 (setq type "file" path link))
7154 ((string-match org-link-re-with-space2 link)
7155 (setq type (match-string 1 link) path (match-string 2 link)))
7156 (t (setq type "thisfile" path link)))
7157 (throw 'match t)))
7159 (when (get-text-property (point) 'org-linked-text)
7160 (setq type "thisfile"
7161 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7162 (1+ (point)) (point))
7163 path (buffer-substring
7164 (previous-single-property-change pos 'org-linked-text)
7165 (next-single-property-change pos 'org-linked-text)))
7166 (throw 'match t))
7168 (save-excursion
7169 (when (or (org-in-regexp org-angle-link-re)
7170 (org-in-regexp org-plain-link-re))
7171 (setq type (match-string 1) path (match-string 2))
7172 (throw 'match t)))
7173 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7174 (setq type "tree-match"
7175 path (match-string 1))
7176 (throw 'match t))
7177 (save-excursion
7178 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7179 (setq type "tags"
7180 path (match-string 1))
7181 (while (string-match ":" path)
7182 (setq path (replace-match "+" t t path)))
7183 (throw 'match t))))
7184 (unless path
7185 (error "No link found"))
7186 ;; Remove any trailing spaces in path
7187 (if (string-match " +\\'" path)
7188 (setq path (replace-match "" t t path)))
7190 (cond
7192 ((assoc type org-link-protocols)
7193 (funcall (nth 1 (assoc type org-link-protocols)) path))
7195 ((equal type "mailto")
7196 (let ((cmd (car org-link-mailto-program))
7197 (args (cdr org-link-mailto-program)) args1
7198 (address path) (subject "") a)
7199 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7200 (setq address (match-string 1 path)
7201 subject (org-link-escape (match-string 2 path))))
7202 (while args
7203 (cond
7204 ((not (stringp (car args))) (push (pop args) args1))
7205 (t (setq a (pop args))
7206 (if (string-match "%a" a)
7207 (setq a (replace-match address t t a)))
7208 (if (string-match "%s" a)
7209 (setq a (replace-match subject t t a)))
7210 (push a args1))))
7211 (apply cmd (nreverse args1))))
7213 ((member type '("http" "https" "ftp" "news"))
7214 (browse-url (concat type ":" (org-link-escape
7215 path org-link-escape-chars-browser))))
7217 ((member type '("message"))
7218 (browse-url (concat type ":" path)))
7220 ((string= type "tags")
7221 (org-tags-view in-emacs path))
7222 ((string= type "thisfile")
7223 (if in-emacs
7224 (switch-to-buffer-other-window
7225 (org-get-buffer-for-internal-link (current-buffer)))
7226 (org-mark-ring-push))
7227 (let ((cmd `(org-link-search
7228 ,path
7229 ,(cond ((equal in-emacs '(4)) 'occur)
7230 ((equal in-emacs '(16)) 'org-occur)
7231 (t nil))
7232 ,pos)))
7233 (condition-case nil (eval cmd)
7234 (error (progn (widen) (eval cmd))))))
7236 ((string= type "tree-match")
7237 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7239 ((string= type "file")
7240 (if (string-match "::\\([0-9]+\\)\\'" path)
7241 (setq line (string-to-number (match-string 1 path))
7242 path (substring path 0 (match-beginning 0)))
7243 (if (string-match "::\\(.+\\)\\'" path)
7244 (setq search (match-string 1 path)
7245 path (substring path 0 (match-beginning 0)))))
7246 (if (string-match "[*?{]" (file-name-nondirectory path))
7247 (dired path)
7248 (org-open-file path in-emacs line search)))
7250 ((string= type "news")
7251 (require 'org-gnus)
7252 (org-gnus-follow-link path))
7254 ((string= type "shell")
7255 (let ((cmd path))
7256 (if (or (not org-confirm-shell-link-function)
7257 (funcall org-confirm-shell-link-function
7258 (format "Execute \"%s\" in shell? "
7259 (org-add-props cmd nil
7260 'face 'org-warning))))
7261 (progn
7262 (message "Executing %s" cmd)
7263 (shell-command cmd))
7264 (error "Abort"))))
7266 ((string= type "elisp")
7267 (let ((cmd path))
7268 (if (or (not org-confirm-elisp-link-function)
7269 (funcall org-confirm-elisp-link-function
7270 (format "Execute \"%s\" as elisp? "
7271 (org-add-props cmd nil
7272 'face 'org-warning))))
7273 (message "%s => %s" cmd (eval (read cmd)))
7274 (error "Abort"))))
7277 (browse-url-at-point)))))
7278 (move-marker org-open-link-marker nil)
7279 (run-hook-with-args 'org-follow-link-hook))
7281 ;;;; Time estimates
7283 (defun org-get-effort (&optional pom)
7284 "Get the effort estimate for the current entry."
7285 (org-entry-get pom org-effort-property))
7287 ;;; File search
7289 (defvar org-create-file-search-functions nil
7290 "List of functions to construct the right search string for a file link.
7291 These functions are called in turn with point at the location to
7292 which the link should point.
7294 A function in the hook should first test if it would like to
7295 handle this file type, for example by checking the major-mode or
7296 the file extension. If it decides not to handle this file, it
7297 should just return nil to give other functions a chance. If it
7298 does handle the file, it must return the search string to be used
7299 when following the link. The search string will be part of the
7300 file link, given after a double colon, and `org-open-at-point'
7301 will automatically search for it. If special measures must be
7302 taken to make the search successful, another function should be
7303 added to the companion hook `org-execute-file-search-functions',
7304 which see.
7306 A function in this hook may also use `setq' to set the variable
7307 `description' to provide a suggestion for the descriptive text to
7308 be used for this link when it gets inserted into an Org-mode
7309 buffer with \\[org-insert-link].")
7311 (defvar org-execute-file-search-functions nil
7312 "List of functions to execute a file search triggered by a link.
7314 Functions added to this hook must accept a single argument, the
7315 search string that was part of the file link, the part after the
7316 double colon. The function must first check if it would like to
7317 handle this search, for example by checking the major-mode or the
7318 file extension. If it decides not to handle this search, it
7319 should just return nil to give other functions a chance. If it
7320 does handle the search, it must return a non-nil value to keep
7321 other functions from trying.
7323 Each function can access the current prefix argument through the
7324 variable `current-prefix-argument'. Note that a single prefix is
7325 used to force opening a link in Emacs, so it may be good to only
7326 use a numeric or double prefix to guide the search function.
7328 In case this is needed, a function in this hook can also restore
7329 the window configuration before `org-open-at-point' was called using:
7331 (set-window-configuration org-window-config-before-follow-link)")
7333 (defun org-link-search (s &optional type avoid-pos)
7334 "Search for a link search option.
7335 If S is surrounded by forward slashes, it is interpreted as a
7336 regular expression. In org-mode files, this will create an `org-occur'
7337 sparse tree. In ordinary files, `occur' will be used to list matches.
7338 If the current buffer is in `dired-mode', grep will be used to search
7339 in all files. If AVOID-POS is given, ignore matches near that position."
7340 (let ((case-fold-search t)
7341 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7342 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7343 (append '(("") (" ") ("\t") ("\n"))
7344 org-emphasis-alist)
7345 "\\|") "\\)"))
7346 (pos (point))
7347 (pre nil) (post nil)
7348 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7349 (cond
7350 ;; First check if there are any special
7351 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7352 ;; Now try the builtin stuff
7353 ((save-excursion
7354 (goto-char (point-min))
7355 (and
7356 (re-search-forward
7357 (concat "<<" (regexp-quote s0) ">>") nil t)
7358 (setq type 'dedicated
7359 pos (match-beginning 0))))
7360 ;; There is an exact target for this
7361 (goto-char pos))
7362 ((string-match "^/\\(.*\\)/$" s)
7363 ;; A regular expression
7364 (cond
7365 ((org-mode-p)
7366 (org-occur (match-string 1 s)))
7367 ;;((eq major-mode 'dired-mode)
7368 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7369 (t (org-do-occur (match-string 1 s)))))
7371 ;; A normal search strings
7372 (when (equal (string-to-char s) ?*)
7373 ;; Anchor on headlines, post may include tags.
7374 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7375 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7376 s (substring s 1)))
7377 (remove-text-properties
7378 0 (length s)
7379 '(face nil mouse-face nil keymap nil fontified nil) s)
7380 ;; Make a series of regular expressions to find a match
7381 (setq words (org-split-string s "[ \n\r\t]+")
7383 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7384 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7385 "\\)" markers)
7386 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7387 re2a (concat "[ \t\r\n]" re2a_)
7388 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7389 re4 (concat "[^a-zA-Z_]" re4_)
7391 re1 (concat pre re2 post)
7392 re3 (concat pre (if pre re4_ re4) post)
7393 re5 (concat pre ".*" re4)
7394 re2 (concat pre re2)
7395 re2a (concat pre (if pre re2a_ re2a))
7396 re4 (concat pre (if pre re4_ re4))
7397 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7398 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7399 re5 "\\)"
7401 (cond
7402 ((eq type 'org-occur) (org-occur reall))
7403 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7404 (t (goto-char (point-min))
7405 (setq type 'fuzzy)
7406 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7407 (org-search-not-self 1 re1 nil t)
7408 (org-search-not-self 1 re2 nil t)
7409 (org-search-not-self 1 re2a nil t)
7410 (org-search-not-self 1 re3 nil t)
7411 (org-search-not-self 1 re4 nil t)
7412 (org-search-not-self 1 re5 nil t)
7414 (goto-char (match-beginning 1))
7415 (goto-char pos)
7416 (error "No match")))))
7418 ;; Normal string-search
7419 (goto-char (point-min))
7420 (if (search-forward s nil t)
7421 (goto-char (match-beginning 0))
7422 (error "No match"))))
7423 (and (org-mode-p) (org-show-context 'link-search))
7424 type))
7426 (defun org-search-not-self (group &rest args)
7427 "Execute `re-search-forward', but only accept matches that do not
7428 enclose the position of `org-open-link-marker'."
7429 (let ((m org-open-link-marker))
7430 (catch 'exit
7431 (while (apply 're-search-forward args)
7432 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7433 (goto-char (match-end group))
7434 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7435 (> (match-beginning 0) (marker-position m))
7436 (< (match-end 0) (marker-position m)))
7437 (save-match-data
7438 (or (not (org-in-regexp
7439 org-bracket-link-analytic-regexp 1))
7440 (not (match-end 4)) ; no description
7441 (and (<= (match-beginning 4) (point))
7442 (>= (match-end 4) (point))))))
7443 (throw 'exit (point))))))))
7445 (defun org-get-buffer-for-internal-link (buffer)
7446 "Return a buffer to be used for displaying the link target of internal links."
7447 (cond
7448 ((not org-display-internal-link-with-indirect-buffer)
7449 buffer)
7450 ((string-match "(Clone)$" (buffer-name buffer))
7451 (message "Buffer is already a clone, not making another one")
7452 ;; we also do not modify visibility in this case
7453 buffer)
7454 (t ; make a new indirect buffer for displaying the link
7455 (let* ((bn (buffer-name buffer))
7456 (ibn (concat bn "(Clone)"))
7457 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7458 (with-current-buffer ib (org-overview))
7459 ib))))
7461 (defun org-do-occur (regexp &optional cleanup)
7462 "Call the Emacs command `occur'.
7463 If CLEANUP is non-nil, remove the printout of the regular expression
7464 in the *Occur* buffer. This is useful if the regex is long and not useful
7465 to read."
7466 (occur regexp)
7467 (when cleanup
7468 (let ((cwin (selected-window)) win beg end)
7469 (when (setq win (get-buffer-window "*Occur*"))
7470 (select-window win))
7471 (goto-char (point-min))
7472 (when (re-search-forward "match[a-z]+" nil t)
7473 (setq beg (match-end 0))
7474 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7475 (setq end (1- (match-beginning 0)))))
7476 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7477 (goto-char (point-min))
7478 (select-window cwin))))
7480 ;;; The mark ring for links jumps
7482 (defvar org-mark-ring nil
7483 "Mark ring for positions before jumps in Org-mode.")
7484 (defvar org-mark-ring-last-goto nil
7485 "Last position in the mark ring used to go back.")
7486 ;; Fill and close the ring
7487 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7488 (loop for i from 1 to org-mark-ring-length do
7489 (push (make-marker) org-mark-ring))
7490 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7491 org-mark-ring)
7493 (defun org-mark-ring-push (&optional pos buffer)
7494 "Put the current position or POS into the mark ring and rotate it."
7495 (interactive)
7496 (setq pos (or pos (point)))
7497 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7498 (move-marker (car org-mark-ring)
7499 (or pos (point))
7500 (or buffer (current-buffer)))
7501 (message "%s"
7502 (substitute-command-keys
7503 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7505 (defun org-mark-ring-goto (&optional n)
7506 "Jump to the previous position in the mark ring.
7507 With prefix arg N, jump back that many stored positions. When
7508 called several times in succession, walk through the entire ring.
7509 Org-mode commands jumping to a different position in the current file,
7510 or to another Org-mode file, automatically push the old position
7511 onto the ring."
7512 (interactive "p")
7513 (let (p m)
7514 (if (eq last-command this-command)
7515 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7516 (setq p org-mark-ring))
7517 (setq org-mark-ring-last-goto p)
7518 (setq m (car p))
7519 (switch-to-buffer (marker-buffer m))
7520 (goto-char m)
7521 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7523 (defun org-remove-angle-brackets (s)
7524 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7525 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7527 (defun org-add-angle-brackets (s)
7528 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7529 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7531 (defun org-remove-double-quotes (s)
7532 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7533 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7536 ;;; Following specific links
7538 (defun org-follow-timestamp-link ()
7539 (cond
7540 ((org-at-date-range-p t)
7541 (let ((org-agenda-start-on-weekday)
7542 (t1 (match-string 1))
7543 (t2 (match-string 2)))
7544 (setq t1 (time-to-days (org-time-string-to-time t1))
7545 t2 (time-to-days (org-time-string-to-time t2)))
7546 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7547 ((org-at-timestamp-p t)
7548 (org-agenda-list nil (time-to-days (org-time-string-to-time
7549 (substring (match-string 1) 0 10)))
7551 (t (error "This should not happen"))))
7554 ;;; Following file links
7555 (defvar org-wait nil)
7556 (defun org-open-file (path &optional in-emacs line search)
7557 "Open the file at PATH.
7558 First, this expands any special file name abbreviations. Then the
7559 configuration variable `org-file-apps' is checked if it contains an
7560 entry for this file type, and if yes, the corresponding command is launched.
7561 If no application is found, Emacs simply visits the file.
7562 With optional argument IN-EMACS, Emacs will visit the file.
7563 Optional LINE specifies a line to go to, optional SEARCH a string to
7564 search for. If LINE or SEARCH is given, the file will always be
7565 opened in Emacs.
7566 If the file does not exist, an error is thrown."
7567 (setq in-emacs (or in-emacs line search))
7568 (let* ((file (if (equal path "")
7569 buffer-file-name
7570 (substitute-in-file-name (expand-file-name path))))
7571 (apps (append org-file-apps (org-default-apps)))
7572 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7573 (dirp (if remp nil (file-directory-p file)))
7574 (dfile (downcase file))
7575 (old-buffer (current-buffer))
7576 (old-pos (point))
7577 (old-mode major-mode)
7578 ext cmd)
7579 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7580 (setq ext (match-string 1 dfile))
7581 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7582 (setq ext (match-string 1 dfile))))
7583 (if in-emacs
7584 (setq cmd 'emacs)
7585 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7586 (and dirp (cdr (assoc 'directory apps)))
7587 (cdr (assoc ext apps))
7588 (cdr (assoc t apps)))))
7589 (when (eq cmd 'mailcap)
7590 (require 'mailcap)
7591 (mailcap-parse-mailcaps)
7592 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7593 (command (mailcap-mime-info mime-type)))
7594 (if (stringp command)
7595 (setq cmd command)
7596 (setq cmd 'emacs))))
7597 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7598 (not (file-exists-p file))
7599 (not org-open-non-existing-files))
7600 (error "No such file: %s" file))
7601 (cond
7602 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7603 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7604 (while (string-match "['\"]%s['\"]" cmd)
7605 (setq cmd (replace-match "%s" t t cmd)))
7606 (while (string-match "%s" cmd)
7607 (setq cmd (replace-match
7608 (save-match-data
7609 (shell-quote-argument
7610 (convert-standard-filename file)))
7611 t t cmd)))
7612 (save-window-excursion
7613 (start-process-shell-command cmd nil cmd)
7614 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7616 ((or (stringp cmd)
7617 (eq cmd 'emacs))
7618 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7619 (widen)
7620 (if line (goto-line line)
7621 (if search (org-link-search search))))
7622 ((consp cmd)
7623 (let ((file (convert-standard-filename file)))
7624 (eval cmd)))
7625 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7626 (and (org-mode-p) (eq old-mode 'org-mode)
7627 (or (not (equal old-buffer (current-buffer)))
7628 (not (equal old-pos (point))))
7629 (org-mark-ring-push old-pos old-buffer))))
7631 (defun org-default-apps ()
7632 "Return the default applications for this operating system."
7633 (cond
7634 ((eq system-type 'darwin)
7635 org-file-apps-defaults-macosx)
7636 ((eq system-type 'windows-nt)
7637 org-file-apps-defaults-windowsnt)
7638 (t org-file-apps-defaults-gnu)))
7640 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7641 (defun org-file-remote-p (file)
7642 "Test whether FILE specifies a location on a remote system.
7643 Return non-nil if the location is indeed remote.
7645 For example, the filename \"/user@host:/foo\" specifies a location
7646 on the system \"/user@host:\"."
7647 (cond ((fboundp 'file-remote-p)
7648 (file-remote-p file))
7649 ((fboundp 'tramp-handle-file-remote-p)
7650 (tramp-handle-file-remote-p file))
7651 ((and (boundp 'ange-ftp-name-format)
7652 (string-match (car ange-ftp-name-format) file))
7654 (t nil)))
7657 ;;;; Refiling
7659 (defun org-get-org-file ()
7660 "Read a filename, with default directory `org-directory'."
7661 (let ((default (or org-default-notes-file remember-data-file)))
7662 (read-file-name (format "File name [%s]: " default)
7663 (file-name-as-directory org-directory)
7664 default)))
7666 (defun org-notes-order-reversed-p ()
7667 "Check if the current file should receive notes in reversed order."
7668 (cond
7669 ((not org-reverse-note-order) nil)
7670 ((eq t org-reverse-note-order) t)
7671 ((not (listp org-reverse-note-order)) nil)
7672 (t (catch 'exit
7673 (let ((all org-reverse-note-order)
7674 entry)
7675 (while (setq entry (pop all))
7676 (if (string-match (car entry) buffer-file-name)
7677 (throw 'exit (cdr entry))))
7678 nil)))))
7680 (defvar org-refile-target-table nil
7681 "The list of refile targets, created by `org-refile'.")
7683 (defvar org-agenda-new-buffers nil
7684 "Buffers created to visit agenda files.")
7686 (defun org-get-refile-targets (&optional default-buffer)
7687 "Produce a table with refile targets."
7688 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7689 targets txt re files f desc descre)
7690 (with-current-buffer (or default-buffer (current-buffer))
7691 (while (setq entry (pop entries))
7692 (setq files (car entry) desc (cdr entry))
7693 (cond
7694 ((null files) (setq files (list (current-buffer))))
7695 ((eq files 'org-agenda-files)
7696 (setq files (org-agenda-files 'unrestricted)))
7697 ((and (symbolp files) (fboundp files))
7698 (setq files (funcall files)))
7699 ((and (symbolp files) (boundp files))
7700 (setq files (symbol-value files))))
7701 (if (stringp files) (setq files (list files)))
7702 (cond
7703 ((eq (car desc) :tag)
7704 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7705 ((eq (car desc) :todo)
7706 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7707 ((eq (car desc) :regexp)
7708 (setq descre (cdr desc)))
7709 ((eq (car desc) :level)
7710 (setq descre (concat "^\\*\\{" (number-to-string
7711 (if org-odd-levels-only
7712 (1- (* 2 (cdr desc)))
7713 (cdr desc)))
7714 "\\}[ \t]")))
7715 ((eq (car desc) :maxlevel)
7716 (setq descre (concat "^\\*\\{1," (number-to-string
7717 (if org-odd-levels-only
7718 (1- (* 2 (cdr desc)))
7719 (cdr desc)))
7720 "\\}[ \t]")))
7721 (t (error "Bad refiling target description %s" desc)))
7722 (while (setq f (pop files))
7723 (save-excursion
7724 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7725 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7726 (save-excursion
7727 (save-restriction
7728 (widen)
7729 (goto-char (point-min))
7730 (while (re-search-forward descre nil t)
7731 (goto-char (point-at-bol))
7732 (when (looking-at org-complex-heading-regexp)
7733 (setq txt (match-string 4)
7734 re (concat "^" (regexp-quote
7735 (buffer-substring (match-beginning 1)
7736 (match-end 4)))))
7737 (if (match-end 5) (setq re (concat re "[ \t]+"
7738 (regexp-quote
7739 (match-string 5)))))
7740 (setq re (concat re "[ \t]*$"))
7741 (when org-refile-use-outline-path
7742 (setq txt (mapconcat 'identity
7743 (append
7744 (if (eq org-refile-use-outline-path 'file)
7745 (list (file-name-nondirectory
7746 (buffer-file-name (buffer-base-buffer))))
7747 (if (eq org-refile-use-outline-path 'full-file-path)
7748 (list (buffer-file-name (buffer-base-buffer)))))
7749 (org-get-outline-path)
7750 (list txt))
7751 "/")))
7752 (push (list txt f re (point)) targets))
7753 (goto-char (point-at-eol))))))))
7754 (nreverse targets))))
7756 (defun org-get-outline-path ()
7757 "Return the outline path to the current entry, as a list."
7758 (let (rtn)
7759 (save-excursion
7760 (while (org-up-heading-safe)
7761 (when (looking-at org-complex-heading-regexp)
7762 (push (org-match-string-no-properties 4) rtn)))
7763 rtn)))
7765 (defvar org-refile-history nil
7766 "History for refiling operations.")
7768 (defun org-refile (&optional goto default-buffer)
7769 "Move the entry at point to another heading.
7770 The list of target headings is compiled using the information in
7771 `org-refile-targets', which see. This list is created before each use
7772 and will therefore always be up-to-date.
7774 At the target location, the entry is filed as a subitem of the target heading.
7775 Depending on `org-reverse-note-order', the new subitem will either be the
7776 first of the last subitem.
7778 With prefix arg GOTO, the command will only visit the target location,
7779 not actually move anything.
7780 With a double prefix `C-c C-c', go to the location where the last refiling
7781 operation has put the subtree."
7782 (interactive "P")
7783 (let* ((cbuf (current-buffer))
7784 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7785 pos it nbuf file re level reversed)
7786 (if (equal goto '(16))
7787 (org-refile-goto-last-stored)
7788 (when (setq it (org-refile-get-location
7789 (if goto "Goto: " "Refile to: ") default-buffer))
7790 (setq file (nth 1 it)
7791 re (nth 2 it)
7792 pos (nth 3 it))
7793 (setq nbuf (or (find-buffer-visiting file)
7794 (find-file-noselect file)))
7795 (if goto
7796 (progn
7797 (switch-to-buffer nbuf)
7798 (goto-char pos)
7799 (org-show-context 'org-goto))
7800 (org-copy-subtree 1 nil t)
7801 (save-excursion
7802 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7803 (find-file-noselect file))))
7804 (setq reversed (org-notes-order-reversed-p))
7805 (save-excursion
7806 (save-restriction
7807 (widen)
7808 (goto-char pos)
7809 (looking-at outline-regexp)
7810 (setq level (org-get-valid-level (funcall outline-level) 1))
7811 (goto-char
7812 (if reversed
7813 (outline-next-heading)
7814 (or (save-excursion (outline-get-next-sibling))
7815 (org-end-of-subtree t t)
7816 (point-max))))
7817 (bookmark-set "org-refile-last-stored")
7818 (org-paste-subtree level))))
7819 (org-cut-subtree)
7820 (setq org-markers-to-move nil)
7821 (message "Entry refiled to \"%s\"" (car it)))))))
7823 (defun org-refile-goto-last-stored ()
7824 "Go to the location where the last refile was stored."
7825 (interactive)
7826 (bookmark-jump "org-refile-last-stored")
7827 (message "This is the location of the last refile"))
7829 (defun org-refile-get-location (&optional prompt default-buffer)
7830 "Prompt the user for a refile location, using PROMPT."
7831 (let ((org-refile-targets org-refile-targets)
7832 (org-refile-use-outline-path org-refile-use-outline-path))
7833 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7834 (unless org-refile-target-table
7835 (error "No refile targets"))
7836 (let* ((cbuf (current-buffer))
7837 (cfunc (if org-refile-use-outline-path
7838 'org-olpath-completing-read
7839 'completing-read))
7840 (extra (if org-refile-use-outline-path "/" ""))
7841 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7842 (fname (and filename (file-truename filename)))
7843 (tbl (mapcar
7844 (lambda (x)
7845 (if (not (equal fname (file-truename (nth 1 x))))
7846 (cons (concat (car x) extra " ("
7847 (file-name-nondirectory (nth 1 x)) ")")
7848 (cdr x))
7849 (cons (concat (car x) extra) (cdr x))))
7850 org-refile-target-table))
7851 (completion-ignore-case t))
7852 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7853 tbl)))
7855 (defun org-olpath-completing-read (prompt collection &rest args)
7856 "Read an outline path like a file name."
7857 (let ((thetable collection))
7858 (apply
7859 'completing-read prompt
7860 (lambda (string predicate &optional flag)
7861 (let (rtn r s f (l (length string)))
7862 (cond
7863 ((eq flag nil)
7864 ;; try completion
7865 (try-completion string thetable))
7866 ((eq flag t)
7867 ;; all-completions
7868 (setq rtn (all-completions string thetable predicate))
7869 (mapcar
7870 (lambda (x)
7871 (setq r (substring x l))
7872 (if (string-match " ([^)]*)$" x)
7873 (setq f (match-string 0 x))
7874 (setq f ""))
7875 (if (string-match "/" r)
7876 (concat string (substring r 0 (match-end 0)) f)
7878 rtn))
7879 ((eq flag 'lambda)
7880 ;; exact match?
7881 (assoc string thetable)))
7883 args)))
7885 ;;;; Dynamic blocks
7887 (defun org-find-dblock (name)
7888 "Find the first dynamic block with name NAME in the buffer.
7889 If not found, stay at current position and return nil."
7890 (let (pos)
7891 (save-excursion
7892 (goto-char (point-min))
7893 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7894 nil t)
7895 (match-beginning 0))))
7896 (if pos (goto-char pos))
7897 pos))
7899 (defconst org-dblock-start-re
7900 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7901 "Matches the startline of a dynamic block, with parameters.")
7903 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7904 "Matches the end of a dyhamic block.")
7906 (defun org-create-dblock (plist)
7907 "Create a dynamic block section, with parameters taken from PLIST.
7908 PLIST must containe a :name entry which is used as name of the block."
7909 (unless (bolp) (newline))
7910 (let ((name (plist-get plist :name)))
7911 (insert "#+BEGIN: " name)
7912 (while plist
7913 (if (eq (car plist) :name)
7914 (setq plist (cddr plist))
7915 (insert " " (prin1-to-string (pop plist)))))
7916 (insert "\n\n#+END:\n")
7917 (beginning-of-line -2)))
7919 (defun org-prepare-dblock ()
7920 "Prepare dynamic block for refresh.
7921 This empties the block, puts the cursor at the insert position and returns
7922 the property list including an extra property :name with the block name."
7923 (unless (looking-at org-dblock-start-re)
7924 (error "Not at a dynamic block"))
7925 (let* ((begdel (1+ (match-end 0)))
7926 (name (org-no-properties (match-string 1)))
7927 (params (append (list :name name)
7928 (read (concat "(" (match-string 3) ")")))))
7929 (unless (re-search-forward org-dblock-end-re nil t)
7930 (error "Dynamic block not terminated"))
7931 (setq params
7932 (append params
7933 (list :content (buffer-substring
7934 begdel (match-beginning 0)))))
7935 (delete-region begdel (match-beginning 0))
7936 (goto-char begdel)
7937 (open-line 1)
7938 params))
7940 (defun org-map-dblocks (&optional command)
7941 "Apply COMMAND to all dynamic blocks in the current buffer.
7942 If COMMAND is not given, use `org-update-dblock'."
7943 (let ((cmd (or command 'org-update-dblock))
7944 pos)
7945 (save-excursion
7946 (goto-char (point-min))
7947 (while (re-search-forward org-dblock-start-re nil t)
7948 (goto-char (setq pos (match-beginning 0)))
7949 (condition-case nil
7950 (funcall cmd)
7951 (error (message "Error during update of dynamic block")))
7952 (goto-char pos)
7953 (unless (re-search-forward org-dblock-end-re nil t)
7954 (error "Dynamic block not terminated"))))))
7956 (defun org-dblock-update (&optional arg)
7957 "User command for updating dynamic blocks.
7958 Update the dynamic block at point. With prefix ARG, update all dynamic
7959 blocks in the buffer."
7960 (interactive "P")
7961 (if arg
7962 (org-update-all-dblocks)
7963 (or (looking-at org-dblock-start-re)
7964 (org-beginning-of-dblock))
7965 (org-update-dblock)))
7967 (defun org-update-dblock ()
7968 "Update the dynamic block at point
7969 This means to empty the block, parse for parameters and then call
7970 the correct writing function."
7971 (save-window-excursion
7972 (let* ((pos (point))
7973 (line (org-current-line))
7974 (params (org-prepare-dblock))
7975 (name (plist-get params :name))
7976 (cmd (intern (concat "org-dblock-write:" name))))
7977 (message "Updating dynamic block `%s' at line %d..." name line)
7978 (funcall cmd params)
7979 (message "Updating dynamic block `%s' at line %d...done" name line)
7980 (goto-char pos))))
7982 (defun org-beginning-of-dblock ()
7983 "Find the beginning of the dynamic block at point.
7984 Error if there is no scuh block at point."
7985 (let ((pos (point))
7986 beg)
7987 (end-of-line 1)
7988 (if (and (re-search-backward org-dblock-start-re nil t)
7989 (setq beg (match-beginning 0))
7990 (re-search-forward org-dblock-end-re nil t)
7991 (> (match-end 0) pos))
7992 (goto-char beg)
7993 (goto-char pos)
7994 (error "Not in a dynamic block"))))
7996 (defun org-update-all-dblocks ()
7997 "Update all dynamic blocks in the buffer.
7998 This function can be used in a hook."
7999 (when (org-mode-p)
8000 (org-map-dblocks 'org-update-dblock)))
8003 ;;;; Completion
8005 (defconst org-additional-option-like-keywords
8006 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8007 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8008 "BEGIN_EXAMPLE" "END_EXAMPLE"))
8010 (defcustom org-structure-template-alist
8012 ("s" "#+begin_src ?\n\n#+end_src"
8013 "<src lang=\"?\">\n\n</src>")
8014 ("e" "#+begin_example\n?\n#+end_example"
8015 "<example>\n?\n</example>")
8016 ("q" "#+begin_quote\n?\n#+end_quote"
8017 "<quote>\n?\n</quote>")
8018 ("v" "#+begin_verse\n?\n#+end_verse"
8019 "<verse>\n?\n/verse>")
8020 ("l" "#+begin_latex\n?\n#+end_latex"
8021 "<literal style=\"latex\">\n?\n</literal>")
8022 ("L" "#+latex: "
8023 "<literal style=\"latex\">?</literal>")
8024 ("h" "#+begin_html\n?\n#+end_html"
8025 "<literal style=\"html\">\n?\n</literal>")
8026 ("H" "#+html: "
8027 "<literal style=\"html\">?</literal>")
8028 ("a" "#+begin_ascii\n?\n#+end_ascii")
8029 ("A" "#+ascii: ")
8030 ("i" "#+include %file ?"
8031 "<include file=%file markup=\"?\">")
8033 "Structure completion elements.
8034 This is a list of abbreviation keys and values. The value gets inserted
8035 it you type @samp{.} followed by the key and then the completion key,
8036 usually `M-TAB'. %file will be replaced by a file name after prompting
8037 for the file uning completion.
8038 There are two templates for each key, the first uses the original Org syntax,
8039 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8040 the default when the /org-mtags.el/ module has been loaded. See also the
8041 variable `org-mtags-prefere-muse-templates'.
8042 This is an experimental feature, it is undecided if it is going to stay in."
8043 :group 'org-completion
8044 :type '(repeat
8045 (string :tag "Key")
8046 (string :tag "Template")
8047 (string :tag "Muse Template")))
8049 (defun org-try-structure-completion ()
8050 "Try to complete a structure template before point.
8051 This looks for strings like \"<e\" on an otherwise empty line and
8052 expands them."
8053 (let ((l (buffer-substring (point-at-bol) (point)))
8055 (when (and (looking-at "[ \t]*$")
8056 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8057 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8058 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8059 (match-beginning 1)) a)
8060 t)))
8062 (defun org-complete-expand-structure-template (start cell)
8063 "Expand a structure template."
8064 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
8065 (rpl (nth (if musep 2 1) cell)))
8066 (delete-region start (point))
8067 (when (string-match "\\`#\\+" rpl)
8068 (cond
8069 ((bolp))
8070 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8071 (delete-region (point-at-bol) (point)))
8072 (t (newline))))
8073 (setq start (point))
8074 (if (string-match "%file" rpl)
8075 (setq rpl (replace-match
8076 (concat
8077 "\""
8078 (save-match-data
8079 (abbreviate-file-name (read-file-name "Include file: ")))
8080 "\"")
8081 t t rpl)))
8082 (insert rpl)
8083 (if (re-search-backward "\\?" start t) (delete-char 1))))
8086 (defun org-complete (&optional arg)
8087 "Perform completion on word at point.
8088 At the beginning of a headline, this completes TODO keywords as given in
8089 `org-todo-keywords'.
8090 If the current word is preceded by a backslash, completes the TeX symbols
8091 that are supported for HTML support.
8092 If the current word is preceded by \"#+\", completes special words for
8093 setting file options.
8094 In the line after \"#+STARTUP:, complete valid keywords.\"
8095 At all other locations, this simply calls the value of
8096 `org-completion-fallback-command'."
8097 (interactive "P")
8098 (org-without-partial-completion
8099 (catch 'exit
8100 (let* ((a nil)
8101 (end (point))
8102 (beg1 (save-excursion
8103 (skip-chars-backward (org-re "[:alnum:]_@"))
8104 (point)))
8105 (beg (save-excursion
8106 (skip-chars-backward "a-zA-Z0-9_:$")
8107 (point)))
8108 (confirm (lambda (x) (stringp (car x))))
8109 (searchhead (equal (char-before beg) ?*))
8110 (struct
8111 (when (and (member (char-before beg1) '(?. ?<))
8112 (setq a (assoc (buffer-substring beg1 (point))
8113 org-structure-template-alist)))
8114 (org-complete-expand-structure-template (1- beg1) a)
8115 (throw 'exit t)))
8116 (tag (and (equal (char-before beg1) ?:)
8117 (equal (char-after (point-at-bol)) ?*)))
8118 (prop (and (equal (char-before beg1) ?:)
8119 (not (equal (char-after (point-at-bol)) ?*))))
8120 (texp (equal (char-before beg) ?\\))
8121 (link (equal (char-before beg) ?\[))
8122 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8123 beg)
8124 "#+"))
8125 (startup (string-match "^#\\+STARTUP:.*"
8126 (buffer-substring (point-at-bol) (point))))
8127 (completion-ignore-case opt)
8128 (type nil)
8129 (tbl nil)
8130 (table (cond
8131 (opt
8132 (setq type :opt)
8133 (require 'org-exp)
8134 (append
8135 (mapcar
8136 (lambda (x)
8137 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8138 (cons (match-string 2 x) (match-string 1 x)))
8139 (org-split-string (org-get-current-options) "\n"))
8140 (mapcar 'list org-additional-option-like-keywords)))
8141 (startup
8142 (setq type :startup)
8143 org-startup-options)
8144 (link (append org-link-abbrev-alist-local
8145 org-link-abbrev-alist))
8146 (texp
8147 (setq type :tex)
8148 org-html-entities)
8149 ((string-match "\\`\\*+[ \t]+\\'"
8150 (buffer-substring (point-at-bol) beg))
8151 (setq type :todo)
8152 (mapcar 'list org-todo-keywords-1))
8153 (searchhead
8154 (setq type :searchhead)
8155 (save-excursion
8156 (goto-char (point-min))
8157 (while (re-search-forward org-todo-line-regexp nil t)
8158 (push (list
8159 (org-make-org-heading-search-string
8160 (match-string 3) t))
8161 tbl)))
8162 tbl)
8163 (tag (setq type :tag beg beg1)
8164 (or org-tag-alist (org-get-buffer-tags)))
8165 (prop (setq type :prop beg beg1)
8166 (mapcar 'list (org-buffer-property-keys nil t t)))
8167 (t (progn
8168 (call-interactively org-completion-fallback-command)
8169 (throw 'exit nil)))))
8170 (pattern (buffer-substring-no-properties beg end))
8171 (completion (try-completion pattern table confirm)))
8172 (cond ((eq completion t)
8173 (if (not (assoc (upcase pattern) table))
8174 (message "Already complete")
8175 (if (and (equal type :opt)
8176 (not (member (car (assoc (upcase pattern) table))
8177 org-additional-option-like-keywords)))
8178 (insert (substring (cdr (assoc (upcase pattern) table))
8179 (length pattern)))
8180 (if (memq type '(:tag :prop)) (insert ":")))))
8181 ((null completion)
8182 (message "Can't find completion for \"%s\"" pattern)
8183 (ding))
8184 ((not (string= pattern completion))
8185 (delete-region beg end)
8186 (if (string-match " +$" completion)
8187 (setq completion (replace-match "" t t completion)))
8188 (insert completion)
8189 (if (get-buffer-window "*Completions*")
8190 (delete-window (get-buffer-window "*Completions*")))
8191 (if (assoc completion table)
8192 (if (eq type :todo) (insert " ")
8193 (if (memq type '(:tag :prop)) (insert ":"))))
8194 (if (and (equal type :opt) (assoc completion table))
8195 (message "%s" (substitute-command-keys
8196 "Press \\[org-complete] again to insert example settings"))))
8198 (message "Making completion list...")
8199 (let ((list (sort (all-completions pattern table confirm)
8200 'string<)))
8201 (with-output-to-temp-buffer "*Completions*"
8202 (condition-case nil
8203 ;; Protection needed for XEmacs and emacs 21
8204 (display-completion-list list pattern)
8205 (error (display-completion-list list)))))
8206 (message "Making completion list...%s" "done")))))))
8208 ;;;; TODO, DEADLINE, Comments
8210 (defun org-toggle-comment ()
8211 "Change the COMMENT state of an entry."
8212 (interactive)
8213 (save-excursion
8214 (org-back-to-heading)
8215 (let (case-fold-search)
8216 (if (looking-at (concat outline-regexp
8217 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8218 (replace-match "" t t nil 1)
8219 (if (looking-at outline-regexp)
8220 (progn
8221 (goto-char (match-end 0))
8222 (insert org-comment-string " ")))))))
8224 (defvar org-last-todo-state-is-todo nil
8225 "This is non-nil when the last TODO state change led to a TODO state.
8226 If the last change removed the TODO tag or switched to DONE, then
8227 this is nil.")
8229 (defvar org-setting-tags nil) ; dynamically skiped
8231 (defun org-parse-local-options (string var)
8232 "Parse STRING for startup setting relevant for variable VAR."
8233 (let ((rtn (symbol-value var))
8234 e opts)
8235 (save-match-data
8236 (if (or (not string) (not (string-match "\\S-" string)))
8238 (setq opts (delq nil (mapcar (lambda (x)
8239 (setq e (assoc x org-startup-options))
8240 (if (eq (nth 1 e) var) e nil))
8241 (org-split-string string "[ \t]+"))))
8242 (if (not opts)
8244 (setq rtn nil)
8245 (while (setq e (pop opts))
8246 (if (not (nth 3 e))
8247 (setq rtn (nth 2 e))
8248 (if (not (listp rtn)) (setq rtn nil))
8249 (push (nth 2 e) rtn)))
8250 rtn)))))
8252 (defvar org-blocker-hook nil
8253 "Hook for functions that are allowed to block a state change.
8255 Each function gets as its single argument a property list, see
8256 `org-trigger-hook' for more information about this list.
8258 If any of the functions in this hook returns nil, the state change
8259 is blocked.")
8261 (defvar org-trigger-hook nil
8262 "Hook for functions that are triggered by a state change.
8264 Each function gets as its single argument a property list with at least
8265 the following elements:
8267 (:type type-of-change :position pos-at-entry-start
8268 :from old-state :to new-state)
8270 Depending on the type, more properties may be present.
8272 This mechanism is currently implemented for:
8274 TODO state changes
8275 ------------------
8276 :type todo-state-change
8277 :from previous state (keyword as a string), or nil
8278 :to new state (keyword as a string), or nil")
8281 (defun org-todo (&optional arg)
8282 "Change the TODO state of an item.
8283 The state of an item is given by a keyword at the start of the heading,
8284 like
8285 *** TODO Write paper
8286 *** DONE Call mom
8288 The different keywords are specified in the variable `org-todo-keywords'.
8289 By default the available states are \"TODO\" and \"DONE\".
8290 So for this example: when the item starts with TODO, it is changed to DONE.
8291 When it starts with DONE, the DONE is removed. And when neither TODO nor
8292 DONE are present, add TODO at the beginning of the heading.
8294 With C-u prefix arg, use completion to determine the new state.
8295 With numeric prefix arg, switch to that state.
8297 For calling through lisp, arg is also interpreted in the following way:
8298 'none -> empty state
8299 \"\"(empty string) -> switch to empty state
8300 'done -> switch to DONE
8301 'nextset -> switch to the next set of keywords
8302 'previousset -> switch to the previous set of keywords
8303 \"WAITING\" -> switch to the specified keyword, but only if it
8304 really is a member of `org-todo-keywords'."
8305 (interactive "P")
8306 (save-excursion
8307 (catch 'exit
8308 (org-back-to-heading)
8309 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8310 (or (looking-at (concat " +" org-todo-regexp " *"))
8311 (looking-at " *"))
8312 (let* ((match-data (match-data))
8313 (startpos (point-at-bol))
8314 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8315 (org-log-done org-log-done)
8316 (org-log-repeat org-log-repeat)
8317 (org-todo-log-states org-todo-log-states)
8318 (this (match-string 1))
8319 (hl-pos (match-beginning 0))
8320 (head (org-get-todo-sequence-head this))
8321 (ass (assoc head org-todo-kwd-alist))
8322 (interpret (nth 1 ass))
8323 (done-word (nth 3 ass))
8324 (final-done-word (nth 4 ass))
8325 (last-state (or this ""))
8326 (completion-ignore-case t)
8327 (member (member this org-todo-keywords-1))
8328 (tail (cdr member))
8329 (state (cond
8330 ((and org-todo-key-trigger
8331 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8332 (and (not arg) org-use-fast-todo-selection
8333 (not (eq org-use-fast-todo-selection 'prefix)))))
8334 ;; Use fast selection
8335 (org-fast-todo-selection))
8336 ((and (equal arg '(4))
8337 (or (not org-use-fast-todo-selection)
8338 (not org-todo-key-trigger)))
8339 ;; Read a state with completion
8340 (completing-read "State: " (mapcar (lambda(x) (list x))
8341 org-todo-keywords-1)
8342 nil t))
8343 ((eq arg 'right)
8344 (if this
8345 (if tail (car tail) nil)
8346 (car org-todo-keywords-1)))
8347 ((eq arg 'left)
8348 (if (equal member org-todo-keywords-1)
8350 (if this
8351 (nth (- (length org-todo-keywords-1) (length tail) 2)
8352 org-todo-keywords-1)
8353 (org-last org-todo-keywords-1))))
8354 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8355 (setq arg nil))) ; hack to fall back to cycling
8356 (arg
8357 ;; user or caller requests a specific state
8358 (cond
8359 ((equal arg "") nil)
8360 ((eq arg 'none) nil)
8361 ((eq arg 'done) (or done-word (car org-done-keywords)))
8362 ((eq arg 'nextset)
8363 (or (car (cdr (member head org-todo-heads)))
8364 (car org-todo-heads)))
8365 ((eq arg 'previousset)
8366 (let ((org-todo-heads (reverse org-todo-heads)))
8367 (or (car (cdr (member head org-todo-heads)))
8368 (car org-todo-heads))))
8369 ((car (member arg org-todo-keywords-1)))
8370 ((nth (1- (prefix-numeric-value arg))
8371 org-todo-keywords-1))))
8372 ((null member) (or head (car org-todo-keywords-1)))
8373 ((equal this final-done-word) nil) ;; -> make empty
8374 ((null tail) nil) ;; -> first entry
8375 ((eq interpret 'sequence)
8376 (car tail))
8377 ((memq interpret '(type priority))
8378 (if (eq this-command last-command)
8379 (car tail)
8380 (if (> (length tail) 0)
8381 (or done-word (car org-done-keywords))
8382 nil)))
8383 (t nil)))
8384 (next (if state (concat " " state " ") " "))
8385 (change-plist (list :type 'todo-state-change :from this :to state
8386 :position startpos))
8387 dolog now-done-p)
8388 (when org-blocker-hook
8389 (unless (save-excursion
8390 (save-match-data
8391 (run-hook-with-args-until-failure
8392 'org-blocker-hook change-plist)))
8393 (if (interactive-p)
8394 (error "TODO state change from %s to %s blocked" this state)
8395 ;; fail silently
8396 (message "TODO state change from %s to %s blocked" this state)
8397 (throw 'exit nil))))
8398 (store-match-data match-data)
8399 (replace-match next t t)
8400 (unless (pos-visible-in-window-p hl-pos)
8401 (message "TODO state changed to %s" (org-trim next)))
8402 (unless head
8403 (setq head (org-get-todo-sequence-head state)
8404 ass (assoc head org-todo-kwd-alist)
8405 interpret (nth 1 ass)
8406 done-word (nth 3 ass)
8407 final-done-word (nth 4 ass)))
8408 (when (memq arg '(nextset previousset))
8409 (message "Keyword-Set %d/%d: %s"
8410 (- (length org-todo-sets) -1
8411 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8412 (length org-todo-sets)
8413 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8414 (setq org-last-todo-state-is-todo
8415 (not (member state org-done-keywords)))
8416 (setq now-done-p (and (member state org-done-keywords)
8417 (not (member this org-done-keywords))))
8418 (and logging (org-local-logging logging))
8419 (when (and (or org-todo-log-states org-log-done)
8420 (not (memq arg '(nextset previousset))))
8421 ;; we need to look at recording a time and note
8422 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8423 (nth 2 (assoc this org-todo-log-states))))
8424 (when (and state
8425 (member state org-not-done-keywords)
8426 (not (member this org-not-done-keywords)))
8427 ;; This is now a todo state and was not one before
8428 ;; If there was a CLOSED time stamp, get rid of it.
8429 (org-add-planning-info nil nil 'closed))
8430 (when (and now-done-p org-log-done)
8431 ;; It is now done, and it was not done before
8432 (org-add-planning-info 'closed (org-current-time))
8433 (if (and (not dolog) (eq 'note org-log-done))
8434 (org-add-log-setup 'done state 'findpos 'note)))
8435 (when (and state dolog)
8436 ;; This is a non-nil state, and we need to log it
8437 (org-add-log-setup 'state state 'findpos dolog)))
8438 ;; Fixup tag positioning
8439 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8440 (when org-provide-todo-statistics
8441 (org-update-parent-todo-statistics))
8442 (run-hooks 'org-after-todo-state-change-hook)
8443 (if (and arg (not (member state org-done-keywords)))
8444 (setq head (org-get-todo-sequence-head state)))
8445 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8446 ;; Do we need to trigger a repeat?
8447 (when now-done-p (org-auto-repeat-maybe state))
8448 ;; Fixup cursor location if close to the keyword
8449 (if (and (outline-on-heading-p)
8450 (not (bolp))
8451 (save-excursion (beginning-of-line 1)
8452 (looking-at org-todo-line-regexp))
8453 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8454 (progn
8455 (goto-char (or (match-end 2) (match-end 1)))
8456 (just-one-space)))
8457 (when org-trigger-hook
8458 (save-excursion
8459 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8461 (defun org-update-parent-todo-statistics ()
8462 "Update any statistics cookie in the parent of the current headline."
8463 (interactive)
8464 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8465 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8466 (catch 'exit
8467 (save-excursion
8468 (setq level (org-up-heading-safe))
8469 (unless (and level
8470 (re-search-forward box-re (point-at-eol) t))
8471 (throw 'exit nil))
8472 (setq is-percent (match-end 2))
8473 (save-match-data
8474 (unless (outline-next-heading) (throw 'exit nil))
8475 (while (looking-at org-todo-line-regexp)
8476 (setq kwd (match-string 2))
8477 (and kwd (setq cnt-all (1+ cnt-all)))
8478 (and (member kwd org-done-keywords)
8479 (setq cnt-done (1+ cnt-done)))
8480 (condition-case nil
8481 (outline-forward-same-level 1)
8482 (error (end-of-line 1)))))
8483 (replace-match
8484 (if is-percent
8485 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8486 (format "[%d/%d]" cnt-done cnt-all)))
8487 (run-hook-with-args 'org-after-todo-statistics-hook
8488 cnt-done (- cnt-all cnt-done))))))
8490 (defvar org-after-todo-statistics-hook nil
8491 "Hook that is called after a TODO statistics cookie has been updated.
8492 Each function is called with two arguments: the number of not-done entries
8493 and the number of done entries.
8495 For example, the following function, when added to this hook, will switch
8496 an entry to DONE when all children are done, and back to TODO when new
8497 entries are set to a TODO status. Note that this hook is only called
8498 when there is a statistics cookie in the headline!
8500 (defun org-summary-todo (n-done n-not-done)
8501 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8502 (let (org-log-done org-log-states) ; turn off logging
8503 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8506 (defun org-local-logging (value)
8507 "Get logging settings from a property VALUE."
8508 (let* (words w a)
8509 ;; directly set the variables, they are already local.
8510 (setq org-log-done nil
8511 org-log-repeat nil
8512 org-todo-log-states nil)
8513 (setq words (org-split-string value))
8514 (while (setq w (pop words))
8515 (cond
8516 ((setq a (assoc w org-startup-options))
8517 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8518 (set (nth 1 a) (nth 2 a))))
8519 ((setq a (org-extract-log-state-settings w))
8520 (and (member (car a) org-todo-keywords-1)
8521 (push a org-todo-log-states)))))))
8523 (defun org-get-todo-sequence-head (kwd)
8524 "Return the head of the TODO sequence to which KWD belongs.
8525 If KWD is not set, check if there is a text property remembering the
8526 right sequence."
8527 (let (p)
8528 (cond
8529 ((not kwd)
8530 (or (get-text-property (point-at-bol) 'org-todo-head)
8531 (progn
8532 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8533 nil (point-at-eol)))
8534 (get-text-property p 'org-todo-head))))
8535 ((not (member kwd org-todo-keywords-1))
8536 (car org-todo-keywords-1))
8537 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8539 (defun org-fast-todo-selection ()
8540 "Fast TODO keyword selection with single keys.
8541 Returns the new TODO keyword, or nil if no state change should occur."
8542 (let* ((fulltable org-todo-key-alist)
8543 (done-keywords org-done-keywords) ;; needed for the faces.
8544 (maxlen (apply 'max (mapcar
8545 (lambda (x)
8546 (if (stringp (car x)) (string-width (car x)) 0))
8547 fulltable)))
8548 (expert nil)
8549 (fwidth (+ maxlen 3 1 3))
8550 (ncol (/ (- (window-width) 4) fwidth))
8551 tg cnt e c tbl
8552 groups ingroup)
8553 (save-window-excursion
8554 (if expert
8555 (set-buffer (get-buffer-create " *Org todo*"))
8556 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8557 (erase-buffer)
8558 (org-set-local 'org-done-keywords done-keywords)
8559 (setq tbl fulltable cnt 0)
8560 (while (setq e (pop tbl))
8561 (cond
8562 ((equal e '(:startgroup))
8563 (push '() groups) (setq ingroup t)
8564 (when (not (= cnt 0))
8565 (setq cnt 0)
8566 (insert "\n"))
8567 (insert "{ "))
8568 ((equal e '(:endgroup))
8569 (setq ingroup nil cnt 0)
8570 (insert "}\n"))
8572 (setq tg (car e) c (cdr e))
8573 (if ingroup (push tg (car groups)))
8574 (setq tg (org-add-props tg nil 'face
8575 (org-get-todo-face tg)))
8576 (if (and (= cnt 0) (not ingroup)) (insert " "))
8577 (insert "[" c "] " tg (make-string
8578 (- fwidth 4 (length tg)) ?\ ))
8579 (when (= (setq cnt (1+ cnt)) ncol)
8580 (insert "\n")
8581 (if ingroup (insert " "))
8582 (setq cnt 0)))))
8583 (insert "\n")
8584 (goto-char (point-min))
8585 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8586 (fit-window-to-buffer))
8587 (message "[a-z..]:Set [SPC]:clear")
8588 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8589 (cond
8590 ((or (= c ?\C-g)
8591 (and (= c ?q) (not (rassoc c fulltable))))
8592 (setq quit-flag t))
8593 ((= c ?\ ) nil)
8594 ((setq e (rassoc c fulltable) tg (car e))
8596 (t (setq quit-flag t))))))
8598 (defun org-entry-is-todo-p ()
8599 (member (org-get-todo-state) org-not-done-keywords))
8601 (defun org-entry-is-done-p ()
8602 (member (org-get-todo-state) org-done-keywords))
8604 (defun org-get-todo-state ()
8605 (save-excursion
8606 (org-back-to-heading t)
8607 (and (looking-at org-todo-line-regexp)
8608 (match-end 2)
8609 (match-string 2))))
8611 (defun org-at-date-range-p (&optional inactive-ok)
8612 "Is the cursor inside a date range?"
8613 (interactive)
8614 (save-excursion
8615 (catch 'exit
8616 (let ((pos (point)))
8617 (skip-chars-backward "^[<\r\n")
8618 (skip-chars-backward "<[")
8619 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8620 (>= (match-end 0) pos)
8621 (throw 'exit t))
8622 (skip-chars-backward "^<[\r\n")
8623 (skip-chars-backward "<[")
8624 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8625 (>= (match-end 0) pos)
8626 (throw 'exit t)))
8627 nil)))
8629 (defun org-get-repeat ()
8630 "Check if there is a deadline/schedule with repeater in this entry."
8631 (save-match-data
8632 (save-excursion
8633 (org-back-to-heading t)
8634 (if (re-search-forward
8635 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8636 (match-string 1)))))
8638 (defvar org-last-changed-timestamp)
8639 (defvar org-last-inserted-timestamp)
8640 (defvar org-log-post-message)
8641 (defvar org-log-note-purpose)
8642 (defvar org-log-note-how)
8643 (defun org-auto-repeat-maybe (done-word)
8644 "Check if the current headline contains a repeated deadline/schedule.
8645 If yes, set TODO state back to what it was and change the base date
8646 of repeating deadline/scheduled time stamps to new date.
8647 This function is run automatically after each state change to a DONE state."
8648 ;; last-state is dynamically scoped into this function
8649 (let* ((repeat (org-get-repeat))
8650 (aa (assoc last-state org-todo-kwd-alist))
8651 (interpret (nth 1 aa))
8652 (head (nth 2 aa))
8653 (whata '(("d" . day) ("m" . month) ("y" . year)))
8654 (msg "Entry repeats: ")
8655 (org-log-done nil)
8656 (org-todo-log-states nil)
8657 (nshiftmax 10) (nshift 0)
8658 re type n what ts mb0 time)
8659 (when repeat
8660 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8661 (org-todo (if (eq interpret 'type) last-state head))
8662 (when org-log-repeat
8663 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8664 (memq 'org-add-log-note post-command-hook))
8665 ;; OK, we are already setup for some record
8666 (if (eq org-log-repeat 'note)
8667 ;; make sure we take a note, not only a time stamp
8668 (setq org-log-note-how 'note))
8669 ;; Set up for taking a record
8670 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8671 'findpos org-log-repeat)))
8672 (org-back-to-heading t)
8673 (org-add-planning-info nil nil 'closed)
8674 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8675 org-deadline-time-regexp "\\)\\|\\("
8676 org-ts-regexp "\\)"))
8677 (while (re-search-forward
8678 re (save-excursion (outline-next-heading) (point)) t)
8679 (setq type (if (match-end 1) org-scheduled-string
8680 (if (match-end 3) org-deadline-string "Plain:"))
8681 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8682 mb0 (match-beginning 0))
8683 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8684 (setq n (string-to-number (match-string 2 ts))
8685 what (match-string 3 ts))
8686 (if (equal what "w") (setq n (* n 7) what "d"))
8687 ;; Preparation, see if we need to modify the start date for the change
8688 (when (match-end 1)
8689 (setq time (save-match-data (org-time-string-to-time ts)))
8690 (cond
8691 ((equal (match-string 1 ts) ".")
8692 ;; Shift starting date to today
8693 (org-timestamp-change
8694 (- (time-to-days (current-time)) (time-to-days time))
8695 'day))
8696 ((equal (match-string 1 ts) "+")
8697 (while (or (= nshift 0)
8698 (<= (time-to-days time) (time-to-days (current-time))))
8699 (when (= (incf nshift) nshiftmax)
8700 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8701 (error "Abort")))
8702 (org-timestamp-change n (cdr (assoc what whata)))
8703 (org-at-timestamp-p t)
8704 (setq ts (match-string 1))
8705 (setq time (save-match-data (org-time-string-to-time ts))))
8706 (org-timestamp-change (- n) (cdr (assoc what whata)))
8707 ;; rematch, so that we have everything in place for the real shift
8708 (org-at-timestamp-p t)
8709 (setq ts (match-string 1))
8710 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8711 (org-timestamp-change n (cdr (assoc what whata)))
8712 (setq msg (concat msg type org-last-changed-timestamp " "))))
8713 (setq org-log-post-message msg)
8714 (message "%s" msg))))
8716 (defun org-show-todo-tree (arg)
8717 "Make a compact tree which shows all headlines marked with TODO.
8718 The tree will show the lines where the regexp matches, and all higher
8719 headlines above the match.
8720 With a \\[universal-argument] prefix, also show the DONE entries.
8721 With a numeric prefix N, construct a sparse tree for the Nth element
8722 of `org-todo-keywords-1'."
8723 (interactive "P")
8724 (let ((case-fold-search nil)
8725 (kwd-re
8726 (cond ((null arg) org-not-done-regexp)
8727 ((equal arg '(4))
8728 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8729 (mapcar 'list org-todo-keywords-1))))
8730 (concat "\\("
8731 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8732 "\\)\\>")))
8733 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8734 (regexp-quote (nth (1- (prefix-numeric-value arg))
8735 org-todo-keywords-1)))
8736 (t (error "Invalid prefix argument: %s" arg)))))
8737 (message "%d TODO entries found"
8738 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8740 (defun org-deadline (&optional remove time)
8741 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8742 With argument REMOVE, remove any deadline from the item.
8743 When TIME is set, it should be an internal time specification, and the
8744 scheduling will use the corresponding date."
8745 (interactive "P")
8746 (if remove
8747 (progn
8748 (org-remove-timestamp-with-keyword org-deadline-string)
8749 (message "Item no longer has a deadline."))
8750 (if (org-get-repeat)
8751 (error "Cannot change deadline on task with repeater, please do that by hand")
8752 (org-add-planning-info 'deadline time 'closed)
8753 (message "Deadline on %s" org-last-inserted-timestamp))))
8755 (defun org-schedule (&optional remove time)
8756 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8757 With argument REMOVE, remove any scheduling date from the item.
8758 When TIME is set, it should be an internal time specification, and the
8759 scheduling will use the corresponding date."
8760 (interactive "P")
8761 (if remove
8762 (progn
8763 (org-remove-timestamp-with-keyword org-scheduled-string)
8764 (message "Item is no longer scheduled."))
8765 (if (org-get-repeat)
8766 (error "Cannot reschedule task with repeater, please do that by hand")
8767 (org-add-planning-info 'scheduled time 'closed)
8768 (message "Scheduled to %s" org-last-inserted-timestamp))))
8770 (defun org-remove-timestamp-with-keyword (keyword)
8771 "Remove all time stamps with KEYWORD in the current entry."
8772 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8773 beg)
8774 (save-excursion
8775 (org-back-to-heading t)
8776 (setq beg (point))
8777 (org-end-of-subtree t t)
8778 (while (re-search-backward re beg t)
8779 (replace-match "")
8780 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8781 (equal (char-before) ?\ ))
8782 (backward-delete-char 1)
8783 (if (string-match "^[ \t]*$" (buffer-substring
8784 (point-at-bol) (point-at-eol)))
8785 (delete-region (point-at-bol)
8786 (min (point-max) (1+ (point-at-eol))))))))))
8788 (defun org-add-planning-info (what &optional time &rest remove)
8789 "Insert new timestamp with keyword in the line directly after the headline.
8790 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8791 If non is given, the user is prompted for a date.
8792 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8793 be removed."
8794 (interactive)
8795 (let (org-time-was-given org-end-time-was-given ts
8796 end default-time default-input)
8798 (when (and (not time) (memq what '(scheduled deadline)))
8799 ;; Try to get a default date/time from existing timestamp
8800 (save-excursion
8801 (org-back-to-heading t)
8802 (setq end (save-excursion (outline-next-heading) (point)))
8803 (when (re-search-forward (if (eq what 'scheduled)
8804 org-scheduled-time-regexp
8805 org-deadline-time-regexp)
8806 end t)
8807 (setq ts (match-string 1)
8808 default-time
8809 (apply 'encode-time (org-parse-time-string ts))
8810 default-input (and ts (org-get-compact-tod ts))))))
8811 (when what
8812 ;; If necessary, get the time from the user
8813 (setq time (or time (org-read-date nil 'to-time nil nil
8814 default-time default-input))))
8816 (when (and org-insert-labeled-timestamps-at-point
8817 (member what '(scheduled deadline)))
8818 (insert
8819 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8820 (org-insert-time-stamp time org-time-was-given
8821 nil nil nil (list org-end-time-was-given))
8822 (setq what nil))
8823 (save-excursion
8824 (save-restriction
8825 (let (col list elt ts buffer-invisibility-spec)
8826 (org-back-to-heading t)
8827 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8828 (goto-char (match-end 1))
8829 (setq col (current-column))
8830 (goto-char (match-end 0))
8831 (if (eobp) (insert "\n") (forward-char 1))
8832 (if (and (not (looking-at outline-regexp))
8833 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8834 "[^\r\n]*"))
8835 (not (equal (match-string 1) org-clock-string)))
8836 (narrow-to-region (match-beginning 0) (match-end 0))
8837 (insert-before-markers "\n")
8838 (backward-char 1)
8839 (narrow-to-region (point) (point))
8840 (and org-adapt-indentation (org-indent-to-column col)))
8841 ;; Check if we have to remove something.
8842 (setq list (cons what remove))
8843 (while list
8844 (setq elt (pop list))
8845 (goto-char (point-min))
8846 (when (or (and (eq elt 'scheduled)
8847 (re-search-forward org-scheduled-time-regexp nil t))
8848 (and (eq elt 'deadline)
8849 (re-search-forward org-deadline-time-regexp nil t))
8850 (and (eq elt 'closed)
8851 (re-search-forward org-closed-time-regexp nil t)))
8852 (replace-match "")
8853 (if (looking-at "--+<[^>]+>") (replace-match ""))
8854 (if (looking-at " +") (replace-match ""))))
8855 (goto-char (point-max))
8856 (when what
8857 (insert
8858 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8859 (cond ((eq what 'scheduled) org-scheduled-string)
8860 ((eq what 'deadline) org-deadline-string)
8861 ((eq what 'closed) org-closed-string))
8862 " ")
8863 (setq ts (org-insert-time-stamp
8864 time
8865 (or org-time-was-given
8866 (and (eq what 'closed) org-log-done-with-time))
8867 (eq what 'closed)
8868 nil nil (list org-end-time-was-given)))
8869 (end-of-line 1))
8870 (goto-char (point-min))
8871 (widen)
8872 (if (and (looking-at "[ \t]+\n")
8873 (equal (char-before) ?\n))
8874 (delete-region (1- (point)) (point-at-eol)))
8875 ts)))))
8877 (defvar org-log-note-marker (make-marker))
8878 (defvar org-log-note-purpose nil)
8879 (defvar org-log-note-state nil)
8880 (defvar org-log-note-how nil)
8881 (defvar org-log-note-window-configuration nil)
8882 (defvar org-log-note-return-to (make-marker))
8883 (defvar org-log-post-message nil
8884 "Message to be displayed after a log note has been stored.
8885 The auto-repeater uses this.")
8887 (defun org-add-note ()
8888 "Add a note to the current entry.
8889 This is done in the same way as adding a state change note."
8890 (interactive)
8891 (org-add-log-setup 'note nil t nil))
8893 (defun org-add-log-setup (&optional purpose state findpos how)
8894 "Set up the post command hook to take a note.
8895 If this is about to TODO state change, the new state is expected in STATE.
8896 When FINDPOS is non-nil, find the correct position for the note in
8897 the current entry. If not, assume that it can be inserted at point."
8898 (save-excursion
8899 (when findpos
8900 (org-back-to-heading t)
8901 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8902 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8903 "[^\r\n]*\\)?"))
8904 (goto-char (match-end 0))
8905 (unless org-log-states-order-reversed
8906 (and (= (char-after) ?\n) (forward-char 1))
8907 (org-skip-over-state-notes)
8908 (skip-chars-backward " \t\n\r")))
8909 (move-marker org-log-note-marker (point))
8910 (setq org-log-note-purpose purpose
8911 org-log-note-state state
8912 org-log-note-how how)
8913 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8915 (defun org-skip-over-state-notes ()
8916 "Skip past the list of State notes in an entry."
8917 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8918 (while (looking-at "[ \t]*- State")
8919 (condition-case nil
8920 (org-next-item)
8921 (error (org-end-of-item)))))
8923 (defun org-add-log-note (&optional purpose)
8924 "Pop up a window for taking a note, and add this note later at point."
8925 (remove-hook 'post-command-hook 'org-add-log-note)
8926 (setq org-log-note-window-configuration (current-window-configuration))
8927 (delete-other-windows)
8928 (move-marker org-log-note-return-to (point))
8929 (switch-to-buffer (marker-buffer org-log-note-marker))
8930 (goto-char org-log-note-marker)
8931 (org-switch-to-buffer-other-window "*Org Note*")
8932 (erase-buffer)
8933 (if (memq org-log-note-how '(time state))
8934 (org-store-log-note)
8935 (let ((org-inhibit-startup t)) (org-mode))
8936 (insert (format "# Insert note for %s.
8937 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8938 (cond
8939 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8940 ((eq org-log-note-purpose 'done) "closed todo item")
8941 ((eq org-log-note-purpose 'state)
8942 (format "state change to \"%s\"" org-log-note-state))
8943 ((eq org-log-note-purpose 'note)
8944 "this entry")
8945 (t (error "This should not happen")))))
8946 (org-set-local 'org-finish-function 'org-store-log-note)))
8948 (defvar org-note-abort nil) ; dynamically scoped
8949 (defun org-store-log-note ()
8950 "Finish taking a log note, and insert it to where it belongs."
8951 (let ((txt (buffer-string))
8952 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8953 lines ind)
8954 (kill-buffer (current-buffer))
8955 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8956 (setq txt (replace-match "" t t txt)))
8957 (if (string-match "\\s-+\\'" txt)
8958 (setq txt (replace-match "" t t txt)))
8959 (setq lines (org-split-string txt "\n"))
8960 (when (and note (string-match "\\S-" note))
8961 (setq note
8962 (org-replace-escapes
8963 note
8964 (list (cons "%u" (user-login-name))
8965 (cons "%U" user-full-name)
8966 (cons "%t" (format-time-string
8967 (org-time-stamp-format 'long 'inactive)
8968 (current-time)))
8969 (cons "%s" (if org-log-note-state
8970 (concat "\"" org-log-note-state "\"")
8971 "")))))
8972 (if lines (setq note (concat note " \\\\")))
8973 (push note lines))
8974 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8975 (when lines
8976 (save-excursion
8977 (set-buffer (marker-buffer org-log-note-marker))
8978 (save-excursion
8979 (goto-char org-log-note-marker)
8980 (move-marker org-log-note-marker nil)
8981 (end-of-line 1)
8982 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8983 (indent-relative nil)
8984 (insert "- " (pop lines))
8985 (org-indent-line-function)
8986 (beginning-of-line 1)
8987 (looking-at "[ \t]*")
8988 (setq ind (concat (match-string 0) " "))
8989 (end-of-line 1)
8990 (while lines (insert "\n" ind (pop lines)))))))
8991 (set-window-configuration org-log-note-window-configuration)
8992 (with-current-buffer (marker-buffer org-log-note-return-to)
8993 (goto-char org-log-note-return-to))
8994 (move-marker org-log-note-return-to nil)
8995 (and org-log-post-message (message "%s" org-log-post-message)))
8997 (defun org-sparse-tree (&optional arg)
8998 "Create a sparse tree, prompt for the details.
8999 This command can create sparse trees. You first need to select the type
9000 of match used to create the tree:
9002 t Show entries with a specific TODO keyword.
9003 T Show entries selected by a tags match.
9004 p Enter a property name and its value (both with completion on existing
9005 names/values) and show entries with that property.
9006 r Show entries matching a regular expression
9007 d Show deadlines due within `org-deadline-warning-days'."
9008 (interactive "P")
9009 (let (ans kwd value)
9010 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9011 (setq ans (read-char-exclusive))
9012 (cond
9013 ((equal ans ?d)
9014 (call-interactively 'org-check-deadlines))
9015 ((equal ans ?b)
9016 (call-interactively 'org-check-before-date))
9017 ((equal ans ?t)
9018 (org-show-todo-tree '(4)))
9019 ((equal ans ?T)
9020 (call-interactively 'org-tags-sparse-tree))
9021 ((member ans '(?p ?P))
9022 (setq kwd (completing-read "Property: "
9023 (mapcar 'list (org-buffer-property-keys))))
9024 (setq value (completing-read "Value: "
9025 (mapcar 'list (org-property-values kwd))))
9026 (unless (string-match "\\`{.*}\\'" value)
9027 (setq value (concat "\"" value "\"")))
9028 (org-tags-sparse-tree arg (concat kwd "=" value)))
9029 ((member ans '(?r ?R ?/))
9030 (call-interactively 'org-occur))
9031 (t (error "No such sparse tree command \"%c\"" ans)))))
9033 (defvar org-occur-highlights nil
9034 "List of overlays used for occur matches.")
9035 (make-variable-buffer-local 'org-occur-highlights)
9036 (defvar org-occur-parameters nil
9037 "Parameters of the active org-occur calls.
9038 This is a list, each call to org-occur pushes as cons cell,
9039 containing the regular expression and the callback, onto the list.
9040 The list can contain several entries if `org-occur' has been called
9041 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9042 will only contain one set of parameters. When the highlights are
9043 removed (for example with `C-c C-c', or with the next edit (depending
9044 on `org-remove-highlights-with-change'), this variable is emptied
9045 as well.")
9046 (make-variable-buffer-local 'org-occur-parameters)
9048 (defun org-occur (regexp &optional keep-previous callback)
9049 "Make a compact tree which shows all matches of REGEXP.
9050 The tree will show the lines where the regexp matches, and all higher
9051 headlines above the match. It will also show the heading after the match,
9052 to make sure editing the matching entry is easy.
9053 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9054 call to `org-occur' will be kept, to allow stacking of calls to this
9055 command.
9056 If CALLBACK is non-nil, it is a function which is called to confirm
9057 that the match should indeed be shown."
9058 (interactive "sRegexp: \nP")
9059 (unless keep-previous
9060 (org-remove-occur-highlights nil nil t))
9061 (push (cons regexp callback) org-occur-parameters)
9062 (let ((cnt 0))
9063 (save-excursion
9064 (goto-char (point-min))
9065 (if (or (not keep-previous) ; do not want to keep
9066 (not org-occur-highlights)) ; no previous matches
9067 ;; hide everything
9068 (org-overview))
9069 (while (re-search-forward regexp nil t)
9070 (when (or (not callback)
9071 (save-match-data (funcall callback)))
9072 (setq cnt (1+ cnt))
9073 (when org-highlight-sparse-tree-matches
9074 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9075 (org-show-context 'occur-tree))))
9076 (when org-remove-highlights-with-change
9077 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9078 nil 'local))
9079 (unless org-sparse-tree-open-archived-trees
9080 (org-hide-archived-subtrees (point-min) (point-max)))
9081 (run-hooks 'org-occur-hook)
9082 (if (interactive-p)
9083 (message "%d match(es) for regexp %s" cnt regexp))
9084 cnt))
9086 (defun org-show-context (&optional key)
9087 "Make sure point and context and visible.
9088 How much context is shown depends upon the variables
9089 `org-show-hierarchy-above', `org-show-following-heading'. and
9090 `org-show-siblings'."
9091 (let ((heading-p (org-on-heading-p t))
9092 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9093 (following-p (org-get-alist-option org-show-following-heading key))
9094 (entry-p (org-get-alist-option org-show-entry-below key))
9095 (siblings-p (org-get-alist-option org-show-siblings key)))
9096 (catch 'exit
9097 ;; Show heading or entry text
9098 (if (and heading-p (not entry-p))
9099 (org-flag-heading nil) ; only show the heading
9100 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9101 (org-show-hidden-entry))) ; show entire entry
9102 (when following-p
9103 ;; Show next sibling, or heading below text
9104 (save-excursion
9105 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9106 (org-flag-heading nil))))
9107 (when siblings-p (org-show-siblings))
9108 (when hierarchy-p
9109 ;; show all higher headings, possibly with siblings
9110 (save-excursion
9111 (while (and (condition-case nil
9112 (progn (org-up-heading-all 1) t)
9113 (error nil))
9114 (not (bobp)))
9115 (org-flag-heading nil)
9116 (when siblings-p (org-show-siblings))))))))
9118 (defun org-reveal (&optional siblings)
9119 "Show current entry, hierarchy above it, and the following headline.
9120 This can be used to show a consistent set of context around locations
9121 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9122 not t for the search context.
9124 With optional argument SIBLINGS, on each level of the hierarchy all
9125 siblings are shown. This repairs the tree structure to what it would
9126 look like when opened with hierarchical calls to `org-cycle'."
9127 (interactive "P")
9128 (let ((org-show-hierarchy-above t)
9129 (org-show-following-heading t)
9130 (org-show-siblings (if siblings t org-show-siblings)))
9131 (org-show-context nil)))
9133 (defun org-highlight-new-match (beg end)
9134 "Highlight from BEG to END and mark the highlight is an occur headline."
9135 (let ((ov (org-make-overlay beg end)))
9136 (org-overlay-put ov 'face 'secondary-selection)
9137 (push ov org-occur-highlights)))
9139 (defun org-remove-occur-highlights (&optional beg end noremove)
9140 "Remove the occur highlights from the buffer.
9141 BEG and END are ignored. If NOREMOVE is nil, remove this function
9142 from the `before-change-functions' in the current buffer."
9143 (interactive)
9144 (unless org-inhibit-highlight-removal
9145 (mapc 'org-delete-overlay org-occur-highlights)
9146 (setq org-occur-highlights nil)
9147 (setq org-occur-parameters nil)
9148 (unless noremove
9149 (remove-hook 'before-change-functions
9150 'org-remove-occur-highlights 'local))))
9152 ;;;; Priorities
9154 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9155 "Regular expression matching the priority indicator.")
9157 (defvar org-remove-priority-next-time nil)
9159 (defun org-priority-up ()
9160 "Increase the priority of the current item."
9161 (interactive)
9162 (org-priority 'up))
9164 (defun org-priority-down ()
9165 "Decrease the priority of the current item."
9166 (interactive)
9167 (org-priority 'down))
9169 (defun org-priority (&optional action)
9170 "Change the priority of an item by ARG.
9171 ACTION can be `set', `up', `down', or a character."
9172 (interactive)
9173 (setq action (or action 'set))
9174 (let (current new news have remove)
9175 (save-excursion
9176 (org-back-to-heading)
9177 (if (looking-at org-priority-regexp)
9178 (setq current (string-to-char (match-string 2))
9179 have t)
9180 (setq current org-default-priority))
9181 (cond
9182 ((or (eq action 'set)
9183 (if (featurep 'xemacs) (characterp action) (integerp action)))
9184 (if (not (eq action 'set))
9185 (setq new action)
9186 (message "Priority %c-%c, SPC to remove: "
9187 org-highest-priority org-lowest-priority)
9188 (setq new (read-char-exclusive)))
9189 (if (and (= (upcase org-highest-priority) org-highest-priority)
9190 (= (upcase org-lowest-priority) org-lowest-priority))
9191 (setq new (upcase new)))
9192 (cond ((equal new ?\ ) (setq remove t))
9193 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9194 (error "Priority must be between `%c' and `%c'"
9195 org-highest-priority org-lowest-priority))))
9196 ((eq action 'up)
9197 (if (and (not have) (eq last-command this-command))
9198 (setq new org-lowest-priority)
9199 (setq new (if (and org-priority-start-cycle-with-default (not have))
9200 org-default-priority (1- current)))))
9201 ((eq action 'down)
9202 (if (and (not have) (eq last-command this-command))
9203 (setq new org-highest-priority)
9204 (setq new (if (and org-priority-start-cycle-with-default (not have))
9205 org-default-priority (1+ current)))))
9206 (t (error "Invalid action")))
9207 (if (or (< (upcase new) org-highest-priority)
9208 (> (upcase new) org-lowest-priority))
9209 (setq remove t))
9210 (setq news (format "%c" new))
9211 (if have
9212 (if remove
9213 (replace-match "" t t nil 1)
9214 (replace-match news t t nil 2))
9215 (if remove
9216 (error "No priority cookie found in line")
9217 (looking-at org-todo-line-regexp)
9218 (if (match-end 2)
9219 (progn
9220 (goto-char (match-end 2))
9221 (insert " [#" news "]"))
9222 (goto-char (match-beginning 3))
9223 (insert "[#" news "] ")))))
9224 (org-preserve-lc (org-set-tags nil 'align))
9225 (if remove
9226 (message "Priority removed")
9227 (message "Priority of current item set to %s" news))))
9230 (defun org-get-priority (s)
9231 "Find priority cookie and return priority."
9232 (save-match-data
9233 (if (not (string-match org-priority-regexp s))
9234 (* 1000 (- org-lowest-priority org-default-priority))
9235 (* 1000 (- org-lowest-priority
9236 (string-to-char (match-string 2 s)))))))
9238 ;;;; Tags
9240 (defvar org-agenda-archives-mode)
9241 (defun org-scan-tags (action matcher &optional todo-only)
9242 "Scan headline tags with inheritance and produce output ACTION.
9244 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9245 or `agenda' to produce an entry list for an agenda view. It can also be
9246 a Lisp form or a function that should be called at each matched headline, in
9247 this case the return value is a list of all return values from these calls.
9249 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9250 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9251 only lines with a TODO keyword are included in the output."
9252 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9253 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9254 (org-re
9255 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9256 (props (list 'face nil
9257 'done-face 'org-done
9258 'undone-face nil
9259 'mouse-face 'highlight
9260 'org-not-done-regexp org-not-done-regexp
9261 'org-todo-regexp org-todo-regexp
9262 'keymap org-agenda-keymap
9263 'help-echo
9264 (format "mouse-2 or RET jump to org file %s"
9265 (abbreviate-file-name
9266 (or (buffer-file-name (buffer-base-buffer))
9267 (buffer-name (buffer-base-buffer)))))))
9268 (case-fold-search nil)
9269 lspos tags tags-list
9270 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9271 (llast 0) rtn rtn1 level category i txt
9272 todo marker entry priority)
9273 (when (not (member action '(agenda sparse-tree)))
9274 (setq action (list 'lambda nil action)))
9275 (save-excursion
9276 (goto-char (point-min))
9277 (when (eq action 'sparse-tree)
9278 (org-overview)
9279 (org-remove-occur-highlights))
9280 (while (re-search-forward re nil t)
9281 (catch :skip
9282 (setq todo (if (match-end 1) (match-string 2))
9283 tags (if (match-end 4) (match-string 4)))
9284 (goto-char (setq lspos (1+ (match-beginning 0))))
9285 (setq level (org-reduced-level (funcall outline-level))
9286 category (org-get-category))
9287 (setq i llast llast level)
9288 ;; remove tag lists from same and sublevels
9289 (while (>= i level)
9290 (when (setq entry (assoc i tags-alist))
9291 (setq tags-alist (delete entry tags-alist)))
9292 (setq i (1- i)))
9293 ;; add the next tags
9294 (when tags
9295 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9296 tags-alist
9297 (cons (cons level tags) tags-alist)))
9298 ;; compile tags for current headline
9299 (setq tags-list
9300 (if org-use-tag-inheritance
9301 (apply 'append (mapcar 'cdr tags-alist))
9302 tags))
9303 (when (and tags org-use-tag-inheritance
9304 (not (eq t org-use-tag-inheritance)))
9305 ;; selective inheritance, remove uninherited ones
9306 (setcdr (car tags-alist)
9307 (org-remove-uniherited-tags (cdar tags-alist))))
9308 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9309 (eval matcher)
9311 (not (member org-archive-tag tags-list))
9312 ;; we have an archive tag, should we use this anyway?
9313 (or (not org-agenda-skip-archived-trees)
9314 (and (eq action 'agenda) org-agenda-archives-mode))))
9315 (unless (eq action 'sparse-tree) (org-agenda-skip))
9317 ;; select this headline
9319 (cond
9320 ((eq action 'sparse-tree)
9321 (and org-highlight-sparse-tree-matches
9322 (org-get-heading) (match-end 0)
9323 (org-highlight-new-match
9324 (match-beginning 0) (match-beginning 1)))
9325 (org-show-context 'tags-tree))
9326 ((eq action 'agenda)
9327 (setq txt (org-format-agenda-item
9329 (concat
9330 (if org-tags-match-list-sublevels
9331 (make-string (1- level) ?.) "")
9332 (org-get-heading))
9333 category tags-list)
9334 priority (org-get-priority txt))
9335 (goto-char lspos)
9336 (setq marker (org-agenda-new-marker))
9337 (org-add-props txt props
9338 'org-marker marker 'org-hd-marker marker 'org-category category
9339 'priority priority 'type "tagsmatch")
9340 (push txt rtn))
9341 ((functionp action)
9342 (save-excursion
9343 (setq rtn1 (funcall action))
9344 (push rtn1 rtn))
9345 (goto-char (point-at-eol)))
9346 (t (error "Invalid action")))
9348 ;; if we are to skip sublevels, jump to end of subtree
9349 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9350 (when (and (eq action 'sparse-tree)
9351 (not org-sparse-tree-open-archived-trees))
9352 (org-hide-archived-subtrees (point-min) (point-max)))
9353 (nreverse rtn)))
9355 (defun org-remove-uniherited-tags (tags)
9356 "Remove all tags that are not inherited from the list TAGS."
9357 (cond
9358 ((eq org-use-tag-inheritance t) tags)
9359 ((not org-use-tag-inheritance) nil)
9360 ((stringp org-use-tag-inheritance)
9361 (delq nil (mapcar
9362 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
9363 tags)))
9364 ((listp org-use-tag-inheritance)
9365 (org-delete-all org-use-tag-inheritance tags))))
9367 (defvar todo-only) ;; dynamically scoped
9369 (defun org-tags-sparse-tree (&optional todo-only match)
9370 "Create a sparse tree according to tags string MATCH.
9371 MATCH can contain positive and negative selection of tags, like
9372 \"+WORK+URGENT-WITHBOSS\".
9373 If optional argument TODO_ONLY is non-nil, only select lines that are
9374 also TODO lines."
9375 (interactive "P")
9376 (org-prepare-agenda-buffers (list (current-buffer)))
9377 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9379 (defvar org-cached-props nil)
9380 (defun org-cached-entry-get (pom property)
9381 (if (or (eq t org-use-property-inheritance)
9382 (and (stringp org-use-property-inheritance)
9383 (string-match org-use-property-inheritance property))
9384 (and (listp org-use-property-inheritance)
9385 (member property org-use-property-inheritance)))
9386 ;; Caching is not possible, check it directly
9387 (org-entry-get pom property 'inherit)
9388 ;; Get all properties, so that we can do complicated checks easily
9389 (cdr (assoc property (or org-cached-props
9390 (setq org-cached-props
9391 (org-entry-properties pom)))))))
9393 (defun org-global-tags-completion-table (&optional files)
9394 "Return the list of all tags in all agenda buffer/files."
9395 (save-excursion
9396 (org-uniquify
9397 (delq nil
9398 (apply 'append
9399 (mapcar
9400 (lambda (file)
9401 (set-buffer (find-file-noselect file))
9402 (append (org-get-buffer-tags)
9403 (mapcar (lambda (x) (if (stringp (car-safe x))
9404 (list (car-safe x)) nil))
9405 org-tag-alist)))
9406 (if (and files (car files))
9407 files
9408 (org-agenda-files))))))))
9410 (defun org-make-tags-matcher (match)
9411 "Create the TAGS//TODO matcher form for the selection string MATCH."
9412 ;; todo-only is scoped dynamically into this function, and the function
9413 ;; may change it it the matcher asksk for it.
9414 (unless match
9415 ;; Get a new match request, with completion
9416 (let ((org-last-tags-completion-table
9417 (org-global-tags-completion-table)))
9418 (setq match (completing-read
9419 "Match: " 'org-tags-completion-function nil nil nil
9420 'org-tags-history))))
9422 ;; Parse the string and create a lisp form
9423 (let ((match0 match)
9424 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9425 minus tag mm
9426 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9427 orterms term orlist re-p str-p level-p level-op
9428 prop-p pn pv po cat-p gv)
9429 (if (string-match "/+" match)
9430 ;; match contains also a todo-matching request
9431 (progn
9432 (setq tagsmatch (substring match 0 (match-beginning 0))
9433 todomatch (substring match (match-end 0)))
9434 (if (string-match "^!" todomatch)
9435 (setq todo-only t todomatch (substring todomatch 1)))
9436 (if (string-match "^\\s-*$" todomatch)
9437 (setq todomatch nil)))
9438 ;; only matching tags
9439 (setq tagsmatch match todomatch nil))
9441 ;; Make the tags matcher
9442 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9443 (setq tagsmatcher t)
9444 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9445 (while (setq term (pop orterms))
9446 (while (and (equal (substring term -1) "\\") orterms)
9447 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9448 (while (string-match re term)
9449 (setq minus (and (match-end 1)
9450 (equal (match-string 1 term) "-"))
9451 tag (match-string 2 term)
9452 re-p (equal (string-to-char tag) ?{)
9453 level-p (match-end 4)
9454 prop-p (match-end 5)
9455 mm (cond
9456 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9457 (level-p
9458 (setq level-op (org-op-to-function (match-string 3 term)))
9459 `(,level-op level ,(string-to-number
9460 (match-string 4 term))))
9461 (prop-p
9462 (setq pn (match-string 5 term)
9463 po (match-string 6 term)
9464 pv (match-string 7 term)
9465 cat-p (equal pn "CATEGORY")
9466 re-p (equal (string-to-char pv) ?{)
9467 str-p (equal (string-to-char pv) ?\")
9468 time-p (save-match-data (string-match "^\"<.*>\"$" pv))
9469 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9470 (if time-p (setq pv (org-matcher-time pv)))
9471 (setq po (org-op-to-function po (if time-p 'time str-p)))
9472 (if (equal pn "CATEGORY")
9473 (setq gv '(get-text-property (point) 'org-category))
9474 (setq gv `(org-cached-entry-get nil ,pn)))
9475 (if re-p
9476 (if (eq po 'org<>)
9477 `(not (string-match ,pv (or ,gv "")))
9478 `(string-match ,pv (or ,gv "")))
9479 (if str-p
9480 `(,po (or ,gv "") ,pv)
9481 `(,po (string-to-number (or ,gv ""))
9482 ,(string-to-number pv) ))))
9483 (t `(member ,(downcase tag) tags-list)))
9484 mm (if minus (list 'not mm) mm)
9485 term (substring term (match-end 0)))
9486 (push mm tagsmatcher))
9487 (push (if (> (length tagsmatcher) 1)
9488 (cons 'and tagsmatcher)
9489 (car tagsmatcher))
9490 orlist)
9491 (setq tagsmatcher nil))
9492 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9493 (setq tagsmatcher
9494 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9495 ;; Make the todo matcher
9496 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9497 (setq todomatcher t)
9498 (setq orterms (org-split-string todomatch "|") orlist nil)
9499 (while (setq term (pop orterms))
9500 (while (string-match re term)
9501 (setq minus (and (match-end 1)
9502 (equal (match-string 1 term) "-"))
9503 kwd (match-string 2 term)
9504 re-p (equal (string-to-char kwd) ?{)
9505 term (substring term (match-end 0))
9506 mm (if re-p
9507 `(string-match ,(substring kwd 1 -1) todo)
9508 (list 'equal 'todo kwd))
9509 mm (if minus (list 'not mm) mm))
9510 (push mm todomatcher))
9511 (push (if (> (length todomatcher) 1)
9512 (cons 'and todomatcher)
9513 (car todomatcher))
9514 orlist)
9515 (setq todomatcher nil))
9516 (setq todomatcher (if (> (length orlist) 1)
9517 (cons 'or orlist) (car orlist))))
9519 ;; Return the string and lisp forms of the matcher
9520 (setq matcher (if todomatcher
9521 (list 'and tagsmatcher todomatcher)
9522 tagsmatcher))
9523 (cons match0 matcher)))
9525 (defun org-op-to-function (op &optional stringp)
9526 "Turn an operator into the appropriate function."
9527 (setq op
9528 (cond
9529 ((equal op "<" ) '(< string< org-time<))
9530 ((equal op ">" ) '(> org-string> org-time>))
9531 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9532 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9533 ((member op '("=" "==")) '(= string= org-time=))
9534 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9535 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9537 (defun org<> (a b) (not (= a b)))
9538 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9539 (defun org-string>= (a b) (not (string< a b)))
9540 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9541 (defun org-string<> (a b) (not (string= a b)))
9542 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9543 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9544 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9545 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9546 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9547 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9548 (defun org-2ft (s)
9549 "Convert S to a floating point time.
9550 If S is already a number, just return it. If it is a string, parse
9551 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9552 (cond
9553 ((numberp s) s)
9554 ((stringp s)
9555 (condition-case nil
9556 (float-time (apply 'encode-time (org-parse-time-string s)))
9557 (error 0.)))
9558 (t 0.)))
9560 (defun org-matcher-time (s)
9561 (cond
9562 ((equal s "<now>") (float-time))
9563 ((equal s "<today>")
9564 (float-time (append '(0 0 0) (nthcdr 3 (decode-time)))))
9565 (t (org-2ft s))))
9567 (defun org-match-any-p (re list)
9568 "Does re match any element of list?"
9569 (setq list (mapcar (lambda (x) (string-match re x)) list))
9570 (delq nil list))
9572 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9573 (defvar org-tags-overlay (org-make-overlay 1 1))
9574 (org-detach-overlay org-tags-overlay)
9576 (defun org-get-tags-at (&optional pos)
9577 "Get a list of all headline tags applicable at POS.
9578 POS defaults to point. If tags are inherited, the list contains
9579 the targets in the same sequence as the headlines appear, i.e.
9580 the tags of the current headline come last."
9581 (interactive)
9582 (let (tags ltags lastpos parent)
9583 (save-excursion
9584 (save-restriction
9585 (widen)
9586 (goto-char (or pos (point)))
9587 (save-match-data
9588 (condition-case nil
9589 (progn
9590 (org-back-to-heading t)
9591 (while (not (equal lastpos (point)))
9592 (setq lastpos (point))
9593 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9594 (setq ltags (org-split-string
9595 (org-match-string-no-properties 1) ":"))
9596 (setq tags (append (org-remove-uniherited-tags ltags)
9597 tags)))
9598 (or org-use-tag-inheritance (error ""))
9599 (org-up-heading-all 1)
9600 (setq parent t)))
9601 (error nil))))
9602 (append (org-remove-uniherited-tags org-file-tags) tags))))
9604 (defun org-toggle-tag (tag &optional onoff)
9605 "Toggle the tag TAG for the current line.
9606 If ONOFF is `on' or `off', don't toggle but set to this state."
9607 (unless (org-on-heading-p t) (error "Not on headling"))
9608 (let (res current)
9609 (save-excursion
9610 (beginning-of-line)
9611 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9612 (point-at-eol) t)
9613 (progn
9614 (setq current (match-string 1))
9615 (replace-match ""))
9616 (setq current ""))
9617 (setq current (nreverse (org-split-string current ":")))
9618 (cond
9619 ((eq onoff 'on)
9620 (setq res t)
9621 (or (member tag current) (push tag current)))
9622 ((eq onoff 'off)
9623 (or (not (member tag current)) (setq current (delete tag current))))
9624 (t (if (member tag current)
9625 (setq current (delete tag current))
9626 (setq res t)
9627 (push tag current))))
9628 (end-of-line 1)
9629 (if current
9630 (progn
9631 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9632 (org-set-tags nil t))
9633 (delete-horizontal-space))
9634 (run-hooks 'org-after-tags-change-hook))
9635 res))
9637 (defun org-align-tags-here (to-col)
9638 ;; Assumes that this is a headline
9639 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9640 (beginning-of-line 1)
9641 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9642 (< pos (match-beginning 2)))
9643 (progn
9644 (setq tags-l (- (match-end 2) (match-beginning 2)))
9645 (goto-char (match-beginning 1))
9646 (insert " ")
9647 (delete-region (point) (1+ (match-beginning 2)))
9648 (setq ncol (max (1+ (current-column))
9649 (1+ col)
9650 (if (> to-col 0)
9651 to-col
9652 (- (abs to-col) tags-l))))
9653 (setq p (point))
9654 (insert (make-string (- ncol (current-column)) ?\ ))
9655 (setq ncol (current-column))
9656 (when indent-tabs-mode (tabify p (point-at-eol)))
9657 (org-move-to-column (min ncol col) t))
9658 (goto-char pos))))
9660 (defun org-set-tags (&optional arg just-align)
9661 "Set the tags for the current headline.
9662 With prefix ARG, realign all tags in headings in the current buffer."
9663 (interactive "P")
9664 (let* ((re (concat "^" outline-regexp))
9665 (current (org-get-tags-string))
9666 (col (current-column))
9667 (org-setting-tags t)
9668 table current-tags inherited-tags ; computed below when needed
9669 tags p0 c0 c1 rpl)
9670 (if arg
9671 (save-excursion
9672 (goto-char (point-min))
9673 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9674 (while (re-search-forward re nil t)
9675 (org-set-tags nil t)
9676 (end-of-line 1)))
9677 (message "All tags realigned to column %d" org-tags-column))
9678 (if just-align
9679 (setq tags current)
9680 ;; Get a new set of tags from the user
9681 (save-excursion
9682 (setq table (or org-tag-alist (org-get-buffer-tags))
9683 org-last-tags-completion-table table
9684 current-tags (org-split-string current ":")
9685 inherited-tags (nreverse
9686 (nthcdr (length current-tags)
9687 (nreverse (org-get-tags-at))))
9688 tags
9689 (if (or (eq t org-use-fast-tag-selection)
9690 (and org-use-fast-tag-selection
9691 (delq nil (mapcar 'cdr table))))
9692 (org-fast-tag-selection
9693 current-tags inherited-tags table
9694 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9695 (let ((org-add-colon-after-tag-completion t))
9696 (org-trim
9697 (org-without-partial-completion
9698 (completing-read "Tags: " 'org-tags-completion-function
9699 nil nil current 'org-tags-history)))))))
9700 (while (string-match "[-+&]+" tags)
9701 ;; No boolean logic, just a list
9702 (setq tags (replace-match ":" t t tags))))
9704 (if (string-match "\\`[\t ]*\\'" tags)
9705 (setq tags "")
9706 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9707 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9709 ;; Insert new tags at the correct column
9710 (beginning-of-line 1)
9711 (cond
9712 ((and (equal current "") (equal tags "")))
9713 ((re-search-forward
9714 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9715 (point-at-eol) t)
9716 (if (equal tags "")
9717 (setq rpl "")
9718 (goto-char (match-beginning 0))
9719 (setq c0 (current-column) p0 (point)
9720 c1 (max (1+ c0) (if (> org-tags-column 0)
9721 org-tags-column
9722 (- (- org-tags-column) (length tags))))
9723 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9724 (replace-match rpl t t)
9725 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9726 tags)
9727 (t (error "Tags alignment failed")))
9728 (org-move-to-column col)
9729 (unless just-align
9730 (run-hooks 'org-after-tags-change-hook)))))
9732 (defun org-change-tag-in-region (beg end tag off)
9733 "Add or remove TAG for each entry in the region.
9734 This works in the agenda, and also in an org-mode buffer."
9735 (interactive
9736 (list (region-beginning) (region-end)
9737 (let ((org-last-tags-completion-table
9738 (if (org-mode-p)
9739 (org-get-buffer-tags)
9740 (org-global-tags-completion-table))))
9741 (completing-read
9742 "Tag: " 'org-tags-completion-function nil nil nil
9743 'org-tags-history))
9744 (progn
9745 (message "[s]et or [r]emove? ")
9746 (equal (read-char-exclusive) ?r))))
9747 (if (fboundp 'deactivate-mark) (deactivate-mark))
9748 (let ((agendap (equal major-mode 'org-agenda-mode))
9749 l1 l2 m buf pos newhead (cnt 0))
9750 (goto-char end)
9751 (setq l2 (1- (org-current-line)))
9752 (goto-char beg)
9753 (setq l1 (org-current-line))
9754 (loop for l from l1 to l2 do
9755 (goto-line l)
9756 (setq m (get-text-property (point) 'org-hd-marker))
9757 (when (or (and (org-mode-p) (org-on-heading-p))
9758 (and agendap m))
9759 (setq buf (if agendap (marker-buffer m) (current-buffer))
9760 pos (if agendap m (point)))
9761 (with-current-buffer buf
9762 (save-excursion
9763 (save-restriction
9764 (goto-char pos)
9765 (setq cnt (1+ cnt))
9766 (org-toggle-tag tag (if off 'off 'on))
9767 (setq newhead (org-get-heading)))))
9768 (and agendap (org-agenda-change-all-lines newhead m))))
9769 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9771 (defun org-tags-completion-function (string predicate &optional flag)
9772 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9773 (confirm (lambda (x) (stringp (car x)))))
9774 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9775 (setq s1 (match-string 1 string)
9776 s2 (match-string 2 string))
9777 (setq s1 "" s2 string))
9778 (cond
9779 ((eq flag nil)
9780 ;; try completion
9781 (setq rtn (try-completion s2 ctable confirm))
9782 (if (stringp rtn)
9783 (setq rtn
9784 (concat s1 s2 (substring rtn (length s2))
9785 (if (and org-add-colon-after-tag-completion
9786 (assoc rtn ctable))
9787 ":" ""))))
9788 rtn)
9789 ((eq flag t)
9790 ;; all-completions
9791 (all-completions s2 ctable confirm)
9793 ((eq flag 'lambda)
9794 ;; exact match?
9795 (assoc s2 ctable)))
9798 (defun org-fast-tag-insert (kwd tags face &optional end)
9799 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9800 (insert (format "%-12s" (concat kwd ":"))
9801 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9802 (or end "")))
9804 (defun org-fast-tag-show-exit (flag)
9805 (save-excursion
9806 (goto-line 3)
9807 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9808 (replace-match ""))
9809 (when flag
9810 (end-of-line 1)
9811 (org-move-to-column (- (window-width) 19) t)
9812 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9814 (defun org-set-current-tags-overlay (current prefix)
9815 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9816 (if (featurep 'xemacs)
9817 (org-overlay-display org-tags-overlay (concat prefix s)
9818 'secondary-selection)
9819 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9820 (org-overlay-display org-tags-overlay (concat prefix s)))))
9822 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9823 "Fast tag selection with single keys.
9824 CURRENT is the current list of tags in the headline, INHERITED is the
9825 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9826 possibly with grouping information. TODO-TABLE is a similar table with
9827 TODO keywords, should these have keys assigned to them.
9828 If the keys are nil, a-z are automatically assigned.
9829 Returns the new tags string, or nil to not change the current settings."
9830 (let* ((fulltable (append table todo-table))
9831 (maxlen (apply 'max (mapcar
9832 (lambda (x)
9833 (if (stringp (car x)) (string-width (car x)) 0))
9834 fulltable)))
9835 (buf (current-buffer))
9836 (expert (eq org-fast-tag-selection-single-key 'expert))
9837 (buffer-tags nil)
9838 (fwidth (+ maxlen 3 1 3))
9839 (ncol (/ (- (window-width) 4) fwidth))
9840 (i-face 'org-done)
9841 (c-face 'org-todo)
9842 tg cnt e c char c1 c2 ntable tbl rtn
9843 ov-start ov-end ov-prefix
9844 (exit-after-next org-fast-tag-selection-single-key)
9845 (done-keywords org-done-keywords)
9846 groups ingroup)
9847 (save-excursion
9848 (beginning-of-line 1)
9849 (if (looking-at
9850 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9851 (setq ov-start (match-beginning 1)
9852 ov-end (match-end 1)
9853 ov-prefix "")
9854 (setq ov-start (1- (point-at-eol))
9855 ov-end (1+ ov-start))
9856 (skip-chars-forward "^\n\r")
9857 (setq ov-prefix
9858 (concat
9859 (buffer-substring (1- (point)) (point))
9860 (if (> (current-column) org-tags-column)
9862 (make-string (- org-tags-column (current-column)) ?\ ))))))
9863 (org-move-overlay org-tags-overlay ov-start ov-end)
9864 (save-window-excursion
9865 (if expert
9866 (set-buffer (get-buffer-create " *Org tags*"))
9867 (delete-other-windows)
9868 (split-window-vertically)
9869 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9870 (erase-buffer)
9871 (org-set-local 'org-done-keywords done-keywords)
9872 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9873 (org-fast-tag-insert "Current" current c-face "\n\n")
9874 (org-fast-tag-show-exit exit-after-next)
9875 (org-set-current-tags-overlay current ov-prefix)
9876 (setq tbl fulltable char ?a cnt 0)
9877 (while (setq e (pop tbl))
9878 (cond
9879 ((equal e '(:startgroup))
9880 (push '() groups) (setq ingroup t)
9881 (when (not (= cnt 0))
9882 (setq cnt 0)
9883 (insert "\n"))
9884 (insert "{ "))
9885 ((equal e '(:endgroup))
9886 (setq ingroup nil cnt 0)
9887 (insert "}\n"))
9889 (setq tg (car e) c2 nil)
9890 (if (cdr e)
9891 (setq c (cdr e))
9892 ;; automatically assign a character.
9893 (setq c1 (string-to-char
9894 (downcase (substring
9895 tg (if (= (string-to-char tg) ?@) 1 0)))))
9896 (if (or (rassoc c1 ntable) (rassoc c1 table))
9897 (while (or (rassoc char ntable) (rassoc char table))
9898 (setq char (1+ char)))
9899 (setq c2 c1))
9900 (setq c (or c2 char)))
9901 (if ingroup (push tg (car groups)))
9902 (setq tg (org-add-props tg nil 'face
9903 (cond
9904 ((not (assoc tg table))
9905 (org-get-todo-face tg))
9906 ((member tg current) c-face)
9907 ((member tg inherited) i-face)
9908 (t nil))))
9909 (if (and (= cnt 0) (not ingroup)) (insert " "))
9910 (insert "[" c "] " tg (make-string
9911 (- fwidth 4 (length tg)) ?\ ))
9912 (push (cons tg c) ntable)
9913 (when (= (setq cnt (1+ cnt)) ncol)
9914 (insert "\n")
9915 (if ingroup (insert " "))
9916 (setq cnt 0)))))
9917 (setq ntable (nreverse ntable))
9918 (insert "\n")
9919 (goto-char (point-min))
9920 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9921 (fit-window-to-buffer))
9922 (setq rtn
9923 (catch 'exit
9924 (while t
9925 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9926 (if groups " [!] no groups" " [!]groups")
9927 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9928 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9929 (cond
9930 ((= c ?\r) (throw 'exit t))
9931 ((= c ?!)
9932 (setq groups (not groups))
9933 (goto-char (point-min))
9934 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9935 ((= c ?\C-c)
9936 (if (not expert)
9937 (org-fast-tag-show-exit
9938 (setq exit-after-next (not exit-after-next)))
9939 (setq expert nil)
9940 (delete-other-windows)
9941 (split-window-vertically)
9942 (org-switch-to-buffer-other-window " *Org tags*")
9943 (and (fboundp 'fit-window-to-buffer)
9944 (fit-window-to-buffer))))
9945 ((or (= c ?\C-g)
9946 (and (= c ?q) (not (rassoc c ntable))))
9947 (org-detach-overlay org-tags-overlay)
9948 (setq quit-flag t))
9949 ((= c ?\ )
9950 (setq current nil)
9951 (if exit-after-next (setq exit-after-next 'now)))
9952 ((= c ?\t)
9953 (condition-case nil
9954 (setq tg (completing-read
9955 "Tag: "
9956 (or buffer-tags
9957 (with-current-buffer buf
9958 (org-get-buffer-tags)))))
9959 (quit (setq tg "")))
9960 (when (string-match "\\S-" tg)
9961 (add-to-list 'buffer-tags (list tg))
9962 (if (member tg current)
9963 (setq current (delete tg current))
9964 (push tg current)))
9965 (if exit-after-next (setq exit-after-next 'now)))
9966 ((setq e (rassoc c todo-table) tg (car e))
9967 (with-current-buffer buf
9968 (save-excursion (org-todo tg)))
9969 (if exit-after-next (setq exit-after-next 'now)))
9970 ((setq e (rassoc c ntable) tg (car e))
9971 (if (member tg current)
9972 (setq current (delete tg current))
9973 (loop for g in groups do
9974 (if (member tg g)
9975 (mapc (lambda (x)
9976 (setq current (delete x current)))
9977 g)))
9978 (push tg current))
9979 (if exit-after-next (setq exit-after-next 'now))))
9981 ;; Create a sorted list
9982 (setq current
9983 (sort current
9984 (lambda (a b)
9985 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9986 (if (eq exit-after-next 'now) (throw 'exit t))
9987 (goto-char (point-min))
9988 (beginning-of-line 2)
9989 (delete-region (point) (point-at-eol))
9990 (org-fast-tag-insert "Current" current c-face)
9991 (org-set-current-tags-overlay current ov-prefix)
9992 (while (re-search-forward
9993 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9994 (setq tg (match-string 1))
9995 (add-text-properties
9996 (match-beginning 1) (match-end 1)
9997 (list 'face
9998 (cond
9999 ((member tg current) c-face)
10000 ((member tg inherited) i-face)
10001 (t (get-text-property (match-beginning 1) 'face))))))
10002 (goto-char (point-min)))))
10003 (org-detach-overlay org-tags-overlay)
10004 (if rtn
10005 (mapconcat 'identity current ":")
10006 nil))))
10008 (defun org-get-tags-string ()
10009 "Get the TAGS string in the current headline."
10010 (unless (org-on-heading-p t)
10011 (error "Not on a heading"))
10012 (save-excursion
10013 (beginning-of-line 1)
10014 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10015 (org-match-string-no-properties 1)
10016 "")))
10018 (defun org-get-tags ()
10019 "Get the list of tags specified in the current headline."
10020 (org-split-string (org-get-tags-string) ":"))
10022 (defun org-get-buffer-tags ()
10023 "Get a table of all tags used in the buffer, for completion."
10024 (let (tags)
10025 (save-excursion
10026 (goto-char (point-min))
10027 (while (re-search-forward
10028 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10029 (when (equal (char-after (point-at-bol 0)) ?*)
10030 (mapc (lambda (x) (add-to-list 'tags x))
10031 (org-split-string (org-match-string-no-properties 1) ":")))))
10032 (mapcar 'list tags)))
10034 ;;;; The mapping API
10036 ;;;###autoload
10037 (defun org-map-entries (func &optional match scope &rest skip)
10038 "Call FUNC at each headline selected by MATCH in SCOPE.
10040 FUNC is a function or a lisp form. The function will be called without
10041 arguments, with the cursor positioned at the beginning of the headline.
10042 The return values of all calls to the function will be collected and
10043 returned as a list.
10045 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10046 Only headlines that are matched by this query will be considered during
10047 the iteration. When MATCH is nil or t, all headlines will be
10048 visited by the iteration.
10050 SCOPE determines the scope of this command. It can be any of:
10052 nil The current buffer, respecting the restriction if any
10053 tree The subtree started with the entry at point
10054 file The current buffer, without restriction
10055 file-with-archives
10056 The current buffer, and any archives associated with it
10057 agenda All agenda files
10058 agenda-with-archives
10059 All agenda files with any archive files associated with them
10060 \(file1 file2 ...)
10061 If this is a list, all files in the list will be scanned
10063 The remaining args are treated as settings for the skipping facilities of
10064 the scanner. The following items can be given here:
10066 archive skip trees with the archive tag.
10067 comment skip trees with the COMMENT keyword
10068 function or Emacs Lisp form:
10069 will be used as value for `org-agenda-skip-function', so whenever
10070 the the function returns t, FUNC will not be called for that
10071 entry and search will continue from the point where the
10072 function leaves it."
10073 (let* ((org-agenda-archives-mode nil) ; just to make sure
10074 (org-agenda-skip-archived-trees (memq 'archive skip))
10075 (org-agenda-skip-comment-trees (memq 'comment skip))
10076 (org-agenda-skip-function
10077 (car (org-delete-all '(comment archive) skip)))
10078 (org-tags-match-list-sublevels t)
10079 matcher pos file)
10081 (cond
10082 ((eq match t) (setq matcher t))
10083 ((eq match nil) (setq matcher t))
10084 (t (setq matcher (if match (org-make-tags-matcher match) t))))
10086 (when (eq scope 'tree)
10087 (org-back-to-heading t)
10088 (org-narrow-to-subtree)
10089 (setq scope nil))
10091 (if (not scope)
10092 (progn
10093 (org-prepare-agenda-buffers
10094 (list (buffer-file-name (current-buffer))))
10095 (org-scan-tags func matcher))
10096 ;; Get the right scope
10097 (setq pos (point))
10098 (cond
10099 ((and scope (listp scope) (symbolp (car scope)))
10100 (setq scope (eval scope)))
10101 ((eq scope 'agenda)
10102 (setq scope (org-agenda-files t)))
10103 ((eq scope 'agenda-with-archives)
10104 (setq scope (org-agenda-files t))
10105 (setq scope (org-add-archive-files scope)))
10106 ((eq scope 'file)
10107 (setq scope (list (buffer-file-name))))
10108 ((eq scope 'file-with-archives)
10109 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10110 (org-prepare-agenda-buffers scope)
10111 (while (setq file (pop scope))
10112 (with-current-buffer (org-find-base-buffer-visiting file)
10113 (save-excursion
10114 (save-restriction
10115 (widen)
10116 (goto-char (point-min))
10117 (org-scan-tags func matcher))))))))
10119 ;;;; Properties
10121 ;;; Setting and retrieving properties
10123 (defconst org-special-properties
10124 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
10125 "TIMESTAMP" "TIMESTAMP_IA")
10126 "The special properties valid in Org-mode.
10128 These are properties that are not defined in the property drawer,
10129 but in some other way.")
10131 (defconst org-default-properties
10132 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10133 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10134 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10135 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10136 "Some properties that are used by Org-mode for various purposes.
10137 Being in this list makes sure that they are offered for completion.")
10139 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10140 "Regular expression matching the first line of a property drawer.")
10142 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10143 "Regular expression matching the first line of a property drawer.")
10145 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10146 "Regular expression matching the first line of a property drawer.")
10148 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10149 "Regular expression matching the first line of a property drawer.")
10151 (defconst org-property-drawer-re
10152 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10153 org-property-end-re "\\)\n?")
10154 "Matches an entire property drawer.")
10156 (defconst org-clock-drawer-re
10157 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10158 org-property-end-re "\\)\n?")
10159 "Matches an entire clock drawer.")
10161 (defun org-property-action ()
10162 "Do an action on properties."
10163 (interactive)
10164 (let (c)
10165 (org-at-property-p)
10166 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10167 (setq c (read-char-exclusive))
10168 (cond
10169 ((equal c ?s)
10170 (call-interactively 'org-set-property))
10171 ((equal c ?d)
10172 (call-interactively 'org-delete-property))
10173 ((equal c ?D)
10174 (call-interactively 'org-delete-property-globally))
10175 ((equal c ?c)
10176 (call-interactively 'org-compute-property-at-point))
10177 (t (error "No such property action %c" c)))))
10179 (defun org-at-property-p ()
10180 "Is the cursor in a property line?"
10181 ;; FIXME: Does not check if we are actually in the drawer.
10182 ;; FIXME: also returns true on any drawers.....
10183 ;; This is used by C-c C-c for property action.
10184 (save-excursion
10185 (beginning-of-line 1)
10186 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10188 (defun org-get-property-block (&optional beg end force)
10189 "Return the (beg . end) range of the body of the property drawer.
10190 BEG and END can be beginning and end of subtree, if not given
10191 they will be found.
10192 If the drawer does not exist and FORCE is non-nil, create the drawer."
10193 (catch 'exit
10194 (save-excursion
10195 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10196 (end (or end (progn (outline-next-heading) (point)))))
10197 (goto-char beg)
10198 (if (re-search-forward org-property-start-re end t)
10199 (setq beg (1+ (match-end 0)))
10200 (if force
10201 (save-excursion
10202 (org-insert-property-drawer)
10203 (setq end (progn (outline-next-heading) (point))))
10204 (throw 'exit nil))
10205 (goto-char beg)
10206 (if (re-search-forward org-property-start-re end t)
10207 (setq beg (1+ (match-end 0)))))
10208 (if (re-search-forward org-property-end-re end t)
10209 (setq end (match-beginning 0))
10210 (or force (throw 'exit nil))
10211 (goto-char beg)
10212 (setq end beg)
10213 (org-indent-line-function)
10214 (insert ":END:\n"))
10215 (cons beg end)))))
10217 (defun org-entry-properties (&optional pom which)
10218 "Get all properties of the entry at point-or-marker POM.
10219 This includes the TODO keyword, the tags, time strings for deadline,
10220 scheduled, and clocking, and any additional properties defined in the
10221 entry. The return value is an alist, keys may occur multiple times
10222 if the property key was used several times.
10223 POM may also be nil, in which case the current entry is used.
10224 If WHICH is nil or `all', get all properties. If WHICH is
10225 `special' or `standard', only get that subclass."
10226 (setq which (or which 'all))
10227 (org-with-point-at pom
10228 (let ((clockstr (substring org-clock-string 0 -1))
10229 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10230 beg end range props sum-props key value string clocksum)
10231 (save-excursion
10232 (when (condition-case nil (org-back-to-heading t) (error nil))
10233 (setq beg (point))
10234 (setq sum-props (get-text-property (point) 'org-summaries))
10235 (setq clocksum (get-text-property (point) :org-clock-minutes))
10236 (outline-next-heading)
10237 (setq end (point))
10238 (when (memq which '(all special))
10239 ;; Get the special properties, like TODO and tags
10240 (goto-char beg)
10241 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10242 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10243 (when (looking-at org-priority-regexp)
10244 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10245 (when (and (setq value (org-get-tags-string))
10246 (string-match "\\S-" value))
10247 (push (cons "TAGS" value) props))
10248 (when (setq value (org-get-tags-at))
10249 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10250 props))
10251 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10252 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10253 string (if (equal key clockstr)
10254 (org-no-properties
10255 (org-trim
10256 (buffer-substring
10257 (match-beginning 3) (goto-char (point-at-eol)))))
10258 (substring (org-match-string-no-properties 3) 1 -1)))
10259 (unless key
10260 (if (= (char-after (match-beginning 3)) ?\[)
10261 (setq key "TIMESTAMP_IA")
10262 (setq key "TIMESTAMP")))
10263 (when (or (equal key clockstr) (not (assoc key props)))
10264 (push (cons key string) props)))
10268 (when (memq which '(all standard))
10269 ;; Get the standard properties, like :PORP: ...
10270 (setq range (org-get-property-block beg end))
10271 (when range
10272 (goto-char (car range))
10273 (while (re-search-forward
10274 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10275 (cdr range) t)
10276 (setq key (org-match-string-no-properties 1)
10277 value (org-trim (or (org-match-string-no-properties 2) "")))
10278 (unless (member key excluded)
10279 (push (cons key (or value "")) props)))))
10280 (if clocksum
10281 (push (cons "CLOCKSUM"
10282 (org-columns-number-to-string (/ (float clocksum) 60.)
10283 'add_times))
10284 props))
10285 (append sum-props (nreverse props)))))))
10287 (defun org-entry-get (pom property &optional inherit)
10288 "Get value of PROPERTY for entry at point-or-marker POM.
10289 If INHERIT is non-nil and the entry does not have the property,
10290 then also check higher levels of the hierarchy.
10291 If INHERIT is the symbol `selective', use inheritance only if the setting
10292 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10293 If the property is present but empty, the return value is the empty string.
10294 If the property is not present at all, nil is returned."
10295 (org-with-point-at pom
10296 (if (and inherit (if (eq inherit 'selective)
10297 (org-property-inherit-p property)
10299 (org-entry-get-with-inheritance property)
10300 (if (member property org-special-properties)
10301 ;; We need a special property. Use brute force, get all properties.
10302 (cdr (assoc property (org-entry-properties nil 'special)))
10303 (let ((range (org-get-property-block)))
10304 (if (and range
10305 (goto-char (car range))
10306 (re-search-forward
10307 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
10308 (cdr range) t))
10309 ;; Found the property, return it.
10310 (if (match-end 1)
10311 (org-match-string-no-properties 1)
10312 "")))))))
10314 (defun org-property-or-variable-value (var &optional inherit)
10315 "Check if there is a property fixing the value of VAR.
10316 If yes, return this value. If not, return the current value of the variable."
10317 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10318 (if (and prop (stringp prop) (string-match "\\S-" prop))
10319 (read prop)
10320 (symbol-value var))))
10322 (defun org-entry-delete (pom property)
10323 "Delete the property PROPERTY from entry at point-or-marker POM."
10324 (org-with-point-at pom
10325 (if (member property org-special-properties)
10326 nil ; cannot delete these properties.
10327 (let ((range (org-get-property-block)))
10328 (if (and range
10329 (goto-char (car range))
10330 (re-search-forward
10331 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
10332 (cdr range) t))
10333 (progn
10334 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10336 nil)))))
10338 ;; Multi-values properties are properties that contain multiple values
10339 ;; These values are assumed to be single words, separated by whitespace.
10340 (defun org-entry-add-to-multivalued-property (pom property value)
10341 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10342 (let* ((old (org-entry-get pom property))
10343 (values (and old (org-split-string old "[ \t]"))))
10344 (unless (member value values)
10345 (setq values (cons value values))
10346 (org-entry-put pom property
10347 (mapconcat 'identity values " ")))))
10349 (defun org-entry-remove-from-multivalued-property (pom property value)
10350 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10351 (let* ((old (org-entry-get pom property))
10352 (values (and old (org-split-string old "[ \t]"))))
10353 (when (member value values)
10354 (setq values (delete value values))
10355 (org-entry-put pom property
10356 (mapconcat 'identity values " ")))))
10358 (defun org-entry-member-in-multivalued-property (pom property value)
10359 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10360 (let* ((old (org-entry-get pom property))
10361 (values (and old (org-split-string old "[ \t]"))))
10362 (member value values)))
10364 (defvar org-entry-property-inherited-from (make-marker))
10366 (defun org-entry-get-with-inheritance (property)
10367 "Get entry property, and search higher levels if not present."
10368 (let (tmp)
10369 (save-excursion
10370 (save-restriction
10371 (widen)
10372 (catch 'ex
10373 (while t
10374 (when (setq tmp (org-entry-get nil property))
10375 (org-back-to-heading t)
10376 (move-marker org-entry-property-inherited-from (point))
10377 (throw 'ex tmp))
10378 (or (org-up-heading-safe) (throw 'ex nil)))))
10379 (or tmp
10380 (cdr (assoc property org-file-properties))
10381 (cdr (assoc property org-global-properties))
10382 (cdr (assoc property org-global-properties-fixed))))))
10384 (defun org-entry-put (pom property value)
10385 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10386 (org-with-point-at pom
10387 (org-back-to-heading t)
10388 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10389 range)
10390 (cond
10391 ((equal property "TODO")
10392 (when (and (stringp value) (string-match "\\S-" value)
10393 (not (member value org-todo-keywords-1)))
10394 (error "\"%s\" is not a valid TODO state" value))
10395 (if (or (not value)
10396 (not (string-match "\\S-" value)))
10397 (setq value 'none))
10398 (org-todo value)
10399 (org-set-tags nil 'align))
10400 ((equal property "PRIORITY")
10401 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10402 (string-to-char value) ?\ ))
10403 (org-set-tags nil 'align))
10404 ((equal property "SCHEDULED")
10405 (if (re-search-forward org-scheduled-time-regexp end t)
10406 (cond
10407 ((eq value 'earlier) (org-timestamp-change -1 'day))
10408 ((eq value 'later) (org-timestamp-change 1 'day))
10409 (t (call-interactively 'org-schedule)))
10410 (call-interactively 'org-schedule)))
10411 ((equal property "DEADLINE")
10412 (if (re-search-forward org-deadline-time-regexp end t)
10413 (cond
10414 ((eq value 'earlier) (org-timestamp-change -1 'day))
10415 ((eq value 'later) (org-timestamp-change 1 'day))
10416 (t (call-interactively 'org-deadline)))
10417 (call-interactively 'org-deadline)))
10418 ((member property org-special-properties)
10419 (error "The %s property can not yet be set with `org-entry-put'"
10420 property))
10421 (t ; a non-special property
10422 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10423 (setq range (org-get-property-block beg end 'force))
10424 (goto-char (car range))
10425 (if (re-search-forward
10426 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10427 (progn
10428 (delete-region (match-beginning 1) (match-end 1))
10429 (goto-char (match-beginning 1)))
10430 (goto-char (cdr range))
10431 (insert "\n")
10432 (backward-char 1)
10433 (org-indent-line-function)
10434 (insert ":" property ":"))
10435 (and value (insert " " value))
10436 (org-indent-line-function)))))))
10438 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10439 "Get all property keys in the current buffer.
10440 With INCLUDE-SPECIALS, also list the special properties that relect things
10441 like tags and TODO state.
10442 With INCLUDE-DEFAULTS, also include properties that has special meaning
10443 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10444 With INCLUDE-COLUMNS, also include property names given in COLUMN
10445 formats in the current buffer."
10446 (let (rtn range cfmt cols s p)
10447 (save-excursion
10448 (save-restriction
10449 (widen)
10450 (goto-char (point-min))
10451 (while (re-search-forward org-property-start-re nil t)
10452 (setq range (org-get-property-block))
10453 (goto-char (car range))
10454 (while (re-search-forward
10455 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10456 (cdr range) t)
10457 (add-to-list 'rtn (org-match-string-no-properties 1)))
10458 (outline-next-heading))))
10460 (when include-specials
10461 (setq rtn (append org-special-properties rtn)))
10463 (when include-defaults
10464 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10466 (when include-columns
10467 (save-excursion
10468 (save-restriction
10469 (widen)
10470 (goto-char (point-min))
10471 (while (re-search-forward
10472 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10473 nil t)
10474 (setq cfmt (match-string 2) s 0)
10475 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10476 cfmt s)
10477 (setq s (match-end 0)
10478 p (match-string 1 cfmt))
10479 (unless (or (equal p "ITEM")
10480 (member p org-special-properties))
10481 (add-to-list 'rtn (match-string 1 cfmt))))))))
10483 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10485 (defun org-property-values (key)
10486 "Return a list of all values of property KEY."
10487 (save-excursion
10488 (save-restriction
10489 (widen)
10490 (goto-char (point-min))
10491 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10492 values)
10493 (while (re-search-forward re nil t)
10494 (add-to-list 'values (org-trim (match-string 1))))
10495 (delete "" values)))))
10497 (defun org-insert-property-drawer ()
10498 "Insert a property drawer into the current entry."
10499 (interactive)
10500 (org-back-to-heading t)
10501 (looking-at outline-regexp)
10502 (let ((indent (- (match-end 0)(match-beginning 0)))
10503 (beg (point))
10504 (re (concat "^[ \t]*" org-keyword-time-regexp))
10505 end hiddenp)
10506 (outline-next-heading)
10507 (setq end (point))
10508 (goto-char beg)
10509 (while (re-search-forward re end t))
10510 (setq hiddenp (org-invisible-p))
10511 (end-of-line 1)
10512 (and (equal (char-after) ?\n) (forward-char 1))
10513 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10514 (beginning-of-line 2))
10515 (org-skip-over-state-notes)
10516 (skip-chars-backward " \t\n\r")
10517 (if (eq (char-before) ?*) (forward-char 1))
10518 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10519 (beginning-of-line 0)
10520 (org-indent-to-column indent)
10521 (beginning-of-line 2)
10522 (org-indent-to-column indent)
10523 (beginning-of-line 0)
10524 (if hiddenp
10525 (save-excursion
10526 (org-back-to-heading t)
10527 (hide-entry))
10528 (org-flag-drawer t))))
10530 (defun org-set-property (property value)
10531 "In the current entry, set PROPERTY to VALUE.
10532 When called interactively, this will prompt for a property name, offering
10533 completion on existing and default properties. And then it will prompt
10534 for a value, offering competion either on allowed values (via an inherited
10535 xxx_ALL property) or on existing values in other instances of this property
10536 in the current file."
10537 (interactive
10538 (let* ((completion-ignore-case t)
10539 (keys (org-buffer-property-keys nil t t))
10540 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10541 (prop (if (member prop0 keys)
10542 prop0
10543 (or (cdr (assoc (downcase prop0)
10544 (mapcar (lambda (x) (cons (downcase x) x))
10545 keys)))
10546 prop0)))
10547 (cur (org-entry-get nil prop))
10548 (allowed (org-property-get-allowed-values nil prop 'table))
10549 (existing (mapcar 'list (org-property-values prop)))
10550 (val (if allowed
10551 (org-completing-read "Value: " allowed nil 'req-match)
10552 (org-completing-read
10553 (concat "Value" (if (and cur (string-match "\\S-" cur))
10554 (concat "[" cur "]") "")
10555 ": ")
10556 existing nil nil "" nil cur))))
10557 (list prop (if (equal val "") cur val))))
10558 (unless (equal (org-entry-get nil property) value)
10559 (org-entry-put nil property value)))
10561 (defun org-delete-property (property)
10562 "In the current entry, delete PROPERTY."
10563 (interactive
10564 (let* ((completion-ignore-case t)
10565 (prop (completing-read
10566 "Property: " (org-entry-properties nil 'standard))))
10567 (list prop)))
10568 (message "Property %s %s" property
10569 (if (org-entry-delete nil property)
10570 "deleted"
10571 "was not present in the entry")))
10573 (defun org-delete-property-globally (property)
10574 "Remove PROPERTY globally, from all entries."
10575 (interactive
10576 (let* ((completion-ignore-case t)
10577 (prop (completing-read
10578 "Globally remove property: "
10579 (mapcar 'list (org-buffer-property-keys)))))
10580 (list prop)))
10581 (save-excursion
10582 (save-restriction
10583 (widen)
10584 (goto-char (point-min))
10585 (let ((cnt 0))
10586 (while (re-search-forward
10587 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10588 nil t)
10589 (setq cnt (1+ cnt))
10590 (replace-match ""))
10591 (message "Property \"%s\" removed from %d entries" property cnt)))))
10593 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10595 (defun org-compute-property-at-point ()
10596 "Compute the property at point.
10597 This looks for an enclosing column format, extracts the operator and
10598 then applies it to the proerty in the column format's scope."
10599 (interactive)
10600 (unless (org-at-property-p)
10601 (error "Not at a property"))
10602 (let ((prop (org-match-string-no-properties 2)))
10603 (org-columns-get-format-and-top-level)
10604 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10605 (error "No operator defined for property %s" prop))
10606 (org-columns-compute prop)))
10608 (defun org-property-get-allowed-values (pom property &optional table)
10609 "Get allowed values for the property PROPERTY.
10610 When TABLE is non-nil, return an alist that can directly be used for
10611 completion."
10612 (let (vals)
10613 (cond
10614 ((equal property "TODO")
10615 (setq vals (org-with-point-at pom
10616 (append org-todo-keywords-1 '("")))))
10617 ((equal property "PRIORITY")
10618 (let ((n org-lowest-priority))
10619 (while (>= n org-highest-priority)
10620 (push (char-to-string n) vals)
10621 (setq n (1- n)))))
10622 ((member property org-special-properties))
10624 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10626 (when (and vals (string-match "\\S-" vals))
10627 (setq vals (car (read-from-string (concat "(" vals ")"))))
10628 (setq vals (mapcar (lambda (x)
10629 (cond ((stringp x) x)
10630 ((numberp x) (number-to-string x))
10631 ((symbolp x) (symbol-name x))
10632 (t "???")))
10633 vals)))))
10634 (if table (mapcar 'list vals) vals)))
10636 (defun org-property-previous-allowed-value (&optional previous)
10637 "Switch to the next allowed value for this property."
10638 (interactive)
10639 (org-property-next-allowed-value t))
10641 (defun org-property-next-allowed-value (&optional previous)
10642 "Switch to the next allowed value for this property."
10643 (interactive)
10644 (unless (org-at-property-p)
10645 (error "Not at a property"))
10646 (let* ((key (match-string 2))
10647 (value (match-string 3))
10648 (allowed (or (org-property-get-allowed-values (point) key)
10649 (and (member value '("[ ]" "[-]" "[X]"))
10650 '("[ ]" "[X]"))))
10651 nval)
10652 (unless allowed
10653 (error "Allowed values for this property have not been defined"))
10654 (if previous (setq allowed (reverse allowed)))
10655 (if (member value allowed)
10656 (setq nval (car (cdr (member value allowed)))))
10657 (setq nval (or nval (car allowed)))
10658 (if (equal nval value)
10659 (error "Only one allowed value for this property"))
10660 (org-at-property-p)
10661 (replace-match (concat " :" key ": " nval) t t)
10662 (org-indent-line-function)
10663 (beginning-of-line 1)
10664 (skip-chars-forward " \t")))
10666 (defun org-find-entry-with-id (ident)
10667 "Locate the entry that contains the ID property with exact value IDENT.
10668 IDENT can be a string, a symbol or a number, this function will search for
10669 the string representation of it.
10670 Return the position where this entry starts, or nil if there is no such entry."
10671 (let ((id (cond
10672 ((stringp ident) ident)
10673 ((symbol-name ident) (symbol-name ident))
10674 ((numberp ident) (number-to-string ident))
10675 (t (error "IDENT %s must be a string, symbol or number" ident))))
10676 (case-fold-search nil))
10677 (save-excursion
10678 (save-restriction
10679 (widen)
10680 (goto-char (point-min))
10681 (when (re-search-forward
10682 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10683 nil t)
10684 (org-back-to-heading)
10685 (point))))))
10687 ;;;; Timestamps
10689 (defvar org-last-changed-timestamp nil)
10690 (defvar org-last-inserted-timestamp nil
10691 "The last time stamp inserted with `org-insert-time-stamp'.")
10692 (defvar org-time-was-given) ; dynamically scoped parameter
10693 (defvar org-end-time-was-given) ; dynamically scoped parameter
10694 (defvar org-ts-what) ; dynamically scoped parameter
10696 (defun org-time-stamp (arg)
10697 "Prompt for a date/time and insert a time stamp.
10698 If the user specifies a time like HH:MM, or if this command is called
10699 with a prefix argument, the time stamp will contain date and time.
10700 Otherwise, only the date will be included. All parts of a date not
10701 specified by the user will be filled in from the current date/time.
10702 So if you press just return without typing anything, the time stamp
10703 will represent the current date/time. If there is already a timestamp
10704 at the cursor, it will be modified."
10705 (interactive "P")
10706 (let* ((ts nil)
10707 (default-time
10708 ;; Default time is either today, or, when entering a range,
10709 ;; the range start.
10710 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10711 (save-excursion
10712 (re-search-backward
10713 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10714 (- (point) 20) t)))
10715 (apply 'encode-time (org-parse-time-string (match-string 1)))
10716 (current-time)))
10717 (default-input (and ts (org-get-compact-tod ts)))
10718 org-time-was-given org-end-time-was-given time)
10719 (cond
10720 ((and (org-at-timestamp-p)
10721 (eq last-command 'org-time-stamp)
10722 (eq this-command 'org-time-stamp))
10723 (insert "--")
10724 (setq time (let ((this-command this-command))
10725 (org-read-date arg 'totime nil nil default-time default-input)))
10726 (org-insert-time-stamp time (or org-time-was-given arg)))
10727 ((org-at-timestamp-p)
10728 (setq time (let ((this-command this-command))
10729 (org-read-date arg 'totime nil nil default-time default-input)))
10730 (when (org-at-timestamp-p) ; just to get the match data
10731 (replace-match "")
10732 (setq org-last-changed-timestamp
10733 (org-insert-time-stamp
10734 time (or org-time-was-given arg)
10735 nil nil nil (list org-end-time-was-given))))
10736 (message "Timestamp updated"))
10738 (setq time (let ((this-command this-command))
10739 (org-read-date arg 'totime nil nil default-time default-input)))
10740 (org-insert-time-stamp time (or org-time-was-given arg)
10741 nil nil nil (list org-end-time-was-given))))))
10743 ;; FIXME: can we use this for something else, like computing time differences?
10744 (defun org-get-compact-tod (s)
10745 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10746 (let* ((t1 (match-string 1 s))
10747 (h1 (string-to-number (match-string 2 s)))
10748 (m1 (string-to-number (match-string 3 s)))
10749 (t2 (and (match-end 4) (match-string 5 s)))
10750 (h2 (and t2 (string-to-number (match-string 6 s))))
10751 (m2 (and t2 (string-to-number (match-string 7 s))))
10752 dh dm)
10753 (if (not t2)
10755 (setq dh (- h2 h1) dm (- m2 m1))
10756 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10757 (concat t1 "+" (number-to-string dh)
10758 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10760 (defun org-time-stamp-inactive (&optional arg)
10761 "Insert an inactive time stamp.
10762 An inactive time stamp is enclosed in square brackets instead of angle
10763 brackets. It is inactive in the sense that it does not trigger agenda entries,
10764 does not link to the calendar and cannot be changed with the S-cursor keys.
10765 So these are more for recording a certain time/date."
10766 (interactive "P")
10767 (let (org-time-was-given org-end-time-was-given time)
10768 (setq time (org-read-date arg 'totime))
10769 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10770 nil nil (list org-end-time-was-given))))
10772 (defvar org-date-ovl (org-make-overlay 1 1))
10773 (org-overlay-put org-date-ovl 'face 'org-warning)
10774 (org-detach-overlay org-date-ovl)
10776 (defvar org-ans1) ; dynamically scoped parameter
10777 (defvar org-ans2) ; dynamically scoped parameter
10779 (defvar org-plain-time-of-day-regexp) ; defined below
10781 (defvar org-overriding-default-time nil) ; dynamically scoped
10782 (defvar org-read-date-overlay nil)
10783 (defvar org-dcst nil) ; dynamically scoped
10785 (defun org-read-date (&optional with-time to-time from-string prompt
10786 default-time default-input)
10787 "Read a date, possibly a time, and make things smooth for the user.
10788 The prompt will suggest to enter an ISO date, but you can also enter anything
10789 which will at least partially be understood by `parse-time-string'.
10790 Unrecognized parts of the date will default to the current day, month, year,
10791 hour and minute. If this command is called to replace a timestamp at point,
10792 of to enter the second timestamp of a range, the default time is taken from the
10793 existing stamp. For example,
10794 3-2-5 --> 2003-02-05
10795 feb 15 --> currentyear-02-15
10796 sep 12 9 --> 2009-09-12
10797 12:45 --> today 12:45
10798 22 sept 0:34 --> currentyear-09-22 0:34
10799 12 --> currentyear-currentmonth-12
10800 Fri --> nearest Friday (today or later)
10801 etc.
10803 Furthermore you can specify a relative date by giving, as the *first* thing
10804 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10805 change in days weeks, months, years.
10806 With a single plus or minus, the date is relative to today. With a double
10807 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10808 +4d --> four days from today
10809 +4 --> same as above
10810 +2w --> two weeks from today
10811 ++5 --> five days from default date
10813 The function understands only English month and weekday abbreviations,
10814 but this can be configured with the variables `parse-time-months' and
10815 `parse-time-weekdays'.
10817 While prompting, a calendar is popped up - you can also select the
10818 date with the mouse (button 1). The calendar shows a period of three
10819 months. To scroll it to other months, use the keys `>' and `<'.
10820 If you don't like the calendar, turn it off with
10821 \(setq org-read-date-popup-calendar nil)
10823 With optional argument TO-TIME, the date will immediately be converted
10824 to an internal time.
10825 With an optional argument WITH-TIME, the prompt will suggest to also
10826 insert a time. Note that when WITH-TIME is not set, you can still
10827 enter a time, and this function will inform the calling routine about
10828 this change. The calling routine may then choose to change the format
10829 used to insert the time stamp into the buffer to include the time.
10830 With optional argument FROM-STRING, read from this string instead from
10831 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10832 the time/date that is used for everything that is not specified by the
10833 user."
10834 (require 'parse-time)
10835 (let* ((org-time-stamp-rounding-minutes
10836 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10837 (org-dcst org-display-custom-times)
10838 (ct (org-current-time))
10839 (def (or org-overriding-default-time default-time ct))
10840 (defdecode (decode-time def))
10841 (dummy (progn
10842 (when (< (nth 2 defdecode) org-extend-today-until)
10843 (setcar (nthcdr 2 defdecode) -1)
10844 (setcar (nthcdr 1 defdecode) 59)
10845 (setq def (apply 'encode-time defdecode)
10846 defdecode (decode-time def)))))
10847 (calendar-move-hook nil)
10848 (calendar-view-diary-initially-flag nil)
10849 (view-diary-entries-initially nil)
10850 (calendar-view-holidays-initially-flag nil)
10851 (view-calendar-holidays-initially nil)
10852 (timestr (format-time-string
10853 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10854 (prompt (concat (if prompt (concat prompt " ") "")
10855 (format "Date+time [%s]: " timestr)))
10856 ans (org-ans0 "") org-ans1 org-ans2 final)
10858 (cond
10859 (from-string (setq ans from-string))
10860 (org-read-date-popup-calendar
10861 (save-excursion
10862 (save-window-excursion
10863 (calendar)
10864 (calendar-forward-day (- (time-to-days def)
10865 (calendar-absolute-from-gregorian
10866 (calendar-current-date))))
10867 (org-eval-in-calendar nil t)
10868 (let* ((old-map (current-local-map))
10869 (map (copy-keymap calendar-mode-map))
10870 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10871 (org-defkey map (kbd "RET") 'org-calendar-select)
10872 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10873 'org-calendar-select-mouse)
10874 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10875 'org-calendar-select-mouse)
10876 (org-defkey minibuffer-local-map [(meta shift left)]
10877 (lambda () (interactive)
10878 (org-eval-in-calendar '(calendar-backward-month 1))))
10879 (org-defkey minibuffer-local-map [(meta shift right)]
10880 (lambda () (interactive)
10881 (org-eval-in-calendar '(calendar-forward-month 1))))
10882 (org-defkey minibuffer-local-map [(meta shift up)]
10883 (lambda () (interactive)
10884 (org-eval-in-calendar '(calendar-backward-year 1))))
10885 (org-defkey minibuffer-local-map [(meta shift down)]
10886 (lambda () (interactive)
10887 (org-eval-in-calendar '(calendar-forward-year 1))))
10888 (org-defkey minibuffer-local-map [(shift up)]
10889 (lambda () (interactive)
10890 (org-eval-in-calendar '(calendar-backward-week 1))))
10891 (org-defkey minibuffer-local-map [(shift down)]
10892 (lambda () (interactive)
10893 (org-eval-in-calendar '(calendar-forward-week 1))))
10894 (org-defkey minibuffer-local-map [(shift left)]
10895 (lambda () (interactive)
10896 (org-eval-in-calendar '(calendar-backward-day 1))))
10897 (org-defkey minibuffer-local-map [(shift right)]
10898 (lambda () (interactive)
10899 (org-eval-in-calendar '(calendar-forward-day 1))))
10900 (org-defkey minibuffer-local-map ">"
10901 (lambda () (interactive)
10902 (org-eval-in-calendar '(scroll-calendar-left 1))))
10903 (org-defkey minibuffer-local-map "<"
10904 (lambda () (interactive)
10905 (org-eval-in-calendar '(scroll-calendar-right 1))))
10906 (unwind-protect
10907 (progn
10908 (use-local-map map)
10909 (add-hook 'post-command-hook 'org-read-date-display)
10910 (setq org-ans0 (read-string prompt default-input nil nil))
10911 ;; org-ans0: from prompt
10912 ;; org-ans1: from mouse click
10913 ;; org-ans2: from calendar motion
10914 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10915 (remove-hook 'post-command-hook 'org-read-date-display)
10916 (use-local-map old-map)
10917 (when org-read-date-overlay
10918 (org-delete-overlay org-read-date-overlay)
10919 (setq org-read-date-overlay nil)))))))
10921 (t ; Naked prompt only
10922 (unwind-protect
10923 (setq ans (read-string prompt default-input nil timestr))
10924 (when org-read-date-overlay
10925 (org-delete-overlay org-read-date-overlay)
10926 (setq org-read-date-overlay nil)))))
10928 (setq final (org-read-date-analyze ans def defdecode))
10930 (if to-time
10931 (apply 'encode-time final)
10932 (if (and (boundp 'org-time-was-given) org-time-was-given)
10933 (format "%04d-%02d-%02d %02d:%02d"
10934 (nth 5 final) (nth 4 final) (nth 3 final)
10935 (nth 2 final) (nth 1 final))
10936 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10937 (defvar def)
10938 (defvar defdecode)
10939 (defvar with-time)
10940 (defun org-read-date-display ()
10941 "Display the currrent date prompt interpretation in the minibuffer."
10942 (when org-read-date-display-live
10943 (when org-read-date-overlay
10944 (org-delete-overlay org-read-date-overlay))
10945 (let ((p (point)))
10946 (end-of-line 1)
10947 (while (not (equal (buffer-substring
10948 (max (point-min) (- (point) 4)) (point))
10949 " "))
10950 (insert " "))
10951 (goto-char p))
10952 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10953 " " (or org-ans1 org-ans2)))
10954 (org-end-time-was-given nil)
10955 (f (org-read-date-analyze ans def defdecode))
10956 (fmts (if org-dcst
10957 org-time-stamp-custom-formats
10958 org-time-stamp-formats))
10959 (fmt (if (or with-time
10960 (and (boundp 'org-time-was-given) org-time-was-given))
10961 (cdr fmts)
10962 (car fmts)))
10963 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10964 (when (and org-end-time-was-given
10965 (string-match org-plain-time-of-day-regexp txt))
10966 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10967 org-end-time-was-given
10968 (substring txt (match-end 0)))))
10969 (setq org-read-date-overlay
10970 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10971 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10973 (defun org-read-date-analyze (ans def defdecode)
10974 "Analyze the combined answer of the date prompt."
10975 ;; FIXME: cleanup and comment
10976 (let (delta deltan deltaw deltadef year month day
10977 hour minute second wday pm h2 m2 tl wday1
10978 iso-year iso-weekday iso-week iso-year iso-date)
10980 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10981 (setq ans "+0"))
10983 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10984 (setq ans (replace-match "" t t ans)
10985 deltan (car delta)
10986 deltaw (nth 1 delta)
10987 deltadef (nth 2 delta)))
10989 ;; Check if there is an iso week date in there
10990 ;; If yes, sore the info and ostpone interpreting it until the rest
10991 ;; of the parsing is done
10992 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10993 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10994 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10995 iso-week (string-to-number (match-string 2 ans)))
10996 (setq ans (replace-match "" t t ans)))
10998 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10999 (when (string-match
11000 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11001 (setq year (if (match-end 2)
11002 (string-to-number (match-string 2 ans))
11003 (string-to-number (format-time-string "%Y")))
11004 month (string-to-number (match-string 3 ans))
11005 day (string-to-number (match-string 4 ans)))
11006 (if (< year 100) (setq year (+ 2000 year)))
11007 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11008 t nil ans)))
11009 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11010 ;; If there is a time with am/pm, and *no* time without it, we convert
11011 ;; so that matching will be successful.
11012 (loop for i from 1 to 2 do ; twice, for end time as well
11013 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11014 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11015 (setq hour (string-to-number (match-string 1 ans))
11016 minute (if (match-end 3)
11017 (string-to-number (match-string 3 ans))
11019 pm (equal ?p
11020 (string-to-char (downcase (match-string 4 ans)))))
11021 (if (and (= hour 12) (not pm))
11022 (setq hour 0)
11023 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11024 (setq ans (replace-match (format "%02d:%02d" hour minute)
11025 t t ans))))
11027 ;; Check if a time range is given as a duration
11028 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11029 (setq hour (string-to-number (match-string 1 ans))
11030 h2 (+ hour (string-to-number (match-string 3 ans)))
11031 minute (string-to-number (match-string 2 ans))
11032 m2 (+ minute (if (match-end 5) (string-to-number
11033 (match-string 5 ans))0)))
11034 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11035 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11036 t t ans)))
11038 ;; Check if there is a time range
11039 (when (boundp 'org-end-time-was-given)
11040 (setq org-time-was-given nil)
11041 (when (and (string-match org-plain-time-of-day-regexp ans)
11042 (match-end 8))
11043 (setq org-end-time-was-given (match-string 8 ans))
11044 (setq ans (concat (substring ans 0 (match-beginning 7))
11045 (substring ans (match-end 7))))))
11047 (setq tl (parse-time-string ans)
11048 day (or (nth 3 tl) (nth 3 defdecode))
11049 month (or (nth 4 tl)
11050 (if (and org-read-date-prefer-future
11051 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11052 (1+ (nth 4 defdecode))
11053 (nth 4 defdecode)))
11054 year (or (nth 5 tl)
11055 (if (and org-read-date-prefer-future
11056 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11057 (1+ (nth 5 defdecode))
11058 (nth 5 defdecode)))
11059 hour (or (nth 2 tl) (nth 2 defdecode))
11060 minute (or (nth 1 tl) (nth 1 defdecode))
11061 second (or (nth 0 tl) 0)
11062 wday (nth 6 tl))
11064 ;; Special date definitions below
11065 (cond
11066 (iso-week
11067 ;; There was an iso week
11068 (setq year (or iso-year year)
11069 day (or iso-weekday wday 1)
11070 wday nil ; to make sure that the trigger below does not match
11071 iso-date (calendar-gregorian-from-absolute
11072 (calendar-absolute-from-iso
11073 (list iso-week day year))))
11074 ; FIXME: Should we also push ISO weeks into the future?
11075 ; (when (and org-read-date-prefer-future
11076 ; (not iso-year)
11077 ; (< (calendar-absolute-from-gregorian iso-date)
11078 ; (time-to-days (current-time))))
11079 ; (setq year (1+ year)
11080 ; iso-date (calendar-gregorian-from-absolute
11081 ; (calendar-absolute-from-iso
11082 ; (list iso-week day year)))))
11083 (setq month (car iso-date)
11084 year (nth 2 iso-date)
11085 day (nth 1 iso-date)))
11086 (deltan
11087 (unless deltadef
11088 (let ((now (decode-time (current-time))))
11089 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11090 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11091 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11092 ((equal deltaw "m") (setq month (+ month deltan)))
11093 ((equal deltaw "y") (setq year (+ year deltan)))))
11094 ((and wday (not (nth 3 tl)))
11095 ;; Weekday was given, but no day, so pick that day in the week
11096 ;; on or after the derived date.
11097 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11098 (unless (equal wday wday1)
11099 (setq day (+ day (% (- wday wday1 -7) 7))))))
11100 (if (and (boundp 'org-time-was-given)
11101 (nth 2 tl))
11102 (setq org-time-was-given t))
11103 (if (< year 100) (setq year (+ 2000 year)))
11104 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11105 (list second minute hour day month year)))
11107 (defvar parse-time-weekdays)
11109 (defun org-read-date-get-relative (s today default)
11110 "Check string S for special relative date string.
11111 TODAY and DEFAULT are internal times, for today and for a default.
11112 Return shift list (N what def-flag)
11113 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11114 N is the number of WHATs to shift.
11115 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11116 the DEFAULT date rather than TODAY."
11117 (when (and
11118 (string-match
11119 (concat
11120 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11121 "\\([0-9]+\\)?"
11122 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11123 "\\([ \t]\\|$\\)") s)
11124 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11125 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11126 (string-to-char (substring (match-string 1 s) -1))
11127 ?+))
11128 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11129 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11130 (what (if (match-end 3) (match-string 3 s) "d"))
11131 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11132 (date (if rel default today))
11133 (wday (nth 6 (decode-time date)))
11134 delta)
11135 (if wday1
11136 (progn
11137 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11138 (if (= dir ?-) (setq delta (- delta 7)))
11139 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11140 (list delta "d" rel))
11141 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11143 (defun org-eval-in-calendar (form &optional keepdate)
11144 "Eval FORM in the calendar window and return to current window.
11145 Also, store the cursor date in variable org-ans2."
11146 (let ((sw (selected-window)))
11147 (select-window (get-buffer-window "*Calendar*"))
11148 (eval form)
11149 (when (and (not keepdate) (calendar-cursor-to-date))
11150 (let* ((date (calendar-cursor-to-date))
11151 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11152 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11153 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11154 (select-window sw)))
11156 ; ;; Update the prompt to show new default date
11157 ; (save-excursion
11158 ; (goto-char (point-min))
11159 ; (when (and org-ans2
11160 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
11161 ; (get-text-property (match-end 0) 'field))
11162 ; (let ((inhibit-read-only t))
11163 ; (replace-match (concat "[" org-ans2 "]") t t)
11164 ; (add-text-properties (point-min) (1+ (match-end 0))
11165 ; (text-properties-at (1+ (point-min)))))))))
11167 (defun org-calendar-select ()
11168 "Return to `org-read-date' with the date currently selected.
11169 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11170 (interactive)
11171 (when (calendar-cursor-to-date)
11172 (let* ((date (calendar-cursor-to-date))
11173 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11174 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11175 (if (active-minibuffer-window) (exit-minibuffer))))
11177 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11178 "Insert a date stamp for the date given by the internal TIME.
11179 WITH-HM means, use the stamp format that includes the time of the day.
11180 INACTIVE means use square brackets instead of angular ones, so that the
11181 stamp will not contribute to the agenda.
11182 PRE and POST are optional strings to be inserted before and after the
11183 stamp.
11184 The command returns the inserted time stamp."
11185 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11186 stamp)
11187 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11188 (insert-before-markers (or pre ""))
11189 (insert-before-markers (setq stamp (format-time-string fmt time)))
11190 (when (listp extra)
11191 (setq extra (car extra))
11192 (if (and (stringp extra)
11193 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11194 (setq extra (format "-%02d:%02d"
11195 (string-to-number (match-string 1 extra))
11196 (string-to-number (match-string 2 extra))))
11197 (setq extra nil)))
11198 (when extra
11199 (backward-char 1)
11200 (insert-before-markers extra)
11201 (forward-char 1))
11202 (insert-before-markers (or post ""))
11203 (setq org-last-inserted-timestamp stamp)))
11205 (defun org-toggle-time-stamp-overlays ()
11206 "Toggle the use of custom time stamp formats."
11207 (interactive)
11208 (setq org-display-custom-times (not org-display-custom-times))
11209 (unless org-display-custom-times
11210 (let ((p (point-min)) (bmp (buffer-modified-p)))
11211 (while (setq p (next-single-property-change p 'display))
11212 (if (and (get-text-property p 'display)
11213 (eq (get-text-property p 'face) 'org-date))
11214 (remove-text-properties
11215 p (setq p (next-single-property-change p 'display))
11216 '(display t))))
11217 (set-buffer-modified-p bmp)))
11218 (if (featurep 'xemacs)
11219 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11220 (org-restart-font-lock)
11221 (setq org-table-may-need-update t)
11222 (if org-display-custom-times
11223 (message "Time stamps are overlayed with custom format")
11224 (message "Time stamp overlays removed")))
11226 (defun org-display-custom-time (beg end)
11227 "Overlay modified time stamp format over timestamp between BEG and END."
11228 (let* ((ts (buffer-substring beg end))
11229 t1 w1 with-hm tf time str w2 (off 0))
11230 (save-match-data
11231 (setq t1 (org-parse-time-string ts t))
11232 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11233 (setq off (- (match-end 0) (match-beginning 0)))))
11234 (setq end (- end off))
11235 (setq w1 (- end beg)
11236 with-hm (and (nth 1 t1) (nth 2 t1))
11237 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11238 time (org-fix-decoded-time t1)
11239 str (org-add-props
11240 (format-time-string
11241 (substring tf 1 -1) (apply 'encode-time time))
11242 nil 'mouse-face 'highlight)
11243 w2 (length str))
11244 (if (not (= w2 w1))
11245 (add-text-properties (1+ beg) (+ 2 beg)
11246 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11247 (if (featurep 'xemacs)
11248 (progn
11249 (put-text-property beg end 'invisible t)
11250 (put-text-property beg end 'end-glyph (make-glyph str)))
11251 (put-text-property beg end 'display str))))
11253 (defun org-translate-time (string)
11254 "Translate all timestamps in STRING to custom format.
11255 But do this only if the variable `org-display-custom-times' is set."
11256 (when org-display-custom-times
11257 (save-match-data
11258 (let* ((start 0)
11259 (re org-ts-regexp-both)
11260 t1 with-hm inactive tf time str beg end)
11261 (while (setq start (string-match re string start))
11262 (setq beg (match-beginning 0)
11263 end (match-end 0)
11264 t1 (save-match-data
11265 (org-parse-time-string (substring string beg end) t))
11266 with-hm (and (nth 1 t1) (nth 2 t1))
11267 inactive (equal (substring string beg (1+ beg)) "[")
11268 tf (funcall (if with-hm 'cdr 'car)
11269 org-time-stamp-custom-formats)
11270 time (org-fix-decoded-time t1)
11271 str (format-time-string
11272 (concat
11273 (if inactive "[" "<") (substring tf 1 -1)
11274 (if inactive "]" ">"))
11275 (apply 'encode-time time))
11276 string (replace-match str t t string)
11277 start (+ start (length str)))))))
11278 string)
11280 (defun org-fix-decoded-time (time)
11281 "Set 0 instead of nil for the first 6 elements of time.
11282 Don't touch the rest."
11283 (let ((n 0))
11284 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11286 (defun org-days-to-time (timestamp-string)
11287 "Difference between TIMESTAMP-STRING and now in days."
11288 (- (time-to-days (org-time-string-to-time timestamp-string))
11289 (time-to-days (current-time))))
11291 (defun org-deadline-close (timestamp-string &optional ndays)
11292 "Is the time in TIMESTAMP-STRING close to the current date?"
11293 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11294 (and (< (org-days-to-time timestamp-string) ndays)
11295 (not (org-entry-is-done-p))))
11297 (defun org-get-wdays (ts)
11298 "Get the deadline lead time appropriate for timestring TS."
11299 (cond
11300 ((<= org-deadline-warning-days 0)
11301 ;; 0 or negative, enforce this value no matter what
11302 (- org-deadline-warning-days))
11303 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11304 ;; lead time is specified.
11305 (floor (* (string-to-number (match-string 1 ts))
11306 (cdr (assoc (match-string 2 ts)
11307 '(("d" . 1) ("w" . 7)
11308 ("m" . 30.4) ("y" . 365.25)))))))
11309 ;; go for the default.
11310 (t org-deadline-warning-days)))
11312 (defun org-calendar-select-mouse (ev)
11313 "Return to `org-read-date' with the date currently selected.
11314 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11315 (interactive "e")
11316 (mouse-set-point ev)
11317 (when (calendar-cursor-to-date)
11318 (let* ((date (calendar-cursor-to-date))
11319 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11320 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11321 (if (active-minibuffer-window) (exit-minibuffer))))
11323 (defun org-check-deadlines (ndays)
11324 "Check if there are any deadlines due or past due.
11325 A deadline is considered due if it happens within `org-deadline-warning-days'
11326 days from today's date. If the deadline appears in an entry marked DONE,
11327 it is not shown. The prefix arg NDAYS can be used to test that many
11328 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11329 (interactive "P")
11330 (let* ((org-warn-days
11331 (cond
11332 ((equal ndays '(4)) 100000)
11333 (ndays (prefix-numeric-value ndays))
11334 (t (abs org-deadline-warning-days))))
11335 (case-fold-search nil)
11336 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11337 (callback
11338 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11340 (message "%d deadlines past-due or due within %d days"
11341 (org-occur regexp nil callback)
11342 org-warn-days)))
11344 (defun org-check-before-date (date)
11345 "Check if there are deadlines or scheduled entries before DATE."
11346 (interactive (list (org-read-date)))
11347 (let ((case-fold-search nil)
11348 (regexp (concat "\\<\\(" org-deadline-string
11349 "\\|" org-scheduled-string
11350 "\\) *<\\([^>]+\\)>"))
11351 (callback
11352 (lambda () (time-less-p
11353 (org-time-string-to-time (match-string 2))
11354 (org-time-string-to-time date)))))
11355 (message "%d entries before %s"
11356 (org-occur regexp nil callback) date)))
11358 (defun org-evaluate-time-range (&optional to-buffer)
11359 "Evaluate a time range by computing the difference between start and end.
11360 Normally the result is just printed in the echo area, but with prefix arg
11361 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11362 If the time range is actually in a table, the result is inserted into the
11363 next column.
11364 For time difference computation, a year is assumed to be exactly 365
11365 days in order to avoid rounding problems."
11366 (interactive "P")
11368 (org-clock-update-time-maybe)
11369 (save-excursion
11370 (unless (org-at-date-range-p t)
11371 (goto-char (point-at-bol))
11372 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11373 (if (not (org-at-date-range-p t))
11374 (error "Not at a time-stamp range, and none found in current line")))
11375 (let* ((ts1 (match-string 1))
11376 (ts2 (match-string 2))
11377 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11378 (match-end (match-end 0))
11379 (time1 (org-time-string-to-time ts1))
11380 (time2 (org-time-string-to-time ts2))
11381 (t1 (time-to-seconds time1))
11382 (t2 (time-to-seconds time2))
11383 (diff (abs (- t2 t1)))
11384 (negative (< (- t2 t1) 0))
11385 ;; (ys (floor (* 365 24 60 60)))
11386 (ds (* 24 60 60))
11387 (hs (* 60 60))
11388 (fy "%dy %dd %02d:%02d")
11389 (fy1 "%dy %dd")
11390 (fd "%dd %02d:%02d")
11391 (fd1 "%dd")
11392 (fh "%02d:%02d")
11393 y d h m align)
11394 (if havetime
11395 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11397 d (floor (/ diff ds)) diff (mod diff ds)
11398 h (floor (/ diff hs)) diff (mod diff hs)
11399 m (floor (/ diff 60)))
11400 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11402 d (floor (+ (/ diff ds) 0.5))
11403 h 0 m 0))
11404 (if (not to-buffer)
11405 (message "%s" (org-make-tdiff-string y d h m))
11406 (if (org-at-table-p)
11407 (progn
11408 (goto-char match-end)
11409 (setq align t)
11410 (and (looking-at " *|") (goto-char (match-end 0))))
11411 (goto-char match-end))
11412 (if (looking-at
11413 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11414 (replace-match ""))
11415 (if negative (insert " -"))
11416 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11417 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11418 (insert " " (format fh h m))))
11419 (if align (org-table-align))
11420 (message "Time difference inserted")))))
11422 (defun org-make-tdiff-string (y d h m)
11423 (let ((fmt "")
11424 (l nil))
11425 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11426 l (push y l)))
11427 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11428 l (push d l)))
11429 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11430 l (push h l)))
11431 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11432 l (push m l)))
11433 (apply 'format fmt (nreverse l))))
11435 (defun org-time-string-to-time (s)
11436 (apply 'encode-time (org-parse-time-string s)))
11438 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11439 "Convert a time stamp to an absolute day number.
11440 If there is a specifyer for a cyclic time stamp, get the closest date to
11441 DAYNR.
11442 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11443 (cond
11444 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11445 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11446 daynr
11447 (+ daynr 1000)))
11448 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11449 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11450 (time-to-days (current-time))) (match-string 0 s)
11451 prefer show-all))
11452 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11454 (defun org-days-to-iso-week (days)
11455 "Return the iso week number."
11456 (require 'cal-iso)
11457 (car (calendar-iso-from-absolute days)))
11459 (defun org-small-year-to-year (year)
11460 "Convert 2-digit years into 4-digit years.
11461 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11462 The year 2000 cannot be abbreviated. Any year lager than 99
11463 is retrned unchanged."
11464 (if (< year 38)
11465 (setq year (+ 2000 year))
11466 (if (< year 100)
11467 (setq year (+ 1900 year))))
11468 year)
11470 (defun org-time-from-absolute (d)
11471 "Return the time corresponding to date D.
11472 D may be an absolute day number, or a calendar-type list (month day year)."
11473 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11474 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11476 (defun org-calendar-holiday ()
11477 "List of holidays, for Diary display in Org-mode."
11478 (require 'holidays)
11479 (let ((hl (funcall
11480 (if (fboundp 'calendar-check-holidays)
11481 'calendar-check-holidays 'check-calendar-holidays) date)))
11482 (if hl (mapconcat 'identity hl "; "))))
11484 (defun org-diary-sexp-entry (sexp entry date)
11485 "Process a SEXP diary ENTRY for DATE."
11486 (require 'diary-lib)
11487 (let ((result (if calendar-debug-sexp
11488 (let ((stack-trace-on-error t))
11489 (eval (car (read-from-string sexp))))
11490 (condition-case nil
11491 (eval (car (read-from-string sexp)))
11492 (error
11493 (beep)
11494 (message "Bad sexp at line %d in %s: %s"
11495 (org-current-line)
11496 (buffer-file-name) sexp)
11497 (sleep-for 2))))))
11498 (cond ((stringp result) result)
11499 ((and (consp result)
11500 (stringp (cdr result))) (cdr result))
11501 (result entry)
11502 (t nil))))
11504 (defun org-diary-to-ical-string (frombuf)
11505 "Get iCalendar entries from diary entries in buffer FROMBUF.
11506 This uses the icalendar.el library."
11507 (let* ((tmpdir (if (featurep 'xemacs)
11508 (temp-directory)
11509 temporary-file-directory))
11510 (tmpfile (make-temp-name
11511 (expand-file-name "orgics" tmpdir)))
11512 buf rtn b e)
11513 (save-excursion
11514 (set-buffer frombuf)
11515 (icalendar-export-region (point-min) (point-max) tmpfile)
11516 (setq buf (find-buffer-visiting tmpfile))
11517 (set-buffer buf)
11518 (goto-char (point-min))
11519 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11520 (setq b (match-beginning 0)))
11521 (goto-char (point-max))
11522 (if (re-search-backward "^END:VEVENT" nil t)
11523 (setq e (match-end 0)))
11524 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11525 (kill-buffer buf)
11526 (delete-file tmpfile)
11527 rtn))
11529 (defun org-closest-date (start current change prefer show-all)
11530 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11531 When PREFER is `past' return a date that is either CURRENT or past.
11532 When PREFER is `future', return a date that is either CURRENT or future.
11533 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11534 ;; Make the proper lists from the dates
11535 (catch 'exit
11536 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11537 dn dw sday cday n1 n2
11538 d m y y1 y2 date1 date2 nmonths nm ny m2)
11540 (setq start (org-date-to-gregorian start)
11541 current (org-date-to-gregorian
11542 (if show-all
11543 current
11544 (time-to-days (current-time))))
11545 sday (calendar-absolute-from-gregorian start)
11546 cday (calendar-absolute-from-gregorian current))
11548 (if (<= cday sday) (throw 'exit sday))
11550 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11551 (setq dn (string-to-number (match-string 1 change))
11552 dw (cdr (assoc (match-string 2 change) a1)))
11553 (error "Invalid change specifyer: %s" change))
11554 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11555 (cond
11556 ((eq dw 'day)
11557 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11558 n2 (+ n1 dn)))
11559 ((eq dw 'year)
11560 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11561 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11562 (setq date1 (list m d y1)
11563 n1 (calendar-absolute-from-gregorian date1)
11564 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11565 n2 (calendar-absolute-from-gregorian date2)))
11566 ((eq dw 'month)
11567 ;; approx number of month between the two dates
11568 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11569 ;; How often does dn fit in there?
11570 (setq d (nth 1 start) m (car start) y (nth 2 start)
11571 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11572 m (+ m nm)
11573 ny (floor (/ m 12))
11574 y (+ y ny)
11575 m (- m (* ny 12)))
11576 (while (> m 12) (setq m (- m 12) y (1+ y)))
11577 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11578 (setq m2 (+ m dn) y2 y)
11579 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11580 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11581 (while (<= n2 cday)
11582 (setq n1 n2 m m2 y y2)
11583 (setq m2 (+ m dn) y2 y)
11584 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11585 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11586 (if show-all
11587 (cond
11588 ((eq prefer 'past) n1)
11589 ((eq prefer 'future) (if (= cday n1) n1 n2))
11590 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11591 (cond
11592 ((eq prefer 'past) n1)
11593 ((eq prefer 'future) (if (= cday n1) n1 n2))
11594 (t (if (= cday n1) n1 n2)))))))
11596 (defun org-date-to-gregorian (date)
11597 "Turn any specification of DATE into a gregorian date for the calendar."
11598 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11599 ((and (listp date) (= (length date) 3)) date)
11600 ((stringp date)
11601 (setq date (org-parse-time-string date))
11602 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11603 ((listp date)
11604 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11606 (defun org-parse-time-string (s &optional nodefault)
11607 "Parse the standard Org-mode time string.
11608 This should be a lot faster than the normal `parse-time-string'.
11609 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11610 hour and minute fields will be nil if not given."
11611 (if (string-match org-ts-regexp0 s)
11612 (list 0
11613 (if (or (match-beginning 8) (not nodefault))
11614 (string-to-number (or (match-string 8 s) "0")))
11615 (if (or (match-beginning 7) (not nodefault))
11616 (string-to-number (or (match-string 7 s) "0")))
11617 (string-to-number (match-string 4 s))
11618 (string-to-number (match-string 3 s))
11619 (string-to-number (match-string 2 s))
11620 nil nil nil)
11621 (make-list 9 0)))
11623 (defun org-timestamp-up (&optional arg)
11624 "Increase the date item at the cursor by one.
11625 If the cursor is on the year, change the year. If it is on the month or
11626 the day, change that.
11627 With prefix ARG, change by that many units."
11628 (interactive "p")
11629 (org-timestamp-change (prefix-numeric-value arg)))
11631 (defun org-timestamp-down (&optional arg)
11632 "Decrease the date item at the cursor by one.
11633 If the cursor is on the year, change the year. If it is on the month or
11634 the day, change that.
11635 With prefix ARG, change by that many units."
11636 (interactive "p")
11637 (org-timestamp-change (- (prefix-numeric-value arg))))
11639 (defun org-timestamp-up-day (&optional arg)
11640 "Increase the date in the time stamp by one day.
11641 With prefix ARG, change that many days."
11642 (interactive "p")
11643 (if (and (not (org-at-timestamp-p t))
11644 (org-on-heading-p))
11645 (org-todo 'up)
11646 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11648 (defun org-timestamp-down-day (&optional arg)
11649 "Decrease the date in the time stamp by one day.
11650 With prefix ARG, change that many days."
11651 (interactive "p")
11652 (if (and (not (org-at-timestamp-p t))
11653 (org-on-heading-p))
11654 (org-todo 'down)
11655 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11657 (defun org-at-timestamp-p (&optional inactive-ok)
11658 "Determine if the cursor is in or at a timestamp."
11659 (interactive)
11660 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11661 (pos (point))
11662 (ans (or (looking-at tsr)
11663 (save-excursion
11664 (skip-chars-backward "^[<\n\r\t")
11665 (if (> (point) (point-min)) (backward-char 1))
11666 (and (looking-at tsr)
11667 (> (- (match-end 0) pos) -1))))))
11668 (and ans
11669 (boundp 'org-ts-what)
11670 (setq org-ts-what
11671 (cond
11672 ((= pos (match-beginning 0)) 'bracket)
11673 ((= pos (1- (match-end 0))) 'bracket)
11674 ((org-pos-in-match-range pos 2) 'year)
11675 ((org-pos-in-match-range pos 3) 'month)
11676 ((org-pos-in-match-range pos 7) 'hour)
11677 ((org-pos-in-match-range pos 8) 'minute)
11678 ((or (org-pos-in-match-range pos 4)
11679 (org-pos-in-match-range pos 5)) 'day)
11680 ((and (> pos (or (match-end 8) (match-end 5)))
11681 (< pos (match-end 0)))
11682 (- pos (or (match-end 8) (match-end 5))))
11683 (t 'day))))
11684 ans))
11686 (defun org-toggle-timestamp-type ()
11687 "Toggle the type (<active> or [inactive]) of a time stamp."
11688 (interactive)
11689 (when (org-at-timestamp-p t)
11690 (save-excursion
11691 (goto-char (match-beginning 0))
11692 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11693 (goto-char (1- (match-end 0)))
11694 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11695 (message "Timestamp is now %sactive"
11696 (if (equal (char-before) ?>) "in" ""))))
11698 (defun org-timestamp-change (n &optional what)
11699 "Change the date in the time stamp at point.
11700 The date will be changed by N times WHAT. WHAT can be `day', `month',
11701 `year', `minute', `second'. If WHAT is not given, the cursor position
11702 in the timestamp determines what will be changed."
11703 (let ((pos (point))
11704 with-hm inactive
11705 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11706 org-ts-what
11707 extra rem
11708 ts time time0)
11709 (if (not (org-at-timestamp-p t))
11710 (error "Not at a timestamp"))
11711 (if (and (not what) (eq org-ts-what 'bracket))
11712 (org-toggle-timestamp-type)
11713 (if (and (not what) (not (eq org-ts-what 'day))
11714 org-display-custom-times
11715 (get-text-property (point) 'display)
11716 (not (get-text-property (1- (point)) 'display)))
11717 (setq org-ts-what 'day))
11718 (setq org-ts-what (or what org-ts-what)
11719 inactive (= (char-after (match-beginning 0)) ?\[)
11720 ts (match-string 0))
11721 (replace-match "")
11722 (if (string-match
11723 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11725 (setq extra (match-string 1 ts)))
11726 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11727 (setq with-hm t))
11728 (setq time0 (org-parse-time-string ts))
11729 (when (and (eq org-ts-what 'minute)
11730 (eq current-prefix-arg nil))
11731 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11732 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11733 (setcar (cdr time0) (+ (nth 1 time0)
11734 (if (> n 0) (- rem) (- dm rem))))))
11735 (setq time
11736 (encode-time (or (car time0) 0)
11737 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11738 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11739 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11740 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11741 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11742 (nthcdr 6 time0)))
11743 (when (integerp org-ts-what)
11744 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11745 (if (eq what 'calendar)
11746 (let ((cal-date (org-get-date-from-calendar)))
11747 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11748 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11749 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11750 (setcar time0 (or (car time0) 0))
11751 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11752 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11753 (setq time (apply 'encode-time time0))))
11754 (setq org-last-changed-timestamp
11755 (org-insert-time-stamp time with-hm inactive nil nil extra))
11756 (org-clock-update-time-maybe)
11757 (goto-char pos)
11758 ;; Try to recenter the calendar window, if any
11759 (if (and org-calendar-follow-timestamp-change
11760 (get-buffer-window "*Calendar*" t)
11761 (memq org-ts-what '(day month year)))
11762 (org-recenter-calendar (time-to-days time))))))
11764 (defun org-modify-ts-extra (s pos n dm)
11765 "Change the different parts of the lead-time and repeat fields in timestamp."
11766 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11767 ng h m new rem)
11768 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11769 (cond
11770 ((or (org-pos-in-match-range pos 2)
11771 (org-pos-in-match-range pos 3))
11772 (setq m (string-to-number (match-string 3 s))
11773 h (string-to-number (match-string 2 s)))
11774 (if (org-pos-in-match-range pos 2)
11775 (setq h (+ h n))
11776 (setq n (* dm (org-no-warnings (signum n))))
11777 (when (not (= 0 (setq rem (% m dm))))
11778 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11779 (setq m (+ m n)))
11780 (if (< m 0) (setq m (+ m 60) h (1- h)))
11781 (if (> m 59) (setq m (- m 60) h (1+ h)))
11782 (setq h (min 24 (max 0 h)))
11783 (setq ng 1 new (format "-%02d:%02d" h m)))
11784 ((org-pos-in-match-range pos 6)
11785 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11786 ((org-pos-in-match-range pos 5)
11787 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11789 ((org-pos-in-match-range pos 9)
11790 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11791 ((org-pos-in-match-range pos 8)
11792 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11794 (when ng
11795 (setq s (concat
11796 (substring s 0 (match-beginning ng))
11798 (substring s (match-end ng))))))
11801 (defun org-recenter-calendar (date)
11802 "If the calendar is visible, recenter it to DATE."
11803 (let* ((win (selected-window))
11804 (cwin (get-buffer-window "*Calendar*" t))
11805 (calendar-move-hook nil))
11806 (when cwin
11807 (select-window cwin)
11808 (calendar-goto-date (if (listp date) date
11809 (calendar-gregorian-from-absolute date)))
11810 (select-window win))))
11812 (defun org-goto-calendar (&optional arg)
11813 "Go to the Emacs calendar at the current date.
11814 If there is a time stamp in the current line, go to that date.
11815 A prefix ARG can be used to force the current date."
11816 (interactive "P")
11817 (let ((tsr org-ts-regexp) diff
11818 (calendar-move-hook nil)
11819 (calendar-view-holidays-initially-flag nil)
11820 (view-calendar-holidays-initially nil)
11821 (calendar-view-diary-initially-flag nil)
11822 (view-diary-entries-initially nil))
11823 (if (or (org-at-timestamp-p)
11824 (save-excursion
11825 (beginning-of-line 1)
11826 (looking-at (concat ".*" tsr))))
11827 (let ((d1 (time-to-days (current-time)))
11828 (d2 (time-to-days
11829 (org-time-string-to-time (match-string 1)))))
11830 (setq diff (- d2 d1))))
11831 (calendar)
11832 (calendar-goto-today)
11833 (if (and diff (not arg)) (calendar-forward-day diff))))
11835 (defun org-get-date-from-calendar ()
11836 "Return a list (month day year) of date at point in calendar."
11837 (with-current-buffer "*Calendar*"
11838 (save-match-data
11839 (calendar-cursor-to-date))))
11841 (defun org-date-from-calendar ()
11842 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11843 If there is already a time stamp at the cursor position, update it."
11844 (interactive)
11845 (if (org-at-timestamp-p t)
11846 (org-timestamp-change 0 'calendar)
11847 (let ((cal-date (org-get-date-from-calendar)))
11848 (org-insert-time-stamp
11849 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11851 (defun org-minutes-to-hh:mm-string (m)
11852 "Compute H:MM from a number of minutes."
11853 (let ((h (/ m 60)))
11854 (setq m (- m (* 60 h)))
11855 (format org-time-clocksum-format h m)))
11857 (defun org-hh:mm-string-to-minutes (s)
11858 "Convert a string H:MM to a number of minutes."
11859 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11860 (+ (* (string-to-number (match-string 1 s)) 60)
11861 (string-to-number (match-string 2 s)))
11864 ;;;; Agenda files
11866 ;;;###autoload
11867 (defun org-iswitchb (&optional arg)
11868 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11869 With a prefix argument, restrict available to files.
11870 With two prefix arguments, restrict available buffers to agenda files.
11872 Due to some yet unresolved reason, global function
11873 `iswitchb-mode' needs to be active for this function to work."
11874 (interactive "P")
11875 (require 'iswitchb)
11876 (let ((enabled iswitchb-mode) blist)
11877 (or enabled (iswitchb-mode 1))
11878 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11879 ((equal arg '(16)) (org-buffer-list 'agenda))
11880 (t (org-buffer-list))))
11881 (unwind-protect
11882 (let ((iswitchb-make-buflist-hook
11883 (lambda ()
11884 (setq iswitchb-temp-buflist
11885 (mapcar 'buffer-name blist)))))
11886 (switch-to-buffer
11887 (iswitchb-read-buffer
11888 "Switch-to: " nil t))
11889 (or enabled (iswitchb-mode -1))))))
11891 (defun org-buffer-list (&optional predicate tmp)
11892 "Return a list of Org buffers.
11893 PREDICATE can be either 'export, 'files or 'agenda.
11895 'export restrict the list to Export buffers.
11896 'files restrict the list to buffers visiting Org files.
11897 'agenda restrict the list to buffers visiting agenda files.
11899 If TMP is non-nil, don't include temporary buffers."
11900 (let (filter blist)
11901 (setq filter
11902 (cond ((eq predicate 'files) "\.org$")
11903 ((eq predicate 'export) "\*Org .*Export")
11904 (t "\*Org \\|\.org$")))
11905 (setq blist
11906 (mapcar
11907 (lambda(b)
11908 (let ((bname (buffer-name b))
11909 (bfile (buffer-file-name b)))
11910 (if (and (string-match filter bname)
11911 (if (eq predicate 'agenda)
11912 (member bfile
11913 (mapcar (lambda(f) (file-truename f))
11914 org-agenda-files)) t)
11915 (if tmp (not (string-match "tmp" bname)) t)) b)))
11916 (buffer-list)))
11917 (delete nil blist)))
11919 (defun org-agenda-files (&optional unrestricted archives)
11920 "Get the list of agenda files.
11921 Optional UNRESTRICTED means return the full list even if a restriction
11922 is currently in place.
11923 When ARCHIVES is t, include all archive files hat are really being
11924 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11925 `org-agenda-archives-mode' is t."
11926 (let ((files
11927 (cond
11928 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11929 ((stringp org-agenda-files) (org-read-agenda-file-list))
11930 ((listp org-agenda-files) org-agenda-files)
11931 (t (error "Invalid value of `org-agenda-files'")))))
11932 (setq files (apply 'append
11933 (mapcar (lambda (f)
11934 (if (file-directory-p f)
11935 (directory-files
11936 f t org-agenda-file-regexp)
11937 (list f)))
11938 files)))
11939 (when org-agenda-skip-unavailable-files
11940 (setq files (delq nil
11941 (mapcar (function
11942 (lambda (file)
11943 (and (file-readable-p file) file)))
11944 files))))
11945 (when (or (eq archives t)
11946 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11947 (setq files (org-add-archive-files files)))
11948 files))
11950 (defun org-edit-agenda-file-list ()
11951 "Edit the list of agenda files.
11952 Depending on setup, this either uses customize to edit the variable
11953 `org-agenda-files', or it visits the file that is holding the list. In the
11954 latter case, the buffer is set up in a way that saving it automatically kills
11955 the buffer and restores the previous window configuration."
11956 (interactive)
11957 (if (stringp org-agenda-files)
11958 (let ((cw (current-window-configuration)))
11959 (find-file org-agenda-files)
11960 (org-set-local 'org-window-configuration cw)
11961 (org-add-hook 'after-save-hook
11962 (lambda ()
11963 (set-window-configuration
11964 (prog1 org-window-configuration
11965 (kill-buffer (current-buffer))))
11966 (org-install-agenda-files-menu)
11967 (message "New agenda file list installed"))
11968 nil 'local)
11969 (message "%s" (substitute-command-keys
11970 "Edit list and finish with \\[save-buffer]")))
11971 (customize-variable 'org-agenda-files)))
11973 (defun org-store-new-agenda-file-list (list)
11974 "Set new value for the agenda file list and save it correcly."
11975 (if (stringp org-agenda-files)
11976 (let ((f org-agenda-files) b)
11977 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11978 (with-temp-file f
11979 (insert (mapconcat 'identity list "\n") "\n")))
11980 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11981 (setq org-agenda-files list)
11982 (customize-save-variable 'org-agenda-files org-agenda-files))))
11984 (defun org-read-agenda-file-list ()
11985 "Read the list of agenda files from a file."
11986 (when (file-directory-p org-agenda-files)
11987 (error "`org-agenda-files' cannot be a single directory"))
11988 (when (stringp org-agenda-files)
11989 (with-temp-buffer
11990 (insert-file-contents org-agenda-files)
11991 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11994 ;;;###autoload
11995 (defun org-cycle-agenda-files ()
11996 "Cycle through the files in `org-agenda-files'.
11997 If the current buffer visits an agenda file, find the next one in the list.
11998 If the current buffer does not, find the first agenda file."
11999 (interactive)
12000 (let* ((fs (org-agenda-files t))
12001 (files (append fs (list (car fs))))
12002 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12003 file)
12004 (unless files (error "No agenda files"))
12005 (catch 'exit
12006 (while (setq file (pop files))
12007 (if (equal (file-truename file) tcf)
12008 (when (car files)
12009 (find-file (car files))
12010 (throw 'exit t))))
12011 (find-file (car fs)))
12012 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12014 (defun org-agenda-file-to-front (&optional to-end)
12015 "Move/add the current file to the top of the agenda file list.
12016 If the file is not present in the list, it is added to the front. If it is
12017 present, it is moved there. With optional argument TO-END, add/move to the
12018 end of the list."
12019 (interactive "P")
12020 (let ((org-agenda-skip-unavailable-files nil)
12021 (file-alist (mapcar (lambda (x)
12022 (cons (file-truename x) x))
12023 (org-agenda-files t)))
12024 (ctf (file-truename buffer-file-name))
12025 x had)
12026 (setq x (assoc ctf file-alist) had x)
12028 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12029 (if to-end
12030 (setq file-alist (append (delq x file-alist) (list x)))
12031 (setq file-alist (cons x (delq x file-alist))))
12032 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12033 (org-install-agenda-files-menu)
12034 (message "File %s to %s of agenda file list"
12035 (if had "moved" "added") (if to-end "end" "front"))))
12037 (defun org-remove-file (&optional file)
12038 "Remove current file from the list of files in variable `org-agenda-files'.
12039 These are the files which are being checked for agenda entries.
12040 Optional argument FILE means, use this file instead of the current."
12041 (interactive)
12042 (let* ((org-agenda-skip-unavailable-files nil)
12043 (file (or file buffer-file-name))
12044 (true-file (file-truename file))
12045 (afile (abbreviate-file-name file))
12046 (files (delq nil (mapcar
12047 (lambda (x)
12048 (if (equal true-file
12049 (file-truename x))
12050 nil x))
12051 (org-agenda-files t)))))
12052 (if (not (= (length files) (length (org-agenda-files t))))
12053 (progn
12054 (org-store-new-agenda-file-list files)
12055 (org-install-agenda-files-menu)
12056 (message "Removed file: %s" afile))
12057 (message "File was not in list: %s (not removed)" afile))))
12059 (defun org-file-menu-entry (file)
12060 (vector file (list 'find-file file) t))
12062 (defun org-check-agenda-file (file)
12063 "Make sure FILE exists. If not, ask user what to do."
12064 (when (not (file-exists-p file))
12065 (message "non-existent file %s. [R]emove from list or [A]bort?"
12066 (abbreviate-file-name file))
12067 (let ((r (downcase (read-char-exclusive))))
12068 (cond
12069 ((equal r ?r)
12070 (org-remove-file file)
12071 (throw 'nextfile t))
12072 (t (error "Abort"))))))
12074 (defun org-get-agenda-file-buffer (file)
12075 "Get a buffer visiting FILE. If the buffer needs to be created, add
12076 it to the list of buffers which might be released later."
12077 (let ((buf (org-find-base-buffer-visiting file)))
12078 (if buf
12079 buf ; just return it
12080 ;; Make a new buffer and remember it
12081 (setq buf (find-file-noselect file))
12082 (if buf (push buf org-agenda-new-buffers))
12083 buf)))
12085 (defun org-release-buffers (blist)
12086 "Release all buffers in list, asking the user for confirmation when needed.
12087 When a buffer is unmodified, it is just killed. When modified, it is saved
12088 \(if the user agrees) and then killed."
12089 (let (buf file)
12090 (while (setq buf (pop blist))
12091 (setq file (buffer-file-name buf))
12092 (when (and (buffer-modified-p buf)
12093 file
12094 (y-or-n-p (format "Save file %s? " file)))
12095 (with-current-buffer buf (save-buffer)))
12096 (kill-buffer buf))))
12098 (defun org-prepare-agenda-buffers (files)
12099 "Create buffers for all agenda files, protect archived trees and comments."
12100 (interactive)
12101 (let ((pa '(:org-archived t))
12102 (pc '(:org-comment t))
12103 (pall '(:org-archived t :org-comment t))
12104 (inhibit-read-only t)
12105 (rea (concat ":" org-archive-tag ":"))
12106 bmp file re)
12107 (save-excursion
12108 (save-restriction
12109 (while (setq file (pop files))
12110 (if (bufferp file)
12111 (set-buffer file)
12112 (org-check-agenda-file file)
12113 (set-buffer (org-get-agenda-file-buffer file)))
12114 (widen)
12115 (setq bmp (buffer-modified-p))
12116 (org-refresh-category-properties)
12117 (setq org-todo-keywords-for-agenda
12118 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12119 (setq org-done-keywords-for-agenda
12120 (append org-done-keywords-for-agenda org-done-keywords))
12121 (save-excursion
12122 (remove-text-properties (point-min) (point-max) pall)
12123 (when org-agenda-skip-archived-trees
12124 (goto-char (point-min))
12125 (while (re-search-forward rea nil t)
12126 (if (org-on-heading-p t)
12127 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12128 (goto-char (point-min))
12129 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12130 (while (re-search-forward re nil t)
12131 (add-text-properties
12132 (match-beginning 0) (org-end-of-subtree t) pc)))
12133 (set-buffer-modified-p bmp))))))
12135 ;;;; Embedded LaTeX
12137 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12138 "Keymap for the minor `org-cdlatex-mode'.")
12140 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12141 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12142 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12143 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12144 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12146 (defvar org-cdlatex-texmathp-advice-is-done nil
12147 "Flag remembering if we have applied the advice to texmathp already.")
12149 (define-minor-mode org-cdlatex-mode
12150 "Toggle the minor `org-cdlatex-mode'.
12151 This mode supports entering LaTeX environment and math in LaTeX fragments
12152 in Org-mode.
12153 \\{org-cdlatex-mode-map}"
12154 nil " OCDL" nil
12155 (when org-cdlatex-mode (require 'cdlatex))
12156 (unless org-cdlatex-texmathp-advice-is-done
12157 (setq org-cdlatex-texmathp-advice-is-done t)
12158 (defadvice texmathp (around org-math-always-on activate)
12159 "Always return t in org-mode buffers.
12160 This is because we want to insert math symbols without dollars even outside
12161 the LaTeX math segments. If Orgmode thinks that point is actually inside
12162 en embedded LaTeX fragement, let texmathp do its job.
12163 \\[org-cdlatex-mode-map]"
12164 (interactive)
12165 (let (p)
12166 (cond
12167 ((not (org-mode-p)) ad-do-it)
12168 ((eq this-command 'cdlatex-math-symbol)
12169 (setq ad-return-value t
12170 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12172 (let ((p (org-inside-LaTeX-fragment-p)))
12173 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12174 (setq ad-return-value t
12175 texmathp-why '("Org-mode embedded math" . 0))
12176 (if p ad-do-it)))))))))
12178 (defun turn-on-org-cdlatex ()
12179 "Unconditionally turn on `org-cdlatex-mode'."
12180 (org-cdlatex-mode 1))
12182 (defun org-inside-LaTeX-fragment-p ()
12183 "Test if point is inside a LaTeX fragment.
12184 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12185 sequence appearing also before point.
12186 Even though the matchers for math are configurable, this function assumes
12187 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12188 delimiters are skipped when they have been removed by customization.
12189 The return value is nil, or a cons cell with the delimiter and
12190 and the position of this delimiter.
12192 This function does a reasonably good job, but can locally be fooled by
12193 for example currency specifications. For example it will assume being in
12194 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12195 fragments that are properly closed, but during editing, we have to live
12196 with the uncertainty caused by missing closing delimiters. This function
12197 looks only before point, not after."
12198 (catch 'exit
12199 (let ((pos (point))
12200 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12201 (lim (progn
12202 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12203 (point)))
12204 dd-on str (start 0) m re)
12205 (goto-char pos)
12206 (when dodollar
12207 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12208 re (nth 1 (assoc "$" org-latex-regexps)))
12209 (while (string-match re str start)
12210 (cond
12211 ((= (match-end 0) (length str))
12212 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12213 ((= (match-end 0) (- (length str) 5))
12214 (throw 'exit nil))
12215 (t (setq start (match-end 0))))))
12216 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12217 (goto-char pos)
12218 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12219 (and (match-beginning 2) (throw 'exit nil))
12220 ;; count $$
12221 (while (re-search-backward "\\$\\$" lim t)
12222 (setq dd-on (not dd-on)))
12223 (goto-char pos)
12224 (if dd-on (cons "$$" m))))))
12227 (defun org-try-cdlatex-tab ()
12228 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12229 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12230 - inside a LaTeX fragment, or
12231 - after the first word in a line, where an abbreviation expansion could
12232 insert a LaTeX environment."
12233 (when org-cdlatex-mode
12234 (cond
12235 ((save-excursion
12236 (skip-chars-backward "a-zA-Z0-9*")
12237 (skip-chars-backward " \t")
12238 (bolp))
12239 (cdlatex-tab) t)
12240 ((org-inside-LaTeX-fragment-p)
12241 (cdlatex-tab) t)
12242 (t nil))))
12244 (defun org-cdlatex-underscore-caret (&optional arg)
12245 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12246 Revert to the normal definition outside of these fragments."
12247 (interactive "P")
12248 (if (org-inside-LaTeX-fragment-p)
12249 (call-interactively 'cdlatex-sub-superscript)
12250 (let (org-cdlatex-mode)
12251 (call-interactively (key-binding (vector last-input-event))))))
12253 (defun org-cdlatex-math-modify (&optional arg)
12254 "Execute `cdlatex-math-modify' in LaTeX fragments.
12255 Revert to the normal definition outside of these fragments."
12256 (interactive "P")
12257 (if (org-inside-LaTeX-fragment-p)
12258 (call-interactively 'cdlatex-math-modify)
12259 (let (org-cdlatex-mode)
12260 (call-interactively (key-binding (vector last-input-event))))))
12262 (defvar org-latex-fragment-image-overlays nil
12263 "List of overlays carrying the images of latex fragments.")
12264 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12266 (defun org-remove-latex-fragment-image-overlays ()
12267 "Remove all overlays with LaTeX fragment images in current buffer."
12268 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12269 (setq org-latex-fragment-image-overlays nil))
12271 (defun org-preview-latex-fragment (&optional subtree)
12272 "Preview the LaTeX fragment at point, or all locally or globally.
12273 If the cursor is in a LaTeX fragment, create the image and overlay
12274 it over the source code. If there is no fragment at point, display
12275 all fragments in the current text, from one headline to the next. With
12276 prefix SUBTREE, display all fragments in the current subtree. With a
12277 double prefix `C-u C-u', or when the cursor is before the first headline,
12278 display all fragments in the buffer.
12279 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12280 (interactive "P")
12281 (org-remove-latex-fragment-image-overlays)
12282 (save-excursion
12283 (save-restriction
12284 (let (beg end at msg)
12285 (cond
12286 ((or (equal subtree '(16))
12287 (not (save-excursion
12288 (re-search-backward (concat "^" outline-regexp) nil t))))
12289 (setq beg (point-min) end (point-max)
12290 msg "Creating images for buffer...%s"))
12291 ((equal subtree '(4))
12292 (org-back-to-heading)
12293 (setq beg (point) end (org-end-of-subtree t)
12294 msg "Creating images for subtree...%s"))
12296 (if (setq at (org-inside-LaTeX-fragment-p))
12297 (goto-char (max (point-min) (- (cdr at) 2)))
12298 (org-back-to-heading))
12299 (setq beg (point) end (progn (outline-next-heading) (point))
12300 msg (if at "Creating image...%s"
12301 "Creating images for entry...%s"))))
12302 (message msg "")
12303 (narrow-to-region beg end)
12304 (goto-char beg)
12305 (org-format-latex
12306 (concat "ltxpng/" (file-name-sans-extension
12307 (file-name-nondirectory
12308 buffer-file-name)))
12309 default-directory 'overlays msg at 'forbuffer)
12310 (message msg "done. Use `C-c C-c' to remove images.")))))
12312 (defvar org-latex-regexps
12313 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12314 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12315 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12316 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12317 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12318 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12319 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12320 "Regular expressions for matching embedded LaTeX.")
12322 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12323 "Replace LaTeX fragments with links to an image, and produce images."
12324 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12325 (let* ((prefixnodir (file-name-nondirectory prefix))
12326 (absprefix (expand-file-name prefix dir))
12327 (todir (file-name-directory absprefix))
12328 (opt org-format-latex-options)
12329 (matchers (plist-get opt :matchers))
12330 (re-list org-latex-regexps)
12331 (cnt 0) txt link beg end re e checkdir
12332 m n block linkfile movefile ov)
12333 ;; Check if there are old images files with this prefix, and remove them
12334 (when (file-directory-p todir)
12335 (mapc 'delete-file
12336 (directory-files
12337 todir 'full
12338 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12339 ;; Check the different regular expressions
12340 (while (setq e (pop re-list))
12341 (setq m (car e) re (nth 1 e) n (nth 2 e)
12342 block (if (nth 3 e) "\n\n" ""))
12343 (when (member m matchers)
12344 (goto-char (point-min))
12345 (while (re-search-forward re nil t)
12346 (when (or (not at) (equal (cdr at) (match-beginning n)))
12347 (setq txt (match-string n)
12348 beg (match-beginning n) end (match-end n)
12349 cnt (1+ cnt)
12350 linkfile (format "%s_%04d.png" prefix cnt)
12351 movefile (format "%s_%04d.png" absprefix cnt)
12352 link (concat block "[[file:" linkfile "]]" block))
12353 (if msg (message msg cnt))
12354 (goto-char beg)
12355 (unless checkdir ; make sure the directory exists
12356 (setq checkdir t)
12357 (or (file-directory-p todir) (make-directory todir)))
12358 (org-create-formula-image
12359 txt movefile opt forbuffer)
12360 (if overlays
12361 (progn
12362 (setq ov (org-make-overlay beg end))
12363 (if (featurep 'xemacs)
12364 (progn
12365 (org-overlay-put ov 'invisible t)
12366 (org-overlay-put
12367 ov 'end-glyph
12368 (make-glyph (vector 'png :file movefile))))
12369 (org-overlay-put
12370 ov 'display
12371 (list 'image :type 'png :file movefile :ascent 'center)))
12372 (push ov org-latex-fragment-image-overlays)
12373 (goto-char end))
12374 (delete-region beg end)
12375 (insert link))))))))
12377 ;; This function borrows from Ganesh Swami's latex2png.el
12378 (defun org-create-formula-image (string tofile options buffer)
12379 (let* ((tmpdir (if (featurep 'xemacs)
12380 (temp-directory)
12381 temporary-file-directory))
12382 (texfilebase (make-temp-name
12383 (expand-file-name "orgtex" tmpdir)))
12384 (texfile (concat texfilebase ".tex"))
12385 (dvifile (concat texfilebase ".dvi"))
12386 (pngfile (concat texfilebase ".png"))
12387 (fnh (if (featurep 'xemacs)
12388 (font-height (get-face-font 'default))
12389 (face-attribute 'default :height nil)))
12390 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12391 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12392 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12393 "Black"))
12394 (bg (or (plist-get options (if buffer :background :html-background))
12395 "Transparent")))
12396 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12397 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12398 (with-temp-file texfile
12399 (insert org-format-latex-header
12400 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12401 (let ((dir default-directory))
12402 (condition-case nil
12403 (progn
12404 (cd tmpdir)
12405 (call-process "latex" nil nil nil texfile))
12406 (error nil))
12407 (cd dir))
12408 (if (not (file-exists-p dvifile))
12409 (progn (message "Failed to create dvi file from %s" texfile) nil)
12410 (call-process "dvipng" nil nil nil
12411 "-E" "-fg" fg "-bg" bg
12412 "-D" dpi
12413 ;;"-x" scale "-y" scale
12414 "-T" "tight"
12415 "-o" pngfile
12416 dvifile)
12417 (if (not (file-exists-p pngfile))
12418 (progn (message "Failed to create png file from %s" texfile) nil)
12419 ;; Use the requested file name and clean up
12420 (copy-file pngfile tofile 'replace)
12421 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12422 (delete-file (concat texfilebase e)))
12423 pngfile))))
12425 (defun org-dvipng-color (attr)
12426 "Return an rgb color specification for dvipng."
12427 (apply 'format "rgb %s %s %s"
12428 (mapcar 'org-normalize-color
12429 (color-values (face-attribute 'default attr nil)))))
12431 (defun org-normalize-color (value)
12432 "Return string to be used as color value for an RGB component."
12433 (format "%g" (/ value 65535.0)))
12436 ;;;; Key bindings
12438 ;; Make `C-c C-x' a prefix key
12439 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12441 ;; TAB key with modifiers
12442 (org-defkey org-mode-map "\C-i" 'org-cycle)
12443 (org-defkey org-mode-map [(tab)] 'org-cycle)
12444 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12445 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12446 (org-defkey org-mode-map "\M-\t" 'org-complete)
12447 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12448 ;; The following line is necessary under Suse GNU/Linux
12449 (unless (featurep 'xemacs)
12450 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12451 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12452 (define-key org-mode-map [backtab] 'org-shifttab)
12454 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12455 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12456 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12458 ;; Cursor keys with modifiers
12459 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12460 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12461 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12462 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12464 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12465 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12466 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12467 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12469 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12470 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12471 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12472 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12474 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12475 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12477 ;;; Extra keys for tty access.
12478 ;; We only set them when really needed because otherwise the
12479 ;; menus don't show the simple keys
12481 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12482 (not window-system))
12483 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12484 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12485 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12486 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12487 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12488 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12489 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12490 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12491 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12492 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12493 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12494 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12495 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12496 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12497 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12498 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12499 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12500 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12501 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12502 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12503 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12504 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12506 ;; All the other keys
12508 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12509 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12510 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
12511 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12512 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12513 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12514 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12515 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12516 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12517 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12518 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12519 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12520 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12521 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12522 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12523 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12524 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12525 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12526 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12527 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12528 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
12529 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12530 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12531 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12532 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12533 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12534 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12535 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12536 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12537 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12538 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12539 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12540 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12541 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12542 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12543 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12544 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12545 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12546 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12547 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12548 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12549 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12550 (org-defkey org-mode-map "\C-c^" 'org-sort)
12551 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12552 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12553 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12554 (org-defkey org-mode-map "\C-m" 'org-return)
12555 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12556 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12557 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12558 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12559 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12560 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12561 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12562 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12563 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12564 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12565 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12566 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12567 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12568 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12569 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12570 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12572 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12573 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12574 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12575 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12577 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12578 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12579 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12580 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12581 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12582 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12583 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12584 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12585 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12586 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12587 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12588 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
12590 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12592 (when (featurep 'xemacs)
12593 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12595 (defvar org-table-auto-blank-field) ; defined in org-table.el
12596 (defun org-self-insert-command (N)
12597 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12598 If the cursor is in a table looking at whitespace, the whitespace is
12599 overwritten, and the table is not marked as requiring realignment."
12600 (interactive "p")
12601 (if (and (org-table-p)
12602 (progn
12603 ;; check if we blank the field, and if that triggers align
12604 (and (featurep 'org-table) org-table-auto-blank-field
12605 (member last-command
12606 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12607 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12608 ;; got extra space, this field does not determine column width
12609 (let (org-table-may-need-update) (org-table-blank-field))
12610 ;; no extra space, this field may determine column width
12611 (org-table-blank-field)))
12613 (eq N 1)
12614 (looking-at "[^|\n]* |"))
12615 (let (org-table-may-need-update)
12616 (goto-char (1- (match-end 0)))
12617 (delete-backward-char 1)
12618 (goto-char (match-beginning 0))
12619 (self-insert-command N))
12620 (setq org-table-may-need-update t)
12621 (self-insert-command N)
12622 (org-fix-tags-on-the-fly)))
12624 (defun org-fix-tags-on-the-fly ()
12625 (when (and (equal (char-after (point-at-bol)) ?*)
12626 (org-on-heading-p))
12627 (org-align-tags-here org-tags-column)))
12629 (defun org-delete-backward-char (N)
12630 "Like `delete-backward-char', insert whitespace at field end in tables.
12631 When deleting backwards, in tables this function will insert whitespace in
12632 front of the next \"|\" separator, to keep the table aligned. The table will
12633 still be marked for re-alignment if the field did fill the entire column,
12634 because, in this case the deletion might narrow the column."
12635 (interactive "p")
12636 (if (and (org-table-p)
12637 (eq N 1)
12638 (string-match "|" (buffer-substring (point-at-bol) (point)))
12639 (looking-at ".*?|"))
12640 (let ((pos (point))
12641 (noalign (looking-at "[^|\n\r]* |"))
12642 (c org-table-may-need-update))
12643 (backward-delete-char N)
12644 (skip-chars-forward "^|")
12645 (insert " ")
12646 (goto-char (1- pos))
12647 ;; noalign: if there were two spaces at the end, this field
12648 ;; does not determine the width of the column.
12649 (if noalign (setq org-table-may-need-update c)))
12650 (backward-delete-char N)
12651 (org-fix-tags-on-the-fly)))
12653 (defun org-delete-char (N)
12654 "Like `delete-char', but insert whitespace at field end in tables.
12655 When deleting characters, in tables this function will insert whitespace in
12656 front of the next \"|\" separator, to keep the table aligned. The table will
12657 still be marked for re-alignment if the field did fill the entire column,
12658 because, in this case the deletion might narrow the column."
12659 (interactive "p")
12660 (if (and (org-table-p)
12661 (not (bolp))
12662 (not (= (char-after) ?|))
12663 (eq N 1))
12664 (if (looking-at ".*?|")
12665 (let ((pos (point))
12666 (noalign (looking-at "[^|\n\r]* |"))
12667 (c org-table-may-need-update))
12668 (replace-match (concat
12669 (substring (match-string 0) 1 -1)
12670 " |"))
12671 (goto-char pos)
12672 ;; noalign: if there were two spaces at the end, this field
12673 ;; does not determine the width of the column.
12674 (if noalign (setq org-table-may-need-update c)))
12675 (delete-char N))
12676 (delete-char N)
12677 (org-fix-tags-on-the-fly)))
12679 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12680 (put 'org-self-insert-command 'delete-selection t)
12681 (put 'orgtbl-self-insert-command 'delete-selection t)
12682 (put 'org-delete-char 'delete-selection 'supersede)
12683 (put 'org-delete-backward-char 'delete-selection 'supersede)
12685 ;; Make `flyspell-mode' delay after some commands
12686 (put 'org-self-insert-command 'flyspell-delayed t)
12687 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12688 (put 'org-delete-char 'flyspell-delayed t)
12689 (put 'org-delete-backward-char 'flyspell-delayed t)
12691 ;; Make pabbrev-mode expand after org-mode commands
12692 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12693 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12695 ;; How to do this: Measure non-white length of current string
12696 ;; If equal to column width, we should realign.
12698 (defun org-remap (map &rest commands)
12699 "In MAP, remap the functions given in COMMANDS.
12700 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12701 (let (new old)
12702 (while commands
12703 (setq old (pop commands) new (pop commands))
12704 (if (fboundp 'command-remapping)
12705 (org-defkey map (vector 'remap old) new)
12706 (substitute-key-definition old new map global-map)))))
12708 (when (eq org-enable-table-editor 'optimized)
12709 ;; If the user wants maximum table support, we need to hijack
12710 ;; some standard editing functions
12711 (org-remap org-mode-map
12712 'self-insert-command 'org-self-insert-command
12713 'delete-char 'org-delete-char
12714 'delete-backward-char 'org-delete-backward-char)
12715 (org-defkey org-mode-map "|" 'org-force-self-insert))
12717 (defun org-shiftcursor-error ()
12718 "Throw an error because Shift-Cursor command was applied in wrong context."
12719 (error "This command is active in special context like tables, headlines or timestamps"))
12721 (defun org-shifttab (&optional arg)
12722 "Global visibility cycling or move to previous table field.
12723 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12724 on context.
12725 See the individual commands for more information."
12726 (interactive "P")
12727 (cond
12728 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12729 ((integerp arg)
12730 (message "Content view to level: %d" arg)
12731 (org-content (prefix-numeric-value arg))
12732 (setq org-cycle-global-status 'overview))
12733 (t (call-interactively 'org-global-cycle))))
12735 (defun org-shiftmetaleft ()
12736 "Promote subtree or delete table column.
12737 Calls `org-promote-subtree', `org-outdent-item',
12738 or `org-table-delete-column', depending on context.
12739 See the individual commands for more information."
12740 (interactive)
12741 (cond
12742 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12743 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12744 ((org-at-item-p) (call-interactively 'org-outdent-item))
12745 (t (org-shiftcursor-error))))
12747 (defun org-shiftmetaright ()
12748 "Demote subtree or insert table column.
12749 Calls `org-demote-subtree', `org-indent-item',
12750 or `org-table-insert-column', depending on context.
12751 See the individual commands for more information."
12752 (interactive)
12753 (cond
12754 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12755 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12756 ((org-at-item-p) (call-interactively 'org-indent-item))
12757 (t (org-shiftcursor-error))))
12759 (defun org-shiftmetaup (&optional arg)
12760 "Move subtree up or kill table row.
12761 Calls `org-move-subtree-up' or `org-table-kill-row' or
12762 `org-move-item-up' depending on context. See the individual commands
12763 for more information."
12764 (interactive "P")
12765 (cond
12766 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12767 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12768 ((org-at-item-p) (call-interactively 'org-move-item-up))
12769 (t (org-shiftcursor-error))))
12770 (defun org-shiftmetadown (&optional arg)
12771 "Move subtree down or insert table row.
12772 Calls `org-move-subtree-down' or `org-table-insert-row' or
12773 `org-move-item-down', depending on context. See the individual
12774 commands for more information."
12775 (interactive "P")
12776 (cond
12777 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12778 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12779 ((org-at-item-p) (call-interactively 'org-move-item-down))
12780 (t (org-shiftcursor-error))))
12782 (defun org-metaleft (&optional arg)
12783 "Promote heading or move table column to left.
12784 Calls `org-do-promote' or `org-table-move-column', depending on context.
12785 With no specific context, calls the Emacs default `backward-word'.
12786 See the individual commands for more information."
12787 (interactive "P")
12788 (cond
12789 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12790 ((or (org-on-heading-p) (org-region-active-p))
12791 (call-interactively 'org-do-promote))
12792 ((org-at-item-p) (call-interactively 'org-outdent-item))
12793 (t (call-interactively 'backward-word))))
12795 (defun org-metaright (&optional arg)
12796 "Demote subtree or move table column to right.
12797 Calls `org-do-demote' or `org-table-move-column', depending on context.
12798 With no specific context, calls the Emacs default `forward-word'.
12799 See the individual commands for more information."
12800 (interactive "P")
12801 (cond
12802 ((org-at-table-p) (call-interactively 'org-table-move-column))
12803 ((or (org-on-heading-p) (org-region-active-p))
12804 (call-interactively 'org-do-demote))
12805 ((org-at-item-p) (call-interactively 'org-indent-item))
12806 (t (call-interactively 'forward-word))))
12808 (defun org-metaup (&optional arg)
12809 "Move subtree up or move table row up.
12810 Calls `org-move-subtree-up' or `org-table-move-row' or
12811 `org-move-item-up', depending on context. See the individual commands
12812 for more information."
12813 (interactive "P")
12814 (cond
12815 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12816 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12817 ((org-at-item-p) (call-interactively 'org-move-item-up))
12818 (t (transpose-lines 1) (beginning-of-line -1))))
12820 (defun org-metadown (&optional arg)
12821 "Move subtree down or move table row down.
12822 Calls `org-move-subtree-down' or `org-table-move-row' or
12823 `org-move-item-down', depending on context. See the individual
12824 commands for more information."
12825 (interactive "P")
12826 (cond
12827 ((org-at-table-p) (call-interactively 'org-table-move-row))
12828 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12829 ((org-at-item-p) (call-interactively 'org-move-item-down))
12830 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12832 (defun org-shiftup (&optional arg)
12833 "Increase item in timestamp or increase priority of current headline.
12834 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12835 depending on context. See the individual commands for more information."
12836 (interactive "P")
12837 (cond
12838 ((org-at-timestamp-p t)
12839 (call-interactively (if org-edit-timestamp-down-means-later
12840 'org-timestamp-down 'org-timestamp-up)))
12841 ((org-on-heading-p) (call-interactively 'org-priority-up))
12842 ((org-at-item-p) (call-interactively 'org-previous-item))
12843 ((org-clocktable-try-shift 'up arg))
12844 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12846 (defun org-shiftdown (&optional arg)
12847 "Decrease item in timestamp or decrease priority of current headline.
12848 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12849 depending on context. See the individual commands for more information."
12850 (interactive "P")
12851 (cond
12852 ((org-at-timestamp-p t)
12853 (call-interactively (if org-edit-timestamp-down-means-later
12854 'org-timestamp-up 'org-timestamp-down)))
12855 ((org-on-heading-p) (call-interactively 'org-priority-down))
12856 ((org-clocktable-try-shift 'down arg))
12857 (t (call-interactively 'org-next-item))))
12859 (defun org-shiftright (&optional arg)
12860 "Next TODO keyword or timestamp one day later, depending on context."
12861 (interactive "P")
12862 (cond
12863 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12864 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12865 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12866 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12867 ((org-clocktable-try-shift 'right arg))
12868 (t (org-shiftcursor-error))))
12870 (defun org-shiftleft (&optional arg)
12871 "Previous TODO keyword or timestamp one day earlier, depending on context."
12872 (interactive "P")
12873 (cond
12874 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12875 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12876 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12877 ((org-at-property-p)
12878 (call-interactively 'org-property-previous-allowed-value))
12879 ((org-clocktable-try-shift 'left arg))
12880 (t (org-shiftcursor-error))))
12882 (defun org-shiftcontrolright ()
12883 "Switch to next TODO set."
12884 (interactive)
12885 (cond
12886 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12887 (t (org-shiftcursor-error))))
12889 (defun org-shiftcontrolleft ()
12890 "Switch to previous TODO set."
12891 (interactive)
12892 (cond
12893 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12894 (t (org-shiftcursor-error))))
12896 (defun org-ctrl-c-ret ()
12897 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12898 (interactive)
12899 (cond
12900 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12901 (t (call-interactively 'org-insert-heading))))
12903 (defun org-copy-special ()
12904 "Copy region in table or copy current subtree.
12905 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12906 See the individual commands for more information."
12907 (interactive)
12908 (call-interactively
12909 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12911 (defun org-cut-special ()
12912 "Cut region in table or cut current subtree.
12913 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12914 See the individual commands for more information."
12915 (interactive)
12916 (call-interactively
12917 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12919 (defun org-paste-special (arg)
12920 "Paste rectangular region into table, or past subtree relative to level.
12921 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12922 See the individual commands for more information."
12923 (interactive "P")
12924 (if (org-at-table-p)
12925 (org-table-paste-rectangle)
12926 (org-paste-subtree arg)))
12928 (defun org-edit-special ()
12929 "Call a special editor for the stuff at point.
12930 When at a table, call the formula editor with `org-table-edit-formulas'.
12931 When at the first line of an src example, call `org-edit-src-code'.
12932 When in an #+include line, visit the include file. Otherwise call
12933 `ffap' to visit the file at point."
12934 (interactive)
12935 (cond
12936 ((org-at-table-p)
12937 (call-interactively 'org-table-edit-formulas))
12938 ((save-excursion
12939 (beginning-of-line 1)
12940 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12941 (find-file (org-trim (match-string 1))))
12942 ((org-edit-src-code))
12943 (t (call-interactively 'ffap))))
12945 (defun org-ctrl-c-ctrl-c (&optional arg)
12946 "Set tags in headline, or update according to changed information at point.
12948 This command does many different things, depending on context:
12950 - If the cursor is in a headline, prompt for tags and insert them
12951 into the current line, aligned to `org-tags-column'. When called
12952 with prefix arg, realign all tags in the current buffer.
12954 - If the cursor is in one of the special #+KEYWORD lines, this
12955 triggers scanning the buffer for these lines and updating the
12956 information.
12958 - If the cursor is inside a table, realign the table. This command
12959 works even if the automatic table editor has been turned off.
12961 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12962 the entire table.
12964 - If the cursor is a the beginning of a dynamic block, update it.
12966 - If the cursor is inside a table created by the table.el package,
12967 activate that table.
12969 - If the current buffer is a remember buffer, close note and file it.
12970 with a prefix argument, file it without further interaction to the default
12971 location.
12973 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12974 links in this buffer.
12976 - If the cursor is on a numbered item in a plain list, renumber the
12977 ordered list.
12979 - If the cursor is on a checkbox, toggle it."
12980 (interactive "P")
12981 (let ((org-enable-table-editor t))
12982 (cond
12983 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12984 org-occur-highlights
12985 org-latex-fragment-image-overlays)
12986 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12987 (org-remove-occur-highlights)
12988 (org-remove-latex-fragment-image-overlays)
12989 (message "Temporary highlights/overlays removed from current buffer"))
12990 ((and (local-variable-p 'org-finish-function (current-buffer))
12991 (fboundp org-finish-function))
12992 (funcall org-finish-function))
12993 ((org-at-property-p)
12994 (call-interactively 'org-property-action))
12995 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12996 ((org-on-heading-p) (call-interactively 'org-set-tags))
12997 ((org-at-table.el-p)
12998 (require 'table)
12999 (beginning-of-line 1)
13000 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13001 (call-interactively 'table-recognize-table))
13002 ((org-at-table-p)
13003 (org-table-maybe-eval-formula)
13004 (if arg
13005 (call-interactively 'org-table-recalculate)
13006 (org-table-maybe-recalculate-line))
13007 (call-interactively 'org-table-align))
13008 ((org-at-item-checkbox-p)
13009 (call-interactively 'org-toggle-checkbox))
13010 ((org-at-item-p)
13011 (call-interactively 'org-maybe-renumber-ordered-list))
13012 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13013 ;; Dynamic block
13014 (beginning-of-line 1)
13015 (org-update-dblock))
13016 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13017 (cond
13018 ((equal (match-string 1) "TBLFM")
13019 ;; Recalculate the table before this line
13020 (save-excursion
13021 (beginning-of-line 1)
13022 (skip-chars-backward " \r\n\t")
13023 (if (org-at-table-p)
13024 (org-call-with-arg 'org-table-recalculate t))))
13026 ; (org-set-regexps-and-options)
13027 ; (org-restart-font-lock)
13028 (let ((org-inhibit-startup t)) (org-mode-restart))
13029 (message "Local setup has been refreshed"))))
13030 (t (error "C-c C-c can do nothing useful at this location.")))))
13032 (defun org-mode-restart ()
13033 "Restart Org-mode, to scan again for special lines.
13034 Also updates the keyword regular expressions."
13035 (interactive)
13036 (org-mode)
13037 (message "Org-mode restarted"))
13039 (defun org-kill-note-or-show-branches ()
13040 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13041 (interactive)
13042 (if (not org-finish-function)
13043 (call-interactively 'show-branches)
13044 (let ((org-note-abort t))
13045 (funcall org-finish-function))))
13047 (defun org-return (&optional indent)
13048 "Goto next table row or insert a newline.
13049 Calls `org-table-next-row' or `newline', depending on context.
13050 See the individual commands for more information."
13051 (interactive)
13052 (cond
13053 ((bobp) (if indent (newline-and-indent) (newline)))
13054 ((and (org-at-heading-p)
13055 (looking-at
13056 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13057 (org-show-entry)
13058 (end-of-line 1)
13059 (newline))
13060 ((org-at-table-p)
13061 (org-table-justify-field-maybe)
13062 (call-interactively 'org-table-next-row))
13063 (t (if indent (newline-and-indent) (newline)))))
13065 (defun org-return-indent ()
13066 "Goto next table row or insert a newline and indent.
13067 Calls `org-table-next-row' or `newline-and-indent', depending on
13068 context. See the individual commands for more information."
13069 (interactive)
13070 (org-return t))
13072 (defun org-ctrl-c-star ()
13073 "Compute table, or change heading status of lines.
13074 Calls `org-table-recalculate' or `org-toggle-region-headings',
13075 depending on context. This will also turn a plain list item or a normal
13076 line into a subheading."
13077 (interactive)
13078 (cond
13079 ((org-at-table-p)
13080 (call-interactively 'org-table-recalculate))
13081 ((org-region-active-p)
13082 ;; Convert all lines in region to list items
13083 (call-interactively 'org-toggle-region-headings))
13084 ((org-on-heading-p)
13085 (org-toggle-region-headings (point-at-bol)
13086 (min (1+ (point-at-eol)) (point-max))))
13087 ((org-at-item-p)
13088 ;; Convert to heading
13089 (let ((level (save-match-data
13090 (save-excursion
13091 (condition-case nil
13092 (progn
13093 (org-back-to-heading t)
13094 (funcall outline-level))
13095 (error 0))))))
13096 (replace-match
13097 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13098 (t (org-toggle-region-headings (point-at-bol)
13099 (min (1+ (point-at-eol)) (point-max))))))
13101 (defun org-ctrl-c-minus ()
13102 "Insert separator line in table or modify bullet status of line.
13103 Also turns a plain line or a region of lines into list items.
13104 Calls `org-table-insert-hline', `org-toggle-region-items', or
13105 `org-cycle-list-bullet', depending on context."
13106 (interactive)
13107 (cond
13108 ((org-at-table-p)
13109 (call-interactively 'org-table-insert-hline))
13110 ((org-on-heading-p)
13111 ;; Convert to item
13112 (save-excursion
13113 (beginning-of-line 1)
13114 (if (looking-at "\\*+ ")
13115 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
13116 ((org-region-active-p)
13117 ;; Convert all lines in region to list items
13118 (call-interactively 'org-toggle-region-items))
13119 ((org-in-item-p)
13120 (call-interactively 'org-cycle-list-bullet))
13121 (t (org-toggle-region-items (point-at-bol)
13122 (min (1+ (point-at-eol)) (point-max))))))
13124 (defun org-toggle-region-items (beg end)
13125 "Convert all lines in region to list items.
13126 If the first line is already an item, convert all list items in the region
13127 to normal lines."
13128 (interactive "r")
13129 (let (l2 l)
13130 (save-excursion
13131 (goto-char end)
13132 (setq l2 (org-current-line))
13133 (goto-char beg)
13134 (beginning-of-line 1)
13135 (setq l (1- (org-current-line)))
13136 (if (org-at-item-p)
13137 ;; We already have items, de-itemize
13138 (while (< (setq l (1+ l)) l2)
13139 (when (org-at-item-p)
13140 (goto-char (match-beginning 2))
13141 (delete-region (match-beginning 2) (match-end 2))
13142 (and (looking-at "[ \t]+") (replace-match "")))
13143 (beginning-of-line 2))
13144 (while (< (setq l (1+ l)) l2)
13145 (unless (org-at-item-p)
13146 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13147 (replace-match "\\1- \\2")))
13148 (beginning-of-line 2))))))
13150 (defun org-toggle-region-headings (beg end)
13151 "Convert all lines in region to list items.
13152 If the first line is already an item, convert all list items in the region
13153 to normal lines."
13154 (interactive "r")
13155 (let (l2 l)
13156 (save-excursion
13157 (goto-char end)
13158 (setq l2 (org-current-line))
13159 (goto-char beg)
13160 (beginning-of-line 1)
13161 (setq l (1- (org-current-line)))
13162 (if (org-on-heading-p)
13163 ;; We already have headlines, de-star them
13164 (while (< (setq l (1+ l)) l2)
13165 (when (org-on-heading-p t)
13166 (and (looking-at outline-regexp) (replace-match "")))
13167 (beginning-of-line 2))
13168 (let* ((stars (save-excursion
13169 (re-search-backward org-complex-heading-regexp nil t)
13170 (or (match-string 1) "*")))
13171 (add-stars (if org-odd-levels-only "**" "*"))
13172 (rpl (concat stars add-stars " \\2")))
13173 (while (< (setq l (1+ l)) l2)
13174 (unless (org-on-heading-p)
13175 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13176 (replace-match rpl)))
13177 (beginning-of-line 2)))))))
13179 (defun org-meta-return (&optional arg)
13180 "Insert a new heading or wrap a region in a table.
13181 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13182 See the individual commands for more information."
13183 (interactive "P")
13184 (cond
13185 ((org-at-table-p)
13186 (call-interactively 'org-table-wrap-region))
13187 (t (call-interactively 'org-insert-heading))))
13189 ;;; Menu entries
13191 ;; Define the Org-mode menus
13192 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13193 '("Tbl"
13194 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13195 ["Next Field" org-cycle (org-at-table-p)]
13196 ["Previous Field" org-shifttab (org-at-table-p)]
13197 ["Next Row" org-return (org-at-table-p)]
13198 "--"
13199 ["Blank Field" org-table-blank-field (org-at-table-p)]
13200 ["Edit Field" org-table-edit-field (org-at-table-p)]
13201 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13202 "--"
13203 ("Column"
13204 ["Move Column Left" org-metaleft (org-at-table-p)]
13205 ["Move Column Right" org-metaright (org-at-table-p)]
13206 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13207 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13208 ("Row"
13209 ["Move Row Up" org-metaup (org-at-table-p)]
13210 ["Move Row Down" org-metadown (org-at-table-p)]
13211 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13212 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13213 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13214 "--"
13215 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13216 ("Rectangle"
13217 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13218 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13219 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13220 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13221 "--"
13222 ("Calculate"
13223 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13224 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13225 ["Edit Formulas" org-edit-special (org-at-table-p)]
13226 "--"
13227 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13228 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13229 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13230 "--"
13231 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13232 "--"
13233 ["Sum Column/Rectangle" org-table-sum
13234 (or (org-at-table-p) (org-region-active-p))]
13235 ["Which Column?" org-table-current-column (org-at-table-p)])
13236 ["Debug Formulas"
13237 org-table-toggle-formula-debugger
13238 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13239 ["Show Col/Row Numbers"
13240 org-table-toggle-coordinate-overlays
13241 :style toggle
13242 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13243 "--"
13244 ["Create" org-table-create (and (not (org-at-table-p))
13245 org-enable-table-editor)]
13246 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13247 ["Import from File" org-table-import (not (org-at-table-p))]
13248 ["Export to File" org-table-export (org-at-table-p)]
13249 "--"
13250 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13252 (easy-menu-define org-org-menu org-mode-map "Org menu"
13253 '("Org"
13254 ("Show/Hide"
13255 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13256 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13257 ["Sparse Tree..." org-sparse-tree t]
13258 ["Reveal Context" org-reveal t]
13259 ["Show All" show-all t]
13260 "--"
13261 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13262 "--"
13263 ["New Heading" org-insert-heading t]
13264 ("Navigate Headings"
13265 ["Up" outline-up-heading t]
13266 ["Next" outline-next-visible-heading t]
13267 ["Previous" outline-previous-visible-heading t]
13268 ["Next Same Level" outline-forward-same-level t]
13269 ["Previous Same Level" outline-backward-same-level t]
13270 "--"
13271 ["Jump" org-goto t])
13272 ("Edit Structure"
13273 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13274 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13275 "--"
13276 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13277 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13278 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13279 "--"
13280 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13281 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13282 ["Demote Heading" org-metaright (not (org-at-table-p))]
13283 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13284 "--"
13285 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13286 "--"
13287 ["Convert to odd levels" org-convert-to-odd-levels t]
13288 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13289 ("Editing"
13290 ["Emphasis..." org-emphasize t]
13291 ["Edit Source Example" org-edit-special t])
13292 ("Archive"
13293 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13294 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13295 ; :active t :keys "C-u C-c C-x C-a"]
13296 ["Sparse trees open ARCHIVE trees"
13297 (setq org-sparse-tree-open-archived-trees
13298 (not org-sparse-tree-open-archived-trees))
13299 :style toggle :selected org-sparse-tree-open-archived-trees]
13300 ["Cycling opens ARCHIVE trees"
13301 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13302 :style toggle :selected org-cycle-open-archived-trees]
13303 "--"
13304 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13305 ; ["Check and Move Children" (org-archive-subtree '(4))
13306 ; :active t :keys "C-u C-c C-x C-s"]
13308 "--"
13309 ("TODO Lists"
13310 ["TODO/DONE/-" org-todo t]
13311 ("Select keyword"
13312 ["Next keyword" org-shiftright (org-on-heading-p)]
13313 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13314 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13315 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13316 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13317 ["Show TODO Tree" org-show-todo-tree t]
13318 ["Global TODO list" org-todo-list t]
13319 "--"
13320 ["Set Priority" org-priority t]
13321 ["Priority Up" org-shiftup t]
13322 ["Priority Down" org-shiftdown t])
13323 ("TAGS and Properties"
13324 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
13325 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13326 "--"
13327 ["Set property" 'org-set-property t]
13328 ["Column view of properties" org-columns t]
13329 ["Insert Column View DBlock" org-insert-columns-dblock t])
13330 ("Dates and Scheduling"
13331 ["Timestamp" org-time-stamp t]
13332 ["Timestamp (inactive)" org-time-stamp-inactive t]
13333 ("Change Date"
13334 ["1 Day Later" org-shiftright t]
13335 ["1 Day Earlier" org-shiftleft t]
13336 ["1 ... Later" org-shiftup t]
13337 ["1 ... Earlier" org-shiftdown t])
13338 ["Compute Time Range" org-evaluate-time-range t]
13339 ["Schedule Item" org-schedule t]
13340 ["Deadline" org-deadline t]
13341 "--"
13342 ["Custom time format" org-toggle-time-stamp-overlays
13343 :style radio :selected org-display-custom-times]
13344 "--"
13345 ["Goto Calendar" org-goto-calendar t]
13346 ["Date from Calendar" org-date-from-calendar t])
13347 ("Logging work"
13348 ["Clock in" org-clock-in t]
13349 ["Clock out" org-clock-out t]
13350 ["Clock cancel" org-clock-cancel t]
13351 ["Goto running clock" org-clock-goto t]
13352 ["Display times" org-clock-display t]
13353 ["Create clock table" org-clock-report t]
13354 "--"
13355 ["Record DONE time"
13356 (progn (setq org-log-done (not org-log-done))
13357 (message "Switching to %s will %s record a timestamp"
13358 (car org-done-keywords)
13359 (if org-log-done "automatically" "not")))
13360 :style toggle :selected org-log-done])
13361 "--"
13362 ["Agenda Command..." org-agenda t]
13363 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13364 ("File List for Agenda")
13365 ("Special views current file"
13366 ["TODO Tree" org-show-todo-tree t]
13367 ["Check Deadlines" org-check-deadlines t]
13368 ["Timeline" org-timeline t]
13369 ["Tags Tree" org-tags-sparse-tree t])
13370 "--"
13371 ("Hyperlinks"
13372 ["Store Link (Global)" org-store-link t]
13373 ["Insert Link" org-insert-link t]
13374 ["Follow Link" org-open-at-point t]
13375 "--"
13376 ["Next link" org-next-link t]
13377 ["Previous link" org-previous-link t]
13378 "--"
13379 ["Descriptive Links"
13380 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13381 :style radio
13382 :selected (member '(org-link) buffer-invisibility-spec)]
13383 ["Literal Links"
13384 (progn
13385 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13386 :style radio
13387 :selected (not (member '(org-link) buffer-invisibility-spec))])
13388 "--"
13389 ["Export/Publish..." org-export t]
13390 ("LaTeX"
13391 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13392 :selected org-cdlatex-mode]
13393 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13394 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13395 ["Modify math symbol" org-cdlatex-math-modify
13396 (org-inside-LaTeX-fragment-p)]
13397 ["Export LaTeX fragments as images"
13398 (if (featurep 'org-exp)
13399 (setq org-export-with-LaTeX-fragments
13400 (not org-export-with-LaTeX-fragments))
13401 (require 'org-exp))
13402 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13403 org-export-with-LaTeX-fragments)])
13404 "--"
13405 ("Documentation"
13406 ["Show Version" org-version t]
13407 ["Info Documentation" org-info t])
13408 ("Customize"
13409 ["Browse Org Group" org-customize t]
13410 "--"
13411 ["Expand This Menu" org-create-customize-menu
13412 (fboundp 'customize-menu-create)])
13413 "--"
13414 ["Refresh setup" org-mode-restart t]
13417 (defun org-info (&optional node)
13418 "Read documentation for Org-mode in the info system.
13419 With optional NODE, go directly to that node."
13420 (interactive)
13421 (info (format "(org)%s" (or node ""))))
13423 (defun org-install-agenda-files-menu ()
13424 (let ((bl (buffer-list)))
13425 (save-excursion
13426 (while bl
13427 (set-buffer (pop bl))
13428 (if (org-mode-p) (setq bl nil)))
13429 (when (org-mode-p)
13430 (easy-menu-change
13431 '("Org") "File List for Agenda"
13432 (append
13433 (list
13434 ["Edit File List" (org-edit-agenda-file-list) t]
13435 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13436 ["Remove Current File from List" org-remove-file t]
13437 ["Cycle through agenda files" org-cycle-agenda-files t]
13438 ["Occur in all agenda files" org-occur-in-agenda-files t]
13439 "--")
13440 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13442 ;;;; Documentation
13444 ;;;###autoload
13445 (defun org-require-autoloaded-modules ()
13446 (interactive)
13447 (mapc 'require
13448 '(org-agenda org-archive org-clock org-colview
13449 org-exp org-id org-export-latex org-publish
13450 org-remember org-table)))
13452 ;;;###autoload
13453 (defun org-customize ()
13454 "Call the customize function with org as argument."
13455 (interactive)
13456 (org-load-modules-maybe)
13457 (org-require-autoloaded-modules)
13458 (customize-browse 'org))
13460 (defun org-create-customize-menu ()
13461 "Create a full customization menu for Org-mode, insert it into the menu."
13462 (interactive)
13463 (org-load-modules-maybe)
13464 (org-require-autoloaded-modules)
13465 (if (fboundp 'customize-menu-create)
13466 (progn
13467 (easy-menu-change
13468 '("Org") "Customize"
13469 `(["Browse Org group" org-customize t]
13470 "--"
13471 ,(customize-menu-create 'org)
13472 ["Set" Custom-set t]
13473 ["Save" Custom-save t]
13474 ["Reset to Current" Custom-reset-current t]
13475 ["Reset to Saved" Custom-reset-saved t]
13476 ["Reset to Standard Settings" Custom-reset-standard t]))
13477 (message "\"Org\"-menu now contains full customization menu"))
13478 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13480 ;;;; Miscellaneous stuff
13482 ;;; Generally useful functions
13484 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13485 "Display the given MESSAGE as a warning."
13486 (if (fboundp 'display-warning)
13487 (display-warning 'org message
13488 (if (featurep 'xemacs)
13489 'warning
13490 :warning))
13491 (let ((buf (get-buffer-create "*Org warnings*")))
13492 (with-current-buffer buf
13493 (goto-char (point-max))
13494 (insert "Warning (Org): " message)
13495 (unless (bolp)
13496 (newline)))
13497 (display-buffer buf)
13498 (sit-for 0))))
13500 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13501 "Go to MARKER, widen if necesary. When marker is not live, try BOOKMARK."
13502 (if (and marker (marker-buffer marker)
13503 (buffer-live-p (marker-buffer marker)))
13504 (progn
13505 (switch-to-buffer (marker-buffer marker))
13506 (if (or (> marker (point-max)) (< marker (point-min)))
13507 (widen))
13508 (goto-char marker))
13509 (if bookmark
13510 (bookmark-jump bookmark)
13511 (error "Cannot find location"))))
13513 (defun org-quote-csv-field (s)
13514 "Quote field for inclusion in CSV material."
13515 (if (string-match "[\",]" s)
13516 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13519 (defun org-plist-delete (plist property)
13520 "Delete PROPERTY from PLIST.
13521 This is in contrast to merely setting it to 0."
13522 (let (p)
13523 (while plist
13524 (if (not (eq property (car plist)))
13525 (setq p (plist-put p (car plist) (nth 1 plist))))
13526 (setq plist (cddr plist)))
13529 (defun org-force-self-insert (N)
13530 "Needed to enforce self-insert under remapping."
13531 (interactive "p")
13532 (self-insert-command N))
13534 (defun org-string-width (s)
13535 "Compute width of string, ignoring invisible characters.
13536 This ignores character with invisibility property `org-link', and also
13537 characters with property `org-cwidth', because these will become invisible
13538 upon the next fontification round."
13539 (let (b l)
13540 (when (or (eq t buffer-invisibility-spec)
13541 (assq 'org-link buffer-invisibility-spec))
13542 (while (setq b (text-property-any 0 (length s)
13543 'invisible 'org-link s))
13544 (setq s (concat (substring s 0 b)
13545 (substring s (or (next-single-property-change
13546 b 'invisible s) (length s)))))))
13547 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13548 (setq s (concat (substring s 0 b)
13549 (substring s (or (next-single-property-change
13550 b 'org-cwidth s) (length s))))))
13551 (setq l (string-width s) b -1)
13552 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13553 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13556 (defun org-base-buffer (buffer)
13557 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13558 (if (not buffer)
13559 buffer
13560 (or (buffer-base-buffer buffer)
13561 buffer)))
13563 (defun org-trim (s)
13564 "Remove whitespace at beginning and end of string."
13565 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13566 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13569 (defun org-wrap (string &optional width lines)
13570 "Wrap string to either a number of lines, or a width in characters.
13571 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13572 that costs. If there is a word longer than WIDTH, the text is actually
13573 wrapped to the length of that word.
13574 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13575 many lines, whatever width that takes.
13576 The return value is a list of lines, without newlines at the end."
13577 (let* ((words (org-split-string string "[ \t\n]+"))
13578 (maxword (apply 'max (mapcar 'org-string-width words)))
13579 w ll)
13580 (cond (width
13581 (org-do-wrap words (max maxword width)))
13582 (lines
13583 (setq w maxword)
13584 (setq ll (org-do-wrap words maxword))
13585 (if (<= (length ll) lines)
13587 (setq ll words)
13588 (while (> (length ll) lines)
13589 (setq w (1+ w))
13590 (setq ll (org-do-wrap words w)))
13591 ll))
13592 (t (error "Cannot wrap this")))))
13594 (defun org-do-wrap (words width)
13595 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13596 (let (lines line)
13597 (while words
13598 (setq line (pop words))
13599 (while (and words (< (+ (length line) (length (car words))) width))
13600 (setq line (concat line " " (pop words))))
13601 (setq lines (push line lines)))
13602 (nreverse lines)))
13604 (defun org-split-string (string &optional separators)
13605 "Splits STRING into substrings at SEPARATORS.
13606 No empty strings are returned if there are matches at the beginning
13607 and end of string."
13608 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13609 (start 0)
13610 notfirst
13611 (list nil))
13612 (while (and (string-match rexp string
13613 (if (and notfirst
13614 (= start (match-beginning 0))
13615 (< start (length string)))
13616 (1+ start) start))
13617 (< (match-beginning 0) (length string)))
13618 (setq notfirst t)
13619 (or (eq (match-beginning 0) 0)
13620 (and (eq (match-beginning 0) (match-end 0))
13621 (eq (match-beginning 0) start))
13622 (setq list
13623 (cons (substring string start (match-beginning 0))
13624 list)))
13625 (setq start (match-end 0)))
13626 (or (eq start (length string))
13627 (setq list
13628 (cons (substring string start)
13629 list)))
13630 (nreverse list)))
13632 (defun org-context ()
13633 "Return a list of contexts of the current cursor position.
13634 If several contexts apply, all are returned.
13635 Each context entry is a list with a symbol naming the context, and
13636 two positions indicating start and end of the context. Possible
13637 contexts are:
13639 :headline anywhere in a headline
13640 :headline-stars on the leading stars in a headline
13641 :todo-keyword on a TODO keyword (including DONE) in a headline
13642 :tags on the TAGS in a headline
13643 :priority on the priority cookie in a headline
13644 :item on the first line of a plain list item
13645 :item-bullet on the bullet/number of a plain list item
13646 :checkbox on the checkbox in a plain list item
13647 :table in an org-mode table
13648 :table-special on a special filed in a table
13649 :table-table in a table.el table
13650 :link on a hyperlink
13651 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13652 :target on a <<target>>
13653 :radio-target on a <<<radio-target>>>
13654 :latex-fragment on a LaTeX fragment
13655 :latex-preview on a LaTeX fragment with overlayed preview image
13657 This function expects the position to be visible because it uses font-lock
13658 faces as a help to recognize the following contexts: :table-special, :link,
13659 and :keyword."
13660 (let* ((f (get-text-property (point) 'face))
13661 (faces (if (listp f) f (list f)))
13662 (p (point)) clist o)
13663 ;; First the large context
13664 (cond
13665 ((org-on-heading-p t)
13666 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13667 (when (progn
13668 (beginning-of-line 1)
13669 (looking-at org-todo-line-tags-regexp))
13670 (push (org-point-in-group p 1 :headline-stars) clist)
13671 (push (org-point-in-group p 2 :todo-keyword) clist)
13672 (push (org-point-in-group p 4 :tags) clist))
13673 (goto-char p)
13674 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13675 (if (looking-at "\\[#[A-Z0-9]\\]")
13676 (push (org-point-in-group p 0 :priority) clist)))
13678 ((org-at-item-p)
13679 (push (org-point-in-group p 2 :item-bullet) clist)
13680 (push (list :item (point-at-bol)
13681 (save-excursion (org-end-of-item) (point)))
13682 clist)
13683 (and (org-at-item-checkbox-p)
13684 (push (org-point-in-group p 0 :checkbox) clist)))
13686 ((org-at-table-p)
13687 (push (list :table (org-table-begin) (org-table-end)) clist)
13688 (if (memq 'org-formula faces)
13689 (push (list :table-special
13690 (previous-single-property-change p 'face)
13691 (next-single-property-change p 'face)) clist)))
13692 ((org-at-table-p 'any)
13693 (push (list :table-table) clist)))
13694 (goto-char p)
13696 ;; Now the small context
13697 (cond
13698 ((org-at-timestamp-p)
13699 (push (org-point-in-group p 0 :timestamp) clist))
13700 ((memq 'org-link faces)
13701 (push (list :link
13702 (previous-single-property-change p 'face)
13703 (next-single-property-change p 'face)) clist))
13704 ((memq 'org-special-keyword faces)
13705 (push (list :keyword
13706 (previous-single-property-change p 'face)
13707 (next-single-property-change p 'face)) clist))
13708 ((org-on-target-p)
13709 (push (org-point-in-group p 0 :target) clist)
13710 (goto-char (1- (match-beginning 0)))
13711 (if (looking-at org-radio-target-regexp)
13712 (push (org-point-in-group p 0 :radio-target) clist))
13713 (goto-char p))
13714 ((setq o (car (delq nil
13715 (mapcar
13716 (lambda (x)
13717 (if (memq x org-latex-fragment-image-overlays) x))
13718 (org-overlays-at (point))))))
13719 (push (list :latex-fragment
13720 (org-overlay-start o) (org-overlay-end o)) clist)
13721 (push (list :latex-preview
13722 (org-overlay-start o) (org-overlay-end o)) clist))
13723 ((org-inside-LaTeX-fragment-p)
13724 ;; FIXME: positions wrong.
13725 (push (list :latex-fragment (point) (point)) clist)))
13727 (setq clist (nreverse (delq nil clist)))
13728 clist))
13730 ;; FIXME: Compare with at-regexp-p Do we need both?
13731 (defun org-in-regexp (re &optional nlines visually)
13732 "Check if point is inside a match of regexp.
13733 Normally only the current line is checked, but you can include NLINES extra
13734 lines both before and after point into the search.
13735 If VISUALLY is set, require that the cursor is not after the match but
13736 really on, so that the block visually is on the match."
13737 (catch 'exit
13738 (let ((pos (point))
13739 (eol (point-at-eol (+ 1 (or nlines 0))))
13740 (inc (if visually 1 0)))
13741 (save-excursion
13742 (beginning-of-line (- 1 (or nlines 0)))
13743 (while (re-search-forward re eol t)
13744 (if (and (<= (match-beginning 0) pos)
13745 (>= (+ inc (match-end 0)) pos))
13746 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13748 (defun org-at-regexp-p (regexp)
13749 "Is point inside a match of REGEXP in the current line?"
13750 (catch 'exit
13751 (save-excursion
13752 (let ((pos (point)) (end (point-at-eol)))
13753 (beginning-of-line 1)
13754 (while (re-search-forward regexp end t)
13755 (if (and (<= (match-beginning 0) pos)
13756 (>= (match-end 0) pos))
13757 (throw 'exit t)))
13758 nil))))
13760 (defun org-occur-in-agenda-files (regexp &optional nlines)
13761 "Call `multi-occur' with buffers for all agenda files."
13762 (interactive "sOrg-files matching: \np")
13763 (let* ((files (org-agenda-files))
13764 (tnames (mapcar 'file-truename files))
13765 (extra org-agenda-text-search-extra-files)
13767 (when (eq (car extra) 'agenda-archives)
13768 (setq extra (cdr extra))
13769 (setq files (org-add-archive-files files)))
13770 (while (setq f (pop extra))
13771 (unless (member (file-truename f) tnames)
13772 (add-to-list 'files f 'append)
13773 (add-to-list 'tnames (file-truename f) 'append)))
13774 (multi-occur
13775 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13776 regexp)))
13778 (if (boundp 'occur-mode-find-occurrence-hook)
13779 ;; Emacs 23
13780 (add-hook 'occur-mode-find-occurrence-hook
13781 (lambda ()
13782 (when (org-mode-p)
13783 (org-reveal))))
13784 ;; Emacs 22
13785 (defadvice occur-mode-goto-occurrence
13786 (after org-occur-reveal activate)
13787 (and (org-mode-p) (org-reveal)))
13788 (defadvice occur-mode-goto-occurrence-other-window
13789 (after org-occur-reveal activate)
13790 (and (org-mode-p) (org-reveal)))
13791 (defadvice occur-mode-display-occurrence
13792 (after org-occur-reveal activate)
13793 (when (org-mode-p)
13794 (let ((pos (occur-mode-find-occurrence)))
13795 (with-current-buffer (marker-buffer pos)
13796 (save-excursion
13797 (goto-char pos)
13798 (org-reveal)))))))
13800 (defun org-uniquify (list)
13801 "Remove duplicate elements from LIST."
13802 (let (res)
13803 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13804 res))
13806 (defun org-delete-all (elts list)
13807 "Remove all elements in ELTS from LIST."
13808 (while elts
13809 (setq list (delete (pop elts) list)))
13810 list)
13812 (defun org-back-over-empty-lines ()
13813 "Move backwards over witespace, to the beginning of the first empty line.
13814 Returns the number of empty lines passed."
13815 (let ((pos (point)))
13816 (skip-chars-backward " \t\n\r")
13817 (beginning-of-line 2)
13818 (goto-char (min (point) pos))
13819 (count-lines (point) pos)))
13821 (defun org-skip-whitespace ()
13822 (skip-chars-forward " \t\n\r"))
13824 (defun org-point-in-group (point group &optional context)
13825 "Check if POINT is in match-group GROUP.
13826 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13827 match. If the match group does ot exist or point is not inside it,
13828 return nil."
13829 (and (match-beginning group)
13830 (>= point (match-beginning group))
13831 (<= point (match-end group))
13832 (if context
13833 (list context (match-beginning group) (match-end group))
13834 t)))
13836 (defun org-switch-to-buffer-other-window (&rest args)
13837 "Switch to buffer in a second window on the current frame.
13838 In particular, do not allow pop-up frames."
13839 (let (pop-up-frames special-display-buffer-names special-display-regexps
13840 special-display-function)
13841 (apply 'switch-to-buffer-other-window args)))
13843 (defun org-combine-plists (&rest plists)
13844 "Create a single property list from all plists in PLISTS.
13845 The process starts by copying the first list, and then setting properties
13846 from the other lists. Settings in the last list are the most significant
13847 ones and overrule settings in the other lists."
13848 (let ((rtn (copy-sequence (pop plists)))
13849 p v ls)
13850 (while plists
13851 (setq ls (pop plists))
13852 (while ls
13853 (setq p (pop ls) v (pop ls))
13854 (setq rtn (plist-put rtn p v))))
13855 rtn))
13857 (defun org-move-line-down (arg)
13858 "Move the current line down. With prefix argument, move it past ARG lines."
13859 (interactive "p")
13860 (let ((col (current-column))
13861 beg end pos)
13862 (beginning-of-line 1) (setq beg (point))
13863 (beginning-of-line 2) (setq end (point))
13864 (beginning-of-line (+ 1 arg))
13865 (setq pos (move-marker (make-marker) (point)))
13866 (insert (delete-and-extract-region beg end))
13867 (goto-char pos)
13868 (org-move-to-column col)))
13870 (defun org-move-line-up (arg)
13871 "Move the current line up. With prefix argument, move it past ARG lines."
13872 (interactive "p")
13873 (let ((col (current-column))
13874 beg end pos)
13875 (beginning-of-line 1) (setq beg (point))
13876 (beginning-of-line 2) (setq end (point))
13877 (beginning-of-line (- arg))
13878 (setq pos (move-marker (make-marker) (point)))
13879 (insert (delete-and-extract-region beg end))
13880 (goto-char pos)
13881 (org-move-to-column col)))
13883 (defun org-replace-escapes (string table)
13884 "Replace %-escapes in STRING with values in TABLE.
13885 TABLE is an association list with keys like \"%a\" and string values.
13886 The sequences in STRING may contain normal field width and padding information,
13887 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13888 so values can contain further %-escapes if they are define later in TABLE."
13889 (let ((case-fold-search nil)
13890 e re rpl)
13891 (while (setq e (pop table))
13892 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13893 (while (string-match re string)
13894 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13895 (cdr e)))
13896 (setq string (replace-match rpl t t string))))
13897 string))
13900 (defun org-sublist (list start end)
13901 "Return a section of LIST, from START to END.
13902 Counting starts at 1."
13903 (let (rtn (c start))
13904 (setq list (nthcdr (1- start) list))
13905 (while (and list (<= c end))
13906 (push (pop list) rtn)
13907 (setq c (1+ c)))
13908 (nreverse rtn)))
13910 (defun org-find-base-buffer-visiting (file)
13911 "Like `find-buffer-visiting' but alway return the base buffer and
13912 not an indirect buffer."
13913 (let ((buf (find-buffer-visiting file)))
13914 (if buf
13915 (or (buffer-base-buffer buf) buf)
13916 nil)))
13918 (defun org-image-file-name-regexp ()
13919 "Return regexp matching the file names of images."
13920 (if (fboundp 'image-file-name-regexp)
13921 (image-file-name-regexp)
13922 (let ((image-file-name-extensions
13923 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13924 "xbm" "xpm" "pbm" "pgm" "ppm")))
13925 (concat "\\."
13926 (regexp-opt (nconc (mapcar 'upcase
13927 image-file-name-extensions)
13928 image-file-name-extensions)
13930 "\\'"))))
13932 (defun org-file-image-p (file)
13933 "Return non-nil if FILE is an image."
13934 (save-match-data
13935 (string-match (org-image-file-name-regexp) file)))
13937 (defun org-get-cursor-date ()
13938 "Return the date at cursor in as a time.
13939 This works in the calendar and in the agenda, anywhere else it just
13940 returns the current time."
13941 (let (date day defd)
13942 (cond
13943 ((eq major-mode 'calendar-mode)
13944 (setq date (calendar-cursor-to-date)
13945 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13946 ((eq major-mode 'org-agenda-mode)
13947 (setq day (get-text-property (point) 'day))
13948 (if day
13949 (setq date (calendar-gregorian-from-absolute day)
13950 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13951 (nth 2 date))))))
13952 (or defd (current-time))))
13954 (defvar org-agenda-action-marker (make-marker)
13955 "Marker pointing to the entry for the next agenda action.")
13957 (defun org-mark-entry-for-agenda-action ()
13958 "Mark the current entry as target of an agenda action.
13959 Agenda actions are actions executed from the agenda with the key `k',
13960 which make use of the date at the cursor."
13961 (interactive)
13962 (move-marker org-agenda-action-marker
13963 (save-excursion (org-back-to-heading t) (point))
13964 (current-buffer))
13965 (message
13966 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13968 ;;; Paragraph filling stuff.
13969 ;; We want this to be just right, so use the full arsenal.
13971 (defun org-indent-line-function ()
13972 "Indent line like previous, but further if previous was headline or item."
13973 (interactive)
13974 (let* ((pos (point))
13975 (itemp (org-at-item-p))
13976 column bpos bcol tpos tcol bullet btype bullet-type)
13977 ;; Find the previous relevant line
13978 (beginning-of-line 1)
13979 (cond
13980 ((looking-at "#") (setq column 0))
13981 ((looking-at "\\*+ ") (setq column 0))
13983 (beginning-of-line 0)
13984 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13985 (beginning-of-line 0))
13986 (cond
13987 ((looking-at "\\*+[ \t]+")
13988 (if (not org-adapt-indentation)
13989 (setq column 0)
13990 (goto-char (match-end 0))
13991 (setq column (current-column))))
13992 ((org-in-item-p)
13993 (org-beginning-of-item)
13994 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13995 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
13996 (setq bpos (match-beginning 1) tpos (match-end 0)
13997 bcol (progn (goto-char bpos) (current-column))
13998 tcol (progn (goto-char tpos) (current-column))
13999 bullet (match-string 1)
14000 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14001 (if (> tcol (+ bcol org-description-max-indent))
14002 (setq tcol (+ bcol 5)))
14003 (if (not itemp)
14004 (setq column tcol)
14005 (goto-char pos)
14006 (beginning-of-line 1)
14007 (if (looking-at "\\S-")
14008 (progn
14009 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14010 (setq bullet (match-string 1)
14011 btype (if (string-match "[0-9]" bullet) "n" bullet))
14012 (setq column (if (equal btype bullet-type) bcol tcol)))
14013 (setq column (org-get-indentation)))))
14014 (t (setq column (org-get-indentation))))))
14015 (goto-char pos)
14016 (if (<= (current-column) (current-indentation))
14017 (org-indent-line-to column)
14018 (save-excursion (org-indent-line-to column)))
14019 (setq column (current-column))
14020 (beginning-of-line 1)
14021 (if (looking-at
14022 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14023 (replace-match (concat "\\1" (format org-property-format
14024 (match-string 2) (match-string 3)))
14025 t nil))
14026 (org-move-to-column column)))
14028 (defun org-set-autofill-regexps ()
14029 (interactive)
14030 ;; In the paragraph separator we include headlines, because filling
14031 ;; text in a line directly attached to a headline would otherwise
14032 ;; fill the headline as well.
14033 (org-set-local 'comment-start-skip "^#+[ \t]*")
14034 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14035 ;; The paragraph starter includes hand-formatted lists.
14036 (org-set-local 'paragraph-start
14037 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14038 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14039 ;; But only if the user has not turned off tables or fixed-width regions
14040 (org-set-local
14041 'auto-fill-inhibit-regexp
14042 (concat "\\*+ \\|#\\+"
14043 "\\|[ \t]*" org-keyword-time-regexp
14044 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14045 (concat
14046 "\\|[ \t]*["
14047 (if org-enable-table-editor "|" "")
14048 (if org-enable-fixed-width-editor ":" "")
14049 "]"))))
14050 ;; We use our own fill-paragraph function, to make sure that tables
14051 ;; and fixed-width regions are not wrapped. That function will pass
14052 ;; through to `fill-paragraph' when appropriate.
14053 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14054 ; Adaptive filling: To get full control, first make sure that
14055 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14056 (org-set-local 'adaptive-fill-regexp "\000")
14057 (org-set-local 'adaptive-fill-function
14058 'org-adaptive-fill-function)
14059 (org-set-local
14060 'align-mode-rules-list
14061 '((org-in-buffer-settings
14062 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14063 (modes . '(org-mode))))))
14065 (defun org-fill-paragraph (&optional justify)
14066 "Re-align a table, pass through to fill-paragraph if no table."
14067 (let ((table-p (org-at-table-p))
14068 (table.el-p (org-at-table.el-p)))
14069 (cond ((and (equal (char-after (point-at-bol)) ?*)
14070 (save-excursion (goto-char (point-at-bol))
14071 (looking-at outline-regexp)))
14072 t) ; skip headlines
14073 (table.el-p t) ; skip table.el tables
14074 (table-p (org-table-align) t) ; align org-mode tables
14075 (t nil)))) ; call paragraph-fill
14077 ;; For reference, this is the default value of adaptive-fill-regexp
14078 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14080 (defun org-adaptive-fill-function ()
14081 "Return a fill prefix for org-mode files.
14082 In particular, this makes sure hanging paragraphs for hand-formatted lists
14083 work correctly."
14084 (cond ((looking-at "#[ \t]+")
14085 (match-string 0))
14086 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14087 (save-excursion
14088 (if (> (match-end 1) (+ (match-beginning 1)
14089 org-description-max-indent))
14090 (goto-char (+ (match-beginning 1) 5))
14091 (goto-char (match-end 0)))
14092 (make-string (current-column) ?\ )))
14093 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
14094 (save-excursion
14095 (goto-char (match-end 0))
14096 (make-string (current-column) ?\ )))
14097 (t nil)))
14099 ;;; Other stuff.
14101 (defun org-toggle-fixed-width-section (arg)
14102 "Toggle the fixed-width export.
14103 If there is no active region, the QUOTE keyword at the current headline is
14104 inserted or removed. When present, it causes the text between this headline
14105 and the next to be exported as fixed-width text, and unmodified.
14106 If there is an active region, this command adds or removes a colon as the
14107 first character of this line. If the first character of a line is a colon,
14108 this line is also exported in fixed-width font."
14109 (interactive "P")
14110 (let* ((cc 0)
14111 (regionp (org-region-active-p))
14112 (beg (if regionp (region-beginning) (point)))
14113 (end (if regionp (region-end)))
14114 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14115 (case-fold-search nil)
14116 (re "[ \t]*\\(:\\)")
14117 off)
14118 (if regionp
14119 (save-excursion
14120 (goto-char beg)
14121 (setq cc (current-column))
14122 (beginning-of-line 1)
14123 (setq off (looking-at re))
14124 (while (> nlines 0)
14125 (setq nlines (1- nlines))
14126 (beginning-of-line 1)
14127 (cond
14128 (arg
14129 (org-move-to-column cc t)
14130 (insert ":\n")
14131 (forward-line -1))
14132 ((and off (looking-at re))
14133 (replace-match "" t t nil 1))
14134 ((not off) (org-move-to-column cc t) (insert ":")))
14135 (forward-line 1)))
14136 (save-excursion
14137 (org-back-to-heading)
14138 (if (looking-at (concat outline-regexp
14139 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14140 (replace-match "" t t nil 1)
14141 (if (looking-at outline-regexp)
14142 (progn
14143 (goto-char (match-end 0))
14144 (insert org-quote-string " "))))))))
14146 ;;;; Functions extending outline functionality
14148 (defun org-beginning-of-line (&optional arg)
14149 "Go to the beginning of the current line. If that is invisible, continue
14150 to a visible line beginning. This makes the function of C-a more intuitive.
14151 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14152 first attempt, and only move to after the tags when the cursor is already
14153 beyond the end of the headline."
14154 (interactive "P")
14155 (let ((pos (point)) refpos)
14156 (beginning-of-line 1)
14157 (if (bobp)
14159 (backward-char 1)
14160 (if (org-invisible-p)
14161 (while (and (not (bobp)) (org-invisible-p))
14162 (backward-char 1)
14163 (beginning-of-line 1))
14164 (forward-char 1)))
14165 (when org-special-ctrl-a/e
14166 (cond
14167 ((and (looking-at org-complex-heading-regexp)
14168 (= (char-after (match-end 1)) ?\ ))
14169 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14170 (point-at-eol)))
14171 (goto-char
14172 (if (eq org-special-ctrl-a/e t)
14173 (cond ((> pos refpos) refpos)
14174 ((= pos (point)) refpos)
14175 (t (point)))
14176 (cond ((> pos (point)) (point))
14177 ((not (eq last-command this-command)) (point))
14178 (t refpos)))))
14179 ((org-at-item-p)
14180 (goto-char
14181 (if (eq org-special-ctrl-a/e t)
14182 (cond ((> pos (match-end 4)) (match-end 4))
14183 ((= pos (point)) (match-end 4))
14184 (t (point)))
14185 (cond ((> pos (point)) (point))
14186 ((not (eq last-command this-command)) (point))
14187 (t (match-end 4))))))))
14188 (org-no-warnings
14189 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14191 (defun org-end-of-line (&optional arg)
14192 "Go to the end of the line.
14193 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14194 first attempt, and only move to after the tags when the cursor is already
14195 beyond the end of the headline."
14196 (interactive "P")
14197 (if (or (not org-special-ctrl-a/e)
14198 (not (org-on-heading-p)))
14199 (end-of-line arg)
14200 (let ((pos (point)))
14201 (beginning-of-line 1)
14202 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14203 (if (eq org-special-ctrl-a/e t)
14204 (if (or (< pos (match-beginning 1))
14205 (= pos (match-end 0)))
14206 (goto-char (match-beginning 1))
14207 (goto-char (match-end 0)))
14208 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14209 (goto-char (match-end 0))
14210 (goto-char (match-beginning 1))))
14211 (end-of-line arg))))
14212 (org-no-warnings
14213 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14216 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14217 (define-key org-mode-map "\C-e" 'org-end-of-line)
14219 (defun org-kill-line (&optional arg)
14220 "Kill line, to tags or end of line."
14221 (interactive "P")
14222 (cond
14223 ((or (not org-special-ctrl-k)
14224 (bolp)
14225 (not (org-on-heading-p)))
14226 (call-interactively 'kill-line))
14227 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14228 (kill-region (point) (match-beginning 1))
14229 (org-set-tags nil t))
14230 (t (kill-region (point) (point-at-eol)))))
14232 (define-key org-mode-map "\C-k" 'org-kill-line)
14234 (defun org-invisible-p ()
14235 "Check if point is at a character currently not visible."
14236 ;; Early versions of noutline don't have `outline-invisible-p'.
14237 (if (fboundp 'outline-invisible-p)
14238 (outline-invisible-p)
14239 (get-char-property (point) 'invisible)))
14241 (defun org-invisible-p2 ()
14242 "Check if point is at a character currently not visible."
14243 (save-excursion
14244 (if (and (eolp) (not (bobp))) (backward-char 1))
14245 ;; Early versions of noutline don't have `outline-invisible-p'.
14246 (if (fboundp 'outline-invisible-p)
14247 (outline-invisible-p)
14248 (get-char-property (point) 'invisible))))
14250 (defalias 'org-back-to-heading 'outline-back-to-heading)
14251 (defalias 'org-on-heading-p 'outline-on-heading-p)
14252 (defalias 'org-at-heading-p 'outline-on-heading-p)
14253 (defun org-at-heading-or-item-p ()
14254 (or (org-on-heading-p) (org-at-item-p)))
14256 (defun org-on-target-p ()
14257 (or (org-in-regexp org-radio-target-regexp)
14258 (org-in-regexp org-target-regexp)))
14260 (defun org-up-heading-all (arg)
14261 "Move to the heading line of which the present line is a subheading.
14262 This function considers both visible and invisible heading lines.
14263 With argument, move up ARG levels."
14264 (if (fboundp 'outline-up-heading-all)
14265 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14266 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14268 (defun org-up-heading-safe ()
14269 "Move to the heading line of which the present line is a subheading.
14270 This version will not throw an error. It will return the level of the
14271 headline found, or nil if no higher level is found."
14272 (let ((pos (point)) start-level level
14273 (re (concat "^" outline-regexp)))
14274 (catch 'exit
14275 (outline-back-to-heading t)
14276 (setq start-level (funcall outline-level))
14277 (if (equal start-level 1) (throw 'exit nil))
14278 (while (re-search-backward re nil t)
14279 (setq level (funcall outline-level))
14280 (if (< level start-level) (throw 'exit level)))
14281 nil)))
14283 (defun org-first-sibling-p ()
14284 "Is this heading the first child of its parents?"
14285 (interactive)
14286 (let ((re (concat "^" outline-regexp))
14287 level l)
14288 (unless (org-at-heading-p t)
14289 (error "Not at a heading"))
14290 (setq level (funcall outline-level))
14291 (save-excursion
14292 (if (not (re-search-backward re nil t))
14294 (setq l (funcall outline-level))
14295 (< l level)))))
14297 (defun org-goto-sibling (&optional previous)
14298 "Goto the next sibling, even if it is invisible.
14299 When PREVIOUS is set, go to the previous sibling instead. Returns t
14300 when a sibling was found. When none is found, return nil and don't
14301 move point."
14302 (let ((fun (if previous 're-search-backward 're-search-forward))
14303 (pos (point))
14304 (re (concat "^" outline-regexp))
14305 level l)
14306 (when (condition-case nil (org-back-to-heading t) (error nil))
14307 (setq level (funcall outline-level))
14308 (catch 'exit
14309 (or previous (forward-char 1))
14310 (while (funcall fun re nil t)
14311 (setq l (funcall outline-level))
14312 (when (< l level) (goto-char pos) (throw 'exit nil))
14313 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14314 (goto-char pos)
14315 nil))))
14317 (defun org-show-siblings ()
14318 "Show all siblings of the current headline."
14319 (save-excursion
14320 (while (org-goto-sibling) (org-flag-heading nil)))
14321 (save-excursion
14322 (while (org-goto-sibling 'previous)
14323 (org-flag-heading nil))))
14325 (defun org-show-hidden-entry ()
14326 "Show an entry where even the heading is hidden."
14327 (save-excursion
14328 (org-show-entry)))
14330 (defun org-flag-heading (flag &optional entry)
14331 "Flag the current heading. FLAG non-nil means make invisible.
14332 When ENTRY is non-nil, show the entire entry."
14333 (save-excursion
14334 (org-back-to-heading t)
14335 ;; Check if we should show the entire entry
14336 (if entry
14337 (progn
14338 (org-show-entry)
14339 (save-excursion
14340 (and (outline-next-heading)
14341 (org-flag-heading nil))))
14342 (outline-flag-region (max (point-min) (1- (point)))
14343 (save-excursion (outline-end-of-heading) (point))
14344 flag))))
14346 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14347 ;; This is an exact copy of the original function, but it uses
14348 ;; `org-back-to-heading', to make it work also in invisible
14349 ;; trees. And is uses an invisible-OK argument.
14350 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14351 (org-back-to-heading invisible-OK)
14352 (let ((first t)
14353 (level (funcall outline-level)))
14354 (while (and (not (eobp))
14355 (or first (> (funcall outline-level) level)))
14356 (setq first nil)
14357 (outline-next-heading))
14358 (unless to-heading
14359 (if (memq (preceding-char) '(?\n ?\^M))
14360 (progn
14361 ;; Go to end of line before heading
14362 (forward-char -1)
14363 (if (memq (preceding-char) '(?\n ?\^M))
14364 ;; leave blank line before heading
14365 (forward-char -1))))))
14366 (point))
14368 (defun org-show-subtree ()
14369 "Show everything after this heading at deeper levels."
14370 (outline-flag-region
14371 (point)
14372 (save-excursion
14373 (outline-end-of-subtree) (outline-next-heading) (point))
14374 nil))
14376 (defun org-show-entry ()
14377 "Show the body directly following this heading.
14378 Show the heading too, if it is currently invisible."
14379 (interactive)
14380 (save-excursion
14381 (condition-case nil
14382 (progn
14383 (org-back-to-heading t)
14384 (outline-flag-region
14385 (max (point-min) (1- (point)))
14386 (save-excursion
14387 (re-search-forward
14388 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14389 (or (match-beginning 1) (point-max)))
14390 nil))
14391 (error nil))))
14393 (defun org-make-options-regexp (kwds)
14394 "Make a regular expression for keyword lines."
14395 (concat
14397 "#?[ \t]*\\+\\("
14398 (mapconcat 'regexp-quote kwds "\\|")
14399 "\\):[ \t]*"
14400 "\\(.+\\)"))
14402 ;; Make isearch reveal the necessary context
14403 (defun org-isearch-end ()
14404 "Reveal context after isearch exits."
14405 (when isearch-success ; only if search was successful
14406 (if (featurep 'xemacs)
14407 ;; Under XEmacs, the hook is run in the correct place,
14408 ;; we directly show the context.
14409 (org-show-context 'isearch)
14410 ;; In Emacs the hook runs *before* restoring the overlays.
14411 ;; So we have to use a one-time post-command-hook to do this.
14412 ;; (Emacs 22 has a special variable, see function `org-mode')
14413 (unless (and (boundp 'isearch-mode-end-hook-quit)
14414 isearch-mode-end-hook-quit)
14415 ;; Only when the isearch was not quitted.
14416 (org-add-hook 'post-command-hook 'org-isearch-post-command
14417 'append 'local)))))
14419 (defun org-isearch-post-command ()
14420 "Remove self from hook, and show context."
14421 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14422 (org-show-context 'isearch))
14425 ;;;; Integration with and fixes for other packages
14427 ;;; Imenu support
14429 (defvar org-imenu-markers nil
14430 "All markers currently used by Imenu.")
14431 (make-variable-buffer-local 'org-imenu-markers)
14433 (defun org-imenu-new-marker (&optional pos)
14434 "Return a new marker for use by Imenu, and remember the marker."
14435 (let ((m (make-marker)))
14436 (move-marker m (or pos (point)))
14437 (push m org-imenu-markers)
14440 (defun org-imenu-get-tree ()
14441 "Produce the index for Imenu."
14442 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14443 (setq org-imenu-markers nil)
14444 (let* ((n org-imenu-depth)
14445 (re (concat "^" outline-regexp))
14446 (subs (make-vector (1+ n) nil))
14447 (last-level 0)
14448 m tree level head)
14449 (save-excursion
14450 (save-restriction
14451 (widen)
14452 (goto-char (point-max))
14453 (while (re-search-backward re nil t)
14454 (setq level (org-reduced-level (funcall outline-level)))
14455 (when (<= level n)
14456 (looking-at org-complex-heading-regexp)
14457 (setq head (org-match-string-no-properties 4)
14458 m (org-imenu-new-marker))
14459 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14460 (if (>= level last-level)
14461 (push (cons head m) (aref subs level))
14462 (push (cons head (aref subs (1+ level))) (aref subs level))
14463 (loop for i from (1+ level) to n do (aset subs i nil)))
14464 (setq last-level level)))))
14465 (aref subs 1)))
14467 (eval-after-load "imenu"
14468 '(progn
14469 (add-hook 'imenu-after-jump-hook
14470 (lambda ()
14471 (if (eq major-mode 'org-mode)
14472 (org-show-context 'org-goto))))))
14474 ;; Speedbar support
14476 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14477 "Overlay marking the agenda restriction line in speedbar.")
14478 (org-overlay-put org-speedbar-restriction-lock-overlay
14479 'face 'org-agenda-restriction-lock)
14480 (org-overlay-put org-speedbar-restriction-lock-overlay
14481 'help-echo "Agendas are currently limited to this item.")
14482 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14484 (defun org-speedbar-set-agenda-restriction ()
14485 "Restrict future agenda commands to the location at point in speedbar.
14486 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14487 (interactive)
14488 (require 'org-agenda)
14489 (let (p m tp np dir txt w)
14490 (cond
14491 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14492 'org-imenu t))
14493 (setq m (get-text-property p 'org-imenu-marker))
14494 (save-excursion
14495 (save-restriction
14496 (set-buffer (marker-buffer m))
14497 (goto-char m)
14498 (org-agenda-set-restriction-lock 'subtree))))
14499 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14500 'speedbar-function 'speedbar-find-file))
14501 (setq tp (previous-single-property-change
14502 (1+ p) 'speedbar-function)
14503 np (next-single-property-change
14504 tp 'speedbar-function)
14505 dir (speedbar-line-directory)
14506 txt (buffer-substring-no-properties (or tp (point-min))
14507 (or np (point-max))))
14508 (save-excursion
14509 (save-restriction
14510 (set-buffer (find-file-noselect
14511 (let ((default-directory dir))
14512 (expand-file-name txt))))
14513 (unless (org-mode-p)
14514 (error "Cannot restrict to non-Org-mode file"))
14515 (org-agenda-set-restriction-lock 'file))))
14516 (t (error "Don't know how to restrict Org-mode's agenda")))
14517 (org-move-overlay org-speedbar-restriction-lock-overlay
14518 (point-at-bol) (point-at-eol))
14519 (setq current-prefix-arg nil)
14520 (org-agenda-maybe-redo)))
14522 (eval-after-load "speedbar"
14523 '(progn
14524 (speedbar-add-supported-extension ".org")
14525 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14526 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14527 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14528 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14529 (add-hook 'speedbar-visiting-tag-hook
14530 (lambda () (org-show-context 'org-goto)))))
14533 ;;; Fixes and Hacks for problems with other packages
14535 ;; Make flyspell not check words in links, to not mess up our keymap
14536 (defun org-mode-flyspell-verify ()
14537 "Don't let flyspell put overlays at active buttons."
14538 (not (get-text-property (point) 'keymap)))
14540 ;; Make `bookmark-jump' show the jump location if it was hidden.
14541 (eval-after-load "bookmark"
14542 '(if (boundp 'bookmark-after-jump-hook)
14543 ;; We can use the hook
14544 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14545 ;; Hook not available, use advice
14546 (defadvice bookmark-jump (after org-make-visible activate)
14547 "Make the position visible."
14548 (org-bookmark-jump-unhide))))
14550 (defun org-bookmark-jump-unhide ()
14551 "Unhide the current position, to show the bookmark location."
14552 (and (org-mode-p)
14553 (or (org-invisible-p)
14554 (save-excursion (goto-char (max (point-min) (1- (point))))
14555 (org-invisible-p)))
14556 (org-show-context 'bookmark-jump)))
14558 ;; Make session.el ignore our circular variable
14559 (eval-after-load "session"
14560 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14562 ;;;; Experimental code
14564 (defun org-closed-in-range ()
14565 "Sparse tree of items closed in a certain time range.
14566 Still experimental, may disappear in the future."
14567 (interactive)
14568 ;; Get the time interval from the user.
14569 (let* ((time1 (time-to-seconds
14570 (org-read-date nil 'to-time nil "Starting date: ")))
14571 (time2 (time-to-seconds
14572 (org-read-date nil 'to-time nil "End date:")))
14573 ;; callback function
14574 (callback (lambda ()
14575 (let ((time
14576 (time-to-seconds
14577 (apply 'encode-time
14578 (org-parse-time-string
14579 (match-string 1))))))
14580 ;; check if time in interval
14581 (and (>= time time1) (<= time time2))))))
14582 ;; make tree, check each match with the callback
14583 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14586 ;;;; Finish up
14588 (provide 'org)
14590 (run-hooks 'org-load-hook)
14592 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14594 ;;; org.el ends here