Minor fixes.
[org-mode.git] / lisp / org.el
blobaff9e07cb23c574fd0007f08e771e96f9a80938c
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.06b
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.06b"
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-align-all-tables nil
224 "Non-nil means, align all tables when visiting a file.
225 This is useful when the column width in tables is forced with <N> cookies
226 in table fields. Such tables will look correct only after the first re-align.
227 This can also be configured on a per-file basis by adding one of
228 the following lines anywhere in the buffer:
229 #+STARTUP: align
230 #+STARTUP: noalign"
231 :group 'org-startup
232 :type 'boolean)
234 (defcustom org-insert-mode-line-in-empty-file nil
235 "Non-nil means insert the first line setting Org-mode in empty files.
236 When the function `org-mode' is called interactively in an empty file, this
237 normally means that the file name does not automatically trigger Org-mode.
238 To ensure that the file will always be in Org-mode in the future, a
239 line enforcing Org-mode will be inserted into the buffer, if this option
240 has been set."
241 :group 'org-startup
242 :type 'boolean)
244 (defcustom org-replace-disputed-keys nil
245 "Non-nil means use alternative key bindings for some keys.
246 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
247 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
248 If you want to use Org-mode together with one of these other modes,
249 or more generally if you would like to move some Org-mode commands to
250 other keys, set this variable and configure the keys with the variable
251 `org-disputed-keys'.
253 This option is only relevant at load-time of Org-mode, and must be set
254 *before* org.el is loaded. Changing it requires a restart of Emacs to
255 become effective."
256 :group 'org-startup
257 :type 'boolean)
259 (if (fboundp 'defvaralias)
260 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
262 (defcustom org-disputed-keys
263 '(([(shift up)] . [(meta p)])
264 ([(shift down)] . [(meta n)])
265 ([(shift left)] . [(meta -)])
266 ([(shift right)] . [(meta +)])
267 ([(control shift right)] . [(meta shift +)])
268 ([(control shift left)] . [(meta shift -)]))
269 "Keys for which Org-mode and other modes compete.
270 This is an alist, cars are the default keys, second element specifies
271 the alternative to use when `org-replace-disputed-keys' is t.
273 Keys can be specified in any syntax supported by `define-key'.
274 The value of this option takes effect only at Org-mode's startup,
275 therefore you'll have to restart Emacs to apply it after changing."
276 :group 'org-startup
277 :type 'alist)
279 (defun org-key (key)
280 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
281 Or return the original if not disputed."
282 (if org-replace-disputed-keys
283 (let* ((nkey (key-description key))
284 (x (org-find-if (lambda (x)
285 (equal (key-description (car x)) nkey))
286 org-disputed-keys)))
287 (if x (cdr x) key))
288 key))
290 (defun org-find-if (predicate seq)
291 (catch 'exit
292 (while seq
293 (if (funcall predicate (car seq))
294 (throw 'exit (car seq))
295 (pop seq)))))
297 (defun org-defkey (keymap key def)
298 "Define a key, possibly translated, as returned by `org-key'."
299 (define-key keymap (org-key key) def))
301 (defcustom org-ellipsis nil
302 "The ellipsis to use in the Org-mode outline.
303 When nil, just use the standard three dots. When a string, use that instead,
304 When a face, use the standart 3 dots, but with the specified face.
305 The change affects only Org-mode (which will then use its own display table).
306 Changing this requires executing `M-x org-mode' in a buffer to become
307 effective."
308 :group 'org-startup
309 :type '(choice (const :tag "Default" nil)
310 (face :tag "Face" :value org-warning)
311 (string :tag "String" :value "...#")))
313 (defvar org-display-table nil
314 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
316 (defgroup org-keywords nil
317 "Keywords in Org-mode."
318 :tag "Org Keywords"
319 :group 'org)
321 (defcustom org-deadline-string "DEADLINE:"
322 "String to mark deadline entries.
323 A deadline is this string, followed by a time stamp. Should be a word,
324 terminated by a colon. You can insert a schedule keyword and
325 a timestamp with \\[org-deadline].
326 Changes become only effective after restarting Emacs."
327 :group 'org-keywords
328 :type 'string)
330 (defcustom org-scheduled-string "SCHEDULED:"
331 "String to mark scheduled TODO entries.
332 A schedule is this string, followed by a time stamp. Should be a word,
333 terminated by a colon. You can insert a schedule keyword and
334 a timestamp with \\[org-schedule].
335 Changes become only effective after restarting Emacs."
336 :group 'org-keywords
337 :type 'string)
339 (defcustom org-closed-string "CLOSED:"
340 "String used as the prefix for timestamps logging closing a TODO entry."
341 :group 'org-keywords
342 :type 'string)
344 (defcustom org-clock-string "CLOCK:"
345 "String used as prefix for timestamps clocking work hours on an item."
346 :group 'org-keywords
347 :type 'string)
349 (defcustom org-comment-string "COMMENT"
350 "Entries starting with this keyword will never be exported.
351 An entry can be toggled between COMMENT and normal with
352 \\[org-toggle-comment].
353 Changes become only effective after restarting Emacs."
354 :group 'org-keywords
355 :type 'string)
357 (defcustom org-quote-string "QUOTE"
358 "Entries starting with this keyword will be exported in fixed-width font.
359 Quoting applies only to the text in the entry following the headline, and does
360 not extend beyond the next headline, even if that is lower level.
361 An entry can be toggled between QUOTE and normal with
362 \\[org-toggle-fixed-width-section]."
363 :group 'org-keywords
364 :type 'string)
366 (defconst org-repeat-re
367 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
368 "Regular expression for specifying repeated events.
369 After a match, group 1 contains the repeat expression.")
371 (defgroup org-structure nil
372 "Options concerning the general structure of Org-mode files."
373 :tag "Org Structure"
374 :group 'org)
376 (defgroup org-reveal-location nil
377 "Options about how to make context of a location visible."
378 :tag "Org Reveal Location"
379 :group 'org-structure)
381 (defconst org-context-choice
382 '(choice
383 (const :tag "Always" t)
384 (const :tag "Never" nil)
385 (repeat :greedy t :tag "Individual contexts"
386 (cons
387 (choice :tag "Context"
388 (const agenda)
389 (const org-goto)
390 (const occur-tree)
391 (const tags-tree)
392 (const link-search)
393 (const mark-goto)
394 (const bookmark-jump)
395 (const isearch)
396 (const default))
397 (boolean))))
398 "Contexts for the reveal options.")
400 (defcustom org-show-hierarchy-above '((default . t))
401 "Non-nil means, show full hierarchy when revealing a location.
402 Org-mode often shows locations in an org-mode file which might have
403 been invisible before. When this is set, the hierarchy of headings
404 above the exposed location is shown.
405 Turning this off for example for sparse trees makes them very compact.
406 Instead of t, this can also be an alist specifying this option for different
407 contexts. Valid contexts are
408 agenda when exposing an entry from the agenda
409 org-goto when using the command `org-goto' on key C-c C-j
410 occur-tree when using the command `org-occur' on key C-c /
411 tags-tree when constructing a sparse tree based on tags matches
412 link-search when exposing search matches associated with a link
413 mark-goto when exposing the jump goal of a mark
414 bookmark-jump when exposing a bookmark location
415 isearch when exiting from an incremental search
416 default default for all contexts not set explicitly"
417 :group 'org-reveal-location
418 :type org-context-choice)
420 (defcustom org-show-following-heading '((default . nil))
421 "Non-nil means, show following heading when revealing a location.
422 Org-mode often shows locations in an org-mode file which might have
423 been invisible before. When this is set, the heading following the
424 match is shown.
425 Turning this off for example for sparse trees makes them very compact,
426 but makes it harder to edit the location of the match. In such a case,
427 use the command \\[org-reveal] to show more context.
428 Instead of t, this can also be an alist specifying this option for different
429 contexts. See `org-show-hierarchy-above' for valid contexts."
430 :group 'org-reveal-location
431 :type org-context-choice)
433 (defcustom org-show-siblings '((default . nil) (isearch t))
434 "Non-nil means, show all sibling heading when revealing a location.
435 Org-mode often shows locations in an org-mode file which might have
436 been invisible before. When this is set, the sibling of the current entry
437 heading are all made visible. If `org-show-hierarchy-above' is t,
438 the same happens on each level of the hierarchy above the current entry.
440 By default this is on for the isearch context, off for all other contexts.
441 Turning this off for example for sparse trees makes them very compact,
442 but makes it harder to edit the location of the match. In such a case,
443 use the command \\[org-reveal] to show more context.
444 Instead of t, this can also be an alist specifying this option for different
445 contexts. See `org-show-hierarchy-above' for valid contexts."
446 :group 'org-reveal-location
447 :type org-context-choice)
449 (defcustom org-show-entry-below '((default . nil))
450 "Non-nil means, show the entry below a headline when revealing a location.
451 Org-mode often shows locations in an org-mode file which might have
452 been invisible before. When this is set, the text below the headline that is
453 exposed is also shown.
455 By default this is off for all contexts.
456 Instead of t, this can also be an alist specifying this option for different
457 contexts. See `org-show-hierarchy-above' for valid contexts."
458 :group 'org-reveal-location
459 :type org-context-choice)
461 (defcustom org-indirect-buffer-display 'other-window
462 "How should indirect tree buffers be displayed?
463 This applies to indirect buffers created with the commands
464 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
465 Valid values are:
466 current-window Display in the current window
467 other-window Just display in another window.
468 dedicated-frame Create one new frame, and re-use it each time.
469 new-frame Make a new frame each time. Note that in this case
470 previously-made indirect buffers are kept, and you need to
471 kill these buffers yourself."
472 :group 'org-structure
473 :group 'org-agenda-windows
474 :type '(choice
475 (const :tag "In current window" current-window)
476 (const :tag "In current frame, other window" other-window)
477 (const :tag "Each time a new frame" new-frame)
478 (const :tag "One dedicated frame" dedicated-frame)))
480 (defgroup org-cycle nil
481 "Options concerning visibility cycling in Org-mode."
482 :tag "Org Cycle"
483 :group 'org-structure)
485 (defcustom org-drawers '("PROPERTIES" "CLOCK")
486 "Names of drawers. Drawers are not opened by cycling on the headline above.
487 Drawers only open with a TAB on the drawer line itself. A drawer looks like
488 this:
489 :DRAWERNAME:
490 .....
491 :END:
492 The drawer \"PROPERTIES\" is special for capturing properties through
493 the property API.
495 Drawers can be defined on the per-file basis with a line like:
497 #+DRAWERS: HIDDEN STATE PROPERTIES"
498 :group 'org-structure
499 :type '(repeat (string :tag "Drawer Name")))
501 (defcustom org-cycle-global-at-bob nil
502 "Cycle globally if cursor is at beginning of buffer and not at a headline.
503 This makes it possible to do global cycling without having to use S-TAB or
504 C-u TAB. For this special case to work, the first line of the buffer
505 must not be a headline - it may be empty ot some other text. When used in
506 this way, `org-cycle-hook' is disables temporarily, to make sure the
507 cursor stays at the beginning of the buffer.
508 When this option is nil, don't do anything special at the beginning
509 of the buffer."
510 :group 'org-cycle
511 :type 'boolean)
513 (defcustom org-cycle-emulate-tab t
514 "Where should `org-cycle' emulate TAB.
515 nil Never
516 white Only in completely white lines
517 whitestart Only at the beginning of lines, before the first non-white char
518 t Everywhere except in headlines
519 exc-hl-bol Everywhere except at the start of a headline
520 If TAB is used in a place where it does not emulate TAB, the current subtree
521 visibility is cycled."
522 :group 'org-cycle
523 :type '(choice (const :tag "Never" nil)
524 (const :tag "Only in completely white lines" white)
525 (const :tag "Before first char in a line" whitestart)
526 (const :tag "Everywhere except in headlines" t)
527 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
530 (defcustom org-cycle-separator-lines 2
531 "Number of empty lines needed to keep an empty line between collapsed trees.
532 If you leave an empty line between the end of a subtree and the following
533 headline, this empty line is hidden when the subtree is folded.
534 Org-mode will leave (exactly) one empty line visible if the number of
535 empty lines is equal or larger to the number given in this variable.
536 So the default 2 means, at least 2 empty lines after the end of a subtree
537 are needed to produce free space between a collapsed subtree and the
538 following headline.
540 Special case: when 0, never leave empty lines in collapsed view."
541 :group 'org-cycle
542 :type 'integer)
543 (put 'org-cycle-separator-lines 'safe-local-variable 'integerp)
545 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
546 org-cycle-hide-drawers
547 org-cycle-show-empty-lines
548 org-optimize-window-after-visibility-change)
549 "Hook that is run after `org-cycle' has changed the buffer visibility.
550 The function(s) in this hook must accept a single argument which indicates
551 the new state that was set by the most recent `org-cycle' command. The
552 argument is a symbol. After a global state change, it can have the values
553 `overview', `content', or `all'. After a local state change, it can have
554 the values `folded', `children', or `subtree'."
555 :group 'org-cycle
556 :type 'hook)
558 (defgroup org-edit-structure nil
559 "Options concerning structure editing in Org-mode."
560 :tag "Org Edit Structure"
561 :group 'org-structure)
563 (defcustom org-odd-levels-only nil
564 "Non-nil means, skip even levels and only use odd levels for the outline.
565 This has the effect that two stars are being added/taken away in
566 promotion/demotion commands. It also influences how levels are
567 handled by the exporters.
568 Changing it requires restart of `font-lock-mode' to become effective
569 for fontification also in regions already fontified.
570 You may also set this on a per-file basis by adding one of the following
571 lines to the buffer:
573 #+STARTUP: odd
574 #+STARTUP: oddeven"
575 :group 'org-edit-structure
576 :group 'org-font-lock
577 :type 'boolean)
579 (defcustom org-adapt-indentation t
580 "Non-nil means, adapt indentation when promoting and demoting.
581 When this is set and the *entire* text in an entry is indented, the
582 indentation is increased by one space in a demotion command, and
583 decreased by one in a promotion command. If any line in the entry
584 body starts at column 0, indentation is not changed at all."
585 :group 'org-edit-structure
586 :type 'boolean)
588 (defcustom org-special-ctrl-a/e nil
589 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
590 When t, `C-a' will bring back the cursor to the beginning of the
591 headline text, i.e. after the stars and after a possible TODO keyword.
592 In an item, this will be the position after the bullet.
593 When the cursor is already at that position, another `C-a' will bring
594 it to the beginning of the line.
595 `C-e' will jump to the end of the headline, ignoring the presence of tags
596 in the headline. A second `C-e' will then jump to the true end of the
597 line, after any tags.
598 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
599 and only a directly following, identical keypress will bring the cursor
600 to the special positions."
601 :group 'org-edit-structure
602 :type '(choice
603 (const :tag "off" nil)
604 (const :tag "after bullet first" t)
605 (const :tag "border first" reversed)))
607 (if (fboundp 'defvaralias)
608 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
610 (defcustom org-special-ctrl-k nil
611 "Non-nil means `C-k' will behave specially in headlines.
612 When nil, `C-k' will call the default `kill-line' command.
613 When t, the following will happen while the cursor is in the headline:
615 - When the cursor is at the beginning of a headline, kill the entire
616 line and possible the folded subtree below the line.
617 - When in the middle of the headline text, kill the headline up to the tags.
618 - When after the headline text, kill the tags."
619 :group 'org-edit-structure
620 :type 'boolean)
622 (defcustom org-M-RET-may-split-line '((default . t))
623 "Non-nil means, M-RET will split the line at the cursor position.
624 When nil, it will go to the end of the line before making a
625 new line.
626 You may also set this option in a different way for different
627 contexts. Valid contexts are:
629 headline when creating a new headline
630 item when creating a new item
631 table in a table field
632 default the value to be used for all contexts not explicitly
633 customized"
634 :group 'org-structure
635 :group 'org-table
636 :type '(choice
637 (const :tag "Always" t)
638 (const :tag "Never" nil)
639 (repeat :greedy t :tag "Individual contexts"
640 (cons
641 (choice :tag "Context"
642 (const headline)
643 (const item)
644 (const table)
645 (const default))
646 (boolean)))))
649 (defcustom org-blank-before-new-entry '((heading . nil)
650 (plain-list-item . nil))
651 "Should `org-insert-heading' leave a blank line before new heading/item?
652 The value is an alist, with `heading' and `plain-list-item' as car,
653 and a boolean flag as cdr."
654 :group 'org-edit-structure
655 :type '(list
656 (cons (const heading) (boolean))
657 (cons (const plain-list-item) (boolean))))
659 (defcustom org-insert-heading-hook nil
660 "Hook being run after inserting a new heading."
661 :group 'org-edit-structure
662 :type 'hook)
664 (defcustom org-enable-fixed-width-editor t
665 "Non-nil means, lines starting with \":\" are treated as fixed-width.
666 This currently only means, they are never auto-wrapped.
667 When nil, such lines will be treated like ordinary lines.
668 See also the QUOTE keyword."
669 :group 'org-edit-structure
670 :type 'boolean)
672 (defcustom org-goto-auto-isearch t
673 "Non-nil means, typing characters in org-goto starts incremental search."
674 :group 'org-edit-structure
675 :type 'boolean)
677 (defgroup org-sparse-trees nil
678 "Options concerning sparse trees in Org-mode."
679 :tag "Org Sparse Trees"
680 :group 'org-structure)
682 (defcustom org-highlight-sparse-tree-matches t
683 "Non-nil means, highlight all matches that define a sparse tree.
684 The highlights will automatically disappear the next time the buffer is
685 changed by an edit command."
686 :group 'org-sparse-trees
687 :type 'boolean)
689 (defcustom org-remove-highlights-with-change t
690 "Non-nil means, any change to the buffer will remove temporary highlights.
691 Such highlights are created by `org-occur' and `org-clock-display'.
692 When nil, `C-c C-c needs to be used to get rid of the highlights.
693 The highlights created by `org-preview-latex-fragment' always need
694 `C-c C-c' to be removed."
695 :group 'org-sparse-trees
696 :group 'org-time
697 :type 'boolean)
700 (defcustom org-occur-hook '(org-first-headline-recenter)
701 "Hook that is run after `org-occur' has constructed a sparse tree.
702 This can be used to recenter the window to show as much of the structure
703 as possible."
704 :group 'org-sparse-trees
705 :type 'hook)
707 (defgroup org-plain-lists nil
708 "Options concerning plain lists in Org-mode."
709 :tag "Org Plain lists"
710 :group 'org-structure)
712 (defcustom org-cycle-include-plain-lists nil
713 "Non-nil means, include plain lists into visibility cycling.
714 This means that during cycling, plain list items will *temporarily* be
715 interpreted as outline headlines with a level given by 1000+i where i is the
716 indentation of the bullet. In all other operations, plain list items are
717 not seen as headlines. For example, you cannot assign a TODO keyword to
718 such an item."
719 :group 'org-plain-lists
720 :type 'boolean)
722 (defcustom org-plain-list-ordered-item-terminator t
723 "The character that makes a line with leading number an ordered list item.
724 Valid values are ?. and ?\). To get both terminators, use t. While
725 ?. may look nicer, it creates the danger that a line with leading
726 number may be incorrectly interpreted as an item. ?\) therefore is
727 the safe choice."
728 :group 'org-plain-lists
729 :type '(choice (const :tag "dot like in \"2.\"" ?.)
730 (const :tag "paren like in \"2)\"" ?\))
731 (const :tab "both" t)))
733 (defcustom org-empty-line-terminates-plain-lists nil
734 "Non-nil means, an empty line ends all plain list levels.
735 When nil, empty lines are part of the preceeding item."
736 :group 'org-plain-lists
737 :type 'boolean)
739 (defcustom org-auto-renumber-ordered-lists t
740 "Non-nil means, automatically renumber ordered plain lists.
741 Renumbering happens when the sequence have been changed with
742 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
743 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
744 :group 'org-plain-lists
745 :type 'boolean)
747 (defcustom org-provide-checkbox-statistics t
748 "Non-nil means, update checkbox statistics after insert and toggle.
749 When this is set, checkbox statistics is updated each time you either insert
750 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
751 with \\[org-ctrl-c-ctrl-c\\]."
752 :group 'org-plain-lists
753 :type 'boolean)
755 (defcustom org-description-max-indent 20
756 "Maximum indentation for the second line of a description list.
757 When the indentation would be larger than this, it will become
758 5 characters instead."
759 :group 'org-plain-lists
760 :type 'integer)
762 (defgroup org-imenu-and-speedbar nil
763 "Options concerning imenu and speedbar in Org-mode."
764 :tag "Org Imenu and Speedbar"
765 :group 'org-structure)
767 (defcustom org-imenu-depth 2
768 "The maximum level for Imenu access to Org-mode headlines.
769 This also applied for speedbar access."
770 :group 'org-imenu-and-speedbar
771 :type 'number)
773 (defgroup org-table nil
774 "Options concerning tables in Org-mode."
775 :tag "Org Table"
776 :group 'org)
778 (defcustom org-enable-table-editor 'optimized
779 "Non-nil means, lines starting with \"|\" are handled by the table editor.
780 When nil, such lines will be treated like ordinary lines.
782 When equal to the symbol `optimized', the table editor will be optimized to
783 do the following:
784 - Automatic overwrite mode in front of whitespace in table fields.
785 This makes the structure of the table stay in tact as long as the edited
786 field does not exceed the column width.
787 - Minimize the number of realigns. Normally, the table is aligned each time
788 TAB or RET are pressed to move to another field. With optimization this
789 happens only if changes to a field might have changed the column width.
790 Optimization requires replacing the functions `self-insert-command',
791 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
792 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
793 very good at guessing when a re-align will be necessary, but you can always
794 force one with \\[org-ctrl-c-ctrl-c].
796 If you would like to use the optimized version in Org-mode, but the
797 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
799 This variable can be used to turn on and off the table editor during a session,
800 but in order to toggle optimization, a restart is required.
802 See also the variable `org-table-auto-blank-field'."
803 :group 'org-table
804 :type '(choice
805 (const :tag "off" nil)
806 (const :tag "on" t)
807 (const :tag "on, optimized" optimized)))
809 (defcustom org-table-tab-recognizes-table.el t
810 "Non-nil means, TAB will automatically notice a table.el table.
811 When it sees such a table, it moves point into it and - if necessary -
812 calls `table-recognize-table'."
813 :group 'org-table-editing
814 :type 'boolean)
816 (defgroup org-link nil
817 "Options concerning links in Org-mode."
818 :tag "Org Link"
819 :group 'org)
821 (defvar org-link-abbrev-alist-local nil
822 "Buffer-local version of `org-link-abbrev-alist', which see.
823 The value of this is taken from the #+LINK lines.")
824 (make-variable-buffer-local 'org-link-abbrev-alist-local)
826 (defcustom org-link-abbrev-alist nil
827 "Alist of link abbreviations.
828 The car of each element is a string, to be replaced at the start of a link.
829 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
830 links in Org-mode buffers can have an optional tag after a double colon, e.g.
832 [[linkkey:tag][description]]
834 If REPLACE is a string, the tag will simply be appended to create the link.
835 If the string contains \"%s\", the tag will be inserted there.
837 REPLACE may also be a function that will be called with the tag as the
838 only argument to create the link, which should be returned as a string.
840 See the manual for examples."
841 :group 'org-link
842 :type 'alist)
844 (defcustom org-descriptive-links t
845 "Non-nil means, hide link part and only show description of bracket links.
846 Bracket links are like [[link][descritpion]]. This variable sets the initial
847 state in new org-mode buffers. The setting can then be toggled on a
848 per-buffer basis from the Org->Hyperlinks menu."
849 :group 'org-link
850 :type 'boolean)
852 (defcustom org-link-file-path-type 'adaptive
853 "How the path name in file links should be stored.
854 Valid values are:
856 relative Relative to the current directory, i.e. the directory of the file
857 into which the link is being inserted.
858 absolute Absolute path, if possible with ~ for home directory.
859 noabbrev Absolute path, no abbreviation of home directory.
860 adaptive Use relative path for files in the current directory and sub-
861 directories of it. For other files, use an absolute path."
862 :group 'org-link
863 :type '(choice
864 (const relative)
865 (const absolute)
866 (const noabbrev)
867 (const adaptive)))
869 (defcustom org-activate-links '(bracket angle plain radio tag date)
870 "Types of links that should be activated in Org-mode files.
871 This is a list of symbols, each leading to the activation of a certain link
872 type. In principle, it does not hurt to turn on most link types - there may
873 be a small gain when turning off unused link types. The types are:
875 bracket The recommended [[link][description]] or [[link]] links with hiding.
876 angular Links in angular brackes that may contain whitespace like
877 <bbdb:Carsten Dominik>.
878 plain Plain links in normal text, no whitespace, like http://google.com.
879 radio Text that is matched by a radio target, see manual for details.
880 tag Tag settings in a headline (link to tag search).
881 date Time stamps (link to calendar).
883 Changing this variable requires a restart of Emacs to become effective."
884 :group 'org-link
885 :type '(set (const :tag "Double bracket links (new style)" bracket)
886 (const :tag "Angular bracket links (old style)" angular)
887 (const :tag "Plain text links" plain)
888 (const :tag "Radio target matches" radio)
889 (const :tag "Tags" tag)
890 (const :tag "Timestamps" date)))
892 (defcustom org-make-link-description-function nil
893 "Function to use to generate link descriptions from links. If
894 nil the link location will be used. This function must take two
895 parameters; the first is the link and the second the description
896 org-insert-link has generated, and should return the description
897 to use."
898 :group 'org-link
899 :type 'function)
901 (defgroup org-link-store nil
902 "Options concerning storing links in Org-mode."
903 :tag "Org Store Link"
904 :group 'org-link)
906 (defcustom org-email-link-description-format "Email %c: %.30s"
907 "Format of the description part of a link to an email or usenet message.
908 The following %-excapes will be replaced by corresponding information:
910 %F full \"From\" field
911 %f name, taken from \"From\" field, address if no name
912 %T full \"To\" field
913 %t first name in \"To\" field, address if no name
914 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
915 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
916 %s subject
917 %m message-id.
919 You may use normal field width specification between the % and the letter.
920 This is for example useful to limit the length of the subject.
922 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
923 :group 'org-link-store
924 :type 'string)
926 (defcustom org-from-is-user-regexp
927 (let (r1 r2)
928 (when (and user-mail-address (not (string= user-mail-address "")))
929 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
930 (when (and user-full-name (not (string= user-full-name "")))
931 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
932 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
933 "Regexp mached against the \"From:\" header of an email or usenet message.
934 It should match if the message is from the user him/herself."
935 :group 'org-link-store
936 :type 'regexp)
938 (defcustom org-context-in-file-links t
939 "Non-nil means, file links from `org-store-link' contain context.
940 A search string will be added to the file name with :: as separator and
941 used to find the context when the link is activated by the command
942 `org-open-at-point'.
943 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
944 negates this setting for the duration of the command."
945 :group 'org-link-store
946 :type 'boolean)
948 (defcustom org-keep-stored-link-after-insertion nil
949 "Non-nil means, keep link in list for entire session.
951 The command `org-store-link' adds a link pointing to the current
952 location to an internal list. These links accumulate during a session.
953 The command `org-insert-link' can be used to insert links into any
954 Org-mode file (offering completion for all stored links). When this
955 option is nil, every link which has been inserted once using \\[org-insert-link]
956 will be removed from the list, to make completing the unused links
957 more efficient."
958 :group 'org-link-store
959 :type 'boolean)
961 (defgroup org-link-follow nil
962 "Options concerning following links in Org-mode."
963 :tag "Org Follow Link"
964 :group 'org-link)
966 (defcustom org-follow-link-hook nil
967 "Hook that is run after a link has been followed."
968 :group 'org-link-follow
969 :type 'hook)
971 (defcustom org-tab-follows-link nil
972 "Non-nil means, on links TAB will follow the link.
973 Needs to be set before org.el is loaded."
974 :group 'org-link-follow
975 :type 'boolean)
977 (defcustom org-return-follows-link nil
978 "Non-nil means, on links RET will follow the link.
979 Needs to be set before org.el is loaded."
980 :group 'org-link-follow
981 :type 'boolean)
983 (defcustom org-mouse-1-follows-link
984 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
985 "Non-nil means, mouse-1 on a link will follow the link.
986 A longer mouse click will still set point. Does not work on XEmacs.
987 Needs to be set before org.el is loaded."
988 :group 'org-link-follow
989 :type 'boolean)
991 (defcustom org-mark-ring-length 4
992 "Number of different positions to be recorded in the ring
993 Changing this requires a restart of Emacs to work correctly."
994 :group 'org-link-follow
995 :type 'interger)
997 (defcustom org-link-frame-setup
998 '((vm . vm-visit-folder-other-frame)
999 (gnus . gnus-other-frame)
1000 (file . find-file-other-window))
1001 "Setup the frame configuration for following links.
1002 When following a link with Emacs, it may often be useful to display
1003 this link in another window or frame. This variable can be used to
1004 set this up for the different types of links.
1005 For VM, use any of
1006 `vm-visit-folder'
1007 `vm-visit-folder-other-frame'
1008 For Gnus, use any of
1009 `gnus'
1010 `gnus-other-frame'
1011 For FILE, use any of
1012 `find-file'
1013 `find-file-other-window'
1014 `find-file-other-frame'
1015 For the calendar, use the variable `calendar-setup'.
1016 For BBDB, it is currently only possible to display the matches in
1017 another window."
1018 :group 'org-link-follow
1019 :type '(list
1020 (cons (const vm)
1021 (choice
1022 (const vm-visit-folder)
1023 (const vm-visit-folder-other-window)
1024 (const vm-visit-folder-other-frame)))
1025 (cons (const gnus)
1026 (choice
1027 (const gnus)
1028 (const gnus-other-frame)))
1029 (cons (const file)
1030 (choice
1031 (const find-file)
1032 (const find-file-other-window)
1033 (const find-file-other-frame)))))
1035 (defcustom org-display-internal-link-with-indirect-buffer nil
1036 "Non-nil means, use indirect buffer to display infile links.
1037 Activating internal links (from one location in a file to another location
1038 in the same file) normally just jumps to the location. When the link is
1039 activated with a C-u prefix (or with mouse-3), the link is displayed in
1040 another window. When this option is set, the other window actually displays
1041 an indirect buffer clone of the current buffer, to avoid any visibility
1042 changes to the current buffer."
1043 :group 'org-link-follow
1044 :type 'boolean)
1046 (defcustom org-open-non-existing-files nil
1047 "Non-nil means, `org-open-file' will open non-existing files.
1048 When nil, an error will be generated."
1049 :group 'org-link-follow
1050 :type 'boolean)
1052 (defcustom org-open-directory-means-index-dot-org nil
1053 "Non-nil means, a link to a directory really means to index.org.
1054 When nil, following a directory link will run dired or open a finder/explorer
1055 window on that directory."
1056 :group 'org-link-follow
1057 :type 'boolean)
1059 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1060 "Function and arguments to call for following mailto links.
1061 This is a list with the first element being a lisp function, and the
1062 remaining elements being arguments to the function. In string arguments,
1063 %a will be replaced by the address, and %s will be replaced by the subject
1064 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1065 :group 'org-link-follow
1066 :type '(choice
1067 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1068 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1069 (const :tag "message-mail" (message-mail "%a" "%s"))
1070 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1072 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1073 "Non-nil means, ask for confirmation before executing shell links.
1074 Shell links can be dangerous: just think about a link
1076 [[shell:rm -rf ~/*][Google Search]]
1078 This link would show up in your Org-mode document as \"Google Search\",
1079 but really it would remove your entire home directory.
1080 Therefore we advise against setting this variable to nil.
1081 Just change it to `y-or-n-p' of you want to confirm with a
1082 single keystroke rather than having to type \"yes\"."
1083 :group 'org-link-follow
1084 :type '(choice
1085 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1086 (const :tag "with y-or-n (faster)" y-or-n-p)
1087 (const :tag "no confirmation (dangerous)" nil)))
1089 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1090 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1091 Elisp links can be dangerous: just think about a link
1093 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1095 This link would show up in your Org-mode document as \"Google Search\",
1096 but really it would remove your entire home directory.
1097 Therefore we advise against setting this variable to nil.
1098 Just change it to `y-or-n-p' of you want to confirm with a
1099 single keystroke rather than having to type \"yes\"."
1100 :group 'org-link-follow
1101 :type '(choice
1102 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1103 (const :tag "with y-or-n (faster)" y-or-n-p)
1104 (const :tag "no confirmation (dangerous)" nil)))
1106 (defconst org-file-apps-defaults-gnu
1107 '((remote . emacs)
1108 (t . mailcap))
1109 "Default file applications on a UNIX or GNU/Linux system.
1110 See `org-file-apps'.")
1112 (defconst org-file-apps-defaults-macosx
1113 '((remote . emacs)
1114 (t . "open %s")
1115 ("ps" . "gv %s")
1116 ("ps.gz" . "gv %s")
1117 ("eps" . "gv %s")
1118 ("eps.gz" . "gv %s")
1119 ("dvi" . "xdvi %s")
1120 ("fig" . "xfig %s"))
1121 "Default file applications on a MacOS X system.
1122 The system \"open\" is known as a default, but we use X11 applications
1123 for some files for which the OS does not have a good default.
1124 See `org-file-apps'.")
1126 (defconst org-file-apps-defaults-windowsnt
1127 (list
1128 '(remote . emacs)
1129 (cons t
1130 (list (if (featurep 'xemacs)
1131 'mswindows-shell-execute
1132 'w32-shell-execute)
1133 "open" 'file)))
1134 "Default file applications on a Windows NT system.
1135 The system \"open\" is used for most files.
1136 See `org-file-apps'.")
1138 (defcustom org-file-apps
1140 ("txt" . emacs)
1141 ("tex" . emacs)
1142 ("ltx" . emacs)
1143 ("org" . emacs)
1144 ("el" . emacs)
1145 ("bib" . emacs)
1147 "External applications for opening `file:path' items in a document.
1148 Org-mode uses system defaults for different file types, but
1149 you can use this variable to set the application for a given file
1150 extension. The entries in this list are cons cells where the car identifies
1151 files and the cdr the corresponding command. Possible values for the
1152 file identifier are
1153 \"ext\" A string identifying an extension
1154 `directory' Matches a directory
1155 `remote' Matches a remote file, accessible through tramp or efs.
1156 Remote files most likely should be visited through Emacs
1157 because external applications cannot handle such paths.
1158 t Default for all remaining files
1160 Possible values for the command are:
1161 `emacs' The file will be visited by the current Emacs process.
1162 `default' Use the default application for this file type.
1163 string A command to be executed by a shell; %s will be replaced
1164 by the path to the file.
1165 sexp A Lisp form which will be evaluated. The file path will
1166 be available in the Lisp variable `file'.
1167 For more examples, see the system specific constants
1168 `org-file-apps-defaults-macosx'
1169 `org-file-apps-defaults-windowsnt'
1170 `org-file-apps-defaults-gnu'."
1171 :group 'org-link-follow
1172 :type '(repeat
1173 (cons (choice :value ""
1174 (string :tag "Extension")
1175 (const :tag "Default for unrecognized files" t)
1176 (const :tag "Remote file" remote)
1177 (const :tag "Links to a directory" directory))
1178 (choice :value ""
1179 (const :tag "Visit with Emacs" emacs)
1180 (const :tag "Use system default" default)
1181 (string :tag "Command")
1182 (sexp :tag "Lisp form")))))
1184 (defgroup org-refile nil
1185 "Options concerning refiling entries in Org-mode."
1186 :tag "Org Remember"
1187 :group 'org)
1189 (defcustom org-directory "~/org"
1190 "Directory with org files.
1191 This directory will be used as default to prompt for org files.
1192 Used by the hooks for remember.el."
1193 :group 'org-refile
1194 :group 'org-remember
1195 :type 'directory)
1197 (defcustom org-default-notes-file "~/.notes"
1198 "Default target for storing notes.
1199 Used by the hooks for remember.el. This can be a string, or nil to mean
1200 the value of `remember-data-file'.
1201 You can set this on a per-template basis with the variable
1202 `org-remember-templates'."
1203 :group 'org-refile
1204 :group 'org-remember
1205 :type '(choice
1206 (const :tag "Default from remember-data-file" nil)
1207 file))
1209 (defcustom org-goto-interface 'outline
1210 "The default interface to be used for `org-goto'.
1211 Allowed vaues are:
1212 outline The interface shows an outline of the relevant file
1213 and the correct heading is found by moving through
1214 the outline or by searching with incremental search.
1215 outline-path-completion Headlines in the current buffer are offered via
1216 completion."
1217 :group 'org-refile
1218 :type '(choice
1219 (const :tag "Outline" outline)
1220 (const :tag "Outline-path-completion" outline-path-completion)))
1222 (defcustom org-reverse-note-order nil
1223 "Non-nil means, store new notes at the beginning of a file or entry.
1224 When nil, new notes will be filed to the end of a file or entry.
1225 This can also be a list with cons cells of regular expressions that
1226 are matched against file names, and values."
1227 :group 'org-remember
1228 :type '(choice
1229 (const :tag "Reverse always" t)
1230 (const :tag "Reverse never" nil)
1231 (repeat :tag "By file name regexp"
1232 (cons regexp boolean))))
1234 (defcustom org-refile-targets nil
1235 "Targets for refiling entries with \\[org-refile].
1236 This is list of cons cells. Each cell contains:
1237 - a specification of the files to be considered, either a list of files,
1238 or a symbol whose function or variable value will be used to retrieve
1239 a file name or a list of file names. Nil means, refile to a different
1240 heading in the current buffer.
1241 - A specification of how to find candidate refile targets. This may be
1242 any of
1243 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1244 This tag has to be present in all target headlines, inheritance will
1245 not be considered.
1246 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1247 todo keyword.
1248 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1249 headlines that are refiling targets.
1250 - a cons cell (:level . N). Any headline of level N is considered a target.
1251 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1252 :group 'org-remember
1253 :type '(repeat
1254 (cons
1255 (choice :value org-agenda-files
1256 (const :tag "All agenda files" org-agenda-files)
1257 (const :tag "Current buffer" nil)
1258 (function) (variable) (file))
1259 (choice :tag "Identify target headline by"
1260 (cons :tag "Specific tag" (const :tag) (string))
1261 (cons :tag "TODO keyword" (const :todo) (string))
1262 (cons :tag "Regular expression" (const :regexp) (regexp))
1263 (cons :tag "Level number" (const :level) (integer))
1264 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1266 (defcustom org-refile-use-outline-path nil
1267 "Non-nil means, provide refile targets as paths.
1268 So a level 3 headline will be available as level1/level2/level3.
1269 When the value is `file', also include the file name (without directory)
1270 into the path. When `full-file-path', include the full file path."
1271 :group 'org-remember
1272 :type '(choice
1273 (const :tag "Not" nil)
1274 (const :tag "Yes" t)
1275 (const :tag "Start with file name" file)
1276 (const :tag "Start with full file path" full-file-path)))
1278 (defgroup org-todo nil
1279 "Options concerning TODO items in Org-mode."
1280 :tag "Org TODO"
1281 :group 'org)
1283 (defgroup org-progress nil
1284 "Options concerning Progress logging in Org-mode."
1285 :tag "Org Progress"
1286 :group 'org-time)
1288 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1289 "List of TODO entry keyword sequences and their interpretation.
1290 \\<org-mode-map>This is a list of sequences.
1292 Each sequence starts with a symbol, either `sequence' or `type',
1293 indicating if the keywords should be interpreted as a sequence of
1294 action steps, or as different types of TODO items. The first
1295 keywords are states requiring action - these states will select a headline
1296 for inclusion into the global TODO list Org-mode produces. If one of
1297 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1298 signify that no further action is necessary. If \"|\" is not found,
1299 the last keyword is treated as the only DONE state of the sequence.
1301 The command \\[org-todo] cycles an entry through these states, and one
1302 additional state where no keyword is present. For details about this
1303 cycling, see the manual.
1305 TODO keywords and interpretation can also be set on a per-file basis with
1306 the special #+SEQ_TODO and #+TYP_TODO lines.
1308 Each keyword can optionally specify a character for fast state selection
1309 \(in combination with the variable `org-use-fast-todo-selection')
1310 and specifiers for state change logging, using the same syntax
1311 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1312 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1313 indicates to record a time stamp each time this state is selected.
1315 Each keyword may also specify if a timestamp or a note should be
1316 recorded when entering or leaving the state, by adding additional
1317 characters in the parenthesis after the keyword. This looks like this:
1318 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1319 record only the time of the state change. With X and Y being either
1320 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1321 Y when leaving the state if and only if the *target* state does not
1322 define X. You may omit any of the fast-selection key or X or /Y,
1323 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1325 For backward compatibility, this variable may also be just a list
1326 of keywords - in this case the interptetation (sequence or type) will be
1327 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1328 :group 'org-todo
1329 :group 'org-keywords
1330 :type '(choice
1331 (repeat :tag "Old syntax, just keywords"
1332 (string :tag "Keyword"))
1333 (repeat :tag "New syntax"
1334 (cons
1335 (choice
1336 :tag "Interpretation"
1337 (const :tag "Sequence (cycling hits every state)" sequence)
1338 (const :tag "Type (cycling directly to DONE)" type))
1339 (repeat
1340 (string :tag "Keyword"))))))
1342 (defvar org-todo-keywords-1 nil
1343 "All TODO and DONE keywords active in a buffer.")
1344 (make-variable-buffer-local 'org-todo-keywords-1)
1345 (defvar org-todo-keywords-for-agenda nil)
1346 (defvar org-done-keywords-for-agenda nil)
1347 (defvar org-agenda-contributing-files nil)
1348 (defvar org-not-done-keywords nil)
1349 (make-variable-buffer-local 'org-not-done-keywords)
1350 (defvar org-done-keywords nil)
1351 (make-variable-buffer-local 'org-done-keywords)
1352 (defvar org-todo-heads nil)
1353 (make-variable-buffer-local 'org-todo-heads)
1354 (defvar org-todo-sets nil)
1355 (make-variable-buffer-local 'org-todo-sets)
1356 (defvar org-todo-log-states nil)
1357 (make-variable-buffer-local 'org-todo-log-states)
1358 (defvar org-todo-kwd-alist nil)
1359 (make-variable-buffer-local 'org-todo-kwd-alist)
1360 (defvar org-todo-key-alist nil)
1361 (make-variable-buffer-local 'org-todo-key-alist)
1362 (defvar org-todo-key-trigger nil)
1363 (make-variable-buffer-local 'org-todo-key-trigger)
1365 (defcustom org-todo-interpretation 'sequence
1366 "Controls how TODO keywords are interpreted.
1367 This variable is in principle obsolete and is only used for
1368 backward compatibility, if the interpretation of todo keywords is
1369 not given already in `org-todo-keywords'. See that variable for
1370 more information."
1371 :group 'org-todo
1372 :group 'org-keywords
1373 :type '(choice (const sequence)
1374 (const type)))
1376 (defcustom org-use-fast-todo-selection 'prefix
1377 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1378 This variable describes if and under what circumstances the cycling
1379 mechanism for TODO keywords will be replaced by a single-key, direct
1380 selection scheme.
1382 When nil, fast selection is never used.
1384 When the symbol `prefix', it will be used when `org-todo' is called with
1385 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1386 in an agenda buffer.
1388 When t, fast selection is used by default. In this case, the prefix
1389 argument forces cycling instead.
1391 In all cases, the special interface is only used if access keys have actually
1392 been assigned by the user, i.e. if keywords in the configuration are followed
1393 by a letter in parenthesis, like TODO(t)."
1394 :group 'org-todo
1395 :type '(choice
1396 (const :tag "Never" nil)
1397 (const :tag "By default" t)
1398 (const :tag "Only with C-u C-c C-t" prefix)))
1400 (defcustom org-provide-todo-statistics t
1401 "Non-nil means, update todo statistics after insert and toggle.
1402 When this is set, todo statistics is updated in the parent of the current
1403 entry each time a todo state is changed."
1404 :group 'org-todo
1405 :type 'boolean)
1407 (defcustom org-after-todo-state-change-hook nil
1408 "Hook which is run after the state of a TODO item was changed.
1409 The new state (a string with a TODO keyword, or nil) is available in the
1410 Lisp variable `state'."
1411 :group 'org-todo
1412 :type 'hook)
1414 (defcustom org-log-done nil
1415 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1416 When equal to the list (done), also prompt for a closing note.
1417 This can also be configured on a per-file basis by adding one of
1418 the following lines anywhere in the buffer:
1420 #+STARTUP: logdone
1421 #+STARTUP: lognotedone
1422 #+STARTUP: nologdone"
1423 :group 'org-todo
1424 :group 'org-progress
1425 :type '(choice
1426 (const :tag "No logging" nil)
1427 (const :tag "Record CLOSED timestamp" time)
1428 (const :tag "Record CLOSED timestamp with closing note." note)))
1430 ;; Normalize old uses of org-log-done.
1431 (cond
1432 ((eq org-log-done t) (setq org-log-done 'time))
1433 ((and (listp org-log-done) (memq 'done org-log-done))
1434 (setq org-log-done 'note)))
1436 (defcustom org-log-note-clock-out nil
1437 "Non-nil means, recored a note when clocking out of an item.
1438 This can also be configured on a per-file basis by adding one of
1439 the following lines anywhere in the buffer:
1441 #+STARTUP: lognoteclock-out
1442 #+STARTUP: nolognoteclock-out"
1443 :group 'org-todo
1444 :group 'org-progress
1445 :type 'boolean)
1447 (defcustom org-log-done-with-time t
1448 "Non-nil means, the CLOSED time stamp will contain date and time.
1449 When nil, only the date will be recorded."
1450 :group 'org-progress
1451 :type 'boolean)
1453 (defcustom org-log-note-headings
1454 '((done . "CLOSING NOTE %t")
1455 (state . "State %-12s %t")
1456 (note . "Note taken on %t")
1457 (clock-out . ""))
1458 "Headings for notes added to entries.
1459 The value is an alist, with the car being a symbol indicating the note
1460 context, and the cdr is the heading to be used. The heading may also be the
1461 empty string.
1462 %t in the heading will be replaced by a time stamp.
1463 %s will be replaced by the new TODO state, in double quotes.
1464 %u will be replaced by the user name.
1465 %U will be replaced by the full user name."
1466 :group 'org-todo
1467 :group 'org-progress
1468 :type '(list :greedy t
1469 (cons (const :tag "Heading when closing an item" done) string)
1470 (cons (const :tag
1471 "Heading when changing todo state (todo sequence only)"
1472 state) string)
1473 (cons (const :tag "Heading when just taking a note" note) string)
1474 (cons (const :tag "Heading when clocking out" clock-out) string)))
1476 (unless (assq 'note org-log-note-headings)
1477 (push '(note . "%t") org-log-note-headings))
1479 (defcustom org-log-states-order-reversed t
1480 "Non-nil means, the latest state change note will be directly after heading.
1481 When nil, the notes will be orderer according to time."
1482 :group 'org-todo
1483 :group 'org-progress
1484 :type 'boolean)
1486 (defcustom org-log-repeat 'time
1487 "Non-nil means, record moving through the DONE state when triggering repeat.
1488 An auto-repeating tasks is immediately switched back to TODO when marked
1489 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1490 the TODO keyword definition, or recording a closing note by setting
1491 `org-log-done', there will be no record of the task moving through DONE.
1492 This variable forces taking a note anyway. Possible values are:
1494 nil Don't force a record
1495 time Record a time stamp
1496 note Record a note
1498 This option can also be set with on a per-file-basis with
1500 #+STARTUP: logrepeat
1501 #+STARTUP: lognoterepeat
1502 #+STARTUP: nologrepeat
1504 You can have local logging settings for a subtree by setting the LOGGING
1505 property to one or more of these keywords."
1506 :group 'org-todo
1507 :group 'org-progress
1508 :type '(choice
1509 (const :tag "Don't force a record" nil)
1510 (const :tag "Force recording the DONE state" time)
1511 (const :tag "Force recording a note with the DONE state" note)))
1514 (defgroup org-priorities nil
1515 "Priorities in Org-mode."
1516 :tag "Org Priorities"
1517 :group 'org-todo)
1519 (defcustom org-highest-priority ?A
1520 "The highest priority of TODO items. A character like ?A, ?B etc.
1521 Must have a smaller ASCII number than `org-lowest-priority'."
1522 :group 'org-priorities
1523 :type 'character)
1525 (defcustom org-lowest-priority ?C
1526 "The lowest priority of TODO items. A character like ?A, ?B etc.
1527 Must have a larger ASCII number than `org-highest-priority'."
1528 :group 'org-priorities
1529 :type 'character)
1531 (defcustom org-default-priority ?B
1532 "The default priority of TODO items.
1533 This is the priority an item get if no explicit priority is given."
1534 :group 'org-priorities
1535 :type 'character)
1537 (defcustom org-priority-start-cycle-with-default t
1538 "Non-nil means, start with default priority when starting to cycle.
1539 When this is nil, the first step in the cycle will be (depending on the
1540 command used) one higher or lower that the default priority."
1541 :group 'org-priorities
1542 :type 'boolean)
1544 (defgroup org-time nil
1545 "Options concerning time stamps and deadlines in Org-mode."
1546 :tag "Org Time"
1547 :group 'org)
1549 (defcustom org-insert-labeled-timestamps-at-point nil
1550 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1551 When nil, these labeled time stamps are forces into the second line of an
1552 entry, just after the headline. When scheduling from the global TODO list,
1553 the time stamp will always be forced into the second line."
1554 :group 'org-time
1555 :type 'boolean)
1557 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1558 "Formats for `format-time-string' which are used for time stamps.
1559 It is not recommended to change this constant.")
1561 (defcustom org-time-stamp-rounding-minutes '(0 5)
1562 "Number of minutes to round time stamps to.
1563 These are two values, the first applies when first creating a time stamp.
1564 The second applies when changing it with the commands `S-up' and `S-down'.
1565 When changing the time stamp, this means that it will change in steps
1566 of N minutes, as given by the second value.
1568 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1569 numbers should be factors of 60, so for example 5, 10, 15.
1571 When this is larger than 1, you can still force an exact time-stamp by using
1572 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1573 and by using a prefix arg to `S-up/down' to specify the exact number
1574 of minutes to shift."
1575 :group 'org-time
1576 :get '(lambda (var) ; Make sure all entries have 5 elements
1577 (if (integerp (default-value var))
1578 (list (default-value var) 5)
1579 (default-value var)))
1580 :type '(list
1581 (integer :tag "when inserting times")
1582 (integer :tag "when modifying times")))
1584 ;; Normalize old customizations of this variable.
1585 (when (integerp org-time-stamp-rounding-minutes)
1586 (setq org-time-stamp-rounding-minutes
1587 (list org-time-stamp-rounding-minutes
1588 org-time-stamp-rounding-minutes)))
1590 (defcustom org-display-custom-times nil
1591 "Non-nil means, overlay custom formats over all time stamps.
1592 The formats are defined through the variable `org-time-stamp-custom-formats'.
1593 To turn this on on a per-file basis, insert anywhere in the file:
1594 #+STARTUP: customtime"
1595 :group 'org-time
1596 :set 'set-default
1597 :type 'sexp)
1598 (make-variable-buffer-local 'org-display-custom-times)
1600 (defcustom org-time-stamp-custom-formats
1601 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1602 "Custom formats for time stamps. See `format-time-string' for the syntax.
1603 These are overlayed over the default ISO format if the variable
1604 `org-display-custom-times' is set. Time like %H:%M should be at the
1605 end of the second format."
1606 :group 'org-time
1607 :type 'sexp)
1609 (defun org-time-stamp-format (&optional long inactive)
1610 "Get the right format for a time string."
1611 (let ((f (if long (cdr org-time-stamp-formats)
1612 (car org-time-stamp-formats))))
1613 (if inactive
1614 (concat "[" (substring f 1 -1) "]")
1615 f)))
1617 (defcustom org-time-clocksum-format "%d:%02d"
1618 "The format string used when creating CLOCKSUM lines, or when
1619 org-mode generates a time duration."
1620 :group 'org-time
1621 :type 'string)
1623 (defcustom org-deadline-warning-days 14
1624 "No. of days before expiration during which a deadline becomes active.
1625 This variable governs the display in sparse trees and in the agenda.
1626 When 0 or negative, it means use this number (the absolute value of it)
1627 even if a deadline has a different individual lead time specified."
1628 :group 'org-time
1629 :group 'org-agenda-daily/weekly
1630 :type 'number)
1632 (defcustom org-read-date-prefer-future t
1633 "Non-nil means, assume future for incomplete date input from user.
1634 This affects the following situations:
1635 1. The user gives a day, but no month.
1636 For example, if today is the 15th, and you enter \"3\", Org-mode will
1637 read this as the third of *next* month. However, if you enter \"17\",
1638 it will be considered as *this* month.
1639 2. The user gives a month but not a year.
1640 For example, if it is april and you enter \"feb 2\", this will be read
1641 as feb 2, *next* year. \"May 5\", however, will be this year.
1643 Currently this does not work for ISO week specifications.
1645 When this option is nil, the current month and year will always be used
1646 as defaults."
1647 :group 'org-time
1648 :type 'boolean)
1650 (defcustom org-read-date-display-live t
1651 "Non-nil means, display current interpretation of date prompt live.
1652 This display will be in an overlay, in the minibuffer."
1653 :group 'org-time
1654 :type 'boolean)
1656 (defcustom org-read-date-popup-calendar t
1657 "Non-nil means, pop up a calendar when prompting for a date.
1658 In the calendar, the date can be selected with mouse-1. However, the
1659 minibuffer will also be active, and you can simply enter the date as well.
1660 When nil, only the minibuffer will be available."
1661 :group 'org-time
1662 :type 'boolean)
1663 (if (fboundp 'defvaralias)
1664 (defvaralias 'org-popup-calendar-for-date-prompt
1665 'org-read-date-popup-calendar))
1667 (defcustom org-extend-today-until 0
1668 "The hour when your day really ends.
1669 This has influence for the following applications:
1670 - When switching the agenda to \"today\". It it is still earlier than
1671 the time given here, the day recognized as TODAY is actually yesterday.
1672 - When a date is read from the user and it is still before the time given
1673 here, the current date and time will be assumed to be yesterday, 23:59.
1675 FIXME:
1676 IMPORTANT: This is still a very experimental feature, it may disappear
1677 again or it may be extended to mean more things."
1678 :group 'org-time
1679 :type 'number)
1681 (defcustom org-edit-timestamp-down-means-later nil
1682 "Non-nil means, S-down will increase the time in a time stamp.
1683 When nil, S-up will increase."
1684 :group 'org-time
1685 :type 'boolean)
1687 (defcustom org-calendar-follow-timestamp-change t
1688 "Non-nil means, make the calendar window follow timestamp changes.
1689 When a timestamp is modified and the calendar window is visible, it will be
1690 moved to the new date."
1691 :group 'org-time
1692 :type 'boolean)
1694 (defgroup org-tags nil
1695 "Options concerning tags in Org-mode."
1696 :tag "Org Tags"
1697 :group 'org)
1699 (defcustom org-tag-alist nil
1700 "List of tags allowed in Org-mode files.
1701 When this list is nil, Org-mode will base TAG input on what is already in the
1702 buffer.
1703 The value of this variable is an alist, the car of each entry must be a
1704 keyword as a string, the cdr may be a character that is used to select
1705 that tag through the fast-tag-selection interface.
1706 See the manual for details."
1707 :group 'org-tags
1708 :type '(repeat
1709 (choice
1710 (cons (string :tag "Tag name")
1711 (character :tag "Access char"))
1712 (const :tag "Start radio group" (:startgroup))
1713 (const :tag "End radio group" (:endgroup)))))
1715 (defvar org-file-tags nil
1716 "List of tags that can be inherited by all entries in the file.
1717 The tags will be inherited if the variable `org-use-tag-inheritance'
1718 says they should be.
1719 This variable is populated from #+TAG lines.")
1721 (defcustom org-use-fast-tag-selection 'auto
1722 "Non-nil means, use fast tag selection scheme.
1723 This is a special interface to select and deselect tags with single keys.
1724 When nil, fast selection is never used.
1725 When the symbol `auto', fast selection is used if and only if selection
1726 characters for tags have been configured, either through the variable
1727 `org-tag-alist' or through a #+TAGS line in the buffer.
1728 When t, fast selection is always used and selection keys are assigned
1729 automatically if necessary."
1730 :group 'org-tags
1731 :type '(choice
1732 (const :tag "Always" t)
1733 (const :tag "Never" nil)
1734 (const :tag "When selection characters are configured" 'auto)))
1736 (defcustom org-fast-tag-selection-single-key nil
1737 "Non-nil means, fast tag selection exits after first change.
1738 When nil, you have to press RET to exit it.
1739 During fast tag selection, you can toggle this flag with `C-c'.
1740 This variable can also have the value `expert'. In this case, the window
1741 displaying the tags menu is not even shown, until you press C-c again."
1742 :group 'org-tags
1743 :type '(choice
1744 (const :tag "No" nil)
1745 (const :tag "Yes" t)
1746 (const :tag "Expert" expert)))
1748 (defvar org-fast-tag-selection-include-todo nil
1749 "Non-nil means, fast tags selection interface will also offer TODO states.
1750 This is an undocumented feature, you should not rely on it.")
1752 (defcustom org-tags-column (if (featurep 'xemacs) -79 -80)
1753 "The column to which tags should be indented in a headline.
1754 If this number is positive, it specifies the column. If it is negative,
1755 it means that the tags should be flushright to that column. For example,
1756 -80 works well for a normal 80 character screen."
1757 :group 'org-tags
1758 :type 'integer)
1760 (defcustom org-auto-align-tags t
1761 "Non-nil means, realign tags after pro/demotion of TODO state change.
1762 These operations change the length of a headline and therefore shift
1763 the tags around. With this options turned on, after each such operation
1764 the tags are again aligned to `org-tags-column'."
1765 :group 'org-tags
1766 :type 'boolean)
1768 (defcustom org-use-tag-inheritance t
1769 "Non-nil means, tags in levels apply also for sublevels.
1770 When nil, only the tags directly given in a specific line apply there.
1771 If this option is t, a match early-on in a tree can lead to a large
1772 number of matches in the subtree. If you only want to see the first
1773 match in a tree during a search, check out the variable
1774 `org-tags-match-list-sublevels'.
1776 This may also be a list of tags that should be inherited, or a regexp that
1777 matches tags that should be inherited."
1778 :group 'org-tags
1779 :type '(choice
1780 (const :tag "Not" nil)
1781 (const :tag "Always" t)
1782 (repeat :tag "Specific tags" (string :tag "Tag"))
1783 (regexp :tag "Tags matched by regexp")))
1785 (defun org-tag-inherit-p (tag)
1786 "Check if TAG is one that should be inherited."
1787 (cond
1788 ((eq org-use-tag-inheritance t) t)
1789 ((not org-use-tag-inheritance) nil)
1790 ((stringp org-use-tag-inheritance)
1791 (string-match org-use-tag-inheritance tag))
1792 ((listp org-use-tag-inheritance)
1793 (member tag org-use-tag-inheritance))
1794 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1796 (defcustom org-tags-match-list-sublevels t
1797 "Non-nil means list also sublevels of headlines matching tag search.
1798 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1799 the sublevels of a headline matching a tag search often also match
1800 the same search. Listing all of them can create very long lists.
1801 Setting this variable to nil causes subtrees of a match to be skipped.
1802 This option is off by default, because inheritance in on. If you turn
1803 inheritance off, you very likely want to turn this option on.
1805 As a special case, if the tag search is restricted to TODO items, the
1806 value of this variable is ignored and sublevels are always checked, to
1807 make sure all corresponding TODO items find their way into the list."
1808 :group 'org-tags
1809 :type 'boolean)
1811 (defvar org-tags-history nil
1812 "History of minibuffer reads for tags.")
1813 (defvar org-last-tags-completion-table nil
1814 "The last used completion table for tags.")
1815 (defvar org-after-tags-change-hook nil
1816 "Hook that is run after the tags in a line have changed.")
1818 (defgroup org-properties nil
1819 "Options concerning properties in Org-mode."
1820 :tag "Org Properties"
1821 :group 'org)
1823 (defcustom org-property-format "%-10s %s"
1824 "How property key/value pairs should be formatted by `indent-line'.
1825 When `indent-line' hits a property definition, it will format the line
1826 according to this format, mainly to make sure that the values are
1827 lined-up with respect to each other."
1828 :group 'org-properties
1829 :type 'string)
1831 (defcustom org-use-property-inheritance nil
1832 "Non-nil means, properties apply also for sublevels.
1834 This setting is chiefly used during property searches. Turning it on can
1835 cause significant overhead when doing a search, which is why it is not
1836 on by default.
1838 When nil, only the properties directly given in the current entry count.
1839 When t, every property is inherited. The value may also be a list of
1840 properties that should have inheritance, or a regular expression matching
1841 properties that should be inherited.
1843 However, note that some special properties use inheritance under special
1844 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1845 and the properties ending in \"_ALL\" when they are used as descriptor
1846 for valid values of a property.
1848 Note for programmers:
1849 When querying an entry with `org-entry-get', you can control if inheritance
1850 should be used. By default, `org-entry-get' looks only at the local
1851 properties. You can request inheritance by setting the inherit argument
1852 to t (to force inheritance) or to `selective' (to respect the setting
1853 in this variable)."
1854 :group 'org-properties
1855 :type '(choice
1856 (const :tag "Not" nil)
1857 (const :tag "Always" t)
1858 (repeat :tag "Specific properties" (string :tag "Property"))
1859 (regexp :tag "Properties matched by regexp")))
1861 (defun org-property-inherit-p (property)
1862 "Check if PROPERTY is one that should be inherited."
1863 (cond
1864 ((eq org-use-property-inheritance t) t)
1865 ((not org-use-property-inheritance) nil)
1866 ((stringp org-use-property-inheritance)
1867 (string-match org-use-property-inheritance property))
1868 ((listp org-use-property-inheritance)
1869 (member property org-use-property-inheritance))
1870 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1872 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1873 "The default column format, if no other format has been defined.
1874 This variable can be set on the per-file basis by inserting a line
1876 #+COLUMNS: %25ITEM ....."
1877 :group 'org-properties
1878 :type 'string)
1880 (defcustom org-columns-ellipses ".."
1881 "The ellipses to be used when a field in column view is truncated.
1882 When this is the empty string, as many characters as possible are shown,
1883 but then there will be no visual indication that the field has been truncated.
1884 When this is a string of length N, the last N characters of a truncated
1885 field are replaced by this string. If the column is narrower than the
1886 ellipses string, only part of the ellipses string will be shown."
1887 :group 'org-properties
1888 :type 'string)
1890 (defcustom org-columns-modify-value-for-display-function nil
1891 "Function that modifies values for display in column view.
1892 For example, it can be used to cut out a certain part from a time stamp.
1893 The function must take 2 argments:
1895 column-title The tite of the column (*not* the property name)
1896 value The value that should be modified.
1898 The function should return the value that should be displayed,
1899 or nil if the normal value should be used."
1900 :group 'org-properties
1901 :type 'function)
1903 (defcustom org-effort-property "Effort"
1904 "The property that is being used to keep track of effort estimates.
1905 Effort estimates given in this property need to have the format H:MM."
1906 :group 'org-properties
1907 :group 'org-progress
1908 :type '(string :tag "Property"))
1910 (defconst org-global-properties-fixed
1911 '(("VISIBILITY_ALL" . "folded children content all"))
1912 "List of property/value pairs that can be inherited by any entry.
1913 These are fixed values, for the preset properties.")
1916 (defcustom org-global-properties nil
1917 "List of property/value pairs that can be inherited by any entry.
1918 You can set buffer-local values for this by adding lines like
1920 #+PROPERTY: NAME VALUE"
1921 :group 'org-properties
1922 :type '(repeat
1923 (cons (string :tag "Property")
1924 (string :tag "Value"))))
1926 (defvar org-file-properties nil
1927 "List of property/value pairs that can be inherited by any entry.
1928 Valid for the current buffer.
1929 This variable is populated from #+PROPERTY lines.")
1930 (make-variable-buffer-local 'org-file-properties)
1932 (defgroup org-agenda nil
1933 "Options concerning agenda views in Org-mode."
1934 :tag "Org Agenda"
1935 :group 'org)
1937 (defvar org-category nil
1938 "Variable used by org files to set a category for agenda display.
1939 Such files should use a file variable to set it, for example
1941 # -*- mode: org; org-category: \"ELisp\"
1943 or contain a special line
1945 #+CATEGORY: ELisp
1947 If the file does not specify a category, then file's base name
1948 is used instead.")
1949 (make-variable-buffer-local 'org-category)
1951 (defcustom org-agenda-files nil
1952 "The files to be used for agenda display.
1953 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1954 \\[org-remove-file]. You can also use customize to edit the list.
1956 If an entry is a directory, all files in that directory that are matched by
1957 `org-agenda-file-regexp' will be part of the file list.
1959 If the value of the variable is not a list but a single file name, then
1960 the list of agenda files is actually stored and maintained in that file, one
1961 agenda file per line."
1962 :group 'org-agenda
1963 :type '(choice
1964 (repeat :tag "List of files and directories" file)
1965 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1967 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1968 "Regular expression to match files for `org-agenda-files'.
1969 If any element in the list in that variable contains a directory instead
1970 of a normal file, all files in that directory that are matched by this
1971 regular expression will be included."
1972 :group 'org-agenda
1973 :type 'regexp)
1975 (defcustom org-agenda-text-search-extra-files nil
1976 "List of extra files to be searched by text search commands.
1977 These files will be search in addition to the agenda files by the
1978 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1979 Note that these files will only be searched for text search commands,
1980 not for the other agenda views like todo lists, tag searches or the weekly
1981 agenda. This variable is intended to list notes and possibly archive files
1982 that should also be searched by these two commands.
1983 In fact, if the first element in the list is the symbol `agenda-archives',
1984 than all archive files of all agenda files will be added to the search
1985 scope."
1986 :group 'org-agenda
1987 :type '(set :greedy t
1988 (const :tag "Agenda Archives" agenda-archives)
1989 (repeat :inline t (file))))
1991 (if (fboundp 'defvaralias)
1992 (defvaralias 'org-agenda-multi-occur-extra-files
1993 'org-agenda-text-search-extra-files))
1995 (defcustom org-agenda-skip-unavailable-files nil
1996 "Non-nil means to just skip non-reachable files in `org-agenda-files'.
1997 A nil value means to remove them, after a query, from the list."
1998 :group 'org-agenda
1999 :type 'boolean)
2001 (defcustom org-calendar-to-agenda-key [?c]
2002 "The key to be installed in `calendar-mode-map' for switching to the agenda.
2003 The command `org-calendar-goto-agenda' will be bound to this key. The
2004 default is the character `c' because then `c' can be used to switch back and
2005 forth between agenda and calendar."
2006 :group 'org-agenda
2007 :type 'sexp)
2009 (defcustom org-calendar-agenda-action-key [?k]
2010 "The key to be installed in `calendar-mode-map' for agenda-action.
2011 The command `org-agenda-action' will be bound to this key. The
2012 default is the character `k' because we use the same key in the agenda."
2013 :group 'org-agenda
2014 :type 'sexp)
2016 (eval-after-load "calendar"
2017 '(progn
2018 (org-defkey calendar-mode-map org-calendar-to-agenda-key
2019 'org-calendar-goto-agenda)
2020 (org-defkey calendar-mode-map org-calendar-agenda-action-key
2021 'org-agenda-action)))
2023 (defgroup org-latex nil
2024 "Options for embedding LaTeX code into Org-mode."
2025 :tag "Org LaTeX"
2026 :group 'org)
2028 (defcustom org-format-latex-options
2029 '(:foreground default :background default :scale 1.0
2030 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
2031 :matchers ("begin" "$" "$$" "\\(" "\\["))
2032 "Options for creating images from LaTeX fragments.
2033 This is a property list with the following properties:
2034 :foreground the foreground color for images embedded in Emacs, e.g. \"Black\".
2035 `default' means use the foreground of the default face.
2036 :background the background color, or \"Transparent\".
2037 `default' means use the background of the default face.
2038 :scale a scaling factor for the size of the images.
2039 :html-foreground, :html-background, :html-scale
2040 the same numbers for HTML export.
2041 :matchers a list indicating which matchers should be used to
2042 find LaTeX fragments. Valid members of this list are:
2043 \"begin\" find environments
2044 \"$\" find math expressions surrounded by $...$
2045 \"$$\" find math expressions surrounded by $$....$$
2046 \"\\(\" find math expressions surrounded by \\(...\\)
2047 \"\\ [\" find math expressions surrounded by \\ [...\\]"
2048 :group 'org-latex
2049 :type 'plist)
2051 (defcustom org-format-latex-header "\\documentclass{article}
2052 \\usepackage{fullpage} % do not remove
2053 \\usepackage{amssymb}
2054 \\usepackage[usenames]{color}
2055 \\usepackage{amsmath}
2056 \\usepackage{latexsym}
2057 \\usepackage[mathscr]{eucal}
2058 \\pagestyle{empty} % do not remove"
2059 "The document header used for processing LaTeX fragments."
2060 :group 'org-latex
2061 :type 'string)
2064 (defgroup org-font-lock nil
2065 "Font-lock settings for highlighting in Org-mode."
2066 :tag "Org Font Lock"
2067 :group 'org)
2069 (defcustom org-level-color-stars-only nil
2070 "Non-nil means fontify only the stars in each headline.
2071 When nil, the entire headline is fontified.
2072 Changing it requires restart of `font-lock-mode' to become effective
2073 also in regions already fontified."
2074 :group 'org-font-lock
2075 :type 'boolean)
2077 (defcustom org-hide-leading-stars nil
2078 "Non-nil means, hide the first N-1 stars in a headline.
2079 This works by using the face `org-hide' for these stars. This
2080 face is white for a light background, and black for a dark
2081 background. You may have to customize the face `org-hide' to
2082 make this work.
2083 Changing it requires restart of `font-lock-mode' to become effective
2084 also in regions already fontified.
2085 You may also set this on a per-file basis by adding one of the following
2086 lines to the buffer:
2088 #+STARTUP: hidestars
2089 #+STARTUP: showstars"
2090 :group 'org-font-lock
2091 :type 'boolean)
2093 (defcustom org-fontify-done-headline nil
2094 "Non-nil means, change the face of a headline if it is marked DONE.
2095 Normally, only the TODO/DONE keyword indicates the state of a headline.
2096 When this is non-nil, the headline after the keyword is set to the
2097 `org-headline-done' as an additional indication."
2098 :group 'org-font-lock
2099 :type 'boolean)
2101 (defcustom org-fontify-emphasized-text t
2102 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2103 Changing this variable requires a restart of Emacs to take effect."
2104 :group 'org-font-lock
2105 :type 'boolean)
2107 (defcustom org-highlight-latex-fragments-and-specials nil
2108 "Non-nil means, fontify what is treated specially by the exporters."
2109 :group 'org-font-lock
2110 :type 'boolean)
2112 (defcustom org-hide-emphasis-markers nil
2113 "Non-nil mean font-lock should hide the emphasis marker characters."
2114 :group 'org-font-lock
2115 :type 'boolean)
2117 (defvar org-emph-re nil
2118 "Regular expression for matching emphasis.")
2119 (defvar org-verbatim-re nil
2120 "Regular expression for matching verbatim text.")
2121 (defvar org-emphasis-regexp-components) ; defined just below
2122 (defvar org-emphasis-alist) ; defined just below
2123 (defun org-set-emph-re (var val)
2124 "Set variable and compute the emphasis regular expression."
2125 (set var val)
2126 (when (and (boundp 'org-emphasis-alist)
2127 (boundp 'org-emphasis-regexp-components)
2128 org-emphasis-alist org-emphasis-regexp-components)
2129 (let* ((e org-emphasis-regexp-components)
2130 (pre (car e))
2131 (post (nth 1 e))
2132 (border (nth 2 e))
2133 (body (nth 3 e))
2134 (nl (nth 4 e))
2135 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2136 (body1 (concat body "*?"))
2137 (markers (mapconcat 'car org-emphasis-alist ""))
2138 (vmarkers (mapconcat
2139 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2140 org-emphasis-alist "")))
2141 ;; make sure special characters appear at the right position in the class
2142 (if (string-match "\\^" markers)
2143 (setq markers (concat (replace-match "" t t markers) "^")))
2144 (if (string-match "-" markers)
2145 (setq markers (concat (replace-match "" t t markers) "-")))
2146 (if (string-match "\\^" vmarkers)
2147 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2148 (if (string-match "-" vmarkers)
2149 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2150 (if (> nl 0)
2151 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2152 (int-to-string nl) "\\}")))
2153 ;; Make the regexp
2154 (setq org-emph-re
2155 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2156 "\\("
2157 "\\([" markers "]\\)"
2158 "\\("
2159 "[^" border "]\\|"
2160 "[^" border (if (and nil stacked) markers) "]"
2161 body1
2162 "[^" border (if (and nil stacked) markers) "]"
2163 "\\)"
2164 "\\3\\)"
2165 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2166 (setq org-verbatim-re
2167 (concat "\\([" pre "]\\|^\\)"
2168 "\\("
2169 "\\([" vmarkers "]\\)"
2170 "\\("
2171 "[^" border "]\\|"
2172 "[^" border "]"
2173 body1
2174 "[^" border "]"
2175 "\\)"
2176 "\\3\\)"
2177 "\\([" post "]\\|$\\)")))))
2179 (defcustom org-emphasis-regexp-components
2180 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2181 "Components used to build the regular expression for emphasis.
2182 This is a list with 6 entries. Terminology: In an emphasis string
2183 like \" *strong word* \", we call the initial space PREMATCH, the final
2184 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2185 and \"trong wor\" is the body. The different components in this variable
2186 specify what is allowed/forbidden in each part:
2188 pre Chars allowed as prematch. Beginning of line will be allowed too.
2189 post Chars allowed as postmatch. End of line will be allowed too.
2190 border The chars *forbidden* as border characters.
2191 body-regexp A regexp like \".\" to match a body character. Don't use
2192 non-shy groups here, and don't allow newline here.
2193 newline The maximum number of newlines allowed in an emphasis exp.
2195 Use customize to modify this, or restart Emacs after changing it."
2196 :group 'org-font-lock
2197 :set 'org-set-emph-re
2198 :type '(list
2199 (sexp :tag "Allowed chars in pre ")
2200 (sexp :tag "Allowed chars in post ")
2201 (sexp :tag "Forbidden chars in border ")
2202 (sexp :tag "Regexp for body ")
2203 (integer :tag "number of newlines allowed")
2204 (option (boolean :tag "Please ignore this button"))))
2206 (defcustom org-emphasis-alist
2207 `(("*" bold "<b>" "</b>")
2208 ("/" italic "<i>" "</i>")
2209 ("_" underline "<u>" "</u>")
2210 ("=" org-code "<code>" "</code>" verbatim)
2211 ("~" org-verbatim "" "" verbatim)
2212 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2213 "<del>" "</del>")
2215 "Special syntax for emphasized text.
2216 Text starting and ending with a special character will be emphasized, for
2217 example *bold*, _underlined_ and /italic/. This variable sets the marker
2218 characters, the face to be used by font-lock for highlighting in Org-mode
2219 Emacs buffers, and the HTML tags to be used for this.
2220 Use customize to modify this, or restart Emacs after changing it."
2221 :group 'org-font-lock
2222 :set 'org-set-emph-re
2223 :type '(repeat
2224 (list
2225 (string :tag "Marker character")
2226 (choice
2227 (face :tag "Font-lock-face")
2228 (plist :tag "Face property list"))
2229 (string :tag "HTML start tag")
2230 (string :tag "HTML end tag")
2231 (option (const verbatim)))))
2233 ;;; Miscellaneous options
2235 (defgroup org-completion nil
2236 "Completion in Org-mode."
2237 :tag "Org Completion"
2238 :group 'org)
2240 (defcustom org-completion-fallback-command 'hippie-expand
2241 "The expansion command called by \\[org-complete] in normal context.
2242 Normal means, no org-mode-specific context."
2243 :group 'org-completion
2244 :type 'function)
2246 ;;; Functions and variables from ther packages
2247 ;; Declared here to avoid compiler warnings
2249 ;; XEmacs only
2250 (defvar outline-mode-menu-heading)
2251 (defvar outline-mode-menu-show)
2252 (defvar outline-mode-menu-hide)
2253 (defvar zmacs-regions) ; XEmacs regions
2255 ;; Emacs only
2256 (defvar mark-active)
2258 ;; Various packages
2259 (declare-function calendar-absolute-from-iso "cal-iso" (date))
2260 (declare-function calendar-forward-day "cal-move" (arg))
2261 (declare-function calendar-goto-date "cal-move" (date))
2262 (declare-function calendar-goto-today "cal-move" ())
2263 (declare-function calendar-iso-from-absolute "cal-iso" (date))
2264 (defvar calc-embedded-close-formula)
2265 (defvar calc-embedded-open-formula)
2266 (declare-function cdlatex-tab "ext:cdlatex" ())
2267 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2268 (defvar font-lock-unfontify-region-function)
2269 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2270 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2271 (defvar iswitchb-temp-buflist)
2272 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2273 (declare-function org-agenda-skip "org-agenda" ())
2274 (declare-function org-format-agenda-item "org-agenda"
2275 (extra txt &optional category tags dotime noprefix remove-re))
2276 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2277 (declare-function org-agenda-change-all-lines "org-agenda"
2278 (newhead hdmarker &optional fixface))
2279 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2280 (declare-function org-agenda-maybe-redo "org-agenda" ())
2281 (declare-function org-agenda-save-markers-for-cut-and-paste "org-agenda"
2282 (beg end))
2283 (declare-function parse-time-string "parse-time" (string))
2284 (declare-function remember "remember" (&optional initial))
2285 (declare-function remember-buffer-desc "remember" ())
2286 (declare-function remember-finalize "remember" ())
2287 (defvar remember-save-after-remembering)
2288 (defvar remember-data-file)
2289 (defvar remember-register)
2290 (defvar remember-buffer)
2291 (defvar remember-handler-functions)
2292 (defvar remember-annotation-functions)
2293 (defvar texmathp-why)
2294 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2295 (declare-function table--at-cell-p "table" (position &optional object at-column))
2297 (defvar w3m-current-url)
2298 (defvar w3m-current-title)
2300 (defvar org-latex-regexps)
2302 ;;; Autoload and prepare some org modules
2304 ;; Some table stuff that needs to be defined here, because it is used
2305 ;; by the functions setting up org-mode or checking for table context.
2307 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2308 "Detects an org-type or table-type table.")
2309 (defconst org-table-line-regexp "^[ \t]*|"
2310 "Detects an org-type table line.")
2311 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2312 "Detects an org-type table line.")
2313 (defconst org-table-hline-regexp "^[ \t]*|-"
2314 "Detects an org-type table hline.")
2315 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2316 "Detects a table-type table hline.")
2317 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2318 "Searching from within a table (any type) this finds the first line
2319 outside the table.")
2321 ;; Autoload the functions in org-table.el that are needed by functions here.
2323 (eval-and-compile
2324 (org-autoload "org-table"
2325 '(org-table-align org-table-begin org-table-blank-field
2326 org-table-convert org-table-convert-region org-table-copy-down
2327 org-table-copy-region org-table-create
2328 org-table-create-or-convert-from-region
2329 org-table-create-with-table.el org-table-current-dline
2330 org-table-cut-region org-table-delete-column org-table-edit-field
2331 org-table-edit-formulas org-table-end org-table-eval-formula
2332 org-table-export org-table-field-info
2333 org-table-get-stored-formulas org-table-goto-column
2334 org-table-hline-and-move org-table-import org-table-insert-column
2335 org-table-insert-hline org-table-insert-row org-table-iterate
2336 org-table-justify-field-maybe org-table-kill-row
2337 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2338 org-table-move-column org-table-move-column-left
2339 org-table-move-column-right org-table-move-row
2340 org-table-move-row-down org-table-move-row-up
2341 org-table-next-field org-table-next-row org-table-paste-rectangle
2342 org-table-previous-field org-table-recalculate
2343 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2344 org-table-toggle-coordinate-overlays
2345 org-table-toggle-formula-debugger org-table-wrap-region
2346 orgtbl-mode turn-on-orgtbl)))
2348 (defun org-at-table-p (&optional table-type)
2349 "Return t if the cursor is inside an org-type table.
2350 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2351 (if org-enable-table-editor
2352 (save-excursion
2353 (beginning-of-line 1)
2354 (looking-at (if table-type org-table-any-line-regexp
2355 org-table-line-regexp)))
2356 nil))
2357 (defsubst org-table-p () (org-at-table-p))
2359 (defun org-at-table.el-p ()
2360 "Return t if and only if we are at a table.el table."
2361 (and (org-at-table-p 'any)
2362 (save-excursion
2363 (goto-char (org-table-begin 'any))
2364 (looking-at org-table1-hline-regexp))))
2365 (defun org-table-recognize-table.el ()
2366 "If there is a table.el table nearby, recognize it and move into it."
2367 (if org-table-tab-recognizes-table.el
2368 (if (org-at-table.el-p)
2369 (progn
2370 (beginning-of-line 1)
2371 (if (looking-at org-table-dataline-regexp)
2373 (if (looking-at org-table1-hline-regexp)
2374 (progn
2375 (beginning-of-line 2)
2376 (if (looking-at org-table-any-border-regexp)
2377 (beginning-of-line -1)))))
2378 (if (re-search-forward "|" (org-table-end t) t)
2379 (progn
2380 (require 'table)
2381 (if (table--at-cell-p (point))
2383 (message "recognizing table.el table...")
2384 (table-recognize-table)
2385 (message "recognizing table.el table...done")))
2386 (error "This should not happen..."))
2388 nil)
2389 nil))
2391 (defun org-at-table-hline-p ()
2392 "Return t if the cursor is inside a hline in a table."
2393 (if org-enable-table-editor
2394 (save-excursion
2395 (beginning-of-line 1)
2396 (looking-at org-table-hline-regexp))
2397 nil))
2399 (defvar org-table-clean-did-remove-column nil)
2401 (defun org-table-map-tables (function)
2402 "Apply FUNCTION to the start of all tables in the buffer."
2403 (save-excursion
2404 (save-restriction
2405 (widen)
2406 (goto-char (point-min))
2407 (while (re-search-forward org-table-any-line-regexp nil t)
2408 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2409 (beginning-of-line 1)
2410 (if (looking-at org-table-line-regexp)
2411 (save-excursion (funcall function)))
2412 (re-search-forward org-table-any-border-regexp nil 1))))
2413 (message "Mapping tables: done"))
2415 ;; Declare and autoload functions from org-exp.el
2417 (declare-function org-default-export-plist "org-exp")
2418 (declare-function org-infile-export-plist "org-exp")
2419 (declare-function org-get-current-options "org-exp")
2420 (eval-and-compile
2421 (org-autoload "org-exp"
2422 '(org-export org-export-as-ascii org-export-visible
2423 org-insert-export-options-template org-export-as-html-and-open
2424 org-export-as-html-batch org-export-as-html-to-buffer
2425 org-replace-region-by-html org-export-region-as-html
2426 org-export-as-html org-export-icalendar-this-file
2427 org-export-icalendar-all-agenda-files
2428 org-table-clean-before-export
2429 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2431 ;; Declare and autoload functions from org-exp.el
2433 (eval-and-compile
2434 (org-autoload "org-exp"
2435 '(org-agenda org-agenda-list org-search-view
2436 org-todo-list org-tags-view org-agenda-list-stuck-projects
2437 org-diary org-agenda-to-appt)))
2439 ;; Autoload org-remember
2441 (eval-and-compile
2442 (org-autoload "org-remember"
2443 '(org-remember-insinuate org-remember-annotation
2444 org-remember-apply-template org-remember org-remember-handler)))
2446 ;; Autoload org-clock.el
2449 (declare-function org-clock-save-markers-for-cut-and-paste "org-clock"
2450 (beg end))
2451 (declare-function org-update-mode-line "org-clock" ())
2452 (defvar org-clock-start-time)
2453 (defvar org-clock-marker (make-marker)
2454 "Marker recording the last clock-in.")
2456 (eval-and-compile
2457 (org-autoload
2458 "org-clock"
2459 '(org-clock-in org-clock-out org-clock-cancel
2460 org-clock-goto org-clock-sum org-clock-display
2461 org-remove-clock-overlays org-clock-report
2462 org-clocktable-shift org-dblock-write:clocktable
2463 org-get-clocktable)))
2465 (defun org-clock-update-time-maybe ()
2466 "If this is a CLOCK line, update it and return t.
2467 Otherwise, return nil."
2468 (interactive)
2469 (save-excursion
2470 (beginning-of-line 1)
2471 (skip-chars-forward " \t")
2472 (when (looking-at org-clock-string)
2473 (let ((re (concat "[ \t]*" org-clock-string
2474 " *[[<]\\([^]>]+\\)[]>]\\(-+[[<]\\([^]>]+\\)[]>]"
2475 "\\([ \t]*=>.*\\)?\\)?"))
2476 ts te h m s)
2477 (cond
2478 ((not (looking-at re))
2479 nil)
2480 ((not (match-end 2))
2481 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2482 (> org-clock-marker (point))
2483 (<= org-clock-marker (point-at-eol)))
2484 ;; The clock is running here
2485 (setq org-clock-start-time
2486 (apply 'encode-time
2487 (org-parse-time-string (match-string 1))))
2488 (org-update-mode-line)))
2490 (and (match-end 4) (delete-region (match-beginning 4) (match-end 4)))
2491 (end-of-line 1)
2492 (setq ts (match-string 1)
2493 te (match-string 3))
2494 (setq s (- (time-to-seconds
2495 (apply 'encode-time (org-parse-time-string te)))
2496 (time-to-seconds
2497 (apply 'encode-time (org-parse-time-string ts))))
2498 h (floor (/ s 3600))
2499 s (- s (* 3600 h))
2500 m (floor (/ s 60))
2501 s (- s (* 60 s)))
2502 (insert " => " (format "%2d:%02d" h m))
2503 t))))))
2505 (defun org-check-running-clock ()
2506 "Check if the current buffer contains the running clock.
2507 If yes, offer to stop it and to save the buffer with the changes."
2508 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2509 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2510 (buffer-name))))
2511 (org-clock-out)
2512 (when (y-or-n-p "Save changed buffer?")
2513 (save-buffer))))
2515 (defun org-clocktable-try-shift (dir n)
2516 "Check if this line starts a clock table, if yes, shift the time block."
2517 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2518 (org-clocktable-shift dir n)))
2520 ;; Autoload archiving code
2521 ;; The stuff that is needed for cycling and tags has to be defined here.
2523 (defgroup org-archive nil
2524 "Options concerning archiving in Org-mode."
2525 :tag "Org Archive"
2526 :group 'org-structure)
2528 (defcustom org-archive-location "%s_archive::"
2529 "The location where subtrees should be archived.
2531 Otherwise, the value of this variable is a string, consisting of two
2532 parts, separated by a double-colon.
2534 The first part is a file name - when omitted, archiving happens in the same
2535 file. %s will be replaced by the current file name (without directory part).
2536 Archiving to a different file is useful to keep archived entries from
2537 contributing to the Org-mode Agenda.
2539 The part after the double colon is a headline. The archived entries will be
2540 filed under that headline. When omitted, the subtrees are simply filed away
2541 at the end of the file, as top-level entries.
2543 Here are a few examples:
2544 \"%s_archive::\"
2545 If the current file is Projects.org, archive in file
2546 Projects.org_archive, as top-level trees. This is the default.
2548 \"::* Archived Tasks\"
2549 Archive in the current file, under the top-level headline
2550 \"* Archived Tasks\".
2552 \"~/org/archive.org::\"
2553 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2555 \"basement::** Finished Tasks\"
2556 Archive in file ./basement (relative path), as level 3 trees
2557 below the level 2 heading \"** Finished Tasks\".
2559 You may set this option on a per-file basis by adding to the buffer a
2560 line like
2562 #+ARCHIVE: basement::** Finished Tasks
2564 You may also define it locally for a subtree by setting an ARCHIVE property
2565 in the entry. If such a property is found in an entry, or anywhere up
2566 the hierarchy, it will be used."
2567 :group 'org-archive
2568 :type 'string)
2570 (defcustom org-archive-tag "ARCHIVE"
2571 "The tag that marks a subtree as archived.
2572 An archived subtree does not open during visibility cycling, and does
2573 not contribute to the agenda listings.
2574 After changing this, font-lock must be restarted in the relevant buffers to
2575 get the proper fontification."
2576 :group 'org-archive
2577 :group 'org-keywords
2578 :type 'string)
2580 (defcustom org-agenda-skip-archived-trees t
2581 "Non-nil means, the agenda will skip any items located in archived trees.
2582 An archived tree is a tree marked with the tag ARCHIVE. The use of this
2583 variable is no longer recommended, you should leave it at the value t.
2584 Instead, use the key `v' to cycle the archives-mode in the agenda."
2585 :group 'org-archive
2586 :group 'org-agenda-skip
2587 :type 'boolean)
2589 (defcustom org-cycle-open-archived-trees nil
2590 "Non-nil means, `org-cycle' will open archived trees.
2591 An archived tree is a tree marked with the tag ARCHIVE.
2592 When nil, archived trees will stay folded. You can still open them with
2593 normal outline commands like `show-all', but not with the cycling commands."
2594 :group 'org-archive
2595 :group 'org-cycle
2596 :type 'boolean)
2598 (defcustom org-sparse-tree-open-archived-trees nil
2599 "Non-nil means sparse tree construction shows matches in archived trees.
2600 When nil, matches in these trees are highlighted, but the trees are kept in
2601 collapsed state."
2602 :group 'org-archive
2603 :group 'org-sparse-trees
2604 :type 'boolean)
2606 (defun org-cycle-hide-archived-subtrees (state)
2607 "Re-hide all archived subtrees after a visibility state change."
2608 (when (and (not org-cycle-open-archived-trees)
2609 (not (memq state '(overview folded))))
2610 (save-excursion
2611 (let* ((globalp (memq state '(contents all)))
2612 (beg (if globalp (point-min) (point)))
2613 (end (if globalp (point-max) (org-end-of-subtree t))))
2614 (org-hide-archived-subtrees beg end)
2615 (goto-char beg)
2616 (if (looking-at (concat ".*:" org-archive-tag ":"))
2617 (message "%s" (substitute-command-keys
2618 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2620 (defun org-force-cycle-archived ()
2621 "Cycle subtree even if it is archived."
2622 (interactive)
2623 (setq this-command 'org-cycle)
2624 (let ((org-cycle-open-archived-trees t))
2625 (call-interactively 'org-cycle)))
2627 (defun org-hide-archived-subtrees (beg end)
2628 "Re-hide all archived subtrees after a visibility state change."
2629 (save-excursion
2630 (let* ((re (concat ":" org-archive-tag ":")))
2631 (goto-char beg)
2632 (while (re-search-forward re end t)
2633 (and (org-on-heading-p) (hide-subtree))
2634 (org-end-of-subtree t)))))
2636 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2638 (eval-and-compile
2639 (org-autoload "org-archive"
2640 '(org-add-archive-files org-archive-subtree
2641 org-archive-to-archive-sibling org-toggle-archive-tag)))
2643 ;; Autoload Column View Code
2645 (declare-function org-columns-number-to-string "org-colview")
2646 (declare-function org-columns-get-format-and-top-level "org-colview")
2647 (declare-function org-columns-compute "org-colview")
2649 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2650 '(org-columns-number-to-string org-columns-get-format-and-top-level
2651 org-columns-compute org-agenda-columns org-columns-remove-overlays
2652 org-columns org-insert-columns-dblock org-dblock-write:columnview))
2654 ;; Autoload ID code
2656 (org-autoload "org-id"
2657 '(org-id-get-create org-id-new org-id-copy org-id-get
2658 org-id-get-with-outline-path-completion
2659 org-id-get-with-outline-drilling
2660 org-id-goto org-id-find))
2662 ;;; Variables for pre-computed regular expressions, all buffer local
2664 (defvar org-drawer-regexp nil
2665 "Matches first line of a hidden block.")
2666 (make-variable-buffer-local 'org-drawer-regexp)
2667 (defvar org-todo-regexp nil
2668 "Matches any of the TODO state keywords.")
2669 (make-variable-buffer-local 'org-todo-regexp)
2670 (defvar org-not-done-regexp nil
2671 "Matches any of the TODO state keywords except the last one.")
2672 (make-variable-buffer-local 'org-not-done-regexp)
2673 (defvar org-todo-line-regexp nil
2674 "Matches a headline and puts TODO state into group 2 if present.")
2675 (make-variable-buffer-local 'org-todo-line-regexp)
2676 (defvar org-complex-heading-regexp nil
2677 "Matches a headline and puts everything into groups:
2678 group 1: the stars
2679 group 2: The todo keyword, maybe
2680 group 3: Priority cookie
2681 group 4: True headline
2682 group 5: Tags")
2683 (make-variable-buffer-local 'org-complex-heading-regexp)
2684 (defvar org-todo-line-tags-regexp nil
2685 "Matches a headline and puts TODO state into group 2 if present.
2686 Also put tags into group 4 if tags are present.")
2687 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2688 (defvar org-nl-done-regexp nil
2689 "Matches newline followed by a headline with the DONE keyword.")
2690 (make-variable-buffer-local 'org-nl-done-regexp)
2691 (defvar org-looking-at-done-regexp nil
2692 "Matches the DONE keyword a point.")
2693 (make-variable-buffer-local 'org-looking-at-done-regexp)
2694 (defvar org-ds-keyword-length 12
2695 "Maximum length of the Deadline and SCHEDULED keywords.")
2696 (make-variable-buffer-local 'org-ds-keyword-length)
2697 (defvar org-deadline-regexp nil
2698 "Matches the DEADLINE keyword.")
2699 (make-variable-buffer-local 'org-deadline-regexp)
2700 (defvar org-deadline-time-regexp nil
2701 "Matches the DEADLINE keyword together with a time stamp.")
2702 (make-variable-buffer-local 'org-deadline-time-regexp)
2703 (defvar org-deadline-line-regexp nil
2704 "Matches the DEADLINE keyword and the rest of the line.")
2705 (make-variable-buffer-local 'org-deadline-line-regexp)
2706 (defvar org-scheduled-regexp nil
2707 "Matches the SCHEDULED keyword.")
2708 (make-variable-buffer-local 'org-scheduled-regexp)
2709 (defvar org-scheduled-time-regexp nil
2710 "Matches the SCHEDULED keyword together with a time stamp.")
2711 (make-variable-buffer-local 'org-scheduled-time-regexp)
2712 (defvar org-closed-time-regexp nil
2713 "Matches the CLOSED keyword together with a time stamp.")
2714 (make-variable-buffer-local 'org-closed-time-regexp)
2716 (defvar org-keyword-time-regexp nil
2717 "Matches any of the 4 keywords, together with the time stamp.")
2718 (make-variable-buffer-local 'org-keyword-time-regexp)
2719 (defvar org-keyword-time-not-clock-regexp nil
2720 "Matches any of the 3 keywords, together with the time stamp.")
2721 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2722 (defvar org-maybe-keyword-time-regexp nil
2723 "Matches a timestamp, possibly preceeded by a keyword.")
2724 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2725 (defvar org-planning-or-clock-line-re nil
2726 "Matches a line with planning or clock info.")
2727 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2729 (defconst org-plain-time-of-day-regexp
2730 (concat
2731 "\\(\\<[012]?[0-9]"
2732 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2733 "\\(--?"
2734 "\\(\\<[012]?[0-9]"
2735 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2736 "\\)?")
2737 "Regular expression to match a plain time or time range.
2738 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2739 groups carry important information:
2740 0 the full match
2741 1 the first time, range or not
2742 8 the second time, if it is a range.")
2744 (defconst org-plain-time-extension-regexp
2745 (concat
2746 "\\(\\<[012]?[0-9]"
2747 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2748 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2749 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2750 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2751 groups carry important information:
2752 0 the full match
2753 7 hours of duration
2754 9 minutes of duration")
2756 (defconst org-stamp-time-of-day-regexp
2757 (concat
2758 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2759 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2760 "\\(--?"
2761 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2762 "Regular expression to match a timestamp time or time range.
2763 After a match, the following groups carry important information:
2764 0 the full match
2765 1 date plus weekday, for backreferencing to make sure both times on same day
2766 2 the first time, range or not
2767 4 the second time, if it is a range.")
2769 (defconst org-startup-options
2770 '(("fold" org-startup-folded t)
2771 ("overview" org-startup-folded t)
2772 ("nofold" org-startup-folded nil)
2773 ("showall" org-startup-folded nil)
2774 ("content" org-startup-folded content)
2775 ("hidestars" org-hide-leading-stars t)
2776 ("showstars" org-hide-leading-stars nil)
2777 ("odd" org-odd-levels-only t)
2778 ("oddeven" org-odd-levels-only nil)
2779 ("align" org-startup-align-all-tables t)
2780 ("noalign" org-startup-align-all-tables nil)
2781 ("customtime" org-display-custom-times t)
2782 ("logdone" org-log-done time)
2783 ("lognotedone" org-log-done note)
2784 ("nologdone" org-log-done nil)
2785 ("lognoteclock-out" org-log-note-clock-out t)
2786 ("nolognoteclock-out" org-log-note-clock-out nil)
2787 ("logrepeat" org-log-repeat state)
2788 ("lognoterepeat" org-log-repeat note)
2789 ("nologrepeat" org-log-repeat nil)
2790 ("constcgs" constants-unit-system cgs)
2791 ("constSI" constants-unit-system SI))
2792 "Variable associated with STARTUP options for org-mode.
2793 Each element is a list of three items: The startup options as written
2794 in the #+STARTUP line, the corresponding variable, and the value to
2795 set this variable to if the option is found. An optional forth element PUSH
2796 means to push this value onto the list in the variable.")
2798 (defun org-set-regexps-and-options ()
2799 "Precompute regular expressions for current buffer."
2800 (when (org-mode-p)
2801 (org-set-local 'org-todo-kwd-alist nil)
2802 (org-set-local 'org-todo-key-alist nil)
2803 (org-set-local 'org-todo-key-trigger nil)
2804 (org-set-local 'org-todo-keywords-1 nil)
2805 (org-set-local 'org-done-keywords nil)
2806 (org-set-local 'org-todo-heads nil)
2807 (org-set-local 'org-todo-sets nil)
2808 (org-set-local 'org-todo-log-states nil)
2809 (org-set-local 'org-file-properties nil)
2810 (org-set-local 'org-file-tags nil)
2811 (let ((re (org-make-options-regexp
2812 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2813 "STARTUP" "ARCHIVE" "FILETAGS" "TAGS" "LINK" "PRIORITIES"
2814 "CONSTANTS" "PROPERTY" "DRAWERS" "SETUPFILE")))
2815 (splitre "[ \t]+")
2816 kwds kws0 kwsa key log value cat arch tags const links hw dws
2817 tail sep kws1 prio props ftags drawers
2818 ext-setup-or-nil setup-contents (start 0))
2819 (save-excursion
2820 (save-restriction
2821 (widen)
2822 (goto-char (point-min))
2823 (while (or (and ext-setup-or-nil
2824 (string-match re ext-setup-or-nil start)
2825 (setq start (match-end 0)))
2826 (and (setq ext-setup-or-nil nil start 0)
2827 (re-search-forward re nil t)))
2828 (setq key (upcase (match-string 1 ext-setup-or-nil))
2829 value (org-match-string-no-properties 2 ext-setup-or-nil))
2830 (cond
2831 ((equal key "CATEGORY")
2832 (if (string-match "[ \t]+$" value)
2833 (setq value (replace-match "" t t value)))
2834 (setq cat value))
2835 ((member key '("SEQ_TODO" "TODO"))
2836 (push (cons 'sequence (org-split-string value splitre)) kwds))
2837 ((equal key "TYP_TODO")
2838 (push (cons 'type (org-split-string value splitre)) kwds))
2839 ((equal key "TAGS")
2840 (setq tags (append tags (org-split-string value splitre))))
2841 ((equal key "COLUMNS")
2842 (org-set-local 'org-columns-default-format value))
2843 ((equal key "LINK")
2844 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2845 (push (cons (match-string 1 value)
2846 (org-trim (match-string 2 value)))
2847 links)))
2848 ((equal key "PRIORITIES")
2849 (setq prio (org-split-string value " +")))
2850 ((equal key "PROPERTY")
2851 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2852 (push (cons (match-string 1 value) (match-string 2 value))
2853 props)))
2854 ((equal key "FILETAGS")
2855 (when (string-match "\\S-" value)
2856 (setq ftags
2857 (append
2858 ftags
2859 (apply 'append
2860 (mapcar (lambda (x) (org-split-string x ":"))
2861 (org-split-string value)))))))
2862 ((equal key "DRAWERS")
2863 (setq drawers (org-split-string value splitre)))
2864 ((equal key "CONSTANTS")
2865 (setq const (append const (org-split-string value splitre))))
2866 ((equal key "STARTUP")
2867 (let ((opts (org-split-string value splitre))
2868 l var val)
2869 (while (setq l (pop opts))
2870 (when (setq l (assoc l org-startup-options))
2871 (setq var (nth 1 l) val (nth 2 l))
2872 (if (not (nth 3 l))
2873 (set (make-local-variable var) val)
2874 (if (not (listp (symbol-value var)))
2875 (set (make-local-variable var) nil))
2876 (set (make-local-variable var) (symbol-value var))
2877 (add-to-list var val))))))
2878 ((equal key "ARCHIVE")
2879 (string-match " *$" value)
2880 (setq arch (replace-match "" t t value))
2881 (remove-text-properties 0 (length arch)
2882 '(face t fontified t) arch))
2883 ((equal key "SETUPFILE")
2884 (setq setup-contents (org-file-contents
2885 (expand-file-name
2886 (org-remove-double-quotes value))
2887 'noerror))
2888 (if (not ext-setup-or-nil)
2889 (setq ext-setup-or-nil setup-contents start 0)
2890 (setq ext-setup-or-nil
2891 (concat (substring ext-setup-or-nil 0 start)
2892 "\n" setup-contents "\n"
2893 (substring ext-setup-or-nil start)))))
2894 ))))
2895 (when cat
2896 (org-set-local 'org-category (intern cat))
2897 (push (cons "CATEGORY" cat) props))
2898 (when prio
2899 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2900 (setq prio (mapcar 'string-to-char prio))
2901 (org-set-local 'org-highest-priority (nth 0 prio))
2902 (org-set-local 'org-lowest-priority (nth 1 prio))
2903 (org-set-local 'org-default-priority (nth 2 prio)))
2904 (and props (org-set-local 'org-file-properties (nreverse props)))
2905 (and ftags (org-set-local 'org-file-tags ftags))
2906 (and drawers (org-set-local 'org-drawers drawers))
2907 (and arch (org-set-local 'org-archive-location arch))
2908 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2909 ;; Process the TODO keywords
2910 (unless kwds
2911 ;; Use the global values as if they had been given locally.
2912 (setq kwds (default-value 'org-todo-keywords))
2913 (if (stringp (car kwds))
2914 (setq kwds (list (cons org-todo-interpretation
2915 (default-value 'org-todo-keywords)))))
2916 (setq kwds (reverse kwds)))
2917 (setq kwds (nreverse kwds))
2918 (let (inter kws kw)
2919 (while (setq kws (pop kwds))
2920 (setq inter (pop kws) sep (member "|" kws)
2921 kws0 (delete "|" (copy-sequence kws))
2922 kwsa nil
2923 kws1 (mapcar
2924 (lambda (x)
2925 ;; 1 2
2926 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2927 (progn
2928 (setq kw (match-string 1 x)
2929 key (and (match-end 2) (match-string 2 x))
2930 log (org-extract-log-state-settings x))
2931 (push (cons kw (and key (string-to-char key))) kwsa)
2932 (and log (push log org-todo-log-states))
2934 (error "Invalid TODO keyword %s" x)))
2935 kws0)
2936 kwsa (if kwsa (append '((:startgroup))
2937 (nreverse kwsa)
2938 '((:endgroup))))
2939 hw (car kws1)
2940 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2941 tail (list inter hw (car dws) (org-last dws)))
2942 (add-to-list 'org-todo-heads hw 'append)
2943 (push kws1 org-todo-sets)
2944 (setq org-done-keywords (append org-done-keywords dws nil))
2945 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2946 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2947 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2948 (setq org-todo-sets (nreverse org-todo-sets)
2949 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2950 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2951 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2952 ;; Process the constants
2953 (when const
2954 (let (e cst)
2955 (while (setq e (pop const))
2956 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2957 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2958 (setq org-table-formula-constants-local cst)))
2960 ;; Process the tags.
2961 (when tags
2962 (let (e tgs)
2963 (while (setq e (pop tags))
2964 (cond
2965 ((equal e "{") (push '(:startgroup) tgs))
2966 ((equal e "}") (push '(:endgroup) tgs))
2967 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2968 (push (cons (match-string 1 e)
2969 (string-to-char (match-string 2 e)))
2970 tgs))
2971 (t (push (list e) tgs))))
2972 (org-set-local 'org-tag-alist nil)
2973 (while (setq e (pop tgs))
2974 (or (and (stringp (car e))
2975 (assoc (car e) org-tag-alist))
2976 (push e org-tag-alist)))))
2978 ;; Compute the regular expressions and other local variables
2979 (if (not org-done-keywords)
2980 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2981 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2982 (length org-scheduled-string)
2983 (length org-clock-string)
2984 (length org-closed-string)))
2985 org-drawer-regexp
2986 (concat "^[ \t]*:\\("
2987 (mapconcat 'regexp-quote org-drawers "\\|")
2988 "\\):[ \t]*$")
2989 org-not-done-keywords
2990 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2991 org-todo-regexp
2992 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2993 "\\|") "\\)\\>")
2994 org-not-done-regexp
2995 (concat "\\<\\("
2996 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2997 "\\)\\>")
2998 org-todo-line-regexp
2999 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3000 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3001 "\\)\\>\\)?[ \t]*\\(.*\\)")
3002 org-complex-heading-regexp
3003 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
3004 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3005 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
3006 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
3007 org-nl-done-regexp
3008 (concat "\n\\*+[ \t]+"
3009 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
3010 "\\)" "\\>")
3011 org-todo-line-tags-regexp
3012 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
3013 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
3014 (org-re
3015 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
3016 org-looking-at-done-regexp
3017 (concat "^" "\\(?:"
3018 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
3019 "\\>")
3020 org-deadline-regexp (concat "\\<" org-deadline-string)
3021 org-deadline-time-regexp
3022 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
3023 org-deadline-line-regexp
3024 (concat "\\<\\(" org-deadline-string "\\).*")
3025 org-scheduled-regexp
3026 (concat "\\<" org-scheduled-string)
3027 org-scheduled-time-regexp
3028 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
3029 org-closed-time-regexp
3030 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
3031 org-keyword-time-regexp
3032 (concat "\\<\\(" org-scheduled-string
3033 "\\|" org-deadline-string
3034 "\\|" org-closed-string
3035 "\\|" org-clock-string "\\)"
3036 " *[[<]\\([^]>]+\\)[]>]")
3037 org-keyword-time-not-clock-regexp
3038 (concat "\\<\\(" org-scheduled-string
3039 "\\|" org-deadline-string
3040 "\\|" org-closed-string
3041 "\\)"
3042 " *[[<]\\([^]>]+\\)[]>]")
3043 org-maybe-keyword-time-regexp
3044 (concat "\\(\\<\\(" org-scheduled-string
3045 "\\|" org-deadline-string
3046 "\\|" org-closed-string
3047 "\\|" org-clock-string "\\)\\)?"
3048 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
3049 org-planning-or-clock-line-re
3050 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
3051 "\\|" org-deadline-string
3052 "\\|" org-closed-string "\\|" org-clock-string
3053 "\\)\\>\\)")
3055 (org-compute-latex-and-specials-regexp)
3056 (org-set-font-lock-defaults))))
3058 (defun org-file-contents (file &optional noerror)
3059 "Return the contents of FILE, as a string."
3060 (if (or (not file)
3061 (not (file-readable-p file)))
3062 (if noerror
3063 (progn
3064 (message "Cannot read file %s" file)
3065 (ding) (sit-for 2)
3067 (error "Cannot read file %s" file))
3068 (with-temp-buffer
3069 (insert-file-contents file)
3070 (buffer-string))))
3072 (defun org-extract-log-state-settings (x)
3073 "Extract the log state setting from a TODO keyword string.
3074 This will extract info from a string like \"WAIT(w@/!)\"."
3075 (let (kw key log1 log2)
3076 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
3077 (setq kw (match-string 1 x)
3078 key (and (match-end 2) (match-string 2 x))
3079 log1 (and (match-end 3) (match-string 3 x))
3080 log2 (and (match-end 4) (match-string 4 x)))
3081 (and (or log1 log2)
3082 (list kw
3083 (and log1 (if (equal log1 "!") 'time 'note))
3084 (and log2 (if (equal log2 "!") 'time 'note)))))))
3086 (defun org-remove-keyword-keys (list)
3087 "Remove a pair of parenthesis at the end of each string in LIST."
3088 (mapcar (lambda (x)
3089 (if (string-match "(.*)$" x)
3090 (substring x 0 (match-beginning 0))
3092 list))
3094 ;; FIXME: this could be done much better, using second characters etc.
3095 (defun org-assign-fast-keys (alist)
3096 "Assign fast keys to a keyword-key alist.
3097 Respect keys that are already there."
3098 (let (new e k c c1 c2 (char ?a))
3099 (while (setq e (pop alist))
3100 (cond
3101 ((equal e '(:startgroup)) (push e new))
3102 ((equal e '(:endgroup)) (push e new))
3104 (setq k (car e) c2 nil)
3105 (if (cdr e)
3106 (setq c (cdr e))
3107 ;; automatically assign a character.
3108 (setq c1 (string-to-char
3109 (downcase (substring
3110 k (if (= (string-to-char k) ?@) 1 0)))))
3111 (if (or (rassoc c1 new) (rassoc c1 alist))
3112 (while (or (rassoc char new) (rassoc char alist))
3113 (setq char (1+ char)))
3114 (setq c2 c1))
3115 (setq c (or c2 char)))
3116 (push (cons k c) new))))
3117 (nreverse new)))
3119 ;;; Some variables used in various places
3121 (defvar org-window-configuration nil
3122 "Used in various places to store a window configuration.")
3123 (defvar org-finish-function nil
3124 "Function to be called when `C-c C-c' is used.
3125 This is for getting out of special buffers like remember.")
3128 ;; FIXME: Occasionally check by commenting these, to make sure
3129 ;; no other functions uses these, forgetting to let-bind them.
3130 (defvar entry)
3131 (defvar state)
3132 (defvar last-state)
3133 (defvar date)
3134 (defvar description)
3136 ;; Defined somewhere in this file, but used before definition.
3137 (defvar org-html-entities)
3138 (defvar org-struct-menu)
3139 (defvar org-org-menu)
3140 (defvar org-tbl-menu)
3141 (defvar org-agenda-keymap)
3143 ;;;; Define the Org-mode
3145 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
3146 (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."))
3149 ;; We use a before-change function to check if a table might need
3150 ;; an update.
3151 (defvar org-table-may-need-update t
3152 "Indicates that a table might need an update.
3153 This variable is set by `org-before-change-function'.
3154 `org-table-align' sets it back to nil.")
3155 (defun org-before-change-function (beg end)
3156 "Every change indicates that a table might need an update."
3157 (setq org-table-may-need-update t))
3158 (defvar org-mode-map)
3159 (defvar org-mode-hook nil)
3160 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3161 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3162 (defvar org-table-buffer-is-an nil)
3163 (defconst org-outline-regexp "\\*+ ")
3165 ;;;###autoload
3166 (define-derived-mode org-mode outline-mode "Org"
3167 "Outline-based notes management and organizer, alias
3168 \"Carsten's outline-mode for keeping track of everything.\"
3170 Org-mode develops organizational tasks around a NOTES file which
3171 contains information about projects as plain text. Org-mode is
3172 implemented on top of outline-mode, which is ideal to keep the content
3173 of large files well structured. It supports ToDo items, deadlines and
3174 time stamps, which magically appear in the diary listing of the Emacs
3175 calendar. Tables are easily created with a built-in table editor.
3176 Plain text URL-like links connect to websites, emails (VM), Usenet
3177 messages (Gnus), BBDB entries, and any files related to the project.
3178 For printing and sharing of notes, an Org-mode file (or a part of it)
3179 can be exported as a structured ASCII or HTML file.
3181 The following commands are available:
3183 \\{org-mode-map}"
3185 ;; Get rid of Outline menus, they are not needed
3186 ;; Need to do this here because define-derived-mode sets up
3187 ;; the keymap so late. Still, it is a waste to call this each time
3188 ;; we switch another buffer into org-mode.
3189 (if (featurep 'xemacs)
3190 (when (boundp 'outline-mode-menu-heading)
3191 ;; Assume this is Greg's port, it used easymenu
3192 (easy-menu-remove outline-mode-menu-heading)
3193 (easy-menu-remove outline-mode-menu-show)
3194 (easy-menu-remove outline-mode-menu-hide))
3195 (define-key org-mode-map [menu-bar headings] 'undefined)
3196 (define-key org-mode-map [menu-bar hide] 'undefined)
3197 (define-key org-mode-map [menu-bar show] 'undefined))
3199 (org-load-modules-maybe)
3200 (easy-menu-add org-org-menu)
3201 (easy-menu-add org-tbl-menu)
3202 (org-install-agenda-files-menu)
3203 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3204 (org-add-to-invisibility-spec '(org-cwidth))
3205 (when (featurep 'xemacs)
3206 (org-set-local 'line-move-ignore-invisible t))
3207 (org-set-local 'outline-regexp org-outline-regexp)
3208 (org-set-local 'outline-level 'org-outline-level)
3209 (when (and org-ellipsis
3210 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3211 (fboundp 'make-glyph-code))
3212 (unless org-display-table
3213 (setq org-display-table (make-display-table)))
3214 (set-display-table-slot
3215 org-display-table 4
3216 (vconcat (mapcar
3217 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3218 org-ellipsis)))
3219 (if (stringp org-ellipsis) org-ellipsis "..."))))
3220 (setq buffer-display-table org-display-table))
3221 (org-set-regexps-and-options)
3222 ;; Calc embedded
3223 (org-set-local 'calc-embedded-open-mode "# ")
3224 (modify-syntax-entry ?# "<")
3225 (modify-syntax-entry ?@ "w")
3226 (if org-startup-truncated (setq truncate-lines t))
3227 (org-set-local 'font-lock-unfontify-region-function
3228 'org-unfontify-region)
3229 ;; Activate before-change-function
3230 (org-set-local 'org-table-may-need-update t)
3231 (org-add-hook 'before-change-functions 'org-before-change-function nil
3232 'local)
3233 ;; Check for running clock before killing a buffer
3234 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3235 ;; Paragraphs and auto-filling
3236 (org-set-autofill-regexps)
3237 (setq indent-line-function 'org-indent-line-function)
3238 (org-update-radio-target-regexp)
3240 ;; Comment characters
3241 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3242 (org-set-local 'comment-padding " ")
3244 ;; Align options lines
3245 (org-set-local
3246 'align-mode-rules-list
3247 '((org-in-buffer-settings
3248 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3249 (modes . '(org-mode)))))
3251 ;; Imenu
3252 (org-set-local 'imenu-create-index-function
3253 'org-imenu-get-tree)
3255 ;; Make isearch reveal context
3256 (if (or (featurep 'xemacs)
3257 (not (boundp 'outline-isearch-open-invisible-function)))
3258 ;; Emacs 21 and XEmacs make use of the hook
3259 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3260 ;; Emacs 22 deals with this through a special variable
3261 (org-set-local 'outline-isearch-open-invisible-function
3262 (lambda (&rest ignore) (org-show-context 'isearch))))
3264 ;; If empty file that did not turn on org-mode automatically, make it to.
3265 (if (and org-insert-mode-line-in-empty-file
3266 (interactive-p)
3267 (= (point-min) (point-max)))
3268 (insert "# -*- mode: org -*-\n\n"))
3270 (unless org-inhibit-startup
3271 (when org-startup-align-all-tables
3272 (let ((bmp (buffer-modified-p)))
3273 (org-table-map-tables 'org-table-align)
3274 (set-buffer-modified-p bmp)))
3275 (org-set-startup-visibility)))
3277 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3279 (defun org-current-time ()
3280 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3281 (if (> (car org-time-stamp-rounding-minutes) 1)
3282 (let ((r (car org-time-stamp-rounding-minutes))
3283 (time (decode-time)))
3284 (apply 'encode-time
3285 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3286 (nthcdr 2 time))))
3287 (current-time)))
3289 ;;;; Font-Lock stuff, including the activators
3291 (defvar org-mouse-map (make-sparse-keymap))
3292 (org-defkey org-mouse-map
3293 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3294 (org-defkey org-mouse-map
3295 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3296 (when org-mouse-1-follows-link
3297 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3298 (when org-tab-follows-link
3299 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3300 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3301 (when org-return-follows-link
3302 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3303 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3305 (require 'font-lock)
3307 (defconst org-non-link-chars "]\t\n\r<>")
3308 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3309 "shell" "elisp"))
3310 (defvar org-link-types-re nil
3311 "Matches a link that has a url-like prefix like \"http:\"")
3312 (defvar org-link-re-with-space nil
3313 "Matches a link with spaces, optional angular brackets around it.")
3314 (defvar org-link-re-with-space2 nil
3315 "Matches a link with spaces, optional angular brackets around it.")
3316 (defvar org-angle-link-re nil
3317 "Matches link with angular brackets, spaces are allowed.")
3318 (defvar org-plain-link-re nil
3319 "Matches plain link, without spaces.")
3320 (defvar org-bracket-link-regexp nil
3321 "Matches a link in double brackets.")
3322 (defvar org-bracket-link-analytic-regexp nil
3323 "Regular expression used to analyze links.
3324 Here is what the match groups contain after a match:
3325 1: http:
3326 2: http
3327 3: path
3328 4: [desc]
3329 5: desc")
3330 (defvar org-any-link-re nil
3331 "Regular expression matching any link.")
3333 (defun org-make-link-regexps ()
3334 "Update the link regular expressions.
3335 This should be called after the variable `org-link-types' has changed."
3336 (setq org-link-types-re
3337 (concat
3338 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3339 org-link-re-with-space
3340 (concat
3341 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3342 "\\([^" org-non-link-chars " ]"
3343 "[^" org-non-link-chars "]*"
3344 "[^" org-non-link-chars " ]\\)>?")
3345 org-link-re-with-space2
3346 (concat
3347 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3348 "\\([^" org-non-link-chars " ]"
3349 "[^]\t\n\r]*"
3350 "[^" org-non-link-chars " ]\\)>?")
3351 org-angle-link-re
3352 (concat
3353 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3354 "\\([^" org-non-link-chars " ]"
3355 "[^" org-non-link-chars "]*"
3356 "\\)>")
3357 org-plain-link-re
3358 (concat
3359 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3360 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3361 org-bracket-link-regexp
3362 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3363 org-bracket-link-analytic-regexp
3364 (concat
3365 "\\[\\["
3366 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3367 "\\([^]]+\\)"
3368 "\\]"
3369 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3370 "\\]")
3371 org-any-link-re
3372 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3373 org-angle-link-re "\\)\\|\\("
3374 org-plain-link-re "\\)")))
3376 (org-make-link-regexps)
3378 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3379 "Regular expression for fast time stamp matching.")
3380 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3381 "Regular expression for fast time stamp matching.")
3382 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3383 "Regular expression matching time strings for analysis.
3384 This one does not require the space after the date, so it can be used
3385 on a string that terminates immediately after the date.")
3386 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3387 "Regular expression matching time strings for analysis.")
3388 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3389 "Regular expression matching time stamps, with groups.")
3390 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3391 "Regular expression matching time stamps (also [..]), with groups.")
3392 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3393 "Regular expression matching a time stamp range.")
3394 (defconst org-tr-regexp-both
3395 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3396 "Regular expression matching a time stamp range.")
3397 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3398 org-ts-regexp "\\)?")
3399 "Regular expression matching a time stamp or time stamp range.")
3400 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3401 org-ts-regexp-both "\\)?")
3402 "Regular expression matching a time stamp or time stamp range.
3403 The time stamps may be either active or inactive.")
3405 (defvar org-emph-face nil)
3407 (defun org-do-emphasis-faces (limit)
3408 "Run through the buffer and add overlays to links."
3409 (let (rtn)
3410 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3411 (if (not (= (char-after (match-beginning 3))
3412 (char-after (match-beginning 4))))
3413 (progn
3414 (setq rtn t)
3415 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3416 'face
3417 (nth 1 (assoc (match-string 3)
3418 org-emphasis-alist)))
3419 (add-text-properties (match-beginning 2) (match-end 2)
3420 '(font-lock-multiline t))
3421 (when org-hide-emphasis-markers
3422 (add-text-properties (match-end 4) (match-beginning 5)
3423 '(invisible org-link))
3424 (add-text-properties (match-beginning 3) (match-end 3)
3425 '(invisible org-link)))))
3426 (backward-char 1))
3427 rtn))
3429 (defun org-emphasize (&optional char)
3430 "Insert or change an emphasis, i.e. a font like bold or italic.
3431 If there is an active region, change that region to a new emphasis.
3432 If there is no region, just insert the marker characters and position
3433 the cursor between them.
3434 CHAR should be either the marker character, or the first character of the
3435 HTML tag associated with that emphasis. If CHAR is a space, the means
3436 to remove the emphasis of the selected region.
3437 If char is not given (for example in an interactive call) it
3438 will be prompted for."
3439 (interactive)
3440 (let ((eal org-emphasis-alist) e det
3441 (erc org-emphasis-regexp-components)
3442 (prompt "")
3443 (string "") beg end move tag c s)
3444 (if (org-region-active-p)
3445 (setq beg (region-beginning) end (region-end)
3446 string (buffer-substring beg end))
3447 (setq move t))
3449 (while (setq e (pop eal))
3450 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3451 c (aref tag 0))
3452 (push (cons c (string-to-char (car e))) det)
3453 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3454 (substring tag 1)))))
3455 (unless char
3456 (message "%s" (concat "Emphasis marker or tag:" prompt))
3457 (setq char (read-char-exclusive)))
3458 (setq char (or (cdr (assoc char det)) char))
3459 (if (equal char ?\ )
3460 (setq s "" move nil)
3461 (unless (assoc (char-to-string char) org-emphasis-alist)
3462 (error "No such emphasis marker: \"%c\"" char))
3463 (setq s (char-to-string char)))
3464 (while (and (> (length string) 1)
3465 (equal (substring string 0 1) (substring string -1))
3466 (assoc (substring string 0 1) org-emphasis-alist))
3467 (setq string (substring string 1 -1)))
3468 (setq string (concat s string s))
3469 (if beg (delete-region beg end))
3470 (unless (or (bolp)
3471 (string-match (concat "[" (nth 0 erc) "\n]")
3472 (char-to-string (char-before (point)))))
3473 (insert " "))
3474 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3475 (char-to-string (char-after (point))))
3476 (insert " ") (backward-char 1))
3477 (insert string)
3478 (and move (backward-char 1))))
3480 (defconst org-nonsticky-props
3481 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3484 (defun org-activate-plain-links (limit)
3485 "Run through the buffer and add overlays to links."
3486 (catch 'exit
3487 (let (f)
3488 (while (re-search-forward org-plain-link-re limit t)
3489 (setq f (get-text-property (match-beginning 0) 'face))
3490 (if (or (eq f 'org-tag)
3491 (and (listp f) (memq 'org-tag f)))
3493 (add-text-properties (match-beginning 0) (match-end 0)
3494 (list 'mouse-face 'highlight
3495 'rear-nonsticky org-nonsticky-props
3496 'keymap org-mouse-map
3498 (throw 'exit t))))))
3500 (defun org-activate-code (limit)
3501 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3502 (unless (get-text-property (match-beginning 1) 'face)
3503 (remove-text-properties (match-beginning 0) (match-end 0)
3504 '(display t invisible t intangible t))
3505 t)))
3507 (defun org-activate-angle-links (limit)
3508 "Run through the buffer and add overlays to links."
3509 (if (re-search-forward org-angle-link-re limit t)
3510 (progn
3511 (add-text-properties (match-beginning 0) (match-end 0)
3512 (list 'mouse-face 'highlight
3513 'rear-nonsticky org-nonsticky-props
3514 'keymap org-mouse-map
3516 t)))
3518 (defun org-activate-bracket-links (limit)
3519 "Run through the buffer and add overlays to bracketed links."
3520 (if (re-search-forward org-bracket-link-regexp limit t)
3521 (let* ((help (concat "LINK: "
3522 (org-match-string-no-properties 1)))
3523 ;; FIXME: above we should remove the escapes.
3524 ;; but that requires another match, protecting match data,
3525 ;; a lot of overhead for font-lock.
3526 (ip (org-maybe-intangible
3527 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3528 'keymap org-mouse-map 'mouse-face 'highlight
3529 'font-lock-multiline t 'help-echo help)))
3530 (vp (list 'rear-nonsticky org-nonsticky-props
3531 'keymap org-mouse-map 'mouse-face 'highlight
3532 ' font-lock-multiline t 'help-echo help)))
3533 ;; We need to remove the invisible property here. Table narrowing
3534 ;; may have made some of this invisible.
3535 (remove-text-properties (match-beginning 0) (match-end 0)
3536 '(invisible nil))
3537 (if (match-end 3)
3538 (progn
3539 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3540 (add-text-properties (match-beginning 3) (match-end 3) vp)
3541 (add-text-properties (match-end 3) (match-end 0) ip))
3542 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3543 (add-text-properties (match-beginning 1) (match-end 1) vp)
3544 (add-text-properties (match-end 1) (match-end 0) ip))
3545 t)))
3547 (defun org-activate-dates (limit)
3548 "Run through the buffer and add overlays to dates."
3549 (if (re-search-forward org-tsr-regexp-both limit t)
3550 (progn
3551 (add-text-properties (match-beginning 0) (match-end 0)
3552 (list 'mouse-face 'highlight
3553 'rear-nonsticky org-nonsticky-props
3554 'keymap org-mouse-map))
3555 (when org-display-custom-times
3556 (if (match-end 3)
3557 (org-display-custom-time (match-beginning 3) (match-end 3)))
3558 (org-display-custom-time (match-beginning 1) (match-end 1)))
3559 t)))
3561 (defvar org-target-link-regexp nil
3562 "Regular expression matching radio targets in plain text.")
3563 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3564 "Regular expression matching a link target.")
3565 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3566 "Regular expression matching a radio target.")
3567 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3568 "Regular expression matching any target.")
3570 (defun org-activate-target-links (limit)
3571 "Run through the buffer and add overlays to target matches."
3572 (when org-target-link-regexp
3573 (let ((case-fold-search t))
3574 (if (re-search-forward org-target-link-regexp limit t)
3575 (progn
3576 (add-text-properties (match-beginning 0) (match-end 0)
3577 (list 'mouse-face 'highlight
3578 'rear-nonsticky org-nonsticky-props
3579 'keymap org-mouse-map
3580 'help-echo "Radio target link"
3581 'org-linked-text t))
3582 t)))))
3584 (defun org-update-radio-target-regexp ()
3585 "Find all radio targets in this file and update the regular expression."
3586 (interactive)
3587 (when (memq 'radio org-activate-links)
3588 (setq org-target-link-regexp
3589 (org-make-target-link-regexp (org-all-targets 'radio)))
3590 (org-restart-font-lock)))
3592 (defun org-hide-wide-columns (limit)
3593 (let (s e)
3594 (setq s (text-property-any (point) (or limit (point-max))
3595 'org-cwidth t))
3596 (when s
3597 (setq e (next-single-property-change s 'org-cwidth))
3598 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3599 (goto-char e)
3600 t)))
3602 (defvar org-latex-and-specials-regexp nil
3603 "Regular expression for highlighting export special stuff.")
3604 (defvar org-match-substring-regexp)
3605 (defvar org-match-substring-with-braces-regexp)
3606 (defvar org-export-html-special-string-regexps)
3608 (defun org-compute-latex-and-specials-regexp ()
3609 "Compute regular expression for stuff treated specially by exporters."
3610 (if (not org-highlight-latex-fragments-and-specials)
3611 (org-set-local 'org-latex-and-specials-regexp nil)
3612 (require 'org-exp)
3613 (let*
3614 ((matchers (plist-get org-format-latex-options :matchers))
3615 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3616 org-latex-regexps)))
3617 (options (org-combine-plists (org-default-export-plist)
3618 (org-infile-export-plist)))
3619 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3620 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3621 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3622 (org-export-html-expand (plist-get options :expand-quoted-html))
3623 (org-export-with-special-strings (plist-get options :special-strings))
3624 (re-sub
3625 (cond
3626 ((equal org-export-with-sub-superscripts '{})
3627 (list org-match-substring-with-braces-regexp))
3628 (org-export-with-sub-superscripts
3629 (list org-match-substring-regexp))
3630 (t nil)))
3631 (re-latex
3632 (if org-export-with-LaTeX-fragments
3633 (mapcar (lambda (x) (nth 1 x)) latexs)))
3634 (re-macros
3635 (if org-export-with-TeX-macros
3636 (list (concat "\\\\"
3637 (regexp-opt
3638 (append (mapcar 'car org-html-entities)
3639 (if (boundp 'org-latex-entities)
3640 org-latex-entities nil))
3641 'words))) ; FIXME
3643 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3644 (re-special (if org-export-with-special-strings
3645 (mapcar (lambda (x) (car x))
3646 org-export-html-special-string-regexps)))
3647 (re-rest
3648 (delq nil
3649 (list
3650 (if org-export-html-expand "@<[^>\n]+>")
3651 ))))
3652 (org-set-local
3653 'org-latex-and-specials-regexp
3654 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3655 re-rest) "\\|")))))
3657 (defun org-do-latex-and-special-faces (limit)
3658 "Run through the buffer and add overlays to links."
3659 (when org-latex-and-specials-regexp
3660 (let (rtn d)
3661 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3662 limit t))
3663 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3664 'face))
3665 '(org-code org-verbatim underline)))
3666 (progn
3667 (setq rtn t
3668 d (cond ((member (char-after (1+ (match-beginning 0)))
3669 '(?_ ?^)) 1)
3670 (t 0)))
3671 (font-lock-prepend-text-property
3672 (+ d (match-beginning 0)) (match-end 0)
3673 'face 'org-latex-and-export-specials)
3674 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3675 '(font-lock-multiline t)))))
3676 rtn)))
3678 (defun org-restart-font-lock ()
3679 "Restart font-lock-mode, to force refontification."
3680 (when (and (boundp 'font-lock-mode) font-lock-mode)
3681 (font-lock-mode -1)
3682 (font-lock-mode 1)))
3684 (defun org-all-targets (&optional radio)
3685 "Return a list of all targets in this file.
3686 With optional argument RADIO, only find radio targets."
3687 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3688 rtn)
3689 (save-excursion
3690 (goto-char (point-min))
3691 (while (re-search-forward re nil t)
3692 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3693 rtn)))
3695 (defun org-make-target-link-regexp (targets)
3696 "Make regular expression matching all strings in TARGETS.
3697 The regular expression finds the targets also if there is a line break
3698 between words."
3699 (and targets
3700 (concat
3701 "\\<\\("
3702 (mapconcat
3703 (lambda (x)
3704 (while (string-match " +" x)
3705 (setq x (replace-match "\\s-+" t t x)))
3707 targets
3708 "\\|")
3709 "\\)\\>")))
3711 (defun org-activate-tags (limit)
3712 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3713 (progn
3714 (add-text-properties (match-beginning 1) (match-end 1)
3715 (list 'mouse-face 'highlight
3716 'rear-nonsticky org-nonsticky-props
3717 'keymap org-mouse-map))
3718 t)))
3720 (defun org-outline-level ()
3721 (save-excursion
3722 (looking-at outline-regexp)
3723 (if (match-beginning 1)
3724 (+ (org-get-string-indentation (match-string 1)) 1000)
3725 (1- (- (match-end 0) (match-beginning 0))))))
3727 (defvar org-font-lock-keywords nil)
3729 (defconst org-property-re (org-re "^[ \t]*\\(:\\([-[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3730 "Regular expression matching a property line.")
3732 (defvar org-font-lock-hook nil
3733 "Functions to be called for special font lock stuff.")
3735 (defun org-font-lock-hook (limit)
3736 (run-hook-with-args 'org-font-lock-hook limit))
3738 (defun org-set-font-lock-defaults ()
3739 (let* ((em org-fontify-emphasized-text)
3740 (lk org-activate-links)
3741 (org-font-lock-extra-keywords
3742 (list
3743 ;; Call the hook
3744 '(org-font-lock-hook)
3745 ;; Headlines
3746 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3747 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3748 ;; Table lines
3749 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3750 (1 'org-table t))
3751 ;; Table internals
3752 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3753 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3754 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3755 ;; Drawers
3756 (list org-drawer-regexp '(0 'org-special-keyword t))
3757 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3758 ;; Properties
3759 (list org-property-re
3760 '(1 'org-special-keyword t)
3761 '(3 'org-property-value t))
3762 (if org-format-transports-properties-p
3763 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3764 ;; Links
3765 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3766 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3767 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3768 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3769 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3770 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3771 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3772 '(org-hide-wide-columns (0 nil append))
3773 ;; TODO lines
3774 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3775 '(1 (org-get-todo-face 1) t))
3776 ;; DONE
3777 (if org-fontify-done-headline
3778 (list (concat "^[*]+ +\\<\\("
3779 (mapconcat 'regexp-quote org-done-keywords "\\|")
3780 "\\)\\(.*\\)")
3781 '(2 'org-headline-done t))
3782 nil)
3783 ;; Priorities
3784 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3785 ;; Special keywords
3786 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3787 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3788 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3789 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3790 ;; Emphasis
3791 (if em
3792 (if (featurep 'xemacs)
3793 '(org-do-emphasis-faces (0 nil append))
3794 '(org-do-emphasis-faces)))
3795 ;; Checkboxes
3796 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3797 2 'bold prepend)
3798 (if org-provide-checkbox-statistics
3799 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3800 (0 (org-get-checkbox-statistics-face) t)))
3801 ;; Description list items
3802 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(.*? ::\\)"
3803 2 'bold prepend)
3804 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3805 '(1 'org-archived prepend))
3806 ;; Specials
3807 '(org-do-latex-and-special-faces)
3808 ;; Code
3809 '(org-activate-code (1 'org-code t))
3810 ;; COMMENT
3811 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3812 "\\|" org-quote-string "\\)\\>")
3813 '(1 'org-special-keyword t))
3814 '("^#.*" (0 'font-lock-comment-face t))
3816 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3817 ;; Now set the full font-lock-keywords
3818 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3819 (org-set-local 'font-lock-defaults
3820 '(org-font-lock-keywords t nil nil backward-paragraph))
3821 (kill-local-variable 'font-lock-keywords) nil))
3823 (defvar org-m nil)
3824 (defvar org-l nil)
3825 (defvar org-f nil)
3826 (defun org-get-level-face (n)
3827 "Get the right face for match N in font-lock matching of healdines."
3828 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3829 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3830 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3831 (cond
3832 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3833 ((eq n 2) org-f)
3834 (t (if org-level-color-stars-only nil org-f))))
3836 (defun org-get-todo-face (kwd)
3837 "Get the right face for a TODO keyword KWD.
3838 If KWD is a number, get the corresponding match group."
3839 (if (numberp kwd) (setq kwd (match-string kwd)))
3840 (or (cdr (assoc kwd org-todo-keyword-faces))
3841 (and (member kwd org-done-keywords) 'org-done)
3842 'org-todo))
3844 (defun org-unfontify-region (beg end &optional maybe_loudly)
3845 "Remove fontification and activation overlays from links."
3846 (font-lock-default-unfontify-region beg end)
3847 (let* ((buffer-undo-list t)
3848 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3849 (inhibit-modification-hooks t)
3850 deactivate-mark buffer-file-name buffer-file-truename)
3851 (remove-text-properties beg end
3852 '(mouse-face t keymap t org-linked-text t
3853 invisible t intangible t))))
3855 ;;;; Visibility cycling, including org-goto and indirect buffer
3857 ;;; Cycling
3859 (defvar org-cycle-global-status nil)
3860 (make-variable-buffer-local 'org-cycle-global-status)
3861 (defvar org-cycle-subtree-status nil)
3862 (make-variable-buffer-local 'org-cycle-subtree-status)
3864 ;;;###autoload
3865 (defun org-cycle (&optional arg)
3866 "Visibility cycling for Org-mode.
3868 - When this function is called with a prefix argument, rotate the entire
3869 buffer through 3 states (global cycling)
3870 1. OVERVIEW: Show only top-level headlines.
3871 2. CONTENTS: Show all headlines of all levels, but no body text.
3872 3. SHOW ALL: Show everything.
3873 When called with two C-c C-u prefixes, switch to the startup visibility,
3874 determined by the variable `org-startup-folded', and by any VISIBILITY
3875 properties in the buffer.
3877 - When point is at the beginning of a headline, rotate the subtree started
3878 by this line through 3 different states (local cycling)
3879 1. FOLDED: Only the main headline is shown.
3880 2. CHILDREN: The main headline and the direct children are shown.
3881 From this state, you can move to one of the children
3882 and zoom in further.
3883 3. SUBTREE: Show the entire subtree, including body text.
3885 - When there is a numeric prefix, go up to a heading with level ARG, do
3886 a `show-subtree' and return to the previous cursor position. If ARG
3887 is negative, go up that many levels.
3889 - When point is not at the beginning of a headline, execute the global
3890 binding for TAB, which is re-indenting the line. See the option
3891 `org-cycle-emulate-tab' for details.
3893 - Special case: if point is at the beginning of the buffer and there is
3894 no headline in line 1, this function will act as if called with prefix arg.
3895 But only if also the variable `org-cycle-global-at-bob' is t."
3896 (interactive "P")
3897 (org-load-modules-maybe)
3898 (let* ((outline-regexp
3899 (if (and (org-mode-p) org-cycle-include-plain-lists)
3900 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3901 outline-regexp))
3902 (bob-special (and org-cycle-global-at-bob (bobp)
3903 (not (looking-at outline-regexp))))
3904 (org-cycle-hook
3905 (if bob-special
3906 (delq 'org-optimize-window-after-visibility-change
3907 (copy-sequence org-cycle-hook))
3908 org-cycle-hook))
3909 (pos (point)))
3911 (if (or bob-special (equal arg '(4)))
3912 ;; special case: use global cycling
3913 (setq arg t))
3915 (cond
3917 ((equal arg '(16))
3918 (org-set-startup-visibility)
3919 (message "Startup visibility, plus VISIBILITY properties."))
3921 ((org-at-table-p 'any)
3922 ;; Enter the table or move to the next field in the table
3923 (or (org-table-recognize-table.el)
3924 (progn
3925 (if arg (org-table-edit-field t)
3926 (org-table-justify-field-maybe)
3927 (call-interactively 'org-table-next-field)))))
3929 ((eq arg t) ;; Global cycling
3931 (cond
3932 ((and (eq last-command this-command)
3933 (eq org-cycle-global-status 'overview))
3934 ;; We just created the overview - now do table of contents
3935 ;; This can be slow in very large buffers, so indicate action
3936 (message "CONTENTS...")
3937 (org-content)
3938 (message "CONTENTS...done")
3939 (setq org-cycle-global-status 'contents)
3940 (run-hook-with-args 'org-cycle-hook 'contents))
3942 ((and (eq last-command this-command)
3943 (eq org-cycle-global-status 'contents))
3944 ;; We just showed the table of contents - now show everything
3945 (show-all)
3946 (message "SHOW ALL")
3947 (setq org-cycle-global-status 'all)
3948 (run-hook-with-args 'org-cycle-hook 'all))
3951 ;; Default action: go to overview
3952 (org-overview)
3953 (message "OVERVIEW")
3954 (setq org-cycle-global-status 'overview)
3955 (run-hook-with-args 'org-cycle-hook 'overview))))
3957 ((and org-drawers org-drawer-regexp
3958 (save-excursion
3959 (beginning-of-line 1)
3960 (looking-at org-drawer-regexp)))
3961 ;; Toggle block visibility
3962 (org-flag-drawer
3963 (not (get-char-property (match-end 0) 'invisible))))
3965 ((integerp arg)
3966 ;; Show-subtree, ARG levels up from here.
3967 (save-excursion
3968 (org-back-to-heading)
3969 (outline-up-heading (if (< arg 0) (- arg)
3970 (- (funcall outline-level) arg)))
3971 (org-show-subtree)))
3973 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3974 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3975 ;; At a heading: rotate between three different views
3976 (org-back-to-heading)
3977 (let ((goal-column 0) eoh eol eos)
3978 ;; First, some boundaries
3979 (save-excursion
3980 (org-back-to-heading)
3981 (save-excursion
3982 (beginning-of-line 2)
3983 (while (and (not (eobp)) ;; this is like `next-line'
3984 (get-char-property (1- (point)) 'invisible))
3985 (beginning-of-line 2)) (setq eol (point)))
3986 (outline-end-of-heading) (setq eoh (point))
3987 (org-end-of-subtree t)
3988 (unless (eobp)
3989 (skip-chars-forward " \t\n")
3990 (beginning-of-line 1) ; in case this is an item
3992 (setq eos (1- (point))))
3993 ;; Find out what to do next and set `this-command'
3994 (cond
3995 ((= eos eoh)
3996 ;; Nothing is hidden behind this heading
3997 (message "EMPTY ENTRY")
3998 (setq org-cycle-subtree-status nil)
3999 (save-excursion
4000 (goto-char eos)
4001 (outline-next-heading)
4002 (if (org-invisible-p) (org-flag-heading nil))))
4003 ((or (>= eol eos)
4004 (not (string-match "\\S-" (buffer-substring eol eos))))
4005 ;; Entire subtree is hidden in one line: open it
4006 (org-show-entry)
4007 (show-children)
4008 (message "CHILDREN")
4009 (save-excursion
4010 (goto-char eos)
4011 (outline-next-heading)
4012 (if (org-invisible-p) (org-flag-heading nil)))
4013 (setq org-cycle-subtree-status 'children)
4014 (run-hook-with-args 'org-cycle-hook 'children))
4015 ((and (eq last-command this-command)
4016 (eq org-cycle-subtree-status 'children))
4017 ;; We just showed the children, now show everything.
4018 (org-show-subtree)
4019 (message "SUBTREE")
4020 (setq org-cycle-subtree-status 'subtree)
4021 (run-hook-with-args 'org-cycle-hook 'subtree))
4023 ;; Default action: hide the subtree.
4024 (hide-subtree)
4025 (message "FOLDED")
4026 (setq org-cycle-subtree-status 'folded)
4027 (run-hook-with-args 'org-cycle-hook 'folded)))))
4029 ;; TAB emulation and template completion
4030 (buffer-read-only (org-back-to-heading))
4032 ((org-try-structure-completion))
4034 ((org-try-cdlatex-tab))
4036 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
4037 (or (not (bolp))
4038 (not (looking-at outline-regexp))))
4039 (call-interactively (global-key-binding "\t")))
4041 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
4042 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
4043 (or (and (eq org-cycle-emulate-tab 'white)
4044 (= (match-end 0) (point-at-eol)))
4045 (and (eq org-cycle-emulate-tab 'whitestart)
4046 (>= (match-end 0) pos))))
4048 (eq org-cycle-emulate-tab t))
4049 (call-interactively (global-key-binding "\t")))
4051 (t (save-excursion
4052 (org-back-to-heading)
4053 (org-cycle))))))
4055 ;;;###autoload
4056 (defun org-global-cycle (&optional arg)
4057 "Cycle the global visibility. For details see `org-cycle'.
4058 With C-u prefix arg, switch to startup visibility.
4059 With a numeric prefix, show all headlines up to that level."
4060 (interactive "P")
4061 (let ((org-cycle-include-plain-lists
4062 (if (org-mode-p) org-cycle-include-plain-lists nil)))
4063 (cond
4064 ((integerp arg)
4065 (show-all)
4066 (hide-sublevels arg)
4067 (setq org-cycle-global-status 'contents))
4068 ((equal arg '(4))
4069 (org-set-startup-visibility)
4070 (message "Startup visibility, plus VISIBILITY properties."))
4072 (org-cycle '(4))))))
4074 (defun org-set-startup-visibility ()
4075 "Set the visibility required by startup options and properties."
4076 (cond
4077 ((eq org-startup-folded t)
4078 (org-cycle '(4)))
4079 ((eq org-startup-folded 'content)
4080 (let ((this-command 'org-cycle) (last-command 'org-cycle))
4081 (org-cycle '(4)) (org-cycle '(4)))))
4082 (org-set-visibility-according-to-property 'no-cleanup)
4083 (org-cycle-hide-archived-subtrees 'all)
4084 (org-cycle-hide-drawers 'all)
4085 (org-cycle-show-empty-lines 'all))
4087 (defun org-set-visibility-according-to-property (&optional no-cleanup)
4088 "Switch subtree visibilities according to :VISIBILITY: property."
4089 (interactive)
4090 (let (state)
4091 (save-excursion
4092 (goto-char (point-min))
4093 (while (re-search-forward
4094 "^[ \t]*:VISIBILITY:[ \t]+\\([a-z]+\\)"
4095 nil t)
4096 (setq state (match-string 1))
4097 (save-excursion
4098 (org-back-to-heading t)
4099 (hide-subtree)
4100 (org-reveal)
4101 (cond
4102 ((equal state '("fold" "folded"))
4103 (hide-subtree))
4104 ((equal state "children")
4105 (org-show-hidden-entry)
4106 (show-children))
4107 ((equal state "content")
4108 (save-excursion
4109 (save-restriction
4110 (org-narrow-to-subtree)
4111 (org-content))))
4112 ((member state '("all" "showall"))
4113 (show-subtree)))))
4114 (unless no-cleanup
4115 (org-cycle-hide-archived-subtrees 'all)
4116 (org-cycle-hide-drawers 'all)
4117 (org-cycle-show-empty-lines 'all)))))
4119 (defun org-overview ()
4120 "Switch to overview mode, shoing only top-level headlines.
4121 Really, this shows all headlines with level equal or greater than the level
4122 of the first headline in the buffer. This is important, because if the
4123 first headline is not level one, then (hide-sublevels 1) gives confusing
4124 results."
4125 (interactive)
4126 (let ((level (save-excursion
4127 (goto-char (point-min))
4128 (if (re-search-forward (concat "^" outline-regexp) nil t)
4129 (progn
4130 (goto-char (match-beginning 0))
4131 (funcall outline-level))))))
4132 (and level (hide-sublevels level))))
4134 (defun org-content (&optional arg)
4135 "Show all headlines in the buffer, like a table of contents.
4136 With numerical argument N, show content up to level N."
4137 (interactive "P")
4138 (save-excursion
4139 ;; Visit all headings and show their offspring
4140 (and (integerp arg) (org-overview))
4141 (goto-char (point-max))
4142 (catch 'exit
4143 (while (and (progn (condition-case nil
4144 (outline-previous-visible-heading 1)
4145 (error (goto-char (point-min))))
4147 (looking-at outline-regexp))
4148 (if (integerp arg)
4149 (show-children (1- arg))
4150 (show-branches))
4151 (if (bobp) (throw 'exit nil))))))
4154 (defun org-optimize-window-after-visibility-change (state)
4155 "Adjust the window after a change in outline visibility.
4156 This function is the default value of the hook `org-cycle-hook'."
4157 (when (get-buffer-window (current-buffer))
4158 (cond
4159 ; ((eq state 'overview) (org-first-headline-recenter 1))
4160 ; ((eq state 'overview) (org-beginning-of-line))
4161 ((eq state 'content) nil)
4162 ((eq state 'all) nil)
4163 ((eq state 'folded) nil)
4164 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
4165 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
4167 (defun org-compact-display-after-subtree-move ()
4168 (let (beg end)
4169 (save-excursion
4170 (if (org-up-heading-safe)
4171 (progn
4172 (hide-subtree)
4173 (show-entry)
4174 (show-children)
4175 (org-cycle-show-empty-lines 'children)
4176 (org-cycle-hide-drawers 'children))
4177 (org-overview)))))
4179 (defun org-cycle-show-empty-lines (state)
4180 "Show empty lines above all visible headlines.
4181 The region to be covered depends on STATE when called through
4182 `org-cycle-hook'. Lisp program can use t for STATE to get the
4183 entire buffer covered. Note that an empty line is only shown if there
4184 are at least `org-cycle-separator-lines' empty lines before the headeline."
4185 (when (> org-cycle-separator-lines 0)
4186 (save-excursion
4187 (let* ((n org-cycle-separator-lines)
4188 (re (cond
4189 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
4190 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
4191 (t (let ((ns (number-to-string (- n 2))))
4192 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
4193 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
4194 beg end)
4195 (cond
4196 ((memq state '(overview contents t))
4197 (setq beg (point-min) end (point-max)))
4198 ((memq state '(children folded))
4199 (setq beg (point) end (progn (org-end-of-subtree t t)
4200 (beginning-of-line 2)
4201 (point)))))
4202 (when beg
4203 (goto-char beg)
4204 (while (re-search-forward re end t)
4205 (if (not (get-char-property (match-end 1) 'invisible))
4206 (outline-flag-region
4207 (match-beginning 1) (match-end 1) nil)))))))
4208 ;; Never hide empty lines at the end of the file.
4209 (save-excursion
4210 (goto-char (point-max))
4211 (outline-previous-heading)
4212 (outline-end-of-heading)
4213 (if (and (looking-at "[ \t\n]+")
4214 (= (match-end 0) (point-max)))
4215 (outline-flag-region (point) (match-end 0) nil))))
4217 (defun org-show-empty-lines-in-parent ()
4218 "Move to the parent and re-show empty lines before visible headlines."
4219 (save-excursion
4220 (let ((context (if (org-up-heading-safe) 'children 'overview)))
4221 (org-cycle-show-empty-lines context))))
4223 (defun org-cycle-hide-drawers (state)
4224 "Re-hide all drawers after a visibility state change."
4225 (when (and (org-mode-p)
4226 (not (memq state '(overview folded))))
4227 (save-excursion
4228 (let* ((globalp (memq state '(contents all)))
4229 (beg (if globalp (point-min) (point)))
4230 (end (if globalp (point-max) (org-end-of-subtree t))))
4231 (goto-char beg)
4232 (while (re-search-forward org-drawer-regexp end t)
4233 (org-flag-drawer t))))))
4235 (defun org-flag-drawer (flag)
4236 (save-excursion
4237 (beginning-of-line 1)
4238 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4239 (let ((b (match-end 0))
4240 (outline-regexp org-outline-regexp))
4241 (if (re-search-forward
4242 "^[ \t]*:END:"
4243 (save-excursion (outline-next-heading) (point)) t)
4244 (outline-flag-region b (point-at-eol) flag)
4245 (error ":END: line missing"))))))
4247 (defun org-subtree-end-visible-p ()
4248 "Is the end of the current subtree visible?"
4249 (pos-visible-in-window-p
4250 (save-excursion (org-end-of-subtree t) (point))))
4252 (defun org-first-headline-recenter (&optional N)
4253 "Move cursor to the first headline and recenter the headline.
4254 Optional argument N means, put the headline into the Nth line of the window."
4255 (goto-char (point-min))
4256 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4257 (beginning-of-line)
4258 (recenter (prefix-numeric-value N))))
4260 ;;; Org-goto
4262 (defvar org-goto-window-configuration nil)
4263 (defvar org-goto-marker nil)
4264 (defvar org-goto-map
4265 (let ((map (make-sparse-keymap)))
4266 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4267 (while (setq cmd (pop cmds))
4268 (substitute-key-definition cmd cmd map global-map)))
4269 (suppress-keymap map)
4270 (org-defkey map "\C-m" 'org-goto-ret)
4271 (org-defkey map [(return)] 'org-goto-ret)
4272 (org-defkey map [(left)] 'org-goto-left)
4273 (org-defkey map [(right)] 'org-goto-right)
4274 (org-defkey map [(control ?g)] 'org-goto-quit)
4275 (org-defkey map "\C-i" 'org-cycle)
4276 (org-defkey map [(tab)] 'org-cycle)
4277 (org-defkey map [(down)] 'outline-next-visible-heading)
4278 (org-defkey map [(up)] 'outline-previous-visible-heading)
4279 (if org-goto-auto-isearch
4280 (if (fboundp 'define-key-after)
4281 (define-key-after map [t] 'org-goto-local-auto-isearch)
4282 nil)
4283 (org-defkey map "q" 'org-goto-quit)
4284 (org-defkey map "n" 'outline-next-visible-heading)
4285 (org-defkey map "p" 'outline-previous-visible-heading)
4286 (org-defkey map "f" 'outline-forward-same-level)
4287 (org-defkey map "b" 'outline-backward-same-level)
4288 (org-defkey map "u" 'outline-up-heading))
4289 (org-defkey map "/" 'org-occur)
4290 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4291 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4292 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4293 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4294 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4295 map))
4297 (defconst org-goto-help
4298 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4299 RET=jump to location [Q]uit and return to previous location
4300 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4302 (defvar org-goto-start-pos) ; dynamically scoped parameter
4304 ;; FIXME: Docstring doe not mention both interfaces
4305 (defun org-goto (&optional alternative-interface)
4306 "Look up a different location in the current file, keeping current visibility.
4308 When you want look-up or go to a different location in a document, the
4309 fastest way is often to fold the entire buffer and then dive into the tree.
4310 This method has the disadvantage, that the previous location will be folded,
4311 which may not be what you want.
4313 This command works around this by showing a copy of the current buffer
4314 in an indirect buffer, in overview mode. You can dive into the tree in
4315 that copy, use org-occur and incremental search to find a location.
4316 When pressing RET or `Q', the command returns to the original buffer in
4317 which the visibility is still unchanged. After RET is will also jump to
4318 the location selected in the indirect buffer and expose the
4319 the headline hierarchy above."
4320 (interactive "P")
4321 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4322 (org-refile-use-outline-path t)
4323 (interface
4324 (if (not alternative-interface)
4325 org-goto-interface
4326 (if (eq org-goto-interface 'outline)
4327 'outline-path-completion
4328 'outline)))
4329 (org-goto-start-pos (point))
4330 (selected-point
4331 (if (eq interface 'outline)
4332 (car (org-get-location (current-buffer) org-goto-help))
4333 (nth 3 (org-refile-get-location "Goto: ")))))
4334 (if selected-point
4335 (progn
4336 (org-mark-ring-push org-goto-start-pos)
4337 (goto-char selected-point)
4338 (if (or (org-invisible-p) (org-invisible-p2))
4339 (org-show-context 'org-goto)))
4340 (message "Quit"))))
4342 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4343 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4344 (defvar org-goto-local-auto-isearch-map) ; defined below
4346 (defun org-get-location (buf help)
4347 "Let the user select a location in the Org-mode buffer BUF.
4348 This function uses a recursive edit. It returns the selected position
4349 or nil."
4350 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4351 (isearch-hide-immediately nil)
4352 (isearch-search-fun-function
4353 (lambda () 'org-goto-local-search-forward-headings))
4354 (org-goto-selected-point org-goto-exit-command))
4355 (save-excursion
4356 (save-window-excursion
4357 (delete-other-windows)
4358 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4359 (switch-to-buffer
4360 (condition-case nil
4361 (make-indirect-buffer (current-buffer) "*org-goto*")
4362 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4363 (with-output-to-temp-buffer "*Help*"
4364 (princ help))
4365 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4366 (setq buffer-read-only nil)
4367 (let ((org-startup-truncated t)
4368 (org-startup-folded nil)
4369 (org-startup-align-all-tables nil))
4370 (org-mode)
4371 (org-overview))
4372 (setq buffer-read-only t)
4373 (if (and (boundp 'org-goto-start-pos)
4374 (integer-or-marker-p org-goto-start-pos))
4375 (let ((org-show-hierarchy-above t)
4376 (org-show-siblings t)
4377 (org-show-following-heading t))
4378 (goto-char org-goto-start-pos)
4379 (and (org-invisible-p) (org-show-context)))
4380 (goto-char (point-min)))
4381 (org-beginning-of-line)
4382 (message "Select location and press RET")
4383 (use-local-map org-goto-map)
4384 (recursive-edit)
4386 (kill-buffer "*org-goto*")
4387 (cons org-goto-selected-point org-goto-exit-command)))
4389 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4390 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4391 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4392 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4394 (defun org-goto-local-search-forward-headings (string bound noerror)
4395 "Search and make sure that anu matches are in headlines."
4396 (catch 'return
4397 (while (search-forward string bound noerror)
4398 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4399 (and (member :headline context)
4400 (not (member :tags context))))
4401 (throw 'return (point))))))
4403 (defun org-goto-local-auto-isearch ()
4404 "Start isearch."
4405 (interactive)
4406 (goto-char (point-min))
4407 (let ((keys (this-command-keys)))
4408 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4409 (isearch-mode t)
4410 (isearch-process-search-char (string-to-char keys)))))
4412 (defun org-goto-ret (&optional arg)
4413 "Finish `org-goto' by going to the new location."
4414 (interactive "P")
4415 (setq org-goto-selected-point (point)
4416 org-goto-exit-command 'return)
4417 (throw 'exit nil))
4419 (defun org-goto-left ()
4420 "Finish `org-goto' by going to the new location."
4421 (interactive)
4422 (if (org-on-heading-p)
4423 (progn
4424 (beginning-of-line 1)
4425 (setq org-goto-selected-point (point)
4426 org-goto-exit-command 'left)
4427 (throw 'exit nil))
4428 (error "Not on a heading")))
4430 (defun org-goto-right ()
4431 "Finish `org-goto' by going to the new location."
4432 (interactive)
4433 (if (org-on-heading-p)
4434 (progn
4435 (setq org-goto-selected-point (point)
4436 org-goto-exit-command 'right)
4437 (throw 'exit nil))
4438 (error "Not on a heading")))
4440 (defun org-goto-quit ()
4441 "Finish `org-goto' without cursor motion."
4442 (interactive)
4443 (setq org-goto-selected-point nil)
4444 (setq org-goto-exit-command 'quit)
4445 (throw 'exit nil))
4447 ;;; Indirect buffer display of subtrees
4449 (defvar org-indirect-dedicated-frame nil
4450 "This is the frame being used for indirect tree display.")
4451 (defvar org-last-indirect-buffer nil)
4453 (defun org-tree-to-indirect-buffer (&optional arg)
4454 "Create indirect buffer and narrow it to current subtree.
4455 With numerical prefix ARG, go up to this level and then take that tree.
4456 If ARG is negative, go up that many levels.
4457 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4458 indirect buffer previously made with this command, to avoid proliferation of
4459 indirect buffers. However, when you call the command with a `C-u' prefix, or
4460 when `org-indirect-buffer-display' is `new-frame', the last buffer
4461 is kept so that you can work with several indirect buffers at the same time.
4462 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4463 requests that a new frame be made for the new buffer, so that the dedicated
4464 frame is not changed."
4465 (interactive "P")
4466 (let ((cbuf (current-buffer))
4467 (cwin (selected-window))
4468 (pos (point))
4469 beg end level heading ibuf)
4470 (save-excursion
4471 (org-back-to-heading t)
4472 (when (numberp arg)
4473 (setq level (org-outline-level))
4474 (if (< arg 0) (setq arg (+ level arg)))
4475 (while (> (setq level (org-outline-level)) arg)
4476 (outline-up-heading 1 t)))
4477 (setq beg (point)
4478 heading (org-get-heading))
4479 (org-end-of-subtree t) (setq end (point)))
4480 (if (and (buffer-live-p org-last-indirect-buffer)
4481 (not (eq org-indirect-buffer-display 'new-frame))
4482 (not arg))
4483 (kill-buffer org-last-indirect-buffer))
4484 (setq ibuf (org-get-indirect-buffer cbuf)
4485 org-last-indirect-buffer ibuf)
4486 (cond
4487 ((or (eq org-indirect-buffer-display 'new-frame)
4488 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4489 (select-frame (make-frame))
4490 (delete-other-windows)
4491 (switch-to-buffer ibuf)
4492 (org-set-frame-title heading))
4493 ((eq org-indirect-buffer-display 'dedicated-frame)
4494 (raise-frame
4495 (select-frame (or (and org-indirect-dedicated-frame
4496 (frame-live-p org-indirect-dedicated-frame)
4497 org-indirect-dedicated-frame)
4498 (setq org-indirect-dedicated-frame (make-frame)))))
4499 (delete-other-windows)
4500 (switch-to-buffer ibuf)
4501 (org-set-frame-title (concat "Indirect: " heading)))
4502 ((eq org-indirect-buffer-display 'current-window)
4503 (switch-to-buffer ibuf))
4504 ((eq org-indirect-buffer-display 'other-window)
4505 (pop-to-buffer ibuf))
4506 (t (error "Invalid value.")))
4507 (if (featurep 'xemacs)
4508 (save-excursion (org-mode) (turn-on-font-lock)))
4509 (narrow-to-region beg end)
4510 (show-all)
4511 (goto-char pos)
4512 (and (window-live-p cwin) (select-window cwin))))
4514 (defun org-get-indirect-buffer (&optional buffer)
4515 (setq buffer (or buffer (current-buffer)))
4516 (let ((n 1) (base (buffer-name buffer)) bname)
4517 (while (buffer-live-p
4518 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4519 (setq n (1+ n)))
4520 (condition-case nil
4521 (make-indirect-buffer buffer bname 'clone)
4522 (error (make-indirect-buffer buffer bname)))))
4524 (defun org-set-frame-title (title)
4525 "Set the title of the current frame to the string TITLE."
4526 ;; FIXME: how to name a single frame in XEmacs???
4527 (unless (featurep 'xemacs)
4528 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4530 ;;;; Structure editing
4532 ;;; Inserting headlines
4534 (defun org-insert-heading (&optional force-heading)
4535 "Insert a new heading or item with same depth at point.
4536 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4537 If point is at the beginning of a headline, insert a sibling before the
4538 current headline. If point is not at the beginning, do not split the line,
4539 but create the new hedline after the current line."
4540 (interactive "P")
4541 (if (= (buffer-size) 0)
4542 (insert "\n* ")
4543 (when (or force-heading (not (org-insert-item)))
4544 (let* ((head (save-excursion
4545 (condition-case nil
4546 (progn
4547 (org-back-to-heading)
4548 (match-string 0))
4549 (error "*"))))
4550 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4551 pos)
4552 (cond
4553 ((and (org-on-heading-p) (bolp)
4554 (or (bobp)
4555 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4556 ;; insert before the current line
4557 (open-line (if blank 2 1)))
4558 ((and (bolp)
4559 (or (bobp)
4560 (save-excursion
4561 (backward-char 1) (not (org-invisible-p)))))
4562 ;; insert right here
4563 nil)
4565 ;; in the middle of the line
4566 (org-show-entry)
4567 (let ((split
4568 (org-get-alist-option org-M-RET-may-split-line 'headline))
4569 tags pos)
4570 (if (org-on-heading-p)
4571 (progn
4572 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4573 (setq tags (and (match-end 2) (match-string 2)))
4574 (and (match-end 1)
4575 (delete-region (match-beginning 1) (match-end 1)))
4576 (setq pos (point-at-bol))
4577 (or split (end-of-line 1))
4578 (delete-horizontal-space)
4579 (newline (if blank 2 1))
4580 (when tags
4581 (save-excursion
4582 (goto-char pos)
4583 (end-of-line 1)
4584 (insert " " tags)
4585 (org-set-tags nil 'align))))
4586 (or split (end-of-line 1))
4587 (newline (if blank 2 1))))))
4588 (insert head) (just-one-space)
4589 (setq pos (point))
4590 (end-of-line 1)
4591 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4592 (run-hooks 'org-insert-heading-hook)))))
4594 (defun org-get-heading (&optional no-tags)
4595 "Return the heading of the current entry, without the stars."
4596 (save-excursion
4597 (org-back-to-heading t)
4598 (if (looking-at
4599 (if no-tags
4600 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4601 "\\*+[ \t]+\\([^\r\n]*\\)"))
4602 (match-string 1) "")))
4604 (defun org-insert-heading-after-current ()
4605 "Insert a new heading with same level as current, after current subtree."
4606 (interactive)
4607 (org-back-to-heading)
4608 (org-insert-heading)
4609 (org-move-subtree-down)
4610 (end-of-line 1))
4612 (defun org-insert-todo-heading (arg)
4613 "Insert a new heading with the same level and TODO state as current heading.
4614 If the heading has no TODO state, or if the state is DONE, use the first
4615 state (TODO by default). Also with prefix arg, force first state."
4616 (interactive "P")
4617 (when (not (org-insert-item 'checkbox))
4618 (org-insert-heading)
4619 (save-excursion
4620 (org-back-to-heading)
4621 (outline-previous-heading)
4622 (looking-at org-todo-line-regexp))
4623 (if (or arg
4624 (not (match-beginning 2))
4625 (member (match-string 2) org-done-keywords))
4626 (insert (car org-todo-keywords-1) " ")
4627 (insert (match-string 2) " "))
4628 (when org-provide-todo-statistics
4629 (org-update-parent-todo-statistics))))
4631 (defun org-insert-subheading (arg)
4632 "Insert a new subheading and demote it.
4633 Works for outline headings and for plain lists alike."
4634 (interactive "P")
4635 (org-insert-heading arg)
4636 (cond
4637 ((org-on-heading-p) (org-do-demote))
4638 ((org-at-item-p) (org-indent-item 1))))
4640 (defun org-insert-todo-subheading (arg)
4641 "Insert a new subheading with TODO keyword or checkbox and demote it.
4642 Works for outline headings and for plain lists alike."
4643 (interactive "P")
4644 (org-insert-todo-heading arg)
4645 (cond
4646 ((org-on-heading-p) (org-do-demote))
4647 ((org-at-item-p) (org-indent-item 1))))
4649 ;;; Promotion and Demotion
4651 (defun org-promote-subtree ()
4652 "Promote the entire subtree.
4653 See also `org-promote'."
4654 (interactive)
4655 (save-excursion
4656 (org-map-tree 'org-promote))
4657 (org-fix-position-after-promote))
4659 (defun org-demote-subtree ()
4660 "Demote the entire subtree. See `org-demote'.
4661 See also `org-promote'."
4662 (interactive)
4663 (save-excursion
4664 (org-map-tree 'org-demote))
4665 (org-fix-position-after-promote))
4668 (defun org-do-promote ()
4669 "Promote the current heading higher up the tree.
4670 If the region is active in `transient-mark-mode', promote all headings
4671 in the region."
4672 (interactive)
4673 (save-excursion
4674 (if (org-region-active-p)
4675 (org-map-region 'org-promote (region-beginning) (region-end))
4676 (org-promote)))
4677 (org-fix-position-after-promote))
4679 (defun org-do-demote ()
4680 "Demote the current heading lower down the tree.
4681 If the region is active in `transient-mark-mode', demote all headings
4682 in the region."
4683 (interactive)
4684 (save-excursion
4685 (if (org-region-active-p)
4686 (org-map-region 'org-demote (region-beginning) (region-end))
4687 (org-demote)))
4688 (org-fix-position-after-promote))
4690 (defun org-fix-position-after-promote ()
4691 "Make sure that after pro/demotion cursor position is right."
4692 (let ((pos (point)))
4693 (when (save-excursion
4694 (beginning-of-line 1)
4695 (looking-at org-todo-line-regexp)
4696 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4697 (cond ((eobp) (insert " "))
4698 ((eolp) (insert " "))
4699 ((equal (char-after) ?\ ) (forward-char 1))))))
4701 (defun org-reduced-level (l)
4702 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4704 (defun org-get-valid-level (level &optional change)
4705 "Rectify a level change under the influence of `org-odd-levels-only'
4706 LEVEL is a current level, CHANGE is by how much the level should be
4707 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4708 even level numbers will become the next higher odd number."
4709 (if org-odd-levels-only
4710 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4711 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4712 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4713 (max 1 (+ level change))))
4715 (if (boundp 'define-obsolete-function-alias)
4716 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4717 (define-obsolete-function-alias 'org-get-legal-level
4718 'org-get-valid-level)
4719 (define-obsolete-function-alias 'org-get-legal-level
4720 'org-get-valid-level "23.1")))
4722 (defun org-promote ()
4723 "Promote the current heading higher up the tree.
4724 If the region is active in `transient-mark-mode', promote all headings
4725 in the region."
4726 (org-back-to-heading t)
4727 (let* ((level (save-match-data (funcall outline-level)))
4728 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4729 (diff (abs (- level (length up-head) -1))))
4730 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4731 (replace-match up-head nil t)
4732 ;; Fixup tag positioning
4733 (and org-auto-align-tags (org-set-tags nil t))
4734 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4736 (defun org-demote ()
4737 "Demote the current heading lower down the tree.
4738 If the region is active in `transient-mark-mode', demote all headings
4739 in the region."
4740 (org-back-to-heading t)
4741 (let* ((level (save-match-data (funcall outline-level)))
4742 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4743 (diff (abs (- level (length down-head) -1))))
4744 (replace-match down-head nil t)
4745 ;; Fixup tag positioning
4746 (and org-auto-align-tags (org-set-tags nil t))
4747 (if org-adapt-indentation (org-fixup-indentation diff))))
4749 (defun org-map-tree (fun)
4750 "Call FUN for every heading underneath the current one."
4751 (org-back-to-heading)
4752 (let ((level (funcall outline-level)))
4753 (save-excursion
4754 (funcall fun)
4755 (while (and (progn
4756 (outline-next-heading)
4757 (> (funcall outline-level) level))
4758 (not (eobp)))
4759 (funcall fun)))))
4761 (defun org-map-region (fun beg end)
4762 "Call FUN for every heading between BEG and END."
4763 (let ((org-ignore-region t))
4764 (save-excursion
4765 (setq end (copy-marker end))
4766 (goto-char beg)
4767 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4768 (< (point) end))
4769 (funcall fun))
4770 (while (and (progn
4771 (outline-next-heading)
4772 (< (point) end))
4773 (not (eobp)))
4774 (funcall fun)))))
4776 (defun org-fixup-indentation (diff)
4777 "Change the indentation in the current entry by DIFF
4778 However, if any line in the current entry has no indentation, or if it
4779 would end up with no indentation after the change, nothing at all is done."
4780 (save-excursion
4781 (let ((end (save-excursion (outline-next-heading)
4782 (point-marker)))
4783 (prohibit (if (> diff 0)
4784 "^\\S-"
4785 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4786 col)
4787 (unless (save-excursion (end-of-line 1)
4788 (re-search-forward prohibit end t))
4789 (while (and (< (point) end)
4790 (re-search-forward "^[ \t]+" end t))
4791 (goto-char (match-end 0))
4792 (setq col (current-column))
4793 (if (< diff 0) (replace-match ""))
4794 (indent-to (+ diff col))))
4795 (move-marker end nil))))
4797 (defun org-convert-to-odd-levels ()
4798 "Convert an org-mode file with all levels allowed to one with odd levels.
4799 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4800 level 5 etc."
4801 (interactive)
4802 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4803 (let ((org-odd-levels-only nil) n)
4804 (save-excursion
4805 (goto-char (point-min))
4806 (while (re-search-forward "^\\*\\*+ " nil t)
4807 (setq n (- (length (match-string 0)) 2))
4808 (while (>= (setq n (1- n)) 0)
4809 (org-demote))
4810 (end-of-line 1))))))
4813 (defun org-convert-to-oddeven-levels ()
4814 "Convert an org-mode file with only odd levels to one with odd and even levels.
4815 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4816 section with an even level, conversion would destroy the structure of the file. An error
4817 is signaled in this case."
4818 (interactive)
4819 (goto-char (point-min))
4820 ;; First check if there are no even levels
4821 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4822 (org-show-context t)
4823 (error "Not all levels are odd in this file. Conversion not possible."))
4824 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4825 (let ((org-odd-levels-only nil) n)
4826 (save-excursion
4827 (goto-char (point-min))
4828 (while (re-search-forward "^\\*\\*+ " nil t)
4829 (setq n (/ (1- (length (match-string 0))) 2))
4830 (while (>= (setq n (1- n)) 0)
4831 (org-promote))
4832 (end-of-line 1))))))
4834 (defun org-tr-level (n)
4835 "Make N odd if required."
4836 (if org-odd-levels-only (1+ (/ n 2)) n))
4838 ;;; Vertical tree motion, cutting and pasting of subtrees
4840 (defun org-move-subtree-up (&optional arg)
4841 "Move the current subtree up past ARG headlines of the same level."
4842 (interactive "p")
4843 (org-move-subtree-down (- (prefix-numeric-value arg))))
4845 (defun org-move-subtree-down (&optional arg)
4846 "Move the current subtree down past ARG headlines of the same level."
4847 (interactive "p")
4848 (setq arg (prefix-numeric-value arg))
4849 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4850 'outline-get-last-sibling))
4851 (ins-point (make-marker))
4852 (cnt (abs arg))
4853 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4854 ;; Select the tree
4855 (org-back-to-heading)
4856 (setq beg0 (point))
4857 (save-excursion
4858 (setq ne-beg (org-back-over-empty-lines))
4859 (setq beg (point)))
4860 (save-match-data
4861 (save-excursion (outline-end-of-heading)
4862 (setq folded (org-invisible-p)))
4863 (outline-end-of-subtree))
4864 (outline-next-heading)
4865 (setq ne-end (org-back-over-empty-lines))
4866 (setq end (point))
4867 (goto-char beg0)
4868 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4869 ;; include less whitespace
4870 (save-excursion
4871 (goto-char beg)
4872 (forward-line (- ne-beg ne-end))
4873 (setq beg (point))))
4874 ;; Find insertion point, with error handling
4875 (while (> cnt 0)
4876 (or (and (funcall movfunc) (looking-at outline-regexp))
4877 (progn (goto-char beg0)
4878 (error "Cannot move past superior level or buffer limit")))
4879 (setq cnt (1- cnt)))
4880 (if (> arg 0)
4881 ;; Moving forward - still need to move over subtree
4882 (progn (org-end-of-subtree t t)
4883 (save-excursion
4884 (org-back-over-empty-lines)
4885 (or (bolp) (newline)))))
4886 (setq ne-ins (org-back-over-empty-lines))
4887 (move-marker ins-point (point))
4888 (setq txt (buffer-substring beg end))
4889 (org-save-markers-in-region beg end)
4890 (delete-region beg end)
4891 (outline-flag-region (1- beg) beg nil)
4892 (outline-flag-region (1- (point)) (point) nil)
4893 (let ((bbb (point)))
4894 (insert-before-markers txt)
4895 (org-reinstall-markers-in-region bbb)
4896 (move-marker ins-point bbb))
4897 (or (bolp) (insert "\n"))
4898 (setq ins-end (point))
4899 (goto-char ins-point)
4900 (org-skip-whitespace)
4901 (when (and (< arg 0)
4902 (org-first-sibling-p)
4903 (> ne-ins ne-beg))
4904 ;; Move whitespace back to beginning
4905 (save-excursion
4906 (goto-char ins-end)
4907 (let ((kill-whole-line t))
4908 (kill-line (- ne-ins ne-beg)) (point)))
4909 (insert (make-string (- ne-ins ne-beg) ?\n)))
4910 (move-marker ins-point nil)
4911 (org-compact-display-after-subtree-move)
4912 (org-show-empty-lines-in-parent)
4913 (unless folded
4914 (org-show-entry)
4915 (show-children)
4916 (org-cycle-hide-drawers 'children))))
4918 (defvar org-subtree-clip ""
4919 "Clipboard for cut and paste of subtrees.
4920 This is actually only a copy of the kill, because we use the normal kill
4921 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4923 (defvar org-subtree-clip-folded nil
4924 "Was the last copied subtree folded?
4925 This is used to fold the tree back after pasting.")
4927 (defun org-cut-subtree (&optional n)
4928 "Cut the current subtree into the clipboard.
4929 With prefix arg N, cut this many sequential subtrees.
4930 This is a short-hand for marking the subtree and then cutting it."
4931 (interactive "p")
4932 (org-copy-subtree n 'cut))
4934 (defun org-copy-subtree (&optional n cut force-store-markers)
4935 "Cut the current subtree into the clipboard.
4936 With prefix arg N, cut this many sequential subtrees.
4937 This is a short-hand for marking the subtree and then copying it.
4938 If CUT is non-nil, actually cut the subtree.
4939 If FORCE-STORE-MARKERS is non-nil, store the relative locations
4940 of some markers in the region, even if CUT is non-nil. This is
4941 useful if the caller implements cut-and-paste as copy-then-paste-then-cut."
4942 (interactive "p")
4943 (let (beg end folded (beg0 (point)))
4944 (if (interactive-p)
4945 (org-back-to-heading nil) ; take what looks like a subtree
4946 (org-back-to-heading t)) ; take what is really there
4947 (org-back-over-empty-lines)
4948 (setq beg (point))
4949 (skip-chars-forward " \t\r\n")
4950 (save-match-data
4951 (save-excursion (outline-end-of-heading)
4952 (setq folded (org-invisible-p)))
4953 (condition-case nil
4954 (outline-forward-same-level (1- n))
4955 (error nil))
4956 (org-end-of-subtree t t))
4957 (org-back-over-empty-lines)
4958 (setq end (point))
4959 (goto-char beg0)
4960 (when (> end beg)
4961 (setq org-subtree-clip-folded folded)
4962 (when (or cut force-store-markers)
4963 (org-save-markers-in-region beg end))
4964 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4965 (setq org-subtree-clip (current-kill 0))
4966 (message "%s: Subtree(s) with %d characters"
4967 (if cut "Cut" "Copied")
4968 (length org-subtree-clip)))))
4970 (defun org-paste-subtree (&optional level tree)
4971 "Paste the clipboard as a subtree, with modification of headline level.
4972 The entire subtree is promoted or demoted in order to match a new headline
4973 level. By default, the new level is derived from the visible headings
4974 before and after the insertion point, and taken to be the inferior headline
4975 level of the two. So if the previous visible heading is level 3 and the
4976 next is level 4 (or vice versa), level 4 will be used for insertion.
4977 This makes sure that the subtree remains an independent subtree and does
4978 not swallow low level entries.
4980 You can also force a different level, either by using a numeric prefix
4981 argument, or by inserting the heading marker by hand. For example, if the
4982 cursor is after \"*****\", then the tree will be shifted to level 5.
4984 If you want to insert the tree as is, just use \\[yank].
4986 If optional TREE is given, use this text instead of the kill ring."
4987 (interactive "P")
4988 (unless (org-kill-is-subtree-p tree)
4989 (error "%s"
4990 (substitute-command-keys
4991 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4992 (let* ((visp (not (org-invisible-p)))
4993 (txt (or tree (and kill-ring (current-kill 0))))
4994 (^re (concat "^\\(" outline-regexp "\\)"))
4995 (re (concat "\\(" outline-regexp "\\)"))
4996 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4998 (old-level (if (string-match ^re txt)
4999 (- (match-end 0) (match-beginning 0) 1)
5000 -1))
5001 (force-level (cond (level (prefix-numeric-value level))
5002 ((string-match
5003 ^re_ (buffer-substring (point-at-bol) (point)))
5004 (- (match-end 1) (match-beginning 1)))
5005 (t nil)))
5006 (previous-level (save-excursion
5007 (condition-case nil
5008 (progn
5009 (outline-previous-visible-heading 1)
5010 (if (looking-at re)
5011 (- (match-end 0) (match-beginning 0) 1)
5013 (error 1))))
5014 (next-level (save-excursion
5015 (condition-case nil
5016 (progn
5017 (or (looking-at outline-regexp)
5018 (outline-next-visible-heading 1))
5019 (if (looking-at re)
5020 (- (match-end 0) (match-beginning 0) 1)
5022 (error 1))))
5023 (new-level (or force-level (max previous-level next-level)))
5024 (shift (if (or (= old-level -1)
5025 (= new-level -1)
5026 (= old-level new-level))
5028 (- new-level old-level)))
5029 (delta (if (> shift 0) -1 1))
5030 (func (if (> shift 0) 'org-demote 'org-promote))
5031 (org-odd-levels-only nil)
5032 beg end)
5033 ;; Remove the forced level indicator
5034 (if force-level
5035 (delete-region (point-at-bol) (point)))
5036 ;; Paste
5037 (beginning-of-line 1)
5038 (org-back-over-empty-lines)
5039 (setq beg (point))
5040 (insert-before-markers txt)
5041 (unless (string-match "\n\\'" txt) (insert "\n"))
5042 (org-reinstall-markers-in-region beg)
5043 (setq end (point))
5044 (goto-char beg)
5045 (skip-chars-forward " \t\n\r")
5046 (setq beg (point))
5047 (if (and (org-invisible-p) visp)
5048 (save-excursion (outline-show-heading)))
5049 ;; Shift if necessary
5050 (unless (= shift 0)
5051 (save-restriction
5052 (narrow-to-region beg end)
5053 (while (not (= shift 0))
5054 (org-map-region func (point-min) (point-max))
5055 (setq shift (+ delta shift)))
5056 (goto-char (point-min))))
5057 (when (interactive-p)
5058 (message "Clipboard pasted as level %d subtree" new-level))
5059 (if (and kill-ring
5060 (eq org-subtree-clip (current-kill 0))
5061 org-subtree-clip-folded)
5062 ;; The tree was folded before it was killed/copied
5063 (hide-subtree))))
5065 (defun org-kill-is-subtree-p (&optional txt)
5066 "Check if the current kill is an outline subtree, or a set of trees.
5067 Returns nil if kill does not start with a headline, or if the first
5068 headline level is not the largest headline level in the tree.
5069 So this will actually accept several entries of equal levels as well,
5070 which is OK for `org-paste-subtree'.
5071 If optional TXT is given, check this string instead of the current kill."
5072 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
5073 (start-level (and kill
5074 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
5075 org-outline-regexp "\\)")
5076 kill)
5077 (- (match-end 2) (match-beginning 2) 1)))
5078 (re (concat "^" org-outline-regexp))
5079 (start (1+ (match-beginning 2))))
5080 (if (not start-level)
5081 (progn
5082 nil) ;; does not even start with a heading
5083 (catch 'exit
5084 (while (setq start (string-match re kill (1+ start)))
5085 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
5086 (throw 'exit nil)))
5087 t))))
5089 (defvar org-markers-to-move nil
5090 "Markers that should be moved with a cut-and-paste operation.
5091 Those markers are stored together with their positions relative to
5092 the start of the region.")
5094 (defun org-save-markers-in-region (beg end)
5095 "Check markers in region.
5096 If these markers are between BEG and END, record their position relative
5097 to BEG, so that after moving the block of text, we can put the markers back
5098 into place.
5099 This function gets called just before an entry or tree gets cut from the
5100 buffer. After re-insertion, `org-reinstall-markers-in-region' must be
5101 called immediately, to move the markers with the entries."
5102 (setq org-markers-to-move nil)
5103 (when (featurep 'org-clock)
5104 (org-clock-save-markers-for-cut-and-paste beg end))
5105 (when (featurep 'org-agenda)
5106 (org-agenda-save-markers-for-cut-and-paste beg end)))
5108 (defun org-check-and-save-marker (marker beg end)
5109 "Check if MARKER is between BEG and END.
5110 If yes, remember the marker and the distance to BEG."
5111 (when (and (marker-buffer marker)
5112 (equal (marker-buffer marker) (current-buffer)))
5113 (if (and (>= marker beg) (< marker end))
5114 (push (cons marker (- marker beg)) org-markers-to-move))))
5116 (defun org-reinstall-markers-in-region (beg)
5117 "Move all remembered markers to their position relative to BEG."
5118 (mapc (lambda (x)
5119 (move-marker (car x) (+ beg (cdr x))))
5120 org-markers-to-move)
5121 (setq org-markers-to-move nil))
5123 (defun org-narrow-to-subtree ()
5124 "Narrow buffer to the current subtree."
5125 (interactive)
5126 (save-excursion
5127 (save-match-data
5128 (narrow-to-region
5129 (progn (org-back-to-heading) (point))
5130 (progn (org-end-of-subtree t) (point))))))
5133 ;;; Outline Sorting
5135 (defun org-sort (with-case)
5136 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
5137 Optional argument WITH-CASE means sort case-sensitively."
5138 (interactive "P")
5139 (if (org-at-table-p)
5140 (org-call-with-arg 'org-table-sort-lines with-case)
5141 (org-call-with-arg 'org-sort-entries-or-items with-case)))
5143 (defun org-sort-remove-invisible (s)
5144 (remove-text-properties 0 (length s) org-rm-props s)
5145 (while (string-match org-bracket-link-regexp s)
5146 (setq s (replace-match (if (match-end 2)
5147 (match-string 3 s)
5148 (match-string 1 s)) t t s)))
5151 (defvar org-priority-regexp) ; defined later in the file
5153 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
5154 "Sort entries on a certain level of an outline tree.
5155 If there is an active region, the entries in the region are sorted.
5156 Else, if the cursor is before the first entry, sort the top-level items.
5157 Else, the children of the entry at point are sorted.
5159 Sorting can be alphabetically, numerically, and by date/time as given by
5160 the first time stamp in the entry. The command prompts for the sorting
5161 type unless it has been given to the function through the SORTING-TYPE
5162 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
5163 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
5164 called with point at the beginning of the record. It must return either
5165 a string or a number that should serve as the sorting key for that record.
5167 Comparing entries ignores case by default. However, with an optional argument
5168 WITH-CASE, the sorting considers case as well."
5169 (interactive "P")
5170 (let ((case-func (if with-case 'identity 'downcase))
5171 start beg end stars re re2
5172 txt what tmp plain-list-p)
5173 ;; Find beginning and end of region to sort
5174 (cond
5175 ((org-region-active-p)
5176 ;; we will sort the region
5177 (setq end (region-end)
5178 what "region")
5179 (goto-char (region-beginning))
5180 (if (not (org-on-heading-p)) (outline-next-heading))
5181 (setq start (point)))
5182 ((org-at-item-p)
5183 ;; we will sort this plain list
5184 (org-beginning-of-item-list) (setq start (point))
5185 (org-end-of-item-list) (setq end (point))
5186 (goto-char start)
5187 (setq plain-list-p t
5188 what "plain list"))
5189 ((or (org-on-heading-p)
5190 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
5191 ;; we will sort the children of the current headline
5192 (org-back-to-heading)
5193 (setq start (point)
5194 end (progn (org-end-of-subtree t t)
5195 (org-back-over-empty-lines)
5196 (point))
5197 what "children")
5198 (goto-char start)
5199 (show-subtree)
5200 (outline-next-heading))
5202 ;; we will sort the top-level entries in this file
5203 (goto-char (point-min))
5204 (or (org-on-heading-p) (outline-next-heading))
5205 (setq start (point) end (point-max) what "top-level")
5206 (goto-char start)
5207 (show-all)))
5209 (setq beg (point))
5210 (if (>= beg end) (error "Nothing to sort"))
5212 (unless plain-list-p
5213 (looking-at "\\(\\*+\\)")
5214 (setq stars (match-string 1)
5215 re (concat "^" (regexp-quote stars) " +")
5216 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
5217 txt (buffer-substring beg end))
5218 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
5219 (if (and (not (equal stars "*")) (string-match re2 txt))
5220 (error "Region to sort contains a level above the first entry")))
5222 (unless sorting-type
5223 (message
5224 (if plain-list-p
5225 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
5226 "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:")
5227 what)
5228 (setq sorting-type (read-char-exclusive))
5230 (and (= (downcase sorting-type) ?f)
5231 (setq getkey-func
5232 (completing-read "Sort using function: "
5233 obarray 'fboundp t nil nil))
5234 (setq getkey-func (intern getkey-func)))
5236 (and (= (downcase sorting-type) ?r)
5237 (setq property
5238 (completing-read "Property: "
5239 (mapcar 'list (org-buffer-property-keys t))
5240 nil t))))
5242 (message "Sorting entries...")
5244 (save-restriction
5245 (narrow-to-region start end)
5247 (let ((dcst (downcase sorting-type))
5248 (now (current-time)))
5249 (sort-subr
5250 (/= dcst sorting-type)
5251 ;; This function moves to the beginning character of the "record" to
5252 ;; be sorted.
5253 (if plain-list-p
5254 (lambda nil
5255 (if (org-at-item-p) t (goto-char (point-max))))
5256 (lambda nil
5257 (if (re-search-forward re nil t)
5258 (goto-char (match-beginning 0))
5259 (goto-char (point-max)))))
5260 ;; This function moves to the last character of the "record" being
5261 ;; sorted.
5262 (if plain-list-p
5263 'org-end-of-item
5264 (lambda nil
5265 (save-match-data
5266 (condition-case nil
5267 (outline-forward-same-level 1)
5268 (error
5269 (goto-char (point-max)))))))
5271 ;; This function returns the value that gets sorted against.
5272 (if plain-list-p
5273 (lambda nil
5274 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5275 (cond
5276 ((= dcst ?n)
5277 (string-to-number (buffer-substring (match-end 0)
5278 (point-at-eol))))
5279 ((= dcst ?a)
5280 (buffer-substring (match-end 0) (point-at-eol)))
5281 ((= dcst ?t)
5282 (if (re-search-forward org-ts-regexp
5283 (point-at-eol) t)
5284 (org-time-string-to-time (match-string 0))
5285 now))
5286 ((= dcst ?f)
5287 (if getkey-func
5288 (progn
5289 (setq tmp (funcall getkey-func))
5290 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5291 tmp)
5292 (error "Invalid key function `%s'" getkey-func)))
5293 (t (error "Invalid sorting type `%c'" sorting-type)))))
5294 (lambda nil
5295 (cond
5296 ((= dcst ?n)
5297 (if (looking-at outline-regexp)
5298 (string-to-number (buffer-substring (match-end 0)
5299 (point-at-eol)))
5300 nil))
5301 ((= dcst ?a)
5302 (funcall case-func (buffer-substring (point-at-bol)
5303 (point-at-eol))))
5304 ((= dcst ?t)
5305 (if (re-search-forward org-ts-regexp
5306 (save-excursion
5307 (forward-line 2)
5308 (point)) t)
5309 (org-time-string-to-time (match-string 0))
5310 now))
5311 ((= dcst ?p)
5312 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5313 (string-to-char (match-string 2))
5314 org-default-priority))
5315 ((= dcst ?r)
5316 (or (org-entry-get nil property) ""))
5317 ((= dcst ?o)
5318 (if (looking-at org-complex-heading-regexp)
5319 (- 9999 (length (member (match-string 2)
5320 org-todo-keywords-1)))))
5321 ((= dcst ?f)
5322 (if getkey-func
5323 (progn
5324 (setq tmp (funcall getkey-func))
5325 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5326 tmp)
5327 (error "Invalid key function `%s'" getkey-func)))
5328 (t (error "Invalid sorting type `%c'" sorting-type)))))
5330 (cond
5331 ((= dcst ?a) 'string<)
5332 ((= dcst ?t) 'time-less-p)
5333 (t nil)))))
5334 (message "Sorting entries...done")))
5336 (defun org-do-sort (table what &optional with-case sorting-type)
5337 "Sort TABLE of WHAT according to SORTING-TYPE.
5338 The user will be prompted for the SORTING-TYPE if the call to this
5339 function does not specify it. WHAT is only for the prompt, to indicate
5340 what is being sorted. The sorting key will be extracted from
5341 the car of the elements of the table.
5342 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5343 (unless sorting-type
5344 (message
5345 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5346 what)
5347 (setq sorting-type (read-char-exclusive)))
5348 (let ((dcst (downcase sorting-type))
5349 extractfun comparefun)
5350 ;; Define the appropriate functions
5351 (cond
5352 ((= dcst ?n)
5353 (setq extractfun 'string-to-number
5354 comparefun (if (= dcst sorting-type) '< '>)))
5355 ((= dcst ?a)
5356 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5357 (lambda(x) (downcase (org-sort-remove-invisible x))))
5358 comparefun (if (= dcst sorting-type)
5359 'string<
5360 (lambda (a b) (and (not (string< a b))
5361 (not (string= a b)))))))
5362 ((= dcst ?t)
5363 (setq extractfun
5364 (lambda (x)
5365 (if (string-match org-ts-regexp x)
5366 (time-to-seconds
5367 (org-time-string-to-time (match-string 0 x)))
5369 comparefun (if (= dcst sorting-type) '< '>)))
5370 (t (error "Invalid sorting type `%c'" sorting-type)))
5372 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5373 table)
5374 (lambda (a b) (funcall comparefun (car a) (car b))))))
5376 ;;; Editing source examples
5378 (defvar org-exit-edit-mode-map (make-sparse-keymap))
5379 (define-key org-exit-edit-mode-map "\C-c'" 'org-edit-src-exit)
5380 (defvar org-edit-src-force-single-line nil)
5381 (defvar org-edit-src-from-org-mode nil)
5383 (define-minor-mode org-exit-edit-mode
5384 "Minor mode installing a single key binding, \"C-c '\" to exit special edit.")
5386 (defun org-edit-src-code ()
5387 "Edit the source code example at point.
5388 An indirect buffer is created, and that buffer is then narrowed to the
5389 example at point and switched to the correct language mode. When done,
5390 exit by killing the buffer with \\[org-edit-src-exit]."
5391 (interactive)
5392 (let ((line (org-current-line))
5393 (case-fold-search t)
5394 (msg (substitute-command-keys
5395 "Edit, then exit with C-c ' (C-c and single quote)"))
5396 (info (org-edit-src-find-region-and-lang))
5397 (org-mode-p (eq major-mode 'org-mode))
5398 beg end lang lang-f single)
5399 (if (not info)
5401 (setq beg (nth 0 info)
5402 end (nth 1 info)
5403 lang (nth 2 info)
5404 single (nth 3 info)
5405 lang-f (intern (concat lang "-mode")))
5406 (unless (functionp lang-f)
5407 (error "No such language mode: %s" lang-f))
5408 (goto-line line)
5409 (if (get-buffer "*Org Edit Src Example*")
5410 (kill-buffer "*Org Edit Src Example*"))
5411 (switch-to-buffer (make-indirect-buffer (current-buffer)
5412 "*Org Edit Src Example*"))
5413 (narrow-to-region beg end)
5414 (remove-text-properties beg end '(display nil invisible nil
5415 intangible nil))
5416 (let ((org-inhibit-startup t))
5417 (funcall lang-f))
5418 (set (make-local-variable 'org-edit-src-force-single-line) single)
5419 (set (make-local-variable 'org-edit-src-from-org-mode) org-mode-p)
5420 (when org-mode-p
5421 (goto-char (point-min))
5422 (while (re-search-forward "^," nil t)
5423 (replace-match "")))
5424 (goto-line line)
5425 (org-exit-edit-mode)
5426 (org-set-local 'header-line-format msg)
5427 (message "%s" msg)
5428 t)))
5430 (defun org-edit-src-find-region-and-lang ()
5431 "Find the region and language for a local edit.
5432 Return a list with beginning and end of the region, a string representing
5433 the language, a switch telling of the content should be in a single line."
5434 (let ((re-list
5436 ("<src\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</src>" lang)
5437 ("<literal\\>[^<]*>[ \t]*\n?" "\n?[ \t]*</literal>" style)
5438 ("<example>[ \t]*\n?" "\n?[ \t]*</example>" "fundamental")
5439 ("<lisp>[ \t]*\n?" "\n?[ \t]*</lisp>" "emacs-lisp")
5440 ("<perl>[ \t]*\n?" "\n?[ \t]*</perl>" "perl")
5441 ("<python>[ \t]*\n?" "\n?[ \t]*</python>" "python")
5442 ("<ruby>[ \t]*\n?" "\n?[ \t]*</ruby>" "ruby")
5443 ("^#\\+begin_src\\( \\([^ \t\n]+\\)\\)?.*\n" "\n#\\+end_src" 2)
5444 ("^#\\+begin_example.*\n" "^#\\+end_example" "fundamental")
5445 ("^#\\+html:" "\n" "html" single-line)
5446 ("^#\\+begin_html.*\n" "\n#\\+end_html" "html")
5447 ("^#\\+begin_latex.*\n" "\n#\\+end_latex" "latex")
5448 ("^#\\+latex:" "\n" "latex" single-line)
5449 ("^#\\+begin_ascii.*\n" "\n#\\+end_ascii" "fundamental")
5450 ("^#\\+ascii:" "\n" "ascii" single-line)
5452 (pos (point))
5453 re re1 re2 single beg end lang)
5454 (catch 'exit
5455 (while (setq entry (pop re-list))
5456 (setq re1 (car entry) re2 (nth 1 entry) lang (nth 2 entry)
5457 single (nth 3 entry))
5458 (save-excursion
5459 (if (or (looking-at re1)
5460 (re-search-backward re1 nil t))
5461 (progn
5462 (setq beg (match-end 0) lang (org-edit-src-get-lang lang))
5463 (if (and (re-search-forward re2 nil t)
5464 (>= (match-end 0) pos))
5465 (throw 'exit (list beg (match-beginning 0) lang single))))
5466 (if (or (looking-at re2)
5467 (re-search-forward re2 nil t))
5468 (progn
5469 (setq end (match-beginning 0))
5470 (if (and (re-search-backward re1 nil t)
5471 (<= (match-beginning 0) pos))
5472 (throw 'exit
5473 (list (match-end 0) end
5474 (org-edit-src-get-lang lang) single)))))))))))
5476 (defun org-edit-src-get-lang (lang)
5477 "Extract the src language."
5478 (let ((m (match-string 0)))
5479 (cond
5480 ((stringp lang) lang)
5481 ((integerp lang) (match-string lang))
5482 ((and (eq lang lang)
5483 (string-match "\\<lang=\"\\([^ \t\n\"]+\\)\"" m))
5484 (match-string 1 m))
5485 ((and (eq lang lang)
5486 (string-match "\\<style=\"\\([^ \t\n\"]+\\)\"" m))
5487 (match-string 1 m))
5488 (t "fundamental"))))
5490 (defun org-edit-src-exit ()
5491 "Exit special edit and protect problematic lines."
5492 (interactive)
5493 (unless (buffer-base-buffer (current-buffer))
5494 (error "This is not an indirect buffer, something is wrong..."))
5495 (unless (> (point-min) 1)
5496 (error "This buffer is not narrowed, something is wrong..."))
5497 (goto-char (point-min))
5498 (if (looking-at "[ \t\n]*\n") (replace-match ""))
5499 (if (re-search-forward "\n[ \t\n]*\\'" nil t) (replace-match ""))
5500 (when (org-bound-and-true-p org-edit-src-force-single-line)
5501 (goto-char (point-min))
5502 (while (re-search-forward "\n" nil t)
5503 (replace-match " "))
5504 (goto-char (point-min))
5505 (if (looking-at "\\s-*") (replace-match " "))
5506 (if (re-search-forward "\\s-+\\'" nil t)
5507 (replace-match "")))
5508 (when (org-bound-and-true-p org-edit-src-from-org-mode)
5509 (goto-char (point-min))
5510 (while (re-search-forward (if (org-mode-p) "^\\(.\\)" "^\\([*#]\\)") nil t)
5511 (replace-match ",\\1"))
5512 (when font-lock-mode
5513 (font-lock-unfontify-region (point-min) (point-max)))
5514 (put-text-property (point-min) (point-max) 'font-lock-fontified t))
5515 (kill-buffer (current-buffer))
5516 (and (org-mode-p) (org-restart-font-lock)))
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