Release 6.06.
[org-mode.git] / lisp / org.el
blob678fd0a68d09c5ef92f3d173e6756815e64cd499
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.06
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.06"
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-open-directory-means-index-dot-org nil
1066 "Non-nil means, a link to a directory really means to index.org.
1067 When nil, following a directory link will run dired or open a finder/explorer
1068 window on that directory."
1069 :group 'org-link-follow
1070 :type 'boolean)
1072 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1073 "Function and arguments to call for following mailto links.
1074 This is a list with the first element being a lisp function, and the
1075 remaining elements being arguments to the function. In string arguments,
1076 %a will be replaced by the address, and %s will be replaced by the subject
1077 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1078 :group 'org-link-follow
1079 :type '(choice
1080 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1081 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1082 (const :tag "message-mail" (message-mail "%a" "%s"))
1083 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1085 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1086 "Non-nil means, ask for confirmation before executing shell links.
1087 Shell links can be dangerous: just think about a link
1089 [[shell:rm -rf ~/*][Google Search]]
1091 This link would show up in your Org-mode document as \"Google Search\",
1092 but really it would remove your entire home directory.
1093 Therefore we advise against setting this variable to nil.
1094 Just change it to `y-or-n-p' of you want to confirm with a
1095 single keystroke rather than having to type \"yes\"."
1096 :group 'org-link-follow
1097 :type '(choice
1098 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1099 (const :tag "with y-or-n (faster)" y-or-n-p)
1100 (const :tag "no confirmation (dangerous)" nil)))
1102 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1103 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1104 Elisp links can be dangerous: just think about a link
1106 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1108 This link would show up in your Org-mode document as \"Google Search\",
1109 but really it would remove your entire home directory.
1110 Therefore we advise against setting this variable to nil.
1111 Just change it to `y-or-n-p' of you want to confirm with a
1112 single keystroke rather than having to type \"yes\"."
1113 :group 'org-link-follow
1114 :type '(choice
1115 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1116 (const :tag "with y-or-n (faster)" y-or-n-p)
1117 (const :tag "no confirmation (dangerous)" nil)))
1119 (defconst org-file-apps-defaults-gnu
1120 '((remote . emacs)
1121 (t . mailcap))
1122 "Default file applications on a UNIX or GNU/Linux system.
1123 See `org-file-apps'.")
1125 (defconst org-file-apps-defaults-macosx
1126 '((remote . emacs)
1127 (t . "open %s")
1128 ("ps" . "gv %s")
1129 ("ps.gz" . "gv %s")
1130 ("eps" . "gv %s")
1131 ("eps.gz" . "gv %s")
1132 ("dvi" . "xdvi %s")
1133 ("fig" . "xfig %s"))
1134 "Default file applications on a MacOS X system.
1135 The system \"open\" is known as a default, but we use X11 applications
1136 for some files for which the OS does not have a good default.
1137 See `org-file-apps'.")
1139 (defconst org-file-apps-defaults-windowsnt
1140 (list
1141 '(remote . emacs)
1142 (cons t
1143 (list (if (featurep 'xemacs)
1144 'mswindows-shell-execute
1145 'w32-shell-execute)
1146 "open" 'file)))
1147 "Default file applications on a Windows NT system.
1148 The system \"open\" is used for most files.
1149 See `org-file-apps'.")
1151 (defcustom org-file-apps
1153 ("txt" . emacs)
1154 ("tex" . emacs)
1155 ("ltx" . emacs)
1156 ("org" . emacs)
1157 ("el" . emacs)
1158 ("bib" . emacs)
1160 "External applications for opening `file:path' items in a document.
1161 Org-mode uses system defaults for different file types, but
1162 you can use this variable to set the application for a given file
1163 extension. The entries in this list are cons cells where the car identifies
1164 files and the cdr the corresponding command. Possible values for the
1165 file identifier are
1166 \"ext\" A string identifying an extension
1167 `directory' Matches a directory
1168 `remote' Matches a remote file, accessible through tramp or efs.
1169 Remote files most likely should be visited through Emacs
1170 because external applications cannot handle such paths.
1171 t Default for all remaining files
1173 Possible values for the command are:
1174 `emacs' The file will be visited by the current Emacs process.
1175 `default' Use the default application for this file type.
1176 string A command to be executed by a shell; %s will be replaced
1177 by the path to the file.
1178 sexp A Lisp form which will be evaluated. The file path will
1179 be available in the Lisp variable `file'.
1180 For more examples, see the system specific constants
1181 `org-file-apps-defaults-macosx'
1182 `org-file-apps-defaults-windowsnt'
1183 `org-file-apps-defaults-gnu'."
1184 :group 'org-link-follow
1185 :type '(repeat
1186 (cons (choice :value ""
1187 (string :tag "Extension")
1188 (const :tag "Default for unrecognized files" t)
1189 (const :tag "Remote file" remote)
1190 (const :tag "Links to a directory" directory))
1191 (choice :value ""
1192 (const :tag "Visit with Emacs" emacs)
1193 (const :tag "Use system default" default)
1194 (string :tag "Command")
1195 (sexp :tag "Lisp form")))))
1197 (defgroup org-refile nil
1198 "Options concerning refiling entries in Org-mode."
1199 :tag "Org Remember"
1200 :group 'org)
1202 (defcustom org-directory "~/org"
1203 "Directory with org files.
1204 This directory will be used as default to prompt for org files.
1205 Used by the hooks for remember.el."
1206 :group 'org-refile
1207 :group 'org-remember
1208 :type 'directory)
1210 (defcustom org-default-notes-file "~/.notes"
1211 "Default target for storing notes.
1212 Used by the hooks for remember.el. This can be a string, or nil to mean
1213 the value of `remember-data-file'.
1214 You can set this on a per-template basis with the variable
1215 `org-remember-templates'."
1216 :group 'org-refile
1217 :group 'org-remember
1218 :type '(choice
1219 (const :tag "Default from remember-data-file" nil)
1220 file))
1222 (defcustom org-goto-interface 'outline
1223 "The default interface to be used for `org-goto'.
1224 Allowed vaues are:
1225 outline The interface shows an outline of the relevant file
1226 and the correct heading is found by moving through
1227 the outline or by searching with incremental search.
1228 outline-path-completion Headlines in the current buffer are offered via
1229 completion."
1230 :group 'org-refile
1231 :type '(choice
1232 (const :tag "Outline" outline)
1233 (const :tag "Outline-path-completion" outline-path-completion)))
1235 (defcustom org-reverse-note-order nil
1236 "Non-nil means, store new notes at the beginning of a file or entry.
1237 When nil, new notes will be filed to the end of a file or entry.
1238 This can also be a list with cons cells of regular expressions that
1239 are matched against file names, and values."
1240 :group 'org-remember
1241 :type '(choice
1242 (const :tag "Reverse always" t)
1243 (const :tag "Reverse never" nil)
1244 (repeat :tag "By file name regexp"
1245 (cons regexp boolean))))
1247 (defcustom org-refile-targets nil
1248 "Targets for refiling entries with \\[org-refile].
1249 This is list of cons cells. Each cell contains:
1250 - a specification of the files to be considered, either a list of files,
1251 or a symbol whose function or variable value will be used to retrieve
1252 a file name or a list of file names. Nil means, refile to a different
1253 heading in the current buffer.
1254 - A specification of how to find candidate refile targets. This may be
1255 any of
1256 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1257 This tag has to be present in all target headlines, inheritance will
1258 not be considered.
1259 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1260 todo keyword.
1261 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1262 headlines that are refiling targets.
1263 - a cons cell (:level . N). Any headline of level N is considered a target.
1264 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1265 :group 'org-remember
1266 :type '(repeat
1267 (cons
1268 (choice :value org-agenda-files
1269 (const :tag "All agenda files" org-agenda-files)
1270 (const :tag "Current buffer" nil)
1271 (function) (variable) (file))
1272 (choice :tag "Identify target headline by"
1273 (cons :tag "Specific tag" (const :tag) (string))
1274 (cons :tag "TODO keyword" (const :todo) (string))
1275 (cons :tag "Regular expression" (const :regexp) (regexp))
1276 (cons :tag "Level number" (const :level) (integer))
1277 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1279 (defcustom org-refile-use-outline-path nil
1280 "Non-nil means, provide refile targets as paths.
1281 So a level 3 headline will be available as level1/level2/level3.
1282 When the value is `file', also include the file name (without directory)
1283 into the path. When `full-file-path', include the full file path."
1284 :group 'org-remember
1285 :type '(choice
1286 (const :tag "Not" nil)
1287 (const :tag "Yes" t)
1288 (const :tag "Start with file name" file)
1289 (const :tag "Start with full file path" full-file-path)))
1291 (defgroup org-todo nil
1292 "Options concerning TODO items in Org-mode."
1293 :tag "Org TODO"
1294 :group 'org)
1296 (defgroup org-progress nil
1297 "Options concerning Progress logging in Org-mode."
1298 :tag "Org Progress"
1299 :group 'org-time)
1301 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1302 "List of TODO entry keyword sequences and their interpretation.
1303 \\<org-mode-map>This is a list of sequences.
1305 Each sequence starts with a symbol, either `sequence' or `type',
1306 indicating if the keywords should be interpreted as a sequence of
1307 action steps, or as different types of TODO items. The first
1308 keywords are states requiring action - these states will select a headline
1309 for inclusion into the global TODO list Org-mode produces. If one of
1310 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1311 signify that no further action is necessary. If \"|\" is not found,
1312 the last keyword is treated as the only DONE state of the sequence.
1314 The command \\[org-todo] cycles an entry through these states, and one
1315 additional state where no keyword is present. For details about this
1316 cycling, see the manual.
1318 TODO keywords and interpretation can also be set on a per-file basis with
1319 the special #+SEQ_TODO and #+TYP_TODO lines.
1321 Each keyword can optionally specify a character for fast state selection
1322 \(in combination with the variable `org-use-fast-todo-selection')
1323 and specifiers for state change logging, using the same syntax
1324 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1325 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1326 indicates to record a time stamp each time this state is selected.
1328 Each keyword may also specify if a timestamp or a note should be
1329 recorded when entering or leaving the state, by adding additional
1330 characters in the parenthesis after the keyword. This looks like this:
1331 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1332 record only the time of the state change. With X and Y being either
1333 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1334 Y when leaving the state if and only if the *target* state does not
1335 define X. You may omit any of the fast-selection key or X or /Y,
1336 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1338 For backward compatibility, this variable may also be just a list
1339 of keywords - in this case the interptetation (sequence or type) will be
1340 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1341 :group 'org-todo
1342 :group 'org-keywords
1343 :type '(choice
1344 (repeat :tag "Old syntax, just keywords"
1345 (string :tag "Keyword"))
1346 (repeat :tag "New syntax"
1347 (cons
1348 (choice
1349 :tag "Interpretation"
1350 (const :tag "Sequence (cycling hits every state)" sequence)
1351 (const :tag "Type (cycling directly to DONE)" type))
1352 (repeat
1353 (string :tag "Keyword"))))))
1355 (defvar org-todo-keywords-1 nil
1356 "All TODO and DONE keywords active in a buffer.")
1357 (make-variable-buffer-local 'org-todo-keywords-1)
1358 (defvar org-todo-keywords-for-agenda nil)
1359 (defvar org-done-keywords-for-agenda nil)
1360 (defvar org-agenda-contributing-files nil)
1361 (defvar org-not-done-keywords nil)
1362 (make-variable-buffer-local 'org-not-done-keywords)
1363 (defvar org-done-keywords nil)
1364 (make-variable-buffer-local 'org-done-keywords)
1365 (defvar org-todo-heads nil)
1366 (make-variable-buffer-local 'org-todo-heads)
1367 (defvar org-todo-sets nil)
1368 (make-variable-buffer-local 'org-todo-sets)
1369 (defvar org-todo-log-states nil)
1370 (make-variable-buffer-local 'org-todo-log-states)
1371 (defvar org-todo-kwd-alist nil)
1372 (make-variable-buffer-local 'org-todo-kwd-alist)
1373 (defvar org-todo-key-alist nil)
1374 (make-variable-buffer-local 'org-todo-key-alist)
1375 (defvar org-todo-key-trigger nil)
1376 (make-variable-buffer-local 'org-todo-key-trigger)
1378 (defcustom org-todo-interpretation 'sequence
1379 "Controls how TODO keywords are interpreted.
1380 This variable is in principle obsolete and is only used for
1381 backward compatibility, if the interpretation of todo keywords is
1382 not given already in `org-todo-keywords'. See that variable for
1383 more information."
1384 :group 'org-todo
1385 :group 'org-keywords
1386 :type '(choice (const sequence)
1387 (const type)))
1389 (defcustom org-use-fast-todo-selection 'prefix
1390 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1391 This variable describes if and under what circumstances the cycling
1392 mechanism for TODO keywords will be replaced by a single-key, direct
1393 selection scheme.
1395 When nil, fast selection is never used.
1397 When the symbol `prefix', it will be used when `org-todo' is called with
1398 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1399 in an agenda buffer.
1401 When t, fast selection is used by default. In this case, the prefix
1402 argument forces cycling instead.
1404 In all cases, the special interface is only used if access keys have actually
1405 been assigned by the user, i.e. if keywords in the configuration are followed
1406 by a letter in parenthesis, like TODO(t)."
1407 :group 'org-todo
1408 :type '(choice
1409 (const :tag "Never" nil)
1410 (const :tag "By default" t)
1411 (const :tag "Only with C-u C-c C-t" prefix)))
1413 (defcustom org-provide-todo-statistics t
1414 "Non-nil means, update todo statistics after insert and toggle.
1415 When this is set, todo statistics is updated in the parent of the current
1416 entry each time a todo state is changed."
1417 :group 'org-todo
1418 :type 'boolean)
1420 (defcustom org-after-todo-state-change-hook nil
1421 "Hook which is run after the state of a TODO item was changed.
1422 The new state (a string with a TODO keyword, or nil) is available in the
1423 Lisp variable `state'."
1424 :group 'org-todo
1425 :type 'hook)
1427 (defcustom org-log-done nil
1428 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1429 When equal to the list (done), also prompt for a closing note.
1430 This can also be configured on a per-file basis by adding one of
1431 the following lines anywhere in the buffer:
1433 #+STARTUP: logdone
1434 #+STARTUP: lognotedone
1435 #+STARTUP: nologdone"
1436 :group 'org-todo
1437 :group 'org-progress
1438 :type '(choice
1439 (const :tag "No logging" nil)
1440 (const :tag "Record CLOSED timestamp" time)
1441 (const :tag "Record CLOSED timestamp with closing note." note)))
1443 ;; Normalize old uses of org-log-done.
1444 (cond
1445 ((eq org-log-done t) (setq org-log-done 'time))
1446 ((and (listp org-log-done) (memq 'done org-log-done))
1447 (setq org-log-done 'note)))
1449 (defcustom org-log-note-clock-out nil
1450 "Non-nil means, recored a note when clocking out of an item.
1451 This can also be configured on a per-file basis by adding one of
1452 the following lines anywhere in the buffer:
1454 #+STARTUP: lognoteclock-out
1455 #+STARTUP: nolognoteclock-out"
1456 :group 'org-todo
1457 :group 'org-progress
1458 :type 'boolean)
1460 (defcustom org-log-done-with-time t
1461 "Non-nil means, the CLOSED time stamp will contain date and time.
1462 When nil, only the date will be recorded."
1463 :group 'org-progress
1464 :type 'boolean)
1466 (defcustom org-log-note-headings
1467 '((done . "CLOSING NOTE %t")
1468 (state . "State %-12s %t")
1469 (note . "Note taken on %t")
1470 (clock-out . ""))
1471 "Headings for notes added to entries.
1472 The value is an alist, with the car being a symbol indicating the note
1473 context, and the cdr is the heading to be used. The heading may also be the
1474 empty string.
1475 %t in the heading will be replaced by a time stamp.
1476 %s will be replaced by the new TODO state, in double quotes.
1477 %u will be replaced by the user name.
1478 %U will be replaced by the full user name."
1479 :group 'org-todo
1480 :group 'org-progress
1481 :type '(list :greedy t
1482 (cons (const :tag "Heading when closing an item" done) string)
1483 (cons (const :tag
1484 "Heading when changing todo state (todo sequence only)"
1485 state) string)
1486 (cons (const :tag "Heading when just taking a note" note) string)
1487 (cons (const :tag "Heading when clocking out" clock-out) string)))
1489 (unless (assq 'note org-log-note-headings)
1490 (push '(note . "%t") org-log-note-headings))
1492 (defcustom org-log-states-order-reversed t
1493 "Non-nil means, the latest state change note will be directly after heading.
1494 When nil, the notes will be orderer according to time."
1495 :group 'org-todo
1496 :group 'org-progress
1497 :type 'boolean)
1499 (defcustom org-log-repeat 'time
1500 "Non-nil means, record moving through the DONE state when triggering repeat.
1501 An auto-repeating tasks is immediately switched back to TODO when marked
1502 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1503 the TODO keyword definition, or recording a closing note by setting
1504 `org-log-done', there will be no record of the task moving through DONE.
1505 This variable forces taking a note anyway. Possible values are:
1507 nil Don't force a record
1508 time Record a time stamp
1509 note Record a note
1511 This option can also be set with on a per-file-basis with
1513 #+STARTUP: logrepeat
1514 #+STARTUP: lognoterepeat
1515 #+STARTUP: nologrepeat
1517 You can have local logging settings for a subtree by setting the LOGGING
1518 property to one or more of these keywords."
1519 :group 'org-todo
1520 :group 'org-progress
1521 :type '(choice
1522 (const :tag "Don't force a record" nil)
1523 (const :tag "Force recording the DONE state" time)
1524 (const :tag "Force recording a note with the DONE state" note)))
1527 (defgroup org-priorities nil
1528 "Priorities in Org-mode."
1529 :tag "Org Priorities"
1530 :group 'org-todo)
1532 (defcustom org-highest-priority ?A
1533 "The highest priority of TODO items. A character like ?A, ?B etc.
1534 Must have a smaller ASCII number than `org-lowest-priority'."
1535 :group 'org-priorities
1536 :type 'character)
1538 (defcustom org-lowest-priority ?C
1539 "The lowest priority of TODO items. A character like ?A, ?B etc.
1540 Must have a larger ASCII number than `org-highest-priority'."
1541 :group 'org-priorities
1542 :type 'character)
1544 (defcustom org-default-priority ?B
1545 "The default priority of TODO items.
1546 This is the priority an item get if no explicit priority is given."
1547 :group 'org-priorities
1548 :type 'character)
1550 (defcustom org-priority-start-cycle-with-default t
1551 "Non-nil means, start with default priority when starting to cycle.
1552 When this is nil, the first step in the cycle will be (depending on the
1553 command used) one higher or lower that the default priority."
1554 :group 'org-priorities
1555 :type 'boolean)
1557 (defgroup org-time nil
1558 "Options concerning time stamps and deadlines in Org-mode."
1559 :tag "Org Time"
1560 :group 'org)
1562 (defcustom org-insert-labeled-timestamps-at-point nil
1563 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1564 When nil, these labeled time stamps are forces into the second line of an
1565 entry, just after the headline. When scheduling from the global TODO list,
1566 the time stamp will always be forced into the second line."
1567 :group 'org-time
1568 :type 'boolean)
1570 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1571 "Formats for `format-time-string' which are used for time stamps.
1572 It is not recommended to change this constant.")
1574 (defcustom org-time-stamp-rounding-minutes '(0 5)
1575 "Number of minutes to round time stamps to.
1576 These are two values, the first applies when first creating a time stamp.
1577 The second applies when changing it with the commands `S-up' and `S-down'.
1578 When changing the time stamp, this means that it will change in steps
1579 of N minutes, as given by the second value.
1581 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1582 numbers should be factors of 60, so for example 5, 10, 15.
1584 When this is larger than 1, you can still force an exact time-stamp by using
1585 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1586 and by using a prefix arg to `S-up/down' to specify the exact number
1587 of minutes to shift."
1588 :group 'org-time
1589 :get '(lambda (var) ; Make sure all entries have 5 elements
1590 (if (integerp (default-value var))
1591 (list (default-value var) 5)
1592 (default-value var)))
1593 :type '(list
1594 (integer :tag "when inserting times")
1595 (integer :tag "when modifying times")))
1597 ;; Normalize old customizations of this variable.
1598 (when (integerp org-time-stamp-rounding-minutes)
1599 (setq org-time-stamp-rounding-minutes
1600 (list org-time-stamp-rounding-minutes
1601 org-time-stamp-rounding-minutes)))
1603 (defcustom org-display-custom-times nil
1604 "Non-nil means, overlay custom formats over all time stamps.
1605 The formats are defined through the variable `org-time-stamp-custom-formats'.
1606 To turn this on on a per-file basis, insert anywhere in the file:
1607 #+STARTUP: customtime"
1608 :group 'org-time
1609 :set 'set-default
1610 :type 'sexp)
1611 (make-variable-buffer-local 'org-display-custom-times)
1613 (defcustom org-time-stamp-custom-formats
1614 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1615 "Custom formats for time stamps. See `format-time-string' for the syntax.
1616 These are overlayed over the default ISO format if the variable
1617 `org-display-custom-times' is set. Time like %H:%M should be at the
1618 end of the second format."
1619 :group 'org-time
1620 :type 'sexp)
1622 (defun org-time-stamp-format (&optional long inactive)
1623 "Get the right format for a time string."
1624 (let ((f (if long (cdr org-time-stamp-formats)
1625 (car org-time-stamp-formats))))
1626 (if inactive
1627 (concat "[" (substring f 1 -1) "]")
1628 f)))
1630 (defcustom org-time-clocksum-format "%d:%02d"
1631 "The format string used when creating CLOCKSUM lines, or when
1632 org-mode generates a time duration."
1633 :group 'org-time
1634 :type 'string)
1636 (defcustom org-deadline-warning-days 14
1637 "No. of days before expiration during which a deadline becomes active.
1638 This variable governs the display in sparse trees and in the agenda.
1639 When 0 or negative, it means use this number (the absolute value of it)
1640 even if a deadline has a different individual lead time specified."
1641 :group 'org-time
1642 :group 'org-agenda-daily/weekly
1643 :type 'number)
1645 (defcustom org-read-date-prefer-future t
1646 "Non-nil means, assume future for incomplete date input from user.
1647 This affects the following situations:
1648 1. The user gives a day, but no month.
1649 For example, if today is the 15th, and you enter \"3\", Org-mode will
1650 read this as the third of *next* month. However, if you enter \"17\",
1651 it will be considered as *this* month.
1652 2. The user gives a month but not a year.
1653 For example, if it is april and you enter \"feb 2\", this will be read
1654 as feb 2, *next* year. \"May 5\", however, will be this year.
1656 Currently this does not work for ISO week specifications.
1658 When this option is nil, the current month and year will always be used
1659 as defaults."
1660 :group 'org-time
1661 :type 'boolean)
1663 (defcustom org-read-date-display-live t
1664 "Non-nil means, display current interpretation of date prompt live.
1665 This display will be in an overlay, in the minibuffer."
1666 :group 'org-time
1667 :type 'boolean)
1669 (defcustom org-read-date-popup-calendar t
1670 "Non-nil means, pop up a calendar when prompting for a date.
1671 In the calendar, the date can be selected with mouse-1. However, the
1672 minibuffer will also be active, and you can simply enter the date as well.
1673 When nil, only the minibuffer will be available."
1674 :group 'org-time
1675 :type 'boolean)
1676 (if (fboundp 'defvaralias)
1677 (defvaralias 'org-popup-calendar-for-date-prompt
1678 'org-read-date-popup-calendar))
1680 (defcustom org-extend-today-until 0
1681 "The hour when your day really ends.
1682 This has influence for the following applications:
1683 - When switching the agenda to \"today\". It it is still earlier than
1684 the time given here, the day recognized as TODAY is actually yesterday.
1685 - When a date is read from the user and it is still before the time given
1686 here, the current date and time will be assumed to be yesterday, 23:59.
1688 FIXME:
1689 IMPORTANT: This is still a very experimental feature, it may disappear
1690 again or it may be extended to mean more things."
1691 :group 'org-time
1692 :type 'number)
1694 (defcustom org-edit-timestamp-down-means-later nil
1695 "Non-nil means, S-down will increase the time in a time stamp.
1696 When nil, S-up will increase."
1697 :group 'org-time
1698 :type 'boolean)
1700 (defcustom org-calendar-follow-timestamp-change t
1701 "Non-nil means, make the calendar window follow timestamp changes.
1702 When a timestamp is modified and the calendar window is visible, it will be
1703 moved to the new date."
1704 :group 'org-time
1705 :type 'boolean)
1707 (defgroup org-tags nil
1708 "Options concerning tags in Org-mode."
1709 :tag "Org Tags"
1710 :group 'org)
1712 (defcustom org-tag-alist nil
1713 "List of tags allowed in Org-mode files.
1714 When this list is nil, Org-mode will base TAG input on what is already in the
1715 buffer.
1716 The value of this variable is an alist, the car of each entry must be a
1717 keyword as a string, the cdr may be a character that is used to select
1718 that tag through the fast-tag-selection interface.
1719 See the manual for details."
1720 :group 'org-tags
1721 :type '(repeat
1722 (choice
1723 (cons (string :tag "Tag name")
1724 (character :tag "Access char"))
1725 (const :tag "Start radio group" (:startgroup))
1726 (const :tag "End radio group" (:endgroup)))))
1728 (defvar org-file-tags nil
1729 "List of tags that can be inherited by all entries in the file.
1730 The tags will be inherited if the variable `org-use-tag-inheritance'
1731 says they should be.
1732 This variable is populated from #+TAG lines.")
1734 (defcustom org-use-fast-tag-selection 'auto
1735 "Non-nil means, use fast tag selection scheme.
1736 This is a special interface to select and deselect tags with single keys.
1737 When nil, fast selection is never used.
1738 When the symbol `auto', fast selection is used if and only if selection
1739 characters for tags have been configured, either through the variable
1740 `org-tag-alist' or through a #+TAGS line in the buffer.
1741 When t, fast selection is always used and selection keys are assigned
1742 automatically if necessary."
1743 :group 'org-tags
1744 :type '(choice
1745 (const :tag "Always" t)
1746 (const :tag "Never" nil)
1747 (const :tag "When selection characters are configured" 'auto)))
1749 (defcustom org-fast-tag-selection-single-key nil
1750 "Non-nil means, fast tag selection exits after first change.
1751 When nil, you have to press RET to exit it.
1752 During fast tag selection, you can toggle this flag with `C-c'.
1753 This variable can also have the value `expert'. In this case, the window
1754 displaying the tags menu is not even shown, until you press C-c again."
1755 :group 'org-tags
1756 :type '(choice
1757 (const :tag "No" nil)
1758 (const :tag "Yes" t)
1759 (const :tag "Expert" expert)))
1761 (defvar org-fast-tag-selection-include-todo nil
1762 "Non-nil means, fast tags selection interface will also offer TODO states.
1763 This is an undocumented feature, you should not rely on it.")
1765 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1766 "The column to which tags should be indented in a headline.
1767 If this number is positive, it specifies the column. If it is negative,
1768 it means that the tags should be flushright to that column. For example,
1769 -80 works well for a normal 80 character screen."
1770 :group 'org-tags
1771 :type 'integer)
1773 (defcustom org-auto-align-tags t
1774 "Non-nil means, realign tags after pro/demotion of TODO state change.
1775 These operations change the length of a headline and therefore shift
1776 the tags around. With this options turned on, after each such operation
1777 the tags are again aligned to `org-tags-column'."
1778 :group 'org-tags
1779 :type 'boolean)
1781 (defcustom org-use-tag-inheritance t
1782 "Non-nil means, tags in levels apply also for sublevels.
1783 When nil, only the tags directly given in a specific line apply there.
1784 If this option is t, a match early-on in a tree can lead to a large
1785 number of matches in the subtree. If you only want to see the first
1786 match in a tree during a search, check out the variable
1787 `org-tags-match-list-sublevels'.
1789 This may also be a list of tags that should be inherited, or a regexp that
1790 matches tags that should be inherited."
1791 :group 'org-tags
1792 :type '(choice
1793 (const :tag "Not" nil)
1794 (const :tag "Always" t)
1795 (repeat :tag "Specific tags" (string :tag "Tag"))
1796 (regexp :tag "Tags matched by regexp")))
1798 (defun org-tag-inherit-p (tag)
1799 "Check if TAG is one that should be inherited."
1800 (cond
1801 ((eq org-use-tag-inheritance t) t)
1802 ((not org-use-tag-inheritance) nil)
1803 ((stringp org-use-tag-inheritance)
1804 (string-match org-use-tag-inheritance tag))
1805 ((listp org-use-tag-inheritance)
1806 (member tag org-use-tag-inheritance))
1807 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1809 (defcustom org-tags-match-list-sublevels t
1810 "Non-nil means list also sublevels of headlines matching tag search.
1811 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1812 the sublevels of a headline matching a tag search often also match
1813 the same search. Listing all of them can create very long lists.
1814 Setting this variable to nil causes subtrees of a match to be skipped.
1815 This option is off by default, because inheritance in on. If you turn
1816 inheritance off, you very likely want to turn this option on.
1818 As a special case, if the tag search is restricted to TODO items, the
1819 value of this variable is ignored and sublevels are always checked, to
1820 make sure all corresponding TODO items find their way into the list."
1821 :group 'org-tags
1822 :type 'boolean)
1824 (defvar org-tags-history nil
1825 "History of minibuffer reads for tags.")
1826 (defvar org-last-tags-completion-table nil
1827 "The last used completion table for tags.")
1828 (defvar org-after-tags-change-hook nil
1829 "Hook that is run after the tags in a line have changed.")
1831 (defgroup org-properties nil
1832 "Options concerning properties in Org-mode."
1833 :tag "Org Properties"
1834 :group 'org)
1836 (defcustom org-property-format "%-10s %s"
1837 "How property key/value pairs should be formatted by `indent-line'.
1838 When `indent-line' hits a property definition, it will format the line
1839 according to this format, mainly to make sure that the values are
1840 lined-up with respect to each other."
1841 :group 'org-properties
1842 :type 'string)
1844 (defcustom org-use-property-inheritance nil
1845 "Non-nil means, properties apply also for sublevels.
1847 This setting is chiefly used during property searches. Turning it on can
1848 cause significant overhead when doing a search, which is why it is not
1849 on by default.
1851 When nil, only the properties directly given in the current entry count.
1852 When t, every property is inherited. The value may also be a list of
1853 properties that should have inheritance, or a regular expression matching
1854 properties that should be inherited.
1856 However, note that some special properties use inheritance under special
1857 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1858 and the properties ending in \"_ALL\" when they are used as descriptor
1859 for valid values of a property.
1861 Note for programmers:
1862 When querying an entry with `org-entry-get', you can control if inheritance
1863 should be used. By default, `org-entry-get' looks only at the local
1864 properties. You can request inheritance by setting the inherit argument
1865 to t (to force inheritance) or to `selective' (to respect the setting
1866 in this variable)."
1867 :group 'org-properties
1868 :type '(choice
1869 (const :tag "Not" nil)
1870 (const :tag "Always" t)
1871 (repeat :tag "Specific properties" (string :tag "Property"))
1872 (regexp :tag "Properties matched by regexp")))
1874 (defun org-property-inherit-p (property)
1875 "Check if PROPERTY is one that should be inherited."
1876 (cond
1877 ((eq org-use-property-inheritance t) t)
1878 ((not org-use-property-inheritance) nil)
1879 ((stringp org-use-property-inheritance)
1880 (string-match org-use-property-inheritance property))
1881 ((listp org-use-property-inheritance)
1882 (member property org-use-property-inheritance))
1883 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1885 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1886 "The default column format, if no other format has been defined.
1887 This variable can be set on the per-file basis by inserting a line
1889 #+COLUMNS: %25ITEM ....."
1890 :group 'org-properties
1891 :type 'string)
1893 (defcustom org-columns-ellipses ".."
1894 "The ellipses to be used when a field in column view is truncated.
1895 When this is the empty string, as many characters as possible are shown,
1896 but then there will be no visual indication that the field has been truncated.
1897 When this is a string of length N, the last N characters of a truncated
1898 field are replaced by this string. If the column is narrower than the
1899 ellipses string, only part of the ellipses string will be shown."
1900 :group 'org-properties
1901 :type 'string)
1904 (defcustom org-effort-property "Effort"
1905 "The property that is being used to keep track of effort estimates.
1906 Effort estimates given in this property need to have the format H:MM."
1907 :group 'org-properties
1908 :group 'org-progress
1909 :type '(string :tag "Property"))
1911 (defconst org-global-properties-fixed
1912 '(("VISIBILITY_ALL" . "folded children content all"))
1913 "List of property/value pairs that can be inherited by any entry.
1914 These are fixed values, for the preset properties.")
1917 (defcustom org-global-properties nil
1918 "List of property/value pairs that can be inherited by any entry.
1919 You can set buffer-local values for this by adding lines like
1921 #+PROPERTY: NAME VALUE"
1922 :group 'org-properties
1923 :type '(repeat
1924 (cons (string :tag "Property")
1925 (string :tag "Value"))))
1927 (defvar org-file-properties nil
1928 "List of property/value pairs that can be inherited by any entry.
1929 Valid for the current buffer.
1930 This variable is populated from #+PROPERTY lines.")
1931 (make-variable-buffer-local 'org-file-properties)
1933 (defgroup org-agenda nil
1934 "Options concerning agenda views in Org-mode."
1935 :tag "Org Agenda"
1936 :group 'org)
1938 (defvar org-category nil
1939 "Variable used by org files to set a category for agenda display.
1940 Such files should use a file variable to set it, for example
1942 # -*- mode: org; org-category: \"ELisp\"
1944 or contain a special line
1946 #+CATEGORY: ELisp
1948 If the file does not specify a category, then file's base name
1949 is used instead.")
1950 (make-variable-buffer-local 'org-category)
1952 (defcustom org-agenda-files nil
1953 "The files to be used for agenda display.
1954 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1955 \\[org-remove-file]. You can also use customize to edit the list.
1957 If an entry is a directory, all files in that directory that are matched by
1958 `org-agenda-file-regexp' will be part of the file list.
1960 If the value of the variable is not a list but a single file name, then
1961 the list of agenda files is actually stored and maintained in that file, one
1962 agenda file per line."
1963 :group 'org-agenda
1964 :type '(choice
1965 (repeat :tag "List of files and directories" file)
1966 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1968 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1969 "Regular expression to match files for `org-agenda-files'.
1970 If any element in the list in that variable contains a directory instead
1971 of a normal file, all files in that directory that are matched by this
1972 regular expression will be included."
1973 :group 'org-agenda
1974 :type 'regexp)
1976 (defcustom org-agenda-text-search-extra-files nil
1977 "List of extra files to be searched by text search commands.
1978 These files will be search in addition to the agenda files by the
1979 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1980 Note that these files will only be searched for text search commands,
1981 not for the other agenda views like todo lists, tag searches or the weekly
1982 agenda. This variable is intended to list notes and possibly archive files
1983 that should also be searched by these two commands.
1984 In fact, if the first element in the list is the symbol `agenda-archives',
1985 than all archive files of all agenda files will be added to the search
1986 scope."
1987 :group 'org-agenda
1988 :type '(set :greedy t
1989 (const :tag "Agenda Archives" agenda-archives)
1990 (repeat :inline t (file))))
1992 (if (fboundp 'defvaralias)
1993 (defvaralias 'org-agenda-multi-occur-extra-files
1994 'org-agenda-text-search-extra-files))
1996 (defcustom org-agenda-skip-unavailable-files nil
1997 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
1998 A nil value means to remove them, after a query, from the list."
1999 :group 'org-agenda
2000 :type 'boolean)
2002 (defcustom org-calendar-to-agenda-key [?c]
2003 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2004 The command `org-calendar-goto-agenda' will be bound to this key. The
2005 default is the character `c' because then `c' can be used to switch back and
2006 forth between agenda and calendar."
2007 :group 'org-agenda
2008 :type 'sexp)
2010 (defcustom org-calendar-agenda-action-key [?k]
2011 "The key to be installed in `calendar-mode-map' for agenda-action.
2012 The command `org-agenda-action' will be bound to this key. The
2013 default is the character `k' because we use the same key in the agenda."
2014 :group 'org-agenda
2015 :type 'sexp)
2017 (eval-after-load "calendar"
2018 '(progn
2019 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2020 'org-calendar-goto-agenda)
2021 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2022 'org-agenda-action)))
2024 (defgroup org-latex nil
2025 "Options for embedding LaTeX code into Org-mode."
2026 :tag "Org LaTeX"
2027 :group 'org)
2029 (defcustom org-format-latex-options
2030 '(:foreground default :background default :scale 1.0
2031 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2032 :matchers ("begin" "$" "$$" "\\(" "\\["))
2033 "Options for creating images from LaTeX fragments.
2034 This is a property list with the following properties:
2035 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2036 `default' means use the foreground of the default face.
2037 :background the background color, or \"Transparent\".
2038 `default' means use the background of the default face.
2039 :scale a scaling factor for the size of the images.
2040 :html-foreground, :html-background, :html-scale
2041 the same numbers for HTML export.
2042 :matchers a list indicating which matchers should be used to
2043 find LaTeX fragments. Valid members of this list are:
2044 \"begin\" find environments
2045 \"$\" find math expressions surrounded by $...$
2046 \"$$\" find math expressions surrounded by $$....$$
2047 \"\\(\" find math expressions surrounded by \\(...\\)
2048 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2049 :group 'org-latex
2050 :type 'plist)
2052 (defcustom org-format-latex-header "\\documentclass{article}
2053 \\usepackage{fullpage} % do not remove
2054 \\usepackage{amssymb}
2055 \\usepackage[usenames]{color}
2056 \\usepackage{amsmath}
2057 \\usepackage{latexsym}
2058 \\usepackage[mathscr]{eucal}
2059 \\pagestyle{empty} % do not remove"
2060 "The document header used for processing LaTeX fragments."
2061 :group 'org-latex
2062 :type 'string)
2065 (defgroup org-font-lock nil
2066 "Font-lock settings for highlighting in Org-mode."
2067 :tag "Org Font Lock"
2068 :group 'org)
2070 (defcustom org-level-color-stars-only nil
2071 "Non-nil means fontify only the stars in each headline.
2072 When nil, the entire headline is fontified.
2073 Changing it requires restart of `font-lock-mode' to become effective
2074 also in regions already fontified."
2075 :group 'org-font-lock
2076 :type 'boolean)
2078 (defcustom org-hide-leading-stars nil
2079 "Non-nil means, hide the first N-1 stars in a headline.
2080 This works by using the face `org-hide' for these stars. This
2081 face is white for a light background, and black for a dark
2082 background. You may have to customize the face `org-hide' to
2083 make this work.
2084 Changing it requires restart of `font-lock-mode' to become effective
2085 also in regions already fontified.
2086 You may also set this on a per-file basis by adding one of the following
2087 lines to the buffer:
2089 #+STARTUP: hidestars
2090 #+STARTUP: showstars"
2091 :group 'org-font-lock
2092 :type 'boolean)
2094 (defcustom org-fontify-done-headline nil
2095 "Non-nil means, change the face of a headline if it is marked DONE.
2096 Normally, only the TODO/DONE keyword indicates the state of a headline.
2097 When this is non-nil, the headline after the keyword is set to the
2098 `org-headline-done' as an additional indication."
2099 :group 'org-font-lock
2100 :type 'boolean)
2102 (defcustom org-fontify-emphasized-text t
2103 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2104 Changing this variable requires a restart of Emacs to take effect."
2105 :group 'org-font-lock
2106 :type 'boolean)
2108 (defcustom org-highlight-latex-fragments-and-specials nil
2109 "Non-nil means, fontify what is treated specially by the exporters."
2110 :group 'org-font-lock
2111 :type 'boolean)
2113 (defcustom org-hide-emphasis-markers nil
2114 "Non-nil mean font-lock should hide the emphasis marker characters."
2115 :group 'org-font-lock
2116 :type 'boolean)
2118 (defvar org-emph-re nil
2119 "Regular expression for matching emphasis.")
2120 (defvar org-verbatim-re nil
2121 "Regular expression for matching verbatim text.")
2122 (defvar org-emphasis-regexp-components) ; defined just below
2123 (defvar org-emphasis-alist) ; defined just below
2124 (defun org-set-emph-re (var val)
2125 "Set variable and compute the emphasis regular expression."
2126 (set var val)
2127 (when (and (boundp 'org-emphasis-alist)
2128 (boundp 'org-emphasis-regexp-components)
2129 org-emphasis-alist org-emphasis-regexp-components)
2130 (let* ((e org-emphasis-regexp-components)
2131 (pre (car e))
2132 (post (nth 1 e))
2133 (border (nth 2 e))
2134 (body (nth 3 e))
2135 (nl (nth 4 e))
2136 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2137 (body1 (concat body "*?"))
2138 (markers (mapconcat 'car org-emphasis-alist ""))
2139 (vmarkers (mapconcat
2140 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2141 org-emphasis-alist "")))
2142 ;; make sure special characters appear at the right position in the class
2143 (if (string-match "\\^" markers)
2144 (setq markers (concat (replace-match "" t t markers) "^")))
2145 (if (string-match "-" markers)
2146 (setq markers (concat (replace-match "" t t markers) "-")))
2147 (if (string-match "\\^" vmarkers)
2148 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2149 (if (string-match "-" vmarkers)
2150 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2151 (if (> nl 0)
2152 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2153 (int-to-string nl) "\\}")))
2154 ;; Make the regexp
2155 (setq org-emph-re
2156 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2157 "\\("
2158 "\\([" markers "]\\)"
2159 "\\("
2160 "[^" border "]\\|"
2161 "[^" border (if (and nil stacked) markers) "]"
2162 body1
2163 "[^" border (if (and nil stacked) markers) "]"
2164 "\\)"
2165 "\\3\\)"
2166 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2167 (setq org-verbatim-re
2168 (concat "\\([" pre "]\\|^\\)"
2169 "\\("
2170 "\\([" vmarkers "]\\)"
2171 "\\("
2172 "[^" border "]\\|"
2173 "[^" border "]"
2174 body1
2175 "[^" border "]"
2176 "\\)"
2177 "\\3\\)"
2178 "\\([" post "]\\|$\\)")))))
2180 (defcustom org-emphasis-regexp-components
2181 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2182 "Components used to build the regular expression for emphasis.
2183 This is a list with 6 entries. Terminology: In an emphasis string
2184 like \" *strong word* \", we call the initial space PREMATCH, the final
2185 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2186 and \"trong wor\" is the body. The different components in this variable
2187 specify what is allowed/forbidden in each part:
2189 pre Chars allowed as prematch. Beginning of line will be allowed too.
2190 post Chars allowed as postmatch. End of line will be allowed too.
2191 border The chars *forbidden* as border characters.
2192 body-regexp A regexp like \".\" to match a body character. Don't use
2193 non-shy groups here, and don't allow newline here.
2194 newline The maximum number of newlines allowed in an emphasis exp.
2196 Use customize to modify this, or restart Emacs after changing it."
2197 :group 'org-font-lock
2198 :set 'org-set-emph-re
2199 :type '(list
2200 (sexp :tag "Allowed chars in pre ")
2201 (sexp :tag "Allowed chars in post ")
2202 (sexp :tag "Forbidden chars in border ")
2203 (sexp :tag "Regexp for body ")
2204 (integer :tag "number of newlines allowed")
2205 (option (boolean :tag "Please ignore this button"))))
2207 (defcustom org-emphasis-alist
2208 `(("*" bold "<b>" "</b>")
2209 ("/" italic "<i>" "</i>")
2210 ("_" underline "<u>" "</u>")
2211 ("=" org-code "<code>" "</code>" verbatim)
2212 ("~" org-verbatim "" "" verbatim)
2213 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2214 "<del>" "</del>")
2216 "Special syntax for emphasized text.
2217 Text starting and ending with a special character will be emphasized, for
2218 example *bold*, _underlined_ and /italic/. This variable sets the marker
2219 characters, the face to be used by font-lock for highlighting in Org-mode
2220 Emacs buffers, and the HTML tags to be used for this.
2221 Use customize to modify this, or restart Emacs after changing it."
2222 :group 'org-font-lock
2223 :set 'org-set-emph-re
2224 :type '(repeat
2225 (list
2226 (string :tag "Marker character")
2227 (choice
2228 (face :tag "Font-lock-face")
2229 (plist :tag "Face property list"))
2230 (string :tag "HTML start tag")
2231 (string :tag "HTML end tag")
2232 (option (const verbatim)))))
2234 ;;; Miscellaneous options
2236 (defgroup org-completion nil
2237 "Completion in Org-mode."
2238 :tag "Org Completion"
2239 :group 'org)
2241 (defcustom org-completion-fallback-command 'hippie-expand
2242 "The expansion command called by \\[org-complete] in normal context.
2243 Normal means, no org-mode-specific context."
2244 :group 'org-completion
2245 :type 'function)
2247 ;;; Functions and variables from ther packages
2248 ;; Declared here to avoid compiler warnings
2250 ;; XEmacs only
2251 (defvar outline-mode-menu-heading)
2252 (defvar outline-mode-menu-show)
2253 (defvar outline-mode-menu-hide)
2254 (defvar zmacs-regions) ; XEmacs regions
2256 ;; Emacs only
2257 (defvar mark-active)
2259 ;; Various packages
2260 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2261 (declare-function calendar-forward-day "cal-move" (arg))
2262 (declare-function calendar-goto-date "cal-move" (date))
2263 (declare-function calendar-goto-today "cal-move" ())
2264 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2265 (defvar calc-embedded-close-formula)
2266 (defvar calc-embedded-open-formula)
2267 (declare-function cdlatex-tab "ext:cdlatex" ())
2268 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2269 (defvar font-lock-unfontify-region-function)
2270 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2271 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2272 (defvar iswitchb-temp-buflist)
2273 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2274 (declare-function org-agenda-skip "org-agenda" ())
2275 (declare-function org-format-agenda-item "org-agenda"
2276 (extra txt &optional category tags dotime noprefix remove-re))
2277 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2278 (declare-function org-agenda-change-all-lines "org-agenda"
2279 (newhead hdmarker &optional fixface))
2280 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2281 (declare-function org-agenda-maybe-redo "org-agenda" ())
2282 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2283 (beg end))
2284 (declare-function parse-time-string "parse-time" (string))
2285 (declare-function remember "remember" (&optional initial))
2286 (declare-function remember-buffer-desc "remember" ())
2287 (declare-function remember-finalize "remember" ())
2288 (defvar remember-save-after-remembering)
2289 (defvar remember-data-file)
2290 (defvar remember-register)
2291 (defvar remember-buffer)
2292 (defvar remember-handler-functions)
2293 (defvar remember-annotation-functions)
2294 (defvar texmathp-why)
2295 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2296 (declare-function table--at-cell-p "table" (position &optional object at-column))
2298 (defvar w3m-current-url)
2299 (defvar w3m-current-title)
2301 (defvar org-latex-regexps)
2303 ;;; Autoload and prepare some org modules
2305 ;; Some table stuff that needs to be defined here, because it is used
2306 ;; by the functions setting up org-mode or checking for table context.
2308 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2309 "Detects an org-type or table-type table.")
2310 (defconst org-table-line-regexp "^[ \t]*|"
2311 "Detects an org-type table line.")
2312 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2313 "Detects an org-type table line.")
2314 (defconst org-table-hline-regexp "^[ \t]*|-"
2315 "Detects an org-type table hline.")
2316 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2317 "Detects a table-type table hline.")
2318 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2319 "Searching from within a table (any type) this finds the first line
2320 outside the table.")
2322 ;; Autoload the functions in org-table.el that are needed by functions here.
2324 (eval-and-compile
2325 (org-autoload "org-table"
2326 '(org-table-align org-table-begin org-table-blank-field
2327 org-table-convert org-table-convert-region org-table-copy-down
2328 org-table-copy-region org-table-create
2329 org-table-create-or-convert-from-region
2330 org-table-create-with-table.el org-table-current-dline
2331 org-table-cut-region org-table-delete-column org-table-edit-field
2332 org-table-edit-formulas org-table-end org-table-eval-formula
2333 org-table-export org-table-field-info
2334 org-table-get-stored-formulas org-table-goto-column
2335 org-table-hline-and-move org-table-import org-table-insert-column
2336 org-table-insert-hline org-table-insert-row org-table-iterate
2337 org-table-justify-field-maybe org-table-kill-row
2338 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2339 org-table-move-column org-table-move-column-left
2340 org-table-move-column-right org-table-move-row
2341 org-table-move-row-down org-table-move-row-up
2342 org-table-next-field org-table-next-row org-table-paste-rectangle
2343 org-table-previous-field org-table-recalculate
2344 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2345 org-table-toggle-coordinate-overlays
2346 org-table-toggle-formula-debugger org-table-wrap-region
2347 orgtbl-mode turn-on-orgtbl)))
2349 (defun org-at-table-p (&optional table-type)
2350 "Return t if the cursor is inside an org-type table.
2351 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2352 (if org-enable-table-editor
2353 (save-excursion
2354 (beginning-of-line 1)
2355 (looking-at (if table-type org-table-any-line-regexp
2356 org-table-line-regexp)))
2357 nil))
2358 (defsubst org-table-p () (org-at-table-p))
2360 (defun org-at-table.el-p ()
2361 "Return t if and only if we are at a table.el table."
2362 (and (org-at-table-p 'any)
2363 (save-excursion
2364 (goto-char (org-table-begin 'any))
2365 (looking-at org-table1-hline-regexp))))
2366 (defun org-table-recognize-table.el ()
2367 "If there is a table.el table nearby, recognize it and move into it."
2368 (if org-table-tab-recognizes-table.el
2369 (if (org-at-table.el-p)
2370 (progn
2371 (beginning-of-line 1)
2372 (if (looking-at org-table-dataline-regexp)
2374 (if (looking-at org-table1-hline-regexp)
2375 (progn
2376 (beginning-of-line 2)
2377 (if (looking-at org-table-any-border-regexp)
2378 (beginning-of-line -1)))))
2379 (if (re-search-forward "|" (org-table-end t) t)
2380 (progn
2381 (require 'table)
2382 (if (table--at-cell-p (point))
2384 (message "recognizing table.el table...")
2385 (table-recognize-table)
2386 (message "recognizing table.el table...done")))
2387 (error "This should not happen..."))
2389 nil)
2390 nil))
2392 (defun org-at-table-hline-p ()
2393 "Return t if the cursor is inside a hline in a table."
2394 (if org-enable-table-editor
2395 (save-excursion
2396 (beginning-of-line 1)
2397 (looking-at org-table-hline-regexp))
2398 nil))
2400 (defvar org-table-clean-did-remove-column nil)
2402 (defun org-table-map-tables (function)
2403 "Apply FUNCTION to the start of all tables in the buffer."
2404 (save-excursion
2405 (save-restriction
2406 (widen)
2407 (goto-char (point-min))
2408 (while (re-search-forward org-table-any-line-regexp nil t)
2409 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2410 (beginning-of-line 1)
2411 (if (looking-at org-table-line-regexp)
2412 (save-excursion (funcall function)))
2413 (re-search-forward org-table-any-border-regexp nil 1))))
2414 (message "Mapping tables: done"))
2416 ;; Declare and autoload functions from org-exp.el
2418 (declare-function org-default-export-plist "org-exp")
2419 (declare-function org-infile-export-plist "org-exp")
2420 (declare-function org-get-current-options "org-exp")
2421 (eval-and-compile
2422 (org-autoload "org-exp"
2423 '(org-export org-export-as-ascii org-export-visible
2424 org-insert-export-options-template org-export-as-html-and-open
2425 org-export-as-html-batch org-export-as-html-to-buffer
2426 org-replace-region-by-html org-export-region-as-html
2427 org-export-as-html org-export-icalendar-this-file
2428 org-export-icalendar-all-agenda-files
2429 org-table-clean-before-export
2430 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2432 ;; Declare and autoload functions from org-exp.el
2434 (eval-and-compile
2435 (org-autoload "org-exp"
2436 '(org-agenda org-agenda-list org-search-view
2437 org-todo-list org-tags-view org-agenda-list-stuck-projects
2438 org-diary org-agenda-to-appt)))
2440 ;; Autoload org-remember
2442 (eval-and-compile
2443 (org-autoload "org-remember"
2444 '(org-remember-insinuate org-remember-annotation
2445 org-remember-apply-template org-remember org-remember-handler)))
2447 ;; Autoload org-clock.el
2450 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2451 (beg end))
2452 (declare-function org-update-mode-line "org-clock" ())
2453 (defvar org-clock-start-time)
2454 (defvar org-clock-marker (make-marker)
2455 "Marker recording the last clock-in.")
2457 (eval-and-compile
2458 (org-autoload
2459 "org-clock"
2460 '(org-clock-in org-clock-out org-clock-cancel
2461 org-clock-goto org-clock-sum org-clock-display
2462 org-remove-clock-overlays org-clock-report
2463 org-clocktable-shift org-dblock-write:clocktable
2464 org-get-clocktable)))
2466 (defun org-clock-update-time-maybe ()
2467 "If this is a CLOCK line, update it and return t.
2468 Otherwise, return nil."
2469 (interactive)
2470 (save-excursion
2471 (beginning-of-line 1)
2472 (skip-chars-forward " \t")
2473 (when (looking-at org-clock-string)
2474 (let ((re (concat "[ \t]*" org-clock-string
2475 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2476 "\\([ \t]*=>.*\\)?\\)?"))
2477 ts te h m s)
2478 (cond
2479 ((not (looking-at re))
2480 nil)
2481 ((not (match-end 2))
2482 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2483 (> org-clock-marker (point))
2484 (<= org-clock-marker (point-at-eol)))
2485 ;; The clock is running here
2486 (setq org-clock-start-time
2487 (apply 'encode-time
2488 (org-parse-time-string (match-string 1))))
2489 (org-update-mode-line)))
2491 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2492 (end-of-line 1)
2493 (setq ts (match-string 1)
2494 te (match-string 3))
2495 (setq s (- (time-to-seconds
2496 (apply 'encode-time (org-parse-time-string te)))
2497 (time-to-seconds
2498 (apply 'encode-time (org-parse-time-string ts))))
2499 h (floor (/ s 3600))
2500 s (- s (* 3600 h))
2501 m (floor (/ s 60))
2502 s (- s (* 60 s)))
2503 (insert " => " (format "%2d:%02d" h m))
2504 t))))))
2506 (defun org-check-running-clock ()
2507 "Check if the current buffer contains the running clock.
2508 If yes, offer to stop it and to save the buffer with the changes."
2509 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2510 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2511 (buffer-name))))
2512 (org-clock-out)
2513 (when (y-or-n-p "Save changed buffer?")
2514 (save-buffer))))
2516 (defun org-clocktable-try-shift (dir n)
2517 "Check if this line starts a clock table, if yes, shift the time block."
2518 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2519 (org-clocktable-shift dir n)))
2521 ;; Autoload archiving code
2522 ;; The stuff that is needed for cycling and tags has to be defined here.
2524 (defgroup org-archive nil
2525 "Options concerning archiving in Org-mode."
2526 :tag "Org Archive"
2527 :group 'org-structure)
2529 (defcustom org-archive-location "%s_archive::"
2530 "The location where subtrees should be archived.
2532 Otherwise, the value of this variable is a string, consisting of two
2533 parts, separated by a double-colon.
2535 The first part is a file name - when omitted, archiving happens in the same
2536 file. %s will be replaced by the current file name (without directory part).
2537 Archiving to a different file is useful to keep archived entries from
2538 contributing to the Org-mode Agenda.
2540 The part after the double colon is a headline. The archived entries will be
2541 filed under that headline. When omitted, the subtrees are simply filed away
2542 at the end of the file, as top-level entries.
2544 Here are a few examples:
2545 \"%s_archive::\"
2546 If the current file is Projects.org, archive in file
2547 Projects.org_archive, as top-level trees. This is the default.
2549 \"::* Archived Tasks\"
2550 Archive in the current file, under the top-level headline
2551 \"* Archived Tasks\".
2553 \"~/org/archive.org::\"
2554 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2556 \"basement::** Finished Tasks\"
2557 Archive in file ./basement (relative path), as level 3 trees
2558 below the level 2 heading \"** Finished Tasks\".
2560 You may set this option on a per-file basis by adding to the buffer a
2561 line like
2563 #+ARCHIVE: basement::** Finished Tasks
2565 You may also define it locally for a subtree by setting an ARCHIVE property
2566 in the entry. If such a property is found in an entry, or anywhere up
2567 the hierarchy, it will be used."
2568 :group 'org-archive
2569 :type 'string)
2571 (defcustom org-archive-tag "ARCHIVE"
2572 "The tag that marks a subtree as archived.
2573 An archived subtree does not open during visibility cycling, and does
2574 not contribute to the agenda listings.
2575 After changing this, font-lock must be restarted in the relevant buffers to
2576 get the proper fontification."
2577 :group 'org-archive
2578 :group 'org-keywords
2579 :type 'string)
2581 (defcustom org-agenda-skip-archived-trees t
2582 "Non-nil means, the agenda will skip any items located in archived trees.
2583 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2584 variable is no longer recommended, you should leave it at the value t.
2585 Instead, use the key `v' to cycle the archives-mode in the agenda."
2586 :group 'org-archive
2587 :group 'org-agenda-skip
2588 :type 'boolean)
2590 (defcustom org-cycle-open-archived-trees nil
2591 "Non-nil means, `org-cycle' will open archived trees.
2592 An archived tree is a tree marked with the tag ARCHIVE.
2593 When nil, archived trees will stay folded. You can still open them with
2594 normal outline commands like `show-all', but not with the cycling commands."
2595 :group 'org-archive
2596 :group 'org-cycle
2597 :type 'boolean)
2599 (defcustom org-sparse-tree-open-archived-trees nil
2600 "Non-nil means sparse tree construction shows matches in archived trees.
2601 When nil, matches in these trees are highlighted, but the trees are kept in
2602 collapsed state."
2603 :group 'org-archive
2604 :group 'org-sparse-trees
2605 :type 'boolean)
2607 (defun org-cycle-hide-archived-subtrees (state)
2608 "Re-hide all archived subtrees after a visibility state change."
2609 (when (and (not org-cycle-open-archived-trees)
2610 (not (memq state '(overview folded))))
2611 (save-excursion
2612 (let* ((globalp (memq state '(contents all)))
2613 (beg (if globalp (point-min) (point)))
2614 (end (if globalp (point-max) (org-end-of-subtree t))))
2615 (org-hide-archived-subtrees beg end)
2616 (goto-char beg)
2617 (if (looking-at (concat ".*:" org-archive-tag ":"))
2618 (message "%s" (substitute-command-keys
2619 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2621 (defun org-force-cycle-archived ()
2622 "Cycle subtree even if it is archived."
2623 (interactive)
2624 (setq this-command 'org-cycle)
2625 (let ((org-cycle-open-archived-trees t))
2626 (call-interactively 'org-cycle)))
2628 (defun org-hide-archived-subtrees (beg end)
2629 "Re-hide all archived subtrees after a visibility state change."
2630 (save-excursion
2631 (let* ((re (concat ":" org-archive-tag ":")))
2632 (goto-char beg)
2633 (while (re-search-forward re end t)
2634 (and (org-on-heading-p) (hide-subtree))
2635 (org-end-of-subtree t)))))
2637 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2639 (eval-and-compile
2640 (org-autoload "org-archive"
2641 '(org-add-archive-files org-archive-subtree
2642 org-archive-to-archive-sibling org-toggle-archive-tag)))
2644 ;; Autoload Column View Code
2646 (declare-function org-columns-number-to-string "org-colview")
2647 (declare-function org-columns-get-format-and-top-level "org-colview")
2648 (declare-function org-columns-compute "org-colview")
2650 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2651 '(org-columns-number-to-string org-columns-get-format-and-top-level
2652 org-columns-compute org-agenda-columns org-columns-remove-overlays
2653 org-columns org-insert-columns-dblock))
2655 ;; Autoload ID code
2657 (org-autoload "org-id"
2658 '(org-id-get-create org-id-new org-id-copy org-id-get
2659 org-id-get-with-outline-path-completion
2660 org-id-get-with-outline-drilling
2661 org-id-goto org-id-find))
2663 ;;; Variables for pre-computed regular expressions, all buffer local
2665 (defvar org-drawer-regexp nil
2666 "Matches first line of a hidden block.")
2667 (make-variable-buffer-local 'org-drawer-regexp)
2668 (defvar org-todo-regexp nil
2669 "Matches any of the TODO state keywords.")
2670 (make-variable-buffer-local 'org-todo-regexp)
2671 (defvar org-not-done-regexp nil
2672 "Matches any of the TODO state keywords except the last one.")
2673 (make-variable-buffer-local 'org-not-done-regexp)
2674 (defvar org-todo-line-regexp nil
2675 "Matches a headline and puts TODO state into group 2 if present.")
2676 (make-variable-buffer-local 'org-todo-line-regexp)
2677 (defvar org-complex-heading-regexp nil
2678 "Matches a headline and puts everything into groups:
2679 group 1: the stars
2680 group 2: The todo keyword, maybe
2681 group 3: Priority cookie
2682 group 4: True headline
2683 group 5: Tags")
2684 (make-variable-buffer-local 'org-complex-heading-regexp)
2685 (defvar org-todo-line-tags-regexp nil
2686 "Matches a headline and puts TODO state into group 2 if present.
2687 Also put tags into group 4 if tags are present.")
2688 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2689 (defvar org-nl-done-regexp nil
2690 "Matches newline followed by a headline with the DONE keyword.")
2691 (make-variable-buffer-local 'org-nl-done-regexp)
2692 (defvar org-looking-at-done-regexp nil
2693 "Matches the DONE keyword a point.")
2694 (make-variable-buffer-local 'org-looking-at-done-regexp)
2695 (defvar org-ds-keyword-length 12
2696 "Maximum length of the Deadline and SCHEDULED keywords.")
2697 (make-variable-buffer-local 'org-ds-keyword-length)
2698 (defvar org-deadline-regexp nil
2699 "Matches the DEADLINE keyword.")
2700 (make-variable-buffer-local 'org-deadline-regexp)
2701 (defvar org-deadline-time-regexp nil
2702 "Matches the DEADLINE keyword together with a time stamp.")
2703 (make-variable-buffer-local 'org-deadline-time-regexp)
2704 (defvar org-deadline-line-regexp nil
2705 "Matches the DEADLINE keyword and the rest of the line.")
2706 (make-variable-buffer-local 'org-deadline-line-regexp)
2707 (defvar org-scheduled-regexp nil
2708 "Matches the SCHEDULED keyword.")
2709 (make-variable-buffer-local 'org-scheduled-regexp)
2710 (defvar org-scheduled-time-regexp nil
2711 "Matches the SCHEDULED keyword together with a time stamp.")
2712 (make-variable-buffer-local 'org-scheduled-time-regexp)
2713 (defvar org-closed-time-regexp nil
2714 "Matches the CLOSED keyword together with a time stamp.")
2715 (make-variable-buffer-local 'org-closed-time-regexp)
2717 (defvar org-keyword-time-regexp nil
2718 "Matches any of the 4 keywords, together with the time stamp.")
2719 (make-variable-buffer-local 'org-keyword-time-regexp)
2720 (defvar org-keyword-time-not-clock-regexp nil
2721 "Matches any of the 3 keywords, together with the time stamp.")
2722 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2723 (defvar org-maybe-keyword-time-regexp nil
2724 "Matches a timestamp, possibly preceeded by a keyword.")
2725 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2726 (defvar org-planning-or-clock-line-re nil
2727 "Matches a line with planning or clock info.")
2728 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2730 (defconst org-plain-time-of-day-regexp
2731 (concat
2732 "\\(\\<[012]?[0-9]"
2733 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2734 "\\(--?"
2735 "\\(\\<[012]?[0-9]"
2736 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2737 "\\)?")
2738 "Regular expression to match a plain time or time range.
2739 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2740 groups carry important information:
2741 0 the full match
2742 1 the first time, range or not
2743 8 the second time, if it is a range.")
2745 (defconst org-plain-time-extension-regexp
2746 (concat
2747 "\\(\\<[012]?[0-9]"
2748 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2749 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2750 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2751 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2752 groups carry important information:
2753 0 the full match
2754 7 hours of duration
2755 9 minutes of duration")
2757 (defconst org-stamp-time-of-day-regexp
2758 (concat
2759 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2760 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2761 "\\(--?"
2762 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2763 "Regular expression to match a timestamp time or time range.
2764 After a match, the following groups carry important information:
2765 0 the full match
2766 1 date plus weekday, for backreferencing to make sure both times on same day
2767 2 the first time, range or not
2768 4 the second time, if it is a range.")
2770 (defconst org-startup-options
2771 '(("fold" org-startup-folded t)
2772 ("overview" org-startup-folded t)
2773 ("nofold" org-startup-folded nil)
2774 ("showall" org-startup-folded nil)
2775 ("content" org-startup-folded content)
2776 ("hidestars" org-hide-leading-stars t)
2777 ("showstars" org-hide-leading-stars nil)
2778 ("odd" org-odd-levels-only t)
2779 ("oddeven" org-odd-levels-only nil)
2780 ("align" org-startup-align-all-tables t)
2781 ("noalign" org-startup-align-all-tables nil)
2782 ("customtime" org-display-custom-times t)
2783 ("logdone" org-log-done time)
2784 ("lognotedone" org-log-done note)
2785 ("nologdone" org-log-done nil)
2786 ("lognoteclock-out" org-log-note-clock-out t)
2787 ("nolognoteclock-out" org-log-note-clock-out nil)
2788 ("logrepeat" org-log-repeat state)
2789 ("lognoterepeat" org-log-repeat note)
2790 ("nologrepeat" org-log-repeat nil)
2791 ("constcgs" constants-unit-system cgs)
2792 ("constSI" constants-unit-system SI))
2793 "Variable associated with STARTUP options for org-mode.
2794 Each element is a list of three items: The startup options as written
2795 in the #+STARTUP line, the corresponding variable, and the value to
2796 set this variable to if the option is found. An optional forth element PUSH
2797 means to push this value onto the list in the variable.")
2799 (defun org-set-regexps-and-options ()
2800 "Precompute regular expressions for current buffer."
2801 (when (org-mode-p)
2802 (org-set-local 'org-todo-kwd-alist nil)
2803 (org-set-local 'org-todo-key-alist nil)
2804 (org-set-local 'org-todo-key-trigger nil)
2805 (org-set-local 'org-todo-keywords-1 nil)
2806 (org-set-local 'org-done-keywords nil)
2807 (org-set-local 'org-todo-heads nil)
2808 (org-set-local 'org-todo-sets nil)
2809 (org-set-local 'org-todo-log-states nil)
2810 (org-set-local 'org-file-properties nil)
2811 (org-set-local 'org-file-tags nil)
2812 (let ((re (org-make-options-regexp
2813 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2814 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2815 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2816 (splitre "[ \t]+")
2817 kwds kws0 kwsa key log value cat arch tags const links hw dws
2818 tail sep kws1 prio props ftags drawers
2819 ext-setup-or-nil setup-contents (start 0))
2820 (save-excursion
2821 (save-restriction
2822 (widen)
2823 (goto-char (point-min))
2824 (while (or (and ext-setup-or-nil
2825 (string-match re ext-setup-or-nil start)
2826 (setq start (match-end 0)))
2827 (and (setq ext-setup-or-nil nil start 0)
2828 (re-search-forward re nil t)))
2829 (setq key (upcase (match-string 1 ext-setup-or-nil))
2830 value (org-match-string-no-properties 2 ext-setup-or-nil))
2831 (cond
2832 ((equal key "CATEGORY")
2833 (if (string-match "[ \t]+$" value)
2834 (setq value (replace-match "" t t value)))
2835 (setq cat value))
2836 ((member key '("SEQ_TODO" "TODO"))
2837 (push (cons 'sequence (org-split-string value splitre)) kwds))
2838 ((equal key "TYP_TODO")
2839 (push (cons 'type (org-split-string value splitre)) kwds))
2840 ((equal key "TAGS")
2841 (setq tags (append tags (org-split-string value splitre))))
2842 ((equal key "COLUMNS")
2843 (org-set-local 'org-columns-default-format value))
2844 ((equal key "LINK")
2845 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2846 (push (cons (match-string 1 value)
2847 (org-trim (match-string 2 value)))
2848 links)))
2849 ((equal key "PRIORITIES")
2850 (setq prio (org-split-string value " +")))
2851 ((equal key "PROPERTY")
2852 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2853 (push (cons (match-string 1 value) (match-string 2 value))
2854 props)))
2855 ((equal key "FILETAGS")
2856 (when (string-match "\\S-" value)
2857 (setq ftags
2858 (append
2859 ftags
2860 (apply 'append
2861 (mapcar (lambda (x) (org-split-string x ":"))
2862 (org-split-string value)))))))
2863 ((equal key "DRAWERS")
2864 (setq drawers (org-split-string value splitre)))
2865 ((equal key "CONSTANTS")
2866 (setq const (append const (org-split-string value splitre))))
2867 ((equal key "STARTUP")
2868 (let ((opts (org-split-string value splitre))
2869 l var val)
2870 (while (setq l (pop opts))
2871 (when (setq l (assoc l org-startup-options))
2872 (setq var (nth 1 l) val (nth 2 l))
2873 (if (not (nth 3 l))
2874 (set (make-local-variable var) val)
2875 (if (not (listp (symbol-value var)))
2876 (set (make-local-variable var) nil))
2877 (set (make-local-variable var) (symbol-value var))
2878 (add-to-list var val))))))
2879 ((equal key "ARCHIVE")
2880 (string-match " *$" value)
2881 (setq arch (replace-match "" t t value))
2882 (remove-text-properties 0 (length arch)
2883 '(face t fontified t) arch))
2884 ((equal key "SETUPFILE")
2885 (setq setup-contents (org-file-contents
2886 (expand-file-name
2887 (org-remove-double-quotes value))
2888 'noerror))
2889 (if (not ext-setup-or-nil)
2890 (setq ext-setup-or-nil setup-contents start 0)
2891 (setq ext-setup-or-nil
2892 (concat (substring ext-setup-or-nil 0 start)
2893 "\n" setup-contents "\n"
2894 (substring ext-setup-or-nil start)))))
2895 ))))
2896 (when cat
2897 (org-set-local 'org-category (intern cat))
2898 (push (cons "CATEGORY" cat) props))
2899 (when prio
2900 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2901 (setq prio (mapcar 'string-to-char prio))
2902 (org-set-local 'org-highest-priority (nth 0 prio))
2903 (org-set-local 'org-lowest-priority (nth 1 prio))
2904 (org-set-local 'org-default-priority (nth 2 prio)))
2905 (and props (org-set-local 'org-file-properties (nreverse props)))
2906 (and ftags (org-set-local 'org-file-tags ftags))
2907 (and drawers (org-set-local 'org-drawers drawers))
2908 (and arch (org-set-local 'org-archive-location arch))
2909 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2910 ;; Process the TODO keywords
2911 (unless kwds
2912 ;; Use the global values as if they had been given locally.
2913 (setq kwds (default-value 'org-todo-keywords))
2914 (if (stringp (car kwds))
2915 (setq kwds (list (cons org-todo-interpretation
2916 (default-value 'org-todo-keywords)))))
2917 (setq kwds (reverse kwds)))
2918 (setq kwds (nreverse kwds))
2919 (let (inter kws kw)
2920 (while (setq kws (pop kwds))
2921 (setq inter (pop kws) sep (member "|" kws)
2922 kws0 (delete "|" (copy-sequence kws))
2923 kwsa nil
2924 kws1 (mapcar
2925 (lambda (x)
2926 ;; 1 2
2927 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2928 (progn
2929 (setq kw (match-string 1 x)
2930 key (and (match-end 2) (match-string 2 x))
2931 log (org-extract-log-state-settings x))
2932 (push (cons kw (and key (string-to-char key))) kwsa)
2933 (and log (push log org-todo-log-states))
2935 (error "Invalid TODO keyword %s" x)))
2936 kws0)
2937 kwsa (if kwsa (append '((:startgroup))
2938 (nreverse kwsa)
2939 '((:endgroup))))
2940 hw (car kws1)
2941 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2942 tail (list inter hw (car dws) (org-last dws)))
2943 (add-to-list 'org-todo-heads hw 'append)
2944 (push kws1 org-todo-sets)
2945 (setq org-done-keywords (append org-done-keywords dws nil))
2946 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2947 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2948 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2949 (setq org-todo-sets (nreverse org-todo-sets)
2950 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2951 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2952 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2953 ;; Process the constants
2954 (when const
2955 (let (e cst)
2956 (while (setq e (pop const))
2957 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2958 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2959 (setq org-table-formula-constants-local cst)))
2961 ;; Process the tags.
2962 (when tags
2963 (let (e tgs)
2964 (while (setq e (pop tags))
2965 (cond
2966 ((equal e "{") (push '(:startgroup) tgs))
2967 ((equal e "}") (push '(:endgroup) tgs))
2968 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2969 (push (cons (match-string 1 e)
2970 (string-to-char (match-string 2 e)))
2971 tgs))
2972 (t (push (list e) tgs))))
2973 (org-set-local 'org-tag-alist nil)
2974 (while (setq e (pop tgs))
2975 (or (and (stringp (car e))
2976 (assoc (car e) org-tag-alist))
2977 (push e org-tag-alist)))))
2979 ;; Compute the regular expressions and other local variables
2980 (if (not org-done-keywords)
2981 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2982 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2983 (length org-scheduled-string)
2984 (length org-clock-string)
2985 (length org-closed-string)))
2986 org-drawer-regexp
2987 (concat "^[ \t]*:\\("
2988 (mapconcat 'regexp-quote org-drawers "\\|")
2989 "\\):[ \t]*$")
2990 org-not-done-keywords
2991 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2992 org-todo-regexp
2993 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2994 "\\|") "\\)\\>")
2995 org-not-done-regexp
2996 (concat "\\<\\("
2997 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2998 "\\)\\>")
2999 org-todo-line-regexp
3000 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3001 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3002 "\\)\\>\\)?[ \t]*\\(.*\\)")
3003 org-complex-heading-regexp
3004 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3005 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3006 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3007 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3008 org-nl-done-regexp
3009 (concat "\n\\*+[ \t]+"
3010 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3011 "\\)" "\\>")
3012 org-todo-line-tags-regexp
3013 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3014 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3015 (org-re
3016 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3017 org-looking-at-done-regexp
3018 (concat "^" "\\(?:"
3019 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3020 "\\>")
3021 org-deadline-regexp (concat "\\<" org-deadline-string)
3022 org-deadline-time-regexp
3023 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3024 org-deadline-line-regexp
3025 (concat "\\<\\(" org-deadline-string "\\).*")
3026 org-scheduled-regexp
3027 (concat "\\<" org-scheduled-string)
3028 org-scheduled-time-regexp
3029 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3030 org-closed-time-regexp
3031 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3032 org-keyword-time-regexp
3033 (concat "\\<\\(" org-scheduled-string
3034 "\\|" org-deadline-string
3035 "\\|" org-closed-string
3036 "\\|" org-clock-string "\\)"
3037 " *[[<]\\([^]>]+\\)[]>]")
3038 org-keyword-time-not-clock-regexp
3039 (concat "\\<\\(" org-scheduled-string
3040 "\\|" org-deadline-string
3041 "\\|" org-closed-string
3042 "\\)"
3043 " *[[<]\\([^]>]+\\)[]>]")
3044 org-maybe-keyword-time-regexp
3045 (concat "\\(\\<\\(" org-scheduled-string
3046 "\\|" org-deadline-string
3047 "\\|" org-closed-string
3048 "\\|" org-clock-string "\\)\\)?"
3049 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3050 org-planning-or-clock-line-re
3051 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3052 "\\|" org-deadline-string
3053 "\\|" org-closed-string "\\|" org-clock-string
3054 "\\)\\>\\)")
3056 (org-compute-latex-and-specials-regexp)
3057 (org-set-font-lock-defaults))))
3059 (defun org-file-contents (file &optional noerror)
3060 "Return the contents of FILE, as a string."
3061 (if (or (not file)
3062 (not (file-readable-p file)))
3063 (if noerror
3064 (progn
3065 (message "Cannot read file %s" file)
3066 (ding) (sit-for 2)
3068 (error "Cannot read file %s" file))
3069 (with-temp-buffer
3070 (insert-file-contents file)
3071 (buffer-string))))
3073 (defun org-extract-log-state-settings (x)
3074 "Extract the log state setting from a TODO keyword string.
3075 This will extract info from a string like \"WAIT(w@/!)\"."
3076 (let (kw key log1 log2)
3077 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3078 (setq kw (match-string 1 x)
3079 key (and (match-end 2) (match-string 2 x))
3080 log1 (and (match-end 3) (match-string 3 x))
3081 log2 (and (match-end 4) (match-string 4 x)))
3082 (and (or log1 log2)
3083 (list kw
3084 (and log1 (if (equal log1 "!") 'time 'note))
3085 (and log2 (if (equal log2 "!") 'time 'note)))))))
3087 (defun org-remove-keyword-keys (list)
3088 "Remove a pair of parenthesis at the end of each string in LIST."
3089 (mapcar (lambda (x)
3090 (if (string-match "(.*)$" x)
3091 (substring x 0 (match-beginning 0))
3093 list))
3095 ;; FIXME: this could be done much better, using second characters etc.
3096 (defun org-assign-fast-keys (alist)
3097 "Assign fast keys to a keyword-key alist.
3098 Respect keys that are already there."
3099 (let (new e k c c1 c2 (char ?a))
3100 (while (setq e (pop alist))
3101 (cond
3102 ((equal e '(:startgroup)) (push e new))
3103 ((equal e '(:endgroup)) (push e new))
3105 (setq k (car e) c2 nil)
3106 (if (cdr e)
3107 (setq c (cdr e))
3108 ;; automatically assign a character.
3109 (setq c1 (string-to-char
3110 (downcase (substring
3111 k (if (= (string-to-char k) ?@) 1 0)))))
3112 (if (or (rassoc c1 new) (rassoc c1 alist))
3113 (while (or (rassoc char new) (rassoc char alist))
3114 (setq char (1+ char)))
3115 (setq c2 c1))
3116 (setq c (or c2 char)))
3117 (push (cons k c) new))))
3118 (nreverse new)))
3120 ;;; Some variables used in various places
3122 (defvar org-window-configuration nil
3123 "Used in various places to store a window configuration.")
3124 (defvar org-finish-function nil
3125 "Function to be called when `C-c C-c' is used.
3126 This is for getting out of special buffers like remember.")
3129 ;; FIXME: Occasionally check by commenting these, to make sure
3130 ;; no other functions uses these, forgetting to let-bind them.
3131 (defvar entry)
3132 (defvar state)
3133 (defvar last-state)
3134 (defvar date)
3135 (defvar description)
3137 ;; Defined somewhere in this file, but used before definition.
3138 (defvar org-html-entities)
3139 (defvar org-struct-menu)
3140 (defvar org-org-menu)
3141 (defvar org-tbl-menu)
3142 (defvar org-agenda-keymap)
3144 ;;;; Define the Org-mode
3146 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3147 (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."))
3150 ;; We use a before-change function to check if a table might need
3151 ;; an update.
3152 (defvar org-table-may-need-update t
3153 "Indicates that a table might need an update.
3154 This variable is set by `org-before-change-function'.
3155 `org-table-align' sets it back to nil.")
3156 (defun org-before-change-function (beg end)
3157 "Every change indicates that a table might need an update."
3158 (setq org-table-may-need-update t))
3159 (defvar org-mode-map)
3160 (defvar org-mode-hook nil)
3161 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3162 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3163 (defvar org-table-buffer-is-an nil)
3164 (defconst org-outline-regexp "\\*+ ")
3166 ;;;###autoload
3167 (define-derived-mode org-mode outline-mode "Org"
3168 "Outline-based notes management and organizer, alias
3169 \"Carsten's outline-mode for keeping track of everything.\"
3171 Org-mode develops organizational tasks around a NOTES file which
3172 contains information about projects as plain text. Org-mode is
3173 implemented on top of outline-mode, which is ideal to keep the content
3174 of large files well structured. It supports ToDo items, deadlines and
3175 time stamps, which magically appear in the diary listing of the Emacs
3176 calendar. Tables are easily created with a built-in table editor.
3177 Plain text URL-like links connect to websites, emails (VM), Usenet
3178 messages (Gnus), BBDB entries, and any files related to the project.
3179 For printing and sharing of notes, an Org-mode file (or a part of it)
3180 can be exported as a structured ASCII or HTML file.
3182 The following commands are available:
3184 \\{org-mode-map}"
3186 ;; Get rid of Outline menus, they are not needed
3187 ;; Need to do this here because define-derived-mode sets up
3188 ;; the keymap so late. Still, it is a waste to call this each time
3189 ;; we switch another buffer into org-mode.
3190 (if (featurep 'xemacs)
3191 (when (boundp 'outline-mode-menu-heading)
3192 ;; Assume this is Greg's port, it used easymenu
3193 (easy-menu-remove outline-mode-menu-heading)
3194 (easy-menu-remove outline-mode-menu-show)
3195 (easy-menu-remove outline-mode-menu-hide))
3196 (define-key org-mode-map [menu-bar headings] 'undefined)
3197 (define-key org-mode-map [menu-bar hide] 'undefined)
3198 (define-key org-mode-map [menu-bar show] 'undefined))
3200 (org-load-modules-maybe)
3201 (easy-menu-add org-org-menu)
3202 (easy-menu-add org-tbl-menu)
3203 (org-install-agenda-files-menu)
3204 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3205 (org-add-to-invisibility-spec '(org-cwidth))
3206 (when (featurep 'xemacs)
3207 (org-set-local 'line-move-ignore-invisible t))
3208 (org-set-local 'outline-regexp org-outline-regexp)
3209 (org-set-local 'outline-level 'org-outline-level)
3210 (when (and org-ellipsis
3211 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3212 (fboundp 'make-glyph-code))
3213 (unless org-display-table
3214 (setq org-display-table (make-display-table)))
3215 (set-display-table-slot
3216 org-display-table 4
3217 (vconcat (mapcar
3218 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3219 org-ellipsis)))
3220 (if (stringp org-ellipsis) org-ellipsis "..."))))
3221 (setq buffer-display-table org-display-table))
3222 (org-set-regexps-and-options)
3223 ;; Calc embedded
3224 (org-set-local 'calc-embedded-open-mode "# ")
3225 (modify-syntax-entry ?# "<")
3226 (modify-syntax-entry ?@ "w")
3227 (if org-startup-truncated (setq truncate-lines t))
3228 (org-set-local 'font-lock-unfontify-region-function
3229 'org-unfontify-region)
3230 ;; Activate before-change-function
3231 (org-set-local 'org-table-may-need-update t)
3232 (org-add-hook 'before-change-functions 'org-before-change-function nil
3233 'local)
3234 ;; Check for running clock before killing a buffer
3235 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3236 ;; Paragraphs and auto-filling
3237 (org-set-autofill-regexps)
3238 (setq indent-line-function 'org-indent-line-function)
3239 (org-update-radio-target-regexp)
3241 ;; Comment characters
3242 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3243 (org-set-local 'comment-padding " ")
3245 ;; Align options lines
3246 (org-set-local
3247 'align-mode-rules-list
3248 '((org-in-buffer-settings
3249 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3250 (modes . '(org-mode)))))
3252 ;; Imenu
3253 (org-set-local 'imenu-create-index-function
3254 'org-imenu-get-tree)
3256 ;; Make isearch reveal context
3257 (if (or (featurep 'xemacs)
3258 (not (boundp 'outline-isearch-open-invisible-function)))
3259 ;; Emacs 21 and XEmacs make use of the hook
3260 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3261 ;; Emacs 22 deals with this through a special variable
3262 (org-set-local 'outline-isearch-open-invisible-function
3263 (lambda (&rest ignore) (org-show-context 'isearch))))
3265 ;; If empty file that did not turn on org-mode automatically, make it to.
3266 (if (and org-insert-mode-line-in-empty-file
3267 (interactive-p)
3268 (= (point-min) (point-max)))
3269 (insert "# -*- mode: org -*-\n\n"))
3271 (unless org-inhibit-startup
3272 (when org-startup-align-all-tables
3273 (let ((bmp (buffer-modified-p)))
3274 (org-table-map-tables 'org-table-align)
3275 (set-buffer-modified-p bmp)))
3276 (org-set-startup-visibility)))
3278 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3280 (defun org-current-time ()
3281 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3282 (if (> (car org-time-stamp-rounding-minutes) 1)
3283 (let ((r (car org-time-stamp-rounding-minutes))
3284 (time (decode-time)))
3285 (apply 'encode-time
3286 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3287 (nthcdr 2 time))))
3288 (current-time)))
3290 ;;;; Font-Lock stuff, including the activators
3292 (defvar org-mouse-map (make-sparse-keymap))
3293 (org-defkey org-mouse-map
3294 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3295 (org-defkey org-mouse-map
3296 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3297 (when org-mouse-1-follows-link
3298 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3299 (when org-tab-follows-link
3300 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3301 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3302 (when org-return-follows-link
3303 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3304 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3306 (require 'font-lock)
3308 (defconst org-non-link-chars "]\t\n\r<>")
3309 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3310 "shell" "elisp"))
3311 (defvar org-link-types-re nil
3312 "Matches a link that has a url-like prefix like \"http:\"")
3313 (defvar org-link-re-with-space nil
3314 "Matches a link with spaces, optional angular brackets around it.")
3315 (defvar org-link-re-with-space2 nil
3316 "Matches a link with spaces, optional angular brackets around it.")
3317 (defvar org-angle-link-re nil
3318 "Matches link with angular brackets, spaces are allowed.")
3319 (defvar org-plain-link-re nil
3320 "Matches plain link, without spaces.")
3321 (defvar org-bracket-link-regexp nil
3322 "Matches a link in double brackets.")
3323 (defvar org-bracket-link-analytic-regexp nil
3324 "Regular expression used to analyze links.
3325 Here is what the match groups contain after a match:
3326 1: http:
3327 2: http
3328 3: path
3329 4: [desc]
3330 5: desc")
3331 (defvar org-any-link-re nil
3332 "Regular expression matching any link.")
3334 (defun org-make-link-regexps ()
3335 "Update the link regular expressions.
3336 This should be called after the variable `org-link-types' has changed."
3337 (setq org-link-types-re
3338 (concat
3339 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3340 org-link-re-with-space
3341 (concat
3342 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3343 "\\([^" org-non-link-chars " ]"
3344 "[^" org-non-link-chars "]*"
3345 "[^" org-non-link-chars " ]\\)>?")
3346 org-link-re-with-space2
3347 (concat
3348 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3349 "\\([^" org-non-link-chars " ]"
3350 "[^]\t\n\r]*"
3351 "[^" org-non-link-chars " ]\\)>?")
3352 org-angle-link-re
3353 (concat
3354 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3355 "\\([^" org-non-link-chars " ]"
3356 "[^" org-non-link-chars "]*"
3357 "\\)>")
3358 org-plain-link-re
3359 (concat
3360 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3361 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3362 org-bracket-link-regexp
3363 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3364 org-bracket-link-analytic-regexp
3365 (concat
3366 "\\[\\["
3367 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3368 "\\([^]]+\\)"
3369 "\\]"
3370 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3371 "\\]")
3372 org-any-link-re
3373 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3374 org-angle-link-re "\\)\\|\\("
3375 org-plain-link-re "\\)")))
3377 (org-make-link-regexps)
3379 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3380 "Regular expression for fast time stamp matching.")
3381 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3382 "Regular expression for fast time stamp matching.")
3383 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3384 "Regular expression matching time strings for analysis.
3385 This one does not require the space after the date, so it can be used
3386 on a string that terminates immediately after the date.")
3387 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3388 "Regular expression matching time strings for analysis.")
3389 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3390 "Regular expression matching time stamps, with groups.")
3391 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3392 "Regular expression matching time stamps (also [..]), with groups.")
3393 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3394 "Regular expression matching a time stamp range.")
3395 (defconst org-tr-regexp-both
3396 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3397 "Regular expression matching a time stamp range.")
3398 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3399 org-ts-regexp "\\)?")
3400 "Regular expression matching a time stamp or time stamp range.")
3401 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3402 org-ts-regexp-both "\\)?")
3403 "Regular expression matching a time stamp or time stamp range.
3404 The time stamps may be either active or inactive.")
3406 (defvar org-emph-face nil)
3408 (defun org-do-emphasis-faces (limit)
3409 "Run through the buffer and add overlays to links."
3410 (let (rtn)
3411 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3412 (if (not (= (char-after (match-beginning 3))
3413 (char-after (match-beginning 4))))
3414 (progn
3415 (setq rtn t)
3416 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3417 'face
3418 (nth 1 (assoc (match-string 3)
3419 org-emphasis-alist)))
3420 (add-text-properties (match-beginning 2) (match-end 2)
3421 '(font-lock-multiline t))
3422 (when org-hide-emphasis-markers
3423 (add-text-properties (match-end 4) (match-beginning 5)
3424 '(invisible org-link))
3425 (add-text-properties (match-beginning 3) (match-end 3)
3426 '(invisible org-link)))))
3427 (backward-char 1))
3428 rtn))
3430 (defun org-emphasize (&optional char)
3431 "Insert or change an emphasis, i.e. a font like bold or italic.
3432 If there is an active region, change that region to a new emphasis.
3433 If there is no region, just insert the marker characters and position
3434 the cursor between them.
3435 CHAR should be either the marker character, or the first character of the
3436 HTML tag associated with that emphasis. If CHAR is a space, the means
3437 to remove the emphasis of the selected region.
3438 If char is not given (for example in an interactive call) it
3439 will be prompted for."
3440 (interactive)
3441 (let ((eal org-emphasis-alist) e det
3442 (erc org-emphasis-regexp-components)
3443 (prompt "")
3444 (string "") beg end move tag c s)
3445 (if (org-region-active-p)
3446 (setq beg (region-beginning) end (region-end)
3447 string (buffer-substring beg end))
3448 (setq move t))
3450 (while (setq e (pop eal))
3451 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3452 c (aref tag 0))
3453 (push (cons c (string-to-char (car e))) det)
3454 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3455 (substring tag 1)))))
3456 (unless char
3457 (message "%s" (concat "Emphasis marker or tag:" prompt))
3458 (setq char (read-char-exclusive)))
3459 (setq char (or (cdr (assoc char det)) char))
3460 (if (equal char ?\ )
3461 (setq s "" move nil)
3462 (unless (assoc (char-to-string char) org-emphasis-alist)
3463 (error "No such emphasis marker: \"%c\"" char))
3464 (setq s (char-to-string char)))
3465 (while (and (> (length string) 1)
3466 (equal (substring string 0 1) (substring string -1))
3467 (assoc (substring string 0 1) org-emphasis-alist))
3468 (setq string (substring string 1 -1)))
3469 (setq string (concat s string s))
3470 (if beg (delete-region beg end))
3471 (unless (or (bolp)
3472 (string-match (concat "[" (nth 0 erc) "\n]")
3473 (char-to-string (char-before (point)))))
3474 (insert " "))
3475 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3476 (char-to-string (char-after (point))))
3477 (insert " ") (backward-char 1))
3478 (insert string)
3479 (and move (backward-char 1))))
3481 (defconst org-nonsticky-props
3482 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3485 (defun org-activate-plain-links (limit)
3486 "Run through the buffer and add overlays to links."
3487 (catch 'exit
3488 (let (f)
3489 (while (re-search-forward org-plain-link-re limit t)
3490 (setq f (get-text-property (match-beginning 0) 'face))
3491 (if (or (eq f 'org-tag)
3492 (and (listp f) (memq 'org-tag f)))
3494 (add-text-properties (match-beginning 0) (match-end 0)
3495 (list 'mouse-face 'highlight
3496 'rear-nonsticky org-nonsticky-props
3497 'keymap org-mouse-map
3499 (throw 'exit t))))))
3501 (defun org-activate-code (limit)
3502 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3503 (unless (get-text-property (match-beginning 1) 'face)
3504 (remove-text-properties (match-beginning 0) (match-end 0)
3505 '(display t invisible t intangible t))
3506 t)))
3508 (defun org-activate-angle-links (limit)
3509 "Run through the buffer and add overlays to links."
3510 (if (re-search-forward org-angle-link-re limit t)
3511 (progn
3512 (add-text-properties (match-beginning 0) (match-end 0)
3513 (list 'mouse-face 'highlight
3514 'rear-nonsticky org-nonsticky-props
3515 'keymap org-mouse-map
3517 t)))
3519 (defun org-activate-bracket-links (limit)
3520 "Run through the buffer and add overlays to bracketed links."
3521 (if (re-search-forward org-bracket-link-regexp limit t)
3522 (let* ((help (concat "LINK: "
3523 (org-match-string-no-properties 1)))
3524 ;; FIXME: above we should remove the escapes.
3525 ;; but that requires another match, protecting match data,
3526 ;; a lot of overhead for font-lock.
3527 (ip (org-maybe-intangible
3528 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3529 'keymap org-mouse-map 'mouse-face 'highlight
3530 'font-lock-multiline t 'help-echo help)))
3531 (vp (list 'rear-nonsticky org-nonsticky-props
3532 'keymap org-mouse-map 'mouse-face 'highlight
3533 ' font-lock-multiline t 'help-echo help)))
3534 ;; We need to remove the invisible property here. Table narrowing
3535 ;; may have made some of this invisible.
3536 (remove-text-properties (match-beginning 0) (match-end 0)
3537 '(invisible nil))
3538 (if (match-end 3)
3539 (progn
3540 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3541 (add-text-properties (match-beginning 3) (match-end 3) vp)
3542 (add-text-properties (match-end 3) (match-end 0) ip))
3543 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3544 (add-text-properties (match-beginning 1) (match-end 1) vp)
3545 (add-text-properties (match-end 1) (match-end 0) ip))
3546 t)))
3548 (defun org-activate-dates (limit)
3549 "Run through the buffer and add overlays to dates."
3550 (if (re-search-forward org-tsr-regexp-both limit t)
3551 (progn
3552 (add-text-properties (match-beginning 0) (match-end 0)
3553 (list 'mouse-face 'highlight
3554 'rear-nonsticky org-nonsticky-props
3555 'keymap org-mouse-map))
3556 (when org-display-custom-times
3557 (if (match-end 3)
3558 (org-display-custom-time (match-beginning 3) (match-end 3)))
3559 (org-display-custom-time (match-beginning 1) (match-end 1)))
3560 t)))
3562 (defvar org-target-link-regexp nil
3563 "Regular expression matching radio targets in plain text.")
3564 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3565 "Regular expression matching a link target.")
3566 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3567 "Regular expression matching a radio target.")
3568 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3569 "Regular expression matching any target.")
3571 (defun org-activate-target-links (limit)
3572 "Run through the buffer and add overlays to target matches."
3573 (when org-target-link-regexp
3574 (let ((case-fold-search t))
3575 (if (re-search-forward org-target-link-regexp limit t)
3576 (progn
3577 (add-text-properties (match-beginning 0) (match-end 0)
3578 (list 'mouse-face 'highlight
3579 'rear-nonsticky org-nonsticky-props
3580 'keymap org-mouse-map
3581 'help-echo "Radio target link"
3582 'org-linked-text t))
3583 t)))))
3585 (defun org-update-radio-target-regexp ()
3586 "Find all radio targets in this file and update the regular expression."
3587 (interactive)
3588 (when (memq 'radio org-activate-links)
3589 (setq org-target-link-regexp
3590 (org-make-target-link-regexp (org-all-targets 'radio)))
3591 (org-restart-font-lock)))
3593 (defun org-hide-wide-columns (limit)
3594 (let (s e)
3595 (setq s (text-property-any (point) (or limit (point-max))
3596 'org-cwidth t))
3597 (when s
3598 (setq e (next-single-property-change s 'org-cwidth))
3599 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3600 (goto-char e)
3601 t)))
3603 (defvar org-latex-and-specials-regexp nil
3604 "Regular expression for highlighting export special stuff.")
3605 (defvar org-match-substring-regexp)
3606 (defvar org-match-substring-with-braces-regexp)
3607 (defvar org-export-html-special-string-regexps)
3609 (defun org-compute-latex-and-specials-regexp ()
3610 "Compute regular expression for stuff treated specially by exporters."
3611 (if (not org-highlight-latex-fragments-and-specials)
3612 (org-set-local 'org-latex-and-specials-regexp nil)
3613 (require 'org-exp)
3614 (let*
3615 ((matchers (plist-get org-format-latex-options :matchers))
3616 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3617 org-latex-regexps)))
3618 (options (org-combine-plists (org-default-export-plist)
3619 (org-infile-export-plist)))
3620 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3621 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3622 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3623 (org-export-html-expand (plist-get options :expand-quoted-html))
3624 (org-export-with-special-strings (plist-get options :special-strings))
3625 (re-sub
3626 (cond
3627 ((equal org-export-with-sub-superscripts '{})
3628 (list org-match-substring-with-braces-regexp))
3629 (org-export-with-sub-superscripts
3630 (list org-match-substring-regexp))
3631 (t nil)))
3632 (re-latex
3633 (if org-export-with-LaTeX-fragments
3634 (mapcar (lambda (x) (nth 1 x)) latexs)))
3635 (re-macros
3636 (if org-export-with-TeX-macros
3637 (list (concat "\\\\"
3638 (regexp-opt
3639 (append (mapcar 'car org-html-entities)
3640 (if (boundp 'org-latex-entities)
3641 org-latex-entities nil))
3642 'words))) ; FIXME
3644 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3645 (re-special (if org-export-with-special-strings
3646 (mapcar (lambda (x) (car x))
3647 org-export-html-special-string-regexps)))
3648 (re-rest
3649 (delq nil
3650 (list
3651 (if org-export-html-expand "@<[^>\n]+>")
3652 ))))
3653 (org-set-local
3654 'org-latex-and-specials-regexp
3655 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3656 re-rest) "\\|")))))
3658 (defun org-do-latex-and-special-faces (limit)
3659 "Run through the buffer and add overlays to links."
3660 (when org-latex-and-specials-regexp
3661 (let (rtn d)
3662 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3663 limit t))
3664 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3665 'face))
3666 '(org-code org-verbatim underline)))
3667 (progn
3668 (setq rtn t
3669 d (cond ((member (char-after (1+ (match-beginning 0)))
3670 '(?_ ?^)) 1)
3671 (t 0)))
3672 (font-lock-prepend-text-property
3673 (+ d (match-beginning 0)) (match-end 0)
3674 'face 'org-latex-and-export-specials)
3675 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3676 '(font-lock-multiline t)))))
3677 rtn)))
3679 (defun org-restart-font-lock ()
3680 "Restart font-lock-mode, to force refontification."
3681 (when (and (boundp 'font-lock-mode) font-lock-mode)
3682 (font-lock-mode -1)
3683 (font-lock-mode 1)))
3685 (defun org-all-targets (&optional radio)
3686 "Return a list of all targets in this file.
3687 With optional argument RADIO, only find radio targets."
3688 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3689 rtn)
3690 (save-excursion
3691 (goto-char (point-min))
3692 (while (re-search-forward re nil t)
3693 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3694 rtn)))
3696 (defun org-make-target-link-regexp (targets)
3697 "Make regular expression matching all strings in TARGETS.
3698 The regular expression finds the targets also if there is a line break
3699 between words."
3700 (and targets
3701 (concat
3702 "\\<\\("
3703 (mapconcat
3704 (lambda (x)
3705 (while (string-match " +" x)
3706 (setq x (replace-match "\\s-+" t t x)))
3708 targets
3709 "\\|")
3710 "\\)\\>")))
3712 (defun org-activate-tags (limit)
3713 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3714 (progn
3715 (add-text-properties (match-beginning 1) (match-end 1)
3716 (list 'mouse-face 'highlight
3717 'rear-nonsticky org-nonsticky-props
3718 'keymap org-mouse-map))
3719 t)))
3721 (defun org-outline-level ()
3722 (save-excursion
3723 (looking-at outline-regexp)
3724 (if (match-beginning 1)
3725 (+ (org-get-string-indentation (match-string 1)) 1000)
3726 (1- (- (match-end 0) (match-beginning 0))))))
3728 (defvar org-font-lock-keywords nil)
3730 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3731 "Regular expression matching a property line.")
3733 (defvar org-font-lock-hook nil
3734 "Functions to be called for special font lock stuff.")
3736 (defun org-font-lock-hook (limit)
3737 (run-hook-with-args 'org-font-lock-hook limit))
3739 (defun org-set-font-lock-defaults ()
3740 (let* ((em org-fontify-emphasized-text)
3741 (lk org-activate-links)
3742 (org-font-lock-extra-keywords
3743 (list
3744 ;; Call the hook
3745 '(org-font-lock-hook)
3746 ;; Headlines
3747 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3748 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3749 ;; Table lines
3750 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3751 (1 'org-table t))
3752 ;; Table internals
3753 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3754 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3755 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3756 ;; Drawers
3757 (list org-drawer-regexp '(0 'org-special-keyword t))
3758 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3759 ;; Properties
3760 (list org-property-re
3761 '(1 'org-special-keyword t)
3762 '(3 'org-property-value t))
3763 (if org-format-transports-properties-p
3764 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3765 ;; Links
3766 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3767 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3768 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3769 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3770 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3771 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3772 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3773 '(org-hide-wide-columns (0 nil append))
3774 ;; TODO lines
3775 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3776 '(1 (org-get-todo-face 1) t))
3777 ;; DONE
3778 (if org-fontify-done-headline
3779 (list (concat "^[*]+ +\\<\\("
3780 (mapconcat 'regexp-quote org-done-keywords "\\|")
3781 "\\)\\(.*\\)")
3782 '(2 'org-headline-done t))
3783 nil)
3784 ;; Priorities
3785 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3786 ;; Special keywords
3787 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3788 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3789 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3790 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3791 ;; Emphasis
3792 (if em
3793 (if (featurep 'xemacs)
3794 '(org-do-emphasis-faces (0 nil append))
3795 '(org-do-emphasis-faces)))
3796 ;; Checkboxes
3797 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3798 2 'bold prepend)
3799 (if org-provide-checkbox-statistics
3800 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3801 (0 (org-get-checkbox-statistics-face) t)))
3802 ;; Description list items
3803 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3804 2 'bold prepend)
3805 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3806 '(1 'org-archived prepend))
3807 ;; Specials
3808 '(org-do-latex-and-special-faces)
3809 ;; Code
3810 '(org-activate-code (1 'org-code t))
3811 ;; COMMENT
3812 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3813 "\\|" org-quote-string "\\)\\>")
3814 '(1 'org-special-keyword t))
3815 '("^#.*" (0 'font-lock-comment-face t))
3817 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3818 ;; Now set the full font-lock-keywords
3819 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3820 (org-set-local 'font-lock-defaults
3821 '(org-font-lock-keywords t nil nil backward-paragraph))
3822 (kill-local-variable 'font-lock-keywords) nil))
3824 (defvar org-m nil)
3825 (defvar org-l nil)
3826 (defvar org-f nil)
3827 (defun org-get-level-face (n)
3828 "Get the right face for match N in font-lock matching of healdines."
3829 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3830 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3831 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3832 (cond
3833 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3834 ((eq n 2) org-f)
3835 (t (if org-level-color-stars-only nil org-f))))
3837 (defun org-get-todo-face (kwd)
3838 "Get the right face for a TODO keyword KWD.
3839 If KWD is a number, get the corresponding match group."
3840 (if (numberp kwd) (setq kwd (match-string kwd)))
3841 (or (cdr (assoc kwd org-todo-keyword-faces))
3842 (and (member kwd org-done-keywords) 'org-done)
3843 'org-todo))
3845 (defun org-unfontify-region (beg end &optional maybe_loudly)
3846 "Remove fontification and activation overlays from links."
3847 (font-lock-default-unfontify-region beg end)
3848 (let* ((buffer-undo-list t)
3849 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3850 (inhibit-modification-hooks t)
3851 deactivate-mark buffer-file-name buffer-file-truename)
3852 (remove-text-properties beg end
3853 '(mouse-face t keymap t org-linked-text t
3854 invisible t intangible t))))
3856 ;;;; Visibility cycling, including org-goto and indirect buffer
3858 ;;; Cycling
3860 (defvar org-cycle-global-status nil)
3861 (make-variable-buffer-local 'org-cycle-global-status)
3862 (defvar org-cycle-subtree-status nil)
3863 (make-variable-buffer-local 'org-cycle-subtree-status)
3865 ;;;###autoload
3866 (defun org-cycle (&optional arg)
3867 "Visibility cycling for Org-mode.
3869 - When this function is called with a prefix argument, rotate the entire
3870 buffer through 3 states (global cycling)
3871 1. OVERVIEW: Show only top-level headlines.
3872 2. CONTENTS: Show all headlines of all levels, but no body text.
3873 3. SHOW ALL: Show everything.
3874 When called with two C-c C-u prefixes, switch to the startup visibility,
3875 determined by the variable `org-startup-folded', and by any VISIBILITY
3876 properties in the buffer.
3878 - When point is at the beginning of a headline, rotate the subtree started
3879 by this line through 3 different states (local cycling)
3880 1. FOLDED: Only the main headline is shown.
3881 2. CHILDREN: The main headline and the direct children are shown.
3882 From this state, you can move to one of the children
3883 and zoom in further.
3884 3. SUBTREE: Show the entire subtree, including body text.
3886 - When there is a numeric prefix, go up to a heading with level ARG, do
3887 a `show-subtree' and return to the previous cursor position. If ARG
3888 is negative, go up that many levels.
3890 - When point is not at the beginning of a headline, execute the global
3891 binding for TAB, which is re-indenting the line. See the option
3892 `org-cycle-emulate-tab' for details.
3894 - Special case: if point is at the beginning of the buffer and there is
3895 no headline in line 1, this function will act as if called with prefix arg.
3896 But only if also the variable `org-cycle-global-at-bob' is t."
3897 (interactive "P")
3898 (org-load-modules-maybe)
3899 (let* ((outline-regexp
3900 (if (and (org-mode-p) org-cycle-include-plain-lists)
3901 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3902 outline-regexp))
3903 (bob-special (and org-cycle-global-at-bob (bobp)
3904 (not (looking-at outline-regexp))))
3905 (org-cycle-hook
3906 (if bob-special
3907 (delq 'org-optimize-window-after-visibility-change
3908 (copy-sequence org-cycle-hook))
3909 org-cycle-hook))
3910 (pos (point)))
3912 (if (or bob-special (equal arg '(4)))
3913 ;; special case: use global cycling
3914 (setq arg t))
3916 (cond
3918 ((equal arg '(16))
3919 (org-set-startup-visibility)
3920 (message "Startup visibility, plus VISIBILITY properties."))
3922 ((org-at-table-p 'any)
3923 ;; Enter the table or move to the next field in the table
3924 (or (org-table-recognize-table.el)
3925 (progn
3926 (if arg (org-table-edit-field t)
3927 (org-table-justify-field-maybe)
3928 (call-interactively 'org-table-next-field)))))
3930 ((eq arg t) ;; Global cycling
3932 (cond
3933 ((and (eq last-command this-command)
3934 (eq org-cycle-global-status 'overview))
3935 ;; We just created the overview - now do table of contents
3936 ;; This can be slow in very large buffers, so indicate action
3937 (message "CONTENTS...")
3938 (org-content)
3939 (message "CONTENTS...done")
3940 (setq org-cycle-global-status 'contents)
3941 (run-hook-with-args 'org-cycle-hook 'contents))
3943 ((and (eq last-command this-command)
3944 (eq org-cycle-global-status 'contents))
3945 ;; We just showed the table of contents - now show everything
3946 (show-all)
3947 (message "SHOW ALL")
3948 (setq org-cycle-global-status 'all)
3949 (run-hook-with-args 'org-cycle-hook 'all))
3952 ;; Default action: go to overview
3953 (org-overview)
3954 (message "OVERVIEW")
3955 (setq org-cycle-global-status 'overview)
3956 (run-hook-with-args 'org-cycle-hook 'overview))))
3958 ((and org-drawers org-drawer-regexp
3959 (save-excursion
3960 (beginning-of-line 1)
3961 (looking-at org-drawer-regexp)))
3962 ;; Toggle block visibility
3963 (org-flag-drawer
3964 (not (get-char-property (match-end 0) 'invisible))))
3966 ((integerp arg)
3967 ;; Show-subtree, ARG levels up from here.
3968 (save-excursion
3969 (org-back-to-heading)
3970 (outline-up-heading (if (< arg 0) (- arg)
3971 (- (funcall outline-level) arg)))
3972 (org-show-subtree)))
3974 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3975 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3976 ;; At a heading: rotate between three different views
3977 (org-back-to-heading)
3978 (let ((goal-column 0) eoh eol eos)
3979 ;; First, some boundaries
3980 (save-excursion
3981 (org-back-to-heading)
3982 (save-excursion
3983 (beginning-of-line 2)
3984 (while (and (not (eobp)) ;; this is like `next-line'
3985 (get-char-property (1- (point)) 'invisible))
3986 (beginning-of-line 2)) (setq eol (point)))
3987 (outline-end-of-heading) (setq eoh (point))
3988 (org-end-of-subtree t)
3989 (unless (eobp)
3990 (skip-chars-forward " \t\n")
3991 (beginning-of-line 1) ; in case this is an item
3993 (setq eos (1- (point))))
3994 ;; Find out what to do next and set `this-command'
3995 (cond
3996 ((= eos eoh)
3997 ;; Nothing is hidden behind this heading
3998 (message "EMPTY ENTRY")
3999 (setq org-cycle-subtree-status nil)
4000 (save-excursion
4001 (goto-char eos)
4002 (outline-next-heading)
4003 (if (org-invisible-p) (org-flag-heading nil))))
4004 ((or (>= eol eos)
4005 (not (string-match "\\S-" (buffer-substring eol eos))))
4006 ;; Entire subtree is hidden in one line: open it
4007 (org-show-entry)
4008 (show-children)
4009 (message "CHILDREN")
4010 (save-excursion
4011 (goto-char eos)
4012 (outline-next-heading)
4013 (if (org-invisible-p) (org-flag-heading nil)))
4014 (setq org-cycle-subtree-status 'children)
4015 (run-hook-with-args 'org-cycle-hook 'children))
4016 ((and (eq last-command this-command)
4017 (eq org-cycle-subtree-status 'children))
4018 ;; We just showed the children, now show everything.
4019 (org-show-subtree)
4020 (message "SUBTREE")
4021 (setq org-cycle-subtree-status 'subtree)
4022 (run-hook-with-args 'org-cycle-hook 'subtree))
4024 ;; Default action: hide the subtree.
4025 (hide-subtree)
4026 (message "FOLDED")
4027 (setq org-cycle-subtree-status 'folded)
4028 (run-hook-with-args 'org-cycle-hook 'folded)))))
4030 ;; TAB emulation and template completion
4031 (buffer-read-only (org-back-to-heading))
4033 ((org-try-structure-completion))
4035 ((org-try-cdlatex-tab))
4037 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4038 (or (not (bolp))
4039 (not (looking-at outline-regexp))))
4040 (call-interactively (global-key-binding "\t")))
4042 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4043 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4044 (or (and (eq org-cycle-emulate-tab 'white)
4045 (= (match-end 0) (point-at-eol)))
4046 (and (eq org-cycle-emulate-tab 'whitestart)
4047 (>= (match-end 0) pos))))
4049 (eq org-cycle-emulate-tab t))
4050 (call-interactively (global-key-binding "\t")))
4052 (t (save-excursion
4053 (org-back-to-heading)
4054 (org-cycle))))))
4056 ;;;###autoload
4057 (defun org-global-cycle (&optional arg)
4058 "Cycle the global visibility. For details see `org-cycle'.
4059 With C-u prefix arg, switch to startup visibility.
4060 With a numeric prefix, show all headlines up to that level."
4061 (interactive "P")
4062 (let ((org-cycle-include-plain-lists
4063 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4064 (cond
4065 ((integerp arg)
4066 (show-all)
4067 (hide-sublevels arg)
4068 (setq org-cycle-global-status 'contents))
4069 ((equal arg '(4))
4070 (org-set-startup-visibility)
4071 (message "Startup visibility, plus VISIBILITY properties."))
4073 (org-cycle '(4))))))
4075 (defun org-set-startup-visibility ()
4076 "Set the visibility required by startup options and properties."
4077 (cond
4078 ((eq org-startup-folded t)
4079 (org-cycle '(4)))
4080 ((eq org-startup-folded 'content)
4081 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4082 (org-cycle '(4)) (org-cycle '(4)))))
4083 (org-set-visibility-according-to-property 'no-cleanup)
4084 (org-cycle-hide-archived-subtrees 'all)
4085 (org-cycle-hide-drawers 'all)
4086 (org-cycle-show-empty-lines 'all))
4088 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4089 "Switch subtree visibilities according to :VISIBILITY: property."
4090 (interactive)
4091 (let (state)
4092 (save-excursion
4093 (goto-char (point-min))
4094 (while (re-search-forward
4095 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4096 nil t)
4097 (setq state (match-string 1))
4098 (save-excursion
4099 (org-back-to-heading t)
4100 (hide-subtree)
4101 (org-reveal)
4102 (cond
4103 ((equal state '("fold" "folded"))
4104 (hide-subtree))
4105 ((equal state "children")
4106 (org-show-hidden-entry)
4107 (show-children))
4108 ((equal state "content")
4109 (save-excursion
4110 (save-restriction
4111 (org-narrow-to-subtree)
4112 (org-content))))
4113 ((member state '("all" "showall"))
4114 (show-subtree)))))
4115 (unless no-cleanup
4116 (org-cycle-hide-archived-subtrees 'all)
4117 (org-cycle-hide-drawers 'all)
4118 (org-cycle-show-empty-lines 'all)))))
4120 (defun org-overview ()
4121 "Switch to overview mode, shoing only top-level headlines.
4122 Really, this shows all headlines with level equal or greater than the level
4123 of the first headline in the buffer. This is important, because if the
4124 first headline is not level one, then (hide-sublevels 1) gives confusing
4125 results."
4126 (interactive)
4127 (let ((level (save-excursion
4128 (goto-char (point-min))
4129 (if (re-search-forward (concat "^" outline-regexp) nil t)
4130 (progn
4131 (goto-char (match-beginning 0))
4132 (funcall outline-level))))))
4133 (and level (hide-sublevels level))))
4135 (defun org-content (&optional arg)
4136 "Show all headlines in the buffer, like a table of contents.
4137 With numerical argument N, show content up to level N."
4138 (interactive "P")
4139 (save-excursion
4140 ;; Visit all headings and show their offspring
4141 (and (integerp arg) (org-overview))
4142 (goto-char (point-max))
4143 (catch 'exit
4144 (while (and (progn (condition-case nil
4145 (outline-previous-visible-heading 1)
4146 (error (goto-char (point-min))))
4148 (looking-at outline-regexp))
4149 (if (integerp arg)
4150 (show-children (1- arg))
4151 (show-branches))
4152 (if (bobp) (throw 'exit nil))))))
4155 (defun org-optimize-window-after-visibility-change (state)
4156 "Adjust the window after a change in outline visibility.
4157 This function is the default value of the hook `org-cycle-hook'."
4158 (when (get-buffer-window (current-buffer))
4159 (cond
4160 ; ((eq state 'overview) (org-first-headline-recenter 1))
4161 ; ((eq state 'overview) (org-beginning-of-line))
4162 ((eq state 'content) nil)
4163 ((eq state 'all) nil)
4164 ((eq state 'folded) nil)
4165 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4166 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4168 (defun org-compact-display-after-subtree-move ()
4169 (let (beg end)
4170 (save-excursion
4171 (if (org-up-heading-safe)
4172 (progn
4173 (hide-subtree)
4174 (show-entry)
4175 (show-children)
4176 (org-cycle-show-empty-lines 'children)
4177 (org-cycle-hide-drawers 'children))
4178 (org-overview)))))
4180 (defun org-cycle-show-empty-lines (state)
4181 "Show empty lines above all visible headlines.
4182 The region to be covered depends on STATE when called through
4183 `org-cycle-hook'. Lisp program can use t for STATE to get the
4184 entire buffer covered. Note that an empty line is only shown if there
4185 are at least `org-cycle-separator-lines' empty lines before the headeline."
4186 (when (> org-cycle-separator-lines 0)
4187 (save-excursion
4188 (let* ((n org-cycle-separator-lines)
4189 (re (cond
4190 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4191 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4192 (t (let ((ns (number-to-string (- n 2))))
4193 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4194 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4195 beg end)
4196 (cond
4197 ((memq state '(overview contents t))
4198 (setq beg (point-min) end (point-max)))
4199 ((memq state '(children folded))
4200 (setq beg (point) end (progn (org-end-of-subtree t t)
4201 (beginning-of-line 2)
4202 (point)))))
4203 (when beg
4204 (goto-char beg)
4205 (while (re-search-forward re end t)
4206 (if (not (get-char-property (match-end 1) 'invisible))
4207 (outline-flag-region
4208 (match-beginning 1) (match-end 1) nil)))))))
4209 ;; Never hide empty lines at the end of the file.
4210 (save-excursion
4211 (goto-char (point-max))
4212 (outline-previous-heading)
4213 (outline-end-of-heading)
4214 (if (and (looking-at "[ \t\n]+")
4215 (= (match-end 0) (point-max)))
4216 (outline-flag-region (point) (match-end 0) nil))))
4218 (defun org-show-empty-lines-in-parent ()
4219 "Move to the parent and re-show empty lines before visible headlines."
4220 (save-excursion
4221 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4222 (org-cycle-show-empty-lines context))))
4224 (defun org-cycle-hide-drawers (state)
4225 "Re-hide all drawers after a visibility state change."
4226 (when (and (org-mode-p)
4227 (not (memq state '(overview folded))))
4228 (save-excursion
4229 (let* ((globalp (memq state '(contents all)))
4230 (beg (if globalp (point-min) (point)))
4231 (end (if globalp (point-max) (org-end-of-subtree t))))
4232 (goto-char beg)
4233 (while (re-search-forward org-drawer-regexp end t)
4234 (org-flag-drawer t))))))
4236 (defun org-flag-drawer (flag)
4237 (save-excursion
4238 (beginning-of-line 1)
4239 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4240 (let ((b (match-end 0))
4241 (outline-regexp org-outline-regexp))
4242 (if (re-search-forward
4243 "^[ \t]*:END:"
4244 (save-excursion (outline-next-heading) (point)) t)
4245 (outline-flag-region b (point-at-eol) flag)
4246 (error ":END: line missing"))))))
4248 (defun org-subtree-end-visible-p ()
4249 "Is the end of the current subtree visible?"
4250 (pos-visible-in-window-p
4251 (save-excursion (org-end-of-subtree t) (point))))
4253 (defun org-first-headline-recenter (&optional N)
4254 "Move cursor to the first headline and recenter the headline.
4255 Optional argument N means, put the headline into the Nth line of the window."
4256 (goto-char (point-min))
4257 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4258 (beginning-of-line)
4259 (recenter (prefix-numeric-value N))))
4261 ;;; Org-goto
4263 (defvar org-goto-window-configuration nil)
4264 (defvar org-goto-marker nil)
4265 (defvar org-goto-map
4266 (let ((map (make-sparse-keymap)))
4267 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4268 (while (setq cmd (pop cmds))
4269 (substitute-key-definition cmd cmd map global-map)))
4270 (suppress-keymap map)
4271 (org-defkey map "\C-m" 'org-goto-ret)
4272 (org-defkey map [(return)] 'org-goto-ret)
4273 (org-defkey map [(left)] 'org-goto-left)
4274 (org-defkey map [(right)] 'org-goto-right)
4275 (org-defkey map [(control ?g)] 'org-goto-quit)
4276 (org-defkey map "\C-i" 'org-cycle)
4277 (org-defkey map [(tab)] 'org-cycle)
4278 (org-defkey map [(down)] 'outline-next-visible-heading)
4279 (org-defkey map [(up)] 'outline-previous-visible-heading)
4280 (if org-goto-auto-isearch
4281 (if (fboundp 'define-key-after)
4282 (define-key-after map [t] 'org-goto-local-auto-isearch)
4283 nil)
4284 (org-defkey map "q" 'org-goto-quit)
4285 (org-defkey map "n" 'outline-next-visible-heading)
4286 (org-defkey map "p" 'outline-previous-visible-heading)
4287 (org-defkey map "f" 'outline-forward-same-level)
4288 (org-defkey map "b" 'outline-backward-same-level)
4289 (org-defkey map "u" 'outline-up-heading))
4290 (org-defkey map "/" 'org-occur)
4291 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4292 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4293 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4294 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4295 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4296 map))
4298 (defconst org-goto-help
4299 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4300 RET=jump to location [Q]uit and return to previous location
4301 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4303 (defvar org-goto-start-pos) ; dynamically scoped parameter
4305 ;; FIXME: Docstring doe not mention both interfaces
4306 (defun org-goto (&optional alternative-interface)
4307 "Look up a different location in the current file, keeping current visibility.
4309 When you want look-up or go to a different location in a document, the
4310 fastest way is often to fold the entire buffer and then dive into the tree.
4311 This method has the disadvantage, that the previous location will be folded,
4312 which may not be what you want.
4314 This command works around this by showing a copy of the current buffer
4315 in an indirect buffer, in overview mode. You can dive into the tree in
4316 that copy, use org-occur and incremental search to find a location.
4317 When pressing RET or `Q', the command returns to the original buffer in
4318 which the visibility is still unchanged. After RET is will also jump to
4319 the location selected in the indirect buffer and expose the
4320 the headline hierarchy above."
4321 (interactive "P")
4322 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4323 (org-refile-use-outline-path t)
4324 (interface
4325 (if (not alternative-interface)
4326 org-goto-interface
4327 (if (eq org-goto-interface 'outline)
4328 'outline-path-completion
4329 'outline)))
4330 (org-goto-start-pos (point))
4331 (selected-point
4332 (if (eq interface 'outline)
4333 (car (org-get-location (current-buffer) org-goto-help))
4334 (nth 3 (org-refile-get-location "Goto: ")))))
4335 (if selected-point
4336 (progn
4337 (org-mark-ring-push org-goto-start-pos)
4338 (goto-char selected-point)
4339 (if (or (org-invisible-p) (org-invisible-p2))
4340 (org-show-context 'org-goto)))
4341 (message "Quit"))))
4343 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4344 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4345 (defvar org-goto-local-auto-isearch-map) ; defined below
4347 (defun org-get-location (buf help)
4348 "Let the user select a location in the Org-mode buffer BUF.
4349 This function uses a recursive edit. It returns the selected position
4350 or nil."
4351 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4352 (isearch-hide-immediately nil)
4353 (isearch-search-fun-function
4354 (lambda () 'org-goto-local-search-forward-headings))
4355 (org-goto-selected-point org-goto-exit-command))
4356 (save-excursion
4357 (save-window-excursion
4358 (delete-other-windows)
4359 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4360 (switch-to-buffer
4361 (condition-case nil
4362 (make-indirect-buffer (current-buffer) "*org-goto*")
4363 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4364 (with-output-to-temp-buffer "*Help*"
4365 (princ help))
4366 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4367 (setq buffer-read-only nil)
4368 (let ((org-startup-truncated t)
4369 (org-startup-folded nil)
4370 (org-startup-align-all-tables nil))
4371 (org-mode)
4372 (org-overview))
4373 (setq buffer-read-only t)
4374 (if (and (boundp 'org-goto-start-pos)
4375 (integer-or-marker-p org-goto-start-pos))
4376 (let ((org-show-hierarchy-above t)
4377 (org-show-siblings t)
4378 (org-show-following-heading t))
4379 (goto-char org-goto-start-pos)
4380 (and (org-invisible-p) (org-show-context)))
4381 (goto-char (point-min)))
4382 (org-beginning-of-line)
4383 (message "Select location and press RET")
4384 (use-local-map org-goto-map)
4385 (recursive-edit)
4387 (kill-buffer "*org-goto*")
4388 (cons org-goto-selected-point org-goto-exit-command)))
4390 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4391 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4392 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4393 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4395 (defun org-goto-local-search-forward-headings (string bound noerror)
4396 "Search and make sure that anu matches are in headlines."
4397 (catch 'return
4398 (while (search-forward string bound noerror)
4399 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4400 (and (member :headline context)
4401 (not (member :tags context))))
4402 (throw 'return (point))))))
4404 (defun org-goto-local-auto-isearch ()
4405 "Start isearch."
4406 (interactive)
4407 (goto-char (point-min))
4408 (let ((keys (this-command-keys)))
4409 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4410 (isearch-mode t)
4411 (isearch-process-search-char (string-to-char keys)))))
4413 (defun org-goto-ret (&optional arg)
4414 "Finish `org-goto' by going to the new location."
4415 (interactive "P")
4416 (setq org-goto-selected-point (point)
4417 org-goto-exit-command 'return)
4418 (throw 'exit nil))
4420 (defun org-goto-left ()
4421 "Finish `org-goto' by going to the new location."
4422 (interactive)
4423 (if (org-on-heading-p)
4424 (progn
4425 (beginning-of-line 1)
4426 (setq org-goto-selected-point (point)
4427 org-goto-exit-command 'left)
4428 (throw 'exit nil))
4429 (error "Not on a heading")))
4431 (defun org-goto-right ()
4432 "Finish `org-goto' by going to the new location."
4433 (interactive)
4434 (if (org-on-heading-p)
4435 (progn
4436 (setq org-goto-selected-point (point)
4437 org-goto-exit-command 'right)
4438 (throw 'exit nil))
4439 (error "Not on a heading")))
4441 (defun org-goto-quit ()
4442 "Finish `org-goto' without cursor motion."
4443 (interactive)
4444 (setq org-goto-selected-point nil)
4445 (setq org-goto-exit-command 'quit)
4446 (throw 'exit nil))
4448 ;;; Indirect buffer display of subtrees
4450 (defvar org-indirect-dedicated-frame nil
4451 "This is the frame being used for indirect tree display.")
4452 (defvar org-last-indirect-buffer nil)
4454 (defun org-tree-to-indirect-buffer (&optional arg)
4455 "Create indirect buffer and narrow it to current subtree.
4456 With numerical prefix ARG, go up to this level and then take that tree.
4457 If ARG is negative, go up that many levels.
4458 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4459 indirect buffer previously made with this command, to avoid proliferation of
4460 indirect buffers. However, when you call the command with a `C-u' prefix, or
4461 when `org-indirect-buffer-display' is `new-frame', the last buffer
4462 is kept so that you can work with several indirect buffers at the same time.
4463 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4464 requests that a new frame be made for the new buffer, so that the dedicated
4465 frame is not changed."
4466 (interactive "P")
4467 (let ((cbuf (current-buffer))
4468 (cwin (selected-window))
4469 (pos (point))
4470 beg end level heading ibuf)
4471 (save-excursion
4472 (org-back-to-heading t)
4473 (when (numberp arg)
4474 (setq level (org-outline-level))
4475 (if (< arg 0) (setq arg (+ level arg)))
4476 (while (> (setq level (org-outline-level)) arg)
4477 (outline-up-heading 1 t)))
4478 (setq beg (point)
4479 heading (org-get-heading))
4480 (org-end-of-subtree t) (setq end (point)))
4481 (if (and (buffer-live-p org-last-indirect-buffer)
4482 (not (eq org-indirect-buffer-display 'new-frame))
4483 (not arg))
4484 (kill-buffer org-last-indirect-buffer))
4485 (setq ibuf (org-get-indirect-buffer cbuf)
4486 org-last-indirect-buffer ibuf)
4487 (cond
4488 ((or (eq org-indirect-buffer-display 'new-frame)
4489 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4490 (select-frame (make-frame))
4491 (delete-other-windows)
4492 (switch-to-buffer ibuf)
4493 (org-set-frame-title heading))
4494 ((eq org-indirect-buffer-display 'dedicated-frame)
4495 (raise-frame
4496 (select-frame (or (and org-indirect-dedicated-frame
4497 (frame-live-p org-indirect-dedicated-frame)
4498 org-indirect-dedicated-frame)
4499 (setq org-indirect-dedicated-frame (make-frame)))))
4500 (delete-other-windows)
4501 (switch-to-buffer ibuf)
4502 (org-set-frame-title (concat "Indirect: " heading)))
4503 ((eq org-indirect-buffer-display 'current-window)
4504 (switch-to-buffer ibuf))
4505 ((eq org-indirect-buffer-display 'other-window)
4506 (pop-to-buffer ibuf))
4507 (t (error "Invalid value.")))
4508 (if (featurep 'xemacs)
4509 (save-excursion (org-mode) (turn-on-font-lock)))
4510 (narrow-to-region beg end)
4511 (show-all)
4512 (goto-char pos)
4513 (and (window-live-p cwin) (select-window cwin))))
4515 (defun org-get-indirect-buffer (&optional buffer)
4516 (setq buffer (or buffer (current-buffer)))
4517 (let ((n 1) (base (buffer-name buffer)) bname)
4518 (while (buffer-live-p
4519 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4520 (setq n (1+ n)))
4521 (condition-case nil
4522 (make-indirect-buffer buffer bname 'clone)
4523 (error (make-indirect-buffer buffer bname)))))
4525 (defun org-set-frame-title (title)
4526 "Set the title of the current frame to the string TITLE."
4527 ;; FIXME: how to name a single frame in XEmacs???
4528 (unless (featurep 'xemacs)
4529 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4531 ;;;; Structure editing
4533 ;;; Inserting headlines
4535 (defun org-insert-heading (&optional force-heading)
4536 "Insert a new heading or item with same depth at point.
4537 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4538 If point is at the beginning of a headline, insert a sibling before the
4539 current headline. If point is not at the beginning, do not split the line,
4540 but create the new hedline after the current line."
4541 (interactive "P")
4542 (if (= (buffer-size) 0)
4543 (insert "\n* ")
4544 (when (or force-heading (not (org-insert-item)))
4545 (let* ((head (save-excursion
4546 (condition-case nil
4547 (progn
4548 (org-back-to-heading)
4549 (match-string 0))
4550 (error "*"))))
4551 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4552 pos)
4553 (cond
4554 ((and (org-on-heading-p) (bolp)
4555 (or (bobp)
4556 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4557 ;; insert before the current line
4558 (open-line (if blank 2 1)))
4559 ((and (bolp)
4560 (or (bobp)
4561 (save-excursion
4562 (backward-char 1) (not (org-invisible-p)))))
4563 ;; insert right here
4564 nil)
4566 ;; in the middle of the line
4567 (org-show-entry)
4568 (let ((split
4569 (org-get-alist-option org-M-RET-may-split-line 'headline))
4570 tags pos)
4571 (if (org-on-heading-p)
4572 (progn
4573 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4574 (setq tags (and (match-end 2) (match-string 2)))
4575 (and (match-end 1)
4576 (delete-region (match-beginning 1) (match-end 1)))
4577 (setq pos (point-at-bol))
4578 (or split (end-of-line 1))
4579 (delete-horizontal-space)
4580 (newline (if blank 2 1))
4581 (when tags
4582 (save-excursion
4583 (goto-char pos)
4584 (end-of-line 1)
4585 (insert " " tags)
4586 (org-set-tags nil 'align))))
4587 (or split (end-of-line 1))
4588 (newline (if blank 2 1))))))
4589 (insert head) (just-one-space)
4590 (setq pos (point))
4591 (end-of-line 1)
4592 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4593 (run-hooks 'org-insert-heading-hook)))))
4595 (defun org-get-heading (&optional no-tags)
4596 "Return the heading of the current entry, without the stars."
4597 (save-excursion
4598 (org-back-to-heading t)
4599 (if (looking-at
4600 (if no-tags
4601 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4602 "\\*+[ \t]+\\([^\r\n]*\\)"))
4603 (match-string 1) "")))
4605 (defun org-insert-heading-after-current ()
4606 "Insert a new heading with same level as current, after current subtree."
4607 (interactive)
4608 (org-back-to-heading)
4609 (org-insert-heading)
4610 (org-move-subtree-down)
4611 (end-of-line 1))
4613 (defun org-insert-todo-heading (arg)
4614 "Insert a new heading with the same level and TODO state as current heading.
4615 If the heading has no TODO state, or if the state is DONE, use the first
4616 state (TODO by default). Also with prefix arg, force first state."
4617 (interactive "P")
4618 (when (not (org-insert-item 'checkbox))
4619 (org-insert-heading)
4620 (save-excursion
4621 (org-back-to-heading)
4622 (outline-previous-heading)
4623 (looking-at org-todo-line-regexp))
4624 (if (or arg
4625 (not (match-beginning 2))
4626 (member (match-string 2) org-done-keywords))
4627 (insert (car org-todo-keywords-1) " ")
4628 (insert (match-string 2) " "))
4629 (when org-provide-todo-statistics
4630 (org-update-parent-todo-statistics))))
4632 (defun org-insert-subheading (arg)
4633 "Insert a new subheading and demote it.
4634 Works for outline headings and for plain lists alike."
4635 (interactive "P")
4636 (org-insert-heading arg)
4637 (cond
4638 ((org-on-heading-p) (org-do-demote))
4639 ((org-at-item-p) (org-indent-item 1))))
4641 (defun org-insert-todo-subheading (arg)
4642 "Insert a new subheading with TODO keyword or checkbox and demote it.
4643 Works for outline headings and for plain lists alike."
4644 (interactive "P")
4645 (org-insert-todo-heading arg)
4646 (cond
4647 ((org-on-heading-p) (org-do-demote))
4648 ((org-at-item-p) (org-indent-item 1))))
4650 ;;; Promotion and Demotion
4652 (defun org-promote-subtree ()
4653 "Promote the entire subtree.
4654 See also `org-promote'."
4655 (interactive)
4656 (save-excursion
4657 (org-map-tree 'org-promote))
4658 (org-fix-position-after-promote))
4660 (defun org-demote-subtree ()
4661 "Demote the entire subtree. See `org-demote'.
4662 See also `org-promote'."
4663 (interactive)
4664 (save-excursion
4665 (org-map-tree 'org-demote))
4666 (org-fix-position-after-promote))
4669 (defun org-do-promote ()
4670 "Promote the current heading higher up the tree.
4671 If the region is active in `transient-mark-mode', promote all headings
4672 in the region."
4673 (interactive)
4674 (save-excursion
4675 (if (org-region-active-p)
4676 (org-map-region 'org-promote (region-beginning) (region-end))
4677 (org-promote)))
4678 (org-fix-position-after-promote))
4680 (defun org-do-demote ()
4681 "Demote the current heading lower down the tree.
4682 If the region is active in `transient-mark-mode', demote all headings
4683 in the region."
4684 (interactive)
4685 (save-excursion
4686 (if (org-region-active-p)
4687 (org-map-region 'org-demote (region-beginning) (region-end))
4688 (org-demote)))
4689 (org-fix-position-after-promote))
4691 (defun org-fix-position-after-promote ()
4692 "Make sure that after pro/demotion cursor position is right."
4693 (let ((pos (point)))
4694 (when (save-excursion
4695 (beginning-of-line 1)
4696 (looking-at org-todo-line-regexp)
4697 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4698 (cond ((eobp) (insert " "))
4699 ((eolp) (insert " "))
4700 ((equal (char-after) ?\ ) (forward-char 1))))))
4702 (defun org-reduced-level (l)
4703 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4705 (defun org-get-valid-level (level &optional change)
4706 "Rectify a level change under the influence of `org-odd-levels-only'
4707 LEVEL is a current level, CHANGE is by how much the level should be
4708 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4709 even level numbers will become the next higher odd number."
4710 (if org-odd-levels-only
4711 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4712 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4713 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4714 (max 1 (+ level change))))
4716 (if (boundp 'define-obsolete-function-alias)
4717 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4718 (define-obsolete-function-alias 'org-get-legal-level
4719 'org-get-valid-level)
4720 (define-obsolete-function-alias 'org-get-legal-level
4721 'org-get-valid-level "23.1")))
4723 (defun org-promote ()
4724 "Promote the current heading higher up the tree.
4725 If the region is active in `transient-mark-mode', promote all headings
4726 in the region."
4727 (org-back-to-heading t)
4728 (let* ((level (save-match-data (funcall outline-level)))
4729 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4730 (diff (abs (- level (length up-head) -1))))
4731 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4732 (replace-match up-head nil t)
4733 ;; Fixup tag positioning
4734 (and org-auto-align-tags (org-set-tags nil t))
4735 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4737 (defun org-demote ()
4738 "Demote the current heading lower down the tree.
4739 If the region is active in `transient-mark-mode', demote all headings
4740 in the region."
4741 (org-back-to-heading t)
4742 (let* ((level (save-match-data (funcall outline-level)))
4743 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4744 (diff (abs (- level (length down-head) -1))))
4745 (replace-match down-head nil t)
4746 ;; Fixup tag positioning
4747 (and org-auto-align-tags (org-set-tags nil t))
4748 (if org-adapt-indentation (org-fixup-indentation diff))))
4750 (defun org-map-tree (fun)
4751 "Call FUN for every heading underneath the current one."
4752 (org-back-to-heading)
4753 (let ((level (funcall outline-level)))
4754 (save-excursion
4755 (funcall fun)
4756 (while (and (progn
4757 (outline-next-heading)
4758 (> (funcall outline-level) level))
4759 (not (eobp)))
4760 (funcall fun)))))
4762 (defun org-map-region (fun beg end)
4763 "Call FUN for every heading between BEG and END."
4764 (let ((org-ignore-region t))
4765 (save-excursion
4766 (setq end (copy-marker end))
4767 (goto-char beg)
4768 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4769 (< (point) end))
4770 (funcall fun))
4771 (while (and (progn
4772 (outline-next-heading)
4773 (< (point) end))
4774 (not (eobp)))
4775 (funcall fun)))))
4777 (defun org-fixup-indentation (diff)
4778 "Change the indentation in the current entry by DIFF
4779 However, if any line in the current entry has no indentation, or if it
4780 would end up with no indentation after the change, nothing at all is done."
4781 (save-excursion
4782 (let ((end (save-excursion (outline-next-heading)
4783 (point-marker)))
4784 (prohibit (if (> diff 0)
4785 "^\\S-"
4786 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4787 col)
4788 (unless (save-excursion (end-of-line 1)
4789 (re-search-forward prohibit end t))
4790 (while (and (< (point) end)
4791 (re-search-forward "^[ \t]+" end t))
4792 (goto-char (match-end 0))
4793 (setq col (current-column))
4794 (if (< diff 0) (replace-match ""))
4795 (indent-to (+ diff col))))
4796 (move-marker end nil))))
4798 (defun org-convert-to-odd-levels ()
4799 "Convert an org-mode file with all levels allowed to one with odd levels.
4800 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4801 level 5 etc."
4802 (interactive)
4803 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4804 (let ((org-odd-levels-only nil) n)
4805 (save-excursion
4806 (goto-char (point-min))
4807 (while (re-search-forward "^\\*\\*+ " nil t)
4808 (setq n (- (length (match-string 0)) 2))
4809 (while (>= (setq n (1- n)) 0)
4810 (org-demote))
4811 (end-of-line 1))))))
4814 (defun org-convert-to-oddeven-levels ()
4815 "Convert an org-mode file with only odd levels to one with odd and even levels.
4816 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4817 section with an even level, conversion would destroy the structure of the file. An error
4818 is signaled in this case."
4819 (interactive)
4820 (goto-char (point-min))
4821 ;; First check if there are no even levels
4822 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4823 (org-show-context t)
4824 (error "Not all levels are odd in this file. Conversion not possible."))
4825 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4826 (let ((org-odd-levels-only nil) n)
4827 (save-excursion
4828 (goto-char (point-min))
4829 (while (re-search-forward "^\\*\\*+ " nil t)
4830 (setq n (/ (1- (length (match-string 0))) 2))
4831 (while (>= (setq n (1- n)) 0)
4832 (org-promote))
4833 (end-of-line 1))))))
4835 (defun org-tr-level (n)
4836 "Make N odd if required."
4837 (if org-odd-levels-only (1+ (/ n 2)) n))
4839 ;;; Vertical tree motion, cutting and pasting of subtrees
4841 (defun org-move-subtree-up (&optional arg)
4842 "Move the current subtree up past ARG headlines of the same level."
4843 (interactive "p")
4844 (org-move-subtree-down (- (prefix-numeric-value arg))))
4846 (defun org-move-subtree-down (&optional arg)
4847 "Move the current subtree down past ARG headlines of the same level."
4848 (interactive "p")
4849 (setq arg (prefix-numeric-value arg))
4850 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4851 'outline-get-last-sibling))
4852 (ins-point (make-marker))
4853 (cnt (abs arg))
4854 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4855 ;; Select the tree
4856 (org-back-to-heading)
4857 (setq beg0 (point))
4858 (save-excursion
4859 (setq ne-beg (org-back-over-empty-lines))
4860 (setq beg (point)))
4861 (save-match-data
4862 (save-excursion (outline-end-of-heading)
4863 (setq folded (org-invisible-p)))
4864 (outline-end-of-subtree))
4865 (outline-next-heading)
4866 (setq ne-end (org-back-over-empty-lines))
4867 (setq end (point))
4868 (goto-char beg0)
4869 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4870 ;; include less whitespace
4871 (save-excursion
4872 (goto-char beg)
4873 (forward-line (- ne-beg ne-end))
4874 (setq beg (point))))
4875 ;; Find insertion point, with error handling
4876 (while (> cnt 0)
4877 (or (and (funcall movfunc) (looking-at outline-regexp))
4878 (progn (goto-char beg0)
4879 (error "Cannot move past superior level or buffer limit")))
4880 (setq cnt (1- cnt)))
4881 (if (> arg 0)
4882 ;; Moving forward - still need to move over subtree
4883 (progn (org-end-of-subtree t t)
4884 (save-excursion
4885 (org-back-over-empty-lines)
4886 (or (bolp) (newline)))))
4887 (setq ne-ins (org-back-over-empty-lines))
4888 (move-marker ins-point (point))
4889 (setq txt (buffer-substring beg end))
4890 (org-save-markers-in-region beg end)
4891 (delete-region beg end)
4892 (outline-flag-region (1- beg) beg nil)
4893 (outline-flag-region (1- (point)) (point) nil)
4894 (let ((bbb (point)))
4895 (insert-before-markers txt)
4896 (org-reinstall-markers-in-region bbb)
4897 (move-marker ins-point bbb))
4898 (or (bolp) (insert "\n"))
4899 (setq ins-end (point))
4900 (goto-char ins-point)
4901 (org-skip-whitespace)
4902 (when (and (< arg 0)
4903 (org-first-sibling-p)
4904 (> ne-ins ne-beg))
4905 ;; Move whitespace back to beginning
4906 (save-excursion
4907 (goto-char ins-end)
4908 (let ((kill-whole-line t))
4909 (kill-line (- ne-ins ne-beg)) (point)))
4910 (insert (make-string (- ne-ins ne-beg) ?\n)))
4911 (move-marker ins-point nil)
4912 (org-compact-display-after-subtree-move)
4913 (org-show-empty-lines-in-parent)
4914 (unless folded
4915 (org-show-entry)
4916 (show-children)
4917 (org-cycle-hide-drawers 'children))))
4919 (defvar org-subtree-clip ""
4920 "Clipboard for cut and paste of subtrees.
4921 This is actually only a copy of the kill, because we use the normal kill
4922 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4924 (defvar org-subtree-clip-folded nil
4925 "Was the last copied subtree folded?
4926 This is used to fold the tree back after pasting.")
4928 (defun org-cut-subtree (&optional n)
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 cutting it."
4932 (interactive "p")
4933 (org-copy-subtree n 'cut))
4935 (defun org-copy-subtree (&optional n cut force-store-markers)
4936 "Cut the current subtree into the clipboard.
4937 With prefix arg N, cut this many sequential subtrees.
4938 This is a short-hand for marking the subtree and then copying it.
4939 If CUT is non-nil, actually cut the subtree.
4940 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4941 of some markers in the region, even if CUT is non-nil. This is
4942 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4943 (interactive "p")
4944 (let (beg end folded (beg0 (point)))
4945 (if (interactive-p)
4946 (org-back-to-heading nil) ; take what looks like a subtree
4947 (org-back-to-heading t)) ; take what is really there
4948 (org-back-over-empty-lines)
4949 (setq beg (point))
4950 (skip-chars-forward " \t\r\n")
4951 (save-match-data
4952 (save-excursion (outline-end-of-heading)
4953 (setq folded (org-invisible-p)))
4954 (condition-case nil
4955 (outline-forward-same-level (1- n))
4956 (error nil))
4957 (org-end-of-subtree t t))
4958 (org-back-over-empty-lines)
4959 (setq end (point))
4960 (goto-char beg0)
4961 (when (> end beg)
4962 (setq org-subtree-clip-folded folded)
4963 (when (or cut force-store-markers)
4964 (org-save-markers-in-region beg end))
4965 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4966 (setq org-subtree-clip (current-kill 0))
4967 (message "%s: Subtree(s) with %d characters"
4968 (if cut "Cut" "Copied")
4969 (length org-subtree-clip)))))
4971 (defun org-paste-subtree (&optional level tree)
4972 "Paste the clipboard as a subtree, with modification of headline level.
4973 The entire subtree is promoted or demoted in order to match a new headline
4974 level. By default, the new level is derived from the visible headings
4975 before and after the insertion point, and taken to be the inferior headline
4976 level of the two. So if the previous visible heading is level 3 and the
4977 next is level 4 (or vice versa), level 4 will be used for insertion.
4978 This makes sure that the subtree remains an independent subtree and does
4979 not swallow low level entries.
4981 You can also force a different level, either by using a numeric prefix
4982 argument, or by inserting the heading marker by hand. For example, if the
4983 cursor is after \"*****\", then the tree will be shifted to level 5.
4985 If you want to insert the tree as is, just use \\[yank].
4987 If optional TREE is given, use this text instead of the kill ring."
4988 (interactive "P")
4989 (unless (org-kill-is-subtree-p tree)
4990 (error "%s"
4991 (substitute-command-keys
4992 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4993 (let* ((visp (not (org-invisible-p)))
4994 (txt (or tree (and kill-ring (current-kill 0))))
4995 (^re (concat "^\\(" outline-regexp "\\)"))
4996 (re (concat "\\(" outline-regexp "\\)"))
4997 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4999 (old-level (if (string-match ^re txt)
5000 (- (match-end 0) (match-beginning 0) 1)
5001 -1))
5002 (force-level (cond (level (prefix-numeric-value level))
5003 ((string-match
5004 ^re_ (buffer-substring (point-at-bol) (point)))
5005 (- (match-end 1) (match-beginning 1)))
5006 (t nil)))
5007 (previous-level (save-excursion
5008 (condition-case nil
5009 (progn
5010 (outline-previous-visible-heading 1)
5011 (if (looking-at re)
5012 (- (match-end 0) (match-beginning 0) 1)
5014 (error 1))))
5015 (next-level (save-excursion
5016 (condition-case nil
5017 (progn
5018 (or (looking-at outline-regexp)
5019 (outline-next-visible-heading 1))
5020 (if (looking-at re)
5021 (- (match-end 0) (match-beginning 0) 1)
5023 (error 1))))
5024 (new-level (or force-level (max previous-level next-level)))
5025 (shift (if (or (= old-level -1)
5026 (= new-level -1)
5027 (= old-level new-level))
5029 (- new-level old-level)))
5030 (delta (if (> shift 0) -1 1))
5031 (func (if (> shift 0) 'org-demote 'org-promote))
5032 (org-odd-levels-only nil)
5033 beg end)
5034 ;; Remove the forced level indicator
5035 (if force-level
5036 (delete-region (point-at-bol) (point)))
5037 ;; Paste
5038 (beginning-of-line 1)
5039 (org-back-over-empty-lines)
5040 (setq beg (point))
5041 (insert-before-markers txt)
5042 (unless (string-match "\n\\'" txt) (insert "\n"))
5043 (org-reinstall-markers-in-region beg)
5044 (setq end (point))
5045 (goto-char beg)
5046 (skip-chars-forward " \t\n\r")
5047 (setq beg (point))
5048 (if (and (org-invisible-p) visp)
5049 (save-excursion (outline-show-heading)))
5050 ;; Shift if necessary
5051 (unless (= shift 0)
5052 (save-restriction
5053 (narrow-to-region beg end)
5054 (while (not (= shift 0))
5055 (org-map-region func (point-min) (point-max))
5056 (setq shift (+ delta shift)))
5057 (goto-char (point-min))))
5058 (when (interactive-p)
5059 (message "Clipboard pasted as level %d subtree" new-level))
5060 (if (and kill-ring
5061 (eq org-subtree-clip (current-kill 0))
5062 org-subtree-clip-folded)
5063 ;; The tree was folded before it was killed/copied
5064 (hide-subtree))))
5066 (defun org-kill-is-subtree-p (&optional txt)
5067 "Check if the current kill is an outline subtree, or a set of trees.
5068 Returns nil if kill does not start with a headline, or if the first
5069 headline level is not the largest headline level in the tree.
5070 So this will actually accept several entries of equal levels as well,
5071 which is OK for `org-paste-subtree'.
5072 If optional TXT is given, check this string instead of the current kill."
5073 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5074 (start-level (and kill
5075 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5076 org-outline-regexp "\\)")
5077 kill)
5078 (- (match-end 2) (match-beginning 2) 1)))
5079 (re (concat "^" org-outline-regexp))
5080 (start (1+ (match-beginning 2))))
5081 (if (not start-level)
5082 (progn
5083 nil) ;; does not even start with a heading
5084 (catch 'exit
5085 (while (setq start (string-match re kill (1+ start)))
5086 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5087 (throw 'exit nil)))
5088 t))))
5090 (defvar org-markers-to-move nil
5091 "Markers that should be moved with a cut-and-paste operation.
5092 Those markers are stored together with their positions relative to
5093 the start of the region.")
5095 (defun org-save-markers-in-region (beg end)
5096 "Check markers in region.
5097 If these markers are between BEG and END, record their position relative
5098 to BEG, so that after moving the block of text, we can put the markers back
5099 into place.
5100 This function gets called just before an entry or tree gets cut from the
5101 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5102 called immediately, to move the markers with the entries."
5103 (setq org-markers-to-move nil)
5104 (when (featurep 'org-clock)
5105 (org-clock-save-markers-for-cut-and-paste beg end))
5106 (when (featurep 'org-agenda)
5107 (org-agenda-save-markers-for-cut-and-paste beg end)))
5109 (defun org-check-and-save-marker (marker beg end)
5110 "Check if MARKER is between BEG and END.
5111 If yes, remember the marker and the distance to BEG."
5112 (when (and (marker-buffer marker)
5113 (equal (marker-buffer marker) (current-buffer)))
5114 (if (and (>= marker beg) (< marker end))
5115 (push (cons marker (- marker beg)) org-markers-to-move))))
5117 (defun org-reinstall-markers-in-region (beg)
5118 "Move all remembered markers to their position relative to BEG."
5119 (mapc (lambda (x)
5120 (move-marker (car x) (+ beg (cdr x))))
5121 org-markers-to-move)
5122 (setq org-markers-to-move nil))
5124 (defun org-narrow-to-subtree ()
5125 "Narrow buffer to the current subtree."
5126 (interactive)
5127 (save-excursion
5128 (save-match-data
5129 (narrow-to-region
5130 (progn (org-back-to-heading) (point))
5131 (progn (org-end-of-subtree t) (point))))))
5134 ;;; Outline Sorting
5136 (defun org-sort (with-case)
5137 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5138 Optional argument WITH-CASE means sort case-sensitively."
5139 (interactive "P")
5140 (if (org-at-table-p)
5141 (org-call-with-arg 'org-table-sort-lines with-case)
5142 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5144 (defun org-sort-remove-invisible (s)
5145 (remove-text-properties 0 (length s) org-rm-props s)
5146 (while (string-match org-bracket-link-regexp s)
5147 (setq s (replace-match (if (match-end 2)
5148 (match-string 3 s)
5149 (match-string 1 s)) t t s)))
5152 (defvar org-priority-regexp) ; defined later in the file
5154 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5155 "Sort entries on a certain level of an outline tree.
5156 If there is an active region, the entries in the region are sorted.
5157 Else, if the cursor is before the first entry, sort the top-level items.
5158 Else, the children of the entry at point are sorted.
5160 Sorting can be alphabetically, numerically, and by date/time as given by
5161 the first time stamp in the entry. The command prompts for the sorting
5162 type unless it has been given to the function through the SORTING-TYPE
5163 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5164 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5165 called with point at the beginning of the record. It must return either
5166 a string or a number that should serve as the sorting key for that record.
5168 Comparing entries ignores case by default. However, with an optional argument
5169 WITH-CASE, the sorting considers case as well."
5170 (interactive "P")
5171 (let ((case-func (if with-case 'identity 'downcase))
5172 start beg end stars re re2
5173 txt what tmp plain-list-p)
5174 ;; Find beginning and end of region to sort
5175 (cond
5176 ((org-region-active-p)
5177 ;; we will sort the region
5178 (setq end (region-end)
5179 what "region")
5180 (goto-char (region-beginning))
5181 (if (not (org-on-heading-p)) (outline-next-heading))
5182 (setq start (point)))
5183 ((org-at-item-p)
5184 ;; we will sort this plain list
5185 (org-beginning-of-item-list) (setq start (point))
5186 (org-end-of-item-list) (setq end (point))
5187 (goto-char start)
5188 (setq plain-list-p t
5189 what "plain list"))
5190 ((or (org-on-heading-p)
5191 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5192 ;; we will sort the children of the current headline
5193 (org-back-to-heading)
5194 (setq start (point)
5195 end (progn (org-end-of-subtree t t)
5196 (org-back-over-empty-lines)
5197 (point))
5198 what "children")
5199 (goto-char start)
5200 (show-subtree)
5201 (outline-next-heading))
5203 ;; we will sort the top-level entries in this file
5204 (goto-char (point-min))
5205 (or (org-on-heading-p) (outline-next-heading))
5206 (setq start (point) end (point-max) what "top-level")
5207 (goto-char start)
5208 (show-all)))
5210 (setq beg (point))
5211 (if (>= beg end) (error "Nothing to sort"))
5213 (unless plain-list-p
5214 (looking-at "\\(\\*+\\)")
5215 (setq stars (match-string 1)
5216 re (concat "^" (regexp-quote stars) " +")
5217 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5218 txt (buffer-substring beg end))
5219 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5220 (if (and (not (equal stars "*")) (string-match re2 txt))
5221 (error "Region to sort contains a level above the first entry")))
5223 (unless sorting-type
5224 (message
5225 (if plain-list-p
5226 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5227 "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:")
5228 what)
5229 (setq sorting-type (read-char-exclusive))
5231 (and (= (downcase sorting-type) ?f)
5232 (setq getkey-func
5233 (completing-read "Sort using function: "
5234 obarray 'fboundp t nil nil))
5235 (setq getkey-func (intern getkey-func)))
5237 (and (= (downcase sorting-type) ?r)
5238 (setq property
5239 (completing-read "Property: "
5240 (mapcar 'list (org-buffer-property-keys t))
5241 nil t))))
5243 (message "Sorting entries...")
5245 (save-restriction
5246 (narrow-to-region start end)
5248 (let ((dcst (downcase sorting-type))
5249 (now (current-time)))
5250 (sort-subr
5251 (/= dcst sorting-type)
5252 ;; This function moves to the beginning character of the "record" to
5253 ;; be sorted.
5254 (if plain-list-p
5255 (lambda nil
5256 (if (org-at-item-p) t (goto-char (point-max))))
5257 (lambda nil
5258 (if (re-search-forward re nil t)
5259 (goto-char (match-beginning 0))
5260 (goto-char (point-max)))))
5261 ;; This function moves to the last character of the "record" being
5262 ;; sorted.
5263 (if plain-list-p
5264 'org-end-of-item
5265 (lambda nil
5266 (save-match-data
5267 (condition-case nil
5268 (outline-forward-same-level 1)
5269 (error
5270 (goto-char (point-max)))))))
5272 ;; This function returns the value that gets sorted against.
5273 (if plain-list-p
5274 (lambda nil
5275 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5276 (cond
5277 ((= dcst ?n)
5278 (string-to-number (buffer-substring (match-end 0)
5279 (point-at-eol))))
5280 ((= dcst ?a)
5281 (buffer-substring (match-end 0) (point-at-eol)))
5282 ((= dcst ?t)
5283 (if (re-search-forward org-ts-regexp
5284 (point-at-eol) t)
5285 (org-time-string-to-time (match-string 0))
5286 now))
5287 ((= dcst ?f)
5288 (if getkey-func
5289 (progn
5290 (setq tmp (funcall getkey-func))
5291 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5292 tmp)
5293 (error "Invalid key function `%s'" getkey-func)))
5294 (t (error "Invalid sorting type `%c'" sorting-type)))))
5295 (lambda nil
5296 (cond
5297 ((= dcst ?n)
5298 (if (looking-at outline-regexp)
5299 (string-to-number (buffer-substring (match-end 0)
5300 (point-at-eol)))
5301 nil))
5302 ((= dcst ?a)
5303 (funcall case-func (buffer-substring (point-at-bol)
5304 (point-at-eol))))
5305 ((= dcst ?t)
5306 (if (re-search-forward org-ts-regexp
5307 (save-excursion
5308 (forward-line 2)
5309 (point)) t)
5310 (org-time-string-to-time (match-string 0))
5311 now))
5312 ((= dcst ?p)
5313 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5314 (string-to-char (match-string 2))
5315 org-default-priority))
5316 ((= dcst ?r)
5317 (or (org-entry-get nil property) ""))
5318 ((= dcst ?o)
5319 (if (looking-at org-complex-heading-regexp)
5320 (- 9999 (length (member (match-string 2)
5321 org-todo-keywords-1)))))
5322 ((= dcst ?f)
5323 (if getkey-func
5324 (progn
5325 (setq tmp (funcall getkey-func))
5326 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5327 tmp)
5328 (error "Invalid key function `%s'" getkey-func)))
5329 (t (error "Invalid sorting type `%c'" sorting-type)))))
5331 (cond
5332 ((= dcst ?a) 'string<)
5333 ((= dcst ?t) 'time-less-p)
5334 (t nil)))))
5335 (message "Sorting entries...done")))
5337 (defun org-do-sort (table what &optional with-case sorting-type)
5338 "Sort TABLE of WHAT according to SORTING-TYPE.
5339 The user will be prompted for the SORTING-TYPE if the call to this
5340 function does not specify it. WHAT is only for the prompt, to indicate
5341 what is being sorted. The sorting key will be extracted from
5342 the car of the elements of the table.
5343 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5344 (unless sorting-type
5345 (message
5346 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5347 what)
5348 (setq sorting-type (read-char-exclusive)))
5349 (let ((dcst (downcase sorting-type))
5350 extractfun comparefun)
5351 ;; Define the appropriate functions
5352 (cond
5353 ((= dcst ?n)
5354 (setq extractfun 'string-to-number
5355 comparefun (if (= dcst sorting-type) '< '>)))
5356 ((= dcst ?a)
5357 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5358 (lambda(x) (downcase (org-sort-remove-invisible x))))
5359 comparefun (if (= dcst sorting-type)
5360 'string<
5361 (lambda (a b) (and (not (string< a b))
5362 (not (string= a b)))))))
5363 ((= dcst ?t)
5364 (setq extractfun
5365 (lambda (x)
5366 (if (string-match org-ts-regexp x)
5367 (time-to-seconds
5368 (org-time-string-to-time (match-string 0 x)))
5370 comparefun (if (= dcst sorting-type) '< '>)))
5371 (t (error "Invalid sorting type `%c'" sorting-type)))
5373 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5374 table)
5375 (lambda (a b) (funcall comparefun (car a) (car b))))))
5377 ;;; Editing source examples
5379 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5380 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5381 (defvar org-edit-src-force-single-line nil)
5382 (defvar org-edit-src-from-org-mode nil)
5384 (define-minor-mode org-exit-edit-mode
5385 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5387 (defun org-edit-src-code ()
5388 "Edit the source code example at point.
5389 An indirect buffer is created, and that buffer is then narrowed to the
5390 example at point and switched to the correct language mode. When done,
5391 exit by killing the buffer with \\[org-edit-src-exit]."
5392 (interactive)
5393 (let ((line (org-current-line))
5394 (case-fold-search t)
5395 (msg (substitute-command-keys
5396 "Edit, then exit with C-c ' (C-c and single quote)"))
5397 (info (org-edit-src-find-region-and-lang))
5398 (org-mode-p (eq major-mode 'org-mode))
5399 beg end lang lang-f single)
5400 (if (not info)
5402 (setq beg (nth 0 info)
5403 end (nth 1 info)
5404 lang (nth 2 info)
5405 single (nth 3 info)
5406 lang-f (intern (concat lang "-mode")))
5407 (unless (functionp lang-f)
5408 (error "No such language mode: %s" lang-f))
5409 (goto-line line)
5410 (if (get-buffer "*Org Edit Src Example*")
5411 (kill-buffer "*Org Edit Src Example*"))
5412 (switch-to-buffer (make-indirect-buffer (current-buffer)
5413 "*Org Edit Src Example*"))
5414 (narrow-to-region beg end)
5415 (remove-text-properties beg end '(display nil invisible nil
5416 intangible nil))
5417 (let ((org-inhibit-startup t))
5418 (funcall lang-f))
5419 (set (make-local-variable 'org-edit-src-force-single-line) single)
5420 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5421 (when org-mode-p
5422 (goto-char (point-min))
5423 (while (re-search-forward "^," nil t)
5424 (replace-match "")))
5425 (goto-line line)
5426 (org-exit-edit-mode)
5427 (org-set-local 'header-line-format msg)
5428 (message "%s" msg)
5429 t)))
5431 (defun org-edit-src-find-region-and-lang ()
5432 "Find the region and language for a local edit.
5433 Return a list with beginning and end of the region, a string representing
5434 the language, a switch telling of the content should be in a single line."
5435 (let ((re-list
5437 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5438 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5439 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5440 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5441 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5442 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5443 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5444 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5445 ("^#\\+begin_example.*\n" "^#\\+end_example" "fundamental")
5446 ("^#\\+html:" "\n" "html" single-line)
5447 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5448 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5449 ("^#\\+latex:" "\n" "latex" single-line)
5450 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5451 ("^#\\+ascii:" "\n" "ascii" single-line)
5453 (pos (point))
5454 re re1 re2 single beg end lang)
5455 (catch 'exit
5456 (while (setq entry (pop re-list))
5457 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5458 single (nth 3 entry))
5459 (save-excursion
5460 (if (or (looking-at re1)
5461 (re-search-backward re1 nil t))
5462 (progn
5463 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5464 (if (and (re-search-forward re2 nil t)
5465 (>= (match-end 0) pos))
5466 (throw 'exit (list beg (match-beginning 0) lang single))))
5467 (if (or (looking-at re2)
5468 (re-search-forward re2 nil t))
5469 (progn
5470 (setq end (match-beginning 0))
5471 (if (and (re-search-backward re1 nil t)
5472 (<= (match-beginning 0) pos))
5473 (throw 'exit
5474 (list (match-end 0) end
5475 (org-edit-src-get-lang lang) single)))))))))))
5477 (defun org-edit-src-get-lang (lang)
5478 "Extract the src language."
5479 (let ((m (match-string 0)))
5480 (cond
5481 ((stringp lang) lang)
5482 ((integerp lang) (match-string lang))
5483 ((and (eq lang lang)
5484 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5485 (match-string 1 m))
5486 ((and (eq lang lang)
5487 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5488 (match-string 1 m))
5489 (t "fundamental"))))
5491 (defun org-edit-src-exit ()
5492 "Exit special edit and protect problematic lines."
5493 (interactive)
5494 (unless (buffer-base-buffer (current-buffer))
5495 (error "This is not an indirect buffer, something is wrong..."))
5496 (unless (> (point-min) 1)
5497 (error "This buffer is not narrowed, something is wrong..."))
5498 (goto-char (point-min))
5499 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5500 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5501 (when (org-bound-and-true-p org-edit-src-force-single-line)
5502 (goto-char (point-min))
5503 (while (re-search-forward "\n" nil t)
5504 (replace-match " "))
5505 (goto-char (point-min))
5506 (if (looking-at "\\s-*") (replace-match " "))
5507 (if (re-search-forward "\\s-+\\'" nil t)
5508 (replace-match "")))
5509 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5510 (goto-char (point-min))
5511 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5512 (replace-match ",\\1"))
5513 (when font-lock-mode
5514 (font-lock-unfontify-region (point-min) (point-max)))
5515 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5516 (kill-buffer (current-buffer)))
5518 ;;;; Plain list items, including checkboxes
5520 ;;; Plain list items
5522 (defun org-at-item-p ()
5523 "Is point in a line starting a hand-formatted item?"
5524 (let ((llt org-plain-list-ordered-item-terminator))
5525 (save-excursion
5526 (goto-char (point-at-bol))
5527 (looking-at
5528 (cond
5529 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5530 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5531 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5532 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5534 (defun org-in-item-p ()
5535 "It the cursor inside a plain list item.
5536 Does not have to be the first line."
5537 (save-excursion
5538 (condition-case nil
5539 (progn
5540 (org-beginning-of-item)
5541 (org-at-item-p)
5543 (error nil))))
5545 (defun org-insert-item (&optional checkbox)
5546 "Insert a new item at the current level.
5547 Return t when things worked, nil when we are not in an item."
5548 (when (save-excursion
5549 (condition-case nil
5550 (progn
5551 (org-beginning-of-item)
5552 (org-at-item-p)
5553 (if (org-invisible-p) (error "Invisible item"))
5555 (error nil)))
5556 (let* ((bul (match-string 0))
5557 (descp (save-excursion (goto-char (match-beginning 0))
5558 (beginning-of-line 1)
5559 (save-match-data
5560 (looking-at "[ \t]*.*? ::"))))
5561 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5562 (match-end 0)))
5563 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5564 pos)
5565 (if descp (setq checkbox nil))
5566 (cond
5567 ((and (org-at-item-p) (<= (point) eow))
5568 ;; before the bullet
5569 (beginning-of-line 1)
5570 (open-line (if blank 2 1)))
5571 ((<= (point) eow)
5572 (beginning-of-line 1))
5574 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5575 (end-of-line 1)
5576 (delete-horizontal-space))
5577 (newline (if blank 2 1))))
5578 (insert bul
5579 (if checkbox "[ ]" "")
5580 (if descp (concat (if checkbox " " "")
5581 (read-string "Term: ") " :: ") ""))
5582 (just-one-space)
5583 (setq pos (point))
5584 (end-of-line 1)
5585 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5586 (org-maybe-renumber-ordered-list)
5587 (and checkbox (org-update-checkbox-count-maybe))
5590 ;;; Checkboxes
5592 (defun org-at-item-checkbox-p ()
5593 "Is point at a line starting a plain-list item with a checklet?"
5594 (and (org-at-item-p)
5595 (save-excursion
5596 (goto-char (match-end 0))
5597 (skip-chars-forward " \t")
5598 (looking-at "\\[[- X]\\]"))))
5600 (defun org-toggle-checkbox (&optional arg)
5601 "Toggle the checkbox in the current line."
5602 (interactive "P")
5603 (catch 'exit
5604 (let (beg end status (firstnew 'unknown))
5605 (cond
5606 ((org-region-active-p)
5607 (setq beg (region-beginning) end (region-end)))
5608 ((org-on-heading-p)
5609 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5610 ((org-at-item-checkbox-p)
5611 (let ((pos (point)))
5612 (replace-match
5613 (cond (arg "[-]")
5614 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5615 (t "[ ]"))
5616 t t)
5617 (goto-char pos))
5618 (throw 'exit t))
5619 (t (error "Not at a checkbox or heading, and no active region")))
5620 (save-excursion
5621 (goto-char beg)
5622 (while (< (point) end)
5623 (when (org-at-item-checkbox-p)
5624 (setq status (equal (match-string 0) "[X]"))
5625 (when (eq firstnew 'unknown)
5626 (setq firstnew (not status)))
5627 (replace-match
5628 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5629 (beginning-of-line 2)))))
5630 (org-update-checkbox-count-maybe))
5632 (defun org-update-checkbox-count-maybe ()
5633 "Update checkbox statistics unless turned off by user."
5634 (when org-provide-checkbox-statistics
5635 (org-update-checkbox-count)))
5637 (defun org-update-checkbox-count (&optional all)
5638 "Update the checkbox statistics in the current section.
5639 This will find all statistic cookies like [57%] and [6/12] and update them
5640 with the current numbers. With optional prefix argument ALL, do this for
5641 the whole buffer."
5642 (interactive "P")
5643 (save-excursion
5644 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5645 (beg (condition-case nil
5646 (progn (outline-back-to-heading) (point))
5647 (error (point-min))))
5648 (end (move-marker (make-marker)
5649 (progn (outline-next-heading) (point))))
5650 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5651 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5652 (re-find (concat re "\\|" re-box))
5653 beg-cookie end-cookie is-percent c-on c-off lim
5654 eline curr-ind next-ind continue-from startsearch
5655 (cstat 0)
5657 (when all
5658 (goto-char (point-min))
5659 (outline-next-heading)
5660 (setq beg (point) end (point-max)))
5661 (goto-char end)
5662 ;; find each statistic cookie
5663 (while (re-search-backward re-find beg t)
5664 (setq beg-cookie (match-beginning 1)
5665 end-cookie (match-end 1)
5666 cstat (+ cstat (if end-cookie 1 0))
5667 startsearch (point-at-eol)
5668 continue-from (point-at-bol)
5669 is-percent (match-beginning 2)
5670 lim (cond
5671 ((org-on-heading-p) (outline-next-heading) (point))
5672 ((org-at-item-p) (org-end-of-item) (point))
5673 (t nil))
5674 c-on 0
5675 c-off 0)
5676 (when lim
5677 ;; find first checkbox for this cookie and gather
5678 ;; statistics from all that are at this indentation level
5679 (goto-char startsearch)
5680 (if (re-search-forward re-box lim t)
5681 (progn
5682 (org-beginning-of-item)
5683 (setq curr-ind (org-get-indentation))
5684 (setq next-ind curr-ind)
5685 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5686 (save-excursion (end-of-line) (setq eline (point)))
5687 (if (re-search-forward re-box eline t)
5688 (if (member (match-string 2) '("[ ]" "[-]"))
5689 (setq c-off (1+ c-off))
5690 (setq c-on (1+ c-on))
5693 (org-end-of-item)
5694 (setq next-ind (org-get-indentation))
5696 (goto-char continue-from)
5697 ;; update cookie
5698 (when end-cookie
5699 (delete-region beg-cookie end-cookie)
5700 (goto-char beg-cookie)
5701 (insert
5702 (if is-percent
5703 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5704 (format "[%d/%d]" c-on (+ c-on c-off)))))
5705 ;; update items checkbox if it has one
5706 (when (org-at-item-p)
5707 (org-beginning-of-item)
5708 (when (and (> (+ c-on c-off) 0)
5709 (re-search-forward re-box (point-at-eol) t))
5710 (setq beg-cookie (match-beginning 2)
5711 end-cookie (match-end 2))
5712 (delete-region beg-cookie end-cookie)
5713 (goto-char beg-cookie)
5714 (cond ((= c-off 0) (insert "[X]"))
5715 ((= c-on 0) (insert "[ ]"))
5716 (t (insert "[-]")))
5718 (goto-char continue-from))
5719 (when (interactive-p)
5720 (message "Checkbox satistics updated %s (%d places)"
5721 (if all "in entire file" "in current outline entry") cstat)))))
5723 (defun org-get-checkbox-statistics-face ()
5724 "Select the face for checkbox statistics.
5725 The face will be `org-done' when all relevant boxes are checked. Otherwise
5726 it will be `org-todo'."
5727 (if (match-end 1)
5728 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5729 (if (and (> (match-end 2) (match-beginning 2))
5730 (equal (match-string 2) (match-string 3)))
5731 'org-done
5732 'org-todo)))
5734 (defun org-get-indentation (&optional line)
5735 "Get the indentation of the current line, interpreting tabs.
5736 When LINE is given, assume it represents a line and compute its indentation."
5737 (if line
5738 (if (string-match "^ *" (org-remove-tabs line))
5739 (match-end 0))
5740 (save-excursion
5741 (beginning-of-line 1)
5742 (skip-chars-forward " \t")
5743 (current-column))))
5745 (defun org-remove-tabs (s &optional width)
5746 "Replace tabulators in S with spaces.
5747 Assumes that s is a single line, starting in column 0."
5748 (setq width (or width tab-width))
5749 (while (string-match "\t" s)
5750 (setq s (replace-match
5751 (make-string
5752 (- (* width (/ (+ (match-beginning 0) width) width))
5753 (match-beginning 0)) ?\ )
5754 t t s)))
5757 (defun org-fix-indentation (line ind)
5758 "Fix indentation in LINE.
5759 IND is a cons cell with target and minimum indentation.
5760 If the current indenation in LINE is smaller than the minimum,
5761 leave it alone. If it is larger than ind, set it to the target."
5762 (let* ((l (org-remove-tabs line))
5763 (i (org-get-indentation l))
5764 (i1 (car ind)) (i2 (cdr ind)))
5765 (if (>= i i2) (setq l (substring line i2)))
5766 (if (> i1 0)
5767 (concat (make-string i1 ?\ ) l)
5768 l)))
5770 (defun org-beginning-of-item ()
5771 "Go to the beginning of the current hand-formatted item.
5772 If the cursor is not in an item, throw an error."
5773 (interactive)
5774 (let ((pos (point))
5775 (limit (save-excursion
5776 (condition-case nil
5777 (progn
5778 (org-back-to-heading)
5779 (beginning-of-line 2) (point))
5780 (error (point-min)))))
5781 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5782 ind ind1)
5783 (if (org-at-item-p)
5784 (beginning-of-line 1)
5785 (beginning-of-line 1)
5786 (skip-chars-forward " \t")
5787 (setq ind (current-column))
5788 (if (catch 'exit
5789 (while t
5790 (beginning-of-line 0)
5791 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5793 (if (looking-at "[ \t]*$")
5794 (setq ind1 ind-empty)
5795 (skip-chars-forward " \t")
5796 (setq ind1 (current-column)))
5797 (if (< ind1 ind)
5798 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5800 (goto-char pos)
5801 (error "Not in an item")))))
5803 (defun org-end-of-item ()
5804 "Go to the end of the current hand-formatted item.
5805 If the cursor is not in an item, throw an error."
5806 (interactive)
5807 (let* ((pos (point))
5808 ind1
5809 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5810 (limit (save-excursion (outline-next-heading) (point)))
5811 (ind (save-excursion
5812 (org-beginning-of-item)
5813 (skip-chars-forward " \t")
5814 (current-column)))
5815 (end (catch 'exit
5816 (while t
5817 (beginning-of-line 2)
5818 (if (eobp) (throw 'exit (point)))
5819 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5820 (if (looking-at "[ \t]*$")
5821 (setq ind1 ind-empty)
5822 (skip-chars-forward " \t")
5823 (setq ind1 (current-column)))
5824 (if (<= ind1 ind)
5825 (throw 'exit (point-at-bol)))))))
5826 (if end
5827 (goto-char end)
5828 (goto-char pos)
5829 (error "Not in an item"))))
5831 (defun org-next-item ()
5832 "Move to the beginning of the next item in the current plain list.
5833 Error if not at a plain list, or if this is the last item in the list."
5834 (interactive)
5835 (let (ind ind1 (pos (point)))
5836 (org-beginning-of-item)
5837 (setq ind (org-get-indentation))
5838 (org-end-of-item)
5839 (setq ind1 (org-get-indentation))
5840 (unless (and (org-at-item-p) (= ind ind1))
5841 (goto-char pos)
5842 (error "On last item"))))
5844 (defun org-previous-item ()
5845 "Move to the beginning of the previous item in the current plain list.
5846 Error if not at a plain list, or if this is the first item in the list."
5847 (interactive)
5848 (let (beg ind ind1 (pos (point)))
5849 (org-beginning-of-item)
5850 (setq beg (point))
5851 (setq ind (org-get-indentation))
5852 (goto-char beg)
5853 (catch 'exit
5854 (while t
5855 (beginning-of-line 0)
5856 (if (looking-at "[ \t]*$")
5858 (if (<= (setq ind1 (org-get-indentation)) ind)
5859 (throw 'exit t)))))
5860 (condition-case nil
5861 (if (or (not (org-at-item-p))
5862 (< ind1 (1- ind)))
5863 (error "")
5864 (org-beginning-of-item))
5865 (error (goto-char pos)
5866 (error "On first item")))))
5868 (defun org-first-list-item-p ()
5869 "Is this heading the item in a plain list?"
5870 (unless (org-at-item-p)
5871 (error "Not at a plain list item"))
5872 (org-beginning-of-item)
5873 (= (point) (save-excursion (org-beginning-of-item-list))))
5875 (defun org-move-item-down ()
5876 "Move the plain list item at point down, i.e. swap with following item.
5877 Subitems (items with larger indentation) are considered part of the item,
5878 so this really moves item trees."
5879 (interactive)
5880 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5881 (org-beginning-of-item)
5882 (setq beg0 (point))
5883 (save-excursion
5884 (setq ne-beg (org-back-over-empty-lines))
5885 (setq beg (point)))
5886 (goto-char beg0)
5887 (setq ind (org-get-indentation))
5888 (org-end-of-item)
5889 (setq end0 (point))
5890 (setq ind1 (org-get-indentation))
5891 (setq ne-end (org-back-over-empty-lines))
5892 (setq end (point))
5893 (goto-char beg0)
5894 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5895 ;; include less whitespace
5896 (save-excursion
5897 (goto-char beg)
5898 (forward-line (- ne-beg ne-end))
5899 (setq beg (point))))
5900 (goto-char end0)
5901 (if (and (org-at-item-p) (= ind ind1))
5902 (progn
5903 (org-end-of-item)
5904 (org-back-over-empty-lines)
5905 (setq txt (buffer-substring beg end))
5906 (save-excursion
5907 (delete-region beg end))
5908 (setq pos (point))
5909 (insert txt)
5910 (goto-char pos) (org-skip-whitespace)
5911 (org-maybe-renumber-ordered-list))
5912 (goto-char pos)
5913 (error "Cannot move this item further down"))))
5915 (defun org-move-item-up (arg)
5916 "Move the plain list item at point up, i.e. swap with previous item.
5917 Subitems (items with larger indentation) are considered part of the item,
5918 so this really moves item trees."
5919 (interactive "p")
5920 (let (beg beg0 end ind ind1 (pos (point)) txt
5921 ne-beg ne-ins ins-end)
5922 (org-beginning-of-item)
5923 (setq beg0 (point))
5924 (setq ind (org-get-indentation))
5925 (save-excursion
5926 (setq ne-beg (org-back-over-empty-lines))
5927 (setq beg (point)))
5928 (goto-char beg0)
5929 (org-end-of-item)
5930 (org-back-over-empty-lines)
5931 (setq end (point))
5932 (goto-char beg0)
5933 (catch 'exit
5934 (while t
5935 (beginning-of-line 0)
5936 (if (looking-at "[ \t]*$")
5937 (if org-empty-line-terminates-plain-lists
5938 (progn
5939 (goto-char pos)
5940 (error "Cannot move this item further up"))
5941 nil)
5942 (if (<= (setq ind1 (org-get-indentation)) ind)
5943 (throw 'exit t)))))
5944 (condition-case nil
5945 (org-beginning-of-item)
5946 (error (goto-char beg0)
5947 (error "Cannot move this item further up")))
5948 (setq ind1 (org-get-indentation))
5949 (if (and (org-at-item-p) (= ind ind1))
5950 (progn
5951 (setq ne-ins (org-back-over-empty-lines))
5952 (setq txt (buffer-substring beg end))
5953 (save-excursion
5954 (delete-region beg end))
5955 (setq pos (point))
5956 (insert txt)
5957 (setq ins-end (point))
5958 (goto-char pos) (org-skip-whitespace)
5960 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5961 ;; Move whitespace back to beginning
5962 (save-excursion
5963 (goto-char ins-end)
5964 (let ((kill-whole-line t))
5965 (kill-line (- ne-ins ne-beg)) (point)))
5966 (insert (make-string (- ne-ins ne-beg) ?\n)))
5968 (org-maybe-renumber-ordered-list))
5969 (goto-char pos)
5970 (error "Cannot move this item further up"))))
5972 (defun org-maybe-renumber-ordered-list ()
5973 "Renumber the ordered list at point if setup allows it.
5974 This tests the user option `org-auto-renumber-ordered-lists' before
5975 doing the renumbering."
5976 (interactive)
5977 (when (and org-auto-renumber-ordered-lists
5978 (org-at-item-p))
5979 (if (match-beginning 3)
5980 (org-renumber-ordered-list 1)
5981 (org-fix-bullet-type))))
5983 (defun org-maybe-renumber-ordered-list-safe ()
5984 (condition-case nil
5985 (save-excursion
5986 (org-maybe-renumber-ordered-list))
5987 (error nil)))
5989 (defun org-cycle-list-bullet (&optional which)
5990 "Cycle through the different itemize/enumerate bullets.
5991 This cycle the entire list level through the sequence:
5993 `-' -> `+' -> `*' -> `1.' -> `1)'
5995 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5996 0 meand `-', 1 means `+' etc."
5997 (interactive "P")
5998 (org-preserve-lc
5999 (org-beginning-of-item-list)
6000 (org-at-item-p)
6001 (beginning-of-line 1)
6002 (let ((current (match-string 0))
6003 (prevp (eq which 'previous))
6004 new)
6005 (setq new (cond
6006 ((and (numberp which)
6007 (nth (1- which) '("-" "+" "*" "1." "1)"))))
6008 ((string-match "-" current) (if prevp "1)" "+"))
6009 ((string-match "\\+" current)
6010 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
6011 ((string-match "\\*" current) (if prevp "+" "1."))
6012 ((string-match "\\." current) (if prevp "*" "1)"))
6013 ((string-match ")" current) (if prevp "1." "-"))
6014 (t (error "This should not happen"))))
6015 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
6016 (org-fix-bullet-type)
6017 (org-maybe-renumber-ordered-list))))
6019 (defun org-get-string-indentation (s)
6020 "What indentation has S due to SPACE and TAB at the beginning of the string?"
6021 (let ((n -1) (i 0) (w tab-width) c)
6022 (catch 'exit
6023 (while (< (setq n (1+ n)) (length s))
6024 (setq c (aref s n))
6025 (cond ((= c ?\ ) (setq i (1+ i)))
6026 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
6027 (t (throw 'exit t)))))
6030 (defun org-renumber-ordered-list (arg)
6031 "Renumber an ordered plain list.
6032 Cursor needs to be in the first line of an item, the line that starts
6033 with something like \"1.\" or \"2)\"."
6034 (interactive "p")
6035 (unless (and (org-at-item-p)
6036 (match-beginning 3))
6037 (error "This is not an ordered list"))
6038 (let ((line (org-current-line))
6039 (col (current-column))
6040 (ind (org-get-string-indentation
6041 (buffer-substring (point-at-bol) (match-beginning 3))))
6042 ;; (term (substring (match-string 3) -1))
6043 ind1 (n (1- arg))
6044 fmt bob)
6045 ;; find where this list begins
6046 (org-beginning-of-item-list)
6047 (setq bobp (bobp))
6048 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
6049 (setq fmt (concat "%d" (match-string 1)))
6050 (beginning-of-line 0)
6051 ;; walk forward and replace these numbers
6052 (catch 'exit
6053 (while t
6054 (catch 'next
6055 (if bobp (setq bobp nil) (beginning-of-line 2))
6056 (if (eobp) (throw 'exit nil))
6057 (if (looking-at "[ \t]*$") (throw 'next nil))
6058 (skip-chars-forward " \t") (setq ind1 (current-column))
6059 (if (> ind1 ind) (throw 'next t))
6060 (if (< ind1 ind) (throw 'exit t))
6061 (if (not (org-at-item-p)) (throw 'exit nil))
6062 (delete-region (match-beginning 2) (match-end 2))
6063 (goto-char (match-beginning 2))
6064 (insert (format fmt (setq n (1+ n)))))))
6065 (goto-line line)
6066 (org-move-to-column col)))
6068 (defun org-fix-bullet-type ()
6069 "Make sure all items in this list have the same bullet as the firsst item."
6070 (interactive)
6071 (unless (org-at-item-p) (error "This is not a list"))
6072 (let ((line (org-current-line))
6073 (col (current-column))
6074 (ind (current-indentation))
6075 ind1 bullet)
6076 ;; find where this list begins
6077 (org-beginning-of-item-list)
6078 (beginning-of-line 1)
6079 ;; find out what the bullet type is
6080 (looking-at "[ \t]*\\(\\S-+\\)")
6081 (setq bullet (match-string 1))
6082 ;; walk forward and replace these numbers
6083 (beginning-of-line 0)
6084 (catch 'exit
6085 (while t
6086 (catch 'next
6087 (beginning-of-line 2)
6088 (if (eobp) (throw 'exit nil))
6089 (if (looking-at "[ \t]*$") (throw 'next nil))
6090 (skip-chars-forward " \t") (setq ind1 (current-column))
6091 (if (> ind1 ind) (throw 'next t))
6092 (if (< ind1 ind) (throw 'exit t))
6093 (if (not (org-at-item-p)) (throw 'exit nil))
6094 (skip-chars-forward " \t")
6095 (looking-at "\\S-+")
6096 (replace-match bullet))))
6097 (goto-line line)
6098 (org-move-to-column col)
6099 (if (string-match "[0-9]" bullet)
6100 (org-renumber-ordered-list 1))))
6102 (defun org-beginning-of-item-list ()
6103 "Go to the beginning of the current item list.
6104 I.e. to the first item in this list."
6105 (interactive)
6106 (org-beginning-of-item)
6107 (let ((pos (point-at-bol))
6108 (ind (org-get-indentation))
6109 ind1)
6110 ;; find where this list begins
6111 (catch 'exit
6112 (while t
6113 (catch 'next
6114 (beginning-of-line 0)
6115 (if (looking-at "[ \t]*$")
6116 (throw (if (bobp) 'exit 'next) t))
6117 (skip-chars-forward " \t") (setq ind1 (current-column))
6118 (if (or (< ind1 ind)
6119 (and (= ind1 ind)
6120 (not (org-at-item-p)))
6121 (and (= (point-at-bol) (point-min))
6122 (setq pos (point-min))))
6123 (throw 'exit t)
6124 (when (org-at-item-p) (setq pos (point-at-bol)))))))
6125 (goto-char pos)))
6128 (defun org-end-of-item-list ()
6129 "Go to the end of the current item list.
6130 I.e. to the text after the last item."
6131 (interactive)
6132 (org-beginning-of-item)
6133 (let ((pos (point-at-bol))
6134 (ind (org-get-indentation))
6135 ind1)
6136 ;; find where this list begins
6137 (catch 'exit
6138 (while t
6139 (catch 'next
6140 (beginning-of-line 2)
6141 (if (looking-at "[ \t]*$")
6142 (throw (if (eobp) 'exit 'next) t))
6143 (skip-chars-forward " \t") (setq ind1 (current-column))
6144 (if (or (< ind1 ind)
6145 (and (= ind1 ind)
6146 (not (org-at-item-p)))
6147 (eobp))
6148 (progn
6149 (setq pos (point-at-bol))
6150 (throw 'exit t))))))
6151 (goto-char pos)))
6154 (defvar org-last-indent-begin-marker (make-marker))
6155 (defvar org-last-indent-end-marker (make-marker))
6157 (defun org-outdent-item (arg)
6158 "Outdent a local list item."
6159 (interactive "p")
6160 (org-indent-item (- arg)))
6162 (defun org-indent-item (arg)
6163 "Indent a local list item."
6164 (interactive "p")
6165 (unless (org-at-item-p)
6166 (error "Not on an item"))
6167 (save-excursion
6168 (let (beg end ind ind1 tmp delta ind-down ind-up)
6169 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
6170 (setq beg org-last-indent-begin-marker
6171 end org-last-indent-end-marker)
6172 (org-beginning-of-item)
6173 (setq beg (move-marker org-last-indent-begin-marker (point)))
6174 (org-end-of-item)
6175 (setq end (move-marker org-last-indent-end-marker (point))))
6176 (goto-char beg)
6177 (setq tmp (org-item-indent-positions)
6178 ind (car tmp)
6179 ind-down (nth 2 tmp)
6180 ind-up (nth 1 tmp)
6181 delta (if (> arg 0)
6182 (if ind-down (- ind-down ind) 2)
6183 (if ind-up (- ind-up ind) -2)))
6184 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
6185 (while (< (point) end)
6186 (beginning-of-line 1)
6187 (skip-chars-forward " \t") (setq ind1 (current-column))
6188 (delete-region (point-at-bol) (point))
6189 (or (eolp) (org-indent-to-column (+ ind1 delta)))
6190 (beginning-of-line 2))))
6191 (org-fix-bullet-type)
6192 (org-maybe-renumber-ordered-list-safe)
6193 (save-excursion
6194 (beginning-of-line 0)
6195 (condition-case nil (org-beginning-of-item) (error nil))
6196 (org-maybe-renumber-ordered-list-safe)))
6198 (defun org-item-indent-positions ()
6199 "Return indentation for plain list items.
6200 This returns a list with three values: The current indentation, the
6201 parent indentation and the indentation a child should habe.
6202 Assumes cursor in item line."
6203 (let* ((bolpos (point-at-bol))
6204 (ind (org-get-indentation))
6205 ind-down ind-up pos)
6206 (save-excursion
6207 (org-beginning-of-item-list)
6208 (skip-chars-backward "\n\r \t")
6209 (when (org-in-item-p)
6210 (org-beginning-of-item)
6211 (setq ind-up (org-get-indentation))))
6212 (setq pos (point))
6213 (save-excursion
6214 (cond
6215 ((and (condition-case nil (progn (org-previous-item) t)
6216 (error nil))
6217 (or (forward-char 1) t)
6218 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
6219 (setq ind-down (org-get-indentation)))
6220 ((and (goto-char pos)
6221 (org-at-item-p))
6222 (goto-char (match-end 0))
6223 (skip-chars-forward " \t")
6224 (setq ind-down (current-column)))))
6225 (list ind ind-up ind-down)))
6227 ;;; The orgstruct minor mode
6229 ;; Define a minor mode which can be used in other modes in order to
6230 ;; integrate the org-mode structure editing commands.
6232 ;; This is really a hack, because the org-mode structure commands use
6233 ;; keys which normally belong to the major mode. Here is how it
6234 ;; works: The minor mode defines all the keys necessary to operate the
6235 ;; structure commands, but wraps the commands into a function which
6236 ;; tests if the cursor is currently at a headline or a plain list
6237 ;; item. If that is the case, the structure command is used,
6238 ;; temporarily setting many Org-mode variables like regular
6239 ;; expressions for filling etc. However, when any of those keys is
6240 ;; used at a different location, function uses `key-binding' to look
6241 ;; up if the key has an associated command in another currently active
6242 ;; keymap (minor modes, major mode, global), and executes that
6243 ;; command. There might be problems if any of the keys is otherwise
6244 ;; used as a prefix key.
6246 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
6247 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
6248 ;; addresses this by checking explicitly for both bindings.
6250 (defvar orgstruct-mode-map (make-sparse-keymap)
6251 "Keymap for the minor `orgstruct-mode'.")
6253 (defvar org-local-vars nil
6254 "List of local variables, for use by `orgstruct-mode'")
6256 ;;;###autoload
6257 (define-minor-mode orgstruct-mode
6258 "Toggle the minor more `orgstruct-mode'.
6259 This mode is for using Org-mode structure commands in other modes.
6260 The following key behave as if Org-mode was active, if the cursor
6261 is on a headline, or on a plain list item (both in the definition
6262 of Org-mode).
6264 M-up Move entry/item up
6265 M-down Move entry/item down
6266 M-left Promote
6267 M-right Demote
6268 M-S-up Move entry/item up
6269 M-S-down Move entry/item down
6270 M-S-left Promote subtree
6271 M-S-right Demote subtree
6272 M-q Fill paragraph and items like in Org-mode
6273 C-c ^ Sort entries
6274 C-c - Cycle list bullet
6275 TAB Cycle item visibility
6276 M-RET Insert new heading/item
6277 S-M-RET Insert new TODO heading / Chekbox item
6278 C-c C-c Set tags / toggle checkbox"
6279 nil " OrgStruct" nil
6280 (org-load-modules-maybe)
6281 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
6283 ;;;###autoload
6284 (defun turn-on-orgstruct ()
6285 "Unconditionally turn on `orgstruct-mode'."
6286 (orgstruct-mode 1))
6288 ;;;###autoload
6289 (defun turn-on-orgstruct++ ()
6290 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
6291 In addition to setting orgstruct-mode, this also exports all indentation and
6292 autofilling variables from org-mode into the buffer. Note that turning
6293 off orgstruct-mode will *not* remove these additional settings."
6294 (orgstruct-mode 1)
6295 (let (var val)
6296 (mapc
6297 (lambda (x)
6298 (when (string-match
6299 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6300 (symbol-name (car x)))
6301 (setq var (car x) val (nth 1 x))
6302 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
6303 org-local-vars)))
6305 (defun orgstruct-error ()
6306 "Error when there is no default binding for a structure key."
6307 (interactive)
6308 (error "This key has no function outside structure elements"))
6310 (defun orgstruct-setup ()
6311 "Setup orgstruct keymaps."
6312 (let ((nfunc 0)
6313 (bindings
6314 (list
6315 '([(meta up)] org-metaup)
6316 '([(meta down)] org-metadown)
6317 '([(meta left)] org-metaleft)
6318 '([(meta right)] org-metaright)
6319 '([(meta shift up)] org-shiftmetaup)
6320 '([(meta shift down)] org-shiftmetadown)
6321 '([(meta shift left)] org-shiftmetaleft)
6322 '([(meta shift right)] org-shiftmetaright)
6323 '([(shift up)] org-shiftup)
6324 '([(shift down)] org-shiftdown)
6325 '("\C-c\C-c" org-ctrl-c-ctrl-c)
6326 '("\M-q" fill-paragraph)
6327 '("\C-c^" org-sort)
6328 '("\C-c-" org-cycle-list-bullet)))
6329 elt key fun cmd)
6330 (while (setq elt (pop bindings))
6331 (setq nfunc (1+ nfunc))
6332 (setq key (org-key (car elt))
6333 fun (nth 1 elt)
6334 cmd (orgstruct-make-binding fun nfunc key))
6335 (org-defkey orgstruct-mode-map key cmd))
6337 ;; Special treatment needed for TAB and RET
6338 (org-defkey orgstruct-mode-map [(tab)]
6339 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
6340 (org-defkey orgstruct-mode-map "\C-i"
6341 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
6343 (org-defkey orgstruct-mode-map "\M-\C-m"
6344 (orgstruct-make-binding 'org-insert-heading 105
6345 "\M-\C-m" [(meta return)]))
6346 (org-defkey orgstruct-mode-map [(meta return)]
6347 (orgstruct-make-binding 'org-insert-heading 106
6348 [(meta return)] "\M-\C-m"))
6350 (org-defkey orgstruct-mode-map [(shift meta return)]
6351 (orgstruct-make-binding 'org-insert-todo-heading 107
6352 [(meta return)] "\M-\C-m"))
6354 (unless org-local-vars
6355 (setq org-local-vars (org-get-local-variables)))
6359 (defun orgstruct-make-binding (fun n &rest keys)
6360 "Create a function for binding in the structure minor mode.
6361 FUN is the command to call inside a table. N is used to create a unique
6362 command name. KEYS are keys that should be checked in for a command
6363 to execute outside of tables."
6364 (eval
6365 (list 'defun
6366 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
6367 '(arg)
6368 (concat "In Structure, run `" (symbol-name fun) "'.\n"
6369 "Outside of structure, run the binding of `"
6370 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
6371 "'.")
6372 '(interactive "p")
6373 (list 'if
6374 '(org-context-p 'headline 'item)
6375 (list 'org-run-like-in-org-mode (list 'quote fun))
6376 (list 'let '(orgstruct-mode)
6377 (list 'call-interactively
6378 (append '(or)
6379 (mapcar (lambda (k)
6380 (list 'key-binding k))
6381 keys)
6382 '('orgstruct-error))))))))
6384 (defun org-context-p (&rest contexts)
6385 "Check if local context is and of CONTEXTS.
6386 Possible values in the list of contexts are `table', `headline', and `item'."
6387 (let ((pos (point)))
6388 (goto-char (point-at-bol))
6389 (prog1 (or (and (memq 'table contexts)
6390 (looking-at "[ \t]*|"))
6391 (and (memq 'headline contexts)
6392 (looking-at "\\*+"))
6393 (and (memq 'item contexts)
6394 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
6395 (goto-char pos))))
6397 (defun org-get-local-variables ()
6398 "Return a list of all local variables in an org-mode buffer."
6399 (let (varlist)
6400 (with-current-buffer (get-buffer-create "*Org tmp*")
6401 (erase-buffer)
6402 (org-mode)
6403 (setq varlist (buffer-local-variables)))
6404 (kill-buffer "*Org tmp*")
6405 (delq nil
6406 (mapcar
6407 (lambda (x)
6408 (setq x
6409 (if (symbolp x)
6410 (list x)
6411 (list (car x) (list 'quote (cdr x)))))
6412 (if (string-match
6413 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
6414 (symbol-name (car x)))
6415 x nil))
6416 varlist))))
6418 ;;;###autoload
6419 (defun org-run-like-in-org-mode (cmd)
6420 (org-load-modules-maybe)
6421 (unless org-local-vars
6422 (setq org-local-vars (org-get-local-variables)))
6423 (eval (list 'let org-local-vars
6424 (list 'call-interactively (list 'quote cmd)))))
6426 ;;;; Archiving
6428 (defun org-get-category (&optional pos)
6429 "Get the category applying to position POS."
6430 (get-text-property (or pos (point)) 'org-category))
6432 (defun org-refresh-category-properties ()
6433 "Refresh category text properties in the buffer."
6434 (let ((def-cat (cond
6435 ((null org-category)
6436 (if buffer-file-name
6437 (file-name-sans-extension
6438 (file-name-nondirectory buffer-file-name))
6439 "???"))
6440 ((symbolp org-category) (symbol-name org-category))
6441 (t org-category)))
6442 beg end cat pos optionp)
6443 (org-unmodified
6444 (save-excursion
6445 (save-restriction
6446 (widen)
6447 (goto-char (point-min))
6448 (put-text-property (point) (point-max) 'org-category def-cat)
6449 (while (re-search-forward
6450 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6451 (setq pos (match-end 0)
6452 optionp (equal (char-after (match-beginning 0)) ?#)
6453 cat (org-trim (match-string 2)))
6454 (if optionp
6455 (setq beg (point-at-bol) end (point-max))
6456 (org-back-to-heading t)
6457 (setq beg (point) end (org-end-of-subtree t t)))
6458 (put-text-property beg end 'org-category cat)
6459 (goto-char pos)))))))
6462 ;;;; Link Stuff
6464 ;;; Link abbreviations
6466 (defun org-link-expand-abbrev (link)
6467 "Apply replacements as defined in `org-link-abbrev-alist."
6468 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6469 (let* ((key (match-string 1 link))
6470 (as (or (assoc key org-link-abbrev-alist-local)
6471 (assoc key org-link-abbrev-alist)))
6472 (tag (and (match-end 2) (match-string 3 link)))
6473 rpl)
6474 (if (not as)
6475 link
6476 (setq rpl (cdr as))
6477 (cond
6478 ((symbolp rpl) (funcall rpl tag))
6479 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6480 (t (concat rpl tag)))))
6481 link))
6483 ;;; Storing and inserting links
6485 (defvar org-insert-link-history nil
6486 "Minibuffer history for links inserted with `org-insert-link'.")
6488 (defvar org-stored-links nil
6489 "Contains the links stored with `org-store-link'.")
6491 (defvar org-store-link-plist nil
6492 "Plist with info about the most recently link created with `org-store-link'.")
6494 (defvar org-link-protocols nil
6495 "Link protocols added to Org-mode using `org-add-link-type'.")
6497 (defvar org-store-link-functions nil
6498 "List of functions that are called to create and store a link.
6499 Each function will be called in turn until one returns a non-nil
6500 value. Each function should check if it is responsible for creating
6501 this link (for example by looking at the major mode).
6502 If not, it must exit and return nil.
6503 If yes, it should return a non-nil value after a calling
6504 `org-store-link-props' with a list of properties and values.
6505 Special properties are:
6507 :type The link prefix. like \"http\". This must be given.
6508 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6509 This is obligatory as well.
6510 :description Optional default description for the second pair
6511 of brackets in an Org-mode link. The user can still change
6512 this when inserting this link into an Org-mode buffer.
6514 In addition to these, any additional properties can be specified
6515 and then used in remember templates.")
6517 (defun org-add-link-type (type &optional follow export)
6518 "Add TYPE to the list of `org-link-types'.
6519 Re-compute all regular expressions depending on `org-link-types'
6521 FOLLOW and EXPORT are two functions.
6523 FOLLOW should take the link path as the single argument and do whatever
6524 is necessary to follow the link, for example find a file or display
6525 a mail message.
6527 EXPORT should format the link path for export to one of the export formats.
6528 It should be a function accepting three arguments:
6530 path the path of the link, the text after the prefix (like \"http:\")
6531 desc the description of the link, if any, nil if there was no descripton
6532 format the export format, a symbol like `html' or `latex'.
6534 The function may use the FORMAT information to return different values
6535 depending on the format. The return value will be put literally into
6536 the exported file.
6537 Org-mode has a built-in default for exporting links. If you are happy with
6538 this default, there is no need to define an export function for the link
6539 type. For a simple example of an export function, see `org-bbdb.el'."
6540 (add-to-list 'org-link-types type t)
6541 (org-make-link-regexps)
6542 (if (assoc type org-link-protocols)
6543 (setcdr (assoc type org-link-protocols) (list follow export))
6544 (push (list type follow export) org-link-protocols)))
6547 ;;;###autoload
6548 (defun org-store-link (arg)
6549 "\\<org-mode-map>Store an org-link to the current location.
6550 This link is added to `org-stored-links' and can later be inserted
6551 into an org-buffer with \\[org-insert-link].
6553 For some link types, a prefix arg is interpreted:
6554 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6555 For file links, arg negates `org-context-in-file-links'."
6556 (interactive "P")
6557 (org-load-modules-maybe)
6558 (setq org-store-link-plist nil) ; reset
6559 (let (link cpltxt desc description search txt)
6560 (cond
6562 ((run-hook-with-args-until-success 'org-store-link-functions)
6563 (setq link (plist-get org-store-link-plist :link)
6564 desc (or (plist-get org-store-link-plist :description) link)))
6566 ((eq major-mode 'calendar-mode)
6567 (let ((cd (calendar-cursor-to-date)))
6568 (setq link
6569 (format-time-string
6570 (car org-time-stamp-formats)
6571 (apply 'encode-time
6572 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6573 nil nil nil))))
6574 (org-store-link-props :type "calendar" :date cd)))
6576 ((eq major-mode 'w3-mode)
6577 (setq cpltxt (url-view-url t)
6578 link (org-make-link cpltxt))
6579 (org-store-link-props :type "w3" :url (url-view-url t)))
6581 ((eq major-mode 'w3m-mode)
6582 (setq cpltxt (or w3m-current-title w3m-current-url)
6583 link (org-make-link w3m-current-url))
6584 (org-store-link-props :type "w3m" :url (url-view-url t)))
6586 ((setq search (run-hook-with-args-until-success
6587 'org-create-file-search-functions))
6588 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6589 "::" search))
6590 (setq cpltxt (or description link)))
6592 ((eq major-mode 'image-mode)
6593 (setq cpltxt (concat "file:"
6594 (abbreviate-file-name buffer-file-name))
6595 link (org-make-link cpltxt))
6596 (org-store-link-props :type "image" :file buffer-file-name))
6598 ((eq major-mode 'dired-mode)
6599 ;; link to the file in the current line
6600 (setq cpltxt (concat "file:"
6601 (abbreviate-file-name
6602 (expand-file-name
6603 (dired-get-filename nil t))))
6604 link (org-make-link cpltxt)))
6606 ((and buffer-file-name (org-mode-p))
6607 ;; Just link to current headline
6608 (setq cpltxt (concat "file:"
6609 (abbreviate-file-name buffer-file-name)))
6610 ;; Add a context search string
6611 (when (org-xor org-context-in-file-links arg)
6612 ;; Check if we are on a target
6613 (if (org-in-regexp "<<\\(.*?\\)>>")
6614 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6615 (setq txt (cond
6616 ((org-on-heading-p) nil)
6617 ((org-region-active-p)
6618 (buffer-substring (region-beginning) (region-end)))
6619 (t nil)))
6620 (when (or (null txt) (string-match "\\S-" txt))
6621 (setq cpltxt
6622 (concat cpltxt "::"
6623 (condition-case nil
6624 (org-make-org-heading-search-string txt)
6625 (error "")))
6626 desc "NONE"))))
6627 (if (string-match "::\\'" cpltxt)
6628 (setq cpltxt (substring cpltxt 0 -2)))
6629 (setq link (org-make-link cpltxt)))
6631 ((buffer-file-name (buffer-base-buffer))
6632 ;; Just link to this file here.
6633 (setq cpltxt (concat "file:"
6634 (abbreviate-file-name
6635 (buffer-file-name (buffer-base-buffer)))))
6636 ;; Add a context string
6637 (when (org-xor org-context-in-file-links arg)
6638 (setq txt (if (org-region-active-p)
6639 (buffer-substring (region-beginning) (region-end))
6640 (buffer-substring (point-at-bol) (point-at-eol))))
6641 ;; Only use search option if there is some text.
6642 (when (string-match "\\S-" txt)
6643 (setq cpltxt
6644 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6645 desc "NONE")))
6646 (setq link (org-make-link cpltxt)))
6648 ((interactive-p)
6649 (error "Cannot link to a buffer which is not visiting a file"))
6651 (t (setq link nil)))
6653 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6654 (setq link (or link cpltxt)
6655 desc (or desc cpltxt))
6656 (if (equal desc "NONE") (setq desc nil))
6658 (if (and (interactive-p) link)
6659 (progn
6660 (setq org-stored-links
6661 (cons (list link desc) org-stored-links))
6662 (message "Stored: %s" (or desc link)))
6663 (and link (org-make-link-string link desc)))))
6665 (defun org-store-link-props (&rest plist)
6666 "Store link properties, extract names and addresses."
6667 (let (x adr)
6668 (when (setq x (plist-get plist :from))
6669 (setq adr (mail-extract-address-components x))
6670 (plist-put plist :fromname (car adr))
6671 (plist-put plist :fromaddress (nth 1 adr)))
6672 (when (setq x (plist-get plist :to))
6673 (setq adr (mail-extract-address-components x))
6674 (plist-put plist :toname (car adr))
6675 (plist-put plist :toaddress (nth 1 adr))))
6676 (let ((from (plist-get plist :from))
6677 (to (plist-get plist :to)))
6678 (when (and from to org-from-is-user-regexp)
6679 (plist-put plist :fromto
6680 (if (string-match org-from-is-user-regexp from)
6681 (concat "to %t")
6682 (concat "from %f")))))
6683 (setq org-store-link-plist plist))
6685 (defun org-add-link-props (&rest plist)
6686 "Add these properties to the link property list."
6687 (let (key value)
6688 (while plist
6689 (setq key (pop plist) value (pop plist))
6690 (setq org-store-link-plist
6691 (plist-put org-store-link-plist key value)))))
6693 (defun org-email-link-description (&optional fmt)
6694 "Return the description part of an email link.
6695 This takes information from `org-store-link-plist' and formats it
6696 according to FMT (default from `org-email-link-description-format')."
6697 (setq fmt (or fmt org-email-link-description-format))
6698 (let* ((p org-store-link-plist)
6699 (to (plist-get p :toaddress))
6700 (from (plist-get p :fromaddress))
6701 (table
6702 (list
6703 (cons "%c" (plist-get p :fromto))
6704 (cons "%F" (plist-get p :from))
6705 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6706 (cons "%T" (plist-get p :to))
6707 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6708 (cons "%s" (plist-get p :subject))
6709 (cons "%m" (plist-get p :message-id)))))
6710 (when (string-match "%c" fmt)
6711 ;; Check if the user wrote this message
6712 (if (and org-from-is-user-regexp from to
6713 (save-match-data (string-match org-from-is-user-regexp from)))
6714 (setq fmt (replace-match "to %t" t t fmt))
6715 (setq fmt (replace-match "from %f" t t fmt))))
6716 (org-replace-escapes fmt table)))
6718 (defun org-make-org-heading-search-string (&optional string heading)
6719 "Make search string for STRING or current headline."
6720 (interactive)
6721 (let ((s (or string (org-get-heading))))
6722 (unless (and string (not heading))
6723 ;; We are using a headline, clean up garbage in there.
6724 (if (string-match org-todo-regexp s)
6725 (setq s (replace-match "" t t s)))
6726 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6727 (setq s (replace-match "" t t s)))
6728 (setq s (org-trim s))
6729 (if (string-match (concat "^\\(" org-quote-string "\\|"
6730 org-comment-string "\\)") s)
6731 (setq s (replace-match "" t t s)))
6732 (while (string-match org-ts-regexp s)
6733 (setq s (replace-match "" t t s))))
6734 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6735 (setq s (replace-match " " t t s)))
6736 (or string (setq s (concat "*" s))) ; Add * for headlines
6737 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6739 (defun org-make-link (&rest strings)
6740 "Concatenate STRINGS."
6741 (apply 'concat strings))
6743 (defun org-make-link-string (link &optional description)
6744 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6745 (unless (string-match "\\S-" link)
6746 (error "Empty link"))
6747 (when (stringp description)
6748 ;; Remove brackets from the description, they are fatal.
6749 (while (string-match "\\[" description)
6750 (setq description (replace-match "{" t t description)))
6751 (while (string-match "\\]" description)
6752 (setq description (replace-match "}" t t description))))
6753 (when (equal (org-link-escape link) description)
6754 ;; No description needed, it is identical
6755 (setq description nil))
6756 (when (and (not description)
6757 (not (equal link (org-link-escape link))))
6758 (setq description (org-extract-attributes link)))
6759 (concat "[[" (org-link-escape link) "]"
6760 (if description (concat "[" description "]") "")
6761 "]"))
6763 (defconst org-link-escape-chars
6764 '((?\ . "%20")
6765 (?\[ . "%5B")
6766 (?\] . "%5D")
6767 (?\340 . "%E0") ; `a
6768 (?\342 . "%E2") ; ^a
6769 (?\347 . "%E7") ; ,c
6770 (?\350 . "%E8") ; `e
6771 (?\351 . "%E9") ; 'e
6772 (?\352 . "%EA") ; ^e
6773 (?\356 . "%EE") ; ^i
6774 (?\364 . "%F4") ; ^o
6775 (?\371 . "%F9") ; `u
6776 (?\373 . "%FB") ; ^u
6777 (?\; . "%3B")
6778 (?? . "%3F")
6779 (?= . "%3D")
6780 (?+ . "%2B")
6782 "Association list of escapes for some characters problematic in links.
6783 This is the list that is used for internal purposes.")
6785 (defconst org-link-escape-chars-browser
6786 '((?\ . "%20")) ; 32 for the SPC char
6787 "Association list of escapes for some characters problematic in links.
6788 This is the list that is used before handing over to the browser.")
6790 (defun org-link-escape (text &optional table)
6791 "Escape charaters in TEXT that are problematic for links."
6792 (setq table (or table org-link-escape-chars))
6793 (when text
6794 (let ((re (mapconcat (lambda (x) (regexp-quote
6795 (char-to-string (car x))))
6796 table "\\|")))
6797 (while (string-match re text)
6798 (setq text
6799 (replace-match
6800 (cdr (assoc (string-to-char (match-string 0 text))
6801 table))
6802 t t text)))
6803 text)))
6805 (defun org-link-unescape (text &optional table)
6806 "Reverse the action of `org-link-escape'."
6807 (setq table (or table org-link-escape-chars))
6808 (when text
6809 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6810 table "\\|")))
6811 (while (string-match re text)
6812 (setq text
6813 (replace-match
6814 (char-to-string (car (rassoc (match-string 0 text) table)))
6815 t t text)))
6816 text)))
6818 (defun org-xor (a b)
6819 "Exclusive or."
6820 (if a (not b) b))
6822 (defun org-get-header (header)
6823 "Find a header field in the current buffer."
6824 (save-excursion
6825 (goto-char (point-min))
6826 (let ((case-fold-search t) s)
6827 (cond
6828 ((eq header 'from)
6829 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6830 (setq s (match-string 1)))
6831 (while (string-match "\"" s)
6832 (setq s (replace-match "" t t s)))
6833 (if (string-match "[<(].*" s)
6834 (setq s (replace-match "" t t s))))
6835 ((eq header 'message-id)
6836 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6837 (setq s (match-string 1))))
6838 ((eq header 'subject)
6839 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6840 (setq s (match-string 1)))))
6841 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6842 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6843 s)))
6846 (defun org-fixup-message-id-for-http (s)
6847 "Replace special characters in a message id, so it can be used in an http query."
6848 (while (string-match "<" s)
6849 (setq s (replace-match "%3C" t t s)))
6850 (while (string-match ">" s)
6851 (setq s (replace-match "%3E" t t s)))
6852 (while (string-match "@" s)
6853 (setq s (replace-match "%40" t t s)))
6856 ;;;###autoload
6857 (defun org-insert-link-global ()
6858 "Insert a link like Org-mode does.
6859 This command can be called in any mode to insert a link in Org-mode syntax."
6860 (interactive)
6861 (org-load-modules-maybe)
6862 (org-run-like-in-org-mode 'org-insert-link))
6864 (defun org-insert-link (&optional complete-file link-location)
6865 "Insert a link. At the prompt, enter the link.
6867 Completion can be used to select a link previously stored with
6868 `org-store-link'. When the empty string is entered (i.e. if you just
6869 press RET at the prompt), the link defaults to the most recently
6870 stored link. As SPC triggers completion in the minibuffer, you need to
6871 use M-SPC or C-q SPC to force the insertion of a space character.
6873 You will also be prompted for a description, and if one is given, it will
6874 be displayed in the buffer instead of the link.
6876 If there is already a link at point, this command will allow you to edit link
6877 and description parts.
6879 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6880 be selected using completion. The path to the file will be relative to the
6881 current directory if the file is in the current directory or a subdirectory.
6882 Otherwise, the link will be the absolute path as completed in the minibuffer
6883 \(i.e. normally ~/path/to/file).
6885 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6886 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6887 of `org-keep-stored-link-after-insertion'.
6889 If `org-make-link-description-function' is non-nil, this function will be
6890 called with the link target, and the result will be the default
6891 link description.
6893 If the LINK-LOCATION parameter is non-nil, this value will be
6894 used as the link location instead of reading one interactively."
6895 (interactive "P")
6896 (let* ((wcf (current-window-configuration))
6897 (region (if (org-region-active-p)
6898 (buffer-substring (region-beginning) (region-end))))
6899 (remove (and region (list (region-beginning) (region-end))))
6900 (desc region)
6901 tmphist ; byte-compile incorrectly complains about this
6902 (link link-location)
6903 entry file)
6904 (cond
6905 (link-location) ; specified by arg, just use it.
6906 ((org-in-regexp org-bracket-link-regexp 1)
6907 ;; We do have a link at point, and we are going to edit it.
6908 (setq remove (list (match-beginning 0) (match-end 0)))
6909 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6910 (setq link (read-string "Link: "
6911 (org-link-unescape
6912 (org-match-string-no-properties 1)))))
6913 ((or (org-in-regexp org-angle-link-re)
6914 (org-in-regexp org-plain-link-re))
6915 ;; Convert to bracket link
6916 (setq remove (list (match-beginning 0) (match-end 0))
6917 link (read-string "Link: "
6918 (org-remove-angle-brackets (match-string 0)))))
6919 ((equal complete-file '(4))
6920 ;; Completing read for file names.
6921 (setq file (read-file-name "File: "))
6922 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6923 (pwd1 (file-name-as-directory (abbreviate-file-name
6924 (expand-file-name ".")))))
6925 (cond
6926 ((equal complete-file '(16))
6927 (setq link (org-make-link
6928 "file:"
6929 (abbreviate-file-name (expand-file-name file)))))
6930 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6931 (setq link (org-make-link "file:" (match-string 1 file))))
6932 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6933 (expand-file-name file))
6934 (setq link (org-make-link
6935 "file:" (match-string 1 (expand-file-name file)))))
6936 (t (setq link (org-make-link "file:" file))))))
6938 ;; Read link, with completion for stored links.
6939 (with-output-to-temp-buffer "*Org Links*"
6940 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6941 (when org-stored-links
6942 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6943 (princ (mapconcat
6944 (lambda (x)
6945 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6946 (reverse org-stored-links) "\n"))))
6947 (let ((cw (selected-window)))
6948 (select-window (get-buffer-window "*Org Links*"))
6949 (shrink-window-if-larger-than-buffer)
6950 (setq truncate-lines t)
6951 (select-window cw))
6952 ;; Fake a link history, containing the stored links.
6953 (setq tmphist (append (mapcar 'car org-stored-links)
6954 org-insert-link-history))
6955 (unwind-protect
6956 (setq link (org-completing-read
6957 "Link: "
6958 (append
6959 (mapcar (lambda (x) (list (concat (car x) ":")))
6960 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6961 (mapcar (lambda (x) (list (concat x ":")))
6962 org-link-types))
6963 nil nil nil
6964 'tmphist
6965 (or (car (car org-stored-links)))))
6966 (set-window-configuration wcf)
6967 (kill-buffer "*Org Links*"))
6968 (setq entry (assoc link org-stored-links))
6969 (or entry (push link org-insert-link-history))
6970 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6971 (not org-keep-stored-link-after-insertion))
6972 (setq org-stored-links (delq (assoc link org-stored-links)
6973 org-stored-links)))
6974 (setq desc (or desc (nth 1 entry)))))
6976 (if (string-match org-plain-link-re link)
6977 ;; URL-like link, normalize the use of angular brackets.
6978 (setq link (org-make-link (org-remove-angle-brackets link))))
6980 ;; Check if we are linking to the current file with a search option
6981 ;; If yes, simplify the link by using only the search option.
6982 (when (and buffer-file-name
6983 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6984 (let* ((path (match-string 1 link))
6985 (case-fold-search nil)
6986 (search (match-string 2 link)))
6987 (save-match-data
6988 (if (equal (file-truename buffer-file-name) (file-truename path))
6989 ;; We are linking to this same file, with a search option
6990 (setq link search)))))
6992 ;; Check if we can/should use a relative path. If yes, simplify the link
6993 (when (string-match "\\<file:\\(.*\\)" link)
6994 (let* ((path (match-string 1 link))
6995 (origpath path)
6996 (case-fold-search nil))
6997 (cond
6998 ((eq org-link-file-path-type 'absolute)
6999 (setq path (abbreviate-file-name (expand-file-name path))))
7000 ((eq org-link-file-path-type 'noabbrev)
7001 (setq path (expand-file-name path)))
7002 ((eq org-link-file-path-type 'relative)
7003 (setq path (file-relative-name path)))
7005 (save-match-data
7006 (if (string-match (concat "^" (regexp-quote
7007 (file-name-as-directory
7008 (expand-file-name "."))))
7009 (expand-file-name path))
7010 ;; We are linking a file with relative path name.
7011 (setq path (substring (expand-file-name path)
7012 (match-end 0)))))))
7013 (setq link (concat "file:" path))
7014 (if (equal desc origpath)
7015 (setq desc path))))
7017 (if org-make-link-description-function
7018 (setq desc (funcall org-make-link-description-function link desc)))
7020 (setq desc (read-string "Description: " desc))
7021 (unless (string-match "\\S-" desc) (setq desc nil))
7022 (if remove (apply 'delete-region remove))
7023 (insert (org-make-link-string link desc))))
7025 (defun org-completing-read (&rest args)
7026 (let ((minibuffer-local-completion-map
7027 (copy-keymap minibuffer-local-completion-map)))
7028 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
7029 (apply 'completing-read args)))
7031 (defun org-extract-attributes (s)
7032 "Extract the attributes cookie from a string and set as text property."
7033 (let (a attr (start 0))
7034 (save-match-data
7035 (when (string-match "{{\\([^}]+\\)}}$" s)
7036 (setq a (match-string 1 s) s (substring s 0 (match-beginning 0)))
7037 (while (string-match "\\([a-zA-Z]+\\)=\"\\([^\"]*\\)\"" a start)
7038 (setq key (match-string 1 a) value (match-string 2 a)
7039 start (match-end 0)
7040 attr (plist-put attr (intern key) value))))
7041 (org-add-props s nil 'org-attributes attr))
7044 (defun org-attributes-to-string (plist)
7045 "Format a property list into an HTML attribute list."
7046 (let ((s "") key value)
7047 (while plist
7048 (setq key (pop plist) value (pop plist))
7049 (setq s (concat s " "(symbol-name key) "=\"" value "\"")))
7052 ;;; Opening/following a link
7054 (defvar org-link-search-failed nil)
7056 (defun org-next-link ()
7057 "Move forward to the next link.
7058 If the link is in hidden text, expose it."
7059 (interactive)
7060 (when (and org-link-search-failed (eq this-command last-command))
7061 (goto-char (point-min))
7062 (message "Link search wrapped back to beginning of buffer"))
7063 (setq org-link-search-failed nil)
7064 (let* ((pos (point))
7065 (ct (org-context))
7066 (a (assoc :link ct)))
7067 (if a (goto-char (nth 2 a)))
7068 (if (re-search-forward org-any-link-re nil t)
7069 (progn
7070 (goto-char (match-beginning 0))
7071 (if (org-invisible-p) (org-show-context)))
7072 (goto-char pos)
7073 (setq org-link-search-failed t)
7074 (error "No further link found"))))
7076 (defun org-previous-link ()
7077 "Move backward to the previous link.
7078 If the link is in hidden text, expose it."
7079 (interactive)
7080 (when (and org-link-search-failed (eq this-command last-command))
7081 (goto-char (point-max))
7082 (message "Link search wrapped back to end of buffer"))
7083 (setq org-link-search-failed nil)
7084 (let* ((pos (point))
7085 (ct (org-context))
7086 (a (assoc :link ct)))
7087 (if a (goto-char (nth 1 a)))
7088 (if (re-search-backward org-any-link-re nil t)
7089 (progn
7090 (goto-char (match-beginning 0))
7091 (if (org-invisible-p) (org-show-context)))
7092 (goto-char pos)
7093 (setq org-link-search-failed t)
7094 (error "No further link found"))))
7096 (defun org-find-file-at-mouse (ev)
7097 "Open file link or URL at mouse."
7098 (interactive "e")
7099 (mouse-set-point ev)
7100 (org-open-at-point 'in-emacs))
7102 (defun org-open-at-mouse (ev)
7103 "Open file link or URL at mouse."
7104 (interactive "e")
7105 (mouse-set-point ev)
7106 (org-open-at-point))
7108 (defvar org-window-config-before-follow-link nil
7109 "The window configuration before following a link.
7110 This is saved in case the need arises to restore it.")
7112 (defvar org-open-link-marker (make-marker)
7113 "Marker pointing to the location where `org-open-at-point; was called.")
7115 ;;;###autoload
7116 (defun org-open-at-point-global ()
7117 "Follow a link like Org-mode does.
7118 This command can be called in any mode to follow a link that has
7119 Org-mode syntax."
7120 (interactive)
7121 (org-run-like-in-org-mode 'org-open-at-point))
7123 ;;;###autoload
7124 (defun org-open-link-from-string (s &optional arg)
7125 "Open a link in the string S, as if it was in Org-mode."
7126 (interactive "sLink: \nP")
7127 (with-temp-buffer
7128 (let ((org-inhibit-startup t))
7129 (org-mode)
7130 (insert s)
7131 (goto-char (point-min))
7132 (org-open-at-point arg))))
7134 (defun org-open-at-point (&optional in-emacs)
7135 "Open link at or after point.
7136 If there is no link at point, this function will search forward up to
7137 the end of the current subtree.
7138 Normally, files will be opened by an appropriate application. If the
7139 optional argument IN-EMACS is non-nil, Emacs will visit the file."
7140 (interactive "P")
7141 (org-load-modules-maybe)
7142 (move-marker org-open-link-marker (point))
7143 (setq org-window-config-before-follow-link (current-window-configuration))
7144 (org-remove-occur-highlights nil nil t)
7145 (if (org-at-timestamp-p t)
7146 (org-follow-timestamp-link)
7147 (let (type path link line search (pos (point)))
7148 (catch 'match
7149 (save-excursion
7150 (skip-chars-forward "^]\n\r")
7151 (when (org-in-regexp org-bracket-link-regexp)
7152 (setq link (org-extract-attributes
7153 (org-link-unescape (org-match-string-no-properties 1))))
7154 (while (string-match " *\n *" link)
7155 (setq link (replace-match " " t t link)))
7156 (setq link (org-link-expand-abbrev link))
7157 (cond
7158 ((or (file-name-absolute-p link)
7159 (string-match "^\\.\\.?/" link))
7160 (setq type "file" path link))
7161 ((string-match org-link-re-with-space2 link)
7162 (setq type (match-string 1 link) path (match-string 2 link)))
7163 (t (setq type "thisfile" path link)))
7164 (throw 'match t)))
7166 (when (get-text-property (point) 'org-linked-text)
7167 (setq type "thisfile"
7168 pos (if (get-text-property (1+ (point)) 'org-linked-text)
7169 (1+ (point)) (point))
7170 path (buffer-substring
7171 (previous-single-property-change pos 'org-linked-text)
7172 (next-single-property-change pos 'org-linked-text)))
7173 (throw 'match t))
7175 (save-excursion
7176 (when (or (org-in-regexp org-angle-link-re)
7177 (org-in-regexp org-plain-link-re))
7178 (setq type (match-string 1) path (match-string 2))
7179 (throw 'match t)))
7180 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
7181 (setq type "tree-match"
7182 path (match-string 1))
7183 (throw 'match t))
7184 (save-excursion
7185 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
7186 (setq type "tags"
7187 path (match-string 1))
7188 (while (string-match ":" path)
7189 (setq path (replace-match "+" t t path)))
7190 (throw 'match t))))
7191 (unless path
7192 (error "No link found"))
7193 ;; Remove any trailing spaces in path
7194 (if (string-match " +\\'" path)
7195 (setq path (replace-match "" t t path)))
7197 (cond
7199 ((assoc type org-link-protocols)
7200 (funcall (nth 1 (assoc type org-link-protocols)) path))
7202 ((equal type "mailto")
7203 (let ((cmd (car org-link-mailto-program))
7204 (args (cdr org-link-mailto-program)) args1
7205 (address path) (subject "") a)
7206 (if (string-match "\\(.*\\)::\\(.*\\)" path)
7207 (setq address (match-string 1 path)
7208 subject (org-link-escape (match-string 2 path))))
7209 (while args
7210 (cond
7211 ((not (stringp (car args))) (push (pop args) args1))
7212 (t (setq a (pop args))
7213 (if (string-match "%a" a)
7214 (setq a (replace-match address t t a)))
7215 (if (string-match "%s" a)
7216 (setq a (replace-match subject t t a)))
7217 (push a args1))))
7218 (apply cmd (nreverse args1))))
7220 ((member type '("http" "https" "ftp" "news"))
7221 (browse-url (concat type ":" (org-link-escape
7222 path org-link-escape-chars-browser))))
7224 ((member type '("message"))
7225 (browse-url (concat type ":" path)))
7227 ((string= type "tags")
7228 (org-tags-view in-emacs path))
7229 ((string= type "thisfile")
7230 (if in-emacs
7231 (switch-to-buffer-other-window
7232 (org-get-buffer-for-internal-link (current-buffer)))
7233 (org-mark-ring-push))
7234 (let ((cmd `(org-link-search
7235 ,path
7236 ,(cond ((equal in-emacs '(4)) 'occur)
7237 ((equal in-emacs '(16)) 'org-occur)
7238 (t nil))
7239 ,pos)))
7240 (condition-case nil (eval cmd)
7241 (error (progn (widen) (eval cmd))))))
7243 ((string= type "tree-match")
7244 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
7246 ((string= type "file")
7247 (if (string-match "::\\([0-9]+\\)\\'" path)
7248 (setq line (string-to-number (match-string 1 path))
7249 path (substring path 0 (match-beginning 0)))
7250 (if (string-match "::\\(.+\\)\\'" path)
7251 (setq search (match-string 1 path)
7252 path (substring path 0 (match-beginning 0)))))
7253 (if (string-match "[*?{]" (file-name-nondirectory path))
7254 (dired path)
7255 (org-open-file path in-emacs line search)))
7257 ((string= type "news")
7258 (require 'org-gnus)
7259 (org-gnus-follow-link path))
7261 ((string= type "shell")
7262 (let ((cmd path))
7263 (if (or (not org-confirm-shell-link-function)
7264 (funcall org-confirm-shell-link-function
7265 (format "Execute \"%s\" in shell? "
7266 (org-add-props cmd nil
7267 'face 'org-warning))))
7268 (progn
7269 (message "Executing %s" cmd)
7270 (shell-command cmd))
7271 (error "Abort"))))
7273 ((string= type "elisp")
7274 (let ((cmd path))
7275 (if (or (not org-confirm-elisp-link-function)
7276 (funcall org-confirm-elisp-link-function
7277 (format "Execute \"%s\" as elisp? "
7278 (org-add-props cmd nil
7279 'face 'org-warning))))
7280 (message "%s => %s" cmd (eval (read cmd)))
7281 (error "Abort"))))
7284 (browse-url-at-point)))))
7285 (move-marker org-open-link-marker nil)
7286 (run-hook-with-args 'org-follow-link-hook))
7288 ;;;; Time estimates
7290 (defun org-get-effort (&optional pom)
7291 "Get the effort estimate for the current entry."
7292 (org-entry-get pom org-effort-property))
7294 ;;; File search
7296 (defvar org-create-file-search-functions nil
7297 "List of functions to construct the right search string for a file link.
7298 These functions are called in turn with point at the location to
7299 which the link should point.
7301 A function in the hook should first test if it would like to
7302 handle this file type, for example by checking the major-mode or
7303 the file extension. If it decides not to handle this file, it
7304 should just return nil to give other functions a chance. If it
7305 does handle the file, it must return the search string to be used
7306 when following the link. The search string will be part of the
7307 file link, given after a double colon, and `org-open-at-point'
7308 will automatically search for it. If special measures must be
7309 taken to make the search successful, another function should be
7310 added to the companion hook `org-execute-file-search-functions',
7311 which see.
7313 A function in this hook may also use `setq' to set the variable
7314 `description' to provide a suggestion for the descriptive text to
7315 be used for this link when it gets inserted into an Org-mode
7316 buffer with \\[org-insert-link].")
7318 (defvar org-execute-file-search-functions nil
7319 "List of functions to execute a file search triggered by a link.
7321 Functions added to this hook must accept a single argument, the
7322 search string that was part of the file link, the part after the
7323 double colon. The function must first check if it would like to
7324 handle this search, for example by checking the major-mode or the
7325 file extension. If it decides not to handle this search, it
7326 should just return nil to give other functions a chance. If it
7327 does handle the search, it must return a non-nil value to keep
7328 other functions from trying.
7330 Each function can access the current prefix argument through the
7331 variable `current-prefix-argument'. Note that a single prefix is
7332 used to force opening a link in Emacs, so it may be good to only
7333 use a numeric or double prefix to guide the search function.
7335 In case this is needed, a function in this hook can also restore
7336 the window configuration before `org-open-at-point' was called using:
7338 (set-window-configuration org-window-config-before-follow-link)")
7340 (defun org-link-search (s &optional type avoid-pos)
7341 "Search for a link search option.
7342 If S is surrounded by forward slashes, it is interpreted as a
7343 regular expression. In org-mode files, this will create an `org-occur'
7344 sparse tree. In ordinary files, `occur' will be used to list matches.
7345 If the current buffer is in `dired-mode', grep will be used to search
7346 in all files. If AVOID-POS is given, ignore matches near that position."
7347 (let ((case-fold-search t)
7348 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
7349 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
7350 (append '(("") (" ") ("\t") ("\n"))
7351 org-emphasis-alist)
7352 "\\|") "\\)"))
7353 (pos (point))
7354 (pre nil) (post nil)
7355 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
7356 (cond
7357 ;; First check if there are any special
7358 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
7359 ;; Now try the builtin stuff
7360 ((save-excursion
7361 (goto-char (point-min))
7362 (and
7363 (re-search-forward
7364 (concat "<<" (regexp-quote s0) ">>") nil t)
7365 (setq type 'dedicated
7366 pos (match-beginning 0))))
7367 ;; There is an exact target for this
7368 (goto-char pos))
7369 ((string-match "^/\\(.*\\)/$" s)
7370 ;; A regular expression
7371 (cond
7372 ((org-mode-p)
7373 (org-occur (match-string 1 s)))
7374 ;;((eq major-mode 'dired-mode)
7375 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
7376 (t (org-do-occur (match-string 1 s)))))
7378 ;; A normal search strings
7379 (when (equal (string-to-char s) ?*)
7380 ;; Anchor on headlines, post may include tags.
7381 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
7382 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
7383 s (substring s 1)))
7384 (remove-text-properties
7385 0 (length s)
7386 '(face nil mouse-face nil keymap nil fontified nil) s)
7387 ;; Make a series of regular expressions to find a match
7388 (setq words (org-split-string s "[ \n\r\t]+")
7390 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
7391 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
7392 "\\)" markers)
7393 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
7394 re2a (concat "[ \t\r\n]" re2a_)
7395 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
7396 re4 (concat "[^a-zA-Z_]" re4_)
7398 re1 (concat pre re2 post)
7399 re3 (concat pre (if pre re4_ re4) post)
7400 re5 (concat pre ".*" re4)
7401 re2 (concat pre re2)
7402 re2a (concat pre (if pre re2a_ re2a))
7403 re4 (concat pre (if pre re4_ re4))
7404 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
7405 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
7406 re5 "\\)"
7408 (cond
7409 ((eq type 'org-occur) (org-occur reall))
7410 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
7411 (t (goto-char (point-min))
7412 (setq type 'fuzzy)
7413 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
7414 (org-search-not-self 1 re1 nil t)
7415 (org-search-not-self 1 re2 nil t)
7416 (org-search-not-self 1 re2a nil t)
7417 (org-search-not-self 1 re3 nil t)
7418 (org-search-not-self 1 re4 nil t)
7419 (org-search-not-self 1 re5 nil t)
7421 (goto-char (match-beginning 1))
7422 (goto-char pos)
7423 (error "No match")))))
7425 ;; Normal string-search
7426 (goto-char (point-min))
7427 (if (search-forward s nil t)
7428 (goto-char (match-beginning 0))
7429 (error "No match"))))
7430 (and (org-mode-p) (org-show-context 'link-search))
7431 type))
7433 (defun org-search-not-self (group &rest args)
7434 "Execute `re-search-forward', but only accept matches that do not
7435 enclose the position of `org-open-link-marker'."
7436 (let ((m org-open-link-marker))
7437 (catch 'exit
7438 (while (apply 're-search-forward args)
7439 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
7440 (goto-char (match-end group))
7441 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
7442 (> (match-beginning 0) (marker-position m))
7443 (< (match-end 0) (marker-position m)))
7444 (save-match-data
7445 (or (not (org-in-regexp
7446 org-bracket-link-analytic-regexp 1))
7447 (not (match-end 4)) ; no description
7448 (and (<= (match-beginning 4) (point))
7449 (>= (match-end 4) (point))))))
7450 (throw 'exit (point))))))))
7452 (defun org-get-buffer-for-internal-link (buffer)
7453 "Return a buffer to be used for displaying the link target of internal links."
7454 (cond
7455 ((not org-display-internal-link-with-indirect-buffer)
7456 buffer)
7457 ((string-match "(Clone)$" (buffer-name buffer))
7458 (message "Buffer is already a clone, not making another one")
7459 ;; we also do not modify visibility in this case
7460 buffer)
7461 (t ; make a new indirect buffer for displaying the link
7462 (let* ((bn (buffer-name buffer))
7463 (ibn (concat bn "(Clone)"))
7464 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7465 (with-current-buffer ib (org-overview))
7466 ib))))
7468 (defun org-do-occur (regexp &optional cleanup)
7469 "Call the Emacs command `occur'.
7470 If CLEANUP is non-nil, remove the printout of the regular expression
7471 in the *Occur* buffer. This is useful if the regex is long and not useful
7472 to read."
7473 (occur regexp)
7474 (when cleanup
7475 (let ((cwin (selected-window)) win beg end)
7476 (when (setq win (get-buffer-window "*Occur*"))
7477 (select-window win))
7478 (goto-char (point-min))
7479 (when (re-search-forward "match[a-z]+" nil t)
7480 (setq beg (match-end 0))
7481 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7482 (setq end (1- (match-beginning 0)))))
7483 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7484 (goto-char (point-min))
7485 (select-window cwin))))
7487 ;;; The mark ring for links jumps
7489 (defvar org-mark-ring nil
7490 "Mark ring for positions before jumps in Org-mode.")
7491 (defvar org-mark-ring-last-goto nil
7492 "Last position in the mark ring used to go back.")
7493 ;; Fill and close the ring
7494 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7495 (loop for i from 1 to org-mark-ring-length do
7496 (push (make-marker) org-mark-ring))
7497 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7498 org-mark-ring)
7500 (defun org-mark-ring-push (&optional pos buffer)
7501 "Put the current position or POS into the mark ring and rotate it."
7502 (interactive)
7503 (setq pos (or pos (point)))
7504 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7505 (move-marker (car org-mark-ring)
7506 (or pos (point))
7507 (or buffer (current-buffer)))
7508 (message "%s"
7509 (substitute-command-keys
7510 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7512 (defun org-mark-ring-goto (&optional n)
7513 "Jump to the previous position in the mark ring.
7514 With prefix arg N, jump back that many stored positions. When
7515 called several times in succession, walk through the entire ring.
7516 Org-mode commands jumping to a different position in the current file,
7517 or to another Org-mode file, automatically push the old position
7518 onto the ring."
7519 (interactive "p")
7520 (let (p m)
7521 (if (eq last-command this-command)
7522 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7523 (setq p org-mark-ring))
7524 (setq org-mark-ring-last-goto p)
7525 (setq m (car p))
7526 (switch-to-buffer (marker-buffer m))
7527 (goto-char m)
7528 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7530 (defun org-remove-angle-brackets (s)
7531 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7532 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7534 (defun org-add-angle-brackets (s)
7535 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7536 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7538 (defun org-remove-double-quotes (s)
7539 (if (equal (substring s 0 1) "\"") (setq s (substring s 1)))
7540 (if (equal (substring s -1) "\"") (setq s (substring s 0 -1)))
7543 ;;; Following specific links
7545 (defun org-follow-timestamp-link ()
7546 (cond
7547 ((org-at-date-range-p t)
7548 (let ((org-agenda-start-on-weekday)
7549 (t1 (match-string 1))
7550 (t2 (match-string 2)))
7551 (setq t1 (time-to-days (org-time-string-to-time t1))
7552 t2 (time-to-days (org-time-string-to-time t2)))
7553 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7554 ((org-at-timestamp-p t)
7555 (org-agenda-list nil (time-to-days (org-time-string-to-time
7556 (substring (match-string 1) 0 10)))
7558 (t (error "This should not happen"))))
7561 ;;; Following file links
7562 (defvar org-wait nil)
7563 (defun org-open-file (path &optional in-emacs line search)
7564 "Open the file at PATH.
7565 First, this expands any special file name abbreviations. Then the
7566 configuration variable `org-file-apps' is checked if it contains an
7567 entry for this file type, and if yes, the corresponding command is launched.
7568 If no application is found, Emacs simply visits the file.
7569 With optional argument IN-EMACS, Emacs will visit the file.
7570 Optional LINE specifies a line to go to, optional SEARCH a string to
7571 search for. If LINE or SEARCH is given, the file will always be
7572 opened in Emacs.
7573 If the file does not exist, an error is thrown."
7574 (setq in-emacs (or in-emacs line search))
7575 (let* ((file (if (equal path "")
7576 buffer-file-name
7577 (substitute-in-file-name (expand-file-name path))))
7578 (apps (append org-file-apps (org-default-apps)))
7579 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7580 (dirp (if remp nil (file-directory-p file)))
7581 (file (if (and dirp org-open-directory-means-index-dot-org)
7582 (concat (file-name-as-directory file) "index.org")
7583 file))
7584 (dfile (downcase file))
7585 (old-buffer (current-buffer))
7586 (old-pos (point))
7587 (old-mode major-mode)
7588 ext cmd)
7589 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7590 (setq ext (match-string 1 dfile))
7591 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7592 (setq ext (match-string 1 dfile))))
7593 (if in-emacs
7594 (setq cmd 'emacs)
7595 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7596 (and dirp (cdr (assoc 'directory apps)))
7597 (cdr (assoc ext apps))
7598 (cdr (assoc t apps)))))
7599 (when (eq cmd 'mailcap)
7600 (require 'mailcap)
7601 (mailcap-parse-mailcaps)
7602 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7603 (command (mailcap-mime-info mime-type)))
7604 (if (stringp command)
7605 (setq cmd command)
7606 (setq cmd 'emacs))))
7607 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7608 (not (file-exists-p file))
7609 (not org-open-non-existing-files))
7610 (error "No such file: %s" file))
7611 (cond
7612 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7613 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7614 (while (string-match "['\"]%s['\"]" cmd)
7615 (setq cmd (replace-match "%s" t t cmd)))
7616 (while (string-match "%s" cmd)
7617 (setq cmd (replace-match
7618 (save-match-data
7619 (shell-quote-argument
7620 (convert-standard-filename file)))
7621 t t cmd)))
7622 (save-window-excursion
7623 (start-process-shell-command cmd nil cmd)
7624 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7626 ((or (stringp cmd)
7627 (eq cmd 'emacs))
7628 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7629 (widen)
7630 (if line (goto-line line)
7631 (if search (org-link-search search))))
7632 ((consp cmd)
7633 (let ((file (convert-standard-filename file)))
7634 (eval cmd)))
7635 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7636 (and (org-mode-p) (eq old-mode 'org-mode)
7637 (or (not (equal old-buffer (current-buffer)))
7638 (not (equal old-pos (point))))
7639 (org-mark-ring-push old-pos old-buffer))))
7641 (defun org-default-apps ()
7642 "Return the default applications for this operating system."
7643 (cond
7644 ((eq system-type 'darwin)
7645 org-file-apps-defaults-macosx)
7646 ((eq system-type 'windows-nt)
7647 org-file-apps-defaults-windowsnt)
7648 (t org-file-apps-defaults-gnu)))
7650 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7651 (defun org-file-remote-p (file)
7652 "Test whether FILE specifies a location on a remote system.
7653 Return non-nil if the location is indeed remote.
7655 For example, the filename \"/user@host:/foo\" specifies a location
7656 on the system \"/user@host:\"."
7657 (cond ((fboundp 'file-remote-p)
7658 (file-remote-p file))
7659 ((fboundp 'tramp-handle-file-remote-p)
7660 (tramp-handle-file-remote-p file))
7661 ((and (boundp 'ange-ftp-name-format)
7662 (string-match (car ange-ftp-name-format) file))
7664 (t nil)))
7667 ;;;; Refiling
7669 (defun org-get-org-file ()
7670 "Read a filename, with default directory `org-directory'."
7671 (let ((default (or org-default-notes-file remember-data-file)))
7672 (read-file-name (format "File name [%s]: " default)
7673 (file-name-as-directory org-directory)
7674 default)))
7676 (defun org-notes-order-reversed-p ()
7677 "Check if the current file should receive notes in reversed order."
7678 (cond
7679 ((not org-reverse-note-order) nil)
7680 ((eq t org-reverse-note-order) t)
7681 ((not (listp org-reverse-note-order)) nil)
7682 (t (catch 'exit
7683 (let ((all org-reverse-note-order)
7684 entry)
7685 (while (setq entry (pop all))
7686 (if (string-match (car entry) buffer-file-name)
7687 (throw 'exit (cdr entry))))
7688 nil)))))
7690 (defvar org-refile-target-table nil
7691 "The list of refile targets, created by `org-refile'.")
7693 (defvar org-agenda-new-buffers nil
7694 "Buffers created to visit agenda files.")
7696 (defun org-get-refile-targets (&optional default-buffer)
7697 "Produce a table with refile targets."
7698 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7699 targets txt re files f desc descre)
7700 (with-current-buffer (or default-buffer (current-buffer))
7701 (while (setq entry (pop entries))
7702 (setq files (car entry) desc (cdr entry))
7703 (cond
7704 ((null files) (setq files (list (current-buffer))))
7705 ((eq files 'org-agenda-files)
7706 (setq files (org-agenda-files 'unrestricted)))
7707 ((and (symbolp files) (fboundp files))
7708 (setq files (funcall files)))
7709 ((and (symbolp files) (boundp files))
7710 (setq files (symbol-value files))))
7711 (if (stringp files) (setq files (list files)))
7712 (cond
7713 ((eq (car desc) :tag)
7714 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7715 ((eq (car desc) :todo)
7716 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7717 ((eq (car desc) :regexp)
7718 (setq descre (cdr desc)))
7719 ((eq (car desc) :level)
7720 (setq descre (concat "^\\*\\{" (number-to-string
7721 (if org-odd-levels-only
7722 (1- (* 2 (cdr desc)))
7723 (cdr desc)))
7724 "\\}[ \t]")))
7725 ((eq (car desc) :maxlevel)
7726 (setq descre (concat "^\\*\\{1," (number-to-string
7727 (if org-odd-levels-only
7728 (1- (* 2 (cdr desc)))
7729 (cdr desc)))
7730 "\\}[ \t]")))
7731 (t (error "Bad refiling target description %s" desc)))
7732 (while (setq f (pop files))
7733 (save-excursion
7734 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7735 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7736 (save-excursion
7737 (save-restriction
7738 (widen)
7739 (goto-char (point-min))
7740 (while (re-search-forward descre nil t)
7741 (goto-char (point-at-bol))
7742 (when (looking-at org-complex-heading-regexp)
7743 (setq txt (match-string 4)
7744 re (concat "^" (regexp-quote
7745 (buffer-substring (match-beginning 1)
7746 (match-end 4)))))
7747 (if (match-end 5) (setq re (concat re "[ \t]+"
7748 (regexp-quote
7749 (match-string 5)))))
7750 (setq re (concat re "[ \t]*$"))
7751 (when org-refile-use-outline-path
7752 (setq txt (mapconcat 'identity
7753 (append
7754 (if (eq org-refile-use-outline-path 'file)
7755 (list (file-name-nondirectory
7756 (buffer-file-name (buffer-base-buffer))))
7757 (if (eq org-refile-use-outline-path 'full-file-path)
7758 (list (buffer-file-name (buffer-base-buffer)))))
7759 (org-get-outline-path)
7760 (list txt))
7761 "/")))
7762 (push (list txt f re (point)) targets))
7763 (goto-char (point-at-eol))))))))
7764 (nreverse targets))))
7766 (defun org-get-outline-path ()
7767 "Return the outline path to the current entry, as a list."
7768 (let (rtn)
7769 (save-excursion
7770 (while (org-up-heading-safe)
7771 (when (looking-at org-complex-heading-regexp)
7772 (push (org-match-string-no-properties 4) rtn)))
7773 rtn)))
7775 (defvar org-refile-history nil
7776 "History for refiling operations.")
7778 (defun org-refile (&optional goto default-buffer)
7779 "Move the entry at point to another heading.
7780 The list of target headings is compiled using the information in
7781 `org-refile-targets', which see. This list is created before each use
7782 and will therefore always be up-to-date.
7784 At the target location, the entry is filed as a subitem of the target heading.
7785 Depending on `org-reverse-note-order', the new subitem will either be the
7786 first of the last subitem.
7788 With prefix arg GOTO, the command will only visit the target location,
7789 not actually move anything.
7790 With a double prefix `C-c C-c', go to the location where the last refiling
7791 operation has put the subtree."
7792 (interactive "P")
7793 (let* ((cbuf (current-buffer))
7794 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7795 pos it nbuf file re level reversed)
7796 (if (equal goto '(16))
7797 (org-refile-goto-last-stored)
7798 (when (setq it (org-refile-get-location
7799 (if goto "Goto: " "Refile to: ") default-buffer))
7800 (setq file (nth 1 it)
7801 re (nth 2 it)
7802 pos (nth 3 it))
7803 (setq nbuf (or (find-buffer-visiting file)
7804 (find-file-noselect file)))
7805 (if goto
7806 (progn
7807 (switch-to-buffer nbuf)
7808 (goto-char pos)
7809 (org-show-context 'org-goto))
7810 (org-copy-subtree 1 nil t)
7811 (save-excursion
7812 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7813 (find-file-noselect file))))
7814 (setq reversed (org-notes-order-reversed-p))
7815 (save-excursion
7816 (save-restriction
7817 (widen)
7818 (goto-char pos)
7819 (looking-at outline-regexp)
7820 (setq level (org-get-valid-level (funcall outline-level) 1))
7821 (goto-char
7822 (if reversed
7823 (outline-next-heading)
7824 (or (save-excursion (outline-get-next-sibling))
7825 (org-end-of-subtree t t)
7826 (point-max))))
7827 (bookmark-set "org-refile-last-stored")
7828 (org-paste-subtree level))))
7829 (org-cut-subtree)
7830 (setq org-markers-to-move nil)
7831 (message "Entry refiled to \"%s\"" (car it)))))))
7833 (defun org-refile-goto-last-stored ()
7834 "Go to the location where the last refile was stored."
7835 (interactive)
7836 (bookmark-jump "org-refile-last-stored")
7837 (message "This is the location of the last refile"))
7839 (defun org-refile-get-location (&optional prompt default-buffer)
7840 "Prompt the user for a refile location, using PROMPT."
7841 (let ((org-refile-targets org-refile-targets)
7842 (org-refile-use-outline-path org-refile-use-outline-path))
7843 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7844 (unless org-refile-target-table
7845 (error "No refile targets"))
7846 (let* ((cbuf (current-buffer))
7847 (cfunc (if org-refile-use-outline-path
7848 'org-olpath-completing-read
7849 'completing-read))
7850 (extra (if org-refile-use-outline-path "/" ""))
7851 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7852 (fname (and filename (file-truename filename)))
7853 (tbl (mapcar
7854 (lambda (x)
7855 (if (not (equal fname (file-truename (nth 1 x))))
7856 (cons (concat (car x) extra " ("
7857 (file-name-nondirectory (nth 1 x)) ")")
7858 (cdr x))
7859 (cons (concat (car x) extra) (cdr x))))
7860 org-refile-target-table))
7861 (completion-ignore-case t))
7862 (assoc (funcall cfunc prompt tbl nil t nil 'org-refile-history)
7863 tbl)))
7865 (defun org-olpath-completing-read (prompt collection &rest args)
7866 "Read an outline path like a file name."
7867 (let ((thetable collection))
7868 (apply
7869 'completing-read prompt
7870 (lambda (string predicate &optional flag)
7871 (let (rtn r s f (l (length string)))
7872 (cond
7873 ((eq flag nil)
7874 ;; try completion
7875 (try-completion string thetable))
7876 ((eq flag t)
7877 ;; all-completions
7878 (setq rtn (all-completions string thetable predicate))
7879 (mapcar
7880 (lambda (x)
7881 (setq r (substring x l))
7882 (if (string-match " ([^)]*)$" x)
7883 (setq f (match-string 0 x))
7884 (setq f ""))
7885 (if (string-match "/" r)
7886 (concat string (substring r 0 (match-end 0)) f)
7888 rtn))
7889 ((eq flag 'lambda)
7890 ;; exact match?
7891 (assoc string thetable)))
7893 args)))
7895 ;;;; Dynamic blocks
7897 (defun org-find-dblock (name)
7898 "Find the first dynamic block with name NAME in the buffer.
7899 If not found, stay at current position and return nil."
7900 (let (pos)
7901 (save-excursion
7902 (goto-char (point-min))
7903 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7904 nil t)
7905 (match-beginning 0))))
7906 (if pos (goto-char pos))
7907 pos))
7909 (defconst org-dblock-start-re
7910 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7911 "Matches the startline of a dynamic block, with parameters.")
7913 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7914 "Matches the end of a dyhamic block.")
7916 (defun org-create-dblock (plist)
7917 "Create a dynamic block section, with parameters taken from PLIST.
7918 PLIST must containe a :name entry which is used as name of the block."
7919 (unless (bolp) (newline))
7920 (let ((name (plist-get plist :name)))
7921 (insert "#+BEGIN: " name)
7922 (while plist
7923 (if (eq (car plist) :name)
7924 (setq plist (cddr plist))
7925 (insert " " (prin1-to-string (pop plist)))))
7926 (insert "\n\n#+END:\n")
7927 (beginning-of-line -2)))
7929 (defun org-prepare-dblock ()
7930 "Prepare dynamic block for refresh.
7931 This empties the block, puts the cursor at the insert position and returns
7932 the property list including an extra property :name with the block name."
7933 (unless (looking-at org-dblock-start-re)
7934 (error "Not at a dynamic block"))
7935 (let* ((begdel (1+ (match-end 0)))
7936 (name (org-no-properties (match-string 1)))
7937 (params (append (list :name name)
7938 (read (concat "(" (match-string 3) ")")))))
7939 (unless (re-search-forward org-dblock-end-re nil t)
7940 (error "Dynamic block not terminated"))
7941 (setq params
7942 (append params
7943 (list :content (buffer-substring
7944 begdel (match-beginning 0)))))
7945 (delete-region begdel (match-beginning 0))
7946 (goto-char begdel)
7947 (open-line 1)
7948 params))
7950 (defun org-map-dblocks (&optional command)
7951 "Apply COMMAND to all dynamic blocks in the current buffer.
7952 If COMMAND is not given, use `org-update-dblock'."
7953 (let ((cmd (or command 'org-update-dblock))
7954 pos)
7955 (save-excursion
7956 (goto-char (point-min))
7957 (while (re-search-forward org-dblock-start-re nil t)
7958 (goto-char (setq pos (match-beginning 0)))
7959 (condition-case nil
7960 (funcall cmd)
7961 (error (message "Error during update of dynamic block")))
7962 (goto-char pos)
7963 (unless (re-search-forward org-dblock-end-re nil t)
7964 (error "Dynamic block not terminated"))))))
7966 (defun org-dblock-update (&optional arg)
7967 "User command for updating dynamic blocks.
7968 Update the dynamic block at point. With prefix ARG, update all dynamic
7969 blocks in the buffer."
7970 (interactive "P")
7971 (if arg
7972 (org-update-all-dblocks)
7973 (or (looking-at org-dblock-start-re)
7974 (org-beginning-of-dblock))
7975 (org-update-dblock)))
7977 (defun org-update-dblock ()
7978 "Update the dynamic block at point
7979 This means to empty the block, parse for parameters and then call
7980 the correct writing function."
7981 (save-window-excursion
7982 (let* ((pos (point))
7983 (line (org-current-line))
7984 (params (org-prepare-dblock))
7985 (name (plist-get params :name))
7986 (cmd (intern (concat "org-dblock-write:" name))))
7987 (message "Updating dynamic block `%s' at line %d..." name line)
7988 (funcall cmd params)
7989 (message "Updating dynamic block `%s' at line %d...done" name line)
7990 (goto-char pos))))
7992 (defun org-beginning-of-dblock ()
7993 "Find the beginning of the dynamic block at point.
7994 Error if there is no scuh block at point."
7995 (let ((pos (point))
7996 beg)
7997 (end-of-line 1)
7998 (if (and (re-search-backward org-dblock-start-re nil t)
7999 (setq beg (match-beginning 0))
8000 (re-search-forward org-dblock-end-re nil t)
8001 (> (match-end 0) pos))
8002 (goto-char beg)
8003 (goto-char pos)
8004 (error "Not in a dynamic block"))))
8006 (defun org-update-all-dblocks ()
8007 "Update all dynamic blocks in the buffer.
8008 This function can be used in a hook."
8009 (when (org-mode-p)
8010 (org-map-dblocks 'org-update-dblock)))
8013 ;;;; Completion
8015 (defconst org-additional-option-like-keywords
8016 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
8017 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
8018 "BEGIN_EXAMPLE" "END_EXAMPLE"))
8020 (defcustom org-structure-template-alist
8022 ("s" "#+begin_src ?\n\n#+end_src"
8023 "<src lang=\"?\">\n\n</src>")
8024 ("e" "#+begin_example\n?\n#+end_example"
8025 "<example>\n?\n</example>")
8026 ("q" "#+begin_quote\n?\n#+end_quote"
8027 "<quote>\n?\n</quote>")
8028 ("v" "#+begin_verse\n?\n#+end_verse"
8029 "<verse>\n?\n/verse>")
8030 ("l" "#+begin_latex\n?\n#+end_latex"
8031 "<literal style=\"latex\">\n?\n</literal>")
8032 ("L" "#+latex: "
8033 "<literal style=\"latex\">?</literal>")
8034 ("h" "#+begin_html\n?\n#+end_html"
8035 "<literal style=\"html\">\n?\n</literal>")
8036 ("H" "#+html: "
8037 "<literal style=\"html\">?</literal>")
8038 ("a" "#+begin_ascii\n?\n#+end_ascii")
8039 ("A" "#+ascii: ")
8040 ("i" "#+include %file ?"
8041 "<include file=%file markup=\"?\">")
8043 "Structure completion elements.
8044 This is a list of abbreviation keys and values. The value gets inserted
8045 it you type @samp{.} followed by the key and then the completion key,
8046 usually `M-TAB'. %file will be replaced by a file name after prompting
8047 for the file uning completion.
8048 There are two templates for each key, the first uses the original Org syntax,
8049 the second uses Emacs Muse-like syntax tags. These Muse-like tags become
8050 the default when the /org-mtags.el/ module has been loaded. See also the
8051 variable `org-mtags-prefere-muse-templates'.
8052 This is an experimental feature, it is undecided if it is going to stay in."
8053 :group 'org-completion
8054 :type '(repeat
8055 (string :tag "Key")
8056 (string :tag "Template")
8057 (string :tag "Muse Template")))
8059 (defun org-try-structure-completion ()
8060 "Try to complete a structure template before point.
8061 This looks for strings like \"<e\" on an otherwise empty line and
8062 expands them."
8063 (let ((l (buffer-substring (point-at-bol) (point)))
8065 (when (and (looking-at "[ \t]*$")
8066 (string-match "^[ \t]*<\\([a-z]+\\)$"l)
8067 (setq a (assoc (match-string 1 l) org-structure-template-alist)))
8068 (org-complete-expand-structure-template (+ -1 (point-at-bol)
8069 (match-beginning 1)) a)
8070 t)))
8072 (defun org-complete-expand-structure-template (start cell)
8073 "Expand a structure template."
8074 (let* ((musep (org-bound-and-true-p org-mtags-prefere-muse-templates))
8075 (rpl (nth (if musep 2 1) cell)))
8076 (delete-region start (point))
8077 (when (string-match "\\`#\\+" rpl)
8078 (cond
8079 ((bolp))
8080 ((not (string-match "\\S-" (buffer-substring (point-at-bol) (point))))
8081 (delete-region (point-at-bol) (point)))
8082 (t (newline))))
8083 (setq start (point))
8084 (if (string-match "%file" rpl)
8085 (setq rpl (replace-match
8086 (concat
8087 "\""
8088 (save-match-data
8089 (abbreviate-file-name (read-file-name "Include file: ")))
8090 "\"")
8091 t t rpl)))
8092 (insert rpl)
8093 (if (re-search-backward "\\?" start t) (delete-char 1))))
8096 (defun org-complete (&optional arg)
8097 "Perform completion on word at point.
8098 At the beginning of a headline, this completes TODO keywords as given in
8099 `org-todo-keywords'.
8100 If the current word is preceded by a backslash, completes the TeX symbols
8101 that are supported for HTML support.
8102 If the current word is preceded by \"#+\", completes special words for
8103 setting file options.
8104 In the line after \"#+STARTUP:, complete valid keywords.\"
8105 At all other locations, this simply calls the value of
8106 `org-completion-fallback-command'."
8107 (interactive "P")
8108 (org-without-partial-completion
8109 (catch 'exit
8110 (let* ((a nil)
8111 (end (point))
8112 (beg1 (save-excursion
8113 (skip-chars-backward (org-re "[:alnum:]_@"))
8114 (point)))
8115 (beg (save-excursion
8116 (skip-chars-backward "a-zA-Z0-9_:$")
8117 (point)))
8118 (confirm (lambda (x) (stringp (car x))))
8119 (searchhead (equal (char-before beg) ?*))
8120 (struct
8121 (when (and (member (char-before beg1) '(?. ?<))
8122 (setq a (assoc (buffer-substring beg1 (point))
8123 org-structure-template-alist)))
8124 (org-complete-expand-structure-template (1- beg1) a)
8125 (throw 'exit t)))
8126 (tag (and (equal (char-before beg1) ?:)
8127 (equal (char-after (point-at-bol)) ?*)))
8128 (prop (and (equal (char-before beg1) ?:)
8129 (not (equal (char-after (point-at-bol)) ?*))))
8130 (texp (equal (char-before beg) ?\\))
8131 (link (equal (char-before beg) ?\[))
8132 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
8133 beg)
8134 "#+"))
8135 (startup (string-match "^#\\+STARTUP:.*"
8136 (buffer-substring (point-at-bol) (point))))
8137 (completion-ignore-case opt)
8138 (type nil)
8139 (tbl nil)
8140 (table (cond
8141 (opt
8142 (setq type :opt)
8143 (require 'org-exp)
8144 (append
8145 (mapcar
8146 (lambda (x)
8147 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
8148 (cons (match-string 2 x) (match-string 1 x)))
8149 (org-split-string (org-get-current-options) "\n"))
8150 (mapcar 'list org-additional-option-like-keywords)))
8151 (startup
8152 (setq type :startup)
8153 org-startup-options)
8154 (link (append org-link-abbrev-alist-local
8155 org-link-abbrev-alist))
8156 (texp
8157 (setq type :tex)
8158 org-html-entities)
8159 ((string-match "\\`\\*+[ \t]+\\'"
8160 (buffer-substring (point-at-bol) beg))
8161 (setq type :todo)
8162 (mapcar 'list org-todo-keywords-1))
8163 (searchhead
8164 (setq type :searchhead)
8165 (save-excursion
8166 (goto-char (point-min))
8167 (while (re-search-forward org-todo-line-regexp nil t)
8168 (push (list
8169 (org-make-org-heading-search-string
8170 (match-string 3) t))
8171 tbl)))
8172 tbl)
8173 (tag (setq type :tag beg beg1)
8174 (or org-tag-alist (org-get-buffer-tags)))
8175 (prop (setq type :prop beg beg1)
8176 (mapcar 'list (org-buffer-property-keys nil t t)))
8177 (t (progn
8178 (call-interactively org-completion-fallback-command)
8179 (throw 'exit nil)))))
8180 (pattern (buffer-substring-no-properties beg end))
8181 (completion (try-completion pattern table confirm)))
8182 (cond ((eq completion t)
8183 (if (not (assoc (upcase pattern) table))
8184 (message "Already complete")
8185 (if (and (equal type :opt)
8186 (not (member (car (assoc (upcase pattern) table))
8187 org-additional-option-like-keywords)))
8188 (insert (substring (cdr (assoc (upcase pattern) table))
8189 (length pattern)))
8190 (if (memq type '(:tag :prop)) (insert ":")))))
8191 ((null completion)
8192 (message "Can't find completion for \"%s\"" pattern)
8193 (ding))
8194 ((not (string= pattern completion))
8195 (delete-region beg end)
8196 (if (string-match " +$" completion)
8197 (setq completion (replace-match "" t t completion)))
8198 (insert completion)
8199 (if (get-buffer-window "*Completions*")
8200 (delete-window (get-buffer-window "*Completions*")))
8201 (if (assoc completion table)
8202 (if (eq type :todo) (insert " ")
8203 (if (memq type '(:tag :prop)) (insert ":"))))
8204 (if (and (equal type :opt) (assoc completion table))
8205 (message "%s" (substitute-command-keys
8206 "Press \\[org-complete] again to insert example settings"))))
8208 (message "Making completion list...")
8209 (let ((list (sort (all-completions pattern table confirm)
8210 'string<)))
8211 (with-output-to-temp-buffer "*Completions*"
8212 (condition-case nil
8213 ;; Protection needed for XEmacs and emacs 21
8214 (display-completion-list list pattern)
8215 (error (display-completion-list list)))))
8216 (message "Making completion list...%s" "done")))))))
8218 ;;;; TODO, DEADLINE, Comments
8220 (defun org-toggle-comment ()
8221 "Change the COMMENT state of an entry."
8222 (interactive)
8223 (save-excursion
8224 (org-back-to-heading)
8225 (let (case-fold-search)
8226 (if (looking-at (concat outline-regexp
8227 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
8228 (replace-match "" t t nil 1)
8229 (if (looking-at outline-regexp)
8230 (progn
8231 (goto-char (match-end 0))
8232 (insert org-comment-string " ")))))))
8234 (defvar org-last-todo-state-is-todo nil
8235 "This is non-nil when the last TODO state change led to a TODO state.
8236 If the last change removed the TODO tag or switched to DONE, then
8237 this is nil.")
8239 (defvar org-setting-tags nil) ; dynamically skiped
8241 (defun org-parse-local-options (string var)
8242 "Parse STRING for startup setting relevant for variable VAR."
8243 (let ((rtn (symbol-value var))
8244 e opts)
8245 (save-match-data
8246 (if (or (not string) (not (string-match "\\S-" string)))
8248 (setq opts (delq nil (mapcar (lambda (x)
8249 (setq e (assoc x org-startup-options))
8250 (if (eq (nth 1 e) var) e nil))
8251 (org-split-string string "[ \t]+"))))
8252 (if (not opts)
8254 (setq rtn nil)
8255 (while (setq e (pop opts))
8256 (if (not (nth 3 e))
8257 (setq rtn (nth 2 e))
8258 (if (not (listp rtn)) (setq rtn nil))
8259 (push (nth 2 e) rtn)))
8260 rtn)))))
8262 (defvar org-blocker-hook nil
8263 "Hook for functions that are allowed to block a state change.
8265 Each function gets as its single argument a property list, see
8266 `org-trigger-hook' for more information about this list.
8268 If any of the functions in this hook returns nil, the state change
8269 is blocked.")
8271 (defvar org-trigger-hook nil
8272 "Hook for functions that are triggered by a state change.
8274 Each function gets as its single argument a property list with at least
8275 the following elements:
8277 (:type type-of-change :position pos-at-entry-start
8278 :from old-state :to new-state)
8280 Depending on the type, more properties may be present.
8282 This mechanism is currently implemented for:
8284 TODO state changes
8285 ------------------
8286 :type todo-state-change
8287 :from previous state (keyword as a string), or nil
8288 :to new state (keyword as a string), or nil")
8291 (defun org-todo (&optional arg)
8292 "Change the TODO state of an item.
8293 The state of an item is given by a keyword at the start of the heading,
8294 like
8295 *** TODO Write paper
8296 *** DONE Call mom
8298 The different keywords are specified in the variable `org-todo-keywords'.
8299 By default the available states are \"TODO\" and \"DONE\".
8300 So for this example: when the item starts with TODO, it is changed to DONE.
8301 When it starts with DONE, the DONE is removed. And when neither TODO nor
8302 DONE are present, add TODO at the beginning of the heading.
8304 With C-u prefix arg, use completion to determine the new state.
8305 With numeric prefix arg, switch to that state.
8307 For calling through lisp, arg is also interpreted in the following way:
8308 'none -> empty state
8309 \"\"(empty string) -> switch to empty state
8310 'done -> switch to DONE
8311 'nextset -> switch to the next set of keywords
8312 'previousset -> switch to the previous set of keywords
8313 \"WAITING\" -> switch to the specified keyword, but only if it
8314 really is a member of `org-todo-keywords'."
8315 (interactive "P")
8316 (save-excursion
8317 (catch 'exit
8318 (org-back-to-heading)
8319 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
8320 (or (looking-at (concat " +" org-todo-regexp " *"))
8321 (looking-at " *"))
8322 (let* ((match-data (match-data))
8323 (startpos (point-at-bol))
8324 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
8325 (org-log-done org-log-done)
8326 (org-log-repeat org-log-repeat)
8327 (org-todo-log-states org-todo-log-states)
8328 (this (match-string 1))
8329 (hl-pos (match-beginning 0))
8330 (head (org-get-todo-sequence-head this))
8331 (ass (assoc head org-todo-kwd-alist))
8332 (interpret (nth 1 ass))
8333 (done-word (nth 3 ass))
8334 (final-done-word (nth 4 ass))
8335 (last-state (or this ""))
8336 (completion-ignore-case t)
8337 (member (member this org-todo-keywords-1))
8338 (tail (cdr member))
8339 (state (cond
8340 ((and org-todo-key-trigger
8341 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
8342 (and (not arg) org-use-fast-todo-selection
8343 (not (eq org-use-fast-todo-selection 'prefix)))))
8344 ;; Use fast selection
8345 (org-fast-todo-selection))
8346 ((and (equal arg '(4))
8347 (or (not org-use-fast-todo-selection)
8348 (not org-todo-key-trigger)))
8349 ;; Read a state with completion
8350 (completing-read "State: " (mapcar (lambda(x) (list x))
8351 org-todo-keywords-1)
8352 nil t))
8353 ((eq arg 'right)
8354 (if this
8355 (if tail (car tail) nil)
8356 (car org-todo-keywords-1)))
8357 ((eq arg 'left)
8358 (if (equal member org-todo-keywords-1)
8360 (if this
8361 (nth (- (length org-todo-keywords-1) (length tail) 2)
8362 org-todo-keywords-1)
8363 (org-last org-todo-keywords-1))))
8364 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
8365 (setq arg nil))) ; hack to fall back to cycling
8366 (arg
8367 ;; user or caller requests a specific state
8368 (cond
8369 ((equal arg "") nil)
8370 ((eq arg 'none) nil)
8371 ((eq arg 'done) (or done-word (car org-done-keywords)))
8372 ((eq arg 'nextset)
8373 (or (car (cdr (member head org-todo-heads)))
8374 (car org-todo-heads)))
8375 ((eq arg 'previousset)
8376 (let ((org-todo-heads (reverse org-todo-heads)))
8377 (or (car (cdr (member head org-todo-heads)))
8378 (car org-todo-heads))))
8379 ((car (member arg org-todo-keywords-1)))
8380 ((nth (1- (prefix-numeric-value arg))
8381 org-todo-keywords-1))))
8382 ((null member) (or head (car org-todo-keywords-1)))
8383 ((equal this final-done-word) nil) ;; -> make empty
8384 ((null tail) nil) ;; -> first entry
8385 ((eq interpret 'sequence)
8386 (car tail))
8387 ((memq interpret '(type priority))
8388 (if (eq this-command last-command)
8389 (car tail)
8390 (if (> (length tail) 0)
8391 (or done-word (car org-done-keywords))
8392 nil)))
8393 (t nil)))
8394 (next (if state (concat " " state " ") " "))
8395 (change-plist (list :type 'todo-state-change :from this :to state
8396 :position startpos))
8397 dolog now-done-p)
8398 (when org-blocker-hook
8399 (unless (save-excursion
8400 (save-match-data
8401 (run-hook-with-args-until-failure
8402 'org-blocker-hook change-plist)))
8403 (if (interactive-p)
8404 (error "TODO state change from %s to %s blocked" this state)
8405 ;; fail silently
8406 (message "TODO state change from %s to %s blocked" this state)
8407 (throw 'exit nil))))
8408 (store-match-data match-data)
8409 (replace-match next t t)
8410 (unless (pos-visible-in-window-p hl-pos)
8411 (message "TODO state changed to %s" (org-trim next)))
8412 (unless head
8413 (setq head (org-get-todo-sequence-head state)
8414 ass (assoc head org-todo-kwd-alist)
8415 interpret (nth 1 ass)
8416 done-word (nth 3 ass)
8417 final-done-word (nth 4 ass)))
8418 (when (memq arg '(nextset previousset))
8419 (message "Keyword-Set %d/%d: %s"
8420 (- (length org-todo-sets) -1
8421 (length (memq (assoc state org-todo-sets) org-todo-sets)))
8422 (length org-todo-sets)
8423 (mapconcat 'identity (assoc state org-todo-sets) " ")))
8424 (setq org-last-todo-state-is-todo
8425 (not (member state org-done-keywords)))
8426 (setq now-done-p (and (member state org-done-keywords)
8427 (not (member this org-done-keywords))))
8428 (and logging (org-local-logging logging))
8429 (when (and (or org-todo-log-states org-log-done)
8430 (not (memq arg '(nextset previousset))))
8431 ;; we need to look at recording a time and note
8432 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
8433 (nth 2 (assoc this org-todo-log-states))))
8434 (when (and state
8435 (member state org-not-done-keywords)
8436 (not (member this org-not-done-keywords)))
8437 ;; This is now a todo state and was not one before
8438 ;; If there was a CLOSED time stamp, get rid of it.
8439 (org-add-planning-info nil nil 'closed))
8440 (when (and now-done-p org-log-done)
8441 ;; It is now done, and it was not done before
8442 (org-add-planning-info 'closed (org-current-time))
8443 (if (and (not dolog) (eq 'note org-log-done))
8444 (org-add-log-setup 'done state 'findpos 'note)))
8445 (when (and state dolog)
8446 ;; This is a non-nil state, and we need to log it
8447 (org-add-log-setup 'state state 'findpos dolog)))
8448 ;; Fixup tag positioning
8449 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
8450 (when org-provide-todo-statistics
8451 (org-update-parent-todo-statistics))
8452 (run-hooks 'org-after-todo-state-change-hook)
8453 (if (and arg (not (member state org-done-keywords)))
8454 (setq head (org-get-todo-sequence-head state)))
8455 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
8456 ;; Do we need to trigger a repeat?
8457 (when now-done-p (org-auto-repeat-maybe state))
8458 ;; Fixup cursor location if close to the keyword
8459 (if (and (outline-on-heading-p)
8460 (not (bolp))
8461 (save-excursion (beginning-of-line 1)
8462 (looking-at org-todo-line-regexp))
8463 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
8464 (progn
8465 (goto-char (or (match-end 2) (match-end 1)))
8466 (just-one-space)))
8467 (when org-trigger-hook
8468 (save-excursion
8469 (run-hook-with-args 'org-trigger-hook change-plist)))))))
8471 (defun org-update-parent-todo-statistics ()
8472 "Update any statistics cookie in the parent of the current headline."
8473 (interactive)
8474 (let ((box-re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
8475 level (cnt-all 0) (cnt-done 0) is-percent kwd)
8476 (catch 'exit
8477 (save-excursion
8478 (setq level (org-up-heading-safe))
8479 (unless (and level
8480 (re-search-forward box-re (point-at-eol) t))
8481 (throw 'exit nil))
8482 (setq is-percent (match-end 2))
8483 (save-match-data
8484 (unless (outline-next-heading) (throw 'exit nil))
8485 (while (looking-at org-todo-line-regexp)
8486 (setq kwd (match-string 2))
8487 (and kwd (setq cnt-all (1+ cnt-all)))
8488 (and (member kwd org-done-keywords)
8489 (setq cnt-done (1+ cnt-done)))
8490 (condition-case nil
8491 (outline-forward-same-level 1)
8492 (error (end-of-line 1)))))
8493 (replace-match
8494 (if is-percent
8495 (format "[%d%%]" (/ (* 100 cnt-done) (max 1 cnt-all)))
8496 (format "[%d/%d]" cnt-done cnt-all)))
8497 (run-hook-with-args 'org-after-todo-statistics-hook
8498 cnt-done (- cnt-all cnt-done))))))
8500 (defvar org-after-todo-statistics-hook nil
8501 "Hook that is called after a TODO statistics cookie has been updated.
8502 Each function is called with two arguments: the number of not-done entries
8503 and the number of done entries.
8505 For example, the following function, when added to this hook, will switch
8506 an entry to DONE when all children are done, and back to TODO when new
8507 entries are set to a TODO status. Note that this hook is only called
8508 when there is a statistics cookie in the headline!
8510 (defun org-summary-todo (n-done n-not-done)
8511 \"Switch entry to DONE when all subentries are done, to TODO otherwise.\"
8512 (let (org-log-done org-log-states) ; turn off logging
8513 (org-todo (if (= n-not-done 0) \"DONE\" \"TODO\"))))
8516 (defun org-local-logging (value)
8517 "Get logging settings from a property VALUE."
8518 (let* (words w a)
8519 ;; directly set the variables, they are already local.
8520 (setq org-log-done nil
8521 org-log-repeat nil
8522 org-todo-log-states nil)
8523 (setq words (org-split-string value))
8524 (while (setq w (pop words))
8525 (cond
8526 ((setq a (assoc w org-startup-options))
8527 (and (member (nth 1 a) '(org-log-done org-log-repeat))
8528 (set (nth 1 a) (nth 2 a))))
8529 ((setq a (org-extract-log-state-settings w))
8530 (and (member (car a) org-todo-keywords-1)
8531 (push a org-todo-log-states)))))))
8533 (defun org-get-todo-sequence-head (kwd)
8534 "Return the head of the TODO sequence to which KWD belongs.
8535 If KWD is not set, check if there is a text property remembering the
8536 right sequence."
8537 (let (p)
8538 (cond
8539 ((not kwd)
8540 (or (get-text-property (point-at-bol) 'org-todo-head)
8541 (progn
8542 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
8543 nil (point-at-eol)))
8544 (get-text-property p 'org-todo-head))))
8545 ((not (member kwd org-todo-keywords-1))
8546 (car org-todo-keywords-1))
8547 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
8549 (defun org-fast-todo-selection ()
8550 "Fast TODO keyword selection with single keys.
8551 Returns the new TODO keyword, or nil if no state change should occur."
8552 (let* ((fulltable org-todo-key-alist)
8553 (done-keywords org-done-keywords) ;; needed for the faces.
8554 (maxlen (apply 'max (mapcar
8555 (lambda (x)
8556 (if (stringp (car x)) (string-width (car x)) 0))
8557 fulltable)))
8558 (expert nil)
8559 (fwidth (+ maxlen 3 1 3))
8560 (ncol (/ (- (window-width) 4) fwidth))
8561 tg cnt e c tbl
8562 groups ingroup)
8563 (save-window-excursion
8564 (if expert
8565 (set-buffer (get-buffer-create " *Org todo*"))
8566 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
8567 (erase-buffer)
8568 (org-set-local 'org-done-keywords done-keywords)
8569 (setq tbl fulltable cnt 0)
8570 (while (setq e (pop tbl))
8571 (cond
8572 ((equal e '(:startgroup))
8573 (push '() groups) (setq ingroup t)
8574 (when (not (= cnt 0))
8575 (setq cnt 0)
8576 (insert "\n"))
8577 (insert "{ "))
8578 ((equal e '(:endgroup))
8579 (setq ingroup nil cnt 0)
8580 (insert "}\n"))
8582 (setq tg (car e) c (cdr e))
8583 (if ingroup (push tg (car groups)))
8584 (setq tg (org-add-props tg nil 'face
8585 (org-get-todo-face tg)))
8586 (if (and (= cnt 0) (not ingroup)) (insert " "))
8587 (insert "[" c "] " tg (make-string
8588 (- fwidth 4 (length tg)) ?\ ))
8589 (when (= (setq cnt (1+ cnt)) ncol)
8590 (insert "\n")
8591 (if ingroup (insert " "))
8592 (setq cnt 0)))))
8593 (insert "\n")
8594 (goto-char (point-min))
8595 (if (and (not expert) (fboundp 'fit-window-to-buffer))
8596 (fit-window-to-buffer))
8597 (message "[a-z..]:Set [SPC]:clear")
8598 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
8599 (cond
8600 ((or (= c ?\C-g)
8601 (and (= c ?q) (not (rassoc c fulltable))))
8602 (setq quit-flag t))
8603 ((= c ?\ ) nil)
8604 ((setq e (rassoc c fulltable) tg (car e))
8606 (t (setq quit-flag t))))))
8608 (defun org-entry-is-todo-p ()
8609 (member (org-get-todo-state) org-not-done-keywords))
8611 (defun org-entry-is-done-p ()
8612 (member (org-get-todo-state) org-done-keywords))
8614 (defun org-get-todo-state ()
8615 (save-excursion
8616 (org-back-to-heading t)
8617 (and (looking-at org-todo-line-regexp)
8618 (match-end 2)
8619 (match-string 2))))
8621 (defun org-at-date-range-p (&optional inactive-ok)
8622 "Is the cursor inside a date range?"
8623 (interactive)
8624 (save-excursion
8625 (catch 'exit
8626 (let ((pos (point)))
8627 (skip-chars-backward "^[<\r\n")
8628 (skip-chars-backward "<[")
8629 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8630 (>= (match-end 0) pos)
8631 (throw 'exit t))
8632 (skip-chars-backward "^<[\r\n")
8633 (skip-chars-backward "<[")
8634 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8635 (>= (match-end 0) pos)
8636 (throw 'exit t)))
8637 nil)))
8639 (defun org-get-repeat ()
8640 "Check if there is a deadline/schedule with repeater in this entry."
8641 (save-match-data
8642 (save-excursion
8643 (org-back-to-heading t)
8644 (if (re-search-forward
8645 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8646 (match-string 1)))))
8648 (defvar org-last-changed-timestamp)
8649 (defvar org-last-inserted-timestamp)
8650 (defvar org-log-post-message)
8651 (defvar org-log-note-purpose)
8652 (defvar org-log-note-how)
8653 (defun org-auto-repeat-maybe (done-word)
8654 "Check if the current headline contains a repeated deadline/schedule.
8655 If yes, set TODO state back to what it was and change the base date
8656 of repeating deadline/scheduled time stamps to new date.
8657 This function is run automatically after each state change to a DONE state."
8658 ;; last-state is dynamically scoped into this function
8659 (let* ((repeat (org-get-repeat))
8660 (aa (assoc last-state org-todo-kwd-alist))
8661 (interpret (nth 1 aa))
8662 (head (nth 2 aa))
8663 (whata '(("d" . day) ("m" . month) ("y" . year)))
8664 (msg "Entry repeats: ")
8665 (org-log-done nil)
8666 (org-todo-log-states nil)
8667 (nshiftmax 10) (nshift 0)
8668 re type n what ts mb0 time)
8669 (when repeat
8670 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8671 (org-todo (if (eq interpret 'type) last-state head))
8672 (when org-log-repeat
8673 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8674 (memq 'org-add-log-note post-command-hook))
8675 ;; OK, we are already setup for some record
8676 (if (eq org-log-repeat 'note)
8677 ;; make sure we take a note, not only a time stamp
8678 (setq org-log-note-how 'note))
8679 ;; Set up for taking a record
8680 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8681 'findpos org-log-repeat)))
8682 (org-back-to-heading t)
8683 (org-add-planning-info nil nil 'closed)
8684 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8685 org-deadline-time-regexp "\\)\\|\\("
8686 org-ts-regexp "\\)"))
8687 (while (re-search-forward
8688 re (save-excursion (outline-next-heading) (point)) t)
8689 (setq type (if (match-end 1) org-scheduled-string
8690 (if (match-end 3) org-deadline-string "Plain:"))
8691 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8692 mb0 (match-beginning 0))
8693 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8694 (setq n (string-to-number (match-string 2 ts))
8695 what (match-string 3 ts))
8696 (if (equal what "w") (setq n (* n 7) what "d"))
8697 ;; Preparation, see if we need to modify the start date for the change
8698 (when (match-end 1)
8699 (setq time (save-match-data (org-time-string-to-time ts)))
8700 (cond
8701 ((equal (match-string 1 ts) ".")
8702 ;; Shift starting date to today
8703 (org-timestamp-change
8704 (- (time-to-days (current-time)) (time-to-days time))
8705 'day))
8706 ((equal (match-string 1 ts) "+")
8707 (while (or (= nshift 0)
8708 (<= (time-to-days time) (time-to-days (current-time))))
8709 (when (= (incf nshift) nshiftmax)
8710 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8711 (error "Abort")))
8712 (org-timestamp-change n (cdr (assoc what whata)))
8713 (org-at-timestamp-p t)
8714 (setq ts (match-string 1))
8715 (setq time (save-match-data (org-time-string-to-time ts))))
8716 (org-timestamp-change (- n) (cdr (assoc what whata)))
8717 ;; rematch, so that we have everything in place for the real shift
8718 (org-at-timestamp-p t)
8719 (setq ts (match-string 1))
8720 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8721 (org-timestamp-change n (cdr (assoc what whata)))
8722 (setq msg (concat msg type org-last-changed-timestamp " "))))
8723 (setq org-log-post-message msg)
8724 (message "%s" msg))))
8726 (defun org-show-todo-tree (arg)
8727 "Make a compact tree which shows all headlines marked with TODO.
8728 The tree will show the lines where the regexp matches, and all higher
8729 headlines above the match.
8730 With a \\[universal-argument] prefix, also show the DONE entries.
8731 With a numeric prefix N, construct a sparse tree for the Nth element
8732 of `org-todo-keywords-1'."
8733 (interactive "P")
8734 (let ((case-fold-search nil)
8735 (kwd-re
8736 (cond ((null arg) org-not-done-regexp)
8737 ((equal arg '(4))
8738 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8739 (mapcar 'list org-todo-keywords-1))))
8740 (concat "\\("
8741 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8742 "\\)\\>")))
8743 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8744 (regexp-quote (nth (1- (prefix-numeric-value arg))
8745 org-todo-keywords-1)))
8746 (t (error "Invalid prefix argument: %s" arg)))))
8747 (message "%d TODO entries found"
8748 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8750 (defun org-deadline (&optional remove time)
8751 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8752 With argument REMOVE, remove any deadline from the item.
8753 When TIME is set, it should be an internal time specification, and the
8754 scheduling will use the corresponding date."
8755 (interactive "P")
8756 (if remove
8757 (progn
8758 (org-remove-timestamp-with-keyword org-deadline-string)
8759 (message "Item no longer has a deadline."))
8760 (if (org-get-repeat)
8761 (error "Cannot change deadline on task with repeater, please do that by hand")
8762 (org-add-planning-info 'deadline time 'closed)
8763 (message "Deadline on %s" org-last-inserted-timestamp))))
8765 (defun org-schedule (&optional remove time)
8766 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8767 With argument REMOVE, remove any scheduling date from the item.
8768 When TIME is set, it should be an internal time specification, and the
8769 scheduling will use the corresponding date."
8770 (interactive "P")
8771 (if remove
8772 (progn
8773 (org-remove-timestamp-with-keyword org-scheduled-string)
8774 (message "Item is no longer scheduled."))
8775 (if (org-get-repeat)
8776 (error "Cannot reschedule task with repeater, please do that by hand")
8777 (org-add-planning-info 'scheduled time 'closed)
8778 (message "Scheduled to %s" org-last-inserted-timestamp))))
8780 (defun org-remove-timestamp-with-keyword (keyword)
8781 "Remove all time stamps with KEYWORD in the current entry."
8782 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8783 beg)
8784 (save-excursion
8785 (org-back-to-heading t)
8786 (setq beg (point))
8787 (org-end-of-subtree t t)
8788 (while (re-search-backward re beg t)
8789 (replace-match "")
8790 (if (and (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8791 (equal (char-before) ?\ ))
8792 (backward-delete-char 1)
8793 (if (string-match "^[ \t]*$" (buffer-substring
8794 (point-at-bol) (point-at-eol)))
8795 (delete-region (point-at-bol)
8796 (min (point-max) (1+ (point-at-eol))))))))))
8798 (defun org-add-planning-info (what &optional time &rest remove)
8799 "Insert new timestamp with keyword in the line directly after the headline.
8800 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8801 If non is given, the user is prompted for a date.
8802 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8803 be removed."
8804 (interactive)
8805 (let (org-time-was-given org-end-time-was-given ts
8806 end default-time default-input)
8808 (when (and (not time) (memq what '(scheduled deadline)))
8809 ;; Try to get a default date/time from existing timestamp
8810 (save-excursion
8811 (org-back-to-heading t)
8812 (setq end (save-excursion (outline-next-heading) (point)))
8813 (when (re-search-forward (if (eq what 'scheduled)
8814 org-scheduled-time-regexp
8815 org-deadline-time-regexp)
8816 end t)
8817 (setq ts (match-string 1)
8818 default-time
8819 (apply 'encode-time (org-parse-time-string ts))
8820 default-input (and ts (org-get-compact-tod ts))))))
8821 (when what
8822 ;; If necessary, get the time from the user
8823 (setq time (or time (org-read-date nil 'to-time nil nil
8824 default-time default-input))))
8826 (when (and org-insert-labeled-timestamps-at-point
8827 (member what '(scheduled deadline)))
8828 (insert
8829 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8830 (org-insert-time-stamp time org-time-was-given
8831 nil nil nil (list org-end-time-was-given))
8832 (setq what nil))
8833 (save-excursion
8834 (save-restriction
8835 (let (col list elt ts buffer-invisibility-spec)
8836 (org-back-to-heading t)
8837 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8838 (goto-char (match-end 1))
8839 (setq col (current-column))
8840 (goto-char (match-end 0))
8841 (if (eobp) (insert "\n") (forward-char 1))
8842 (if (and (not (looking-at outline-regexp))
8843 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8844 "[^\r\n]*"))
8845 (not (equal (match-string 1) org-clock-string)))
8846 (narrow-to-region (match-beginning 0) (match-end 0))
8847 (insert-before-markers "\n")
8848 (backward-char 1)
8849 (narrow-to-region (point) (point))
8850 (and org-adapt-indentation (org-indent-to-column col)))
8851 ;; Check if we have to remove something.
8852 (setq list (cons what remove))
8853 (while list
8854 (setq elt (pop list))
8855 (goto-char (point-min))
8856 (when (or (and (eq elt 'scheduled)
8857 (re-search-forward org-scheduled-time-regexp nil t))
8858 (and (eq elt 'deadline)
8859 (re-search-forward org-deadline-time-regexp nil t))
8860 (and (eq elt 'closed)
8861 (re-search-forward org-closed-time-regexp nil t)))
8862 (replace-match "")
8863 (if (looking-at "--+<[^>]+>") (replace-match ""))
8864 (if (looking-at " +") (replace-match ""))))
8865 (goto-char (point-max))
8866 (when what
8867 (insert
8868 (if (not (or (bolp) (eq (char-before) ?\ ))) " " "")
8869 (cond ((eq what 'scheduled) org-scheduled-string)
8870 ((eq what 'deadline) org-deadline-string)
8871 ((eq what 'closed) org-closed-string))
8872 " ")
8873 (setq ts (org-insert-time-stamp
8874 time
8875 (or org-time-was-given
8876 (and (eq what 'closed) org-log-done-with-time))
8877 (eq what 'closed)
8878 nil nil (list org-end-time-was-given)))
8879 (end-of-line 1))
8880 (goto-char (point-min))
8881 (widen)
8882 (if (and (looking-at "[ \t]+\n")
8883 (equal (char-before) ?\n))
8884 (delete-region (1- (point)) (point-at-eol)))
8885 ts)))))
8887 (defvar org-log-note-marker (make-marker))
8888 (defvar org-log-note-purpose nil)
8889 (defvar org-log-note-state nil)
8890 (defvar org-log-note-how nil)
8891 (defvar org-log-note-window-configuration nil)
8892 (defvar org-log-note-return-to (make-marker))
8893 (defvar org-log-post-message nil
8894 "Message to be displayed after a log note has been stored.
8895 The auto-repeater uses this.")
8897 (defun org-add-note ()
8898 "Add a note to the current entry.
8899 This is done in the same way as adding a state change note."
8900 (interactive)
8901 (org-add-log-setup 'note nil t nil))
8903 (defun org-add-log-setup (&optional purpose state findpos how)
8904 "Set up the post command hook to take a note.
8905 If this is about to TODO state change, the new state is expected in STATE.
8906 When FINDPOS is non-nil, find the correct position for the note in
8907 the current entry. If not, assume that it can be inserted at point."
8908 (save-excursion
8909 (when findpos
8910 (org-back-to-heading t)
8911 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8912 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8913 "[^\r\n]*\\)?"))
8914 (goto-char (match-end 0))
8915 (unless org-log-states-order-reversed
8916 (and (= (char-after) ?\n) (forward-char 1))
8917 (org-skip-over-state-notes)
8918 (skip-chars-backward " \t\n\r")))
8919 (move-marker org-log-note-marker (point))
8920 (setq org-log-note-purpose purpose
8921 org-log-note-state state
8922 org-log-note-how how)
8923 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8925 (defun org-skip-over-state-notes ()
8926 "Skip past the list of State notes in an entry."
8927 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8928 (while (looking-at "[ \t]*- State")
8929 (condition-case nil
8930 (org-next-item)
8931 (error (org-end-of-item)))))
8933 (defun org-add-log-note (&optional purpose)
8934 "Pop up a window for taking a note, and add this note later at point."
8935 (remove-hook 'post-command-hook 'org-add-log-note)
8936 (setq org-log-note-window-configuration (current-window-configuration))
8937 (delete-other-windows)
8938 (move-marker org-log-note-return-to (point))
8939 (switch-to-buffer (marker-buffer org-log-note-marker))
8940 (goto-char org-log-note-marker)
8941 (org-switch-to-buffer-other-window "*Org Note*")
8942 (erase-buffer)
8943 (if (memq org-log-note-how '(time state))
8944 (org-store-log-note)
8945 (let ((org-inhibit-startup t)) (org-mode))
8946 (insert (format "# Insert note for %s.
8947 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8948 (cond
8949 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8950 ((eq org-log-note-purpose 'done) "closed todo item")
8951 ((eq org-log-note-purpose 'state)
8952 (format "state change to \"%s\"" org-log-note-state))
8953 ((eq org-log-note-purpose 'note)
8954 "this entry")
8955 (t (error "This should not happen")))))
8956 (org-set-local 'org-finish-function 'org-store-log-note)))
8958 (defvar org-note-abort nil) ; dynamically scoped
8959 (defun org-store-log-note ()
8960 "Finish taking a log note, and insert it to where it belongs."
8961 (let ((txt (buffer-string))
8962 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8963 lines ind)
8964 (kill-buffer (current-buffer))
8965 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8966 (setq txt (replace-match "" t t txt)))
8967 (if (string-match "\\s-+\\'" txt)
8968 (setq txt (replace-match "" t t txt)))
8969 (setq lines (org-split-string txt "\n"))
8970 (when (and note (string-match "\\S-" note))
8971 (setq note
8972 (org-replace-escapes
8973 note
8974 (list (cons "%u" (user-login-name))
8975 (cons "%U" user-full-name)
8976 (cons "%t" (format-time-string
8977 (org-time-stamp-format 'long 'inactive)
8978 (current-time)))
8979 (cons "%s" (if org-log-note-state
8980 (concat "\"" org-log-note-state "\"")
8981 "")))))
8982 (if lines (setq note (concat note " \\\\")))
8983 (push note lines))
8984 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8985 (when lines
8986 (save-excursion
8987 (set-buffer (marker-buffer org-log-note-marker))
8988 (save-excursion
8989 (goto-char org-log-note-marker)
8990 (move-marker org-log-note-marker nil)
8991 (end-of-line 1)
8992 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8993 (indent-relative nil)
8994 (insert "- " (pop lines))
8995 (org-indent-line-function)
8996 (beginning-of-line 1)
8997 (looking-at "[ \t]*")
8998 (setq ind (concat (match-string 0) " "))
8999 (end-of-line 1)
9000 (while lines (insert "\n" ind (pop lines)))))))
9001 (set-window-configuration org-log-note-window-configuration)
9002 (with-current-buffer (marker-buffer org-log-note-return-to)
9003 (goto-char org-log-note-return-to))
9004 (move-marker org-log-note-return-to nil)
9005 (and org-log-post-message (message "%s" org-log-post-message)))
9007 (defun org-sparse-tree (&optional arg)
9008 "Create a sparse tree, prompt for the details.
9009 This command can create sparse trees. You first need to select the type
9010 of match used to create the tree:
9012 t Show entries with a specific TODO keyword.
9013 T Show entries selected by a tags match.
9014 p Enter a property name and its value (both with completion on existing
9015 names/values) and show entries with that property.
9016 r Show entries matching a regular expression
9017 d Show deadlines due within `org-deadline-warning-days'."
9018 (interactive "P")
9019 (let (ans kwd value)
9020 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
9021 (setq ans (read-char-exclusive))
9022 (cond
9023 ((equal ans ?d)
9024 (call-interactively 'org-check-deadlines))
9025 ((equal ans ?b)
9026 (call-interactively 'org-check-before-date))
9027 ((equal ans ?t)
9028 (org-show-todo-tree '(4)))
9029 ((equal ans ?T)
9030 (call-interactively 'org-tags-sparse-tree))
9031 ((member ans '(?p ?P))
9032 (setq kwd (completing-read "Property: "
9033 (mapcar 'list (org-buffer-property-keys))))
9034 (setq value (completing-read "Value: "
9035 (mapcar 'list (org-property-values kwd))))
9036 (unless (string-match "\\`{.*}\\'" value)
9037 (setq value (concat "\"" value "\"")))
9038 (org-tags-sparse-tree arg (concat kwd "=" value)))
9039 ((member ans '(?r ?R ?/))
9040 (call-interactively 'org-occur))
9041 (t (error "No such sparse tree command \"%c\"" ans)))))
9043 (defvar org-occur-highlights nil
9044 "List of overlays used for occur matches.")
9045 (make-variable-buffer-local 'org-occur-highlights)
9046 (defvar org-occur-parameters nil
9047 "Parameters of the active org-occur calls.
9048 This is a list, each call to org-occur pushes as cons cell,
9049 containing the regular expression and the callback, onto the list.
9050 The list can contain several entries if `org-occur' has been called
9051 several time with the KEEP-PREVIOUS argument. Otherwise, this list
9052 will only contain one set of parameters. When the highlights are
9053 removed (for example with `C-c C-c', or with the next edit (depending
9054 on `org-remove-highlights-with-change'), this variable is emptied
9055 as well.")
9056 (make-variable-buffer-local 'org-occur-parameters)
9058 (defun org-occur (regexp &optional keep-previous callback)
9059 "Make a compact tree which shows all matches of REGEXP.
9060 The tree will show the lines where the regexp matches, and all higher
9061 headlines above the match. It will also show the heading after the match,
9062 to make sure editing the matching entry is easy.
9063 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
9064 call to `org-occur' will be kept, to allow stacking of calls to this
9065 command.
9066 If CALLBACK is non-nil, it is a function which is called to confirm
9067 that the match should indeed be shown."
9068 (interactive "sRegexp: \nP")
9069 (unless keep-previous
9070 (org-remove-occur-highlights nil nil t))
9071 (push (cons regexp callback) org-occur-parameters)
9072 (let ((cnt 0))
9073 (save-excursion
9074 (goto-char (point-min))
9075 (if (or (not keep-previous) ; do not want to keep
9076 (not org-occur-highlights)) ; no previous matches
9077 ;; hide everything
9078 (org-overview))
9079 (while (re-search-forward regexp nil t)
9080 (when (or (not callback)
9081 (save-match-data (funcall callback)))
9082 (setq cnt (1+ cnt))
9083 (when org-highlight-sparse-tree-matches
9084 (org-highlight-new-match (match-beginning 0) (match-end 0)))
9085 (org-show-context 'occur-tree))))
9086 (when org-remove-highlights-with-change
9087 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
9088 nil 'local))
9089 (unless org-sparse-tree-open-archived-trees
9090 (org-hide-archived-subtrees (point-min) (point-max)))
9091 (run-hooks 'org-occur-hook)
9092 (if (interactive-p)
9093 (message "%d match(es) for regexp %s" cnt regexp))
9094 cnt))
9096 (defun org-show-context (&optional key)
9097 "Make sure point and context and visible.
9098 How much context is shown depends upon the variables
9099 `org-show-hierarchy-above', `org-show-following-heading'. and
9100 `org-show-siblings'."
9101 (let ((heading-p (org-on-heading-p t))
9102 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
9103 (following-p (org-get-alist-option org-show-following-heading key))
9104 (entry-p (org-get-alist-option org-show-entry-below key))
9105 (siblings-p (org-get-alist-option org-show-siblings key)))
9106 (catch 'exit
9107 ;; Show heading or entry text
9108 (if (and heading-p (not entry-p))
9109 (org-flag-heading nil) ; only show the heading
9110 (and (or entry-p (org-invisible-p) (org-invisible-p2))
9111 (org-show-hidden-entry))) ; show entire entry
9112 (when following-p
9113 ;; Show next sibling, or heading below text
9114 (save-excursion
9115 (and (if heading-p (org-goto-sibling) (outline-next-heading))
9116 (org-flag-heading nil))))
9117 (when siblings-p (org-show-siblings))
9118 (when hierarchy-p
9119 ;; show all higher headings, possibly with siblings
9120 (save-excursion
9121 (while (and (condition-case nil
9122 (progn (org-up-heading-all 1) t)
9123 (error nil))
9124 (not (bobp)))
9125 (org-flag-heading nil)
9126 (when siblings-p (org-show-siblings))))))))
9128 (defun org-reveal (&optional siblings)
9129 "Show current entry, hierarchy above it, and the following headline.
9130 This can be used to show a consistent set of context around locations
9131 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
9132 not t for the search context.
9134 With optional argument SIBLINGS, on each level of the hierarchy all
9135 siblings are shown. This repairs the tree structure to what it would
9136 look like when opened with hierarchical calls to `org-cycle'."
9137 (interactive "P")
9138 (let ((org-show-hierarchy-above t)
9139 (org-show-following-heading t)
9140 (org-show-siblings (if siblings t org-show-siblings)))
9141 (org-show-context nil)))
9143 (defun org-highlight-new-match (beg end)
9144 "Highlight from BEG to END and mark the highlight is an occur headline."
9145 (let ((ov (org-make-overlay beg end)))
9146 (org-overlay-put ov 'face 'secondary-selection)
9147 (push ov org-occur-highlights)))
9149 (defun org-remove-occur-highlights (&optional beg end noremove)
9150 "Remove the occur highlights from the buffer.
9151 BEG and END are ignored. If NOREMOVE is nil, remove this function
9152 from the `before-change-functions' in the current buffer."
9153 (interactive)
9154 (unless org-inhibit-highlight-removal
9155 (mapc 'org-delete-overlay org-occur-highlights)
9156 (setq org-occur-highlights nil)
9157 (setq org-occur-parameters nil)
9158 (unless noremove
9159 (remove-hook 'before-change-functions
9160 'org-remove-occur-highlights 'local))))
9162 ;;;; Priorities
9164 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
9165 "Regular expression matching the priority indicator.")
9167 (defvar org-remove-priority-next-time nil)
9169 (defun org-priority-up ()
9170 "Increase the priority of the current item."
9171 (interactive)
9172 (org-priority 'up))
9174 (defun org-priority-down ()
9175 "Decrease the priority of the current item."
9176 (interactive)
9177 (org-priority 'down))
9179 (defun org-priority (&optional action)
9180 "Change the priority of an item by ARG.
9181 ACTION can be `set', `up', `down', or a character."
9182 (interactive)
9183 (setq action (or action 'set))
9184 (let (current new news have remove)
9185 (save-excursion
9186 (org-back-to-heading)
9187 (if (looking-at org-priority-regexp)
9188 (setq current (string-to-char (match-string 2))
9189 have t)
9190 (setq current org-default-priority))
9191 (cond
9192 ((or (eq action 'set)
9193 (if (featurep 'xemacs) (characterp action) (integerp action)))
9194 (if (not (eq action 'set))
9195 (setq new action)
9196 (message "Priority %c-%c, SPC to remove: "
9197 org-highest-priority org-lowest-priority)
9198 (setq new (read-char-exclusive)))
9199 (if (and (= (upcase org-highest-priority) org-highest-priority)
9200 (= (upcase org-lowest-priority) org-lowest-priority))
9201 (setq new (upcase new)))
9202 (cond ((equal new ?\ ) (setq remove t))
9203 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
9204 (error "Priority must be between `%c' and `%c'"
9205 org-highest-priority org-lowest-priority))))
9206 ((eq action 'up)
9207 (if (and (not have) (eq last-command this-command))
9208 (setq new org-lowest-priority)
9209 (setq new (if (and org-priority-start-cycle-with-default (not have))
9210 org-default-priority (1- current)))))
9211 ((eq action 'down)
9212 (if (and (not have) (eq last-command this-command))
9213 (setq new org-highest-priority)
9214 (setq new (if (and org-priority-start-cycle-with-default (not have))
9215 org-default-priority (1+ current)))))
9216 (t (error "Invalid action")))
9217 (if (or (< (upcase new) org-highest-priority)
9218 (> (upcase new) org-lowest-priority))
9219 (setq remove t))
9220 (setq news (format "%c" new))
9221 (if have
9222 (if remove
9223 (replace-match "" t t nil 1)
9224 (replace-match news t t nil 2))
9225 (if remove
9226 (error "No priority cookie found in line")
9227 (looking-at org-todo-line-regexp)
9228 (if (match-end 2)
9229 (progn
9230 (goto-char (match-end 2))
9231 (insert " [#" news "]"))
9232 (goto-char (match-beginning 3))
9233 (insert "[#" news "] ")))))
9234 (org-preserve-lc (org-set-tags nil 'align))
9235 (if remove
9236 (message "Priority removed")
9237 (message "Priority of current item set to %s" news))))
9240 (defun org-get-priority (s)
9241 "Find priority cookie and return priority."
9242 (save-match-data
9243 (if (not (string-match org-priority-regexp s))
9244 (* 1000 (- org-lowest-priority org-default-priority))
9245 (* 1000 (- org-lowest-priority
9246 (string-to-char (match-string 2 s)))))))
9248 ;;;; Tags
9250 (defvar org-agenda-archives-mode)
9251 (defun org-scan-tags (action matcher &optional todo-only)
9252 "Scan headline tags with inheritance and produce output ACTION.
9254 ACTION can be `sparse-tree' to produce a sparse tree in the current buffer,
9255 or `agenda' to produce an entry list for an agenda view. It can also be
9256 a Lisp form or a function that should be called at each matched headline, in
9257 this case the return value is a list of all return values from these calls.
9259 MATCHER is a Lisp form to be evaluated, testing if a given set of tags
9260 qualifies a headline for inclusion. When TODO-ONLY is non-nil,
9261 only lines with a TODO keyword are included in the output."
9262 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
9263 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
9264 (org-re
9265 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
9266 (props (list 'face 'default
9267 'done-face 'org-done
9268 'undone-face 'default
9269 'mouse-face 'highlight
9270 'org-not-done-regexp org-not-done-regexp
9271 'org-todo-regexp org-todo-regexp
9272 'keymap org-agenda-keymap
9273 'help-echo
9274 (format "mouse-2 or RET jump to org file %s"
9275 (abbreviate-file-name
9276 (or (buffer-file-name (buffer-base-buffer))
9277 (buffer-name (buffer-base-buffer)))))))
9278 (case-fold-search nil)
9279 lspos tags tags-list
9280 (tags-alist (list (cons 0 (mapcar 'downcase org-file-tags))))
9281 (llast 0) rtn rtn1 level category i txt
9282 todo marker entry priority)
9283 (when (not (member action '(agenda sparse-tree)))
9284 (setq action (list 'lambda nil action)))
9285 (save-excursion
9286 (goto-char (point-min))
9287 (when (eq action 'sparse-tree)
9288 (org-overview)
9289 (org-remove-occur-highlights))
9290 (while (re-search-forward re nil t)
9291 (catch :skip
9292 (setq todo (if (match-end 1) (match-string 2))
9293 tags (if (match-end 4) (match-string 4)))
9294 (goto-char (setq lspos (1+ (match-beginning 0))))
9295 (setq level (org-reduced-level (funcall outline-level))
9296 category (org-get-category))
9297 (setq i llast llast level)
9298 ;; remove tag lists from same and sublevels
9299 (while (>= i level)
9300 (when (setq entry (assoc i tags-alist))
9301 (setq tags-alist (delete entry tags-alist)))
9302 (setq i (1- i)))
9303 ;; add the next tags
9304 (when tags
9305 (setq tags (mapcar 'downcase (org-split-string tags ":"))
9306 tags-alist
9307 (cons (cons level tags) tags-alist)))
9308 ;; compile tags for current headline
9309 (setq tags-list
9310 (if org-use-tag-inheritance
9311 (apply 'append (mapcar 'cdr tags-alist))
9312 tags))
9313 (when (and tags org-use-tag-inheritance
9314 (not (eq t org-use-tag-inheritance)))
9315 ;; selective inheritance, remove uninherited ones
9316 (setcdr (car tags-alist)
9317 (org-remove-uniherited-tags (cdar tags-alist))))
9318 (when (and (or (not todo-only) (member todo org-not-done-keywords))
9319 (eval matcher)
9321 (not (member org-archive-tag tags-list))
9322 ;; we have an archive tag, should we use this anyway?
9323 (or (not org-agenda-skip-archived-trees)
9324 (and (eq action 'agenda) org-agenda-archives-mode))))
9325 (unless (eq action 'sparse-tree) (org-agenda-skip))
9327 ;; select this headline
9329 (cond
9330 ((eq action 'sparse-tree)
9331 (and org-highlight-sparse-tree-matches
9332 (org-get-heading) (match-end 0)
9333 (org-highlight-new-match
9334 (match-beginning 0) (match-beginning 1)))
9335 (org-show-context 'tags-tree))
9336 ((eq action 'agenda)
9337 (setq txt (org-format-agenda-item
9339 (concat
9340 (if org-tags-match-list-sublevels
9341 (make-string (1- level) ?.) "")
9342 (org-get-heading))
9343 category tags-list)
9344 priority (org-get-priority txt))
9345 (goto-char lspos)
9346 (setq marker (org-agenda-new-marker))
9347 (org-add-props txt props
9348 'org-marker marker 'org-hd-marker marker 'org-category category
9349 'priority priority 'type "tagsmatch")
9350 (push txt rtn))
9351 ((functionp action)
9352 (save-excursion
9353 (setq rtn1 (funcall action))
9354 (push rtn1 rtn))
9355 (goto-char (point-at-eol)))
9356 (t (error "Invalid action")))
9358 ;; if we are to skip sublevels, jump to end of subtree
9359 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
9360 (when (and (eq action 'sparse-tree)
9361 (not org-sparse-tree-open-archived-trees))
9362 (org-hide-archived-subtrees (point-min) (point-max)))
9363 (nreverse rtn)))
9365 (defun org-remove-uniherited-tags (tags)
9366 "Remove all tags that are not inherited from the list TAGS."
9367 (cond
9368 ((eq org-use-tag-inheritance t) tags)
9369 ((not org-use-tag-inheritance) nil)
9370 ((stringp org-use-tag-inheritance)
9371 (delq nil (mapcar
9372 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
9373 tags)))
9374 ((listp org-use-tag-inheritance)
9375 (org-delete-all org-use-tag-inheritance tags))))
9377 (defvar todo-only) ;; dynamically scoped
9379 (defun org-tags-sparse-tree (&optional todo-only match)
9380 "Create a sparse tree according to tags string MATCH.
9381 MATCH can contain positive and negative selection of tags, like
9382 \"+WORK+URGENT-WITHBOSS\".
9383 If optional argument TODO_ONLY is non-nil, only select lines that are
9384 also TODO lines."
9385 (interactive "P")
9386 (org-prepare-agenda-buffers (list (current-buffer)))
9387 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
9389 (defvar org-cached-props nil)
9390 (defun org-cached-entry-get (pom property)
9391 (if (or (eq t org-use-property-inheritance)
9392 (and (stringp org-use-property-inheritance)
9393 (string-match org-use-property-inheritance property))
9394 (and (listp org-use-property-inheritance)
9395 (member property org-use-property-inheritance)))
9396 ;; Caching is not possible, check it directly
9397 (org-entry-get pom property 'inherit)
9398 ;; Get all properties, so that we can do complicated checks easily
9399 (cdr (assoc property (or org-cached-props
9400 (setq org-cached-props
9401 (org-entry-properties pom)))))))
9403 (defun org-global-tags-completion-table (&optional files)
9404 "Return the list of all tags in all agenda buffer/files."
9405 (save-excursion
9406 (org-uniquify
9407 (delq nil
9408 (apply 'append
9409 (mapcar
9410 (lambda (file)
9411 (set-buffer (find-file-noselect file))
9412 (append (org-get-buffer-tags)
9413 (mapcar (lambda (x) (if (stringp (car-safe x))
9414 (list (car-safe x)) nil))
9415 org-tag-alist)))
9416 (if (and files (car files))
9417 files
9418 (org-agenda-files))))))))
9420 (defun org-make-tags-matcher (match)
9421 "Create the TAGS//TODO matcher form for the selection string MATCH."
9422 ;; todo-only is scoped dynamically into this function, and the function
9423 ;; may change it it the matcher asksk for it.
9424 (unless match
9425 ;; Get a new match request, with completion
9426 (let ((org-last-tags-completion-table
9427 (org-global-tags-completion-table)))
9428 (setq match (completing-read
9429 "Match: " 'org-tags-completion-function nil nil nil
9430 'org-tags-history))))
9432 ;; Parse the string and create a lisp form
9433 (let ((match0 match)
9434 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
9435 minus tag mm
9436 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
9437 orterms term orlist re-p str-p level-p level-op
9438 prop-p pn pv po cat-p gv)
9439 (if (string-match "/+" match)
9440 ;; match contains also a todo-matching request
9441 (progn
9442 (setq tagsmatch (substring match 0 (match-beginning 0))
9443 todomatch (substring match (match-end 0)))
9444 (if (string-match "^!" todomatch)
9445 (setq todo-only t todomatch (substring todomatch 1)))
9446 (if (string-match "^\\s-*$" todomatch)
9447 (setq todomatch nil)))
9448 ;; only matching tags
9449 (setq tagsmatch match todomatch nil))
9451 ;; Make the tags matcher
9452 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
9453 (setq tagsmatcher t)
9454 (setq orterms (org-split-string tagsmatch "|") orlist nil)
9455 (while (setq term (pop orterms))
9456 (while (and (equal (substring term -1) "\\") orterms)
9457 (setq term (concat term "|" (pop orterms)))) ; repair bad split
9458 (while (string-match re term)
9459 (setq minus (and (match-end 1)
9460 (equal (match-string 1 term) "-"))
9461 tag (match-string 2 term)
9462 re-p (equal (string-to-char tag) ?{)
9463 level-p (match-end 4)
9464 prop-p (match-end 5)
9465 mm (cond
9466 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
9467 (level-p
9468 (setq level-op (org-op-to-function (match-string 3 term)))
9469 `(,level-op level ,(string-to-number
9470 (match-string 4 term))))
9471 (prop-p
9472 (setq pn (match-string 5 term)
9473 po (match-string 6 term)
9474 pv (match-string 7 term)
9475 cat-p (equal pn "CATEGORY")
9476 re-p (equal (string-to-char pv) ?{)
9477 str-p (equal (string-to-char pv) ?\")
9478 time-p (save-match-data (string-match "^\"<.*>\"$" pv))
9479 pv (if (or re-p str-p) (substring pv 1 -1) pv))
9480 (if time-p (setq pv (org-matcher-time pv)))
9481 (setq po (org-op-to-function po (if time-p 'time str-p)))
9482 (if (equal pn "CATEGORY")
9483 (setq gv '(get-text-property (point) 'org-category))
9484 (setq gv `(org-cached-entry-get nil ,pn)))
9485 (if re-p
9486 (if (eq po 'org<>)
9487 `(not (string-match ,pv (or ,gv "")))
9488 `(string-match ,pv (or ,gv "")))
9489 (if str-p
9490 `(,po (or ,gv "") ,pv)
9491 `(,po (string-to-number (or ,gv ""))
9492 ,(string-to-number pv) ))))
9493 (t `(member ,(downcase tag) tags-list)))
9494 mm (if minus (list 'not mm) mm)
9495 term (substring term (match-end 0)))
9496 (push mm tagsmatcher))
9497 (push (if (> (length tagsmatcher) 1)
9498 (cons 'and tagsmatcher)
9499 (car tagsmatcher))
9500 orlist)
9501 (setq tagsmatcher nil))
9502 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
9503 (setq tagsmatcher
9504 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
9505 ;; Make the todo matcher
9506 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
9507 (setq todomatcher t)
9508 (setq orterms (org-split-string todomatch "|") orlist nil)
9509 (while (setq term (pop orterms))
9510 (while (string-match re term)
9511 (setq minus (and (match-end 1)
9512 (equal (match-string 1 term) "-"))
9513 kwd (match-string 2 term)
9514 re-p (equal (string-to-char kwd) ?{)
9515 term (substring term (match-end 0))
9516 mm (if re-p
9517 `(string-match ,(substring kwd 1 -1) todo)
9518 (list 'equal 'todo kwd))
9519 mm (if minus (list 'not mm) mm))
9520 (push mm todomatcher))
9521 (push (if (> (length todomatcher) 1)
9522 (cons 'and todomatcher)
9523 (car todomatcher))
9524 orlist)
9525 (setq todomatcher nil))
9526 (setq todomatcher (if (> (length orlist) 1)
9527 (cons 'or orlist) (car orlist))))
9529 ;; Return the string and lisp forms of the matcher
9530 (setq matcher (if todomatcher
9531 (list 'and tagsmatcher todomatcher)
9532 tagsmatcher))
9533 (cons match0 matcher)))
9535 (defun org-op-to-function (op &optional stringp)
9536 "Turn an operator into the appropriate function."
9537 (setq op
9538 (cond
9539 ((equal op "<" ) '(< string< org-time<))
9540 ((equal op ">" ) '(> org-string> org-time>))
9541 ((member op '("<=" "=<")) '(<= org-string<= org-time<=))
9542 ((member op '(">=" "=>")) '(>= org-string>= org-time>=))
9543 ((member op '("=" "==")) '(= string= org-time=))
9544 ((member op '("<>" "!=")) '(org<> org-string<> org-time<>))))
9545 (nth (if (eq stringp 'time) 2 (if stringp 1 0)) op))
9547 (defun org<> (a b) (not (= a b)))
9548 (defun org-string<= (a b) (or (string= a b) (string< a b)))
9549 (defun org-string>= (a b) (not (string< a b)))
9550 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
9551 (defun org-string<> (a b) (not (string= a b)))
9552 (defun org-time= (a b) (= (org-2ft a) (org-2ft b)))
9553 (defun org-time< (a b) (< (org-2ft a) (org-2ft b)))
9554 (defun org-time<= (a b) (<= (org-2ft a) (org-2ft b)))
9555 (defun org-time> (a b) (> (org-2ft a) (org-2ft b)))
9556 (defun org-time>= (a b) (>= (org-2ft a) (org-2ft b)))
9557 (defun org-time<> (a b) (org<> (org-2ft a) (org-2ft b)))
9558 (defun org-2ft (s)
9559 "Convert S to a floating point time.
9560 If S is already a number, just return it. If it is a string, parse
9561 it as a time string and apply `float-time' to it. f S is nil, just return 0."
9562 (cond
9563 ((numberp s) s)
9564 ((stringp s)
9565 (condition-case nil
9566 (float-time (apply 'encode-time (org-parse-time-string s)))
9567 (error 0.)))
9568 (t 0.)))
9570 (defun org-matcher-time (s)
9571 (cond
9572 ((equal s "<now>") (float-time))
9573 ((equal s "<today>")
9574 (float-time (append '(0 0 0) (nthcdr 3 (decode-time)))))
9575 (t (org-2ft s))))
9577 (defun org-match-any-p (re list)
9578 "Does re match any element of list?"
9579 (setq list (mapcar (lambda (x) (string-match re x)) list))
9580 (delq nil list))
9582 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
9583 (defvar org-tags-overlay (org-make-overlay 1 1))
9584 (org-detach-overlay org-tags-overlay)
9586 (defun org-get-tags-at (&optional pos)
9587 "Get a list of all headline tags applicable at POS.
9588 POS defaults to point. If tags are inherited, the list contains
9589 the targets in the same sequence as the headlines appear, i.e.
9590 the tags of the current headline come last."
9591 (interactive)
9592 (let (tags ltags lastpos parent)
9593 (save-excursion
9594 (save-restriction
9595 (widen)
9596 (goto-char (or pos (point)))
9597 (save-match-data
9598 (condition-case nil
9599 (progn
9600 (org-back-to-heading t)
9601 (while (not (equal lastpos (point)))
9602 (setq lastpos (point))
9603 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
9604 (setq ltags (org-split-string
9605 (org-match-string-no-properties 1) ":"))
9606 (setq tags (append (org-remove-uniherited-tags ltags)
9607 tags)))
9608 (or org-use-tag-inheritance (error ""))
9609 (org-up-heading-all 1)
9610 (setq parent t)))
9611 (error nil))))
9612 (append (org-remove-uniherited-tags org-file-tags) tags))))
9614 (defun org-toggle-tag (tag &optional onoff)
9615 "Toggle the tag TAG for the current line.
9616 If ONOFF is `on' or `off', don't toggle but set to this state."
9617 (unless (org-on-heading-p t) (error "Not on headling"))
9618 (let (res current)
9619 (save-excursion
9620 (beginning-of-line)
9621 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
9622 (point-at-eol) t)
9623 (progn
9624 (setq current (match-string 1))
9625 (replace-match ""))
9626 (setq current ""))
9627 (setq current (nreverse (org-split-string current ":")))
9628 (cond
9629 ((eq onoff 'on)
9630 (setq res t)
9631 (or (member tag current) (push tag current)))
9632 ((eq onoff 'off)
9633 (or (not (member tag current)) (setq current (delete tag current))))
9634 (t (if (member tag current)
9635 (setq current (delete tag current))
9636 (setq res t)
9637 (push tag current))))
9638 (end-of-line 1)
9639 (if current
9640 (progn
9641 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
9642 (org-set-tags nil t))
9643 (delete-horizontal-space))
9644 (run-hooks 'org-after-tags-change-hook))
9645 res))
9647 (defun org-align-tags-here (to-col)
9648 ;; Assumes that this is a headline
9649 (let ((pos (point)) (col (current-column)) ncol tags-l p)
9650 (beginning-of-line 1)
9651 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9652 (< pos (match-beginning 2)))
9653 (progn
9654 (setq tags-l (- (match-end 2) (match-beginning 2)))
9655 (goto-char (match-beginning 1))
9656 (insert " ")
9657 (delete-region (point) (1+ (match-beginning 2)))
9658 (setq ncol (max (1+ (current-column))
9659 (1+ col)
9660 (if (> to-col 0)
9661 to-col
9662 (- (abs to-col) tags-l))))
9663 (setq p (point))
9664 (insert (make-string (- ncol (current-column)) ?\ ))
9665 (setq ncol (current-column))
9666 (when indent-tabs-mode (tabify p (point-at-eol)))
9667 (org-move-to-column (min ncol col) t))
9668 (goto-char pos))))
9670 (defun org-set-tags (&optional arg just-align)
9671 "Set the tags for the current headline.
9672 With prefix ARG, realign all tags in headings in the current buffer."
9673 (interactive "P")
9674 (let* ((re (concat "^" outline-regexp))
9675 (current (org-get-tags-string))
9676 (col (current-column))
9677 (org-setting-tags t)
9678 table current-tags inherited-tags ; computed below when needed
9679 tags p0 c0 c1 rpl)
9680 (if arg
9681 (save-excursion
9682 (goto-char (point-min))
9683 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9684 (while (re-search-forward re nil t)
9685 (org-set-tags nil t)
9686 (end-of-line 1)))
9687 (message "All tags realigned to column %d" org-tags-column))
9688 (if just-align
9689 (setq tags current)
9690 ;; Get a new set of tags from the user
9691 (save-excursion
9692 (setq table (or org-tag-alist (org-get-buffer-tags))
9693 org-last-tags-completion-table table
9694 current-tags (org-split-string current ":")
9695 inherited-tags (nreverse
9696 (nthcdr (length current-tags)
9697 (nreverse (org-get-tags-at))))
9698 tags
9699 (if (or (eq t org-use-fast-tag-selection)
9700 (and org-use-fast-tag-selection
9701 (delq nil (mapcar 'cdr table))))
9702 (org-fast-tag-selection
9703 current-tags inherited-tags table
9704 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9705 (let ((org-add-colon-after-tag-completion t))
9706 (org-trim
9707 (org-without-partial-completion
9708 (completing-read "Tags: " 'org-tags-completion-function
9709 nil nil current 'org-tags-history)))))))
9710 (while (string-match "[-+&]+" tags)
9711 ;; No boolean logic, just a list
9712 (setq tags (replace-match ":" t t tags))))
9714 (if (string-match "\\`[\t ]*\\'" tags)
9715 (setq tags "")
9716 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9717 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9719 ;; Insert new tags at the correct column
9720 (beginning-of-line 1)
9721 (cond
9722 ((and (equal current "") (equal tags "")))
9723 ((re-search-forward
9724 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9725 (point-at-eol) t)
9726 (if (equal tags "")
9727 (setq rpl "")
9728 (goto-char (match-beginning 0))
9729 (setq c0 (current-column) p0 (point)
9730 c1 (max (1+ c0) (if (> org-tags-column 0)
9731 org-tags-column
9732 (- (- org-tags-column) (length tags))))
9733 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9734 (replace-match rpl t t)
9735 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9736 tags)
9737 (t (error "Tags alignment failed")))
9738 (org-move-to-column col)
9739 (unless just-align
9740 (run-hooks 'org-after-tags-change-hook)))))
9742 (defun org-change-tag-in-region (beg end tag off)
9743 "Add or remove TAG for each entry in the region.
9744 This works in the agenda, and also in an org-mode buffer."
9745 (interactive
9746 (list (region-beginning) (region-end)
9747 (let ((org-last-tags-completion-table
9748 (if (org-mode-p)
9749 (org-get-buffer-tags)
9750 (org-global-tags-completion-table))))
9751 (completing-read
9752 "Tag: " 'org-tags-completion-function nil nil nil
9753 'org-tags-history))
9754 (progn
9755 (message "[s]et or [r]emove? ")
9756 (equal (read-char-exclusive) ?r))))
9757 (if (fboundp 'deactivate-mark) (deactivate-mark))
9758 (let ((agendap (equal major-mode 'org-agenda-mode))
9759 l1 l2 m buf pos newhead (cnt 0))
9760 (goto-char end)
9761 (setq l2 (1- (org-current-line)))
9762 (goto-char beg)
9763 (setq l1 (org-current-line))
9764 (loop for l from l1 to l2 do
9765 (goto-line l)
9766 (setq m (get-text-property (point) 'org-hd-marker))
9767 (when (or (and (org-mode-p) (org-on-heading-p))
9768 (and agendap m))
9769 (setq buf (if agendap (marker-buffer m) (current-buffer))
9770 pos (if agendap m (point)))
9771 (with-current-buffer buf
9772 (save-excursion
9773 (save-restriction
9774 (goto-char pos)
9775 (setq cnt (1+ cnt))
9776 (org-toggle-tag tag (if off 'off 'on))
9777 (setq newhead (org-get-heading)))))
9778 (and agendap (org-agenda-change-all-lines newhead m))))
9779 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9781 (defun org-tags-completion-function (string predicate &optional flag)
9782 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9783 (confirm (lambda (x) (stringp (car x)))))
9784 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9785 (setq s1 (match-string 1 string)
9786 s2 (match-string 2 string))
9787 (setq s1 "" s2 string))
9788 (cond
9789 ((eq flag nil)
9790 ;; try completion
9791 (setq rtn (try-completion s2 ctable confirm))
9792 (if (stringp rtn)
9793 (setq rtn
9794 (concat s1 s2 (substring rtn (length s2))
9795 (if (and org-add-colon-after-tag-completion
9796 (assoc rtn ctable))
9797 ":" ""))))
9798 rtn)
9799 ((eq flag t)
9800 ;; all-completions
9801 (all-completions s2 ctable confirm)
9803 ((eq flag 'lambda)
9804 ;; exact match?
9805 (assoc s2 ctable)))
9808 (defun org-fast-tag-insert (kwd tags face &optional end)
9809 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9810 (insert (format "%-12s" (concat kwd ":"))
9811 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9812 (or end "")))
9814 (defun org-fast-tag-show-exit (flag)
9815 (save-excursion
9816 (goto-line 3)
9817 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9818 (replace-match ""))
9819 (when flag
9820 (end-of-line 1)
9821 (org-move-to-column (- (window-width) 19) t)
9822 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9824 (defun org-set-current-tags-overlay (current prefix)
9825 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9826 (if (featurep 'xemacs)
9827 (org-overlay-display org-tags-overlay (concat prefix s)
9828 'secondary-selection)
9829 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9830 (org-overlay-display org-tags-overlay (concat prefix s)))))
9832 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9833 "Fast tag selection with single keys.
9834 CURRENT is the current list of tags in the headline, INHERITED is the
9835 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9836 possibly with grouping information. TODO-TABLE is a similar table with
9837 TODO keywords, should these have keys assigned to them.
9838 If the keys are nil, a-z are automatically assigned.
9839 Returns the new tags string, or nil to not change the current settings."
9840 (let* ((fulltable (append table todo-table))
9841 (maxlen (apply 'max (mapcar
9842 (lambda (x)
9843 (if (stringp (car x)) (string-width (car x)) 0))
9844 fulltable)))
9845 (buf (current-buffer))
9846 (expert (eq org-fast-tag-selection-single-key 'expert))
9847 (buffer-tags nil)
9848 (fwidth (+ maxlen 3 1 3))
9849 (ncol (/ (- (window-width) 4) fwidth))
9850 (i-face 'org-done)
9851 (c-face 'org-todo)
9852 tg cnt e c char c1 c2 ntable tbl rtn
9853 ov-start ov-end ov-prefix
9854 (exit-after-next org-fast-tag-selection-single-key)
9855 (done-keywords org-done-keywords)
9856 groups ingroup)
9857 (save-excursion
9858 (beginning-of-line 1)
9859 (if (looking-at
9860 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9861 (setq ov-start (match-beginning 1)
9862 ov-end (match-end 1)
9863 ov-prefix "")
9864 (setq ov-start (1- (point-at-eol))
9865 ov-end (1+ ov-start))
9866 (skip-chars-forward "^\n\r")
9867 (setq ov-prefix
9868 (concat
9869 (buffer-substring (1- (point)) (point))
9870 (if (> (current-column) org-tags-column)
9872 (make-string (- org-tags-column (current-column)) ?\ ))))))
9873 (org-move-overlay org-tags-overlay ov-start ov-end)
9874 (save-window-excursion
9875 (if expert
9876 (set-buffer (get-buffer-create " *Org tags*"))
9877 (delete-other-windows)
9878 (split-window-vertically)
9879 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9880 (erase-buffer)
9881 (org-set-local 'org-done-keywords done-keywords)
9882 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9883 (org-fast-tag-insert "Current" current c-face "\n\n")
9884 (org-fast-tag-show-exit exit-after-next)
9885 (org-set-current-tags-overlay current ov-prefix)
9886 (setq tbl fulltable char ?a cnt 0)
9887 (while (setq e (pop tbl))
9888 (cond
9889 ((equal e '(:startgroup))
9890 (push '() groups) (setq ingroup t)
9891 (when (not (= cnt 0))
9892 (setq cnt 0)
9893 (insert "\n"))
9894 (insert "{ "))
9895 ((equal e '(:endgroup))
9896 (setq ingroup nil cnt 0)
9897 (insert "}\n"))
9899 (setq tg (car e) c2 nil)
9900 (if (cdr e)
9901 (setq c (cdr e))
9902 ;; automatically assign a character.
9903 (setq c1 (string-to-char
9904 (downcase (substring
9905 tg (if (= (string-to-char tg) ?@) 1 0)))))
9906 (if (or (rassoc c1 ntable) (rassoc c1 table))
9907 (while (or (rassoc char ntable) (rassoc char table))
9908 (setq char (1+ char)))
9909 (setq c2 c1))
9910 (setq c (or c2 char)))
9911 (if ingroup (push tg (car groups)))
9912 (setq tg (org-add-props tg nil 'face
9913 (cond
9914 ((not (assoc tg table))
9915 (org-get-todo-face tg))
9916 ((member tg current) c-face)
9917 ((member tg inherited) i-face)
9918 (t nil))))
9919 (if (and (= cnt 0) (not ingroup)) (insert " "))
9920 (insert "[" c "] " tg (make-string
9921 (- fwidth 4 (length tg)) ?\ ))
9922 (push (cons tg c) ntable)
9923 (when (= (setq cnt (1+ cnt)) ncol)
9924 (insert "\n")
9925 (if ingroup (insert " "))
9926 (setq cnt 0)))))
9927 (setq ntable (nreverse ntable))
9928 (insert "\n")
9929 (goto-char (point-min))
9930 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9931 (fit-window-to-buffer))
9932 (setq rtn
9933 (catch 'exit
9934 (while t
9935 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9936 (if groups " [!] no groups" " [!]groups")
9937 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9938 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9939 (cond
9940 ((= c ?\r) (throw 'exit t))
9941 ((= c ?!)
9942 (setq groups (not groups))
9943 (goto-char (point-min))
9944 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9945 ((= c ?\C-c)
9946 (if (not expert)
9947 (org-fast-tag-show-exit
9948 (setq exit-after-next (not exit-after-next)))
9949 (setq expert nil)
9950 (delete-other-windows)
9951 (split-window-vertically)
9952 (org-switch-to-buffer-other-window " *Org tags*")
9953 (and (fboundp 'fit-window-to-buffer)
9954 (fit-window-to-buffer))))
9955 ((or (= c ?\C-g)
9956 (and (= c ?q) (not (rassoc c ntable))))
9957 (org-detach-overlay org-tags-overlay)
9958 (setq quit-flag t))
9959 ((= c ?\ )
9960 (setq current nil)
9961 (if exit-after-next (setq exit-after-next 'now)))
9962 ((= c ?\t)
9963 (condition-case nil
9964 (setq tg (completing-read
9965 "Tag: "
9966 (or buffer-tags
9967 (with-current-buffer buf
9968 (org-get-buffer-tags)))))
9969 (quit (setq tg "")))
9970 (when (string-match "\\S-" tg)
9971 (add-to-list 'buffer-tags (list tg))
9972 (if (member tg current)
9973 (setq current (delete tg current))
9974 (push tg current)))
9975 (if exit-after-next (setq exit-after-next 'now)))
9976 ((setq e (rassoc c todo-table) tg (car e))
9977 (with-current-buffer buf
9978 (save-excursion (org-todo tg)))
9979 (if exit-after-next (setq exit-after-next 'now)))
9980 ((setq e (rassoc c ntable) tg (car e))
9981 (if (member tg current)
9982 (setq current (delete tg current))
9983 (loop for g in groups do
9984 (if (member tg g)
9985 (mapc (lambda (x)
9986 (setq current (delete x current)))
9987 g)))
9988 (push tg current))
9989 (if exit-after-next (setq exit-after-next 'now))))
9991 ;; Create a sorted list
9992 (setq current
9993 (sort current
9994 (lambda (a b)
9995 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9996 (if (eq exit-after-next 'now) (throw 'exit t))
9997 (goto-char (point-min))
9998 (beginning-of-line 2)
9999 (delete-region (point) (point-at-eol))
10000 (org-fast-tag-insert "Current" current c-face)
10001 (org-set-current-tags-overlay current ov-prefix)
10002 (while (re-search-forward
10003 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
10004 (setq tg (match-string 1))
10005 (add-text-properties
10006 (match-beginning 1) (match-end 1)
10007 (list 'face
10008 (cond
10009 ((member tg current) c-face)
10010 ((member tg inherited) i-face)
10011 (t (get-text-property (match-beginning 1) 'face))))))
10012 (goto-char (point-min)))))
10013 (org-detach-overlay org-tags-overlay)
10014 (if rtn
10015 (mapconcat 'identity current ":")
10016 nil))))
10018 (defun org-get-tags-string ()
10019 "Get the TAGS string in the current headline."
10020 (unless (org-on-heading-p t)
10021 (error "Not on a heading"))
10022 (save-excursion
10023 (beginning-of-line 1)
10024 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
10025 (org-match-string-no-properties 1)
10026 "")))
10028 (defun org-get-tags ()
10029 "Get the list of tags specified in the current headline."
10030 (org-split-string (org-get-tags-string) ":"))
10032 (defun org-get-buffer-tags ()
10033 "Get a table of all tags used in the buffer, for completion."
10034 (let (tags)
10035 (save-excursion
10036 (goto-char (point-min))
10037 (while (re-search-forward
10038 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
10039 (when (equal (char-after (point-at-bol 0)) ?*)
10040 (mapc (lambda (x) (add-to-list 'tags x))
10041 (org-split-string (org-match-string-no-properties 1) ":")))))
10042 (mapcar 'list tags)))
10044 ;;;; The mapping API
10046 ;;;###autoload
10047 (defun org-map-entries (func &optional match scope &rest skip)
10048 "Call FUNC at each headline selected by MATCH in SCOPE.
10050 FUNC is a function or a lisp form. The function will be called without
10051 arguments, with the cursor positioned at the beginning of the headline.
10052 The return values of all calls to the function will be collected and
10053 returned as a list.
10055 MATCH is a tags/property/todo match as it is used in the agenda tags view.
10056 Only headlines that are matched by this query will be considered during
10057 the iteration. When MATCH is nil or t, all headlines will be
10058 visited by the iteration.
10060 SCOPE determines the scope of this command. It can be any of:
10062 nil The current buffer, respecting the restriction if any
10063 tree The subtree started with the entry at point
10064 file The current buffer, without restriction
10065 file-with-archives
10066 The current buffer, and any archives associated with it
10067 agenda All agenda files
10068 agenda-with-archives
10069 All agenda files with any archive files associated with them
10070 \(file1 file2 ...)
10071 If this is a list, all files in the list will be scanned
10073 The remaining args are treated as settings for the skipping facilities of
10074 the scanner. The following items can be given here:
10076 archive skip trees with the archive tag.
10077 comment skip trees with the COMMENT keyword
10078 function or Emacs Lisp form:
10079 will be used as value for `org-agenda-skip-function', so whenever
10080 the the function returns t, FUNC will not be called for that
10081 entry and search will continue from the point where the
10082 function leaves it."
10083 (let* ((org-agenda-archives-mode nil) ; just to make sure
10084 (org-agenda-skip-archived-trees (memq 'archive skip))
10085 (org-agenda-skip-comment-trees (memq 'comment skip))
10086 (org-agenda-skip-function
10087 (car (org-delete-all '(comment archive) skip)))
10088 (org-tags-match-list-sublevels t)
10089 matcher pos file)
10091 (cond
10092 ((eq match t) (setq matcher t))
10093 ((eq match nil) (setq matcher t))
10094 (t (setq matcher (if match (org-make-tags-matcher match) t))))
10096 (when (eq scope 'tree)
10097 (org-back-to-heading t)
10098 (org-narrow-to-subtree)
10099 (setq scope nil))
10101 (if (not scope)
10102 (progn
10103 (org-prepare-agenda-buffers
10104 (list (buffer-file-name (current-buffer))))
10105 (org-scan-tags func matcher))
10106 ;; Get the right scope
10107 (setq pos (point))
10108 (cond
10109 ((and scope (listp scope) (symbolp (car scope)))
10110 (setq scope (eval scope)))
10111 ((eq scope 'agenda)
10112 (setq scope (org-agenda-files t)))
10113 ((eq scope 'agenda-with-archives)
10114 (setq scope (org-agenda-files t))
10115 (setq scope (org-add-archive-files scope)))
10116 ((eq scope 'file)
10117 (setq scope (list (buffer-file-name))))
10118 ((eq scope 'file-with-archives)
10119 (setq scope (org-add-archive-files (list (buffer-file-name))))))
10120 (org-prepare-agenda-buffers scope)
10121 (while (setq file (pop scope))
10122 (with-current-buffer (org-find-base-buffer-visiting file)
10123 (save-excursion
10124 (save-restriction
10125 (widen)
10126 (goto-char (point-min))
10127 (org-scan-tags func matcher))))))))
10129 ;;;; Properties
10131 ;;; Setting and retrieving properties
10133 (defconst org-special-properties
10134 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
10135 "TIMESTAMP" "TIMESTAMP_IA")
10136 "The special properties valid in Org-mode.
10138 These are properties that are not defined in the property drawer,
10139 but in some other way.")
10141 (defconst org-default-properties
10142 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
10143 "LOCATION" "LOGGING" "COLUMNS" "VISIBILITY"
10144 "TABLE_EXPORT_FORMAT" "TABLE_EXPORT_FILE"
10145 "EXPORT_FILE_NAME" "EXPORT_TITLE")
10146 "Some properties that are used by Org-mode for various purposes.
10147 Being in this list makes sure that they are offered for completion.")
10149 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
10150 "Regular expression matching the first line of a property drawer.")
10152 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
10153 "Regular expression matching the first line of a property drawer.")
10155 (defconst org-clock-drawer-start-re "^[ \t]*:CLOCK:[ \t]*$"
10156 "Regular expression matching the first line of a property drawer.")
10158 (defconst org-clock-drawer-end-re "^[ \t]*:END:[ \t]*$"
10159 "Regular expression matching the first line of a property drawer.")
10161 (defconst org-property-drawer-re
10162 (concat "\\(" org-property-start-re "\\)[^\000]*\\("
10163 org-property-end-re "\\)\n?")
10164 "Matches an entire property drawer.")
10166 (defconst org-clock-drawer-re
10167 (concat "\\(" org-clock-drawer-start-re "\\)[^\000]*\\("
10168 org-property-end-re "\\)\n?")
10169 "Matches an entire clock drawer.")
10171 (defun org-property-action ()
10172 "Do an action on properties."
10173 (interactive)
10174 (let (c)
10175 (org-at-property-p)
10176 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
10177 (setq c (read-char-exclusive))
10178 (cond
10179 ((equal c ?s)
10180 (call-interactively 'org-set-property))
10181 ((equal c ?d)
10182 (call-interactively 'org-delete-property))
10183 ((equal c ?D)
10184 (call-interactively 'org-delete-property-globally))
10185 ((equal c ?c)
10186 (call-interactively 'org-compute-property-at-point))
10187 (t (error "No such property action %c" c)))))
10189 (defun org-at-property-p ()
10190 "Is the cursor in a property line?"
10191 ;; FIXME: Does not check if we are actually in the drawer.
10192 ;; FIXME: also returns true on any drawers.....
10193 ;; This is used by C-c C-c for property action.
10194 (save-excursion
10195 (beginning-of-line 1)
10196 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
10198 (defun org-get-property-block (&optional beg end force)
10199 "Return the (beg . end) range of the body of the property drawer.
10200 BEG and END can be beginning and end of subtree, if not given
10201 they will be found.
10202 If the drawer does not exist and FORCE is non-nil, create the drawer."
10203 (catch 'exit
10204 (save-excursion
10205 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
10206 (end (or end (progn (outline-next-heading) (point)))))
10207 (goto-char beg)
10208 (if (re-search-forward org-property-start-re end t)
10209 (setq beg (1+ (match-end 0)))
10210 (if force
10211 (save-excursion
10212 (org-insert-property-drawer)
10213 (setq end (progn (outline-next-heading) (point))))
10214 (throw 'exit nil))
10215 (goto-char beg)
10216 (if (re-search-forward org-property-start-re end t)
10217 (setq beg (1+ (match-end 0)))))
10218 (if (re-search-forward org-property-end-re end t)
10219 (setq end (match-beginning 0))
10220 (or force (throw 'exit nil))
10221 (goto-char beg)
10222 (setq end beg)
10223 (org-indent-line-function)
10224 (insert ":END:\n"))
10225 (cons beg end)))))
10227 (defun org-entry-properties (&optional pom which)
10228 "Get all properties of the entry at point-or-marker POM.
10229 This includes the TODO keyword, the tags, time strings for deadline,
10230 scheduled, and clocking, and any additional properties defined in the
10231 entry. The return value is an alist, keys may occur multiple times
10232 if the property key was used several times.
10233 POM may also be nil, in which case the current entry is used.
10234 If WHICH is nil or `all', get all properties. If WHICH is
10235 `special' or `standard', only get that subclass."
10236 (setq which (or which 'all))
10237 (org-with-point-at pom
10238 (let ((clockstr (substring org-clock-string 0 -1))
10239 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
10240 beg end range props sum-props key value string clocksum)
10241 (save-excursion
10242 (when (condition-case nil (org-back-to-heading t) (error nil))
10243 (setq beg (point))
10244 (setq sum-props (get-text-property (point) 'org-summaries))
10245 (setq clocksum (get-text-property (point) :org-clock-minutes))
10246 (outline-next-heading)
10247 (setq end (point))
10248 (when (memq which '(all special))
10249 ;; Get the special properties, like TODO and tags
10250 (goto-char beg)
10251 (when (and (looking-at org-todo-line-regexp) (match-end 2))
10252 (push (cons "TODO" (org-match-string-no-properties 2)) props))
10253 (when (looking-at org-priority-regexp)
10254 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
10255 (when (and (setq value (org-get-tags-string))
10256 (string-match "\\S-" value))
10257 (push (cons "TAGS" value) props))
10258 (when (setq value (org-get-tags-at))
10259 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
10260 props))
10261 (while (re-search-forward org-maybe-keyword-time-regexp end t)
10262 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
10263 string (if (equal key clockstr)
10264 (org-no-properties
10265 (org-trim
10266 (buffer-substring
10267 (match-beginning 3) (goto-char (point-at-eol)))))
10268 (substring (org-match-string-no-properties 3) 1 -1)))
10269 (unless key
10270 (if (= (char-after (match-beginning 3)) ?\[)
10271 (setq key "TIMESTAMP_IA")
10272 (setq key "TIMESTAMP")))
10273 (when (or (equal key clockstr) (not (assoc key props)))
10274 (push (cons key string) props)))
10278 (when (memq which '(all standard))
10279 ;; Get the standard properties, like :PORP: ...
10280 (setq range (org-get-property-block beg end))
10281 (when range
10282 (goto-char (car range))
10283 (while (re-search-forward
10284 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
10285 (cdr range) t)
10286 (setq key (org-match-string-no-properties 1)
10287 value (org-trim (or (org-match-string-no-properties 2) "")))
10288 (unless (member key excluded)
10289 (push (cons key (or value "")) props)))))
10290 (if clocksum
10291 (push (cons "CLOCKSUM"
10292 (org-columns-number-to-string (/ (float clocksum) 60.)
10293 'add_times))
10294 props))
10295 (append sum-props (nreverse props)))))))
10297 (defun org-entry-get (pom property &optional inherit)
10298 "Get value of PROPERTY for entry at point-or-marker POM.
10299 If INHERIT is non-nil and the entry does not have the property,
10300 then also check higher levels of the hierarchy.
10301 If INHERIT is the symbol `selective', use inheritance only if the setting
10302 in `org-use-property-inheritance' selects PROPERTY for inheritance.
10303 If the property is present but empty, the return value is the empty string.
10304 If the property is not present at all, nil is returned."
10305 (org-with-point-at pom
10306 (if (and inherit (if (eq inherit 'selective)
10307 (org-property-inherit-p property)
10309 (org-entry-get-with-inheritance property)
10310 (if (member property org-special-properties)
10311 ;; We need a special property. Use brute force, get all properties.
10312 (cdr (assoc property (org-entry-properties nil 'special)))
10313 (let ((range (org-get-property-block)))
10314 (if (and range
10315 (goto-char (car range))
10316 (re-search-forward
10317 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
10318 (cdr range) t))
10319 ;; Found the property, return it.
10320 (if (match-end 1)
10321 (org-match-string-no-properties 1)
10322 "")))))))
10324 (defun org-property-or-variable-value (var &optional inherit)
10325 "Check if there is a property fixing the value of VAR.
10326 If yes, return this value. If not, return the current value of the variable."
10327 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
10328 (if (and prop (stringp prop) (string-match "\\S-" prop))
10329 (read prop)
10330 (symbol-value var))))
10332 (defun org-entry-delete (pom property)
10333 "Delete the property PROPERTY from entry at point-or-marker POM."
10334 (org-with-point-at pom
10335 (if (member property org-special-properties)
10336 nil ; cannot delete these properties.
10337 (let ((range (org-get-property-block)))
10338 (if (and range
10339 (goto-char (car range))
10340 (re-search-forward
10341 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
10342 (cdr range) t))
10343 (progn
10344 (delete-region (match-beginning 0) (1+ (point-at-eol)))
10346 nil)))))
10348 ;; Multi-values properties are properties that contain multiple values
10349 ;; These values are assumed to be single words, separated by whitespace.
10350 (defun org-entry-add-to-multivalued-property (pom property value)
10351 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
10352 (let* ((old (org-entry-get pom property))
10353 (values (and old (org-split-string old "[ \t]"))))
10354 (unless (member value values)
10355 (setq values (cons value values))
10356 (org-entry-put pom property
10357 (mapconcat 'identity values " ")))))
10359 (defun org-entry-remove-from-multivalued-property (pom property value)
10360 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
10361 (let* ((old (org-entry-get pom property))
10362 (values (and old (org-split-string old "[ \t]"))))
10363 (when (member value values)
10364 (setq values (delete value values))
10365 (org-entry-put pom property
10366 (mapconcat 'identity values " ")))))
10368 (defun org-entry-member-in-multivalued-property (pom property value)
10369 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
10370 (let* ((old (org-entry-get pom property))
10371 (values (and old (org-split-string old "[ \t]"))))
10372 (member value values)))
10374 (defvar org-entry-property-inherited-from (make-marker))
10376 (defun org-entry-get-with-inheritance (property)
10377 "Get entry property, and search higher levels if not present."
10378 (let (tmp)
10379 (save-excursion
10380 (save-restriction
10381 (widen)
10382 (catch 'ex
10383 (while t
10384 (when (setq tmp (org-entry-get nil property))
10385 (org-back-to-heading t)
10386 (move-marker org-entry-property-inherited-from (point))
10387 (throw 'ex tmp))
10388 (or (org-up-heading-safe) (throw 'ex nil)))))
10389 (or tmp
10390 (cdr (assoc property org-file-properties))
10391 (cdr (assoc property org-global-properties))
10392 (cdr (assoc property org-global-properties-fixed))))))
10394 (defun org-entry-put (pom property value)
10395 "Set PROPERTY to VALUE for entry at point-or-marker POM."
10396 (org-with-point-at pom
10397 (org-back-to-heading t)
10398 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
10399 range)
10400 (cond
10401 ((equal property "TODO")
10402 (when (and (stringp value) (string-match "\\S-" value)
10403 (not (member value org-todo-keywords-1)))
10404 (error "\"%s\" is not a valid TODO state" value))
10405 (if (or (not value)
10406 (not (string-match "\\S-" value)))
10407 (setq value 'none))
10408 (org-todo value)
10409 (org-set-tags nil 'align))
10410 ((equal property "PRIORITY")
10411 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
10412 (string-to-char value) ?\ ))
10413 (org-set-tags nil 'align))
10414 ((equal property "SCHEDULED")
10415 (if (re-search-forward org-scheduled-time-regexp end t)
10416 (cond
10417 ((eq value 'earlier) (org-timestamp-change -1 'day))
10418 ((eq value 'later) (org-timestamp-change 1 'day))
10419 (t (call-interactively 'org-schedule)))
10420 (call-interactively 'org-schedule)))
10421 ((equal property "DEADLINE")
10422 (if (re-search-forward org-deadline-time-regexp end t)
10423 (cond
10424 ((eq value 'earlier) (org-timestamp-change -1 'day))
10425 ((eq value 'later) (org-timestamp-change 1 'day))
10426 (t (call-interactively 'org-deadline)))
10427 (call-interactively 'org-deadline)))
10428 ((member property org-special-properties)
10429 (error "The %s property can not yet be set with `org-entry-put'"
10430 property))
10431 (t ; a non-special property
10432 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
10433 (setq range (org-get-property-block beg end 'force))
10434 (goto-char (car range))
10435 (if (re-search-forward
10436 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
10437 (progn
10438 (delete-region (match-beginning 1) (match-end 1))
10439 (goto-char (match-beginning 1)))
10440 (goto-char (cdr range))
10441 (insert "\n")
10442 (backward-char 1)
10443 (org-indent-line-function)
10444 (insert ":" property ":"))
10445 (and value (insert " " value))
10446 (org-indent-line-function)))))))
10448 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
10449 "Get all property keys in the current buffer.
10450 With INCLUDE-SPECIALS, also list the special properties that relect things
10451 like tags and TODO state.
10452 With INCLUDE-DEFAULTS, also include properties that has special meaning
10453 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
10454 With INCLUDE-COLUMNS, also include property names given in COLUMN
10455 formats in the current buffer."
10456 (let (rtn range cfmt cols s p)
10457 (save-excursion
10458 (save-restriction
10459 (widen)
10460 (goto-char (point-min))
10461 (while (re-search-forward org-property-start-re nil t)
10462 (setq range (org-get-property-block))
10463 (goto-char (car range))
10464 (while (re-search-forward
10465 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
10466 (cdr range) t)
10467 (add-to-list 'rtn (org-match-string-no-properties 1)))
10468 (outline-next-heading))))
10470 (when include-specials
10471 (setq rtn (append org-special-properties rtn)))
10473 (when include-defaults
10474 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
10476 (when include-columns
10477 (save-excursion
10478 (save-restriction
10479 (widen)
10480 (goto-char (point-min))
10481 (while (re-search-forward
10482 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
10483 nil t)
10484 (setq cfmt (match-string 2) s 0)
10485 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
10486 cfmt s)
10487 (setq s (match-end 0)
10488 p (match-string 1 cfmt))
10489 (unless (or (equal p "ITEM")
10490 (member p org-special-properties))
10491 (add-to-list 'rtn (match-string 1 cfmt))))))))
10493 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
10495 (defun org-property-values (key)
10496 "Return a list of all values of property KEY."
10497 (save-excursion
10498 (save-restriction
10499 (widen)
10500 (goto-char (point-min))
10501 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
10502 values)
10503 (while (re-search-forward re nil t)
10504 (add-to-list 'values (org-trim (match-string 1))))
10505 (delete "" values)))))
10507 (defun org-insert-property-drawer ()
10508 "Insert a property drawer into the current entry."
10509 (interactive)
10510 (org-back-to-heading t)
10511 (looking-at outline-regexp)
10512 (let ((indent (- (match-end 0)(match-beginning 0)))
10513 (beg (point))
10514 (re (concat "^[ \t]*" org-keyword-time-regexp))
10515 end hiddenp)
10516 (outline-next-heading)
10517 (setq end (point))
10518 (goto-char beg)
10519 (while (re-search-forward re end t))
10520 (setq hiddenp (org-invisible-p))
10521 (end-of-line 1)
10522 (and (equal (char-after) ?\n) (forward-char 1))
10523 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
10524 (beginning-of-line 2))
10525 (org-skip-over-state-notes)
10526 (skip-chars-backward " \t\n\r")
10527 (if (eq (char-before) ?*) (forward-char 1))
10528 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
10529 (beginning-of-line 0)
10530 (org-indent-to-column indent)
10531 (beginning-of-line 2)
10532 (org-indent-to-column indent)
10533 (beginning-of-line 0)
10534 (if hiddenp
10535 (save-excursion
10536 (org-back-to-heading t)
10537 (hide-entry))
10538 (org-flag-drawer t))))
10540 (defun org-set-property (property value)
10541 "In the current entry, set PROPERTY to VALUE.
10542 When called interactively, this will prompt for a property name, offering
10543 completion on existing and default properties. And then it will prompt
10544 for a value, offering competion either on allowed values (via an inherited
10545 xxx_ALL property) or on existing values in other instances of this property
10546 in the current file."
10547 (interactive
10548 (let* ((completion-ignore-case t)
10549 (keys (org-buffer-property-keys nil t t))
10550 (prop0 (completing-read "Property: " (mapcar 'list keys)))
10551 (prop (if (member prop0 keys)
10552 prop0
10553 (or (cdr (assoc (downcase prop0)
10554 (mapcar (lambda (x) (cons (downcase x) x))
10555 keys)))
10556 prop0)))
10557 (cur (org-entry-get nil prop))
10558 (allowed (org-property-get-allowed-values nil prop 'table))
10559 (existing (mapcar 'list (org-property-values prop)))
10560 (val (if allowed
10561 (org-completing-read "Value: " allowed nil 'req-match)
10562 (org-completing-read
10563 (concat "Value" (if (and cur (string-match "\\S-" cur))
10564 (concat "[" cur "]") "")
10565 ": ")
10566 existing nil nil "" nil cur))))
10567 (list prop (if (equal val "") cur val))))
10568 (unless (equal (org-entry-get nil property) value)
10569 (org-entry-put nil property value)))
10571 (defun org-delete-property (property)
10572 "In the current entry, delete PROPERTY."
10573 (interactive
10574 (let* ((completion-ignore-case t)
10575 (prop (completing-read
10576 "Property: " (org-entry-properties nil 'standard))))
10577 (list prop)))
10578 (message "Property %s %s" property
10579 (if (org-entry-delete nil property)
10580 "deleted"
10581 "was not present in the entry")))
10583 (defun org-delete-property-globally (property)
10584 "Remove PROPERTY globally, from all entries."
10585 (interactive
10586 (let* ((completion-ignore-case t)
10587 (prop (completing-read
10588 "Globally remove property: "
10589 (mapcar 'list (org-buffer-property-keys)))))
10590 (list prop)))
10591 (save-excursion
10592 (save-restriction
10593 (widen)
10594 (goto-char (point-min))
10595 (let ((cnt 0))
10596 (while (re-search-forward
10597 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
10598 nil t)
10599 (setq cnt (1+ cnt))
10600 (replace-match ""))
10601 (message "Property \"%s\" removed from %d entries" property cnt)))))
10603 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
10605 (defun org-compute-property-at-point ()
10606 "Compute the property at point.
10607 This looks for an enclosing column format, extracts the operator and
10608 then applies it to the proerty in the column format's scope."
10609 (interactive)
10610 (unless (org-at-property-p)
10611 (error "Not at a property"))
10612 (let ((prop (org-match-string-no-properties 2)))
10613 (org-columns-get-format-and-top-level)
10614 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
10615 (error "No operator defined for property %s" prop))
10616 (org-columns-compute prop)))
10618 (defun org-property-get-allowed-values (pom property &optional table)
10619 "Get allowed values for the property PROPERTY.
10620 When TABLE is non-nil, return an alist that can directly be used for
10621 completion."
10622 (let (vals)
10623 (cond
10624 ((equal property "TODO")
10625 (setq vals (org-with-point-at pom
10626 (append org-todo-keywords-1 '("")))))
10627 ((equal property "PRIORITY")
10628 (let ((n org-lowest-priority))
10629 (while (>= n org-highest-priority)
10630 (push (char-to-string n) vals)
10631 (setq n (1- n)))))
10632 ((member property org-special-properties))
10634 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
10636 (when (and vals (string-match "\\S-" vals))
10637 (setq vals (car (read-from-string (concat "(" vals ")"))))
10638 (setq vals (mapcar (lambda (x)
10639 (cond ((stringp x) x)
10640 ((numberp x) (number-to-string x))
10641 ((symbolp x) (symbol-name x))
10642 (t "???")))
10643 vals)))))
10644 (if table (mapcar 'list vals) vals)))
10646 (defun org-property-previous-allowed-value (&optional previous)
10647 "Switch to the next allowed value for this property."
10648 (interactive)
10649 (org-property-next-allowed-value t))
10651 (defun org-property-next-allowed-value (&optional previous)
10652 "Switch to the next allowed value for this property."
10653 (interactive)
10654 (unless (org-at-property-p)
10655 (error "Not at a property"))
10656 (let* ((key (match-string 2))
10657 (value (match-string 3))
10658 (allowed (or (org-property-get-allowed-values (point) key)
10659 (and (member value '("[ ]" "[-]" "[X]"))
10660 '("[ ]" "[X]"))))
10661 nval)
10662 (unless allowed
10663 (error "Allowed values for this property have not been defined"))
10664 (if previous (setq allowed (reverse allowed)))
10665 (if (member value allowed)
10666 (setq nval (car (cdr (member value allowed)))))
10667 (setq nval (or nval (car allowed)))
10668 (if (equal nval value)
10669 (error "Only one allowed value for this property"))
10670 (org-at-property-p)
10671 (replace-match (concat " :" key ": " nval) t t)
10672 (org-indent-line-function)
10673 (beginning-of-line 1)
10674 (skip-chars-forward " \t")))
10676 (defun org-find-entry-with-id (ident)
10677 "Locate the entry that contains the ID property with exact value IDENT.
10678 IDENT can be a string, a symbol or a number, this function will search for
10679 the string representation of it.
10680 Return the position where this entry starts, or nil if there is no such entry."
10681 (let ((id (cond
10682 ((stringp ident) ident)
10683 ((symbol-name ident) (symbol-name ident))
10684 ((numberp ident) (number-to-string ident))
10685 (t (error "IDENT %s must be a string, symbol or number" ident))))
10686 (case-fold-search nil))
10687 (save-excursion
10688 (save-restriction
10689 (widen)
10690 (goto-char (point-min))
10691 (when (re-search-forward
10692 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
10693 nil t)
10694 (org-back-to-heading)
10695 (point))))))
10697 ;;;; Timestamps
10699 (defvar org-last-changed-timestamp nil)
10700 (defvar org-last-inserted-timestamp nil
10701 "The last time stamp inserted with `org-insert-time-stamp'.")
10702 (defvar org-time-was-given) ; dynamically scoped parameter
10703 (defvar org-end-time-was-given) ; dynamically scoped parameter
10704 (defvar org-ts-what) ; dynamically scoped parameter
10706 (defun org-time-stamp (arg)
10707 "Prompt for a date/time and insert a time stamp.
10708 If the user specifies a time like HH:MM, or if this command is called
10709 with a prefix argument, the time stamp will contain date and time.
10710 Otherwise, only the date will be included. All parts of a date not
10711 specified by the user will be filled in from the current date/time.
10712 So if you press just return without typing anything, the time stamp
10713 will represent the current date/time. If there is already a timestamp
10714 at the cursor, it will be modified."
10715 (interactive "P")
10716 (let* ((ts nil)
10717 (default-time
10718 ;; Default time is either today, or, when entering a range,
10719 ;; the range start.
10720 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
10721 (save-excursion
10722 (re-search-backward
10723 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
10724 (- (point) 20) t)))
10725 (apply 'encode-time (org-parse-time-string (match-string 1)))
10726 (current-time)))
10727 (default-input (and ts (org-get-compact-tod ts)))
10728 org-time-was-given org-end-time-was-given time)
10729 (cond
10730 ((and (org-at-timestamp-p)
10731 (eq last-command 'org-time-stamp)
10732 (eq this-command 'org-time-stamp))
10733 (insert "--")
10734 (setq time (let ((this-command this-command))
10735 (org-read-date arg 'totime nil nil default-time default-input)))
10736 (org-insert-time-stamp time (or org-time-was-given arg)))
10737 ((org-at-timestamp-p)
10738 (setq time (let ((this-command this-command))
10739 (org-read-date arg 'totime nil nil default-time default-input)))
10740 (when (org-at-timestamp-p) ; just to get the match data
10741 (replace-match "")
10742 (setq org-last-changed-timestamp
10743 (org-insert-time-stamp
10744 time (or org-time-was-given arg)
10745 nil nil nil (list org-end-time-was-given))))
10746 (message "Timestamp updated"))
10748 (setq time (let ((this-command this-command))
10749 (org-read-date arg 'totime nil nil default-time default-input)))
10750 (org-insert-time-stamp time (or org-time-was-given arg)
10751 nil nil nil (list org-end-time-was-given))))))
10753 ;; FIXME: can we use this for something else, like computing time differences?
10754 (defun org-get-compact-tod (s)
10755 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
10756 (let* ((t1 (match-string 1 s))
10757 (h1 (string-to-number (match-string 2 s)))
10758 (m1 (string-to-number (match-string 3 s)))
10759 (t2 (and (match-end 4) (match-string 5 s)))
10760 (h2 (and t2 (string-to-number (match-string 6 s))))
10761 (m2 (and t2 (string-to-number (match-string 7 s))))
10762 dh dm)
10763 (if (not t2)
10765 (setq dh (- h2 h1) dm (- m2 m1))
10766 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
10767 (concat t1 "+" (number-to-string dh)
10768 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
10770 (defun org-time-stamp-inactive (&optional arg)
10771 "Insert an inactive time stamp.
10772 An inactive time stamp is enclosed in square brackets instead of angle
10773 brackets. It is inactive in the sense that it does not trigger agenda entries,
10774 does not link to the calendar and cannot be changed with the S-cursor keys.
10775 So these are more for recording a certain time/date."
10776 (interactive "P")
10777 (let (org-time-was-given org-end-time-was-given time)
10778 (setq time (org-read-date arg 'totime))
10779 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
10780 nil nil (list org-end-time-was-given))))
10782 (defvar org-date-ovl (org-make-overlay 1 1))
10783 (org-overlay-put org-date-ovl 'face 'org-warning)
10784 (org-detach-overlay org-date-ovl)
10786 (defvar org-ans1) ; dynamically scoped parameter
10787 (defvar org-ans2) ; dynamically scoped parameter
10789 (defvar org-plain-time-of-day-regexp) ; defined below
10791 (defvar org-overriding-default-time nil) ; dynamically scoped
10792 (defvar org-read-date-overlay nil)
10793 (defvar org-dcst nil) ; dynamically scoped
10795 (defun org-read-date (&optional with-time to-time from-string prompt
10796 default-time default-input)
10797 "Read a date, possibly a time, and make things smooth for the user.
10798 The prompt will suggest to enter an ISO date, but you can also enter anything
10799 which will at least partially be understood by `parse-time-string'.
10800 Unrecognized parts of the date will default to the current day, month, year,
10801 hour and minute. If this command is called to replace a timestamp at point,
10802 of to enter the second timestamp of a range, the default time is taken from the
10803 existing stamp. For example,
10804 3-2-5 --> 2003-02-05
10805 feb 15 --> currentyear-02-15
10806 sep 12 9 --> 2009-09-12
10807 12:45 --> today 12:45
10808 22 sept 0:34 --> currentyear-09-22 0:34
10809 12 --> currentyear-currentmonth-12
10810 Fri --> nearest Friday (today or later)
10811 etc.
10813 Furthermore you can specify a relative date by giving, as the *first* thing
10814 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10815 change in days weeks, months, years.
10816 With a single plus or minus, the date is relative to today. With a double
10817 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10818 +4d --> four days from today
10819 +4 --> same as above
10820 +2w --> two weeks from today
10821 ++5 --> five days from default date
10823 The function understands only English month and weekday abbreviations,
10824 but this can be configured with the variables `parse-time-months' and
10825 `parse-time-weekdays'.
10827 While prompting, a calendar is popped up - you can also select the
10828 date with the mouse (button 1). The calendar shows a period of three
10829 months. To scroll it to other months, use the keys `>' and `<'.
10830 If you don't like the calendar, turn it off with
10831 \(setq org-read-date-popup-calendar nil)
10833 With optional argument TO-TIME, the date will immediately be converted
10834 to an internal time.
10835 With an optional argument WITH-TIME, the prompt will suggest to also
10836 insert a time. Note that when WITH-TIME is not set, you can still
10837 enter a time, and this function will inform the calling routine about
10838 this change. The calling routine may then choose to change the format
10839 used to insert the time stamp into the buffer to include the time.
10840 With optional argument FROM-STRING, read from this string instead from
10841 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10842 the time/date that is used for everything that is not specified by the
10843 user."
10844 (require 'parse-time)
10845 (let* ((org-time-stamp-rounding-minutes
10846 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10847 (org-dcst org-display-custom-times)
10848 (ct (org-current-time))
10849 (def (or org-overriding-default-time default-time ct))
10850 (defdecode (decode-time def))
10851 (dummy (progn
10852 (when (< (nth 2 defdecode) org-extend-today-until)
10853 (setcar (nthcdr 2 defdecode) -1)
10854 (setcar (nthcdr 1 defdecode) 59)
10855 (setq def (apply 'encode-time defdecode)
10856 defdecode (decode-time def)))))
10857 (calendar-move-hook nil)
10858 (calendar-view-diary-initially-flag nil)
10859 (view-diary-entries-initially nil)
10860 (calendar-view-holidays-initially-flag nil)
10861 (view-calendar-holidays-initially nil)
10862 (timestr (format-time-string
10863 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10864 (prompt (concat (if prompt (concat prompt " ") "")
10865 (format "Date+time [%s]: " timestr)))
10866 ans (org-ans0 "") org-ans1 org-ans2 final)
10868 (cond
10869 (from-string (setq ans from-string))
10870 (org-read-date-popup-calendar
10871 (save-excursion
10872 (save-window-excursion
10873 (calendar)
10874 (calendar-forward-day (- (time-to-days def)
10875 (calendar-absolute-from-gregorian
10876 (calendar-current-date))))
10877 (org-eval-in-calendar nil t)
10878 (let* ((old-map (current-local-map))
10879 (map (copy-keymap calendar-mode-map))
10880 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10881 (org-defkey map (kbd "RET") 'org-calendar-select)
10882 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10883 'org-calendar-select-mouse)
10884 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10885 'org-calendar-select-mouse)
10886 (org-defkey minibuffer-local-map [(meta shift left)]
10887 (lambda () (interactive)
10888 (org-eval-in-calendar '(calendar-backward-month 1))))
10889 (org-defkey minibuffer-local-map [(meta shift right)]
10890 (lambda () (interactive)
10891 (org-eval-in-calendar '(calendar-forward-month 1))))
10892 (org-defkey minibuffer-local-map [(meta shift up)]
10893 (lambda () (interactive)
10894 (org-eval-in-calendar '(calendar-backward-year 1))))
10895 (org-defkey minibuffer-local-map [(meta shift down)]
10896 (lambda () (interactive)
10897 (org-eval-in-calendar '(calendar-forward-year 1))))
10898 (org-defkey minibuffer-local-map [(shift up)]
10899 (lambda () (interactive)
10900 (org-eval-in-calendar '(calendar-backward-week 1))))
10901 (org-defkey minibuffer-local-map [(shift down)]
10902 (lambda () (interactive)
10903 (org-eval-in-calendar '(calendar-forward-week 1))))
10904 (org-defkey minibuffer-local-map [(shift left)]
10905 (lambda () (interactive)
10906 (org-eval-in-calendar '(calendar-backward-day 1))))
10907 (org-defkey minibuffer-local-map [(shift right)]
10908 (lambda () (interactive)
10909 (org-eval-in-calendar '(calendar-forward-day 1))))
10910 (org-defkey minibuffer-local-map ">"
10911 (lambda () (interactive)
10912 (org-eval-in-calendar '(scroll-calendar-left 1))))
10913 (org-defkey minibuffer-local-map "<"
10914 (lambda () (interactive)
10915 (org-eval-in-calendar '(scroll-calendar-right 1))))
10916 (unwind-protect
10917 (progn
10918 (use-local-map map)
10919 (add-hook 'post-command-hook 'org-read-date-display)
10920 (setq org-ans0 (read-string prompt default-input nil nil))
10921 ;; org-ans0: from prompt
10922 ;; org-ans1: from mouse click
10923 ;; org-ans2: from calendar motion
10924 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10925 (remove-hook 'post-command-hook 'org-read-date-display)
10926 (use-local-map old-map)
10927 (when org-read-date-overlay
10928 (org-delete-overlay org-read-date-overlay)
10929 (setq org-read-date-overlay nil)))))))
10931 (t ; Naked prompt only
10932 (unwind-protect
10933 (setq ans (read-string prompt default-input nil timestr))
10934 (when org-read-date-overlay
10935 (org-delete-overlay org-read-date-overlay)
10936 (setq org-read-date-overlay nil)))))
10938 (setq final (org-read-date-analyze ans def defdecode))
10940 (if to-time
10941 (apply 'encode-time final)
10942 (if (and (boundp 'org-time-was-given) org-time-was-given)
10943 (format "%04d-%02d-%02d %02d:%02d"
10944 (nth 5 final) (nth 4 final) (nth 3 final)
10945 (nth 2 final) (nth 1 final))
10946 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10947 (defvar def)
10948 (defvar defdecode)
10949 (defvar with-time)
10950 (defun org-read-date-display ()
10951 "Display the currrent date prompt interpretation in the minibuffer."
10952 (when org-read-date-display-live
10953 (when org-read-date-overlay
10954 (org-delete-overlay org-read-date-overlay))
10955 (let ((p (point)))
10956 (end-of-line 1)
10957 (while (not (equal (buffer-substring
10958 (max (point-min) (- (point) 4)) (point))
10959 " "))
10960 (insert " "))
10961 (goto-char p))
10962 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10963 " " (or org-ans1 org-ans2)))
10964 (org-end-time-was-given nil)
10965 (f (org-read-date-analyze ans def defdecode))
10966 (fmts (if org-dcst
10967 org-time-stamp-custom-formats
10968 org-time-stamp-formats))
10969 (fmt (if (or with-time
10970 (and (boundp 'org-time-was-given) org-time-was-given))
10971 (cdr fmts)
10972 (car fmts)))
10973 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10974 (when (and org-end-time-was-given
10975 (string-match org-plain-time-of-day-regexp txt))
10976 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10977 org-end-time-was-given
10978 (substring txt (match-end 0)))))
10979 (setq org-read-date-overlay
10980 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10981 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10983 (defun org-read-date-analyze (ans def defdecode)
10984 "Analyze the combined answer of the date prompt."
10985 ;; FIXME: cleanup and comment
10986 (let (delta deltan deltaw deltadef year month day
10987 hour minute second wday pm h2 m2 tl wday1
10988 iso-year iso-weekday iso-week iso-year iso-date)
10990 (when (string-match "\\`[ \t]*\\.[ \t]*\\'" ans)
10991 (setq ans "+0"))
10993 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10994 (setq ans (replace-match "" t t ans)
10995 deltan (car delta)
10996 deltaw (nth 1 delta)
10997 deltadef (nth 2 delta)))
10999 ;; Check if there is an iso week date in there
11000 ;; If yes, sore the info and ostpone interpreting it until the rest
11001 ;; of the parsing is done
11002 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
11003 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
11004 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
11005 iso-week (string-to-number (match-string 2 ans)))
11006 (setq ans (replace-match "" t t ans)))
11008 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
11009 (when (string-match
11010 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
11011 (setq year (if (match-end 2)
11012 (string-to-number (match-string 2 ans))
11013 (string-to-number (format-time-string "%Y")))
11014 month (string-to-number (match-string 3 ans))
11015 day (string-to-number (match-string 4 ans)))
11016 (if (< year 100) (setq year (+ 2000 year)))
11017 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
11018 t nil ans)))
11019 ;; Help matching am/pm times, because `parse-time-string' does not do that.
11020 ;; If there is a time with am/pm, and *no* time without it, we convert
11021 ;; so that matching will be successful.
11022 (loop for i from 1 to 2 do ; twice, for end time as well
11023 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
11024 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
11025 (setq hour (string-to-number (match-string 1 ans))
11026 minute (if (match-end 3)
11027 (string-to-number (match-string 3 ans))
11029 pm (equal ?p
11030 (string-to-char (downcase (match-string 4 ans)))))
11031 (if (and (= hour 12) (not pm))
11032 (setq hour 0)
11033 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
11034 (setq ans (replace-match (format "%02d:%02d" hour minute)
11035 t t ans))))
11037 ;; Check if a time range is given as a duration
11038 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
11039 (setq hour (string-to-number (match-string 1 ans))
11040 h2 (+ hour (string-to-number (match-string 3 ans)))
11041 minute (string-to-number (match-string 2 ans))
11042 m2 (+ minute (if (match-end 5) (string-to-number
11043 (match-string 5 ans))0)))
11044 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
11045 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
11046 t t ans)))
11048 ;; Check if there is a time range
11049 (when (boundp 'org-end-time-was-given)
11050 (setq org-time-was-given nil)
11051 (when (and (string-match org-plain-time-of-day-regexp ans)
11052 (match-end 8))
11053 (setq org-end-time-was-given (match-string 8 ans))
11054 (setq ans (concat (substring ans 0 (match-beginning 7))
11055 (substring ans (match-end 7))))))
11057 (setq tl (parse-time-string ans)
11058 day (or (nth 3 tl) (nth 3 defdecode))
11059 month (or (nth 4 tl)
11060 (if (and org-read-date-prefer-future
11061 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
11062 (1+ (nth 4 defdecode))
11063 (nth 4 defdecode)))
11064 year (or (nth 5 tl)
11065 (if (and org-read-date-prefer-future
11066 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
11067 (1+ (nth 5 defdecode))
11068 (nth 5 defdecode)))
11069 hour (or (nth 2 tl) (nth 2 defdecode))
11070 minute (or (nth 1 tl) (nth 1 defdecode))
11071 second (or (nth 0 tl) 0)
11072 wday (nth 6 tl))
11074 ;; Special date definitions below
11075 (cond
11076 (iso-week
11077 ;; There was an iso week
11078 (setq year (or iso-year year)
11079 day (or iso-weekday wday 1)
11080 wday nil ; to make sure that the trigger below does not match
11081 iso-date (calendar-gregorian-from-absolute
11082 (calendar-absolute-from-iso
11083 (list iso-week day year))))
11084 ; FIXME: Should we also push ISO weeks into the future?
11085 ; (when (and org-read-date-prefer-future
11086 ; (not iso-year)
11087 ; (< (calendar-absolute-from-gregorian iso-date)
11088 ; (time-to-days (current-time))))
11089 ; (setq year (1+ year)
11090 ; iso-date (calendar-gregorian-from-absolute
11091 ; (calendar-absolute-from-iso
11092 ; (list iso-week day year)))))
11093 (setq month (car iso-date)
11094 year (nth 2 iso-date)
11095 day (nth 1 iso-date)))
11096 (deltan
11097 (unless deltadef
11098 (let ((now (decode-time (current-time))))
11099 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
11100 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
11101 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
11102 ((equal deltaw "m") (setq month (+ month deltan)))
11103 ((equal deltaw "y") (setq year (+ year deltan)))))
11104 ((and wday (not (nth 3 tl)))
11105 ;; Weekday was given, but no day, so pick that day in the week
11106 ;; on or after the derived date.
11107 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
11108 (unless (equal wday wday1)
11109 (setq day (+ day (% (- wday wday1 -7) 7))))))
11110 (if (and (boundp 'org-time-was-given)
11111 (nth 2 tl))
11112 (setq org-time-was-given t))
11113 (if (< year 100) (setq year (+ 2000 year)))
11114 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
11115 (list second minute hour day month year)))
11117 (defvar parse-time-weekdays)
11119 (defun org-read-date-get-relative (s today default)
11120 "Check string S for special relative date string.
11121 TODAY and DEFAULT are internal times, for today and for a default.
11122 Return shift list (N what def-flag)
11123 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
11124 N is the number of WHATs to shift.
11125 DEF-FLAG is t when a double ++ or -- indicates shift relative to
11126 the DEFAULT date rather than TODAY."
11127 (when (and
11128 (string-match
11129 (concat
11130 "\\`[ \t]*\\([-+]\\{0,2\\}\\)"
11131 "\\([0-9]+\\)?"
11132 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
11133 "\\([ \t]\\|$\\)") s)
11134 (or (> (match-end 1) (match-beginning 1)) (match-end 4)))
11135 (let* ((dir (if (> (match-end 1) (match-beginning 1))
11136 (string-to-char (substring (match-string 1 s) -1))
11137 ?+))
11138 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
11139 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
11140 (what (if (match-end 3) (match-string 3 s) "d"))
11141 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
11142 (date (if rel default today))
11143 (wday (nth 6 (decode-time date)))
11144 delta)
11145 (if wday1
11146 (progn
11147 (setq delta (mod (+ 7 (- wday1 wday)) 7))
11148 (if (= dir ?-) (setq delta (- delta 7)))
11149 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
11150 (list delta "d" rel))
11151 (list (* n (if (= dir ?-) -1 1)) what rel)))))
11153 (defun org-eval-in-calendar (form &optional keepdate)
11154 "Eval FORM in the calendar window and return to current window.
11155 Also, store the cursor date in variable org-ans2."
11156 (let ((sw (selected-window)))
11157 (select-window (get-buffer-window "*Calendar*"))
11158 (eval form)
11159 (when (and (not keepdate) (calendar-cursor-to-date))
11160 (let* ((date (calendar-cursor-to-date))
11161 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11162 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
11163 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
11164 (select-window sw)))
11166 ; ;; Update the prompt to show new default date
11167 ; (save-excursion
11168 ; (goto-char (point-min))
11169 ; (when (and org-ans2
11170 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
11171 ; (get-text-property (match-end 0) 'field))
11172 ; (let ((inhibit-read-only t))
11173 ; (replace-match (concat "[" org-ans2 "]") t t)
11174 ; (add-text-properties (point-min) (1+ (match-end 0))
11175 ; (text-properties-at (1+ (point-min)))))))))
11177 (defun org-calendar-select ()
11178 "Return to `org-read-date' with the date currently selected.
11179 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11180 (interactive)
11181 (when (calendar-cursor-to-date)
11182 (let* ((date (calendar-cursor-to-date))
11183 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11184 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11185 (if (active-minibuffer-window) (exit-minibuffer))))
11187 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
11188 "Insert a date stamp for the date given by the internal TIME.
11189 WITH-HM means, use the stamp format that includes the time of the day.
11190 INACTIVE means use square brackets instead of angular ones, so that the
11191 stamp will not contribute to the agenda.
11192 PRE and POST are optional strings to be inserted before and after the
11193 stamp.
11194 The command returns the inserted time stamp."
11195 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
11196 stamp)
11197 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
11198 (insert-before-markers (or pre ""))
11199 (insert-before-markers (setq stamp (format-time-string fmt time)))
11200 (when (listp extra)
11201 (setq extra (car extra))
11202 (if (and (stringp extra)
11203 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
11204 (setq extra (format "-%02d:%02d"
11205 (string-to-number (match-string 1 extra))
11206 (string-to-number (match-string 2 extra))))
11207 (setq extra nil)))
11208 (when extra
11209 (backward-char 1)
11210 (insert-before-markers extra)
11211 (forward-char 1))
11212 (insert-before-markers (or post ""))
11213 (setq org-last-inserted-timestamp stamp)))
11215 (defun org-toggle-time-stamp-overlays ()
11216 "Toggle the use of custom time stamp formats."
11217 (interactive)
11218 (setq org-display-custom-times (not org-display-custom-times))
11219 (unless org-display-custom-times
11220 (let ((p (point-min)) (bmp (buffer-modified-p)))
11221 (while (setq p (next-single-property-change p 'display))
11222 (if (and (get-text-property p 'display)
11223 (eq (get-text-property p 'face) 'org-date))
11224 (remove-text-properties
11225 p (setq p (next-single-property-change p 'display))
11226 '(display t))))
11227 (set-buffer-modified-p bmp)))
11228 (if (featurep 'xemacs)
11229 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
11230 (org-restart-font-lock)
11231 (setq org-table-may-need-update t)
11232 (if org-display-custom-times
11233 (message "Time stamps are overlayed with custom format")
11234 (message "Time stamp overlays removed")))
11236 (defun org-display-custom-time (beg end)
11237 "Overlay modified time stamp format over timestamp between BEG and END."
11238 (let* ((ts (buffer-substring beg end))
11239 t1 w1 with-hm tf time str w2 (off 0))
11240 (save-match-data
11241 (setq t1 (org-parse-time-string ts t))
11242 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
11243 (setq off (- (match-end 0) (match-beginning 0)))))
11244 (setq end (- end off))
11245 (setq w1 (- end beg)
11246 with-hm (and (nth 1 t1) (nth 2 t1))
11247 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
11248 time (org-fix-decoded-time t1)
11249 str (org-add-props
11250 (format-time-string
11251 (substring tf 1 -1) (apply 'encode-time time))
11252 nil 'mouse-face 'highlight)
11253 w2 (length str))
11254 (if (not (= w2 w1))
11255 (add-text-properties (1+ beg) (+ 2 beg)
11256 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
11257 (if (featurep 'xemacs)
11258 (progn
11259 (put-text-property beg end 'invisible t)
11260 (put-text-property beg end 'end-glyph (make-glyph str)))
11261 (put-text-property beg end 'display str))))
11263 (defun org-translate-time (string)
11264 "Translate all timestamps in STRING to custom format.
11265 But do this only if the variable `org-display-custom-times' is set."
11266 (when org-display-custom-times
11267 (save-match-data
11268 (let* ((start 0)
11269 (re org-ts-regexp-both)
11270 t1 with-hm inactive tf time str beg end)
11271 (while (setq start (string-match re string start))
11272 (setq beg (match-beginning 0)
11273 end (match-end 0)
11274 t1 (save-match-data
11275 (org-parse-time-string (substring string beg end) t))
11276 with-hm (and (nth 1 t1) (nth 2 t1))
11277 inactive (equal (substring string beg (1+ beg)) "[")
11278 tf (funcall (if with-hm 'cdr 'car)
11279 org-time-stamp-custom-formats)
11280 time (org-fix-decoded-time t1)
11281 str (format-time-string
11282 (concat
11283 (if inactive "[" "<") (substring tf 1 -1)
11284 (if inactive "]" ">"))
11285 (apply 'encode-time time))
11286 string (replace-match str t t string)
11287 start (+ start (length str)))))))
11288 string)
11290 (defun org-fix-decoded-time (time)
11291 "Set 0 instead of nil for the first 6 elements of time.
11292 Don't touch the rest."
11293 (let ((n 0))
11294 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
11296 (defun org-days-to-time (timestamp-string)
11297 "Difference between TIMESTAMP-STRING and now in days."
11298 (- (time-to-days (org-time-string-to-time timestamp-string))
11299 (time-to-days (current-time))))
11301 (defun org-deadline-close (timestamp-string &optional ndays)
11302 "Is the time in TIMESTAMP-STRING close to the current date?"
11303 (setq ndays (or ndays (org-get-wdays timestamp-string)))
11304 (and (< (org-days-to-time timestamp-string) ndays)
11305 (not (org-entry-is-done-p))))
11307 (defun org-get-wdays (ts)
11308 "Get the deadline lead time appropriate for timestring TS."
11309 (cond
11310 ((<= org-deadline-warning-days 0)
11311 ;; 0 or negative, enforce this value no matter what
11312 (- org-deadline-warning-days))
11313 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
11314 ;; lead time is specified.
11315 (floor (* (string-to-number (match-string 1 ts))
11316 (cdr (assoc (match-string 2 ts)
11317 '(("d" . 1) ("w" . 7)
11318 ("m" . 30.4) ("y" . 365.25)))))))
11319 ;; go for the default.
11320 (t org-deadline-warning-days)))
11322 (defun org-calendar-select-mouse (ev)
11323 "Return to `org-read-date' with the date currently selected.
11324 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
11325 (interactive "e")
11326 (mouse-set-point ev)
11327 (when (calendar-cursor-to-date)
11328 (let* ((date (calendar-cursor-to-date))
11329 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
11330 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
11331 (if (active-minibuffer-window) (exit-minibuffer))))
11333 (defun org-check-deadlines (ndays)
11334 "Check if there are any deadlines due or past due.
11335 A deadline is considered due if it happens within `org-deadline-warning-days'
11336 days from today's date. If the deadline appears in an entry marked DONE,
11337 it is not shown. The prefix arg NDAYS can be used to test that many
11338 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
11339 (interactive "P")
11340 (let* ((org-warn-days
11341 (cond
11342 ((equal ndays '(4)) 100000)
11343 (ndays (prefix-numeric-value ndays))
11344 (t (abs org-deadline-warning-days))))
11345 (case-fold-search nil)
11346 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
11347 (callback
11348 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
11350 (message "%d deadlines past-due or due within %d days"
11351 (org-occur regexp nil callback)
11352 org-warn-days)))
11354 (defun org-check-before-date (date)
11355 "Check if there are deadlines or scheduled entries before DATE."
11356 (interactive (list (org-read-date)))
11357 (let ((case-fold-search nil)
11358 (regexp (concat "\\<\\(" org-deadline-string
11359 "\\|" org-scheduled-string
11360 "\\) *<\\([^>]+\\)>"))
11361 (callback
11362 (lambda () (time-less-p
11363 (org-time-string-to-time (match-string 2))
11364 (org-time-string-to-time date)))))
11365 (message "%d entries before %s"
11366 (org-occur regexp nil callback) date)))
11368 (defun org-evaluate-time-range (&optional to-buffer)
11369 "Evaluate a time range by computing the difference between start and end.
11370 Normally the result is just printed in the echo area, but with prefix arg
11371 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
11372 If the time range is actually in a table, the result is inserted into the
11373 next column.
11374 For time difference computation, a year is assumed to be exactly 365
11375 days in order to avoid rounding problems."
11376 (interactive "P")
11378 (org-clock-update-time-maybe)
11379 (save-excursion
11380 (unless (org-at-date-range-p t)
11381 (goto-char (point-at-bol))
11382 (re-search-forward org-tr-regexp-both (point-at-eol) t))
11383 (if (not (org-at-date-range-p t))
11384 (error "Not at a time-stamp range, and none found in current line")))
11385 (let* ((ts1 (match-string 1))
11386 (ts2 (match-string 2))
11387 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
11388 (match-end (match-end 0))
11389 (time1 (org-time-string-to-time ts1))
11390 (time2 (org-time-string-to-time ts2))
11391 (t1 (time-to-seconds time1))
11392 (t2 (time-to-seconds time2))
11393 (diff (abs (- t2 t1)))
11394 (negative (< (- t2 t1) 0))
11395 ;; (ys (floor (* 365 24 60 60)))
11396 (ds (* 24 60 60))
11397 (hs (* 60 60))
11398 (fy "%dy %dd %02d:%02d")
11399 (fy1 "%dy %dd")
11400 (fd "%dd %02d:%02d")
11401 (fd1 "%dd")
11402 (fh "%02d:%02d")
11403 y d h m align)
11404 (if havetime
11405 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11407 d (floor (/ diff ds)) diff (mod diff ds)
11408 h (floor (/ diff hs)) diff (mod diff hs)
11409 m (floor (/ diff 60)))
11410 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
11412 d (floor (+ (/ diff ds) 0.5))
11413 h 0 m 0))
11414 (if (not to-buffer)
11415 (message "%s" (org-make-tdiff-string y d h m))
11416 (if (org-at-table-p)
11417 (progn
11418 (goto-char match-end)
11419 (setq align t)
11420 (and (looking-at " *|") (goto-char (match-end 0))))
11421 (goto-char match-end))
11422 (if (looking-at
11423 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
11424 (replace-match ""))
11425 (if negative (insert " -"))
11426 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
11427 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
11428 (insert " " (format fh h m))))
11429 (if align (org-table-align))
11430 (message "Time difference inserted")))))
11432 (defun org-make-tdiff-string (y d h m)
11433 (let ((fmt "")
11434 (l nil))
11435 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
11436 l (push y l)))
11437 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
11438 l (push d l)))
11439 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
11440 l (push h l)))
11441 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
11442 l (push m l)))
11443 (apply 'format fmt (nreverse l))))
11445 (defun org-time-string-to-time (s)
11446 (apply 'encode-time (org-parse-time-string s)))
11448 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
11449 "Convert a time stamp to an absolute day number.
11450 If there is a specifyer for a cyclic time stamp, get the closest date to
11451 DAYNR.
11452 PREFER and SHOW_ALL are passed through to `org-closest-date'."
11453 (cond
11454 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
11455 (if (org-diary-sexp-entry (match-string 1 s) "" date)
11456 daynr
11457 (+ daynr 1000)))
11458 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
11459 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
11460 (time-to-days (current-time))) (match-string 0 s)
11461 prefer show-all))
11462 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
11464 (defun org-days-to-iso-week (days)
11465 "Return the iso week number."
11466 (require 'cal-iso)
11467 (car (calendar-iso-from-absolute days)))
11469 (defun org-small-year-to-year (year)
11470 "Convert 2-digit years into 4-digit years.
11471 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
11472 The year 2000 cannot be abbreviated. Any year lager than 99
11473 is retrned unchanged."
11474 (if (< year 38)
11475 (setq year (+ 2000 year))
11476 (if (< year 100)
11477 (setq year (+ 1900 year))))
11478 year)
11480 (defun org-time-from-absolute (d)
11481 "Return the time corresponding to date D.
11482 D may be an absolute day number, or a calendar-type list (month day year)."
11483 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
11484 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
11486 (defun org-calendar-holiday ()
11487 "List of holidays, for Diary display in Org-mode."
11488 (require 'holidays)
11489 (let ((hl (funcall
11490 (if (fboundp 'calendar-check-holidays)
11491 'calendar-check-holidays 'check-calendar-holidays) date)))
11492 (if hl (mapconcat 'identity hl "; "))))
11494 (defun org-diary-sexp-entry (sexp entry date)
11495 "Process a SEXP diary ENTRY for DATE."
11496 (require 'diary-lib)
11497 (let ((result (if calendar-debug-sexp
11498 (let ((stack-trace-on-error t))
11499 (eval (car (read-from-string sexp))))
11500 (condition-case nil
11501 (eval (car (read-from-string sexp)))
11502 (error
11503 (beep)
11504 (message "Bad sexp at line %d in %s: %s"
11505 (org-current-line)
11506 (buffer-file-name) sexp)
11507 (sleep-for 2))))))
11508 (cond ((stringp result) result)
11509 ((and (consp result)
11510 (stringp (cdr result))) (cdr result))
11511 (result entry)
11512 (t nil))))
11514 (defun org-diary-to-ical-string (frombuf)
11515 "Get iCalendar entries from diary entries in buffer FROMBUF.
11516 This uses the icalendar.el library."
11517 (let* ((tmpdir (if (featurep 'xemacs)
11518 (temp-directory)
11519 temporary-file-directory))
11520 (tmpfile (make-temp-name
11521 (expand-file-name "orgics" tmpdir)))
11522 buf rtn b e)
11523 (save-excursion
11524 (set-buffer frombuf)
11525 (icalendar-export-region (point-min) (point-max) tmpfile)
11526 (setq buf (find-buffer-visiting tmpfile))
11527 (set-buffer buf)
11528 (goto-char (point-min))
11529 (if (re-search-forward "^BEGIN:VEVENT" nil t)
11530 (setq b (match-beginning 0)))
11531 (goto-char (point-max))
11532 (if (re-search-backward "^END:VEVENT" nil t)
11533 (setq e (match-end 0)))
11534 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
11535 (kill-buffer buf)
11536 (delete-file tmpfile)
11537 rtn))
11539 (defun org-closest-date (start current change prefer show-all)
11540 "Find the date closest to CURRENT that is consistent with START and CHANGE.
11541 When PREFER is `past' return a date that is either CURRENT or past.
11542 When PREFER is `future', return a date that is either CURRENT or future.
11543 When SHOW-ALL is nil, only return the current occurence of a time stamp."
11544 ;; Make the proper lists from the dates
11545 (catch 'exit
11546 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
11547 dn dw sday cday n1 n2
11548 d m y y1 y2 date1 date2 nmonths nm ny m2)
11550 (setq start (org-date-to-gregorian start)
11551 current (org-date-to-gregorian
11552 (if show-all
11553 current
11554 (time-to-days (current-time))))
11555 sday (calendar-absolute-from-gregorian start)
11556 cday (calendar-absolute-from-gregorian current))
11558 (if (<= cday sday) (throw 'exit sday))
11560 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
11561 (setq dn (string-to-number (match-string 1 change))
11562 dw (cdr (assoc (match-string 2 change) a1)))
11563 (error "Invalid change specifyer: %s" change))
11564 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
11565 (cond
11566 ((eq dw 'day)
11567 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
11568 n2 (+ n1 dn)))
11569 ((eq dw 'year)
11570 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
11571 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
11572 (setq date1 (list m d y1)
11573 n1 (calendar-absolute-from-gregorian date1)
11574 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
11575 n2 (calendar-absolute-from-gregorian date2)))
11576 ((eq dw 'month)
11577 ;; approx number of month between the two dates
11578 (setq nmonths (floor (/ (- cday sday) 30.436875)))
11579 ;; How often does dn fit in there?
11580 (setq d (nth 1 start) m (car start) y (nth 2 start)
11581 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
11582 m (+ m nm)
11583 ny (floor (/ m 12))
11584 y (+ y ny)
11585 m (- m (* ny 12)))
11586 (while (> m 12) (setq m (- m 12) y (1+ y)))
11587 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
11588 (setq m2 (+ m dn) y2 y)
11589 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11590 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
11591 (while (<= n2 cday)
11592 (setq n1 n2 m m2 y y2)
11593 (setq m2 (+ m dn) y2 y)
11594 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
11595 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
11596 (if show-all
11597 (cond
11598 ((eq prefer 'past) n1)
11599 ((eq prefer 'future) (if (= cday n1) n1 n2))
11600 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
11601 (cond
11602 ((eq prefer 'past) n1)
11603 ((eq prefer 'future) (if (= cday n1) n1 n2))
11604 (t (if (= cday n1) n1 n2)))))))
11606 (defun org-date-to-gregorian (date)
11607 "Turn any specification of DATE into a gregorian date for the calendar."
11608 (cond ((integerp date) (calendar-gregorian-from-absolute date))
11609 ((and (listp date) (= (length date) 3)) date)
11610 ((stringp date)
11611 (setq date (org-parse-time-string date))
11612 (list (nth 4 date) (nth 3 date) (nth 5 date)))
11613 ((listp date)
11614 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
11616 (defun org-parse-time-string (s &optional nodefault)
11617 "Parse the standard Org-mode time string.
11618 This should be a lot faster than the normal `parse-time-string'.
11619 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
11620 hour and minute fields will be nil if not given."
11621 (if (string-match org-ts-regexp0 s)
11622 (list 0
11623 (if (or (match-beginning 8) (not nodefault))
11624 (string-to-number (or (match-string 8 s) "0")))
11625 (if (or (match-beginning 7) (not nodefault))
11626 (string-to-number (or (match-string 7 s) "0")))
11627 (string-to-number (match-string 4 s))
11628 (string-to-number (match-string 3 s))
11629 (string-to-number (match-string 2 s))
11630 nil nil nil)
11631 (make-list 9 0)))
11633 (defun org-timestamp-up (&optional arg)
11634 "Increase the date item at the cursor by one.
11635 If the cursor is on the year, change the year. If it is on the month or
11636 the day, change that.
11637 With prefix ARG, change by that many units."
11638 (interactive "p")
11639 (org-timestamp-change (prefix-numeric-value arg)))
11641 (defun org-timestamp-down (&optional arg)
11642 "Decrease the date item at the cursor by one.
11643 If the cursor is on the year, change the year. If it is on the month or
11644 the day, change that.
11645 With prefix ARG, change by that many units."
11646 (interactive "p")
11647 (org-timestamp-change (- (prefix-numeric-value arg))))
11649 (defun org-timestamp-up-day (&optional arg)
11650 "Increase the date in the time stamp by one day.
11651 With prefix ARG, change that many days."
11652 (interactive "p")
11653 (if (and (not (org-at-timestamp-p t))
11654 (org-on-heading-p))
11655 (org-todo 'up)
11656 (org-timestamp-change (prefix-numeric-value arg) 'day)))
11658 (defun org-timestamp-down-day (&optional arg)
11659 "Decrease the date in the time stamp by one day.
11660 With prefix ARG, change that many days."
11661 (interactive "p")
11662 (if (and (not (org-at-timestamp-p t))
11663 (org-on-heading-p))
11664 (org-todo 'down)
11665 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
11667 (defun org-at-timestamp-p (&optional inactive-ok)
11668 "Determine if the cursor is in or at a timestamp."
11669 (interactive)
11670 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
11671 (pos (point))
11672 (ans (or (looking-at tsr)
11673 (save-excursion
11674 (skip-chars-backward "^[<\n\r\t")
11675 (if (> (point) (point-min)) (backward-char 1))
11676 (and (looking-at tsr)
11677 (> (- (match-end 0) pos) -1))))))
11678 (and ans
11679 (boundp 'org-ts-what)
11680 (setq org-ts-what
11681 (cond
11682 ((= pos (match-beginning 0)) 'bracket)
11683 ((= pos (1- (match-end 0))) 'bracket)
11684 ((org-pos-in-match-range pos 2) 'year)
11685 ((org-pos-in-match-range pos 3) 'month)
11686 ((org-pos-in-match-range pos 7) 'hour)
11687 ((org-pos-in-match-range pos 8) 'minute)
11688 ((or (org-pos-in-match-range pos 4)
11689 (org-pos-in-match-range pos 5)) 'day)
11690 ((and (> pos (or (match-end 8) (match-end 5)))
11691 (< pos (match-end 0)))
11692 (- pos (or (match-end 8) (match-end 5))))
11693 (t 'day))))
11694 ans))
11696 (defun org-toggle-timestamp-type ()
11697 "Toggle the type (<active> or [inactive]) of a time stamp."
11698 (interactive)
11699 (when (org-at-timestamp-p t)
11700 (save-excursion
11701 (goto-char (match-beginning 0))
11702 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
11703 (goto-char (1- (match-end 0)))
11704 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
11705 (message "Timestamp is now %sactive"
11706 (if (equal (char-before) ?>) "in" ""))))
11708 (defun org-timestamp-change (n &optional what)
11709 "Change the date in the time stamp at point.
11710 The date will be changed by N times WHAT. WHAT can be `day', `month',
11711 `year', `minute', `second'. If WHAT is not given, the cursor position
11712 in the timestamp determines what will be changed."
11713 (let ((pos (point))
11714 with-hm inactive
11715 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
11716 org-ts-what
11717 extra rem
11718 ts time time0)
11719 (if (not (org-at-timestamp-p t))
11720 (error "Not at a timestamp"))
11721 (if (and (not what) (eq org-ts-what 'bracket))
11722 (org-toggle-timestamp-type)
11723 (if (and (not what) (not (eq org-ts-what 'day))
11724 org-display-custom-times
11725 (get-text-property (point) 'display)
11726 (not (get-text-property (1- (point)) 'display)))
11727 (setq org-ts-what 'day))
11728 (setq org-ts-what (or what org-ts-what)
11729 inactive (= (char-after (match-beginning 0)) ?\[)
11730 ts (match-string 0))
11731 (replace-match "")
11732 (if (string-match
11733 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
11735 (setq extra (match-string 1 ts)))
11736 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
11737 (setq with-hm t))
11738 (setq time0 (org-parse-time-string ts))
11739 (when (and (eq org-ts-what 'minute)
11740 (eq current-prefix-arg nil))
11741 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
11742 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
11743 (setcar (cdr time0) (+ (nth 1 time0)
11744 (if (> n 0) (- rem) (- dm rem))))))
11745 (setq time
11746 (encode-time (or (car time0) 0)
11747 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
11748 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
11749 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
11750 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
11751 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
11752 (nthcdr 6 time0)))
11753 (when (integerp org-ts-what)
11754 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
11755 (if (eq what 'calendar)
11756 (let ((cal-date (org-get-date-from-calendar)))
11757 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
11758 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
11759 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
11760 (setcar time0 (or (car time0) 0))
11761 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
11762 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
11763 (setq time (apply 'encode-time time0))))
11764 (setq org-last-changed-timestamp
11765 (org-insert-time-stamp time with-hm inactive nil nil extra))
11766 (org-clock-update-time-maybe)
11767 (goto-char pos)
11768 ;; Try to recenter the calendar window, if any
11769 (if (and org-calendar-follow-timestamp-change
11770 (get-buffer-window "*Calendar*" t)
11771 (memq org-ts-what '(day month year)))
11772 (org-recenter-calendar (time-to-days time))))))
11774 (defun org-modify-ts-extra (s pos n dm)
11775 "Change the different parts of the lead-time and repeat fields in timestamp."
11776 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
11777 ng h m new rem)
11778 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
11779 (cond
11780 ((or (org-pos-in-match-range pos 2)
11781 (org-pos-in-match-range pos 3))
11782 (setq m (string-to-number (match-string 3 s))
11783 h (string-to-number (match-string 2 s)))
11784 (if (org-pos-in-match-range pos 2)
11785 (setq h (+ h n))
11786 (setq n (* dm (org-no-warnings (signum n))))
11787 (when (not (= 0 (setq rem (% m dm))))
11788 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
11789 (setq m (+ m n)))
11790 (if (< m 0) (setq m (+ m 60) h (1- h)))
11791 (if (> m 59) (setq m (- m 60) h (1+ h)))
11792 (setq h (min 24 (max 0 h)))
11793 (setq ng 1 new (format "-%02d:%02d" h m)))
11794 ((org-pos-in-match-range pos 6)
11795 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
11796 ((org-pos-in-match-range pos 5)
11797 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
11799 ((org-pos-in-match-range pos 9)
11800 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
11801 ((org-pos-in-match-range pos 8)
11802 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11804 (when ng
11805 (setq s (concat
11806 (substring s 0 (match-beginning ng))
11808 (substring s (match-end ng))))))
11811 (defun org-recenter-calendar (date)
11812 "If the calendar is visible, recenter it to DATE."
11813 (let* ((win (selected-window))
11814 (cwin (get-buffer-window "*Calendar*" t))
11815 (calendar-move-hook nil))
11816 (when cwin
11817 (select-window cwin)
11818 (calendar-goto-date (if (listp date) date
11819 (calendar-gregorian-from-absolute date)))
11820 (select-window win))))
11822 (defun org-goto-calendar (&optional arg)
11823 "Go to the Emacs calendar at the current date.
11824 If there is a time stamp in the current line, go to that date.
11825 A prefix ARG can be used to force the current date."
11826 (interactive "P")
11827 (let ((tsr org-ts-regexp) diff
11828 (calendar-move-hook nil)
11829 (calendar-view-holidays-initially-flag nil)
11830 (view-calendar-holidays-initially nil)
11831 (calendar-view-diary-initially-flag nil)
11832 (view-diary-entries-initially nil))
11833 (if (or (org-at-timestamp-p)
11834 (save-excursion
11835 (beginning-of-line 1)
11836 (looking-at (concat ".*" tsr))))
11837 (let ((d1 (time-to-days (current-time)))
11838 (d2 (time-to-days
11839 (org-time-string-to-time (match-string 1)))))
11840 (setq diff (- d2 d1))))
11841 (calendar)
11842 (calendar-goto-today)
11843 (if (and diff (not arg)) (calendar-forward-day diff))))
11845 (defun org-get-date-from-calendar ()
11846 "Return a list (month day year) of date at point in calendar."
11847 (with-current-buffer "*Calendar*"
11848 (save-match-data
11849 (calendar-cursor-to-date))))
11851 (defun org-date-from-calendar ()
11852 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11853 If there is already a time stamp at the cursor position, update it."
11854 (interactive)
11855 (if (org-at-timestamp-p t)
11856 (org-timestamp-change 0 'calendar)
11857 (let ((cal-date (org-get-date-from-calendar)))
11858 (org-insert-time-stamp
11859 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11861 (defun org-minutes-to-hh:mm-string (m)
11862 "Compute H:MM from a number of minutes."
11863 (let ((h (/ m 60)))
11864 (setq m (- m (* 60 h)))
11865 (format org-time-clocksum-format h m)))
11867 (defun org-hh:mm-string-to-minutes (s)
11868 "Convert a string H:MM to a number of minutes."
11869 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11870 (+ (* (string-to-number (match-string 1 s)) 60)
11871 (string-to-number (match-string 2 s)))
11874 ;;;; Agenda files
11876 ;;;###autoload
11877 (defun org-iswitchb (&optional arg)
11878 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11879 With a prefix argument, restrict available to files.
11880 With two prefix arguments, restrict available buffers to agenda files.
11882 Due to some yet unresolved reason, global function
11883 `iswitchb-mode' needs to be active for this function to work."
11884 (interactive "P")
11885 (require 'iswitchb)
11886 (let ((enabled iswitchb-mode) blist)
11887 (or enabled (iswitchb-mode 1))
11888 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11889 ((equal arg '(16)) (org-buffer-list 'agenda))
11890 (t (org-buffer-list))))
11891 (unwind-protect
11892 (let ((iswitchb-make-buflist-hook
11893 (lambda ()
11894 (setq iswitchb-temp-buflist
11895 (mapcar 'buffer-name blist)))))
11896 (switch-to-buffer
11897 (iswitchb-read-buffer
11898 "Switch-to: " nil t))
11899 (or enabled (iswitchb-mode -1))))))
11901 (defun org-buffer-list (&optional predicate tmp)
11902 "Return a list of Org buffers.
11903 PREDICATE can be either 'export, 'files or 'agenda.
11905 'export restrict the list to Export buffers.
11906 'files restrict the list to buffers visiting Org files.
11907 'agenda restrict the list to buffers visiting agenda files.
11909 If TMP is non-nil, don't include temporary buffers."
11910 (let (filter blist)
11911 (setq filter
11912 (cond ((eq predicate 'files) "\.org$")
11913 ((eq predicate 'export) "\*Org .*Export")
11914 (t "\*Org \\|\.org$")))
11915 (setq blist
11916 (mapcar
11917 (lambda(b)
11918 (let ((bname (buffer-name b))
11919 (bfile (buffer-file-name b)))
11920 (if (and (string-match filter bname)
11921 (if (eq predicate 'agenda)
11922 (member bfile
11923 (mapcar (lambda(f) (file-truename f))
11924 org-agenda-files)) t)
11925 (if tmp (not (string-match "tmp" bname)) t)) b)))
11926 (buffer-list)))
11927 (delete nil blist)))
11929 (defun org-agenda-files (&optional unrestricted archives)
11930 "Get the list of agenda files.
11931 Optional UNRESTRICTED means return the full list even if a restriction
11932 is currently in place.
11933 When ARCHIVES is t, include all archive files hat are really being
11934 used by the agenda files. If ARCHIVE is `ifmode', do this only if
11935 `org-agenda-archives-mode' is t."
11936 (let ((files
11937 (cond
11938 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11939 ((stringp org-agenda-files) (org-read-agenda-file-list))
11940 ((listp org-agenda-files) org-agenda-files)
11941 (t (error "Invalid value of `org-agenda-files'")))))
11942 (setq files (apply 'append
11943 (mapcar (lambda (f)
11944 (if (file-directory-p f)
11945 (directory-files
11946 f t org-agenda-file-regexp)
11947 (list f)))
11948 files)))
11949 (when org-agenda-skip-unavailable-files
11950 (setq files (delq nil
11951 (mapcar (function
11952 (lambda (file)
11953 (and (file-readable-p file) file)))
11954 files))))
11955 (when (or (eq archives t)
11956 (and (eq archives 'ifmode) (eq org-agenda-archives-mode t)))
11957 (setq files (org-add-archive-files files)))
11958 files))
11960 (defun org-edit-agenda-file-list ()
11961 "Edit the list of agenda files.
11962 Depending on setup, this either uses customize to edit the variable
11963 `org-agenda-files', or it visits the file that is holding the list. In the
11964 latter case, the buffer is set up in a way that saving it automatically kills
11965 the buffer and restores the previous window configuration."
11966 (interactive)
11967 (if (stringp org-agenda-files)
11968 (let ((cw (current-window-configuration)))
11969 (find-file org-agenda-files)
11970 (org-set-local 'org-window-configuration cw)
11971 (org-add-hook 'after-save-hook
11972 (lambda ()
11973 (set-window-configuration
11974 (prog1 org-window-configuration
11975 (kill-buffer (current-buffer))))
11976 (org-install-agenda-files-menu)
11977 (message "New agenda file list installed"))
11978 nil 'local)
11979 (message "%s" (substitute-command-keys
11980 "Edit list and finish with \\[save-buffer]")))
11981 (customize-variable 'org-agenda-files)))
11983 (defun org-store-new-agenda-file-list (list)
11984 "Set new value for the agenda file list and save it correcly."
11985 (if (stringp org-agenda-files)
11986 (let ((f org-agenda-files) b)
11987 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11988 (with-temp-file f
11989 (insert (mapconcat 'identity list "\n") "\n")))
11990 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11991 (setq org-agenda-files list)
11992 (customize-save-variable 'org-agenda-files org-agenda-files))))
11994 (defun org-read-agenda-file-list ()
11995 "Read the list of agenda files from a file."
11996 (when (file-directory-p org-agenda-files)
11997 (error "`org-agenda-files' cannot be a single directory"))
11998 (when (stringp org-agenda-files)
11999 (with-temp-buffer
12000 (insert-file-contents org-agenda-files)
12001 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
12004 ;;;###autoload
12005 (defun org-cycle-agenda-files ()
12006 "Cycle through the files in `org-agenda-files'.
12007 If the current buffer visits an agenda file, find the next one in the list.
12008 If the current buffer does not, find the first agenda file."
12009 (interactive)
12010 (let* ((fs (org-agenda-files t))
12011 (files (append fs (list (car fs))))
12012 (tcf (if buffer-file-name (file-truename buffer-file-name)))
12013 file)
12014 (unless files (error "No agenda files"))
12015 (catch 'exit
12016 (while (setq file (pop files))
12017 (if (equal (file-truename file) tcf)
12018 (when (car files)
12019 (find-file (car files))
12020 (throw 'exit t))))
12021 (find-file (car fs)))
12022 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
12024 (defun org-agenda-file-to-front (&optional to-end)
12025 "Move/add the current file to the top of the agenda file list.
12026 If the file is not present in the list, it is added to the front. If it is
12027 present, it is moved there. With optional argument TO-END, add/move to the
12028 end of the list."
12029 (interactive "P")
12030 (let ((org-agenda-skip-unavailable-files nil)
12031 (file-alist (mapcar (lambda (x)
12032 (cons (file-truename x) x))
12033 (org-agenda-files t)))
12034 (ctf (file-truename buffer-file-name))
12035 x had)
12036 (setq x (assoc ctf file-alist) had x)
12038 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
12039 (if to-end
12040 (setq file-alist (append (delq x file-alist) (list x)))
12041 (setq file-alist (cons x (delq x file-alist))))
12042 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
12043 (org-install-agenda-files-menu)
12044 (message "File %s to %s of agenda file list"
12045 (if had "moved" "added") (if to-end "end" "front"))))
12047 (defun org-remove-file (&optional file)
12048 "Remove current file from the list of files in variable `org-agenda-files'.
12049 These are the files which are being checked for agenda entries.
12050 Optional argument FILE means, use this file instead of the current."
12051 (interactive)
12052 (let* ((org-agenda-skip-unavailable-files nil)
12053 (file (or file buffer-file-name))
12054 (true-file (file-truename file))
12055 (afile (abbreviate-file-name file))
12056 (files (delq nil (mapcar
12057 (lambda (x)
12058 (if (equal true-file
12059 (file-truename x))
12060 nil x))
12061 (org-agenda-files t)))))
12062 (if (not (= (length files) (length (org-agenda-files t))))
12063 (progn
12064 (org-store-new-agenda-file-list files)
12065 (org-install-agenda-files-menu)
12066 (message "Removed file: %s" afile))
12067 (message "File was not in list: %s (not removed)" afile))))
12069 (defun org-file-menu-entry (file)
12070 (vector file (list 'find-file file) t))
12072 (defun org-check-agenda-file (file)
12073 "Make sure FILE exists. If not, ask user what to do."
12074 (when (not (file-exists-p file))
12075 (message "non-existent file %s. [R]emove from list or [A]bort?"
12076 (abbreviate-file-name file))
12077 (let ((r (downcase (read-char-exclusive))))
12078 (cond
12079 ((equal r ?r)
12080 (org-remove-file file)
12081 (throw 'nextfile t))
12082 (t (error "Abort"))))))
12084 (defun org-get-agenda-file-buffer (file)
12085 "Get a buffer visiting FILE. If the buffer needs to be created, add
12086 it to the list of buffers which might be released later."
12087 (let ((buf (org-find-base-buffer-visiting file)))
12088 (if buf
12089 buf ; just return it
12090 ;; Make a new buffer and remember it
12091 (setq buf (find-file-noselect file))
12092 (if buf (push buf org-agenda-new-buffers))
12093 buf)))
12095 (defun org-release-buffers (blist)
12096 "Release all buffers in list, asking the user for confirmation when needed.
12097 When a buffer is unmodified, it is just killed. When modified, it is saved
12098 \(if the user agrees) and then killed."
12099 (let (buf file)
12100 (while (setq buf (pop blist))
12101 (setq file (buffer-file-name buf))
12102 (when (and (buffer-modified-p buf)
12103 file
12104 (y-or-n-p (format "Save file %s? " file)))
12105 (with-current-buffer buf (save-buffer)))
12106 (kill-buffer buf))))
12108 (defun org-prepare-agenda-buffers (files)
12109 "Create buffers for all agenda files, protect archived trees and comments."
12110 (interactive)
12111 (let ((pa '(:org-archived t))
12112 (pc '(:org-comment t))
12113 (pall '(:org-archived t :org-comment t))
12114 (inhibit-read-only t)
12115 (rea (concat ":" org-archive-tag ":"))
12116 bmp file re)
12117 (save-excursion
12118 (save-restriction
12119 (while (setq file (pop files))
12120 (if (bufferp file)
12121 (set-buffer file)
12122 (org-check-agenda-file file)
12123 (set-buffer (org-get-agenda-file-buffer file)))
12124 (widen)
12125 (setq bmp (buffer-modified-p))
12126 (org-refresh-category-properties)
12127 (setq org-todo-keywords-for-agenda
12128 (append org-todo-keywords-for-agenda org-todo-keywords-1))
12129 (setq org-done-keywords-for-agenda
12130 (append org-done-keywords-for-agenda org-done-keywords))
12131 (save-excursion
12132 (remove-text-properties (point-min) (point-max) pall)
12133 (when org-agenda-skip-archived-trees
12134 (goto-char (point-min))
12135 (while (re-search-forward rea nil t)
12136 (if (org-on-heading-p t)
12137 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
12138 (goto-char (point-min))
12139 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
12140 (while (re-search-forward re nil t)
12141 (add-text-properties
12142 (match-beginning 0) (org-end-of-subtree t) pc)))
12143 (set-buffer-modified-p bmp))))))
12145 ;;;; Embedded LaTeX
12147 (defvar org-cdlatex-mode-map (make-sparse-keymap)
12148 "Keymap for the minor `org-cdlatex-mode'.")
12150 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
12151 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
12152 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
12153 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
12154 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
12156 (defvar org-cdlatex-texmathp-advice-is-done nil
12157 "Flag remembering if we have applied the advice to texmathp already.")
12159 (define-minor-mode org-cdlatex-mode
12160 "Toggle the minor `org-cdlatex-mode'.
12161 This mode supports entering LaTeX environment and math in LaTeX fragments
12162 in Org-mode.
12163 \\{org-cdlatex-mode-map}"
12164 nil " OCDL" nil
12165 (when org-cdlatex-mode (require 'cdlatex))
12166 (unless org-cdlatex-texmathp-advice-is-done
12167 (setq org-cdlatex-texmathp-advice-is-done t)
12168 (defadvice texmathp (around org-math-always-on activate)
12169 "Always return t in org-mode buffers.
12170 This is because we want to insert math symbols without dollars even outside
12171 the LaTeX math segments. If Orgmode thinks that point is actually inside
12172 en embedded LaTeX fragement, let texmathp do its job.
12173 \\[org-cdlatex-mode-map]"
12174 (interactive)
12175 (let (p)
12176 (cond
12177 ((not (org-mode-p)) ad-do-it)
12178 ((eq this-command 'cdlatex-math-symbol)
12179 (setq ad-return-value t
12180 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
12182 (let ((p (org-inside-LaTeX-fragment-p)))
12183 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
12184 (setq ad-return-value t
12185 texmathp-why '("Org-mode embedded math" . 0))
12186 (if p ad-do-it)))))))))
12188 (defun turn-on-org-cdlatex ()
12189 "Unconditionally turn on `org-cdlatex-mode'."
12190 (org-cdlatex-mode 1))
12192 (defun org-inside-LaTeX-fragment-p ()
12193 "Test if point is inside a LaTeX fragment.
12194 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
12195 sequence appearing also before point.
12196 Even though the matchers for math are configurable, this function assumes
12197 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
12198 delimiters are skipped when they have been removed by customization.
12199 The return value is nil, or a cons cell with the delimiter and
12200 and the position of this delimiter.
12202 This function does a reasonably good job, but can locally be fooled by
12203 for example currency specifications. For example it will assume being in
12204 inline math after \"$22.34\". The LaTeX fragment formatter will only format
12205 fragments that are properly closed, but during editing, we have to live
12206 with the uncertainty caused by missing closing delimiters. This function
12207 looks only before point, not after."
12208 (catch 'exit
12209 (let ((pos (point))
12210 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
12211 (lim (progn
12212 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
12213 (point)))
12214 dd-on str (start 0) m re)
12215 (goto-char pos)
12216 (when dodollar
12217 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
12218 re (nth 1 (assoc "$" org-latex-regexps)))
12219 (while (string-match re str start)
12220 (cond
12221 ((= (match-end 0) (length str))
12222 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
12223 ((= (match-end 0) (- (length str) 5))
12224 (throw 'exit nil))
12225 (t (setq start (match-end 0))))))
12226 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
12227 (goto-char pos)
12228 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
12229 (and (match-beginning 2) (throw 'exit nil))
12230 ;; count $$
12231 (while (re-search-backward "\\$\\$" lim t)
12232 (setq dd-on (not dd-on)))
12233 (goto-char pos)
12234 (if dd-on (cons "$$" m))))))
12237 (defun org-try-cdlatex-tab ()
12238 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
12239 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
12240 - inside a LaTeX fragment, or
12241 - after the first word in a line, where an abbreviation expansion could
12242 insert a LaTeX environment."
12243 (when org-cdlatex-mode
12244 (cond
12245 ((save-excursion
12246 (skip-chars-backward "a-zA-Z0-9*")
12247 (skip-chars-backward " \t")
12248 (bolp))
12249 (cdlatex-tab) t)
12250 ((org-inside-LaTeX-fragment-p)
12251 (cdlatex-tab) t)
12252 (t nil))))
12254 (defun org-cdlatex-underscore-caret (&optional arg)
12255 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
12256 Revert to the normal definition outside of these fragments."
12257 (interactive "P")
12258 (if (org-inside-LaTeX-fragment-p)
12259 (call-interactively 'cdlatex-sub-superscript)
12260 (let (org-cdlatex-mode)
12261 (call-interactively (key-binding (vector last-input-event))))))
12263 (defun org-cdlatex-math-modify (&optional arg)
12264 "Execute `cdlatex-math-modify' in LaTeX fragments.
12265 Revert to the normal definition outside of these fragments."
12266 (interactive "P")
12267 (if (org-inside-LaTeX-fragment-p)
12268 (call-interactively 'cdlatex-math-modify)
12269 (let (org-cdlatex-mode)
12270 (call-interactively (key-binding (vector last-input-event))))))
12272 (defvar org-latex-fragment-image-overlays nil
12273 "List of overlays carrying the images of latex fragments.")
12274 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
12276 (defun org-remove-latex-fragment-image-overlays ()
12277 "Remove all overlays with LaTeX fragment images in current buffer."
12278 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
12279 (setq org-latex-fragment-image-overlays nil))
12281 (defun org-preview-latex-fragment (&optional subtree)
12282 "Preview the LaTeX fragment at point, or all locally or globally.
12283 If the cursor is in a LaTeX fragment, create the image and overlay
12284 it over the source code. If there is no fragment at point, display
12285 all fragments in the current text, from one headline to the next. With
12286 prefix SUBTREE, display all fragments in the current subtree. With a
12287 double prefix `C-u C-u', or when the cursor is before the first headline,
12288 display all fragments in the buffer.
12289 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
12290 (interactive "P")
12291 (org-remove-latex-fragment-image-overlays)
12292 (save-excursion
12293 (save-restriction
12294 (let (beg end at msg)
12295 (cond
12296 ((or (equal subtree '(16))
12297 (not (save-excursion
12298 (re-search-backward (concat "^" outline-regexp) nil t))))
12299 (setq beg (point-min) end (point-max)
12300 msg "Creating images for buffer...%s"))
12301 ((equal subtree '(4))
12302 (org-back-to-heading)
12303 (setq beg (point) end (org-end-of-subtree t)
12304 msg "Creating images for subtree...%s"))
12306 (if (setq at (org-inside-LaTeX-fragment-p))
12307 (goto-char (max (point-min) (- (cdr at) 2)))
12308 (org-back-to-heading))
12309 (setq beg (point) end (progn (outline-next-heading) (point))
12310 msg (if at "Creating image...%s"
12311 "Creating images for entry...%s"))))
12312 (message msg "")
12313 (narrow-to-region beg end)
12314 (goto-char beg)
12315 (org-format-latex
12316 (concat "ltxpng/" (file-name-sans-extension
12317 (file-name-nondirectory
12318 buffer-file-name)))
12319 default-directory 'overlays msg at 'forbuffer)
12320 (message msg "done. Use `C-c C-c' to remove images.")))))
12322 (defvar org-latex-regexps
12323 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
12324 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
12325 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
12326 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
12327 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
12328 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
12329 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
12330 "Regular expressions for matching embedded LaTeX.")
12332 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
12333 "Replace LaTeX fragments with links to an image, and produce images."
12334 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
12335 (let* ((prefixnodir (file-name-nondirectory prefix))
12336 (absprefix (expand-file-name prefix dir))
12337 (todir (file-name-directory absprefix))
12338 (opt org-format-latex-options)
12339 (matchers (plist-get opt :matchers))
12340 (re-list org-latex-regexps)
12341 (cnt 0) txt link beg end re e checkdir
12342 m n block linkfile movefile ov)
12343 ;; Check if there are old images files with this prefix, and remove them
12344 (when (file-directory-p todir)
12345 (mapc 'delete-file
12346 (directory-files
12347 todir 'full
12348 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
12349 ;; Check the different regular expressions
12350 (while (setq e (pop re-list))
12351 (setq m (car e) re (nth 1 e) n (nth 2 e)
12352 block (if (nth 3 e) "\n\n" ""))
12353 (when (member m matchers)
12354 (goto-char (point-min))
12355 (while (re-search-forward re nil t)
12356 (when (or (not at) (equal (cdr at) (match-beginning n)))
12357 (setq txt (match-string n)
12358 beg (match-beginning n) end (match-end n)
12359 cnt (1+ cnt)
12360 linkfile (format "%s_%04d.png" prefix cnt)
12361 movefile (format "%s_%04d.png" absprefix cnt)
12362 link (concat block "[[file:" linkfile "]]" block))
12363 (if msg (message msg cnt))
12364 (goto-char beg)
12365 (unless checkdir ; make sure the directory exists
12366 (setq checkdir t)
12367 (or (file-directory-p todir) (make-directory todir)))
12368 (org-create-formula-image
12369 txt movefile opt forbuffer)
12370 (if overlays
12371 (progn
12372 (setq ov (org-make-overlay beg end))
12373 (if (featurep 'xemacs)
12374 (progn
12375 (org-overlay-put ov 'invisible t)
12376 (org-overlay-put
12377 ov 'end-glyph
12378 (make-glyph (vector 'png :file movefile))))
12379 (org-overlay-put
12380 ov 'display
12381 (list 'image :type 'png :file movefile :ascent 'center)))
12382 (push ov org-latex-fragment-image-overlays)
12383 (goto-char end))
12384 (delete-region beg end)
12385 (insert link))))))))
12387 ;; This function borrows from Ganesh Swami's latex2png.el
12388 (defun org-create-formula-image (string tofile options buffer)
12389 (let* ((tmpdir (if (featurep 'xemacs)
12390 (temp-directory)
12391 temporary-file-directory))
12392 (texfilebase (make-temp-name
12393 (expand-file-name "orgtex" tmpdir)))
12394 (texfile (concat texfilebase ".tex"))
12395 (dvifile (concat texfilebase ".dvi"))
12396 (pngfile (concat texfilebase ".png"))
12397 (fnh (if (featurep 'xemacs)
12398 (font-height (get-face-font 'default))
12399 (face-attribute 'default :height nil)))
12400 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
12401 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
12402 (fg (or (plist-get options (if buffer :foreground :html-foreground))
12403 "Black"))
12404 (bg (or (plist-get options (if buffer :background :html-background))
12405 "Transparent")))
12406 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
12407 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
12408 (with-temp-file texfile
12409 (insert org-format-latex-header
12410 "\n\\begin{document}\n" string "\n\\end{document}\n"))
12411 (let ((dir default-directory))
12412 (condition-case nil
12413 (progn
12414 (cd tmpdir)
12415 (call-process "latex" nil nil nil texfile))
12416 (error nil))
12417 (cd dir))
12418 (if (not (file-exists-p dvifile))
12419 (progn (message "Failed to create dvi file from %s" texfile) nil)
12420 (condition-case nil
12421 (call-process "dvipng" nil nil nil
12422 "-E" "-fg" fg "-bg" bg
12423 "-D" dpi
12424 ;;"-x" scale "-y" scale
12425 "-T" "tight"
12426 "-o" pngfile
12427 dvifile)
12428 (error nil))
12429 (if (not (file-exists-p pngfile))
12430 (progn (message "Failed to create png file from %s" texfile) nil)
12431 ;; Use the requested file name and clean up
12432 (copy-file pngfile tofile 'replace)
12433 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
12434 (delete-file (concat texfilebase e)))
12435 pngfile))))
12437 (defun org-dvipng-color (attr)
12438 "Return an rgb color specification for dvipng."
12439 (apply 'format "rgb %s %s %s"
12440 (mapcar 'org-normalize-color
12441 (color-values (face-attribute 'default attr nil)))))
12443 (defun org-normalize-color (value)
12444 "Return string to be used as color value for an RGB component."
12445 (format "%g" (/ value 65535.0)))
12448 ;;;; Key bindings
12450 ;; Make `C-c C-x' a prefix key
12451 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
12453 ;; TAB key with modifiers
12454 (org-defkey org-mode-map "\C-i" 'org-cycle)
12455 (org-defkey org-mode-map [(tab)] 'org-cycle)
12456 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
12457 (org-defkey org-mode-map [(meta tab)] 'org-complete)
12458 (org-defkey org-mode-map "\M-\t" 'org-complete)
12459 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
12460 ;; The following line is necessary under Suse GNU/Linux
12461 (unless (featurep 'xemacs)
12462 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
12463 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
12464 (define-key org-mode-map [backtab] 'org-shifttab)
12466 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
12467 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
12468 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
12470 ;; Cursor keys with modifiers
12471 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
12472 (org-defkey org-mode-map [(meta right)] 'org-metaright)
12473 (org-defkey org-mode-map [(meta up)] 'org-metaup)
12474 (org-defkey org-mode-map [(meta down)] 'org-metadown)
12476 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
12477 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
12478 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
12479 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
12481 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
12482 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
12483 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
12484 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
12486 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
12487 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
12489 ;;; Extra keys for tty access.
12490 ;; We only set them when really needed because otherwise the
12491 ;; menus don't show the simple keys
12493 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
12494 (not window-system))
12495 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
12496 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
12497 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
12498 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
12499 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
12500 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
12501 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
12502 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
12503 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
12504 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
12505 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
12506 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
12507 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
12508 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
12509 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
12510 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
12511 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
12512 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
12513 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
12514 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
12515 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
12516 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
12518 ;; All the other keys
12520 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
12521 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
12522 (if (boundp 'narrow-map)
12523 (org-defkey narrow-map "s" 'org-narrow-to-subtree)
12524 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree))
12525 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
12526 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
12527 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
12528 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
12529 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
12530 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
12531 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
12532 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
12533 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
12534 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
12535 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
12536 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
12537 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
12538 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
12539 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
12540 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
12541 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
12542 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
12543 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
12544 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
12545 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
12546 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
12547 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
12548 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
12549 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
12550 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
12551 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
12552 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
12553 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
12554 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
12555 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
12556 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
12557 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
12558 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
12559 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
12560 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
12561 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
12562 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
12563 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
12564 (org-defkey org-mode-map "\C-c^" 'org-sort)
12565 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
12566 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
12567 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
12568 (org-defkey org-mode-map "\C-m" 'org-return)
12569 (org-defkey org-mode-map "\C-j" 'org-return-indent)
12570 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
12571 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
12572 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
12573 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
12574 (org-defkey org-mode-map "\C-c'" 'org-edit-special)
12575 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
12576 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
12577 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
12578 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
12579 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
12580 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
12581 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
12582 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
12583 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
12584 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
12586 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-mark-entry-for-agenda-action)
12587 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
12588 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
12589 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
12591 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
12592 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
12593 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
12594 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
12595 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
12596 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
12597 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
12598 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
12599 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
12600 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
12601 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
12602 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
12604 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
12606 (when (featurep 'xemacs)
12607 (org-defkey org-mode-map 'button3 'popup-mode-menu))
12609 (defvar org-table-auto-blank-field) ; defined in org-table.el
12610 (defun org-self-insert-command (N)
12611 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
12612 If the cursor is in a table looking at whitespace, the whitespace is
12613 overwritten, and the table is not marked as requiring realignment."
12614 (interactive "p")
12615 (if (and (org-table-p)
12616 (progn
12617 ;; check if we blank the field, and if that triggers align
12618 (and (featurep 'org-table) org-table-auto-blank-field
12619 (member last-command
12620 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
12621 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
12622 ;; got extra space, this field does not determine column width
12623 (let (org-table-may-need-update) (org-table-blank-field))
12624 ;; no extra space, this field may determine column width
12625 (org-table-blank-field)))
12627 (eq N 1)
12628 (looking-at "[^|\n]* |"))
12629 (let (org-table-may-need-update)
12630 (goto-char (1- (match-end 0)))
12631 (delete-backward-char 1)
12632 (goto-char (match-beginning 0))
12633 (self-insert-command N))
12634 (setq org-table-may-need-update t)
12635 (self-insert-command N)
12636 (org-fix-tags-on-the-fly)))
12638 (defun org-fix-tags-on-the-fly ()
12639 (when (and (equal (char-after (point-at-bol)) ?*)
12640 (org-on-heading-p))
12641 (org-align-tags-here org-tags-column)))
12643 (defun org-delete-backward-char (N)
12644 "Like `delete-backward-char', insert whitespace at field end in tables.
12645 When deleting backwards, in tables this function will insert whitespace in
12646 front of the next \"|\" separator, to keep the table aligned. The table will
12647 still be marked for re-alignment if the field did fill the entire column,
12648 because, in this case the deletion might narrow the column."
12649 (interactive "p")
12650 (if (and (org-table-p)
12651 (eq N 1)
12652 (string-match "|" (buffer-substring (point-at-bol) (point)))
12653 (looking-at ".*?|"))
12654 (let ((pos (point))
12655 (noalign (looking-at "[^|\n\r]* |"))
12656 (c org-table-may-need-update))
12657 (backward-delete-char N)
12658 (skip-chars-forward "^|")
12659 (insert " ")
12660 (goto-char (1- pos))
12661 ;; noalign: if there were two spaces at the end, this field
12662 ;; does not determine the width of the column.
12663 (if noalign (setq org-table-may-need-update c)))
12664 (backward-delete-char N)
12665 (org-fix-tags-on-the-fly)))
12667 (defun org-delete-char (N)
12668 "Like `delete-char', but insert whitespace at field end in tables.
12669 When deleting characters, in tables this function will insert whitespace in
12670 front of the next \"|\" separator, to keep the table aligned. The table will
12671 still be marked for re-alignment if the field did fill the entire column,
12672 because, in this case the deletion might narrow the column."
12673 (interactive "p")
12674 (if (and (org-table-p)
12675 (not (bolp))
12676 (not (= (char-after) ?|))
12677 (eq N 1))
12678 (if (looking-at ".*?|")
12679 (let ((pos (point))
12680 (noalign (looking-at "[^|\n\r]* |"))
12681 (c org-table-may-need-update))
12682 (replace-match (concat
12683 (substring (match-string 0) 1 -1)
12684 " |"))
12685 (goto-char pos)
12686 ;; noalign: if there were two spaces at the end, this field
12687 ;; does not determine the width of the column.
12688 (if noalign (setq org-table-may-need-update c)))
12689 (delete-char N))
12690 (delete-char N)
12691 (org-fix-tags-on-the-fly)))
12693 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
12694 (put 'org-self-insert-command 'delete-selection t)
12695 (put 'orgtbl-self-insert-command 'delete-selection t)
12696 (put 'org-delete-char 'delete-selection 'supersede)
12697 (put 'org-delete-backward-char 'delete-selection 'supersede)
12699 ;; Make `flyspell-mode' delay after some commands
12700 (put 'org-self-insert-command 'flyspell-delayed t)
12701 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
12702 (put 'org-delete-char 'flyspell-delayed t)
12703 (put 'org-delete-backward-char 'flyspell-delayed t)
12705 ;; Make pabbrev-mode expand after org-mode commands
12706 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
12707 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
12709 ;; How to do this: Measure non-white length of current string
12710 ;; If equal to column width, we should realign.
12712 (defun org-remap (map &rest commands)
12713 "In MAP, remap the functions given in COMMANDS.
12714 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
12715 (let (new old)
12716 (while commands
12717 (setq old (pop commands) new (pop commands))
12718 (if (fboundp 'command-remapping)
12719 (org-defkey map (vector 'remap old) new)
12720 (substitute-key-definition old new map global-map)))))
12722 (when (eq org-enable-table-editor 'optimized)
12723 ;; If the user wants maximum table support, we need to hijack
12724 ;; some standard editing functions
12725 (org-remap org-mode-map
12726 'self-insert-command 'org-self-insert-command
12727 'delete-char 'org-delete-char
12728 'delete-backward-char 'org-delete-backward-char)
12729 (org-defkey org-mode-map "|" 'org-force-self-insert))
12731 (defun org-shiftcursor-error ()
12732 "Throw an error because Shift-Cursor command was applied in wrong context."
12733 (error "This command is active in special context like tables, headlines or timestamps"))
12735 (defun org-shifttab (&optional arg)
12736 "Global visibility cycling or move to previous table field.
12737 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
12738 on context.
12739 See the individual commands for more information."
12740 (interactive "P")
12741 (cond
12742 ((org-at-table-p) (call-interactively 'org-table-previous-field))
12743 ((integerp arg)
12744 (message "Content view to level: %d" arg)
12745 (org-content (prefix-numeric-value arg))
12746 (setq org-cycle-global-status 'overview))
12747 (t (call-interactively 'org-global-cycle))))
12749 (defun org-shiftmetaleft ()
12750 "Promote subtree or delete table column.
12751 Calls `org-promote-subtree', `org-outdent-item',
12752 or `org-table-delete-column', depending on context.
12753 See the individual commands for more information."
12754 (interactive)
12755 (cond
12756 ((org-at-table-p) (call-interactively 'org-table-delete-column))
12757 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
12758 ((org-at-item-p) (call-interactively 'org-outdent-item))
12759 (t (org-shiftcursor-error))))
12761 (defun org-shiftmetaright ()
12762 "Demote subtree or insert table column.
12763 Calls `org-demote-subtree', `org-indent-item',
12764 or `org-table-insert-column', depending on context.
12765 See the individual commands for more information."
12766 (interactive)
12767 (cond
12768 ((org-at-table-p) (call-interactively 'org-table-insert-column))
12769 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
12770 ((org-at-item-p) (call-interactively 'org-indent-item))
12771 (t (org-shiftcursor-error))))
12773 (defun org-shiftmetaup (&optional arg)
12774 "Move subtree up or kill table row.
12775 Calls `org-move-subtree-up' or `org-table-kill-row' or
12776 `org-move-item-up' depending on context. See the individual commands
12777 for more information."
12778 (interactive "P")
12779 (cond
12780 ((org-at-table-p) (call-interactively 'org-table-kill-row))
12781 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12782 ((org-at-item-p) (call-interactively 'org-move-item-up))
12783 (t (org-shiftcursor-error))))
12784 (defun org-shiftmetadown (&optional arg)
12785 "Move subtree down or insert table row.
12786 Calls `org-move-subtree-down' or `org-table-insert-row' or
12787 `org-move-item-down', depending on context. See the individual
12788 commands for more information."
12789 (interactive "P")
12790 (cond
12791 ((org-at-table-p) (call-interactively 'org-table-insert-row))
12792 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12793 ((org-at-item-p) (call-interactively 'org-move-item-down))
12794 (t (org-shiftcursor-error))))
12796 (defun org-metaleft (&optional arg)
12797 "Promote heading or move table column to left.
12798 Calls `org-do-promote' or `org-table-move-column', depending on context.
12799 With no specific context, calls the Emacs default `backward-word'.
12800 See the individual commands for more information."
12801 (interactive "P")
12802 (cond
12803 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12804 ((or (org-on-heading-p) (org-region-active-p))
12805 (call-interactively 'org-do-promote))
12806 ((org-at-item-p) (call-interactively 'org-outdent-item))
12807 (t (call-interactively 'backward-word))))
12809 (defun org-metaright (&optional arg)
12810 "Demote subtree or move table column to right.
12811 Calls `org-do-demote' or `org-table-move-column', depending on context.
12812 With no specific context, calls the Emacs default `forward-word'.
12813 See the individual commands for more information."
12814 (interactive "P")
12815 (cond
12816 ((org-at-table-p) (call-interactively 'org-table-move-column))
12817 ((or (org-on-heading-p) (org-region-active-p))
12818 (call-interactively 'org-do-demote))
12819 ((org-at-item-p) (call-interactively 'org-indent-item))
12820 (t (call-interactively 'forward-word))))
12822 (defun org-metaup (&optional arg)
12823 "Move subtree up or move table row up.
12824 Calls `org-move-subtree-up' or `org-table-move-row' or
12825 `org-move-item-up', depending on context. See the individual commands
12826 for more information."
12827 (interactive "P")
12828 (cond
12829 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12830 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12831 ((org-at-item-p) (call-interactively 'org-move-item-up))
12832 (t (transpose-lines 1) (beginning-of-line -1))))
12834 (defun org-metadown (&optional arg)
12835 "Move subtree down or move table row down.
12836 Calls `org-move-subtree-down' or `org-table-move-row' or
12837 `org-move-item-down', depending on context. See the individual
12838 commands for more information."
12839 (interactive "P")
12840 (cond
12841 ((org-at-table-p) (call-interactively 'org-table-move-row))
12842 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12843 ((org-at-item-p) (call-interactively 'org-move-item-down))
12844 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12846 (defun org-shiftup (&optional arg)
12847 "Increase item in timestamp or increase priority of current headline.
12848 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-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-down 'org-timestamp-up)))
12855 ((org-on-heading-p) (call-interactively 'org-priority-up))
12856 ((org-at-item-p) (call-interactively 'org-previous-item))
12857 ((org-clocktable-try-shift 'up arg))
12858 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12860 (defun org-shiftdown (&optional arg)
12861 "Decrease item in timestamp or decrease priority of current headline.
12862 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12863 depending on context. See the individual commands for more information."
12864 (interactive "P")
12865 (cond
12866 ((org-at-timestamp-p t)
12867 (call-interactively (if org-edit-timestamp-down-means-later
12868 'org-timestamp-up 'org-timestamp-down)))
12869 ((org-on-heading-p) (call-interactively 'org-priority-down))
12870 ((org-clocktable-try-shift 'down arg))
12871 (t (call-interactively 'org-next-item))))
12873 (defun org-shiftright (&optional arg)
12874 "Next TODO keyword or timestamp one day later, depending on context."
12875 (interactive "P")
12876 (cond
12877 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12878 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12879 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12880 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12881 ((org-clocktable-try-shift 'right arg))
12882 (t (org-shiftcursor-error))))
12884 (defun org-shiftleft (&optional arg)
12885 "Previous TODO keyword or timestamp one day earlier, depending on context."
12886 (interactive "P")
12887 (cond
12888 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12889 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12890 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12891 ((org-at-property-p)
12892 (call-interactively 'org-property-previous-allowed-value))
12893 ((org-clocktable-try-shift 'left arg))
12894 (t (org-shiftcursor-error))))
12896 (defun org-shiftcontrolright ()
12897 "Switch to next TODO set."
12898 (interactive)
12899 (cond
12900 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12901 (t (org-shiftcursor-error))))
12903 (defun org-shiftcontrolleft ()
12904 "Switch to previous TODO set."
12905 (interactive)
12906 (cond
12907 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12908 (t (org-shiftcursor-error))))
12910 (defun org-ctrl-c-ret ()
12911 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12912 (interactive)
12913 (cond
12914 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12915 (t (call-interactively 'org-insert-heading))))
12917 (defun org-copy-special ()
12918 "Copy region in table or copy current subtree.
12919 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12920 See the individual commands for more information."
12921 (interactive)
12922 (call-interactively
12923 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12925 (defun org-cut-special ()
12926 "Cut region in table or cut current subtree.
12927 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12928 See the individual commands for more information."
12929 (interactive)
12930 (call-interactively
12931 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12933 (defun org-paste-special (arg)
12934 "Paste rectangular region into table, or past subtree relative to level.
12935 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12936 See the individual commands for more information."
12937 (interactive "P")
12938 (if (org-at-table-p)
12939 (org-table-paste-rectangle)
12940 (org-paste-subtree arg)))
12942 (defun org-edit-special ()
12943 "Call a special editor for the stuff at point.
12944 When at a table, call the formula editor with `org-table-edit-formulas'.
12945 When at the first line of an src example, call `org-edit-src-code'.
12946 When in an #+include line, visit the include file. Otherwise call
12947 `ffap' to visit the file at point."
12948 (interactive)
12949 (cond
12950 ((org-at-table-p)
12951 (call-interactively 'org-table-edit-formulas))
12952 ((save-excursion
12953 (beginning-of-line 1)
12954 (looking-at "\\(?:#\\+\\(?:setupfile\\|include\\):?[ \t]+\"?\\|[ \t]*<include\\>.*?file=\"\\)\\([^\"\n>]+\\)"))
12955 (find-file (org-trim (match-string 1))))
12956 ((org-edit-src-code))
12957 (t (call-interactively 'ffap))))
12959 (defun org-ctrl-c-ctrl-c (&optional arg)
12960 "Set tags in headline, or update according to changed information at point.
12962 This command does many different things, depending on context:
12964 - If the cursor is in a headline, prompt for tags and insert them
12965 into the current line, aligned to `org-tags-column'. When called
12966 with prefix arg, realign all tags in the current buffer.
12968 - If the cursor is in one of the special #+KEYWORD lines, this
12969 triggers scanning the buffer for these lines and updating the
12970 information.
12972 - If the cursor is inside a table, realign the table. This command
12973 works even if the automatic table editor has been turned off.
12975 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12976 the entire table.
12978 - If the cursor is a the beginning of a dynamic block, update it.
12980 - If the cursor is inside a table created by the table.el package,
12981 activate that table.
12983 - If the current buffer is a remember buffer, close note and file it.
12984 with a prefix argument, file it without further interaction to the default
12985 location.
12987 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12988 links in this buffer.
12990 - If the cursor is on a numbered item in a plain list, renumber the
12991 ordered list.
12993 - If the cursor is on a checkbox, toggle it."
12994 (interactive "P")
12995 (let ((org-enable-table-editor t))
12996 (cond
12997 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12998 org-occur-highlights
12999 org-latex-fragment-image-overlays)
13000 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
13001 (org-remove-occur-highlights)
13002 (org-remove-latex-fragment-image-overlays)
13003 (message "Temporary highlights/overlays removed from current buffer"))
13004 ((and (local-variable-p 'org-finish-function (current-buffer))
13005 (fboundp org-finish-function))
13006 (funcall org-finish-function))
13007 ((org-at-property-p)
13008 (call-interactively 'org-property-action))
13009 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
13010 ((org-on-heading-p) (call-interactively 'org-set-tags))
13011 ((org-at-table.el-p)
13012 (require 'table)
13013 (beginning-of-line 1)
13014 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
13015 (call-interactively 'table-recognize-table))
13016 ((org-at-table-p)
13017 (org-table-maybe-eval-formula)
13018 (if arg
13019 (call-interactively 'org-table-recalculate)
13020 (org-table-maybe-recalculate-line))
13021 (call-interactively 'org-table-align))
13022 ((org-at-item-checkbox-p)
13023 (call-interactively 'org-toggle-checkbox))
13024 ((org-at-item-p)
13025 (call-interactively 'org-maybe-renumber-ordered-list))
13026 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
13027 ;; Dynamic block
13028 (beginning-of-line 1)
13029 (org-update-dblock))
13030 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
13031 (cond
13032 ((equal (match-string 1) "TBLFM")
13033 ;; Recalculate the table before this line
13034 (save-excursion
13035 (beginning-of-line 1)
13036 (skip-chars-backward " \r\n\t")
13037 (if (org-at-table-p)
13038 (org-call-with-arg 'org-table-recalculate t))))
13040 ; (org-set-regexps-and-options)
13041 ; (org-restart-font-lock)
13042 (let ((org-inhibit-startup t)) (org-mode-restart))
13043 (message "Local setup has been refreshed"))))
13044 (t (error "C-c C-c can do nothing useful at this location.")))))
13046 (defun org-mode-restart ()
13047 "Restart Org-mode, to scan again for special lines.
13048 Also updates the keyword regular expressions."
13049 (interactive)
13050 (org-mode)
13051 (message "Org-mode restarted"))
13053 (defun org-kill-note-or-show-branches ()
13054 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
13055 (interactive)
13056 (if (not org-finish-function)
13057 (call-interactively 'show-branches)
13058 (let ((org-note-abort t))
13059 (funcall org-finish-function))))
13061 (defun org-return (&optional indent)
13062 "Goto next table row or insert a newline.
13063 Calls `org-table-next-row' or `newline', depending on context.
13064 See the individual commands for more information."
13065 (interactive)
13066 (cond
13067 ((bobp) (if indent (newline-and-indent) (newline)))
13068 ((and (org-at-heading-p)
13069 (looking-at
13070 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
13071 (org-show-entry)
13072 (end-of-line 1)
13073 (newline))
13074 ((org-at-table-p)
13075 (org-table-justify-field-maybe)
13076 (call-interactively 'org-table-next-row))
13077 (t (if indent (newline-and-indent) (newline)))))
13079 (defun org-return-indent ()
13080 "Goto next table row or insert a newline and indent.
13081 Calls `org-table-next-row' or `newline-and-indent', depending on
13082 context. See the individual commands for more information."
13083 (interactive)
13084 (org-return t))
13086 (defun org-ctrl-c-star ()
13087 "Compute table, or change heading status of lines.
13088 Calls `org-table-recalculate' or `org-toggle-region-headings',
13089 depending on context. This will also turn a plain list item or a normal
13090 line into a subheading."
13091 (interactive)
13092 (cond
13093 ((org-at-table-p)
13094 (call-interactively 'org-table-recalculate))
13095 ((org-region-active-p)
13096 ;; Convert all lines in region to list items
13097 (call-interactively 'org-toggle-region-headings))
13098 ((org-on-heading-p)
13099 (org-toggle-region-headings (point-at-bol)
13100 (min (1+ (point-at-eol)) (point-max))))
13101 ((org-at-item-p)
13102 ;; Convert to heading
13103 (let ((level (save-match-data
13104 (save-excursion
13105 (condition-case nil
13106 (progn
13107 (org-back-to-heading t)
13108 (funcall outline-level))
13109 (error 0))))))
13110 (replace-match
13111 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
13112 (t (org-toggle-region-headings (point-at-bol)
13113 (min (1+ (point-at-eol)) (point-max))))))
13115 (defun org-ctrl-c-minus ()
13116 "Insert separator line in table or modify bullet status of line.
13117 Also turns a plain line or a region of lines into list items.
13118 Calls `org-table-insert-hline', `org-toggle-region-items', or
13119 `org-cycle-list-bullet', depending on context."
13120 (interactive)
13121 (cond
13122 ((org-at-table-p)
13123 (call-interactively 'org-table-insert-hline))
13124 ((org-on-heading-p)
13125 ;; Convert to item
13126 (save-excursion
13127 (beginning-of-line 1)
13128 (if (looking-at "\\*+ ")
13129 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
13130 ((org-region-active-p)
13131 ;; Convert all lines in region to list items
13132 (call-interactively 'org-toggle-region-items))
13133 ((org-in-item-p)
13134 (call-interactively 'org-cycle-list-bullet))
13135 (t (org-toggle-region-items (point-at-bol)
13136 (min (1+ (point-at-eol)) (point-max))))))
13138 (defun org-toggle-region-items (beg end)
13139 "Convert all lines in region to list items.
13140 If the first line is already an item, convert all list items in the region
13141 to normal lines."
13142 (interactive "r")
13143 (let (l2 l)
13144 (save-excursion
13145 (goto-char end)
13146 (setq l2 (org-current-line))
13147 (goto-char beg)
13148 (beginning-of-line 1)
13149 (setq l (1- (org-current-line)))
13150 (if (org-at-item-p)
13151 ;; We already have items, de-itemize
13152 (while (< (setq l (1+ l)) l2)
13153 (when (org-at-item-p)
13154 (goto-char (match-beginning 2))
13155 (delete-region (match-beginning 2) (match-end 2))
13156 (and (looking-at "[ \t]+") (replace-match "")))
13157 (beginning-of-line 2))
13158 (while (< (setq l (1+ l)) l2)
13159 (unless (org-at-item-p)
13160 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13161 (replace-match "\\1- \\2")))
13162 (beginning-of-line 2))))))
13164 (defun org-toggle-region-headings (beg end)
13165 "Convert all lines in region to list items.
13166 If the first line is already an item, convert all list items in the region
13167 to normal lines."
13168 (interactive "r")
13169 (let (l2 l)
13170 (save-excursion
13171 (goto-char end)
13172 (setq l2 (org-current-line))
13173 (goto-char beg)
13174 (beginning-of-line 1)
13175 (setq l (1- (org-current-line)))
13176 (if (org-on-heading-p)
13177 ;; We already have headlines, de-star them
13178 (while (< (setq l (1+ l)) l2)
13179 (when (org-on-heading-p t)
13180 (and (looking-at outline-regexp) (replace-match "")))
13181 (beginning-of-line 2))
13182 (let* ((stars (save-excursion
13183 (re-search-backward org-complex-heading-regexp nil t)
13184 (or (match-string 1) "*")))
13185 (add-stars (if org-odd-levels-only "**" "*"))
13186 (rpl (concat stars add-stars " \\2")))
13187 (while (< (setq l (1+ l)) l2)
13188 (unless (org-on-heading-p)
13189 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
13190 (replace-match rpl)))
13191 (beginning-of-line 2)))))))
13193 (defun org-meta-return (&optional arg)
13194 "Insert a new heading or wrap a region in a table.
13195 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
13196 See the individual commands for more information."
13197 (interactive "P")
13198 (cond
13199 ((org-at-table-p)
13200 (call-interactively 'org-table-wrap-region))
13201 (t (call-interactively 'org-insert-heading))))
13203 ;;; Menu entries
13205 ;; Define the Org-mode menus
13206 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
13207 '("Tbl"
13208 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
13209 ["Next Field" org-cycle (org-at-table-p)]
13210 ["Previous Field" org-shifttab (org-at-table-p)]
13211 ["Next Row" org-return (org-at-table-p)]
13212 "--"
13213 ["Blank Field" org-table-blank-field (org-at-table-p)]
13214 ["Edit Field" org-table-edit-field (org-at-table-p)]
13215 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
13216 "--"
13217 ("Column"
13218 ["Move Column Left" org-metaleft (org-at-table-p)]
13219 ["Move Column Right" org-metaright (org-at-table-p)]
13220 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
13221 ["Insert Column" org-shiftmetaright (org-at-table-p)])
13222 ("Row"
13223 ["Move Row Up" org-metaup (org-at-table-p)]
13224 ["Move Row Down" org-metadown (org-at-table-p)]
13225 ["Delete Row" org-shiftmetaup (org-at-table-p)]
13226 ["Insert Row" org-shiftmetadown (org-at-table-p)]
13227 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
13228 "--"
13229 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
13230 ("Rectangle"
13231 ["Copy Rectangle" org-copy-special (org-at-table-p)]
13232 ["Cut Rectangle" org-cut-special (org-at-table-p)]
13233 ["Paste Rectangle" org-paste-special (org-at-table-p)]
13234 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
13235 "--"
13236 ("Calculate"
13237 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
13238 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
13239 ["Edit Formulas" org-edit-special (org-at-table-p)]
13240 "--"
13241 ["Recalculate line" org-table-recalculate (org-at-table-p)]
13242 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
13243 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
13244 "--"
13245 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
13246 "--"
13247 ["Sum Column/Rectangle" org-table-sum
13248 (or (org-at-table-p) (org-region-active-p))]
13249 ["Which Column?" org-table-current-column (org-at-table-p)])
13250 ["Debug Formulas"
13251 org-table-toggle-formula-debugger
13252 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
13253 ["Show Col/Row Numbers"
13254 org-table-toggle-coordinate-overlays
13255 :style toggle
13256 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
13257 "--"
13258 ["Create" org-table-create (and (not (org-at-table-p))
13259 org-enable-table-editor)]
13260 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
13261 ["Import from File" org-table-import (not (org-at-table-p))]
13262 ["Export to File" org-table-export (org-at-table-p)]
13263 "--"
13264 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
13266 (easy-menu-define org-org-menu org-mode-map "Org menu"
13267 '("Org"
13268 ("Show/Hide"
13269 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
13270 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
13271 ["Sparse Tree..." org-sparse-tree t]
13272 ["Reveal Context" org-reveal t]
13273 ["Show All" show-all t]
13274 "--"
13275 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
13276 "--"
13277 ["New Heading" org-insert-heading t]
13278 ("Navigate Headings"
13279 ["Up" outline-up-heading t]
13280 ["Next" outline-next-visible-heading t]
13281 ["Previous" outline-previous-visible-heading t]
13282 ["Next Same Level" outline-forward-same-level t]
13283 ["Previous Same Level" outline-backward-same-level t]
13284 "--"
13285 ["Jump" org-goto t])
13286 ("Edit Structure"
13287 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
13288 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
13289 "--"
13290 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
13291 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
13292 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
13293 "--"
13294 ["Promote Heading" org-metaleft (not (org-at-table-p))]
13295 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
13296 ["Demote Heading" org-metaright (not (org-at-table-p))]
13297 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
13298 "--"
13299 ["Sort Region/Children" org-sort (not (org-at-table-p))]
13300 "--"
13301 ["Convert to odd levels" org-convert-to-odd-levels t]
13302 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
13303 ("Editing"
13304 ["Emphasis..." org-emphasize t]
13305 ["Edit Source Example" org-edit-special t])
13306 ("Archive"
13307 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
13308 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
13309 ; :active t :keys "C-u C-c C-x C-a"]
13310 ["Sparse trees open ARCHIVE trees"
13311 (setq org-sparse-tree-open-archived-trees
13312 (not org-sparse-tree-open-archived-trees))
13313 :style toggle :selected org-sparse-tree-open-archived-trees]
13314 ["Cycling opens ARCHIVE trees"
13315 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
13316 :style toggle :selected org-cycle-open-archived-trees]
13317 "--"
13318 ["Move Subtree to Archive" org-advertized-archive-subtree t]
13319 ; ["Check and Move Children" (org-archive-subtree '(4))
13320 ; :active t :keys "C-u C-c C-x C-s"]
13322 "--"
13323 ("TODO Lists"
13324 ["TODO/DONE/-" org-todo t]
13325 ("Select keyword"
13326 ["Next keyword" org-shiftright (org-on-heading-p)]
13327 ["Previous keyword" org-shiftleft (org-on-heading-p)]
13328 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
13329 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
13330 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
13331 ["Show TODO Tree" org-show-todo-tree t]
13332 ["Global TODO list" org-todo-list t]
13333 "--"
13334 ["Set Priority" org-priority t]
13335 ["Priority Up" org-shiftup t]
13336 ["Priority Down" org-shiftdown t])
13337 ("TAGS and Properties"
13338 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
13339 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
13340 "--"
13341 ["Set property" 'org-set-property t]
13342 ["Column view of properties" org-columns t]
13343 ["Insert Column View DBlock" org-insert-columns-dblock t])
13344 ("Dates and Scheduling"
13345 ["Timestamp" org-time-stamp t]
13346 ["Timestamp (inactive)" org-time-stamp-inactive t]
13347 ("Change Date"
13348 ["1 Day Later" org-shiftright t]
13349 ["1 Day Earlier" org-shiftleft t]
13350 ["1 ... Later" org-shiftup t]
13351 ["1 ... Earlier" org-shiftdown t])
13352 ["Compute Time Range" org-evaluate-time-range t]
13353 ["Schedule Item" org-schedule t]
13354 ["Deadline" org-deadline t]
13355 "--"
13356 ["Custom time format" org-toggle-time-stamp-overlays
13357 :style radio :selected org-display-custom-times]
13358 "--"
13359 ["Goto Calendar" org-goto-calendar t]
13360 ["Date from Calendar" org-date-from-calendar t])
13361 ("Logging work"
13362 ["Clock in" org-clock-in t]
13363 ["Clock out" org-clock-out t]
13364 ["Clock cancel" org-clock-cancel t]
13365 ["Goto running clock" org-clock-goto t]
13366 ["Display times" org-clock-display t]
13367 ["Create clock table" org-clock-report t]
13368 "--"
13369 ["Record DONE time"
13370 (progn (setq org-log-done (not org-log-done))
13371 (message "Switching to %s will %s record a timestamp"
13372 (car org-done-keywords)
13373 (if org-log-done "automatically" "not")))
13374 :style toggle :selected org-log-done])
13375 "--"
13376 ["Agenda Command..." org-agenda t]
13377 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
13378 ("File List for Agenda")
13379 ("Special views current file"
13380 ["TODO Tree" org-show-todo-tree t]
13381 ["Check Deadlines" org-check-deadlines t]
13382 ["Timeline" org-timeline t]
13383 ["Tags Tree" org-tags-sparse-tree t])
13384 "--"
13385 ("Hyperlinks"
13386 ["Store Link (Global)" org-store-link t]
13387 ["Insert Link" org-insert-link t]
13388 ["Follow Link" org-open-at-point t]
13389 "--"
13390 ["Next link" org-next-link t]
13391 ["Previous link" org-previous-link t]
13392 "--"
13393 ["Descriptive Links"
13394 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
13395 :style radio
13396 :selected (member '(org-link) buffer-invisibility-spec)]
13397 ["Literal Links"
13398 (progn
13399 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
13400 :style radio
13401 :selected (not (member '(org-link) buffer-invisibility-spec))])
13402 "--"
13403 ["Export/Publish..." org-export t]
13404 ("LaTeX"
13405 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
13406 :selected org-cdlatex-mode]
13407 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
13408 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
13409 ["Modify math symbol" org-cdlatex-math-modify
13410 (org-inside-LaTeX-fragment-p)]
13411 ["Export LaTeX fragments as images"
13412 (if (featurep 'org-exp)
13413 (setq org-export-with-LaTeX-fragments
13414 (not org-export-with-LaTeX-fragments))
13415 (require 'org-exp))
13416 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
13417 org-export-with-LaTeX-fragments)])
13418 "--"
13419 ("Documentation"
13420 ["Show Version" org-version t]
13421 ["Info Documentation" org-info t])
13422 ("Customize"
13423 ["Browse Org Group" org-customize t]
13424 "--"
13425 ["Expand This Menu" org-create-customize-menu
13426 (fboundp 'customize-menu-create)])
13427 "--"
13428 ["Refresh setup" org-mode-restart t]
13431 (defun org-info (&optional node)
13432 "Read documentation for Org-mode in the info system.
13433 With optional NODE, go directly to that node."
13434 (interactive)
13435 (info (format "(org)%s" (or node ""))))
13437 (defun org-install-agenda-files-menu ()
13438 (let ((bl (buffer-list)))
13439 (save-excursion
13440 (while bl
13441 (set-buffer (pop bl))
13442 (if (org-mode-p) (setq bl nil)))
13443 (when (org-mode-p)
13444 (easy-menu-change
13445 '("Org") "File List for Agenda"
13446 (append
13447 (list
13448 ["Edit File List" (org-edit-agenda-file-list) t]
13449 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
13450 ["Remove Current File from List" org-remove-file t]
13451 ["Cycle through agenda files" org-cycle-agenda-files t]
13452 ["Occur in all agenda files" org-occur-in-agenda-files t]
13453 "--")
13454 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
13456 ;;;; Documentation
13458 ;;;###autoload
13459 (defun org-require-autoloaded-modules ()
13460 (interactive)
13461 (mapc 'require
13462 '(org-agenda org-archive org-clock org-colview
13463 org-exp org-id org-export-latex org-publish
13464 org-remember org-table)))
13466 ;;;###autoload
13467 (defun org-customize ()
13468 "Call the customize function with org as argument."
13469 (interactive)
13470 (org-load-modules-maybe)
13471 (org-require-autoloaded-modules)
13472 (customize-browse 'org))
13474 (defun org-create-customize-menu ()
13475 "Create a full customization menu for Org-mode, insert it into the menu."
13476 (interactive)
13477 (org-load-modules-maybe)
13478 (org-require-autoloaded-modules)
13479 (if (fboundp 'customize-menu-create)
13480 (progn
13481 (easy-menu-change
13482 '("Org") "Customize"
13483 `(["Browse Org group" org-customize t]
13484 "--"
13485 ,(customize-menu-create 'org)
13486 ["Set" Custom-set t]
13487 ["Save" Custom-save t]
13488 ["Reset to Current" Custom-reset-current t]
13489 ["Reset to Saved" Custom-reset-saved t]
13490 ["Reset to Standard Settings" Custom-reset-standard t]))
13491 (message "\"Org\"-menu now contains full customization menu"))
13492 (error "Cannot expand menu (outdated version of cus-edit.el)")))
13494 ;;;; Miscellaneous stuff
13496 ;;; Generally useful functions
13498 (defun org-display-warning (message) ;; Copied from Emacs-Muse
13499 "Display the given MESSAGE as a warning."
13500 (if (fboundp 'display-warning)
13501 (display-warning 'org message
13502 (if (featurep 'xemacs)
13503 'warning
13504 :warning))
13505 (let ((buf (get-buffer-create "*Org warnings*")))
13506 (with-current-buffer buf
13507 (goto-char (point-max))
13508 (insert "Warning (Org): " message)
13509 (unless (bolp)
13510 (newline)))
13511 (display-buffer buf)
13512 (sit-for 0))))
13514 (defun org-goto-marker-or-bmk (marker &optional bookmark)
13515 "Go to MARKER, widen if necesary. When marker is not live, try BOOKMARK."
13516 (if (and marker (marker-buffer marker)
13517 (buffer-live-p (marker-buffer marker)))
13518 (progn
13519 (switch-to-buffer (marker-buffer marker))
13520 (if (or (> marker (point-max)) (< marker (point-min)))
13521 (widen))
13522 (goto-char marker))
13523 (if bookmark
13524 (bookmark-jump bookmark)
13525 (error "Cannot find location"))))
13527 (defun org-quote-csv-field (s)
13528 "Quote field for inclusion in CSV material."
13529 (if (string-match "[\",]" s)
13530 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
13533 (defun org-plist-delete (plist property)
13534 "Delete PROPERTY from PLIST.
13535 This is in contrast to merely setting it to 0."
13536 (let (p)
13537 (while plist
13538 (if (not (eq property (car plist)))
13539 (setq p (plist-put p (car plist) (nth 1 plist))))
13540 (setq plist (cddr plist)))
13543 (defun org-force-self-insert (N)
13544 "Needed to enforce self-insert under remapping."
13545 (interactive "p")
13546 (self-insert-command N))
13548 (defun org-string-width (s)
13549 "Compute width of string, ignoring invisible characters.
13550 This ignores character with invisibility property `org-link', and also
13551 characters with property `org-cwidth', because these will become invisible
13552 upon the next fontification round."
13553 (let (b l)
13554 (when (or (eq t buffer-invisibility-spec)
13555 (assq 'org-link buffer-invisibility-spec))
13556 (while (setq b (text-property-any 0 (length s)
13557 'invisible 'org-link s))
13558 (setq s (concat (substring s 0 b)
13559 (substring s (or (next-single-property-change
13560 b 'invisible s) (length s)))))))
13561 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
13562 (setq s (concat (substring s 0 b)
13563 (substring s (or (next-single-property-change
13564 b 'org-cwidth s) (length s))))))
13565 (setq l (string-width s) b -1)
13566 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
13567 (setq l (- l (get-text-property b 'org-dwidth-n s))))
13570 (defun org-base-buffer (buffer)
13571 "Return the base buffer of BUFFER, if it has one. Else return the buffer."
13572 (if (not buffer)
13573 buffer
13574 (or (buffer-base-buffer buffer)
13575 buffer)))
13577 (defun org-trim (s)
13578 "Remove whitespace at beginning and end of string."
13579 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
13580 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
13583 (defun org-wrap (string &optional width lines)
13584 "Wrap string to either a number of lines, or a width in characters.
13585 If WIDTH is non-nil, the string is wrapped to that width, however many lines
13586 that costs. If there is a word longer than WIDTH, the text is actually
13587 wrapped to the length of that word.
13588 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
13589 many lines, whatever width that takes.
13590 The return value is a list of lines, without newlines at the end."
13591 (let* ((words (org-split-string string "[ \t\n]+"))
13592 (maxword (apply 'max (mapcar 'org-string-width words)))
13593 w ll)
13594 (cond (width
13595 (org-do-wrap words (max maxword width)))
13596 (lines
13597 (setq w maxword)
13598 (setq ll (org-do-wrap words maxword))
13599 (if (<= (length ll) lines)
13601 (setq ll words)
13602 (while (> (length ll) lines)
13603 (setq w (1+ w))
13604 (setq ll (org-do-wrap words w)))
13605 ll))
13606 (t (error "Cannot wrap this")))))
13608 (defun org-do-wrap (words width)
13609 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
13610 (let (lines line)
13611 (while words
13612 (setq line (pop words))
13613 (while (and words (< (+ (length line) (length (car words))) width))
13614 (setq line (concat line " " (pop words))))
13615 (setq lines (push line lines)))
13616 (nreverse lines)))
13618 (defun org-split-string (string &optional separators)
13619 "Splits STRING into substrings at SEPARATORS.
13620 No empty strings are returned if there are matches at the beginning
13621 and end of string."
13622 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
13623 (start 0)
13624 notfirst
13625 (list nil))
13626 (while (and (string-match rexp string
13627 (if (and notfirst
13628 (= start (match-beginning 0))
13629 (< start (length string)))
13630 (1+ start) start))
13631 (< (match-beginning 0) (length string)))
13632 (setq notfirst t)
13633 (or (eq (match-beginning 0) 0)
13634 (and (eq (match-beginning 0) (match-end 0))
13635 (eq (match-beginning 0) start))
13636 (setq list
13637 (cons (substring string start (match-beginning 0))
13638 list)))
13639 (setq start (match-end 0)))
13640 (or (eq start (length string))
13641 (setq list
13642 (cons (substring string start)
13643 list)))
13644 (nreverse list)))
13646 (defun org-context ()
13647 "Return a list of contexts of the current cursor position.
13648 If several contexts apply, all are returned.
13649 Each context entry is a list with a symbol naming the context, and
13650 two positions indicating start and end of the context. Possible
13651 contexts are:
13653 :headline anywhere in a headline
13654 :headline-stars on the leading stars in a headline
13655 :todo-keyword on a TODO keyword (including DONE) in a headline
13656 :tags on the TAGS in a headline
13657 :priority on the priority cookie in a headline
13658 :item on the first line of a plain list item
13659 :item-bullet on the bullet/number of a plain list item
13660 :checkbox on the checkbox in a plain list item
13661 :table in an org-mode table
13662 :table-special on a special filed in a table
13663 :table-table in a table.el table
13664 :link on a hyperlink
13665 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
13666 :target on a <<target>>
13667 :radio-target on a <<<radio-target>>>
13668 :latex-fragment on a LaTeX fragment
13669 :latex-preview on a LaTeX fragment with overlayed preview image
13671 This function expects the position to be visible because it uses font-lock
13672 faces as a help to recognize the following contexts: :table-special, :link,
13673 and :keyword."
13674 (let* ((f (get-text-property (point) 'face))
13675 (faces (if (listp f) f (list f)))
13676 (p (point)) clist o)
13677 ;; First the large context
13678 (cond
13679 ((org-on-heading-p t)
13680 (push (list :headline (point-at-bol) (point-at-eol)) clist)
13681 (when (progn
13682 (beginning-of-line 1)
13683 (looking-at org-todo-line-tags-regexp))
13684 (push (org-point-in-group p 1 :headline-stars) clist)
13685 (push (org-point-in-group p 2 :todo-keyword) clist)
13686 (push (org-point-in-group p 4 :tags) clist))
13687 (goto-char p)
13688 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
13689 (if (looking-at "\\[#[A-Z0-9]\\]")
13690 (push (org-point-in-group p 0 :priority) clist)))
13692 ((org-at-item-p)
13693 (push (org-point-in-group p 2 :item-bullet) clist)
13694 (push (list :item (point-at-bol)
13695 (save-excursion (org-end-of-item) (point)))
13696 clist)
13697 (and (org-at-item-checkbox-p)
13698 (push (org-point-in-group p 0 :checkbox) clist)))
13700 ((org-at-table-p)
13701 (push (list :table (org-table-begin) (org-table-end)) clist)
13702 (if (memq 'org-formula faces)
13703 (push (list :table-special
13704 (previous-single-property-change p 'face)
13705 (next-single-property-change p 'face)) clist)))
13706 ((org-at-table-p 'any)
13707 (push (list :table-table) clist)))
13708 (goto-char p)
13710 ;; Now the small context
13711 (cond
13712 ((org-at-timestamp-p)
13713 (push (org-point-in-group p 0 :timestamp) clist))
13714 ((memq 'org-link faces)
13715 (push (list :link
13716 (previous-single-property-change p 'face)
13717 (next-single-property-change p 'face)) clist))
13718 ((memq 'org-special-keyword faces)
13719 (push (list :keyword
13720 (previous-single-property-change p 'face)
13721 (next-single-property-change p 'face)) clist))
13722 ((org-on-target-p)
13723 (push (org-point-in-group p 0 :target) clist)
13724 (goto-char (1- (match-beginning 0)))
13725 (if (looking-at org-radio-target-regexp)
13726 (push (org-point-in-group p 0 :radio-target) clist))
13727 (goto-char p))
13728 ((setq o (car (delq nil
13729 (mapcar
13730 (lambda (x)
13731 (if (memq x org-latex-fragment-image-overlays) x))
13732 (org-overlays-at (point))))))
13733 (push (list :latex-fragment
13734 (org-overlay-start o) (org-overlay-end o)) clist)
13735 (push (list :latex-preview
13736 (org-overlay-start o) (org-overlay-end o)) clist))
13737 ((org-inside-LaTeX-fragment-p)
13738 ;; FIXME: positions wrong.
13739 (push (list :latex-fragment (point) (point)) clist)))
13741 (setq clist (nreverse (delq nil clist)))
13742 clist))
13744 ;; FIXME: Compare with at-regexp-p Do we need both?
13745 (defun org-in-regexp (re &optional nlines visually)
13746 "Check if point is inside a match of regexp.
13747 Normally only the current line is checked, but you can include NLINES extra
13748 lines both before and after point into the search.
13749 If VISUALLY is set, require that the cursor is not after the match but
13750 really on, so that the block visually is on the match."
13751 (catch 'exit
13752 (let ((pos (point))
13753 (eol (point-at-eol (+ 1 (or nlines 0))))
13754 (inc (if visually 1 0)))
13755 (save-excursion
13756 (beginning-of-line (- 1 (or nlines 0)))
13757 (while (re-search-forward re eol t)
13758 (if (and (<= (match-beginning 0) pos)
13759 (>= (+ inc (match-end 0)) pos))
13760 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
13762 (defun org-at-regexp-p (regexp)
13763 "Is point inside a match of REGEXP in the current line?"
13764 (catch 'exit
13765 (save-excursion
13766 (let ((pos (point)) (end (point-at-eol)))
13767 (beginning-of-line 1)
13768 (while (re-search-forward regexp end t)
13769 (if (and (<= (match-beginning 0) pos)
13770 (>= (match-end 0) pos))
13771 (throw 'exit t)))
13772 nil))))
13774 (defun org-occur-in-agenda-files (regexp &optional nlines)
13775 "Call `multi-occur' with buffers for all agenda files."
13776 (interactive "sOrg-files matching: \np")
13777 (let* ((files (org-agenda-files))
13778 (tnames (mapcar 'file-truename files))
13779 (extra org-agenda-text-search-extra-files)
13781 (when (eq (car extra) 'agenda-archives)
13782 (setq extra (cdr extra))
13783 (setq files (org-add-archive-files files)))
13784 (while (setq f (pop extra))
13785 (unless (member (file-truename f) tnames)
13786 (add-to-list 'files f 'append)
13787 (add-to-list 'tnames (file-truename f) 'append)))
13788 (multi-occur
13789 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
13790 regexp)))
13792 (if (boundp 'occur-mode-find-occurrence-hook)
13793 ;; Emacs 23
13794 (add-hook 'occur-mode-find-occurrence-hook
13795 (lambda ()
13796 (when (org-mode-p)
13797 (org-reveal))))
13798 ;; Emacs 22
13799 (defadvice occur-mode-goto-occurrence
13800 (after org-occur-reveal activate)
13801 (and (org-mode-p) (org-reveal)))
13802 (defadvice occur-mode-goto-occurrence-other-window
13803 (after org-occur-reveal activate)
13804 (and (org-mode-p) (org-reveal)))
13805 (defadvice occur-mode-display-occurrence
13806 (after org-occur-reveal activate)
13807 (when (org-mode-p)
13808 (let ((pos (occur-mode-find-occurrence)))
13809 (with-current-buffer (marker-buffer pos)
13810 (save-excursion
13811 (goto-char pos)
13812 (org-reveal)))))))
13814 (defun org-uniquify (list)
13815 "Remove duplicate elements from LIST."
13816 (let (res)
13817 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
13818 res))
13820 (defun org-delete-all (elts list)
13821 "Remove all elements in ELTS from LIST."
13822 (while elts
13823 (setq list (delete (pop elts) list)))
13824 list)
13826 (defun org-back-over-empty-lines ()
13827 "Move backwards over witespace, to the beginning of the first empty line.
13828 Returns the number of empty lines passed."
13829 (let ((pos (point)))
13830 (skip-chars-backward " \t\n\r")
13831 (beginning-of-line 2)
13832 (goto-char (min (point) pos))
13833 (count-lines (point) pos)))
13835 (defun org-skip-whitespace ()
13836 (skip-chars-forward " \t\n\r"))
13838 (defun org-point-in-group (point group &optional context)
13839 "Check if POINT is in match-group GROUP.
13840 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
13841 match. If the match group does ot exist or point is not inside it,
13842 return nil."
13843 (and (match-beginning group)
13844 (>= point (match-beginning group))
13845 (<= point (match-end group))
13846 (if context
13847 (list context (match-beginning group) (match-end group))
13848 t)))
13850 (defun org-switch-to-buffer-other-window (&rest args)
13851 "Switch to buffer in a second window on the current frame.
13852 In particular, do not allow pop-up frames."
13853 (let (pop-up-frames special-display-buffer-names special-display-regexps
13854 special-display-function)
13855 (apply 'switch-to-buffer-other-window args)))
13857 (defun org-combine-plists (&rest plists)
13858 "Create a single property list from all plists in PLISTS.
13859 The process starts by copying the first list, and then setting properties
13860 from the other lists. Settings in the last list are the most significant
13861 ones and overrule settings in the other lists."
13862 (let ((rtn (copy-sequence (pop plists)))
13863 p v ls)
13864 (while plists
13865 (setq ls (pop plists))
13866 (while ls
13867 (setq p (pop ls) v (pop ls))
13868 (setq rtn (plist-put rtn p v))))
13869 rtn))
13871 (defun org-move-line-down (arg)
13872 "Move the current line down. With prefix argument, move it past ARG lines."
13873 (interactive "p")
13874 (let ((col (current-column))
13875 beg end pos)
13876 (beginning-of-line 1) (setq beg (point))
13877 (beginning-of-line 2) (setq end (point))
13878 (beginning-of-line (+ 1 arg))
13879 (setq pos (move-marker (make-marker) (point)))
13880 (insert (delete-and-extract-region beg end))
13881 (goto-char pos)
13882 (org-move-to-column col)))
13884 (defun org-move-line-up (arg)
13885 "Move the current line up. With prefix argument, move it past ARG lines."
13886 (interactive "p")
13887 (let ((col (current-column))
13888 beg end pos)
13889 (beginning-of-line 1) (setq beg (point))
13890 (beginning-of-line 2) (setq end (point))
13891 (beginning-of-line (- arg))
13892 (setq pos (move-marker (make-marker) (point)))
13893 (insert (delete-and-extract-region beg end))
13894 (goto-char pos)
13895 (org-move-to-column col)))
13897 (defun org-replace-escapes (string table)
13898 "Replace %-escapes in STRING with values in TABLE.
13899 TABLE is an association list with keys like \"%a\" and string values.
13900 The sequences in STRING may contain normal field width and padding information,
13901 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13902 so values can contain further %-escapes if they are define later in TABLE."
13903 (let ((case-fold-search nil)
13904 e re rpl)
13905 (while (setq e (pop table))
13906 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13907 (while (string-match re string)
13908 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13909 (cdr e)))
13910 (setq string (replace-match rpl t t string))))
13911 string))
13914 (defun org-sublist (list start end)
13915 "Return a section of LIST, from START to END.
13916 Counting starts at 1."
13917 (let (rtn (c start))
13918 (setq list (nthcdr (1- start) list))
13919 (while (and list (<= c end))
13920 (push (pop list) rtn)
13921 (setq c (1+ c)))
13922 (nreverse rtn)))
13924 (defun org-find-base-buffer-visiting (file)
13925 "Like `find-buffer-visiting' but alway return the base buffer and
13926 not an indirect buffer."
13927 (let ((buf (find-buffer-visiting file)))
13928 (if buf
13929 (or (buffer-base-buffer buf) buf)
13930 nil)))
13932 (defun org-image-file-name-regexp ()
13933 "Return regexp matching the file names of images."
13934 (if (fboundp 'image-file-name-regexp)
13935 (image-file-name-regexp)
13936 (let ((image-file-name-extensions
13937 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13938 "xbm" "xpm" "pbm" "pgm" "ppm")))
13939 (concat "\\."
13940 (regexp-opt (nconc (mapcar 'upcase
13941 image-file-name-extensions)
13942 image-file-name-extensions)
13944 "\\'"))))
13946 (defun org-file-image-p (file)
13947 "Return non-nil if FILE is an image."
13948 (save-match-data
13949 (string-match (org-image-file-name-regexp) file)))
13951 (defun org-get-cursor-date ()
13952 "Return the date at cursor in as a time.
13953 This works in the calendar and in the agenda, anywhere else it just
13954 returns the current time."
13955 (let (date day defd)
13956 (cond
13957 ((eq major-mode 'calendar-mode)
13958 (setq date (calendar-cursor-to-date)
13959 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
13960 ((eq major-mode 'org-agenda-mode)
13961 (setq day (get-text-property (point) 'day))
13962 (if day
13963 (setq date (calendar-gregorian-from-absolute day)
13964 defd (encode-time 0 0 0 (nth 1 date) (nth 0 date)
13965 (nth 2 date))))))
13966 (or defd (current-time))))
13968 (defvar org-agenda-action-marker (make-marker)
13969 "Marker pointing to the entry for the next agenda action.")
13971 (defun org-mark-entry-for-agenda-action ()
13972 "Mark the current entry as target of an agenda action.
13973 Agenda actions are actions executed from the agenda with the key `k',
13974 which make use of the date at the cursor."
13975 (interactive)
13976 (move-marker org-agenda-action-marker
13977 (save-excursion (org-back-to-heading t) (point))
13978 (current-buffer))
13979 (message
13980 "Entry marked for action; press `k' at desired date in agenda or calendar"))
13982 ;;; Paragraph filling stuff.
13983 ;; We want this to be just right, so use the full arsenal.
13985 (defun org-indent-line-function ()
13986 "Indent line like previous, but further if previous was headline or item."
13987 (interactive)
13988 (let* ((pos (point))
13989 (itemp (org-at-item-p))
13990 column bpos bcol tpos tcol bullet btype bullet-type)
13991 ;; Find the previous relevant line
13992 (beginning-of-line 1)
13993 (cond
13994 ((looking-at "#") (setq column 0))
13995 ((looking-at "\\*+ ") (setq column 0))
13997 (beginning-of-line 0)
13998 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13999 (beginning-of-line 0))
14000 (cond
14001 ((looking-at "\\*+[ \t]+")
14002 (if (not org-adapt-indentation)
14003 (setq column 0)
14004 (goto-char (match-end 0))
14005 (setq column (current-column))))
14006 ((org-in-item-p)
14007 (org-beginning-of-item)
14008 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14009 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\|.*? :: \\)?")
14010 (setq bpos (match-beginning 1) tpos (match-end 0)
14011 bcol (progn (goto-char bpos) (current-column))
14012 tcol (progn (goto-char tpos) (current-column))
14013 bullet (match-string 1)
14014 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
14015 (if (> tcol (+ bcol org-description-max-indent))
14016 (setq tcol (+ bcol 5)))
14017 (if (not itemp)
14018 (setq column tcol)
14019 (goto-char pos)
14020 (beginning-of-line 1)
14021 (if (looking-at "\\S-")
14022 (progn
14023 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
14024 (setq bullet (match-string 1)
14025 btype (if (string-match "[0-9]" bullet) "n" bullet))
14026 (setq column (if (equal btype bullet-type) bcol tcol)))
14027 (setq column (org-get-indentation)))))
14028 (t (setq column (org-get-indentation))))))
14029 (goto-char pos)
14030 (if (<= (current-column) (current-indentation))
14031 (org-indent-line-to column)
14032 (save-excursion (org-indent-line-to column)))
14033 (setq column (current-column))
14034 (beginning-of-line 1)
14035 (if (looking-at
14036 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
14037 (replace-match (concat "\\1" (format org-property-format
14038 (match-string 2) (match-string 3)))
14039 t nil))
14040 (org-move-to-column column)))
14042 (defun org-set-autofill-regexps ()
14043 (interactive)
14044 ;; In the paragraph separator we include headlines, because filling
14045 ;; text in a line directly attached to a headline would otherwise
14046 ;; fill the headline as well.
14047 (org-set-local 'comment-start-skip "^#+[ \t]*")
14048 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
14049 ;; The paragraph starter includes hand-formatted lists.
14050 (org-set-local 'paragraph-start
14051 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
14052 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
14053 ;; But only if the user has not turned off tables or fixed-width regions
14054 (org-set-local
14055 'auto-fill-inhibit-regexp
14056 (concat "\\*+ \\|#\\+"
14057 "\\|[ \t]*" org-keyword-time-regexp
14058 (if (or org-enable-table-editor org-enable-fixed-width-editor)
14059 (concat
14060 "\\|[ \t]*["
14061 (if org-enable-table-editor "|" "")
14062 (if org-enable-fixed-width-editor ":" "")
14063 "]"))))
14064 ;; We use our own fill-paragraph function, to make sure that tables
14065 ;; and fixed-width regions are not wrapped. That function will pass
14066 ;; through to `fill-paragraph' when appropriate.
14067 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
14068 ; Adaptive filling: To get full control, first make sure that
14069 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
14070 (org-set-local 'adaptive-fill-regexp "\000")
14071 (org-set-local 'adaptive-fill-function
14072 'org-adaptive-fill-function)
14073 (org-set-local
14074 'align-mode-rules-list
14075 '((org-in-buffer-settings
14076 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
14077 (modes . '(org-mode))))))
14079 (defun org-fill-paragraph (&optional justify)
14080 "Re-align a table, pass through to fill-paragraph if no table."
14081 (let ((table-p (org-at-table-p))
14082 (table.el-p (org-at-table.el-p)))
14083 (cond ((and (equal (char-after (point-at-bol)) ?*)
14084 (save-excursion (goto-char (point-at-bol))
14085 (looking-at outline-regexp)))
14086 t) ; skip headlines
14087 (table.el-p t) ; skip table.el tables
14088 (table-p (org-table-align) t) ; align org-mode tables
14089 (t nil)))) ; call paragraph-fill
14091 ;; For reference, this is the default value of adaptive-fill-regexp
14092 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
14094 (defun org-adaptive-fill-function ()
14095 "Return a fill prefix for org-mode files.
14096 In particular, this makes sure hanging paragraphs for hand-formatted lists
14097 work correctly."
14098 (cond ((looking-at "#[ \t]+")
14099 (match-string 0))
14100 ((looking-at "[ \t]*\\([-*+] .*? :: \\)")
14101 (save-excursion
14102 (if (> (match-end 1) (+ (match-beginning 1)
14103 org-description-max-indent))
14104 (goto-char (+ (match-beginning 1) 5))
14105 (goto-char (match-end 0)))
14106 (make-string (current-column) ?\ )))
14107 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
14108 (save-excursion
14109 (goto-char (match-end 0))
14110 (make-string (current-column) ?\ )))
14111 (t nil)))
14113 ;;; Other stuff.
14115 (defun org-toggle-fixed-width-section (arg)
14116 "Toggle the fixed-width export.
14117 If there is no active region, the QUOTE keyword at the current headline is
14118 inserted or removed. When present, it causes the text between this headline
14119 and the next to be exported as fixed-width text, and unmodified.
14120 If there is an active region, this command adds or removes a colon as the
14121 first character of this line. If the first character of a line is a colon,
14122 this line is also exported in fixed-width font."
14123 (interactive "P")
14124 (let* ((cc 0)
14125 (regionp (org-region-active-p))
14126 (beg (if regionp (region-beginning) (point)))
14127 (end (if regionp (region-end)))
14128 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
14129 (case-fold-search nil)
14130 (re "[ \t]*\\(:\\)")
14131 off)
14132 (if regionp
14133 (save-excursion
14134 (goto-char beg)
14135 (setq cc (current-column))
14136 (beginning-of-line 1)
14137 (setq off (looking-at re))
14138 (while (> nlines 0)
14139 (setq nlines (1- nlines))
14140 (beginning-of-line 1)
14141 (cond
14142 (arg
14143 (org-move-to-column cc t)
14144 (insert ":\n")
14145 (forward-line -1))
14146 ((and off (looking-at re))
14147 (replace-match "" t t nil 1))
14148 ((not off) (org-move-to-column cc t) (insert ":")))
14149 (forward-line 1)))
14150 (save-excursion
14151 (org-back-to-heading)
14152 (if (looking-at (concat outline-regexp
14153 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
14154 (replace-match "" t t nil 1)
14155 (if (looking-at outline-regexp)
14156 (progn
14157 (goto-char (match-end 0))
14158 (insert org-quote-string " "))))))))
14160 ;;;; Functions extending outline functionality
14162 (defun org-beginning-of-line (&optional arg)
14163 "Go to the beginning of the current line. If that is invisible, continue
14164 to a visible line beginning. This makes the function of C-a more intuitive.
14165 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14166 first attempt, and only move to after the tags when the cursor is already
14167 beyond the end of the headline."
14168 (interactive "P")
14169 (let ((pos (point)) refpos)
14170 (beginning-of-line 1)
14171 (if (bobp)
14173 (backward-char 1)
14174 (if (org-invisible-p)
14175 (while (and (not (bobp)) (org-invisible-p))
14176 (backward-char 1)
14177 (beginning-of-line 1))
14178 (forward-char 1)))
14179 (when org-special-ctrl-a/e
14180 (cond
14181 ((and (looking-at org-complex-heading-regexp)
14182 (= (char-after (match-end 1)) ?\ ))
14183 (setq refpos (min (1+ (or (match-end 3) (match-end 2) (match-end 1)))
14184 (point-at-eol)))
14185 (goto-char
14186 (if (eq org-special-ctrl-a/e t)
14187 (cond ((> pos refpos) refpos)
14188 ((= pos (point)) refpos)
14189 (t (point)))
14190 (cond ((> pos (point)) (point))
14191 ((not (eq last-command this-command)) (point))
14192 (t refpos)))))
14193 ((org-at-item-p)
14194 (goto-char
14195 (if (eq org-special-ctrl-a/e t)
14196 (cond ((> pos (match-end 4)) (match-end 4))
14197 ((= pos (point)) (match-end 4))
14198 (t (point)))
14199 (cond ((> pos (point)) (point))
14200 ((not (eq last-command this-command)) (point))
14201 (t (match-end 4))))))))
14202 (org-no-warnings
14203 (and (featurep 'xemacs) (setq zmacs-region-stays t)))))
14205 (defun org-end-of-line (&optional arg)
14206 "Go to the end of the line.
14207 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
14208 first attempt, and only move to after the tags when the cursor is already
14209 beyond the end of the headline."
14210 (interactive "P")
14211 (if (or (not org-special-ctrl-a/e)
14212 (not (org-on-heading-p)))
14213 (end-of-line arg)
14214 (let ((pos (point)))
14215 (beginning-of-line 1)
14216 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
14217 (if (eq org-special-ctrl-a/e t)
14218 (if (or (< pos (match-beginning 1))
14219 (= pos (match-end 0)))
14220 (goto-char (match-beginning 1))
14221 (goto-char (match-end 0)))
14222 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
14223 (goto-char (match-end 0))
14224 (goto-char (match-beginning 1))))
14225 (end-of-line arg))))
14226 (org-no-warnings
14227 (and (featurep 'xemacs) (setq zmacs-region-stays t))))
14230 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
14231 (define-key org-mode-map "\C-e" 'org-end-of-line)
14233 (defun org-kill-line (&optional arg)
14234 "Kill line, to tags or end of line."
14235 (interactive "P")
14236 (cond
14237 ((or (not org-special-ctrl-k)
14238 (bolp)
14239 (not (org-on-heading-p)))
14240 (call-interactively 'kill-line))
14241 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
14242 (kill-region (point) (match-beginning 1))
14243 (org-set-tags nil t))
14244 (t (kill-region (point) (point-at-eol)))))
14246 (define-key org-mode-map "\C-k" 'org-kill-line)
14248 (defun org-invisible-p ()
14249 "Check if point is at a character currently not visible."
14250 ;; Early versions of noutline don't have `outline-invisible-p'.
14251 (if (fboundp 'outline-invisible-p)
14252 (outline-invisible-p)
14253 (get-char-property (point) 'invisible)))
14255 (defun org-invisible-p2 ()
14256 "Check if point is at a character currently not visible."
14257 (save-excursion
14258 (if (and (eolp) (not (bobp))) (backward-char 1))
14259 ;; Early versions of noutline don't have `outline-invisible-p'.
14260 (if (fboundp 'outline-invisible-p)
14261 (outline-invisible-p)
14262 (get-char-property (point) 'invisible))))
14264 (defalias 'org-back-to-heading 'outline-back-to-heading)
14265 (defalias 'org-on-heading-p 'outline-on-heading-p)
14266 (defalias 'org-at-heading-p 'outline-on-heading-p)
14267 (defun org-at-heading-or-item-p ()
14268 (or (org-on-heading-p) (org-at-item-p)))
14270 (defun org-on-target-p ()
14271 (or (org-in-regexp org-radio-target-regexp)
14272 (org-in-regexp org-target-regexp)))
14274 (defun org-up-heading-all (arg)
14275 "Move to the heading line of which the present line is a subheading.
14276 This function considers both visible and invisible heading lines.
14277 With argument, move up ARG levels."
14278 (if (fboundp 'outline-up-heading-all)
14279 (outline-up-heading-all arg) ; emacs 21 version of outline.el
14280 (outline-up-heading arg t))) ; emacs 22 version of outline.el
14282 (defun org-up-heading-safe ()
14283 "Move to the heading line of which the present line is a subheading.
14284 This version will not throw an error. It will return the level of the
14285 headline found, or nil if no higher level is found."
14286 (let ((pos (point)) start-level level
14287 (re (concat "^" outline-regexp)))
14288 (catch 'exit
14289 (outline-back-to-heading t)
14290 (setq start-level (funcall outline-level))
14291 (if (equal start-level 1) (throw 'exit nil))
14292 (while (re-search-backward re nil t)
14293 (setq level (funcall outline-level))
14294 (if (< level start-level) (throw 'exit level)))
14295 nil)))
14297 (defun org-first-sibling-p ()
14298 "Is this heading the first child of its parents?"
14299 (interactive)
14300 (let ((re (concat "^" outline-regexp))
14301 level l)
14302 (unless (org-at-heading-p t)
14303 (error "Not at a heading"))
14304 (setq level (funcall outline-level))
14305 (save-excursion
14306 (if (not (re-search-backward re nil t))
14308 (setq l (funcall outline-level))
14309 (< l level)))))
14311 (defun org-goto-sibling (&optional previous)
14312 "Goto the next sibling, even if it is invisible.
14313 When PREVIOUS is set, go to the previous sibling instead. Returns t
14314 when a sibling was found. When none is found, return nil and don't
14315 move point."
14316 (let ((fun (if previous 're-search-backward 're-search-forward))
14317 (pos (point))
14318 (re (concat "^" outline-regexp))
14319 level l)
14320 (when (condition-case nil (org-back-to-heading t) (error nil))
14321 (setq level (funcall outline-level))
14322 (catch 'exit
14323 (or previous (forward-char 1))
14324 (while (funcall fun re nil t)
14325 (setq l (funcall outline-level))
14326 (when (< l level) (goto-char pos) (throw 'exit nil))
14327 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
14328 (goto-char pos)
14329 nil))))
14331 (defun org-show-siblings ()
14332 "Show all siblings of the current headline."
14333 (save-excursion
14334 (while (org-goto-sibling) (org-flag-heading nil)))
14335 (save-excursion
14336 (while (org-goto-sibling 'previous)
14337 (org-flag-heading nil))))
14339 (defun org-show-hidden-entry ()
14340 "Show an entry where even the heading is hidden."
14341 (save-excursion
14342 (org-show-entry)))
14344 (defun org-flag-heading (flag &optional entry)
14345 "Flag the current heading. FLAG non-nil means make invisible.
14346 When ENTRY is non-nil, show the entire entry."
14347 (save-excursion
14348 (org-back-to-heading t)
14349 ;; Check if we should show the entire entry
14350 (if entry
14351 (progn
14352 (org-show-entry)
14353 (save-excursion
14354 (and (outline-next-heading)
14355 (org-flag-heading nil))))
14356 (outline-flag-region (max (point-min) (1- (point)))
14357 (save-excursion (outline-end-of-heading) (point))
14358 flag))))
14360 (defun org-end-of-subtree (&optional invisible-OK to-heading)
14361 ;; This is an exact copy of the original function, but it uses
14362 ;; `org-back-to-heading', to make it work also in invisible
14363 ;; trees. And is uses an invisible-OK argument.
14364 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
14365 (org-back-to-heading invisible-OK)
14366 (let ((first t)
14367 (level (funcall outline-level)))
14368 (while (and (not (eobp))
14369 (or first (> (funcall outline-level) level)))
14370 (setq first nil)
14371 (outline-next-heading))
14372 (unless to-heading
14373 (if (memq (preceding-char) '(?\n ?\^M))
14374 (progn
14375 ;; Go to end of line before heading
14376 (forward-char -1)
14377 (if (memq (preceding-char) '(?\n ?\^M))
14378 ;; leave blank line before heading
14379 (forward-char -1))))))
14380 (point))
14382 (defun org-show-subtree ()
14383 "Show everything after this heading at deeper levels."
14384 (outline-flag-region
14385 (point)
14386 (save-excursion
14387 (outline-end-of-subtree) (outline-next-heading) (point))
14388 nil))
14390 (defun org-show-entry ()
14391 "Show the body directly following this heading.
14392 Show the heading too, if it is currently invisible."
14393 (interactive)
14394 (save-excursion
14395 (condition-case nil
14396 (progn
14397 (org-back-to-heading t)
14398 (outline-flag-region
14399 (max (point-min) (1- (point)))
14400 (save-excursion
14401 (re-search-forward
14402 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
14403 (or (match-beginning 1) (point-max)))
14404 nil))
14405 (error nil))))
14407 (defun org-make-options-regexp (kwds)
14408 "Make a regular expression for keyword lines."
14409 (concat
14411 "#?[ \t]*\\+\\("
14412 (mapconcat 'regexp-quote kwds "\\|")
14413 "\\):[ \t]*"
14414 "\\(.+\\)"))
14416 ;; Make isearch reveal the necessary context
14417 (defun org-isearch-end ()
14418 "Reveal context after isearch exits."
14419 (when isearch-success ; only if search was successful
14420 (if (featurep 'xemacs)
14421 ;; Under XEmacs, the hook is run in the correct place,
14422 ;; we directly show the context.
14423 (org-show-context 'isearch)
14424 ;; In Emacs the hook runs *before* restoring the overlays.
14425 ;; So we have to use a one-time post-command-hook to do this.
14426 ;; (Emacs 22 has a special variable, see function `org-mode')
14427 (unless (and (boundp 'isearch-mode-end-hook-quit)
14428 isearch-mode-end-hook-quit)
14429 ;; Only when the isearch was not quitted.
14430 (org-add-hook 'post-command-hook 'org-isearch-post-command
14431 'append 'local)))))
14433 (defun org-isearch-post-command ()
14434 "Remove self from hook, and show context."
14435 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
14436 (org-show-context 'isearch))
14439 ;;;; Integration with and fixes for other packages
14441 ;;; Imenu support
14443 (defvar org-imenu-markers nil
14444 "All markers currently used by Imenu.")
14445 (make-variable-buffer-local 'org-imenu-markers)
14447 (defun org-imenu-new-marker (&optional pos)
14448 "Return a new marker for use by Imenu, and remember the marker."
14449 (let ((m (make-marker)))
14450 (move-marker m (or pos (point)))
14451 (push m org-imenu-markers)
14454 (defun org-imenu-get-tree ()
14455 "Produce the index for Imenu."
14456 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
14457 (setq org-imenu-markers nil)
14458 (let* ((n org-imenu-depth)
14459 (re (concat "^" outline-regexp))
14460 (subs (make-vector (1+ n) nil))
14461 (last-level 0)
14462 m tree level head)
14463 (save-excursion
14464 (save-restriction
14465 (widen)
14466 (goto-char (point-max))
14467 (while (re-search-backward re nil t)
14468 (setq level (org-reduced-level (funcall outline-level)))
14469 (when (<= level n)
14470 (looking-at org-complex-heading-regexp)
14471 (setq head (org-match-string-no-properties 4)
14472 m (org-imenu-new-marker))
14473 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
14474 (if (>= level last-level)
14475 (push (cons head m) (aref subs level))
14476 (push (cons head (aref subs (1+ level))) (aref subs level))
14477 (loop for i from (1+ level) to n do (aset subs i nil)))
14478 (setq last-level level)))))
14479 (aref subs 1)))
14481 (eval-after-load "imenu"
14482 '(progn
14483 (add-hook 'imenu-after-jump-hook
14484 (lambda ()
14485 (if (eq major-mode 'org-mode)
14486 (org-show-context 'org-goto))))))
14488 ;; Speedbar support
14490 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
14491 "Overlay marking the agenda restriction line in speedbar.")
14492 (org-overlay-put org-speedbar-restriction-lock-overlay
14493 'face 'org-agenda-restriction-lock)
14494 (org-overlay-put org-speedbar-restriction-lock-overlay
14495 'help-echo "Agendas are currently limited to this item.")
14496 (org-detach-overlay org-speedbar-restriction-lock-overlay)
14498 (defun org-speedbar-set-agenda-restriction ()
14499 "Restrict future agenda commands to the location at point in speedbar.
14500 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
14501 (interactive)
14502 (require 'org-agenda)
14503 (let (p m tp np dir txt w)
14504 (cond
14505 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14506 'org-imenu t))
14507 (setq m (get-text-property p 'org-imenu-marker))
14508 (save-excursion
14509 (save-restriction
14510 (set-buffer (marker-buffer m))
14511 (goto-char m)
14512 (org-agenda-set-restriction-lock 'subtree))))
14513 ((setq p (text-property-any (point-at-bol) (point-at-eol)
14514 'speedbar-function 'speedbar-find-file))
14515 (setq tp (previous-single-property-change
14516 (1+ p) 'speedbar-function)
14517 np (next-single-property-change
14518 tp 'speedbar-function)
14519 dir (speedbar-line-directory)
14520 txt (buffer-substring-no-properties (or tp (point-min))
14521 (or np (point-max))))
14522 (save-excursion
14523 (save-restriction
14524 (set-buffer (find-file-noselect
14525 (let ((default-directory dir))
14526 (expand-file-name txt))))
14527 (unless (org-mode-p)
14528 (error "Cannot restrict to non-Org-mode file"))
14529 (org-agenda-set-restriction-lock 'file))))
14530 (t (error "Don't know how to restrict Org-mode's agenda")))
14531 (org-move-overlay org-speedbar-restriction-lock-overlay
14532 (point-at-bol) (point-at-eol))
14533 (setq current-prefix-arg nil)
14534 (org-agenda-maybe-redo)))
14536 (eval-after-load "speedbar"
14537 '(progn
14538 (speedbar-add-supported-extension ".org")
14539 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
14540 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
14541 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
14542 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
14543 (add-hook 'speedbar-visiting-tag-hook
14544 (lambda () (org-show-context 'org-goto)))))
14547 ;;; Fixes and Hacks for problems with other packages
14549 ;; Make flyspell not check words in links, to not mess up our keymap
14550 (defun org-mode-flyspell-verify ()
14551 "Don't let flyspell put overlays at active buttons."
14552 (not (get-text-property (point) 'keymap)))
14554 ;; Make `bookmark-jump' show the jump location if it was hidden.
14555 (eval-after-load "bookmark"
14556 '(if (boundp 'bookmark-after-jump-hook)
14557 ;; We can use the hook
14558 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
14559 ;; Hook not available, use advice
14560 (defadvice bookmark-jump (after org-make-visible activate)
14561 "Make the position visible."
14562 (org-bookmark-jump-unhide))))
14564 (defun org-bookmark-jump-unhide ()
14565 "Unhide the current position, to show the bookmark location."
14566 (and (org-mode-p)
14567 (or (org-invisible-p)
14568 (save-excursion (goto-char (max (point-min) (1- (point))))
14569 (org-invisible-p)))
14570 (org-show-context 'bookmark-jump)))
14572 ;; Make session.el ignore our circular variable
14573 (eval-after-load "session"
14574 '(add-to-list 'session-globals-exclude 'org-mark-ring))
14576 ;;;; Experimental code
14578 (defun org-closed-in-range ()
14579 "Sparse tree of items closed in a certain time range.
14580 Still experimental, may disappear in the future."
14581 (interactive)
14582 ;; Get the time interval from the user.
14583 (let* ((time1 (time-to-seconds
14584 (org-read-date nil 'to-time nil "Starting date: ")))
14585 (time2 (time-to-seconds
14586 (org-read-date nil 'to-time nil "End date:")))
14587 ;; callback function
14588 (callback (lambda ()
14589 (let ((time
14590 (time-to-seconds
14591 (apply 'encode-time
14592 (org-parse-time-string
14593 (match-string 1))))))
14594 ;; check if time in interval
14595 (and (>= time time1) (<= time time2))))))
14596 ;; make tree, check each match with the callback
14597 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
14600 ;;;; Finish up
14602 (provide 'org)
14604 (run-hooks 'org-load-hook)
14606 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
14608 ;;; org.el ends here