General operators for property searches.
[org-mode/org-mode-NeilSmithlineMods.git] / lisp / org.el
blob4ebe0338ab677ff0199ea6375a376601b6ce5e1d
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.02pre-04
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, or (at your option)
15 ;; 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; see the file COPYING. If not, write to the
24 ;; Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
25 ;; Boston, MA 02110-1301, USA.
26 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
28 ;;; Commentary:
30 ;; Org-mode is a mode for keeping notes, maintaining ToDo lists, and doing
31 ;; project planning with a fast and effective plain-text system.
33 ;; Org-mode develops organizational tasks around NOTES files that contain
34 ;; information about projects as plain text. Org-mode is implemented on
35 ;; top of outline-mode, which makes it possible to keep the content of
36 ;; large files well structured. Visibility cycling and structure editing
37 ;; help to work with the tree. Tables are easily created with a built-in
38 ;; table editor. Org-mode supports ToDo items, deadlines, time stamps,
39 ;; and scheduling. It dynamically compiles entries into an agenda that
40 ;; utilizes and smoothly integrates much of the Emacs calendar and diary.
41 ;; Plain text URL-like links connect to websites, emails, Usenet
42 ;; messages, BBDB entries, and any files related to the projects. For
43 ;; printing and sharing of notes, an Org-mode file can be exported as a
44 ;; structured ASCII file, as HTML, or (todo and agenda items only) as an
45 ;; iCalendar file. It can also serve as a publishing tool for a set of
46 ;; linked webpages.
48 ;; Installation and Activation
49 ;; ---------------------------
50 ;; See the corresponding sections in the manual at
52 ;; http://orgmode.org/org.html#Installation
54 ;; Documentation
55 ;; -------------
56 ;; The documentation of Org-mode can be found in the TeXInfo file. The
57 ;; distribution also contains a PDF version of it. At the homepage of
58 ;; Org-mode, you can read the same text online as HTML. There is also an
59 ;; excellent reference card made by Philip Rooke. This card can be found
60 ;; in the etc/ directory of Emacs 22.
62 ;; A list of recent changes can be found at
63 ;; http://orgmode.org/Changes.html
65 ;;; Code:
67 (defvar org-inhibit-highlight-removal nil) ; dynamically scoped param
68 (defvar org-table-formula-constants-local nil
69 "Local version of `org-table-formula-constants'.")
70 (make-variable-buffer-local 'org-table-formula-constants-local)
72 ;;;; Require other packages
74 (eval-when-compile
75 (require 'cl)
76 (require 'gnus-sum)
77 (require 'calendar))
78 ;; For XEmacs, noutline is not yet provided by outline.el, so arrange for
79 ;; the file noutline.el being loaded.
80 (if (featurep 'xemacs) (condition-case nil (require 'noutline)))
81 ;; We require noutline, which might be provided in outline.el
82 (require 'outline) (require 'noutline)
83 ;; Other stuff we need.
84 (require 'time-date)
85 (unless (fboundp 'time-subtract) (defalias 'time-subtract 'subtract-time))
86 (require 'easymenu)
88 (require 'org-macs)
89 (require 'org-compat)
90 (require 'org-faces)
92 ;;;; Customization variables
94 ;;; Version
96 (defconst org-version "6.02pre-04"
97 "The version number of the file org.el.")
99 (defun org-version (&optional here)
100 "Show the org-mode version in the echo area.
101 With prefix arg HERE, insert it at point."
102 (interactive "P")
103 (let ((version (format "Org-mode version %s" org-version)))
104 (message version)
105 (if here
106 (insert version))))
108 ;;; Compatibility constants
110 ;;; The custom variables
112 (defgroup org nil
113 "Outline-based notes management and organizer."
114 :tag "Org"
115 :group 'outlines
116 :group 'hypermedia
117 :group 'calendar)
119 (defcustom org-load-hook nil
120 "Hook that is run after org.el has been loaded."
121 :group 'org
122 :type 'hook)
124 (defvar org-modules) ; defined below
125 (defvar org-modules-loaded nil
126 "Have the modules been loaded already?")
128 (defun org-load-modules-maybe (&optional force)
129 "Load all extensions listed in `org-default-extensions'."
130 (when (or force (not org-modules-loaded))
131 (mapc (lambda (ext)
132 (condition-case nil (require ext)
133 (error (message "Problems while trying to load feature `%s'" ext))))
134 org-modules)
135 (setq org-modules-loaded t)))
137 (defun org-set-modules (var value)
138 "Set VAR to VALUE and call `org-load-modules-maybe' with the force flag."
139 (set var value)
140 (when (featurep 'org)
141 (org-load-modules-maybe 'force)))
143 (defcustom org-modules '(org-bbdb org-bibtex org-gnus org-info org-infojs org-irc org-mew org-mhe org-rmail org-vm org-wl)
144 "Modules that should always be loaded together with org.el.
145 If a description starts with <C>, the file is not part of emacs
146 and loading it will require that you have downloaded and properly installed
147 the org-mode distribution.
149 You can also use this system to load external packages (i.e. neither Org
150 core modules, not modules from the CONTRIB directory). Just add symbols
151 to the end of the list. If the package is called org-xyz.e, then you need
152 to add the symbol `xyz', and the package must have a call to
154 (provide 'org-xyz)"
155 :group 'org
156 :set 'org-set-modules
157 :type
158 '(set :greedy t
159 (const :tag " bbdb: Links to BBDB entries" org-bbdb)
160 (const :tag " bibtex: Links to BibTeX entries" org-bibtex)
161 (const :tag " gnus: Links to GNUS folders/messages" org-gnus)
162 (const :tag " info: Links to Info nodes" org-info)
163 (const :tag " infojs: Set up Sebastian Rose's JavaScript org-info.js" org-infojs)
164 (const :tag " irc: Links to IRC/ERC chat sessions" org-irc)
165 (const :tag " mac-message: Links to messages in Apple Mail" org-mac-message)
166 (const :tag " mew Links to Mew folders/messages" org-mew)
167 (const :tag " mhe: Links to MHE folders/messages" org-mhe)
168 (const :tag " rmail: Links to RMAIL folders/messages" org-rmail)
169 (const :tag " vm: Links to VM folders/messages" org-vm)
170 (const :tag " wl: Links to Wanderlust folders/messages" org-wl)
171 (const :tag " mouse: Additional mouse support" org-mouse)
173 (const :tag "C annotate-file: Annotate a file with org syntax" org-annotate-file)
174 (const :tag "C bookmark: Org links to bookmarks" org-bookmark)
175 (const :tag "C depend: TODO dependencies for Org-mode" org-depend)
176 (const :tag "C elisp-symbol: Org links to emacs-lisp symbols" org-elisp-symbol)
177 (const :tag "C expiry: Expiry mechanism for Org entries" org-expiry)
178 (const :tag "C id: Global id's for identifying entries" org-id)
179 (const :tag "C interactive-query: Interactive modification of tags query" org-interactive-query)
180 (const :tag "C mairix: Hook mairix search into Org for different MUAs" org-mairix)
181 (const :tag "C man: Support for links to manpages in Org-mode" org-man)
182 (const :tag "C mew: Support for links to messages in Mew" org-mew)
183 (const :tag "C panel: Simple routines for us with bad memory" org-panel)
184 (const :tag "C registry: A registry for Org links" org-registry)
185 (const :tag "C org2rem: Convert org appointments into reminders" org2rem)
186 (const :tag "C screen: Visit screen sessions through Org-mode links" org-screen)
187 (const :tag "C toc: Table of contents for Org-mode buffer" org-toc)
188 (const :tag "C sqlinsert: Convert Org-mode tables to SQL insertions" orgtbl-sqlinsert)
189 (repeat :tag "External packages" :inline t (symbol :tag "Package"))))
192 (defgroup org-startup nil
193 "Options concerning startup of Org-mode."
194 :tag "Org Startup"
195 :group 'org)
197 (defcustom org-startup-folded t
198 "Non-nil means, entering Org-mode will switch to OVERVIEW.
199 This can also be configured on a per-file basis by adding one of
200 the following lines anywhere in the buffer:
202 #+STARTUP: fold
203 #+STARTUP: nofold
204 #+STARTUP: content"
205 :group 'org-startup
206 :type '(choice
207 (const :tag "nofold: show all" nil)
208 (const :tag "fold: overview" t)
209 (const :tag "content: all headlines" content)))
211 (defcustom org-startup-truncated t
212 "Non-nil means, entering Org-mode will set `truncate-lines'.
213 This is useful since some lines containing links can be very long and
214 uninteresting. Also tables look terrible when wrapped."
215 :group 'org-startup
216 :type 'boolean)
218 (defcustom org-startup-align-all-tables nil
219 "Non-nil means, align all tables when visiting a file.
220 This is useful when the column width in tables is forced with <N> cookies
221 in table fields. Such tables will look correct only after the first re-align.
222 This can also be configured on a per-file basis by adding one of
223 the following lines anywhere in the buffer:
224 #+STARTUP: align
225 #+STARTUP: noalign"
226 :group 'org-startup
227 :type 'boolean)
229 (defcustom org-insert-mode-line-in-empty-file nil
230 "Non-nil means insert the first line setting Org-mode in empty files.
231 When the function `org-mode' is called interactively in an empty file, this
232 normally means that the file name does not automatically trigger Org-mode.
233 To ensure that the file will always be in Org-mode in the future, a
234 line enforcing Org-mode will be inserted into the buffer, if this option
235 has been set."
236 :group 'org-startup
237 :type 'boolean)
239 (defcustom org-replace-disputed-keys nil
240 "Non-nil means use alternative key bindings for some keys.
241 Org-mode uses S-<cursor> keys for changing timestamps and priorities.
242 These keys are also used by other packages like `CUA-mode' or `windmove.el'.
243 If you want to use Org-mode together with one of these other modes,
244 or more generally if you would like to move some Org-mode commands to
245 other keys, set this variable and configure the keys with the variable
246 `org-disputed-keys'.
248 This option is only relevant at load-time of Org-mode, and must be set
249 *before* org.el is loaded. Changing it requires a restart of Emacs to
250 become effective."
251 :group 'org-startup
252 :type 'boolean)
254 (if (fboundp 'defvaralias)
255 (defvaralias 'org-CUA-compatible 'org-replace-disputed-keys))
257 (defcustom org-disputed-keys
258 '(([(shift up)] . [(meta p)])
259 ([(shift down)] . [(meta n)])
260 ([(shift left)] . [(meta -)])
261 ([(shift right)] . [(meta +)])
262 ([(control shift right)] . [(meta shift +)])
263 ([(control shift left)] . [(meta shift -)]))
264 "Keys for which Org-mode and other modes compete.
265 This is an alist, cars are the default keys, second element specifies
266 the alternative to use when `org-replace-disputed-keys' is t.
268 Keys can be specified in any syntax supported by `define-key'.
269 The value of this option takes effect only at Org-mode's startup,
270 therefore you'll have to restart Emacs to apply it after changing."
271 :group 'org-startup
272 :type 'alist)
274 (defun org-key (key)
275 "Select key according to `org-replace-disputed-keys' and `org-disputed-keys'.
276 Or return the original if not disputed."
277 (if org-replace-disputed-keys
278 (let* ((nkey (key-description key))
279 (x (org-find-if (lambda (x)
280 (equal (key-description (car x)) nkey))
281 org-disputed-keys)))
282 (if x (cdr x) key))
283 key))
285 (defun org-find-if (predicate seq)
286 (catch 'exit
287 (while seq
288 (if (funcall predicate (car seq))
289 (throw 'exit (car seq))
290 (pop seq)))))
292 (defun org-defkey (keymap key def)
293 "Define a key, possibly translated, as returned by `org-key'."
294 (define-key keymap (org-key key) def))
296 (defcustom org-ellipsis nil
297 "The ellipsis to use in the Org-mode outline.
298 When nil, just use the standard three dots. When a string, use that instead,
299 When a face, use the standart 3 dots, but with the specified face.
300 The change affects only Org-mode (which will then use its own display table).
301 Changing this requires executing `M-x org-mode' in a buffer to become
302 effective."
303 :group 'org-startup
304 :type '(choice (const :tag "Default" nil)
305 (face :tag "Face" :value org-warning)
306 (string :tag "String" :value "...#")))
308 (defvar org-display-table nil
309 "The display table for org-mode, in case `org-ellipsis' is non-nil.")
311 (defgroup org-keywords nil
312 "Keywords in Org-mode."
313 :tag "Org Keywords"
314 :group 'org)
316 (defcustom org-deadline-string "DEADLINE:"
317 "String to mark deadline entries.
318 A deadline is this string, followed by a time stamp. Should be a word,
319 terminated by a colon. You can insert a schedule keyword and
320 a timestamp with \\[org-deadline].
321 Changes become only effective after restarting Emacs."
322 :group 'org-keywords
323 :type 'string)
325 (defcustom org-scheduled-string "SCHEDULED:"
326 "String to mark scheduled TODO entries.
327 A schedule is this string, followed by a time stamp. Should be a word,
328 terminated by a colon. You can insert a schedule keyword and
329 a timestamp with \\[org-schedule].
330 Changes become only effective after restarting Emacs."
331 :group 'org-keywords
332 :type 'string)
334 (defcustom org-closed-string "CLOSED:"
335 "String used as the prefix for timestamps logging closing a TODO entry."
336 :group 'org-keywords
337 :type 'string)
339 (defcustom org-clock-string "CLOCK:"
340 "String used as prefix for timestamps clocking work hours on an item."
341 :group 'org-keywords
342 :type 'string)
344 (defcustom org-comment-string "COMMENT"
345 "Entries starting with this keyword will never be exported.
346 An entry can be toggled between COMMENT and normal with
347 \\[org-toggle-comment].
348 Changes become only effective after restarting Emacs."
349 :group 'org-keywords
350 :type 'string)
352 (defcustom org-quote-string "QUOTE"
353 "Entries starting with this keyword will be exported in fixed-width font.
354 Quoting applies only to the text in the entry following the headline, and does
355 not extend beyond the next headline, even if that is lower level.
356 An entry can be toggled between QUOTE and normal with
357 \\[org-toggle-fixed-width-section]."
358 :group 'org-keywords
359 :type 'string)
361 (defconst org-repeat-re
362 "<[0-9]\\{4\\}-[0-9][0-9]-[0-9][0-9] [^>\n]*\\([.+]?\\+[0-9]+[dwmy]\\)"
363 "Regular expression for specifying repeated events.
364 After a match, group 1 contains the repeat expression.")
366 (defgroup org-structure nil
367 "Options concerning the general structure of Org-mode files."
368 :tag "Org Structure"
369 :group 'org)
371 (defgroup org-reveal-location nil
372 "Options about how to make context of a location visible."
373 :tag "Org Reveal Location"
374 :group 'org-structure)
376 (defconst org-context-choice
377 '(choice
378 (const :tag "Always" t)
379 (const :tag "Never" nil)
380 (repeat :greedy t :tag "Individual contexts"
381 (cons
382 (choice :tag "Context"
383 (const agenda)
384 (const org-goto)
385 (const occur-tree)
386 (const tags-tree)
387 (const link-search)
388 (const mark-goto)
389 (const bookmark-jump)
390 (const isearch)
391 (const default))
392 (boolean))))
393 "Contexts for the reveal options.")
395 (defcustom org-show-hierarchy-above '((default . t))
396 "Non-nil means, show full hierarchy when revealing a location.
397 Org-mode often shows locations in an org-mode file which might have
398 been invisible before. When this is set, the hierarchy of headings
399 above the exposed location is shown.
400 Turning this off for example for sparse trees makes them very compact.
401 Instead of t, this can also be an alist specifying this option for different
402 contexts. Valid contexts are
403 agenda when exposing an entry from the agenda
404 org-goto when using the command `org-goto' on key C-c C-j
405 occur-tree when using the command `org-occur' on key C-c /
406 tags-tree when constructing a sparse tree based on tags matches
407 link-search when exposing search matches associated with a link
408 mark-goto when exposing the jump goal of a mark
409 bookmark-jump when exposing a bookmark location
410 isearch when exiting from an incremental search
411 default default for all contexts not set explicitly"
412 :group 'org-reveal-location
413 :type org-context-choice)
415 (defcustom org-show-following-heading '((default . nil))
416 "Non-nil means, show following heading when revealing a location.
417 Org-mode often shows locations in an org-mode file which might have
418 been invisible before. When this is set, the heading following the
419 match is shown.
420 Turning this off for example for sparse trees makes them very compact,
421 but makes it harder to edit the location of the match. In such a case,
422 use the command \\[org-reveal] to show more context.
423 Instead of t, this can also be an alist specifying this option for different
424 contexts. See `org-show-hierarchy-above' for valid contexts."
425 :group 'org-reveal-location
426 :type org-context-choice)
428 (defcustom org-show-siblings '((default . nil) (isearch t))
429 "Non-nil means, show all sibling heading when revealing a location.
430 Org-mode often shows locations in an org-mode file which might have
431 been invisible before. When this is set, the sibling of the current entry
432 heading are all made visible. If `org-show-hierarchy-above' is t,
433 the same happens on each level of the hierarchy above the current entry.
435 By default this is on for the isearch context, off for all other contexts.
436 Turning this off for example for sparse trees makes them very compact,
437 but makes it harder to edit the location of the match. In such a case,
438 use the command \\[org-reveal] to show more context.
439 Instead of t, this can also be an alist specifying this option for different
440 contexts. See `org-show-hierarchy-above' for valid contexts."
441 :group 'org-reveal-location
442 :type org-context-choice)
444 (defcustom org-show-entry-below '((default . nil))
445 "Non-nil means, show the entry below a headline when revealing a location.
446 Org-mode often shows locations in an org-mode file which might have
447 been invisible before. When this is set, the text below the headline that is
448 exposed is also shown.
450 By default this is off for all contexts.
451 Instead of t, this can also be an alist specifying this option for different
452 contexts. See `org-show-hierarchy-above' for valid contexts."
453 :group 'org-reveal-location
454 :type org-context-choice)
456 (defcustom org-indirect-buffer-display 'other-window
457 "How should indirect tree buffers be displayed?
458 This applies to indirect buffers created with the commands
459 \\[org-tree-to-indirect-buffer] and \\[org-agenda-tree-to-indirect-buffer].
460 Valid values are:
461 current-window Display in the current window
462 other-window Just display in another window.
463 dedicated-frame Create one new frame, and re-use it each time.
464 new-frame Make a new frame each time. Note that in this case
465 previously-made indirect buffers are kept, and you need to
466 kill these buffers yourself."
467 :group 'org-structure
468 :group 'org-agenda-windows
469 :type '(choice
470 (const :tag "In current window" current-window)
471 (const :tag "In current frame, other window" other-window)
472 (const :tag "Each time a new frame" new-frame)
473 (const :tag "One dedicated frame" dedicated-frame)))
475 (defgroup org-cycle nil
476 "Options concerning visibility cycling in Org-mode."
477 :tag "Org Cycle"
478 :group 'org-structure)
480 (defcustom org-drawers '("PROPERTIES" "CLOCK")
481 "Names of drawers. Drawers are not opened by cycling on the headline above.
482 Drawers only open with a TAB on the drawer line itself. A drawer looks like
483 this:
484 :DRAWERNAME:
485 .....
486 :END:
487 The drawer \"PROPERTIES\" is special for capturing properties through
488 the property API.
490 Drawers can be defined on the per-file basis with a line like:
492 #+DRAWERS: HIDDEN STATE PROPERTIES"
493 :group 'org-structure
494 :type '(repeat (string :tag "Drawer Name")))
496 (defcustom org-cycle-global-at-bob nil
497 "Cycle globally if cursor is at beginning of buffer and not at a headline.
498 This makes it possible to do global cycling without having to use S-TAB or
499 C-u TAB. For this special case to work, the first line of the buffer
500 must not be a headline - it may be empty ot some other text. When used in
501 this way, `org-cycle-hook' is disables temporarily, to make sure the
502 cursor stays at the beginning of the buffer.
503 When this option is nil, don't do anything special at the beginning
504 of the buffer."
505 :group 'org-cycle
506 :type 'boolean)
508 (defcustom org-cycle-emulate-tab t
509 "Where should `org-cycle' emulate TAB.
510 nil Never
511 white Only in completely white lines
512 whitestart Only at the beginning of lines, before the first non-white char
513 t Everywhere except in headlines
514 exc-hl-bol Everywhere except at the start of a headline
515 If TAB is used in a place where it does not emulate TAB, the current subtree
516 visibility is cycled."
517 :group 'org-cycle
518 :type '(choice (const :tag "Never" nil)
519 (const :tag "Only in completely white lines" white)
520 (const :tag "Before first char in a line" whitestart)
521 (const :tag "Everywhere except in headlines" t)
522 (const :tag "Everywhere except at bol in headlines" exc-hl-bol)
525 (defcustom org-cycle-separator-lines 2
526 "Number of empty lines needed to keep an empty line between collapsed trees.
527 If you leave an empty line between the end of a subtree and the following
528 headline, this empty line is hidden when the subtree is folded.
529 Org-mode will leave (exactly) one empty line visible if the number of
530 empty lines is equal or larger to the number given in this variable.
531 So the default 2 means, at least 2 empty lines after the end of a subtree
532 are needed to produce free space between a collapsed subtree and the
533 following headline.
535 Special case: when 0, never leave empty lines in collapsed view."
536 :group 'org-cycle
537 :type 'integer)
539 (defcustom org-cycle-hook '(org-cycle-hide-archived-subtrees
540 org-cycle-hide-drawers
541 org-cycle-show-empty-lines
542 org-optimize-window-after-visibility-change)
543 "Hook that is run after `org-cycle' has changed the buffer visibility.
544 The function(s) in this hook must accept a single argument which indicates
545 the new state that was set by the most recent `org-cycle' command. The
546 argument is a symbol. After a global state change, it can have the values
547 `overview', `content', or `all'. After a local state change, it can have
548 the values `folded', `children', or `subtree'."
549 :group 'org-cycle
550 :type 'hook)
552 (defgroup org-edit-structure nil
553 "Options concerning structure editing in Org-mode."
554 :tag "Org Edit Structure"
555 :group 'org-structure)
557 (defcustom org-odd-levels-only nil
558 "Non-nil means, skip even levels and only use odd levels for the outline.
559 This has the effect that two stars are being added/taken away in
560 promotion/demotion commands. It also influences how levels are
561 handled by the exporters.
562 Changing it requires restart of `font-lock-mode' to become effective
563 for fontification also in regions already fontified.
564 You may also set this on a per-file basis by adding one of the following
565 lines to the buffer:
567 #+STARTUP: odd
568 #+STARTUP: oddeven"
569 :group 'org-edit-structure
570 :group 'org-font-lock
571 :type 'boolean)
573 (defcustom org-adapt-indentation t
574 "Non-nil means, adapt indentation when promoting and demoting.
575 When this is set and the *entire* text in an entry is indented, the
576 indentation is increased by one space in a demotion command, and
577 decreased by one in a promotion command. If any line in the entry
578 body starts at column 0, indentation is not changed at all."
579 :group 'org-edit-structure
580 :type 'boolean)
582 (defcustom org-special-ctrl-a/e nil
583 "Non-nil means `C-a' and `C-e' behave specially in headlines and items.
584 When t, `C-a' will bring back the cursor to the beginning of the
585 headline text, i.e. after the stars and after a possible TODO keyword.
586 In an item, this will be the position after the bullet.
587 When the cursor is already at that position, another `C-a' will bring
588 it to the beginning of the line.
589 `C-e' will jump to the end of the headline, ignoring the presence of tags
590 in the headline. A second `C-e' will then jump to the true end of the
591 line, after any tags.
592 When set to the symbol `reversed', the first `C-a' or `C-e' works normally,
593 and only a directly following, identical keypress will bring the cursor
594 to the special positions."
595 :group 'org-edit-structure
596 :type '(choice
597 (const :tag "off" nil)
598 (const :tag "after bullet first" t)
599 (const :tag "border first" reversed)))
601 (if (fboundp 'defvaralias)
602 (defvaralias 'org-special-ctrl-a 'org-special-ctrl-a/e))
604 (defcustom org-special-ctrl-k nil
605 "Non-nil means `C-k' will behave specially in headlines.
606 When nil, `C-k' will call the default `kill-line' command.
607 When t, the following will happen while the cursor is in the headline:
609 - When the cursor is at the beginning of a headline, kill the entire
610 line and possible the folded subtree below the line.
611 - When in the middle of the headline text, kill the headline up to the tags.
612 - When after the headline text, kill the tags."
613 :group 'org-edit-structure
614 :type 'boolean)
616 (defcustom org-M-RET-may-split-line '((default . t))
617 "Non-nil means, M-RET will split the line at the cursor position.
618 When nil, it will go to the end of the line before making a
619 new line.
620 You may also set this option in a different way for different
621 contexts. Valid contexts are:
623 headline when creating a new headline
624 item when creating a new item
625 table in a table field
626 default the value to be used for all contexts not explicitly
627 customized"
628 :group 'org-structure
629 :group 'org-table
630 :type '(choice
631 (const :tag "Always" t)
632 (const :tag "Never" nil)
633 (repeat :greedy t :tag "Individual contexts"
634 (cons
635 (choice :tag "Context"
636 (const headline)
637 (const item)
638 (const table)
639 (const default))
640 (boolean)))))
643 (defcustom org-blank-before-new-entry '((heading . nil)
644 (plain-list-item . nil))
645 "Should `org-insert-heading' leave a blank line before new heading/item?
646 The value is an alist, with `heading' and `plain-list-item' as car,
647 and a boolean flag as cdr."
648 :group 'org-edit-structure
649 :type '(list
650 (cons (const heading) (boolean))
651 (cons (const plain-list-item) (boolean))))
653 (defcustom org-insert-heading-hook nil
654 "Hook being run after inserting a new heading."
655 :group 'org-edit-structure
656 :type 'hook)
658 (defcustom org-enable-fixed-width-editor t
659 "Non-nil means, lines starting with \":\" are treated as fixed-width.
660 This currently only means, they are never auto-wrapped.
661 When nil, such lines will be treated like ordinary lines.
662 See also the QUOTE keyword."
663 :group 'org-edit-structure
664 :type 'boolean)
666 (defcustom org-goto-auto-isearch t
667 "Non-nil means, typing characters in org-goto starts incremental search."
668 :group 'org-edit-structure
669 :type 'boolean)
671 (defgroup org-sparse-trees nil
672 "Options concerning sparse trees in Org-mode."
673 :tag "Org Sparse Trees"
674 :group 'org-structure)
676 (defcustom org-highlight-sparse-tree-matches t
677 "Non-nil means, highlight all matches that define a sparse tree.
678 The highlights will automatically disappear the next time the buffer is
679 changed by an edit command."
680 :group 'org-sparse-trees
681 :type 'boolean)
683 (defcustom org-remove-highlights-with-change t
684 "Non-nil means, any change to the buffer will remove temporary highlights.
685 Such highlights are created by `org-occur' and `org-clock-display'.
686 When nil, `C-c C-c needs to be used to get rid of the highlights.
687 The highlights created by `org-preview-latex-fragment' always need
688 `C-c C-c' to be removed."
689 :group 'org-sparse-trees
690 :group 'org-time
691 :type 'boolean)
694 (defcustom org-occur-hook '(org-first-headline-recenter)
695 "Hook that is run after `org-occur' has constructed a sparse tree.
696 This can be used to recenter the window to show as much of the structure
697 as possible."
698 :group 'org-sparse-trees
699 :type 'hook)
701 (defgroup org-plain-lists nil
702 "Options concerning plain lists in Org-mode."
703 :tag "Org Plain lists"
704 :group 'org-structure)
706 (defcustom org-cycle-include-plain-lists nil
707 "Non-nil means, include plain lists into visibility cycling.
708 This means that during cycling, plain list items will *temporarily* be
709 interpreted as outline headlines with a level given by 1000+i where i is the
710 indentation of the bullet. In all other operations, plain list items are
711 not seen as headlines. For example, you cannot assign a TODO keyword to
712 such an item."
713 :group 'org-plain-lists
714 :type 'boolean)
716 (defcustom org-plain-list-ordered-item-terminator t
717 "The character that makes a line with leading number an ordered list item.
718 Valid values are ?. and ?\). To get both terminators, use t. While
719 ?. may look nicer, it creates the danger that a line with leading
720 number may be incorrectly interpreted as an item. ?\) therefore is
721 the safe choice."
722 :group 'org-plain-lists
723 :type '(choice (const :tag "dot like in \"2.\"" ?.)
724 (const :tag "paren like in \"2)\"" ?\))
725 (const :tab "both" t)))
727 (defcustom org-empty-line-terminates-plain-lists nil
728 "Non-nil means, an empty line ends all plain list levels.
729 When nil, empty lines are part of the preceeding item."
730 :group 'org-plain-lists
731 :type 'boolean)
733 (defcustom org-auto-renumber-ordered-lists t
734 "Non-nil means, automatically renumber ordered plain lists.
735 Renumbering happens when the sequence have been changed with
736 \\[org-shiftmetaup] or \\[org-shiftmetadown]. After other editing commands,
737 use \\[org-ctrl-c-ctrl-c] to trigger renumbering."
738 :group 'org-plain-lists
739 :type 'boolean)
741 (defcustom org-provide-checkbox-statistics t
742 "Non-nil means, update checkbox statistics after insert and toggle.
743 When this is set, checkbox statistics is updated each time you either insert
744 a new checkbox with \\[org-insert-todo-heading] or toggle a checkbox
745 with \\[org-ctrl-c-ctrl-c\\]."
746 :group 'org-plain-lists
747 :type 'boolean)
750 (defgroup org-imenu-and-speedbar nil
751 "Options concerning imenu and speedbar in Org-mode."
752 :tag "Org Imenu and Speedbar"
753 :group 'org-structure)
755 (defcustom org-imenu-depth 2
756 "The maximum level for Imenu access to Org-mode headlines.
757 This also applied for speedbar access."
758 :group 'org-imenu-and-speedbar
759 :type 'number)
761 (defgroup org-table nil
762 "Options concerning tables in Org-mode."
763 :tag "Org Table"
764 :group 'org)
766 (defcustom org-enable-table-editor 'optimized
767 "Non-nil means, lines starting with \"|\" are handled by the table editor.
768 When nil, such lines will be treated like ordinary lines.
770 When equal to the symbol `optimized', the table editor will be optimized to
771 do the following:
772 - Automatic overwrite mode in front of whitespace in table fields.
773 This makes the structure of the table stay in tact as long as the edited
774 field does not exceed the column width.
775 - Minimize the number of realigns. Normally, the table is aligned each time
776 TAB or RET are pressed to move to another field. With optimization this
777 happens only if changes to a field might have changed the column width.
778 Optimization requires replacing the functions `self-insert-command',
779 `delete-char', and `backward-delete-char' in Org-mode buffers, with a
780 slight (in fact: unnoticeable) speed impact for normal typing. Org-mode is
781 very good at guessing when a re-align will be necessary, but you can always
782 force one with \\[org-ctrl-c-ctrl-c].
784 If you would like to use the optimized version in Org-mode, but the
785 un-optimized version in OrgTbl-mode, see the variable `orgtbl-optimized'.
787 This variable can be used to turn on and off the table editor during a session,
788 but in order to toggle optimization, a restart is required.
790 See also the variable `org-table-auto-blank-field'."
791 :group 'org-table
792 :type '(choice
793 (const :tag "off" nil)
794 (const :tag "on" t)
795 (const :tag "on, optimized" optimized)))
797 (defcustom org-table-tab-recognizes-table.el t
798 "Non-nil means, TAB will automatically notice a table.el table.
799 When it sees such a table, it moves point into it and - if necessary -
800 calls `table-recognize-table'."
801 :group 'org-table-editing
802 :type 'boolean)
804 (defgroup org-link nil
805 "Options concerning links in Org-mode."
806 :tag "Org Link"
807 :group 'org)
809 (defvar org-link-abbrev-alist-local nil
810 "Buffer-local version of `org-link-abbrev-alist', which see.
811 The value of this is taken from the #+LINK lines.")
812 (make-variable-buffer-local 'org-link-abbrev-alist-local)
814 (defcustom org-link-abbrev-alist nil
815 "Alist of link abbreviations.
816 The car of each element is a string, to be replaced at the start of a link.
817 The cdrs are replacement values, like (\"linkkey\" . REPLACE). Abbreviated
818 links in Org-mode buffers can have an optional tag after a double colon, e.g.
820 [[linkkey:tag][description]]
822 If REPLACE is a string, the tag will simply be appended to create the link.
823 If the string contains \"%s\", the tag will be inserted there.
825 REPLACE may also be a function that will be called with the tag as the
826 only argument to create the link, which should be returned as a string.
828 See the manual for examples."
829 :group 'org-link
830 :type 'alist)
832 (defcustom org-descriptive-links t
833 "Non-nil means, hide link part and only show description of bracket links.
834 Bracket links are like [[link][descritpion]]. This variable sets the initial
835 state in new org-mode buffers. The setting can then be toggled on a
836 per-buffer basis from the Org->Hyperlinks menu."
837 :group 'org-link
838 :type 'boolean)
840 (defcustom org-link-file-path-type 'adaptive
841 "How the path name in file links should be stored.
842 Valid values are:
844 relative Relative to the current directory, i.e. the directory of the file
845 into which the link is being inserted.
846 absolute Absolute path, if possible with ~ for home directory.
847 noabbrev Absolute path, no abbreviation of home directory.
848 adaptive Use relative path for files in the current directory and sub-
849 directories of it. For other files, use an absolute path."
850 :group 'org-link
851 :type '(choice
852 (const relative)
853 (const absolute)
854 (const noabbrev)
855 (const adaptive)))
857 (defcustom org-activate-links '(bracket angle plain radio tag date)
858 "Types of links that should be activated in Org-mode files.
859 This is a list of symbols, each leading to the activation of a certain link
860 type. In principle, it does not hurt to turn on most link types - there may
861 be a small gain when turning off unused link types. The types are:
863 bracket The recommended [[link][description]] or [[link]] links with hiding.
864 angular Links in angular brackes that may contain whitespace like
865 <bbdb:Carsten Dominik>.
866 plain Plain links in normal text, no whitespace, like http://google.com.
867 radio Text that is matched by a radio target, see manual for details.
868 tag Tag settings in a headline (link to tag search).
869 date Time stamps (link to calendar).
871 Changing this variable requires a restart of Emacs to become effective."
872 :group 'org-link
873 :type '(set (const :tag "Double bracket links (new style)" bracket)
874 (const :tag "Angular bracket links (old style)" angular)
875 (const :tag "Plain text links" plain)
876 (const :tag "Radio target matches" radio)
877 (const :tag "Tags" tag)
878 (const :tag "Timestamps" date)))
880 (defcustom org-make-link-description-function nil
881 "Function to use to generate link descriptions from links. If
882 nil the link location will be used. This function must take two
883 parameters; the first is the link and the second the description
884 org-insert-link has generated, and should return the description
885 to use."
886 :group 'org-link
887 :type 'function)
889 (defgroup org-link-store nil
890 "Options concerning storing links in Org-mode."
891 :tag "Org Store Link"
892 :group 'org-link)
894 (defcustom org-email-link-description-format "Email %c: %.30s"
895 "Format of the description part of a link to an email or usenet message.
896 The following %-excapes will be replaced by corresponding information:
898 %F full \"From\" field
899 %f name, taken from \"From\" field, address if no name
900 %T full \"To\" field
901 %t first name in \"To\" field, address if no name
902 %c correspondent. Unually \"from NAME\", but if you sent it yourself, it
903 will be \"to NAME\". See also the variable `org-from-is-user-regexp'.
904 %s subject
905 %m message-id.
907 You may use normal field width specification between the % and the letter.
908 This is for example useful to limit the length of the subject.
910 Examples: \"%f on: %.30s\", \"Email from %f\", \"Email %c\""
911 :group 'org-link-store
912 :type 'string)
914 (defcustom org-from-is-user-regexp
915 (let (r1 r2)
916 (when (and user-mail-address (not (string= user-mail-address "")))
917 (setq r1 (concat "\\<" (regexp-quote user-mail-address) "\\>")))
918 (when (and user-full-name (not (string= user-full-name "")))
919 (setq r2 (concat "\\<" (regexp-quote user-full-name) "\\>")))
920 (if (and r1 r2) (concat r1 "\\|" r2) (or r1 r2)))
921 "Regexp mached against the \"From:\" header of an email or usenet message.
922 It should match if the message is from the user him/herself."
923 :group 'org-link-store
924 :type 'regexp)
926 (defcustom org-context-in-file-links t
927 "Non-nil means, file links from `org-store-link' contain context.
928 A search string will be added to the file name with :: as separator and
929 used to find the context when the link is activated by the command
930 `org-open-at-point'.
931 Using a prefix arg to the command \\[org-store-link] (`org-store-link')
932 negates this setting for the duration of the command."
933 :group 'org-link-store
934 :type 'boolean)
936 (defcustom org-keep-stored-link-after-insertion nil
937 "Non-nil means, keep link in list for entire session.
939 The command `org-store-link' adds a link pointing to the current
940 location to an internal list. These links accumulate during a session.
941 The command `org-insert-link' can be used to insert links into any
942 Org-mode file (offering completion for all stored links). When this
943 option is nil, every link which has been inserted once using \\[org-insert-link]
944 will be removed from the list, to make completing the unused links
945 more efficient."
946 :group 'org-link-store
947 :type 'boolean)
949 (defgroup org-link-follow nil
950 "Options concerning following links in Org-mode."
951 :tag "Org Follow Link"
952 :group 'org-link)
954 (defcustom org-follow-link-hook nil
955 "Hook that is run after a link has been followed."
956 :group 'org-link-follow
957 :type 'hook)
959 (defcustom org-tab-follows-link nil
960 "Non-nil means, on links TAB will follow the link.
961 Needs to be set before org.el is loaded."
962 :group 'org-link-follow
963 :type 'boolean)
965 (defcustom org-return-follows-link nil
966 "Non-nil means, on links RET will follow the link.
967 Needs to be set before org.el is loaded."
968 :group 'org-link-follow
969 :type 'boolean)
971 (defcustom org-mouse-1-follows-link
972 (if (boundp 'mouse-1-click-follows-link) mouse-1-click-follows-link t)
973 "Non-nil means, mouse-1 on a link will follow the link.
974 A longer mouse click will still set point. Does not work on XEmacs.
975 Needs to be set before org.el is loaded."
976 :group 'org-link-follow
977 :type 'boolean)
979 (defcustom org-mark-ring-length 4
980 "Number of different positions to be recorded in the ring
981 Changing this requires a restart of Emacs to work correctly."
982 :group 'org-link-follow
983 :type 'interger)
985 (defcustom org-link-frame-setup
986 '((vm . vm-visit-folder-other-frame)
987 (gnus . gnus-other-frame)
988 (file . find-file-other-window))
989 "Setup the frame configuration for following links.
990 When following a link with Emacs, it may often be useful to display
991 this link in another window or frame. This variable can be used to
992 set this up for the different types of links.
993 For VM, use any of
994 `vm-visit-folder'
995 `vm-visit-folder-other-frame'
996 For Gnus, use any of
997 `gnus'
998 `gnus-other-frame'
999 For FILE, use any of
1000 `find-file'
1001 `find-file-other-window'
1002 `find-file-other-frame'
1003 For the calendar, use the variable `calendar-setup'.
1004 For BBDB, it is currently only possible to display the matches in
1005 another window."
1006 :group 'org-link-follow
1007 :type '(list
1008 (cons (const vm)
1009 (choice
1010 (const vm-visit-folder)
1011 (const vm-visit-folder-other-window)
1012 (const vm-visit-folder-other-frame)))
1013 (cons (const gnus)
1014 (choice
1015 (const gnus)
1016 (const gnus-other-frame)))
1017 (cons (const file)
1018 (choice
1019 (const find-file)
1020 (const find-file-other-window)
1021 (const find-file-other-frame)))))
1023 (defcustom org-display-internal-link-with-indirect-buffer nil
1024 "Non-nil means, use indirect buffer to display infile links.
1025 Activating internal links (from one location in a file to another location
1026 in the same file) normally just jumps to the location. When the link is
1027 activated with a C-u prefix (or with mouse-3), the link is displayed in
1028 another window. When this option is set, the other window actually displays
1029 an indirect buffer clone of the current buffer, to avoid any visibility
1030 changes to the current buffer."
1031 :group 'org-link-follow
1032 :type 'boolean)
1034 (defcustom org-open-non-existing-files nil
1035 "Non-nil means, `org-open-file' will open non-existing files.
1036 When nil, an error will be generated."
1037 :group 'org-link-follow
1038 :type 'boolean)
1040 (defcustom org-link-mailto-program '(browse-url "mailto:%a?subject=%s")
1041 "Function and arguments to call for following mailto links.
1042 This is a list with the first element being a lisp function, and the
1043 remaining elements being arguments to the function. In string arguments,
1044 %a will be replaced by the address, and %s will be replaced by the subject
1045 if one was given like in <mailto:arthur@galaxy.org::this subject>."
1046 :group 'org-link-follow
1047 :type '(choice
1048 (const :tag "browse-url" (browse-url-mail "mailto:%a?subject=%s"))
1049 (const :tag "compose-mail" (compose-mail "%a" "%s"))
1050 (const :tag "message-mail" (message-mail "%a" "%s"))
1051 (cons :tag "other" (function) (repeat :tag "argument" sexp))))
1053 (defcustom org-confirm-shell-link-function 'yes-or-no-p
1054 "Non-nil means, ask for confirmation before executing shell links.
1055 Shell links can be dangerous: just think about a link
1057 [[shell:rm -rf ~/*][Google Search]]
1059 This link would show up in your Org-mode document as \"Google Search\",
1060 but really it would remove your entire home directory.
1061 Therefore we advise against setting this variable to nil.
1062 Just change it to `y-or-n-p' of you want to confirm with a
1063 single keystroke rather than having to type \"yes\"."
1064 :group 'org-link-follow
1065 :type '(choice
1066 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1067 (const :tag "with y-or-n (faster)" y-or-n-p)
1068 (const :tag "no confirmation (dangerous)" nil)))
1070 (defcustom org-confirm-elisp-link-function 'yes-or-no-p
1071 "Non-nil means, ask for confirmation before executing Emacs Lisp links.
1072 Elisp links can be dangerous: just think about a link
1074 [[elisp:(shell-command \"rm -rf ~/*\")][Google Search]]
1076 This link would show up in your Org-mode document as \"Google Search\",
1077 but really it would remove your entire home directory.
1078 Therefore we advise against setting this variable to nil.
1079 Just change it to `y-or-n-p' of you want to confirm with a
1080 single keystroke rather than having to type \"yes\"."
1081 :group 'org-link-follow
1082 :type '(choice
1083 (const :tag "with yes-or-no (safer)" yes-or-no-p)
1084 (const :tag "with y-or-n (faster)" y-or-n-p)
1085 (const :tag "no confirmation (dangerous)" nil)))
1087 (defconst org-file-apps-defaults-gnu
1088 '((remote . emacs)
1089 (t . mailcap))
1090 "Default file applications on a UNIX or GNU/Linux system.
1091 See `org-file-apps'.")
1093 (defconst org-file-apps-defaults-macosx
1094 '((remote . emacs)
1095 (t . "open %s")
1096 ("ps" . "gv %s")
1097 ("ps.gz" . "gv %s")
1098 ("eps" . "gv %s")
1099 ("eps.gz" . "gv %s")
1100 ("dvi" . "xdvi %s")
1101 ("fig" . "xfig %s"))
1102 "Default file applications on a MacOS X system.
1103 The system \"open\" is known as a default, but we use X11 applications
1104 for some files for which the OS does not have a good default.
1105 See `org-file-apps'.")
1107 (defconst org-file-apps-defaults-windowsnt
1108 (list
1109 '(remote . emacs)
1110 (cons t
1111 (list (if (featurep 'xemacs)
1112 'mswindows-shell-execute
1113 'w32-shell-execute)
1114 "open" 'file)))
1115 "Default file applications on a Windows NT system.
1116 The system \"open\" is used for most files.
1117 See `org-file-apps'.")
1119 (defcustom org-file-apps
1121 ("txt" . emacs)
1122 ("tex" . emacs)
1123 ("ltx" . emacs)
1124 ("org" . emacs)
1125 ("el" . emacs)
1126 ("bib" . emacs)
1128 "External applications for opening `file:path' items in a document.
1129 Org-mode uses system defaults for different file types, but
1130 you can use this variable to set the application for a given file
1131 extension. The entries in this list are cons cells where the car identifies
1132 files and the cdr the corresponding command. Possible values for the
1133 file identifier are
1134 \"ext\" A string identifying an extension
1135 `directory' Matches a directory
1136 `remote' Matches a remote file, accessible through tramp or efs.
1137 Remote files most likely should be visited through Emacs
1138 because external applications cannot handle such paths.
1139 t Default for all remaining files
1141 Possible values for the command are:
1142 `emacs' The file will be visited by the current Emacs process.
1143 `default' Use the default application for this file type.
1144 string A command to be executed by a shell; %s will be replaced
1145 by the path to the file.
1146 sexp A Lisp form which will be evaluated. The file path will
1147 be available in the Lisp variable `file'.
1148 For more examples, see the system specific constants
1149 `org-file-apps-defaults-macosx'
1150 `org-file-apps-defaults-windowsnt'
1151 `org-file-apps-defaults-gnu'."
1152 :group 'org-link-follow
1153 :type '(repeat
1154 (cons (choice :value ""
1155 (string :tag "Extension")
1156 (const :tag "Default for unrecognized files" t)
1157 (const :tag "Remote file" remote)
1158 (const :tag "Links to a directory" directory))
1159 (choice :value ""
1160 (const :tag "Visit with Emacs" emacs)
1161 (const :tag "Use system default" default)
1162 (string :tag "Command")
1163 (sexp :tag "Lisp form")))))
1165 (defgroup org-refile nil
1166 "Options concerning refiling entries in Org-mode."
1167 :tag "Org Remember"
1168 :group 'org)
1170 (defcustom org-directory "~/org"
1171 "Directory with org files.
1172 This directory will be used as default to prompt for org files.
1173 Used by the hooks for remember.el."
1174 :group 'org-refile
1175 :group 'org-remember
1176 :type 'directory)
1178 (defcustom org-default-notes-file "~/.notes"
1179 "Default target for storing notes.
1180 Used by the hooks for remember.el. This can be a string, or nil to mean
1181 the value of `remember-data-file'.
1182 You can set this on a per-template basis with the variable
1183 `org-remember-templates'."
1184 :group 'org-refile
1185 :group 'org-remember
1186 :type '(choice
1187 (const :tag "Default from remember-data-file" nil)
1188 file))
1190 (defcustom org-goto-interface 'outline
1191 "The default interface to be used for `org-goto'.
1192 Allowed vaues are:
1193 outline The interface shows an outline of the relevant file
1194 and the correct heading is found by moving through
1195 the outline or by searching with incremental search.
1196 outline-path-completion Headlines in the current buffer are offered via
1197 completion."
1198 :group 'org-refile
1199 :type '(choice
1200 (const :tag "Outline" outline)
1201 (const :tag "Outline-path-completion" outline-path-completion)))
1203 (defcustom org-reverse-note-order nil
1204 "Non-nil means, store new notes at the beginning of a file or entry.
1205 When nil, new notes will be filed to the end of a file or entry.
1206 This can also be a list with cons cells of regular expressions that
1207 are matched against file names, and values."
1208 :group 'org-remember
1209 :type '(choice
1210 (const :tag "Reverse always" t)
1211 (const :tag "Reverse never" nil)
1212 (repeat :tag "By file name regexp"
1213 (cons regexp boolean))))
1215 (defcustom org-refile-targets nil
1216 "Targets for refiling entries with \\[org-refile].
1217 This is list of cons cells. Each cell contains:
1218 - a specification of the files to be considered, either a list of files,
1219 or a symbol whose function or variable value will be used to retrieve
1220 a file name or a list of file names. Nil means, refile to a different
1221 heading in the current buffer.
1222 - A specification of how to find candidate refile targets. This may be
1223 any of
1224 - a cons cell (:tag . \"TAG\") to identify refile targets by a tag.
1225 This tag has to be present in all target headlines, inheritance will
1226 not be considered.
1227 - a cons cell (:todo . \"KEYWORD\") to identify refile targets by
1228 todo keyword.
1229 - a cons cell (:regexp . \"REGEXP\") with a regular expression matching
1230 headlines that are refiling targets.
1231 - a cons cell (:level . N). Any headline of level N is considered a target.
1232 - a cons cell (:maxlevel . N). Any headline with level <= N is a target."
1233 :group 'org-remember
1234 :type '(repeat
1235 (cons
1236 (choice :value org-agenda-files
1237 (const :tag "All agenda files" org-agenda-files)
1238 (const :tag "Current buffer" nil)
1239 (function) (variable) (file))
1240 (choice :tag "Identify target headline by"
1241 (cons :tag "Specific tag" (const :tag) (string))
1242 (cons :tag "TODO keyword" (const :todo) (string))
1243 (cons :tag "Regular expression" (const :regexp) (regexp))
1244 (cons :tag "Level number" (const :level) (integer))
1245 (cons :tag "Max Level number" (const :maxlevel) (integer))))))
1247 (defcustom org-refile-use-outline-path nil
1248 "Non-nil means, provide refile targets as paths.
1249 So a level 3 headline will be available as level1/level2/level3.
1250 When the value is `file', also include the file name (without directory)
1251 into the path. When `full-file-path', include the full file path."
1252 :group 'org-remember
1253 :type '(choice
1254 (const :tag "Not" nil)
1255 (const :tag "Yes" t)
1256 (const :tag "Start with file name" file)
1257 (const :tag "Start with full file path" full-file-path)))
1259 (defgroup org-todo nil
1260 "Options concerning TODO items in Org-mode."
1261 :tag "Org TODO"
1262 :group 'org)
1264 (defgroup org-progress nil
1265 "Options concerning Progress logging in Org-mode."
1266 :tag "Org Progress"
1267 :group 'org-time)
1269 (defcustom org-todo-keywords '((sequence "TODO" "DONE"))
1270 "List of TODO entry keyword sequences and their interpretation.
1271 \\<org-mode-map>This is a list of sequences.
1273 Each sequence starts with a symbol, either `sequence' or `type',
1274 indicating if the keywords should be interpreted as a sequence of
1275 action steps, or as different types of TODO items. The first
1276 keywords are states requiring action - these states will select a headline
1277 for inclusion into the global TODO list Org-mode produces. If one of
1278 the \"keywords\" is the vertical bat \"|\" the remaining keywords
1279 signify that no further action is necessary. If \"|\" is not found,
1280 the last keyword is treated as the only DONE state of the sequence.
1282 The command \\[org-todo] cycles an entry through these states, and one
1283 additional state where no keyword is present. For details about this
1284 cycling, see the manual.
1286 TODO keywords and interpretation can also be set on a per-file basis with
1287 the special #+SEQ_TODO and #+TYP_TODO lines.
1289 Each keyword can optionally specify a character for fast state selection
1290 \(in combination with the variable `org-use-fast-todo-selection')
1291 and specifiers for state change logging, using the same syntax
1292 that is used in the \"#+TODO:\" lines. For example, \"WAIT(w)\" says
1293 that the WAIT state can be selected with the \"w\" key. \"WAIT(w!)\"
1294 indicates to record a time stamp each time this state is selected.
1296 Each keyword may also specify if a timestamp or a note should be
1297 recorded when entering or leaving the state, by adding additional
1298 characters in the parenthesis after the keyword. This looks like this:
1299 \"WAIT(w@/!)\". \"@\" means to add a note (with time), \"!\" means to
1300 record only the time of the state change. With X and Y being either
1301 \"@\" or \"!\", \"X/Y\" means use X when entering the state, and use
1302 Y when leaving the state if and only if the *target* state does not
1303 define X. You may omit any of the fast-selection key or X or /Y,
1304 so WAIT(w@), WAIT(w/@) and WAIT(@/@) are all valid.
1306 For backward compatibility, this variable may also be just a list
1307 of keywords - in this case the interptetation (sequence or type) will be
1308 taken from the (otherwise obsolete) variable `org-todo-interpretation'."
1309 :group 'org-todo
1310 :group 'org-keywords
1311 :type '(choice
1312 (repeat :tag "Old syntax, just keywords"
1313 (string :tag "Keyword"))
1314 (repeat :tag "New syntax"
1315 (cons
1316 (choice
1317 :tag "Interpretation"
1318 (const :tag "Sequence (cycling hits every state)" sequence)
1319 (const :tag "Type (cycling directly to DONE)" type))
1320 (repeat
1321 (string :tag "Keyword"))))))
1323 (defvar org-todo-keywords-1 nil
1324 "All TODO and DONE keywords active in a buffer.")
1325 (make-variable-buffer-local 'org-todo-keywords-1)
1326 (defvar org-todo-keywords-for-agenda nil)
1327 (defvar org-done-keywords-for-agenda nil)
1328 (defvar org-agenda-contributing-files nil)
1329 (defvar org-not-done-keywords nil)
1330 (make-variable-buffer-local 'org-not-done-keywords)
1331 (defvar org-done-keywords nil)
1332 (make-variable-buffer-local 'org-done-keywords)
1333 (defvar org-todo-heads nil)
1334 (make-variable-buffer-local 'org-todo-heads)
1335 (defvar org-todo-sets nil)
1336 (make-variable-buffer-local 'org-todo-sets)
1337 (defvar org-todo-log-states nil)
1338 (make-variable-buffer-local 'org-todo-log-states)
1339 (defvar org-todo-kwd-alist nil)
1340 (make-variable-buffer-local 'org-todo-kwd-alist)
1341 (defvar org-todo-key-alist nil)
1342 (make-variable-buffer-local 'org-todo-key-alist)
1343 (defvar org-todo-key-trigger nil)
1344 (make-variable-buffer-local 'org-todo-key-trigger)
1346 (defcustom org-todo-interpretation 'sequence
1347 "Controls how TODO keywords are interpreted.
1348 This variable is in principle obsolete and is only used for
1349 backward compatibility, if the interpretation of todo keywords is
1350 not given already in `org-todo-keywords'. See that variable for
1351 more information."
1352 :group 'org-todo
1353 :group 'org-keywords
1354 :type '(choice (const sequence)
1355 (const type)))
1357 (defcustom org-use-fast-todo-selection 'prefix
1358 "Non-nil means, use the fast todo selection scheme with C-c C-t.
1359 This variable describes if and under what circumstances the cycling
1360 mechanism for TODO keywords will be replaced by a single-key, direct
1361 selection scheme.
1363 When nil, fast selection is never used.
1365 When the symbol `prefix', it will be used when `org-todo' is called with
1366 a prefix argument, i.e. `C-u C-c C-t' in an Org-mode buffer, and `C-u t'
1367 in an agenda buffer.
1369 When t, fast selection is used by default. In this case, the prefix
1370 argument forces cycling instead.
1372 In all cases, the special interface is only used if access keys have actually
1373 been assigned by the user, i.e. if keywords in the configuration are followed
1374 by a letter in parenthesis, like TODO(t)."
1375 :group 'org-todo
1376 :type '(choice
1377 (const :tag "Never" nil)
1378 (const :tag "By default" t)
1379 (const :tag "Only with C-u C-c C-t" prefix)))
1381 (defcustom org-after-todo-state-change-hook nil
1382 "Hook which is run after the state of a TODO item was changed.
1383 The new state (a string with a TODO keyword, or nil) is available in the
1384 Lisp variable `state'."
1385 :group 'org-todo
1386 :type 'hook)
1388 (defcustom org-log-done nil
1389 "Non-nil means, record a CLOSED timestamp when moving an entry to DONE.
1390 When equal to the list (done), also prompt for a closing note.
1391 This can also be configured on a per-file basis by adding one of
1392 the following lines anywhere in the buffer:
1394 #+STARTUP: logdone
1395 #+STARTUP: lognotedone
1396 #+STARTUP: nologdone"
1397 :group 'org-todo
1398 :group 'org-progress
1399 :type '(choice
1400 (const :tag "No logging" nil)
1401 (const :tag "Record CLOSED timestamp" time)
1402 (const :tag "Record CLOSED timestamp with closing note." note)))
1404 ;; Normalize old uses of org-log-done.
1405 (cond
1406 ((eq org-log-done t) (setq org-log-done 'time))
1407 ((and (listp org-log-done) (memq 'done org-log-done))
1408 (setq org-log-done 'note)))
1410 (defcustom org-log-note-clock-out nil
1411 "Non-nil means, recored a note when clocking out of an item.
1412 This can also be configured on a per-file basis by adding one of
1413 the following lines anywhere in the buffer:
1415 #+STARTUP: lognoteclock-out
1416 #+STARTUP: nolognoteclock-out"
1417 :group 'org-todo
1418 :group 'org-progress
1419 :type 'boolean)
1421 (defcustom org-log-done-with-time t
1422 "Non-nil means, the CLOSED time stamp will contain date and time.
1423 When nil, only the date will be recorded."
1424 :group 'org-progress
1425 :type 'boolean)
1427 (defcustom org-log-note-headings
1428 '((done . "CLOSING NOTE %t")
1429 (state . "State %-12s %t")
1430 (note . "Note taken on %t")
1431 (clock-out . ""))
1432 "Headings for notes added to entries.
1433 The value is an alist, with the car being a symbol indicating the note
1434 context, and the cdr is the heading to be used. The heading may also be the
1435 empty string.
1436 %t in the heading will be replaced by a time stamp.
1437 %s will be replaced by the new TODO state, in double quotes.
1438 %u will be replaced by the user name.
1439 %U will be replaced by the full user name."
1440 :group 'org-todo
1441 :group 'org-progress
1442 :type '(list :greedy t
1443 (cons (const :tag "Heading when closing an item" done) string)
1444 (cons (const :tag
1445 "Heading when changing todo state (todo sequence only)"
1446 state) string)
1447 (cons (const :tag "Heading when just taking a note" note) string)
1448 (cons (const :tag "Heading when clocking out" clock-out) string)))
1450 (unless (assq 'note org-log-note-headings)
1451 (push '(note . "%t") org-log-note-headings))
1453 (defcustom org-log-states-order-reversed t
1454 "Non-nil means, the latest state change note will be directly after heading.
1455 When nil, the notes will be orderer according to time."
1456 :group 'org-todo
1457 :group 'org-progress
1458 :type 'boolean)
1460 (defcustom org-log-repeat 'time
1461 "Non-nil means, record moving through the DONE state when triggering repeat.
1462 An auto-repeating tasks is immediately switched back to TODO when marked
1463 done. If you are not logging state changes (by adding \"@\" or \"!\" to
1464 the TODO keyword definition, or recording a cloing note by setting
1465 `org-log-done', there will be no record of the task moving trhough DONE.
1466 This variable forces taking a note anyway. Possible values are:
1468 nil Don't force a record
1469 time Record a time stamp
1470 note Record a note
1472 This option can also be set with on a per-file-basis with
1474 #+STARTUP: logrepeat
1475 #+STARTUP: lognoterepeat
1476 #+STARTUP: nologrepeat
1478 You can have local logging settings for a subtree by setting the LOGGING
1479 property to one or more of these keywords."
1480 :group 'org-todo
1481 :group 'org-progress
1482 :type '(choice
1483 (const :tag "Don't force a record" nil)
1484 (const :tag "Force recording the DONE state" time)
1485 (const :tag "Force recording a note with the DONE state" note)))
1488 (defgroup org-priorities nil
1489 "Priorities in Org-mode."
1490 :tag "Org Priorities"
1491 :group 'org-todo)
1493 (defcustom org-highest-priority ?A
1494 "The highest priority of TODO items. A character like ?A, ?B etc.
1495 Must have a smaller ASCII number than `org-lowest-priority'."
1496 :group 'org-priorities
1497 :type 'character)
1499 (defcustom org-lowest-priority ?C
1500 "The lowest priority of TODO items. A character like ?A, ?B etc.
1501 Must have a larger ASCII number than `org-highest-priority'."
1502 :group 'org-priorities
1503 :type 'character)
1505 (defcustom org-default-priority ?B
1506 "The default priority of TODO items.
1507 This is the priority an item get if no explicit priority is given."
1508 :group 'org-priorities
1509 :type 'character)
1511 (defcustom org-priority-start-cycle-with-default t
1512 "Non-nil means, start with default priority when starting to cycle.
1513 When this is nil, the first step in the cycle will be (depending on the
1514 command used) one higher or lower that the default priority."
1515 :group 'org-priorities
1516 :type 'boolean)
1518 (defgroup org-time nil
1519 "Options concerning time stamps and deadlines in Org-mode."
1520 :tag "Org Time"
1521 :group 'org)
1523 (defcustom org-insert-labeled-timestamps-at-point nil
1524 "Non-nil means, SCHEDULED and DEADLINE timestamps are inserted at point.
1525 When nil, these labeled time stamps are forces into the second line of an
1526 entry, just after the headline. When scheduling from the global TODO list,
1527 the time stamp will always be forced into the second line."
1528 :group 'org-time
1529 :type 'boolean)
1531 (defconst org-time-stamp-formats '("<%Y-%m-%d %a>" . "<%Y-%m-%d %a %H:%M>")
1532 "Formats for `format-time-string' which are used for time stamps.
1533 It is not recommended to change this constant.")
1535 (defcustom org-time-stamp-rounding-minutes '(0 5)
1536 "Number of minutes to round time stamps to.
1537 These are two values, the first applies when first creating a time stamp.
1538 The second applies when changing it with the commands `S-up' and `S-down'.
1539 When changing the time stamp, this means that it will change in steps
1540 of N minutes, as given by the second value.
1542 When a setting is 0 or 1, insert the time unmodified. Useful rounding
1543 numbers should be factors of 60, so for example 5, 10, 15.
1545 When this is larger than 1, you can still force an exact time-stamp by using
1546 a double prefix argument to a time-stamp command like `C-c .' or `C-c !',
1547 and by using a prefix arg to `S-up/down' to specify the exact number
1548 of minutes to shift."
1549 :group 'org-time
1550 :get '(lambda (var) ; Make sure all entries have 5 elements
1551 (if (integerp (default-value var))
1552 (list (default-value var) 5)
1553 (default-value var)))
1554 :type '(list
1555 (integer :tag "when inserting times")
1556 (integer :tag "when modifying times")))
1558 ;; Normalize old customizations of this variable.
1559 (when (integerp org-time-stamp-rounding-minutes)
1560 (setq org-time-stamp-rounding-minutes
1561 (list org-time-stamp-rounding-minutes
1562 org-time-stamp-rounding-minutes)))
1564 (defcustom org-display-custom-times nil
1565 "Non-nil means, overlay custom formats over all time stamps.
1566 The formats are defined through the variable `org-time-stamp-custom-formats'.
1567 To turn this on on a per-file basis, insert anywhere in the file:
1568 #+STARTUP: customtime"
1569 :group 'org-time
1570 :set 'set-default
1571 :type 'sexp)
1572 (make-variable-buffer-local 'org-display-custom-times)
1574 (defcustom org-time-stamp-custom-formats
1575 '("<%m/%d/%y %a>" . "<%m/%d/%y %a %H:%M>") ; american
1576 "Custom formats for time stamps. See `format-time-string' for the syntax.
1577 These are overlayed over the default ISO format if the variable
1578 `org-display-custom-times' is set. Time like %H:%M should be at the
1579 end of the second format."
1580 :group 'org-time
1581 :type 'sexp)
1583 (defun org-time-stamp-format (&optional long inactive)
1584 "Get the right format for a time string."
1585 (let ((f (if long (cdr org-time-stamp-formats)
1586 (car org-time-stamp-formats))))
1587 (if inactive
1588 (concat "[" (substring f 1 -1) "]")
1589 f)))
1591 (defcustom org-deadline-warning-days 14
1592 "No. of days before expiration during which a deadline becomes active.
1593 This variable governs the display in sparse trees and in the agenda.
1594 When 0 or negative, it means use this number (the absolute value of it)
1595 even if a deadline has a different individual lead time specified."
1596 :group 'org-time
1597 :group 'org-agenda-daily/weekly
1598 :type 'number)
1600 (defcustom org-read-date-prefer-future t
1601 "Non-nil means, assume future for incomplete date input from user.
1602 This affects the following situations:
1603 1. The user gives a day, but no month.
1604 For example, if today is the 15th, and you enter \"3\", Org-mode will
1605 read this as the third of *next* month. However, if you enter \"17\",
1606 it will be considered as *this* month.
1607 2. The user gives a month but not a year.
1608 For example, if it is april and you enter \"feb 2\", this will be read
1609 as feb 2, *next* year. \"May 5\", however, will be this year.
1611 Currently this does not work for ISO week specifications.
1613 When this option is nil, the current month and year will always be used
1614 as defaults."
1615 :group 'org-time
1616 :type 'boolean)
1618 (defcustom org-read-date-display-live t
1619 "Non-nil means, display current interpretation of date prompt live.
1620 This display will be in an overlay, in the minibuffer."
1621 :group 'org-time
1622 :type 'boolean)
1624 (defcustom org-read-date-popup-calendar t
1625 "Non-nil means, pop up a calendar when prompting for a date.
1626 In the calendar, the date can be selected with mouse-1. However, the
1627 minibuffer will also be active, and you can simply enter the date as well.
1628 When nil, only the minibuffer will be available."
1629 :group 'org-time
1630 :type 'boolean)
1631 (if (fboundp 'defvaralias)
1632 (defvaralias 'org-popup-calendar-for-date-prompt
1633 'org-read-date-popup-calendar))
1635 (defcustom org-extend-today-until 0
1636 "The hour when your day really ends.
1637 This has influence for the following applications:
1638 - When switching the agenda to \"today\". It it is still earlier than
1639 the time given here, the day recognized as TODAY is actually yesterday.
1640 - When a date is read from the user and it is still before the time given
1641 here, the current date and time will be assumed to be yesterday, 23:59.
1643 FIXME:
1644 IMPORTANT: This is still a very experimental feature, it may disappear
1645 again or it may be extended to mean more things."
1646 :group 'org-time
1647 :type 'number)
1649 (defcustom org-edit-timestamp-down-means-later nil
1650 "Non-nil means, S-down will increase the time in a time stamp.
1651 When nil, S-up will increase."
1652 :group 'org-time
1653 :type 'boolean)
1655 (defcustom org-calendar-follow-timestamp-change t
1656 "Non-nil means, make the calendar window follow timestamp changes.
1657 When a timestamp is modified and the calendar window is visible, it will be
1658 moved to the new date."
1659 :group 'org-time
1660 :type 'boolean)
1662 (defgroup org-tags nil
1663 "Options concerning tags in Org-mode."
1664 :tag "Org Tags"
1665 :group 'org)
1667 (defcustom org-tag-alist nil
1668 "List of tags allowed in Org-mode files.
1669 When this list is nil, Org-mode will base TAG input on what is already in the
1670 buffer.
1671 The value of this variable is an alist, the car of each entry must be a
1672 keyword as a string, the cdr may be a character that is used to select
1673 that tag through the fast-tag-selection interface.
1674 See the manual for details."
1675 :group 'org-tags
1676 :type '(repeat
1677 (choice
1678 (cons (string :tag "Tag name")
1679 (character :tag "Access char"))
1680 (const :tag "Start radio group" (:startgroup))
1681 (const :tag "End radio group" (:endgroup)))))
1683 (defcustom org-use-fast-tag-selection 'auto
1684 "Non-nil means, use fast tag selection scheme.
1685 This is a special interface to select and deselect tags with single keys.
1686 When nil, fast selection is never used.
1687 When the symbol `auto', fast selection is used if and only if selection
1688 characters for tags have been configured, either through the variable
1689 `org-tag-alist' or through a #+TAGS line in the buffer.
1690 When t, fast selection is always used and selection keys are assigned
1691 automatically if necessary."
1692 :group 'org-tags
1693 :type '(choice
1694 (const :tag "Always" t)
1695 (const :tag "Never" nil)
1696 (const :tag "When selection characters are configured" 'auto)))
1698 (defcustom org-fast-tag-selection-single-key nil
1699 "Non-nil means, fast tag selection exits after first change.
1700 When nil, you have to press RET to exit it.
1701 During fast tag selection, you can toggle this flag with `C-c'.
1702 This variable can also have the value `expert'. In this case, the window
1703 displaying the tags menu is not even shown, until you press C-c again."
1704 :group 'org-tags
1705 :type '(choice
1706 (const :tag "No" nil)
1707 (const :tag "Yes" t)
1708 (const :tag "Expert" expert)))
1710 (defvar org-fast-tag-selection-include-todo nil
1711 "Non-nil means, fast tags selection interface will also offer TODO states.
1712 This is an undocumented feature, you should not rely on it.")
1714 (defcustom org-tags-column -80
1715 "The column to which tags should be indented in a headline.
1716 If this number is positive, it specifies the column. If it is negative,
1717 it means that the tags should be flushright to that column. For example,
1718 -80 works well for a normal 80 character screen."
1719 :group 'org-tags
1720 :type 'integer)
1722 (defcustom org-auto-align-tags t
1723 "Non-nil means, realign tags after pro/demotion of TODO state change.
1724 These operations change the length of a headline and therefore shift
1725 the tags around. With this options turned on, after each such operation
1726 the tags are again aligned to `org-tags-column'."
1727 :group 'org-tags
1728 :type 'boolean)
1730 (defcustom org-use-tag-inheritance t
1731 "Non-nil means, tags in levels apply also for sublevels.
1732 When nil, only the tags directly given in a specific line apply there.
1733 If you turn off this option, you very likely want to turn on the
1734 companion option `org-tags-match-list-sublevels'.
1736 This may also be a list of tags that should be inherited, or a regexp that
1737 matches tags that should be inherited."
1738 :group 'org-tags
1739 :type '(choice
1740 (const :tag "Not" nil)
1741 (const :tag "Always" t)
1742 (repeat :tag "Specific tags" (string :tag "Tag"))
1743 (regexp :tag "Tags matched by regexp")))
1745 (defun org-tag-inherit-p (tag)
1746 "Check if TAG is one that should be inherited."
1747 (cond
1748 ((eq org-use-tag-inheritance t) t)
1749 ((not org-use-tag-inheritance) nil)
1750 ((stringp org-use-tag-inheritance)
1751 (string-match org-use-tag-inheritance tag))
1752 ((listp org-use-tag-inheritance)
1753 (member tag org-use-tag-inheritance))
1754 (t (error "Invalid setting of `org-use-tag-inheritance'"))))
1756 (defcustom org-tags-match-list-sublevels nil
1757 "Non-nil means list also sublevels of headlines matching tag search.
1758 Because of tag inheritance (see variable `org-use-tag-inheritance'),
1759 the sublevels of a headline matching a tag search often also match
1760 the same search. Listing all of them can create very long lists.
1761 Setting this variable to nil causes subtrees of a match to be skipped.
1762 This option is off by default, because inheritance in on. If you turn
1763 inheritance off, you very likely want to turn this option on.
1765 As a special case, if the tag search is restricted to TODO items, the
1766 value of this variable is ignored and sublevels are always checked, to
1767 make sure all corresponding TODO items find their way into the list."
1768 :group 'org-tags
1769 :type 'boolean)
1771 (defvar org-tags-history nil
1772 "History of minibuffer reads for tags.")
1773 (defvar org-last-tags-completion-table nil
1774 "The last used completion table for tags.")
1775 (defvar org-after-tags-change-hook nil
1776 "Hook that is run after the tags in a line have changed.")
1778 (defgroup org-properties nil
1779 "Options concerning properties in Org-mode."
1780 :tag "Org Properties"
1781 :group 'org)
1783 (defcustom org-property-format "%-10s %s"
1784 "How property key/value pairs should be formatted by `indent-line'.
1785 When `indent-line' hits a property definition, it will format the line
1786 according to this format, mainly to make sure that the values are
1787 lined-up with respect to each other."
1788 :group 'org-properties
1789 :type 'string)
1791 (defcustom org-use-property-inheritance nil
1792 "Non-nil means, properties apply also for sublevels.
1794 This setting is chiefly used during property searches. Turning it on can
1795 cause significant overhead when doing a search, which is why it is not
1796 on by default.
1798 When nil, only the properties directly given in the current entry count.
1799 When t, every property is inherited. The value may also be a list of
1800 properties that should have inheritance, or a regular expression matching
1801 properties that should be inherited.
1803 However, note that some special properties use inheritance under special
1804 circumstances (not in searches). Examples are CATEGORY, ARCHIVE, COLUMNS,
1805 and the properties ending in \"_ALL\" when they are used as descriptor
1806 for valid values of a property.
1808 Note for programmers:
1809 When querying an entry with `org-entry-get', you can control if inheritance
1810 should be used. By default, `org-entry-get' looks only at the local
1811 properties. You can request inheritance by setting the inherit argument
1812 to t (to force inheritance) or to `selective' (to respect the setting
1813 in this variable)."
1814 :group 'org-properties
1815 :type '(choice
1816 (const :tag "Not" nil)
1817 (const :tag "Always" t)
1818 (repeat :tag "Specific properties" (string :tag "Property"))
1819 (regexp :tag "Properties matched by regexp")))
1821 (defun org-property-inherit-p (property)
1822 "Check if PROPERTY is one that should be inherited."
1823 (cond
1824 ((eq org-use-property-inheritance t) t)
1825 ((not org-use-property-inheritance) nil)
1826 ((stringp org-use-property-inheritance)
1827 (string-match org-use-property-inheritance property))
1828 ((listp org-use-property-inheritance)
1829 (member property org-use-property-inheritance))
1830 (t (error "Invalid setting of `org-use-property-inheritance'"))))
1832 (defcustom org-columns-default-format "%25ITEM %TODO %3PRIORITY %TAGS"
1833 "The default column format, if no other format has been defined.
1834 This variable can be set on the per-file basis by inserting a line
1836 #+COLUMNS: %25ITEM ....."
1837 :group 'org-properties
1838 :type 'string)
1840 (defcustom org-effort-property "Effort"
1841 "The property that is being used to keep track of effort estimates.
1842 Effort estimates given in this property need to have the format H:MM."
1843 :group 'org-properties
1844 :group 'org-progress
1845 :type '(string :tag "Property"))
1847 (defcustom org-global-properties nil
1848 "List of property/value pairs that can be inherited by any entry.
1849 You can set buffer-local values for this by adding lines like
1851 #+PROPERTY: NAME VALUE"
1852 :group 'org-properties
1853 :type '(repeat
1854 (cons (string :tag "Property")
1855 (string :tag "Value"))))
1857 (defvar org-local-properties nil
1858 "List of property/value pairs that can be inherited by any entry.
1859 Valid for the current buffer.
1860 This variable is populated from #+PROPERTY lines.")
1862 (defgroup org-agenda nil
1863 "Options concerning agenda views in Org-mode."
1864 :tag "Org Agenda"
1865 :group 'org)
1867 (defvar org-category nil
1868 "Variable used by org files to set a category for agenda display.
1869 Such files should use a file variable to set it, for example
1871 # -*- mode: org; org-category: \"ELisp\"
1873 or contain a special line
1875 #+CATEGORY: ELisp
1877 If the file does not specify a category, then file's base name
1878 is used instead.")
1879 (make-variable-buffer-local 'org-category)
1881 (defcustom org-agenda-files nil
1882 "The files to be used for agenda display.
1883 Entries may be added to this list with \\[org-agenda-file-to-front] and removed with
1884 \\[org-remove-file]. You can also use customize to edit the list.
1886 If an entry is a directory, all files in that directory that are matched by
1887 `org-agenda-file-regexp' will be part of the file list.
1889 If the value of the variable is not a list but a single file name, then
1890 the list of agenda files is actually stored and maintained in that file, one
1891 agenda file per line."
1892 :group 'org-agenda
1893 :type '(choice
1894 (repeat :tag "List of files and directories" file)
1895 (file :tag "Store list in a file\n" :value "~/.agenda_files")))
1897 (defcustom org-agenda-file-regexp "\\`[^.].*\\.org\\'"
1898 "Regular expression to match files for `org-agenda-files'.
1899 If any element in the list in that variable contains a directory instead
1900 of a normal file, all files in that directory that are matched by this
1901 regular expression will be included."
1902 :group 'org-agenda
1903 :type 'regexp)
1905 (defcustom org-agenda-text-search-extra-files nil
1906 "List of extra files to be searched by text search commands.
1907 These files will be search in addition to the agenda files by the
1908 commands `org-search-view' (`C-c a s') and `org-occur-in-agenda-files'.
1909 Note that these files will only be searched for text search commands,
1910 not for the other agenda views like todo lists, tag searches or the weekly
1911 agenda. This variable is intended to list notes and possibly archive files
1912 that should also be searched by these two commands.
1913 In fact, if the first element in the list is the symbol `agenda-archives',
1914 than all archive files of all agenda files will be added to the search
1915 scope."
1916 :group 'org-agenda
1917 :type '(set :greedy t
1918 (const :tag "Agenda Archives" agenda-archives)
1919 (repeat :inline t (file))))
1921 (if (fboundp 'defvaralias)
1922 (defvaralias 'org-agenda-multi-occur-extra-files
1923 'org-agenda-text-search-extra-files))
1925 (defcustom org-agenda-skip-unavailable-files nil
1926 "t means to just skip non-reachable files in `org-agenda-files'.
1927 Nil means to remove them, after a query, from the list."
1928 :group 'org-agenda
1929 :type 'boolean)
1931 (defcustom org-calendar-to-agenda-key [?c]
1932 "The key to be installed in `calendar-mode-map' for switching to the agenda.
1933 The command `org-calendar-goto-agenda' will be bound to this key. The
1934 default is the character `c' because then `c' can be used to switch back and
1935 forth between agenda and calendar."
1936 :group 'org-agenda
1937 :type 'sexp)
1939 (eval-after-load "calendar"
1940 '(org-defkey calendar-mode-map org-calendar-to-agenda-key
1941 'org-calendar-goto-agenda))
1943 (defgroup org-latex nil
1944 "Options for embedding LaTeX code into Org-mode."
1945 :tag "Org LaTeX"
1946 :group 'org)
1948 (defcustom org-format-latex-options
1949 '(:foreground default :background default :scale 1.0
1950 :html-foreground "Black" :html-background "Transparent" :html-scale 1.0
1951 :matchers ("begin" "$" "$$" "\\(" "\\["))
1952 "Options for creating images from LaTeX fragments.
1953 This is a property list with the following properties:
1954 :foreground the foreground color for images embedded in emacs, e.g. \"Black\".
1955 `default' means use the forground of the default face.
1956 :background the background color, or \"Transparent\".
1957 `default' means use the background of the default face.
1958 :scale a scaling factor for the size of the images
1959 :html-foreground, :html-background, :html-scale
1960 The same numbers for HTML export.
1961 :matchers a list indicating which matchers should be used to
1962 find LaTeX fragments. Valid members of this list are:
1963 \"begin\" find environments
1964 \"$\" find math expressions surrounded by $...$
1965 \"$$\" find math expressions surrounded by $$....$$
1966 \"\\(\" find math expressions surrounded by \\(...\\)
1967 \"\\ [\" find math expressions surrounded by \\ [...\\]"
1968 :group 'org-latex
1969 :type 'plist)
1971 (defcustom org-format-latex-header "\\documentclass{article}
1972 \\usepackage{fullpage} % do not remove
1973 \\usepackage{amssymb}
1974 \\usepackage[usenames]{color}
1975 \\usepackage{amsmath}
1976 \\usepackage{latexsym}
1977 \\usepackage[mathscr]{eucal}
1978 \\pagestyle{empty} % do not remove"
1979 "The document header used for processing LaTeX fragments."
1980 :group 'org-latex
1981 :type 'string)
1984 (defgroup org-font-lock nil
1985 "Font-lock settings for highlighting in Org-mode."
1986 :tag "Org Font Lock"
1987 :group 'org)
1989 (defcustom org-level-color-stars-only nil
1990 "Non-nil means fontify only the stars in each headline.
1991 When nil, the entire headline is fontified.
1992 Changing it requires restart of `font-lock-mode' to become effective
1993 also in regions already fontified."
1994 :group 'org-font-lock
1995 :type 'boolean)
1997 (defcustom org-hide-leading-stars nil
1998 "Non-nil means, hide the first N-1 stars in a headline.
1999 This works by using the face `org-hide' for these stars. This
2000 face is white for a light background, and black for a dark
2001 background. You may have to customize the face `org-hide' to
2002 make this work.
2003 Changing it requires restart of `font-lock-mode' to become effective
2004 also in regions already fontified.
2005 You may also set this on a per-file basis by adding one of the following
2006 lines to the buffer:
2008 #+STARTUP: hidestars
2009 #+STARTUP: showstars"
2010 :group 'org-font-lock
2011 :type 'boolean)
2013 (defcustom org-fontify-done-headline nil
2014 "Non-nil means, change the face of a headline if it is marked DONE.
2015 Normally, only the TODO/DONE keyword indicates the state of a headline.
2016 When this is non-nil, the headline after the keyword is set to the
2017 `org-headline-done' as an additional indication."
2018 :group 'org-font-lock
2019 :type 'boolean)
2021 (defcustom org-fontify-emphasized-text t
2022 "Non-nil means fontify *bold*, /italic/ and _underlined_ text.
2023 Changing this variable requires a restart of Emacs to take effect."
2024 :group 'org-font-lock
2025 :type 'boolean)
2027 (defcustom org-highlight-latex-fragments-and-specials nil
2028 "Non-nil means, fontify what is treated specially by the exporters."
2029 :group 'org-font-lock
2030 :type 'boolean)
2032 (defcustom org-hide-emphasis-markers nil
2033 "Non-nil mean font-lock should hide the emphasis marker characters."
2034 :group 'org-font-lock
2035 :type 'boolean)
2037 (defvar org-emph-re nil
2038 "Regular expression for matching emphasis.")
2039 (defvar org-verbatim-re nil
2040 "Regular expression for matching verbatim text.")
2041 (defvar org-emphasis-regexp-components) ; defined just below
2042 (defvar org-emphasis-alist) ; defined just below
2043 (defun org-set-emph-re (var val)
2044 "Set variable and compute the emphasis regular expression."
2045 (set var val)
2046 (when (and (boundp 'org-emphasis-alist)
2047 (boundp 'org-emphasis-regexp-components)
2048 org-emphasis-alist org-emphasis-regexp-components)
2049 (let* ((e org-emphasis-regexp-components)
2050 (pre (car e))
2051 (post (nth 1 e))
2052 (border (nth 2 e))
2053 (body (nth 3 e))
2054 (nl (nth 4 e))
2055 (stacked (and nil (nth 5 e))) ; stacked is no longer allowed, forced to nil
2056 (body1 (concat body "*?"))
2057 (markers (mapconcat 'car org-emphasis-alist ""))
2058 (vmarkers (mapconcat
2059 (lambda (x) (if (eq (nth 4 x) 'verbatim) (car x) ""))
2060 org-emphasis-alist "")))
2061 ;; make sure special characters appear at the right position in the class
2062 (if (string-match "\\^" markers)
2063 (setq markers (concat (replace-match "" t t markers) "^")))
2064 (if (string-match "-" markers)
2065 (setq markers (concat (replace-match "" t t markers) "-")))
2066 (if (string-match "\\^" vmarkers)
2067 (setq vmarkers (concat (replace-match "" t t vmarkers) "^")))
2068 (if (string-match "-" vmarkers)
2069 (setq vmarkers (concat (replace-match "" t t vmarkers) "-")))
2070 (if (> nl 0)
2071 (setq body1 (concat body1 "\\(?:\n" body "*?\\)\\{0,"
2072 (int-to-string nl) "\\}")))
2073 ;; Make the regexp
2074 (setq org-emph-re
2075 (concat "\\([" pre (if (and nil stacked) markers) "]\\|^\\)"
2076 "\\("
2077 "\\([" markers "]\\)"
2078 "\\("
2079 "[^" border "]\\|"
2080 "[^" border (if (and nil stacked) markers) "]"
2081 body1
2082 "[^" border (if (and nil stacked) markers) "]"
2083 "\\)"
2084 "\\3\\)"
2085 "\\([" post (if (and nil stacked) markers) "]\\|$\\)"))
2086 (setq org-verbatim-re
2087 (concat "\\([" pre "]\\|^\\)"
2088 "\\("
2089 "\\([" vmarkers "]\\)"
2090 "\\("
2091 "[^" border "]\\|"
2092 "[^" border "]"
2093 body1
2094 "[^" border "]"
2095 "\\)"
2096 "\\3\\)"
2097 "\\([" post "]\\|$\\)")))))
2099 (defcustom org-emphasis-regexp-components
2100 '(" \t('\"" "- \t.,:?;'\")" " \t\r\n,\"'" "." 1)
2101 "Components used to build the regular expression for emphasis.
2102 This is a list with 6 entries. Terminology: In an emphasis string
2103 like \" *strong word* \", we call the initial space PREMATCH, the final
2104 space POSTMATCH, the stars MARKERS, \"s\" and \"d\" are BORDER characters
2105 and \"trong wor\" is the body. The different components in this variable
2106 specify what is allowed/forbidden in each part:
2108 pre Chars allowed as prematch. Beginning of line will be allowed too.
2109 post Chars allowed as postmatch. End of line will be allowed too.
2110 border The chars *forbidden* as border characters.
2111 body-regexp A regexp like \".\" to match a body character. Don't use
2112 non-shy groups here, and don't allow newline here.
2113 newline The maximum number of newlines allowed in an emphasis exp.
2115 Use customize to modify this, or restart Emacs after changing it."
2116 :group 'org-font-lock
2117 :set 'org-set-emph-re
2118 :type '(list
2119 (sexp :tag "Allowed chars in pre ")
2120 (sexp :tag "Allowed chars in post ")
2121 (sexp :tag "Forbidden chars in border ")
2122 (sexp :tag "Regexp for body ")
2123 (integer :tag "number of newlines allowed")
2124 (option (boolean :tag "Stacking (DISABLED) "))))
2126 (defcustom org-emphasis-alist
2127 '(("*" bold "<b>" "</b>")
2128 ("/" italic "<i>" "</i>")
2129 ("_" underline "<u>" "</u>")
2130 ("=" org-code "<code>" "</code>" verbatim)
2131 ("~" org-verbatim "" "" verbatim)
2132 ("+" (:strike-through t) "<del>" "</del>")
2134 "Special syntax for emphasized text.
2135 Text starting and ending with a special character will be emphasized, for
2136 example *bold*, _underlined_ and /italic/. This variable sets the marker
2137 characters, the face to be used by font-lock for highlighting in Org-mode
2138 Emacs buffers, and the HTML tags to be used for this.
2139 Use customize to modify this, or restart Emacs after changing it."
2140 :group 'org-font-lock
2141 :set 'org-set-emph-re
2142 :type '(repeat
2143 (list
2144 (string :tag "Marker character")
2145 (choice
2146 (face :tag "Font-lock-face")
2147 (plist :tag "Face property list"))
2148 (string :tag "HTML start tag")
2149 (string :tag "HTML end tag")
2150 (option (const verbatim)))))
2152 ;;; Miscellaneous options
2154 (defgroup org-completion nil
2155 "Completion in Org-mode."
2156 :tag "Org Completion"
2157 :group 'org)
2159 (defcustom org-completion-fallback-command 'hippie-expand
2160 "The expansion command called by \\[org-complete] in normal context.
2161 Normal means, no org-mode-specific context."
2162 :group 'org-completion
2163 :type 'function)
2165 ;;; Functions and variables from ther packages
2166 ;; Declared here to avoid compiler warnings
2168 ;; XEmacs only
2169 (defvar outline-mode-menu-heading)
2170 (defvar outline-mode-menu-show)
2171 (defvar outline-mode-menu-hide)
2172 (defvar zmacs-regions) ; XEmacs regions
2174 ;; Emacs only
2175 (defvar mark-active)
2177 ;; Various packages
2178 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
2179 (declare-function calendar-forward-day "cal-move" (arg))
2180 (declare-function calendar-goto-date "cal-move" (date))
2181 (declare-function calendar-goto-today "cal-move" ())
2182 (declare-function calendar-iso-from-absolute "cal-iso" (&optional date))
2183 (defvar calc-embedded-close-formula)
2184 (defvar calc-embedded-open-formula)
2185 (declare-function cdlatex-tab "ext:cdlatex" ())
2186 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2187 (defvar font-lock-unfontify-region-function)
2188 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2189 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2190 (defvar iswitchb-temp-buflist)
2191 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2192 (declare-function org-agenda-skip "org-agenda" ())
2193 (declare-function org-format-agenda-item "org-agenda"
2194 (extra txt &optional category tags dotime noprefix remove-re))
2195 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2196 (declare-function org-agenda-change-all-lines "org-agenda"
2197 (newhead hdmarker &optional fixface))
2198 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2199 (declare-function org-agenda-maybe-redo "org-agenda" ())
2200 (declare-function parse-time-string "parse-time" (string))
2201 (declare-function remember "remember" (&optional initial))
2202 (declare-function remember-buffer-desc "remember" ())
2203 (declare-function remember-finalize "remember" ())
2204 (defvar remember-save-after-remembering)
2205 (defvar remember-data-file)
2206 (defvar remember-register)
2207 (defvar remember-buffer)
2208 (defvar remember-handler-functions)
2209 (defvar remember-annotation-functions)
2210 (defvar texmathp-why)
2211 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2212 (declare-function table--at-cell-p "table" (position &optional object at-column))
2214 (defvar w3m-current-url)
2215 (defvar w3m-current-title)
2217 (defvar org-latex-regexps)
2219 ;;; Autoload and prepare some org modules
2221 ;; Some table stuff that needs to be defined here, because it is used
2222 ;; by the functions setting up org-mode or checking for table context.
2224 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2225 "Detects an org-type or table-type table.")
2226 (defconst org-table-line-regexp "^[ \t]*|"
2227 "Detects an org-type table line.")
2228 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2229 "Detects an org-type table line.")
2230 (defconst org-table-hline-regexp "^[ \t]*|-"
2231 "Detects an org-type table hline.")
2232 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2233 "Detects a table-type table hline.")
2234 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2235 "Searching from within a table (any type) this finds the first line
2236 outside the table.")
2238 ;; Autoload the functions in org-table.el that are needed by functions here.
2240 (eval-and-compile
2241 (org-autoload "org-table"
2242 '(org-table-align org-table-begin org-table-blank-field
2243 org-table-convert org-table-convert-region org-table-copy-down
2244 org-table-copy-region org-table-create
2245 org-table-create-or-convert-from-region
2246 org-table-create-with-table.el org-table-current-dline
2247 org-table-cut-region org-table-delete-column org-table-edit-field
2248 org-table-edit-formulas org-table-end org-table-eval-formula
2249 org-table-export org-table-field-info
2250 org-table-get-stored-formulas org-table-goto-column
2251 org-table-hline-and-move org-table-import org-table-insert-column
2252 org-table-insert-hline org-table-insert-row org-table-iterate
2253 org-table-justify-field-maybe org-table-kill-row
2254 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2255 org-table-move-column org-table-move-column-left
2256 org-table-move-column-right org-table-move-row
2257 org-table-move-row-down org-table-move-row-up
2258 org-table-next-field org-table-next-row org-table-paste-rectangle
2259 org-table-previous-field org-table-recalculate
2260 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2261 org-table-toggle-coordinate-overlays
2262 org-table-toggle-formula-debugger org-table-wrap-region
2263 orgtbl-mode turn-on-orgtbl)))
2265 (defun org-at-table-p (&optional table-type)
2266 "Return t if the cursor is inside an org-type table.
2267 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2268 (if org-enable-table-editor
2269 (save-excursion
2270 (beginning-of-line 1)
2271 (looking-at (if table-type org-table-any-line-regexp
2272 org-table-line-regexp)))
2273 nil))
2274 (defsubst org-table-p () (org-at-table-p))
2276 (defun org-at-table.el-p ()
2277 "Return t if and only if we are at a table.el table."
2278 (and (org-at-table-p 'any)
2279 (save-excursion
2280 (goto-char (org-table-begin 'any))
2281 (looking-at org-table1-hline-regexp))))
2282 (defun org-table-recognize-table.el ()
2283 "If there is a table.el table nearby, recognize it and move into it."
2284 (if org-table-tab-recognizes-table.el
2285 (if (org-at-table.el-p)
2286 (progn
2287 (beginning-of-line 1)
2288 (if (looking-at org-table-dataline-regexp)
2290 (if (looking-at org-table1-hline-regexp)
2291 (progn
2292 (beginning-of-line 2)
2293 (if (looking-at org-table-any-border-regexp)
2294 (beginning-of-line -1)))))
2295 (if (re-search-forward "|" (org-table-end t) t)
2296 (progn
2297 (require 'table)
2298 (if (table--at-cell-p (point))
2300 (message "recognizing table.el table...")
2301 (table-recognize-table)
2302 (message "recognizing table.el table...done")))
2303 (error "This should not happen..."))
2305 nil)
2306 nil))
2308 (defun org-at-table-hline-p ()
2309 "Return t if the cursor is inside a hline in a table."
2310 (if org-enable-table-editor
2311 (save-excursion
2312 (beginning-of-line 1)
2313 (looking-at org-table-hline-regexp))
2314 nil))
2316 (defvar org-table-clean-did-remove-column nil)
2318 (defun org-table-map-tables (function)
2319 "Apply FUNCTION to the start of all tables in the buffer."
2320 (save-excursion
2321 (save-restriction
2322 (widen)
2323 (goto-char (point-min))
2324 (while (re-search-forward org-table-any-line-regexp nil t)
2325 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2326 (beginning-of-line 1)
2327 (if (looking-at org-table-line-regexp)
2328 (save-excursion (funcall function)))
2329 (re-search-forward org-table-any-border-regexp nil 1))))
2330 (message "Mapping tables: done"))
2332 ;; Declare and autoload functions from org-exp.el
2334 (declare-function org-default-export-plist "org-exp")
2335 (declare-function org-infile-export-plist "org-exp")
2336 (declare-function org-get-current-options "org-exp")
2337 (eval-and-compile
2338 (org-autoload "org-exp"
2339 '(org-export org-export-as-ascii org-export-visible
2340 org-insert-export-options-template org-export-as-html-and-open
2341 org-export-as-html-batch org-export-as-html-to-buffer
2342 org-replace-region-by-html org-export-region-as-html
2343 org-export-as-html org-export-icalendar-this-file
2344 org-export-icalendar-all-agenda-files
2345 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2347 ;; Declare and autoload functions from org-exp.el
2349 (eval-and-compile
2350 (org-autoload "org-exp"
2351 '(org-agenda org-agenda-list org-search-view
2352 org-todo-list org-tags-view org-agenda-list-stuck-projects
2353 org-diary org-agenda-to-appt)))
2355 ;; Autoload org-remember
2357 (eval-and-compile
2358 (org-autoload "org-remember"
2359 '(org-remember-insinuate org-remember-annotation
2360 org-remember-apply-template org-remember org-remember-handler)))
2362 ;; Autoload org-clock.el
2364 (defvar org-clock-marker (make-marker)
2365 "Marker recording the last clock-in.")
2367 (eval-and-compile
2368 (org-autoload
2369 "org-clock"
2370 '(org-clock-in org-clock-out org-clock-cancel
2371 org-clock-goto org-clock-sum org-clock-display
2372 org-remove-clock-overlays org-clock-report
2373 org-clocktable-shift org-dblock-write:clocktable
2374 org-get-clocktable)))
2376 (defun org-clock-update-time-maybe ()
2377 "If this is a CLOCK line, update it and return t.
2378 Otherwise, return nil."
2379 (interactive)
2380 (save-excursion
2381 (beginning-of-line 1)
2382 (skip-chars-forward " \t")
2383 (when (looking-at org-clock-string)
2384 (let ((re (concat "[ \t]*" org-clock-string
2385 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
2386 "\\([ \t]*=>.*\\)?"))
2387 ts te h m s)
2388 (if (not (looking-at re))
2390 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
2391 (end-of-line 1)
2392 (setq ts (match-string 1)
2393 te (match-string 2))
2394 (setq s (- (time-to-seconds
2395 (apply 'encode-time (org-parse-time-string te)))
2396 (time-to-seconds
2397 (apply 'encode-time (org-parse-time-string ts))))
2398 h (floor (/ s 3600))
2399 s (- s (* 3600 h))
2400 m (floor (/ s 60))
2401 s (- s (* 60 s)))
2402 (insert " => " (format "%2d:%02d" h m))
2403 t)))))
2405 (defun org-check-running-clock ()
2406 "Check if the current buffer contains the running clock.
2407 If yes, offer to stop it and to save the buffer with the changes."
2408 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2409 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2410 (buffer-name))))
2411 (org-clock-out)
2412 (when (y-or-n-p "Save changed buffer?")
2413 (save-buffer))))
2415 (defun org-clocktable-try-shift (dir n)
2416 "Check if this line starts a clock table, if yes, shift the time block."
2417 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2418 (org-clocktable-shift dir n)))
2420 ;; Autoload archiving code
2421 ;; The stuff that is needed for cycling and tags has to be defined here.
2423 (defgroup org-archive nil
2424 "Options concerning archiving in Org-mode."
2425 :tag "Org Archive"
2426 :group 'org-structure)
2428 (defcustom org-archive-location "%s_archive::"
2429 "The location where subtrees should be archived.
2431 Otherwise, the value of this variable is a string, consisting of two
2432 parts, separated by a double-colon.
2434 The first part is a file name - when omitted, archiving happens in the same
2435 file. %s will be replaced by the current file name (without directory part).
2436 Archiving to a different file is useful to keep archived entries from
2437 contributing to the Org-mode Agenda.
2439 The part after the double colon is a headline. The archived entries will be
2440 filed under that headline. When omitted, the subtrees are simply filed away
2441 at the end of the file, as top-level entries.
2443 Here are a few examples:
2444 \"%s_archive::\"
2445 If the current file is Projects.org, archive in file
2446 Projects.org_archive, as top-level trees. This is the default.
2448 \"::* Archived Tasks\"
2449 Archive in the current file, under the top-level headline
2450 \"* Archived Tasks\".
2452 \"~/org/archive.org::\"
2453 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2455 \"basement::** Finished Tasks\"
2456 Archive in file ./basement (relative path), as level 3 trees
2457 below the level 2 heading \"** Finished Tasks\".
2459 You may set this option on a per-file basis by adding to the buffer a
2460 line like
2462 #+ARCHIVE: basement::** Finished Tasks
2464 You may also define it locally for a subtree by setting an ARCHIVE property
2465 in the entry. If such a property is found in an entry, or anywhere up
2466 the hierarchy, it will be used."
2467 :group 'org-archive
2468 :type 'string)
2470 (defcustom org-archive-tag "ARCHIVE"
2471 "The tag that marks a subtree as archived.
2472 An archived subtree does not open during visibility cycling, and does
2473 not contribute to the agenda listings.
2474 After changing this, font-lock must be restarted in the relevant buffers to
2475 get the proper fontification."
2476 :group 'org-archive
2477 :group 'org-keywords
2478 :type 'string)
2480 (defcustom org-agenda-skip-archived-trees t
2481 "Non-nil means, the agenda will skip any items located in archived trees.
2482 An archived tree is a tree marked with the tag ARCHIVE."
2483 :group 'org-archive
2484 :group 'org-agenda-skip
2485 :type 'boolean)
2487 (defcustom org-cycle-open-archived-trees nil
2488 "Non-nil means, `org-cycle' will open archived trees.
2489 An archived tree is a tree marked with the tag ARCHIVE.
2490 When nil, archived trees will stay folded. You can still open them with
2491 normal outline commands like `show-all', but not with the cycling commands."
2492 :group 'org-archive
2493 :group 'org-cycle
2494 :type 'boolean)
2496 (defcustom org-sparse-tree-open-archived-trees nil
2497 "Non-nil means sparse tree construction shows matches in archived trees.
2498 When nil, matches in these trees are highlighted, but the trees are kept in
2499 collapsed state."
2500 :group 'org-archive
2501 :group 'org-sparse-trees
2502 :type 'boolean)
2504 (defun org-cycle-hide-archived-subtrees (state)
2505 "Re-hide all archived subtrees after a visibility state change."
2506 (when (and (not org-cycle-open-archived-trees)
2507 (not (memq state '(overview folded))))
2508 (save-excursion
2509 (let* ((globalp (memq state '(contents all)))
2510 (beg (if globalp (point-min) (point)))
2511 (end (if globalp (point-max) (org-end-of-subtree t))))
2512 (org-hide-archived-subtrees beg end)
2513 (goto-char beg)
2514 (if (looking-at (concat ".*:" org-archive-tag ":"))
2515 (message "%s" (substitute-command-keys
2516 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2518 (defun org-force-cycle-archived ()
2519 "Cycle subtree even if it is archived."
2520 (interactive)
2521 (setq this-command 'org-cycle)
2522 (let ((org-cycle-open-archived-trees t))
2523 (call-interactively 'org-cycle)))
2525 (defun org-hide-archived-subtrees (beg end)
2526 "Re-hide all archived subtrees after a visibility state change."
2527 (save-excursion
2528 (let* ((re (concat ":" org-archive-tag ":")))
2529 (goto-char beg)
2530 (while (re-search-forward re end t)
2531 (and (org-on-heading-p) (hide-subtree))
2532 (org-end-of-subtree t)))))
2534 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2536 (eval-and-compile
2537 (org-autoload "org-archive"
2538 '(org-add-archive-files org-archive-subtree
2539 org-archive-to-archive-sibling org-toggle-archive-tag)))
2541 ;; Autoload Column View Code
2543 (declare-function org-columns-number-to-string "org-colview")
2544 (declare-function org-columns-get-format-and-top-level "org-colview")
2545 (declare-function org-columns-compute "org-colview")
2547 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2548 '(org-columns-number-to-string org-columns-get-format-and-top-level
2549 org-columns-compute org-agenda-columns org-columns-remove-overlays
2550 org-columns org-insert-columns-dblock))
2552 ;;; Variables for pre-computed regular expressions, all buffer local
2554 (defvar org-drawer-regexp nil
2555 "Matches first line of a hidden block.")
2556 (make-variable-buffer-local 'org-drawer-regexp)
2557 (defvar org-todo-regexp nil
2558 "Matches any of the TODO state keywords.")
2559 (make-variable-buffer-local 'org-todo-regexp)
2560 (defvar org-not-done-regexp nil
2561 "Matches any of the TODO state keywords except the last one.")
2562 (make-variable-buffer-local 'org-not-done-regexp)
2563 (defvar org-todo-line-regexp nil
2564 "Matches a headline and puts TODO state into group 2 if present.")
2565 (make-variable-buffer-local 'org-todo-line-regexp)
2566 (defvar org-complex-heading-regexp nil
2567 "Matches a headline and puts everything into groups:
2568 group 1: the stars
2569 group 2: The todo keyword, maybe
2570 group 3: Priority cookie
2571 group 4: True headline
2572 group 5: Tags")
2573 (make-variable-buffer-local 'org-complex-heading-regexp)
2574 (defvar org-todo-line-tags-regexp nil
2575 "Matches a headline and puts TODO state into group 2 if present.
2576 Also put tags into group 4 if tags are present.")
2577 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2578 (defvar org-nl-done-regexp nil
2579 "Matches newline followed by a headline with the DONE keyword.")
2580 (make-variable-buffer-local 'org-nl-done-regexp)
2581 (defvar org-looking-at-done-regexp nil
2582 "Matches the DONE keyword a point.")
2583 (make-variable-buffer-local 'org-looking-at-done-regexp)
2584 (defvar org-ds-keyword-length 12
2585 "Maximum length of the Deadline and SCHEDULED keywords.")
2586 (make-variable-buffer-local 'org-ds-keyword-length)
2587 (defvar org-deadline-regexp nil
2588 "Matches the DEADLINE keyword.")
2589 (make-variable-buffer-local 'org-deadline-regexp)
2590 (defvar org-deadline-time-regexp nil
2591 "Matches the DEADLINE keyword together with a time stamp.")
2592 (make-variable-buffer-local 'org-deadline-time-regexp)
2593 (defvar org-deadline-line-regexp nil
2594 "Matches the DEADLINE keyword and the rest of the line.")
2595 (make-variable-buffer-local 'org-deadline-line-regexp)
2596 (defvar org-scheduled-regexp nil
2597 "Matches the SCHEDULED keyword.")
2598 (make-variable-buffer-local 'org-scheduled-regexp)
2599 (defvar org-scheduled-time-regexp nil
2600 "Matches the SCHEDULED keyword together with a time stamp.")
2601 (make-variable-buffer-local 'org-scheduled-time-regexp)
2602 (defvar org-closed-time-regexp nil
2603 "Matches the CLOSED keyword together with a time stamp.")
2604 (make-variable-buffer-local 'org-closed-time-regexp)
2606 (defvar org-keyword-time-regexp nil
2607 "Matches any of the 4 keywords, together with the time stamp.")
2608 (make-variable-buffer-local 'org-keyword-time-regexp)
2609 (defvar org-keyword-time-not-clock-regexp nil
2610 "Matches any of the 3 keywords, together with the time stamp.")
2611 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2612 (defvar org-maybe-keyword-time-regexp nil
2613 "Matches a timestamp, possibly preceeded by a keyword.")
2614 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2615 (defvar org-planning-or-clock-line-re nil
2616 "Matches a line with planning or clock info.")
2617 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2619 (defconst org-plain-time-of-day-regexp
2620 (concat
2621 "\\(\\<[012]?[0-9]"
2622 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2623 "\\(--?"
2624 "\\(\\<[012]?[0-9]"
2625 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2626 "\\)?")
2627 "Regular expression to match a plain time or time range.
2628 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2629 groups carry important information:
2630 0 the full match
2631 1 the first time, range or not
2632 8 the second time, if it is a range.")
2634 (defconst org-plain-time-extension-regexp
2635 (concat
2636 "\\(\\<[012]?[0-9]"
2637 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2638 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2639 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2640 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2641 groups carry important information:
2642 0 the full match
2643 7 hours of duration
2644 9 minutes of duration")
2646 (defconst org-stamp-time-of-day-regexp
2647 (concat
2648 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2649 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2650 "\\(--?"
2651 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2652 "Regular expression to match a timestamp time or time range.
2653 After a match, the following groups carry important information:
2654 0 the full match
2655 1 date plus weekday, for backreferencing to make sure both times on same day
2656 2 the first time, range or not
2657 4 the second time, if it is a range.")
2659 (defconst org-startup-options
2660 '(("fold" org-startup-folded t)
2661 ("overview" org-startup-folded t)
2662 ("nofold" org-startup-folded nil)
2663 ("showall" org-startup-folded nil)
2664 ("content" org-startup-folded content)
2665 ("hidestars" org-hide-leading-stars t)
2666 ("showstars" org-hide-leading-stars nil)
2667 ("odd" org-odd-levels-only t)
2668 ("oddeven" org-odd-levels-only nil)
2669 ("align" org-startup-align-all-tables t)
2670 ("noalign" org-startup-align-all-tables nil)
2671 ("customtime" org-display-custom-times t)
2672 ("logdone" org-log-done time)
2673 ("lognotedone" org-log-done note)
2674 ("nologdone" org-log-done nil)
2675 ("lognoteclock-out" org-log-note-clock-out t)
2676 ("nolognoteclock-out" org-log-note-clock-out nil)
2677 ("logrepeat" org-log-repeat state)
2678 ("lognoterepeat" org-log-repeat note)
2679 ("nologrepeat" org-log-repeat nil)
2680 ("constcgs" constants-unit-system cgs)
2681 ("constSI" constants-unit-system SI))
2682 "Variable associated with STARTUP options for org-mode.
2683 Each element is a list of three items: The startup options as written
2684 in the #+STARTUP line, the corresponding variable, and the value to
2685 set this variable to if the option is found. An optional forth element PUSH
2686 means to push this value onto the list in the variable.")
2688 (defun org-set-regexps-and-options ()
2689 "Precompute regular expressions for current buffer."
2690 (when (org-mode-p)
2691 (org-set-local 'org-todo-kwd-alist nil)
2692 (org-set-local 'org-todo-key-alist nil)
2693 (org-set-local 'org-todo-key-trigger nil)
2694 (org-set-local 'org-todo-keywords-1 nil)
2695 (org-set-local 'org-done-keywords nil)
2696 (org-set-local 'org-todo-heads nil)
2697 (org-set-local 'org-todo-sets nil)
2698 (org-set-local 'org-todo-log-states nil)
2699 (let ((re (org-make-options-regexp
2700 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2701 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
2702 "CONSTANTS" "PROPERTY" "DRAWERS")))
2703 (splitre "[ \t]+")
2704 kwds kws0 kwsa key log value cat arch tags const links hw dws
2705 tail sep kws1 prio props drawers)
2706 (save-excursion
2707 (save-restriction
2708 (widen)
2709 (goto-char (point-min))
2710 (while (re-search-forward re nil t)
2711 (setq key (match-string 1) value (org-match-string-no-properties 2))
2712 (cond
2713 ((equal key "CATEGORY")
2714 (if (string-match "[ \t]+$" value)
2715 (setq value (replace-match "" t t value)))
2716 (setq cat value))
2717 ((member key '("SEQ_TODO" "TODO"))
2718 (push (cons 'sequence (org-split-string value splitre)) kwds))
2719 ((equal key "TYP_TODO")
2720 (push (cons 'type (org-split-string value splitre)) kwds))
2721 ((equal key "TAGS")
2722 (setq tags (append tags (org-split-string value splitre))))
2723 ((equal key "COLUMNS")
2724 (org-set-local 'org-columns-default-format value))
2725 ((equal key "LINK")
2726 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2727 (push (cons (match-string 1 value)
2728 (org-trim (match-string 2 value)))
2729 links)))
2730 ((equal key "PRIORITIES")
2731 (setq prio (org-split-string value " +")))
2732 ((equal key "PROPERTY")
2733 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2734 (push (cons (match-string 1 value) (match-string 2 value))
2735 props)))
2736 ((equal key "DRAWERS")
2737 (setq drawers (org-split-string value splitre)))
2738 ((equal key "CONSTANTS")
2739 (setq const (append const (org-split-string value splitre))))
2740 ((equal key "STARTUP")
2741 (let ((opts (org-split-string value splitre))
2742 l var val)
2743 (while (setq l (pop opts))
2744 (when (setq l (assoc l org-startup-options))
2745 (setq var (nth 1 l) val (nth 2 l))
2746 (if (not (nth 3 l))
2747 (set (make-local-variable var) val)
2748 (if (not (listp (symbol-value var)))
2749 (set (make-local-variable var) nil))
2750 (set (make-local-variable var) (symbol-value var))
2751 (add-to-list var val))))))
2752 ((equal key "ARCHIVE")
2753 (string-match " *$" value)
2754 (setq arch (replace-match "" t t value))
2755 (remove-text-properties 0 (length arch)
2756 '(face t fontified t) arch)))
2758 (when cat
2759 (org-set-local 'org-category (intern cat))
2760 (push (cons "CATEGORY" cat) props))
2761 (when prio
2762 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2763 (setq prio (mapcar 'string-to-char prio))
2764 (org-set-local 'org-highest-priority (nth 0 prio))
2765 (org-set-local 'org-lowest-priority (nth 1 prio))
2766 (org-set-local 'org-default-priority (nth 2 prio)))
2767 (and props (org-set-local 'org-local-properties (nreverse props)))
2768 (and drawers (org-set-local 'org-drawers drawers))
2769 (and arch (org-set-local 'org-archive-location arch))
2770 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2771 ;; Process the TODO keywords
2772 (unless kwds
2773 ;; Use the global values as if they had been given locally.
2774 (setq kwds (default-value 'org-todo-keywords))
2775 (if (stringp (car kwds))
2776 (setq kwds (list (cons org-todo-interpretation
2777 (default-value 'org-todo-keywords)))))
2778 (setq kwds (reverse kwds)))
2779 (setq kwds (nreverse kwds))
2780 (let (inter kws kw)
2781 (while (setq kws (pop kwds))
2782 (setq inter (pop kws) sep (member "|" kws)
2783 kws0 (delete "|" (copy-sequence kws))
2784 kwsa nil
2785 kws1 (mapcar
2786 (lambda (x)
2787 ;; 1 2
2788 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2789 (progn
2790 (setq kw (match-string 1 x)
2791 key (and (match-end 2) (match-string 2 x))
2792 log (org-extract-log-state-settings x))
2793 (push (cons kw (and key (string-to-char key))) kwsa)
2794 (and log (push log org-todo-log-states))
2796 (error "Invalid TODO keyword %s" x)))
2797 kws0)
2798 kwsa (if kwsa (append '((:startgroup))
2799 (nreverse kwsa)
2800 '((:endgroup))))
2801 hw (car kws1)
2802 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2803 tail (list inter hw (car dws) (org-last dws)))
2804 (add-to-list 'org-todo-heads hw 'append)
2805 (push kws1 org-todo-sets)
2806 (setq org-done-keywords (append org-done-keywords dws nil))
2807 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2808 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2809 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2810 (setq org-todo-sets (nreverse org-todo-sets)
2811 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2812 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2813 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2814 ;; Process the constants
2815 (when const
2816 (let (e cst)
2817 (while (setq e (pop const))
2818 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2819 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2820 (setq org-table-formula-constants-local cst)))
2822 ;; Process the tags.
2823 (when tags
2824 (let (e tgs)
2825 (while (setq e (pop tags))
2826 (cond
2827 ((equal e "{") (push '(:startgroup) tgs))
2828 ((equal e "}") (push '(:endgroup) tgs))
2829 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2830 (push (cons (match-string 1 e)
2831 (string-to-char (match-string 2 e)))
2832 tgs))
2833 (t (push (list e) tgs))))
2834 (org-set-local 'org-tag-alist nil)
2835 (while (setq e (pop tgs))
2836 (or (and (stringp (car e))
2837 (assoc (car e) org-tag-alist))
2838 (push e org-tag-alist))))))
2840 ;; Compute the regular expressions and other local variables
2841 (if (not org-done-keywords)
2842 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2843 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2844 (length org-scheduled-string)
2845 (length org-clock-string)
2846 (length org-closed-string)))
2847 org-drawer-regexp
2848 (concat "^[ \t]*:\\("
2849 (mapconcat 'regexp-quote org-drawers "\\|")
2850 "\\):[ \t]*$")
2851 org-not-done-keywords
2852 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2853 org-todo-regexp
2854 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2855 "\\|") "\\)\\>")
2856 org-not-done-regexp
2857 (concat "\\<\\("
2858 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2859 "\\)\\>")
2860 org-todo-line-regexp
2861 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2862 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2863 "\\)\\>\\)?[ \t]*\\(.*\\)")
2864 org-complex-heading-regexp
2865 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2866 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2867 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2868 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2869 org-nl-done-regexp
2870 (concat "\n\\*+[ \t]+"
2871 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2872 "\\)" "\\>")
2873 org-todo-line-tags-regexp
2874 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2875 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2876 (org-re
2877 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2878 org-looking-at-done-regexp
2879 (concat "^" "\\(?:"
2880 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
2881 "\\>")
2882 org-deadline-regexp (concat "\\<" org-deadline-string)
2883 org-deadline-time-regexp
2884 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2885 org-deadline-line-regexp
2886 (concat "\\<\\(" org-deadline-string "\\).*")
2887 org-scheduled-regexp
2888 (concat "\\<" org-scheduled-string)
2889 org-scheduled-time-regexp
2890 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2891 org-closed-time-regexp
2892 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2893 org-keyword-time-regexp
2894 (concat "\\<\\(" org-scheduled-string
2895 "\\|" org-deadline-string
2896 "\\|" org-closed-string
2897 "\\|" org-clock-string "\\)"
2898 " *[[<]\\([^]>]+\\)[]>]")
2899 org-keyword-time-not-clock-regexp
2900 (concat "\\<\\(" org-scheduled-string
2901 "\\|" org-deadline-string
2902 "\\|" org-closed-string
2903 "\\)"
2904 " *[[<]\\([^]>]+\\)[]>]")
2905 org-maybe-keyword-time-regexp
2906 (concat "\\(\\<\\(" org-scheduled-string
2907 "\\|" org-deadline-string
2908 "\\|" org-closed-string
2909 "\\|" org-clock-string "\\)\\)?"
2910 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
2911 org-planning-or-clock-line-re
2912 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
2913 "\\|" org-deadline-string
2914 "\\|" org-closed-string "\\|" org-clock-string
2915 "\\)\\>\\)")
2917 (org-compute-latex-and-specials-regexp)
2918 (org-set-font-lock-defaults)))
2920 (defun org-extract-log-state-settings (x)
2921 "Extract the log state setting from a TODO keyword string.
2922 This will extract info from a string like \"WAIT(w@/!)\"."
2923 (let (kw key log1 log2)
2924 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
2925 (setq kw (match-string 1 x)
2926 key (and (match-end 2) (match-string 2 x))
2927 log1 (and (match-end 3) (match-string 3 x))
2928 log2 (and (match-end 4) (match-string 4 x)))
2929 (and (or log1 log2)
2930 (list kw
2931 (and log1 (if (equal log1 "!") 'time 'note))
2932 (and log2 (if (equal log2 "!") 'time 'note)))))))
2934 (defun org-remove-keyword-keys (list)
2935 "Remove a pair of parenthesis at the end of each string in LIST."
2936 (mapcar (lambda (x)
2937 (if (string-match "(.*)$" x)
2938 (substring x 0 (match-beginning 0))
2940 list))
2942 ;; FIXME: this could be done much better, using second characters etc.
2943 (defun org-assign-fast-keys (alist)
2944 "Assign fast keys to a keyword-key alist.
2945 Respect keys that are already there."
2946 (let (new e k c c1 c2 (char ?a))
2947 (while (setq e (pop alist))
2948 (cond
2949 ((equal e '(:startgroup)) (push e new))
2950 ((equal e '(:endgroup)) (push e new))
2952 (setq k (car e) c2 nil)
2953 (if (cdr e)
2954 (setq c (cdr e))
2955 ;; automatically assign a character.
2956 (setq c1 (string-to-char
2957 (downcase (substring
2958 k (if (= (string-to-char k) ?@) 1 0)))))
2959 (if (or (rassoc c1 new) (rassoc c1 alist))
2960 (while (or (rassoc char new) (rassoc char alist))
2961 (setq char (1+ char)))
2962 (setq c2 c1))
2963 (setq c (or c2 char)))
2964 (push (cons k c) new))))
2965 (nreverse new)))
2967 ;;; Some variables used in various places
2969 (defvar org-window-configuration nil
2970 "Used in various places to store a window configuration.")
2971 (defvar org-finish-function nil
2972 "Function to be called when `C-c C-c' is used.
2973 This is for getting out of special buffers like remember.")
2976 ;; FIXME: Occasionally check by commenting these, to make sure
2977 ;; no other functions uses these, forgetting to let-bind them.
2978 (defvar entry)
2979 (defvar state)
2980 (defvar last-state)
2981 (defvar date)
2982 (defvar description)
2984 ;; Defined somewhere in this file, but used before definition.
2985 (defvar org-html-entities)
2986 (defvar org-struct-menu)
2987 (defvar org-org-menu)
2988 (defvar org-tbl-menu)
2989 (defvar org-agenda-keymap)
2991 ;;;; Define the Org-mode
2993 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2994 (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."))
2997 ;; We use a before-change function to check if a table might need
2998 ;; an update.
2999 (defvar org-table-may-need-update t
3000 "Indicates that a table might need an update.
3001 This variable is set by `org-before-change-function'.
3002 `org-table-align' sets it back to nil.")
3003 (defun org-before-change-function (beg end)
3004 "Every change indicates that a table might need an update."
3005 (setq org-table-may-need-update t))
3006 (defvar org-mode-map)
3007 (defvar org-mode-hook nil)
3008 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3009 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3010 (defvar org-table-buffer-is-an nil)
3011 (defconst org-outline-regexp "\\*+ ")
3013 ;;;###autoload
3014 (define-derived-mode org-mode outline-mode "Org"
3015 "Outline-based notes management and organizer, alias
3016 \"Carsten's outline-mode for keeping track of everything.\"
3018 Org-mode develops organizational tasks around a NOTES file which
3019 contains information about projects as plain text. Org-mode is
3020 implemented on top of outline-mode, which is ideal to keep the content
3021 of large files well structured. It supports ToDo items, deadlines and
3022 time stamps, which magically appear in the diary listing of the Emacs
3023 calendar. Tables are easily created with a built-in table editor.
3024 Plain text URL-like links connect to websites, emails (VM), Usenet
3025 messages (Gnus), BBDB entries, and any files related to the project.
3026 For printing and sharing of notes, an Org-mode file (or a part of it)
3027 can be exported as a structured ASCII or HTML file.
3029 The following commands are available:
3031 \\{org-mode-map}"
3033 ;; Get rid of Outline menus, they are not needed
3034 ;; Need to do this here because define-derived-mode sets up
3035 ;; the keymap so late. Still, it is a waste to call this each time
3036 ;; we switch another buffer into org-mode.
3037 (if (featurep 'xemacs)
3038 (when (boundp 'outline-mode-menu-heading)
3039 ;; Assume this is Greg's port, it used easymenu
3040 (easy-menu-remove outline-mode-menu-heading)
3041 (easy-menu-remove outline-mode-menu-show)
3042 (easy-menu-remove outline-mode-menu-hide))
3043 (define-key org-mode-map [menu-bar headings] 'undefined)
3044 (define-key org-mode-map [menu-bar hide] 'undefined)
3045 (define-key org-mode-map [menu-bar show] 'undefined))
3047 (org-load-modules-maybe)
3048 (easy-menu-add org-org-menu)
3049 (easy-menu-add org-tbl-menu)
3050 (org-install-agenda-files-menu)
3051 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3052 (org-add-to-invisibility-spec '(org-cwidth))
3053 (when (featurep 'xemacs)
3054 (org-set-local 'line-move-ignore-invisible t))
3055 (org-set-local 'outline-regexp org-outline-regexp)
3056 (org-set-local 'outline-level 'org-outline-level)
3057 (when (and org-ellipsis
3058 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3059 (fboundp 'make-glyph-code))
3060 (unless org-display-table
3061 (setq org-display-table (make-display-table)))
3062 (set-display-table-slot
3063 org-display-table 4
3064 (vconcat (mapcar
3065 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3066 org-ellipsis)))
3067 (if (stringp org-ellipsis) org-ellipsis "..."))))
3068 (setq buffer-display-table org-display-table))
3069 (org-set-regexps-and-options)
3070 ;; Calc embedded
3071 (org-set-local 'calc-embedded-open-mode "# ")
3072 (modify-syntax-entry ?# "<")
3073 (modify-syntax-entry ?@ "w")
3074 (if org-startup-truncated (setq truncate-lines t))
3075 (org-set-local 'font-lock-unfontify-region-function
3076 'org-unfontify-region)
3077 ;; Activate before-change-function
3078 (org-set-local 'org-table-may-need-update t)
3079 (org-add-hook 'before-change-functions 'org-before-change-function nil
3080 'local)
3081 ;; Check for running clock before killing a buffer
3082 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3083 ;; Paragraphs and auto-filling
3084 (org-set-autofill-regexps)
3085 (setq indent-line-function 'org-indent-line-function)
3086 (org-update-radio-target-regexp)
3088 ;; Comment characters
3089 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3090 (org-set-local 'comment-padding " ")
3092 ;; Align options lines
3093 (org-set-local
3094 'align-mode-rules-list
3095 '((org-in-buffer-settings
3096 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3097 (modes . '(org-mode)))))
3099 ;; Imenu
3100 (org-set-local 'imenu-create-index-function
3101 'org-imenu-get-tree)
3103 ;; Make isearch reveal context
3104 (if (or (featurep 'xemacs)
3105 (not (boundp 'outline-isearch-open-invisible-function)))
3106 ;; Emacs 21 and XEmacs make use of the hook
3107 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3108 ;; Emacs 22 deals with this through a special variable
3109 (org-set-local 'outline-isearch-open-invisible-function
3110 (lambda (&rest ignore) (org-show-context 'isearch))))
3112 ;; If empty file that did not turn on org-mode automatically, make it to.
3113 (if (and org-insert-mode-line-in-empty-file
3114 (interactive-p)
3115 (= (point-min) (point-max)))
3116 (insert "# -*- mode: org -*-\n\n"))
3118 (unless org-inhibit-startup
3119 (when org-startup-align-all-tables
3120 (let ((bmp (buffer-modified-p)))
3121 (org-table-map-tables 'org-table-align)
3122 (set-buffer-modified-p bmp)))
3123 (org-cycle-hide-drawers 'all)
3124 (cond
3125 ((eq org-startup-folded t)
3126 (org-cycle '(4)))
3127 ((eq org-startup-folded 'content)
3128 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3129 (org-cycle '(4)) (org-cycle '(4)))))))
3131 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3133 (defun org-current-time ()
3134 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3135 (if (> (car org-time-stamp-rounding-minutes) 1)
3136 (let ((r (car org-time-stamp-rounding-minutes))
3137 (time (decode-time)))
3138 (apply 'encode-time
3139 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3140 (nthcdr 2 time))))
3141 (current-time)))
3143 ;;;; Font-Lock stuff, including the activators
3145 (defvar org-mouse-map (make-sparse-keymap))
3146 (org-defkey org-mouse-map
3147 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3148 (org-defkey org-mouse-map
3149 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3150 (when org-mouse-1-follows-link
3151 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3152 (when org-tab-follows-link
3153 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3154 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3155 (when org-return-follows-link
3156 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3157 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3159 (require 'font-lock)
3161 (defconst org-non-link-chars "]\t\n\r<>")
3162 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3163 "shell" "elisp"))
3164 (defvar org-link-types-re nil
3165 "Matches a link that has a url-like prefix like \"http:\"")
3166 (defvar org-link-re-with-space nil
3167 "Matches a link with spaces, optional angular brackets around it.")
3168 (defvar org-link-re-with-space2 nil
3169 "Matches a link with spaces, optional angular brackets around it.")
3170 (defvar org-angle-link-re nil
3171 "Matches link with angular brackets, spaces are allowed.")
3172 (defvar org-plain-link-re nil
3173 "Matches plain link, without spaces.")
3174 (defvar org-bracket-link-regexp nil
3175 "Matches a link in double brackets.")
3176 (defvar org-bracket-link-analytic-regexp nil
3177 "Regular expression used to analyze links.
3178 Here is what the match groups contain after a match:
3179 1: http:
3180 2: http
3181 3: path
3182 4: [desc]
3183 5: desc")
3184 (defvar org-any-link-re nil
3185 "Regular expression matching any link.")
3187 (defun org-make-link-regexps ()
3188 "Update the link regular expressions.
3189 This should be called after the variable `org-link-types' has changed."
3190 (setq org-link-types-re
3191 (concat
3192 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3193 org-link-re-with-space
3194 (concat
3195 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3196 "\\([^" org-non-link-chars " ]"
3197 "[^" org-non-link-chars "]*"
3198 "[^" org-non-link-chars " ]\\)>?")
3199 org-link-re-with-space2
3200 (concat
3201 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3202 "\\([^" org-non-link-chars " ]"
3203 "[^]\t\n\r]*"
3204 "[^" org-non-link-chars " ]\\)>?")
3205 org-angle-link-re
3206 (concat
3207 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3208 "\\([^" org-non-link-chars " ]"
3209 "[^" org-non-link-chars "]*"
3210 "\\)>")
3211 org-plain-link-re
3212 (concat
3213 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3214 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3215 org-bracket-link-regexp
3216 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3217 org-bracket-link-analytic-regexp
3218 (concat
3219 "\\[\\["
3220 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3221 "\\([^]]+\\)"
3222 "\\]"
3223 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3224 "\\]")
3225 org-any-link-re
3226 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3227 org-angle-link-re "\\)\\|\\("
3228 org-plain-link-re "\\)")))
3230 (org-make-link-regexps)
3232 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3233 "Regular expression for fast time stamp matching.")
3234 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3235 "Regular expression for fast time stamp matching.")
3236 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3237 "Regular expression matching time strings for analysis.
3238 This one does not require the space after the date, so it can be used
3239 on a string that terminates immediately after the date.")
3240 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3241 "Regular expression matching time strings for analysis.")
3242 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3243 "Regular expression matching time stamps, with groups.")
3244 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3245 "Regular expression matching time stamps (also [..]), with groups.")
3246 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3247 "Regular expression matching a time stamp range.")
3248 (defconst org-tr-regexp-both
3249 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3250 "Regular expression matching a time stamp range.")
3251 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3252 org-ts-regexp "\\)?")
3253 "Regular expression matching a time stamp or time stamp range.")
3254 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3255 org-ts-regexp-both "\\)?")
3256 "Regular expression matching a time stamp or time stamp range.
3257 The time stamps may be either active or inactive.")
3259 (defvar org-emph-face nil)
3261 (defun org-do-emphasis-faces (limit)
3262 "Run through the buffer and add overlays to links."
3263 (let (rtn)
3264 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3265 (if (not (= (char-after (match-beginning 3))
3266 (char-after (match-beginning 4))))
3267 (progn
3268 (setq rtn t)
3269 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3270 'face
3271 (nth 1 (assoc (match-string 3)
3272 org-emphasis-alist)))
3273 (add-text-properties (match-beginning 2) (match-end 2)
3274 '(font-lock-multiline t))
3275 (when org-hide-emphasis-markers
3276 (add-text-properties (match-end 4) (match-beginning 5)
3277 '(invisible org-link))
3278 (add-text-properties (match-beginning 3) (match-end 3)
3279 '(invisible org-link)))))
3280 (backward-char 1))
3281 rtn))
3283 (defun org-emphasize (&optional char)
3284 "Insert or change an emphasis, i.e. a font like bold or italic.
3285 If there is an active region, change that region to a new emphasis.
3286 If there is no region, just insert the marker characters and position
3287 the cursor between them.
3288 CHAR should be either the marker character, or the first character of the
3289 HTML tag associated with that emphasis. If CHAR is a space, the means
3290 to remove the emphasis of the selected region.
3291 If char is not given (for example in an interactive call) it
3292 will be prompted for."
3293 (interactive)
3294 (let ((eal org-emphasis-alist) e det
3295 (erc org-emphasis-regexp-components)
3296 (prompt "")
3297 (string "") beg end move tag c s)
3298 (if (org-region-active-p)
3299 (setq beg (region-beginning) end (region-end)
3300 string (buffer-substring beg end))
3301 (setq move t))
3303 (while (setq e (pop eal))
3304 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3305 c (aref tag 0))
3306 (push (cons c (string-to-char (car e))) det)
3307 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3308 (substring tag 1)))))
3309 (unless char
3310 (message "%s" (concat "Emphasis marker or tag:" prompt))
3311 (setq char (read-char-exclusive)))
3312 (setq char (or (cdr (assoc char det)) char))
3313 (if (equal char ?\ )
3314 (setq s "" move nil)
3315 (unless (assoc (char-to-string char) org-emphasis-alist)
3316 (error "No such emphasis marker: \"%c\"" char))
3317 (setq s (char-to-string char)))
3318 (while (and (> (length string) 1)
3319 (equal (substring string 0 1) (substring string -1))
3320 (assoc (substring string 0 1) org-emphasis-alist))
3321 (setq string (substring string 1 -1)))
3322 (setq string (concat s string s))
3323 (if beg (delete-region beg end))
3324 (unless (or (bolp)
3325 (string-match (concat "[" (nth 0 erc) "\n]")
3326 (char-to-string (char-before (point)))))
3327 (insert " "))
3328 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3329 (char-to-string (char-after (point))))
3330 (insert " ") (backward-char 1))
3331 (insert string)
3332 (and move (backward-char 1))))
3334 (defconst org-nonsticky-props
3335 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3338 (defun org-activate-plain-links (limit)
3339 "Run through the buffer and add overlays to links."
3340 (catch 'exit
3341 (let (f)
3342 (while (re-search-forward org-plain-link-re limit t)
3343 (setq f (get-text-property (match-beginning 0) 'face))
3344 (if (or (eq f 'org-tag)
3345 (and (listp f) (memq 'org-tag f)))
3347 (add-text-properties (match-beginning 0) (match-end 0)
3348 (list 'mouse-face 'highlight
3349 'rear-nonsticky org-nonsticky-props
3350 'keymap org-mouse-map
3352 (throw 'exit t))))))
3354 (defun org-activate-code (limit)
3355 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3356 (unless (get-text-property (match-beginning 1) 'face)
3357 (remove-text-properties (match-beginning 0) (match-end 0)
3358 '(display t invisible t intangible t))
3359 t)))
3361 (defun org-activate-angle-links (limit)
3362 "Run through the buffer and add overlays to links."
3363 (if (re-search-forward org-angle-link-re limit t)
3364 (progn
3365 (add-text-properties (match-beginning 0) (match-end 0)
3366 (list 'mouse-face 'highlight
3367 'rear-nonsticky org-nonsticky-props
3368 'keymap org-mouse-map
3370 t)))
3372 (defun org-activate-bracket-links (limit)
3373 "Run through the buffer and add overlays to bracketed links."
3374 (if (re-search-forward org-bracket-link-regexp limit t)
3375 (let* ((help (concat "LINK: "
3376 (org-match-string-no-properties 1)))
3377 ;; FIXME: above we should remove the escapes.
3378 ;; but that requires another match, protecting match data,
3379 ;; a lot of overhead for font-lock.
3380 (ip (org-maybe-intangible
3381 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3382 'keymap org-mouse-map 'mouse-face 'highlight
3383 'font-lock-multiline t 'help-echo help)))
3384 (vp (list 'rear-nonsticky org-nonsticky-props
3385 'keymap org-mouse-map 'mouse-face 'highlight
3386 ' font-lock-multiline t 'help-echo help)))
3387 ;; We need to remove the invisible property here. Table narrowing
3388 ;; may have made some of this invisible.
3389 (remove-text-properties (match-beginning 0) (match-end 0)
3390 '(invisible nil))
3391 (if (match-end 3)
3392 (progn
3393 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3394 (add-text-properties (match-beginning 3) (match-end 3) vp)
3395 (add-text-properties (match-end 3) (match-end 0) ip))
3396 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3397 (add-text-properties (match-beginning 1) (match-end 1) vp)
3398 (add-text-properties (match-end 1) (match-end 0) ip))
3399 t)))
3401 (defun org-activate-dates (limit)
3402 "Run through the buffer and add overlays to dates."
3403 (if (re-search-forward org-tsr-regexp-both limit t)
3404 (progn
3405 (add-text-properties (match-beginning 0) (match-end 0)
3406 (list 'mouse-face 'highlight
3407 'rear-nonsticky org-nonsticky-props
3408 'keymap org-mouse-map))
3409 (when org-display-custom-times
3410 (if (match-end 3)
3411 (org-display-custom-time (match-beginning 3) (match-end 3)))
3412 (org-display-custom-time (match-beginning 1) (match-end 1)))
3413 t)))
3415 (defvar org-target-link-regexp nil
3416 "Regular expression matching radio targets in plain text.")
3417 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3418 "Regular expression matching a link target.")
3419 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3420 "Regular expression matching a radio target.")
3421 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3422 "Regular expression matching any target.")
3424 (defun org-activate-target-links (limit)
3425 "Run through the buffer and add overlays to target matches."
3426 (when org-target-link-regexp
3427 (let ((case-fold-search t))
3428 (if (re-search-forward org-target-link-regexp limit t)
3429 (progn
3430 (add-text-properties (match-beginning 0) (match-end 0)
3431 (list 'mouse-face 'highlight
3432 'rear-nonsticky org-nonsticky-props
3433 'keymap org-mouse-map
3434 'help-echo "Radio target link"
3435 'org-linked-text t))
3436 t)))))
3438 (defun org-update-radio-target-regexp ()
3439 "Find all radio targets in this file and update the regular expression."
3440 (interactive)
3441 (when (memq 'radio org-activate-links)
3442 (setq org-target-link-regexp
3443 (org-make-target-link-regexp (org-all-targets 'radio)))
3444 (org-restart-font-lock)))
3446 (defun org-hide-wide-columns (limit)
3447 (let (s e)
3448 (setq s (text-property-any (point) (or limit (point-max))
3449 'org-cwidth t))
3450 (when s
3451 (setq e (next-single-property-change s 'org-cwidth))
3452 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3453 (goto-char e)
3454 t)))
3456 (defvar org-latex-and-specials-regexp nil
3457 "Regular expression for highlighting export special stuff.")
3458 (defvar org-match-substring-regexp)
3459 (defvar org-match-substring-with-braces-regexp)
3460 (defvar org-export-html-special-string-regexps)
3462 (defun org-compute-latex-and-specials-regexp ()
3463 "Compute regular expression for stuff treated specially by exporters."
3464 (if (not org-highlight-latex-fragments-and-specials)
3465 (org-set-local 'org-latex-and-specials-regexp nil)
3466 (require 'org-exp)
3467 (let*
3468 ((matchers (plist-get org-format-latex-options :matchers))
3469 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3470 org-latex-regexps)))
3471 (options (org-combine-plists (org-default-export-plist)
3472 (org-infile-export-plist)))
3473 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3474 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3475 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3476 (org-export-html-expand (plist-get options :expand-quoted-html))
3477 (org-export-with-special-strings (plist-get options :special-strings))
3478 (re-sub
3479 (cond
3480 ((equal org-export-with-sub-superscripts '{})
3481 (list org-match-substring-with-braces-regexp))
3482 (org-export-with-sub-superscripts
3483 (list org-match-substring-regexp))
3484 (t nil)))
3485 (re-latex
3486 (if org-export-with-LaTeX-fragments
3487 (mapcar (lambda (x) (nth 1 x)) latexs)))
3488 (re-macros
3489 (if org-export-with-TeX-macros
3490 (list (concat "\\\\"
3491 (regexp-opt
3492 (append (mapcar 'car org-html-entities)
3493 (if (boundp 'org-latex-entities)
3494 org-latex-entities nil))
3495 'words))) ; FIXME
3497 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3498 (re-special (if org-export-with-special-strings
3499 (mapcar (lambda (x) (car x))
3500 org-export-html-special-string-regexps)))
3501 (re-rest
3502 (delq nil
3503 (list
3504 (if org-export-html-expand "@<[^>\n]+>")
3505 ))))
3506 (org-set-local
3507 'org-latex-and-specials-regexp
3508 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3509 re-rest) "\\|")))))
3511 (defun org-do-latex-and-special-faces (limit)
3512 "Run through the buffer and add overlays to links."
3513 (when org-latex-and-specials-regexp
3514 (let (rtn d)
3515 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3516 limit t))
3517 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3518 'face))
3519 '(org-code org-verbatim underline)))
3520 (progn
3521 (setq rtn t
3522 d (cond ((member (char-after (1+ (match-beginning 0)))
3523 '(?_ ?^)) 1)
3524 (t 0)))
3525 (font-lock-prepend-text-property
3526 (+ d (match-beginning 0)) (match-end 0)
3527 'face 'org-latex-and-export-specials)
3528 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3529 '(font-lock-multiline t)))))
3530 rtn)))
3532 (defun org-restart-font-lock ()
3533 "Restart font-lock-mode, to force refontification."
3534 (when (and (boundp 'font-lock-mode) font-lock-mode)
3535 (font-lock-mode -1)
3536 (font-lock-mode 1)))
3538 (defun org-all-targets (&optional radio)
3539 "Return a list of all targets in this file.
3540 With optional argument RADIO, only find radio targets."
3541 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3542 rtn)
3543 (save-excursion
3544 (goto-char (point-min))
3545 (while (re-search-forward re nil t)
3546 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3547 rtn)))
3549 (defun org-make-target-link-regexp (targets)
3550 "Make regular expression matching all strings in TARGETS.
3551 The regular expression finds the targets also if there is a line break
3552 between words."
3553 (and targets
3554 (concat
3555 "\\<\\("
3556 (mapconcat
3557 (lambda (x)
3558 (while (string-match " +" x)
3559 (setq x (replace-match "\\s-+" t t x)))
3561 targets
3562 "\\|")
3563 "\\)\\>")))
3565 (defun org-activate-tags (limit)
3566 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3567 (progn
3568 (add-text-properties (match-beginning 1) (match-end 1)
3569 (list 'mouse-face 'highlight
3570 'rear-nonsticky org-nonsticky-props
3571 'keymap org-mouse-map))
3572 t)))
3574 (defun org-outline-level ()
3575 (save-excursion
3576 (looking-at outline-regexp)
3577 (if (match-beginning 1)
3578 (+ (org-get-string-indentation (match-string 1)) 1000)
3579 (1- (- (match-end 0) (match-beginning 0))))))
3581 (defvar org-font-lock-keywords nil)
3583 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\(\\S-.*\\)")
3584 "Regular expression matching a property line.")
3586 (defun org-set-font-lock-defaults ()
3587 (let* ((em org-fontify-emphasized-text)
3588 (lk org-activate-links)
3589 (org-font-lock-extra-keywords
3590 (list
3591 ;; Headlines
3592 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3593 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3594 ;; Table lines
3595 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3596 (1 'org-table t))
3597 ;; Table internals
3598 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3599 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3600 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3601 ;; Drawers
3602 (list org-drawer-regexp '(0 'org-special-keyword t))
3603 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3604 ;; Properties
3605 (list org-property-re
3606 '(1 'org-special-keyword t)
3607 '(3 'org-property-value t))
3608 (if org-format-transports-properties-p
3609 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3610 ;; Links
3611 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3612 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3613 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3614 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3615 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3616 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3617 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3618 '(org-hide-wide-columns (0 nil append))
3619 ;; TODO lines
3620 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3621 '(1 (org-get-todo-face 1) t))
3622 ;; DONE
3623 (if org-fontify-done-headline
3624 (list (concat "^[*]+ +\\<\\("
3625 (mapconcat 'regexp-quote org-done-keywords "\\|")
3626 "\\)\\(.*\\)")
3627 '(2 'org-headline-done t))
3628 nil)
3629 ;; Priorities
3630 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3631 ;; Special keywords
3632 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3633 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3634 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3635 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3636 ;; Emphasis
3637 (if em
3638 (if (featurep 'xemacs)
3639 '(org-do-emphasis-faces (0 nil append))
3640 '(org-do-emphasis-faces)))
3641 ;; Checkboxes
3642 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3643 2 'bold prepend)
3644 (if org-provide-checkbox-statistics
3645 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3646 (0 (org-get-checkbox-statistics-face) t)))
3647 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3648 '(1 'org-archived prepend))
3649 ;; Specials
3650 '(org-do-latex-and-special-faces)
3651 ;; Code
3652 '(org-activate-code (1 'org-code t))
3653 ;; COMMENT
3654 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3655 "\\|" org-quote-string "\\)\\>")
3656 '(1 'org-special-keyword t))
3657 '("^#.*" (0 'font-lock-comment-face t))
3659 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3660 ;; Now set the full font-lock-keywords
3661 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3662 (org-set-local 'font-lock-defaults
3663 '(org-font-lock-keywords t nil nil backward-paragraph))
3664 (kill-local-variable 'font-lock-keywords) nil))
3666 (defvar org-m nil)
3667 (defvar org-l nil)
3668 (defvar org-f nil)
3669 (defun org-get-level-face (n)
3670 "Get the right face for match N in font-lock matching of healdines."
3671 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3672 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3673 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3674 (cond
3675 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3676 ((eq n 2) org-f)
3677 (t (if org-level-color-stars-only nil org-f))))
3679 (defun org-get-todo-face (kwd)
3680 "Get the right face for a TODO keyword KWD.
3681 If KWD is a number, get the corresponding match group."
3682 (if (numberp kwd) (setq kwd (match-string kwd)))
3683 (or (cdr (assoc kwd org-todo-keyword-faces))
3684 (and (member kwd org-done-keywords) 'org-done)
3685 'org-todo))
3687 (defun org-unfontify-region (beg end &optional maybe_loudly)
3688 "Remove fontification and activation overlays from links."
3689 (font-lock-default-unfontify-region beg end)
3690 (let* ((buffer-undo-list t)
3691 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3692 (inhibit-modification-hooks t)
3693 deactivate-mark buffer-file-name buffer-file-truename)
3694 (remove-text-properties beg end
3695 '(mouse-face t keymap t org-linked-text t
3696 invisible t intangible t))))
3698 ;;;; Visibility cycling, including org-goto and indirect buffer
3700 ;;; Cycling
3702 (defvar org-cycle-global-status nil)
3703 (make-variable-buffer-local 'org-cycle-global-status)
3704 (defvar org-cycle-subtree-status nil)
3705 (make-variable-buffer-local 'org-cycle-subtree-status)
3707 ;;;###autoload
3708 (defun org-cycle (&optional arg)
3709 "Visibility cycling for Org-mode.
3711 - When this function is called with a prefix argument, rotate the entire
3712 buffer through 3 states (global cycling)
3713 1. OVERVIEW: Show only top-level headlines.
3714 2. CONTENTS: Show all headlines of all levels, but no body text.
3715 3. SHOW ALL: Show everything.
3717 - When point is at the beginning of a headline, rotate the subtree started
3718 by this line through 3 different states (local cycling)
3719 1. FOLDED: Only the main headline is shown.
3720 2. CHILDREN: The main headline and the direct children are shown.
3721 From this state, you can move to one of the children
3722 and zoom in further.
3723 3. SUBTREE: Show the entire subtree, including body text.
3725 - When there is a numeric prefix, go up to a heading with level ARG, do
3726 a `show-subtree' and return to the previous cursor position. If ARG
3727 is negative, go up that many levels.
3729 - When point is not at the beginning of a headline, execute
3730 `indent-relative', like TAB normally does. See the option
3731 `org-cycle-emulate-tab' for details.
3733 - Special case: if point is at the beginning of the buffer and there is
3734 no headline in line 1, this function will act as if called with prefix arg.
3735 But only if also the variable `org-cycle-global-at-bob' is t."
3736 (interactive "P")
3737 (org-load-modules-maybe)
3738 (let* ((outline-regexp
3739 (if (and (org-mode-p) org-cycle-include-plain-lists)
3740 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3741 outline-regexp))
3742 (bob-special (and org-cycle-global-at-bob (bobp)
3743 (not (looking-at outline-regexp))))
3744 (org-cycle-hook
3745 (if bob-special
3746 (delq 'org-optimize-window-after-visibility-change
3747 (copy-sequence org-cycle-hook))
3748 org-cycle-hook))
3749 (pos (point)))
3751 (if (or bob-special (equal arg '(4)))
3752 ;; special case: use global cycling
3753 (setq arg t))
3755 (cond
3757 ((org-at-table-p 'any)
3758 ;; Enter the table or move to the next field in the table
3759 (or (org-table-recognize-table.el)
3760 (progn
3761 (if arg (org-table-edit-field t)
3762 (org-table-justify-field-maybe)
3763 (call-interactively 'org-table-next-field)))))
3765 ((eq arg t) ;; Global cycling
3767 (cond
3768 ((and (eq last-command this-command)
3769 (eq org-cycle-global-status 'overview))
3770 ;; We just created the overview - now do table of contents
3771 ;; This can be slow in very large buffers, so indicate action
3772 (message "CONTENTS...")
3773 (org-content)
3774 (message "CONTENTS...done")
3775 (setq org-cycle-global-status 'contents)
3776 (run-hook-with-args 'org-cycle-hook 'contents))
3778 ((and (eq last-command this-command)
3779 (eq org-cycle-global-status 'contents))
3780 ;; We just showed the table of contents - now show everything
3781 (show-all)
3782 (message "SHOW ALL")
3783 (setq org-cycle-global-status 'all)
3784 (run-hook-with-args 'org-cycle-hook 'all))
3787 ;; Default action: go to overview
3788 (org-overview)
3789 (message "OVERVIEW")
3790 (setq org-cycle-global-status 'overview)
3791 (run-hook-with-args 'org-cycle-hook 'overview))))
3793 ((and org-drawers org-drawer-regexp
3794 (save-excursion
3795 (beginning-of-line 1)
3796 (looking-at org-drawer-regexp)))
3797 ;; Toggle block visibility
3798 (org-flag-drawer
3799 (not (get-char-property (match-end 0) 'invisible))))
3801 ((integerp arg)
3802 ;; Show-subtree, ARG levels up from here.
3803 (save-excursion
3804 (org-back-to-heading)
3805 (outline-up-heading (if (< arg 0) (- arg)
3806 (- (funcall outline-level) arg)))
3807 (org-show-subtree)))
3809 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3810 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3811 ;; At a heading: rotate between three different views
3812 (org-back-to-heading)
3813 (let ((goal-column 0) eoh eol eos)
3814 ;; First, some boundaries
3815 (save-excursion
3816 (org-back-to-heading)
3817 (save-excursion
3818 (beginning-of-line 2)
3819 (while (and (not (eobp)) ;; this is like `next-line'
3820 (get-char-property (1- (point)) 'invisible))
3821 (beginning-of-line 2)) (setq eol (point)))
3822 (outline-end-of-heading) (setq eoh (point))
3823 (org-end-of-subtree t)
3824 (unless (eobp)
3825 (skip-chars-forward " \t\n")
3826 (beginning-of-line 1) ; in case this is an item
3828 (setq eos (1- (point))))
3829 ;; Find out what to do next and set `this-command'
3830 (cond
3831 ((= eos eoh)
3832 ;; Nothing is hidden behind this heading
3833 (message "EMPTY ENTRY")
3834 (setq org-cycle-subtree-status nil)
3835 (save-excursion
3836 (goto-char eos)
3837 (outline-next-heading)
3838 (if (org-invisible-p) (org-flag-heading nil))))
3839 ((or (>= eol eos)
3840 (not (string-match "\\S-" (buffer-substring eol eos))))
3841 ;; Entire subtree is hidden in one line: open it
3842 (org-show-entry)
3843 (show-children)
3844 (message "CHILDREN")
3845 (save-excursion
3846 (goto-char eos)
3847 (outline-next-heading)
3848 (if (org-invisible-p) (org-flag-heading nil)))
3849 (setq org-cycle-subtree-status 'children)
3850 (run-hook-with-args 'org-cycle-hook 'children))
3851 ((and (eq last-command this-command)
3852 (eq org-cycle-subtree-status 'children))
3853 ;; We just showed the children, now show everything.
3854 (org-show-subtree)
3855 (message "SUBTREE")
3856 (setq org-cycle-subtree-status 'subtree)
3857 (run-hook-with-args 'org-cycle-hook 'subtree))
3859 ;; Default action: hide the subtree.
3860 (hide-subtree)
3861 (message "FOLDED")
3862 (setq org-cycle-subtree-status 'folded)
3863 (run-hook-with-args 'org-cycle-hook 'folded)))))
3865 ;; TAB emulation
3866 (buffer-read-only (org-back-to-heading))
3868 ((org-try-cdlatex-tab))
3870 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
3871 (or (not (bolp))
3872 (not (looking-at outline-regexp))))
3873 (call-interactively (global-key-binding "\t")))
3875 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3876 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3877 (or (and (eq org-cycle-emulate-tab 'white)
3878 (= (match-end 0) (point-at-eol)))
3879 (and (eq org-cycle-emulate-tab 'whitestart)
3880 (>= (match-end 0) pos))))
3882 (eq org-cycle-emulate-tab t))
3883 (call-interactively (global-key-binding "\t")))
3885 (t (save-excursion
3886 (org-back-to-heading)
3887 (org-cycle))))))
3889 ;;;###autoload
3890 (defun org-global-cycle (&optional arg)
3891 "Cycle the global visibility. For details see `org-cycle'."
3892 (interactive "P")
3893 (let ((org-cycle-include-plain-lists
3894 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3895 (if (integerp arg)
3896 (progn
3897 (show-all)
3898 (hide-sublevels arg)
3899 (setq org-cycle-global-status 'contents))
3900 (org-cycle '(4)))))
3902 (defun org-overview ()
3903 "Switch to overview mode, shoing only top-level headlines.
3904 Really, this shows all headlines with level equal or greater than the level
3905 of the first headline in the buffer. This is important, because if the
3906 first headline is not level one, then (hide-sublevels 1) gives confusing
3907 results."
3908 (interactive)
3909 (let ((level (save-excursion
3910 (goto-char (point-min))
3911 (if (re-search-forward (concat "^" outline-regexp) nil t)
3912 (progn
3913 (goto-char (match-beginning 0))
3914 (funcall outline-level))))))
3915 (and level (hide-sublevels level))))
3917 (defun org-content (&optional arg)
3918 "Show all headlines in the buffer, like a table of contents.
3919 With numerical argument N, show content up to level N."
3920 (interactive "P")
3921 (save-excursion
3922 ;; Visit all headings and show their offspring
3923 (and (integerp arg) (org-overview))
3924 (goto-char (point-max))
3925 (catch 'exit
3926 (while (and (progn (condition-case nil
3927 (outline-previous-visible-heading 1)
3928 (error (goto-char (point-min))))
3930 (looking-at outline-regexp))
3931 (if (integerp arg)
3932 (show-children (1- arg))
3933 (show-branches))
3934 (if (bobp) (throw 'exit nil))))))
3937 (defun org-optimize-window-after-visibility-change (state)
3938 "Adjust the window after a change in outline visibility.
3939 This function is the default value of the hook `org-cycle-hook'."
3940 (when (get-buffer-window (current-buffer))
3941 (cond
3942 ; ((eq state 'overview) (org-first-headline-recenter 1))
3943 ; ((eq state 'overview) (org-beginning-of-line))
3944 ((eq state 'content) nil)
3945 ((eq state 'all) nil)
3946 ((eq state 'folded) nil)
3947 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3948 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3950 (defun org-compact-display-after-subtree-move ()
3951 (let (beg end)
3952 (save-excursion
3953 (if (org-up-heading-safe)
3954 (progn
3955 (hide-subtree)
3956 (show-entry)
3957 (show-children)
3958 (org-cycle-show-empty-lines 'children)
3959 (org-cycle-hide-drawers 'children))
3960 (org-overview)))))
3962 (defun org-cycle-show-empty-lines (state)
3963 "Show empty lines above all visible headlines.
3964 The region to be covered depends on STATE when called through
3965 `org-cycle-hook'. Lisp program can use t for STATE to get the
3966 entire buffer covered. Note that an empty line is only shown if there
3967 are at least `org-cycle-separator-lines' empty lines before the headeline."
3968 (when (> org-cycle-separator-lines 0)
3969 (save-excursion
3970 (let* ((n org-cycle-separator-lines)
3971 (re (cond
3972 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
3973 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
3974 (t (let ((ns (number-to-string (- n 2))))
3975 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
3976 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
3977 beg end)
3978 (cond
3979 ((memq state '(overview contents t))
3980 (setq beg (point-min) end (point-max)))
3981 ((memq state '(children folded))
3982 (setq beg (point) end (progn (org-end-of-subtree t t)
3983 (beginning-of-line 2)
3984 (point)))))
3985 (when beg
3986 (goto-char beg)
3987 (while (re-search-forward re end t)
3988 (if (not (get-char-property (match-end 1) 'invisible))
3989 (outline-flag-region
3990 (match-beginning 1) (match-end 1) nil)))))))
3991 ;; Never hide empty lines at the end of the file.
3992 (save-excursion
3993 (goto-char (point-max))
3994 (outline-previous-heading)
3995 (outline-end-of-heading)
3996 (if (and (looking-at "[ \t\n]+")
3997 (= (match-end 0) (point-max)))
3998 (outline-flag-region (point) (match-end 0) nil))))
4000 (defun org-cycle-hide-drawers (state)
4001 "Re-hide all drawers after a visibility state change."
4002 (when (and (org-mode-p)
4003 (not (memq state '(overview folded))))
4004 (save-excursion
4005 (let* ((globalp (memq state '(contents all)))
4006 (beg (if globalp (point-min) (point)))
4007 (end (if globalp (point-max) (org-end-of-subtree t))))
4008 (goto-char beg)
4009 (while (re-search-forward org-drawer-regexp end t)
4010 (org-flag-drawer t))))))
4012 (defun org-flag-drawer (flag)
4013 (save-excursion
4014 (beginning-of-line 1)
4015 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4016 (let ((b (match-end 0))
4017 (outline-regexp org-outline-regexp))
4018 (if (re-search-forward
4019 "^[ \t]*:END:"
4020 (save-excursion (outline-next-heading) (point)) t)
4021 (outline-flag-region b (point-at-eol) flag)
4022 (error ":END: line missing"))))))
4026 (defun org-subtree-end-visible-p ()
4027 "Is the end of the current subtree visible?"
4028 (pos-visible-in-window-p
4029 (save-excursion (org-end-of-subtree t) (point))))
4031 (defun org-first-headline-recenter (&optional N)
4032 "Move cursor to the first headline and recenter the headline.
4033 Optional argument N means, put the headline into the Nth line of the window."
4034 (goto-char (point-min))
4035 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4036 (beginning-of-line)
4037 (recenter (prefix-numeric-value N))))
4039 ;;; Org-goto
4041 (defvar org-goto-window-configuration nil)
4042 (defvar org-goto-marker nil)
4043 (defvar org-goto-map
4044 (let ((map (make-sparse-keymap)))
4045 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4046 (while (setq cmd (pop cmds))
4047 (substitute-key-definition cmd cmd map global-map)))
4048 (suppress-keymap map)
4049 (org-defkey map "\C-m" 'org-goto-ret)
4050 (org-defkey map [(return)] 'org-goto-ret)
4051 (org-defkey map [(left)] 'org-goto-left)
4052 (org-defkey map [(right)] 'org-goto-right)
4053 (org-defkey map [(control ?g)] 'org-goto-quit)
4054 (org-defkey map "\C-i" 'org-cycle)
4055 (org-defkey map [(tab)] 'org-cycle)
4056 (org-defkey map [(down)] 'outline-next-visible-heading)
4057 (org-defkey map [(up)] 'outline-previous-visible-heading)
4058 (if org-goto-auto-isearch
4059 (if (fboundp 'define-key-after)
4060 (define-key-after map [t] 'org-goto-local-auto-isearch)
4061 nil)
4062 (org-defkey map "q" 'org-goto-quit)
4063 (org-defkey map "n" 'outline-next-visible-heading)
4064 (org-defkey map "p" 'outline-previous-visible-heading)
4065 (org-defkey map "f" 'outline-forward-same-level)
4066 (org-defkey map "b" 'outline-backward-same-level)
4067 (org-defkey map "u" 'outline-up-heading))
4068 (org-defkey map "/" 'org-occur)
4069 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4070 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4071 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4072 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4073 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4074 map))
4076 (defconst org-goto-help
4077 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4078 RET=jump to location [Q]uit and return to previous location
4079 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4081 (defvar org-goto-start-pos) ; dynamically scoped parameter
4083 (defun org-goto (&optional alternative-interface)
4084 "Look up a different location in the current file, keeping current visibility.
4086 When you want look-up or go to a different location in a document, the
4087 fastest way is often to fold the entire buffer and then dive into the tree.
4088 This method has the disadvantage, that the previous location will be folded,
4089 which may not be what you want.
4091 This command works around this by showing a copy of the current buffer
4092 in an indirect buffer, in overview mode. You can dive into the tree in
4093 that copy, use org-occur and incremental search to find a location.
4094 When pressing RET or `Q', the command returns to the original buffer in
4095 which the visibility is still unchanged. After RET is will also jump to
4096 the location selected in the indirect buffer and expose the
4097 the headline hierarchy above."
4098 (interactive "P")
4099 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4100 (org-refile-use-outline-path t)
4101 (interface
4102 (if (not alternative-interface)
4103 org-goto-interface
4104 (if (eq org-goto-interface 'outline)
4105 'outline-path-completion
4106 'outline)))
4107 (org-goto-start-pos (point))
4108 (selected-point
4109 (if (eq interface 'outline)
4110 (car (org-get-location (current-buffer) org-goto-help))
4111 (nth 3 (org-refile-get-location "Goto: ")))))
4112 (if selected-point
4113 (progn
4114 (org-mark-ring-push org-goto-start-pos)
4115 (goto-char selected-point)
4116 (if (or (org-invisible-p) (org-invisible-p2))
4117 (org-show-context 'org-goto)))
4118 (message "Quit"))))
4120 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4121 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4122 (defvar org-goto-local-auto-isearch-map) ; defined below
4124 (defun org-get-location (buf help)
4125 "Let the user select a location in the Org-mode buffer BUF.
4126 This function uses a recursive edit. It returns the selected position
4127 or nil."
4128 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4129 (isearch-hide-immediately nil)
4130 (isearch-search-fun-function
4131 (lambda () 'org-goto-local-search-forward-headings))
4132 (org-goto-selected-point org-goto-exit-command))
4133 (save-excursion
4134 (save-window-excursion
4135 (delete-other-windows)
4136 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4137 (switch-to-buffer
4138 (condition-case nil
4139 (make-indirect-buffer (current-buffer) "*org-goto*")
4140 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4141 (with-output-to-temp-buffer "*Help*"
4142 (princ help))
4143 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4144 (setq buffer-read-only nil)
4145 (let ((org-startup-truncated t)
4146 (org-startup-folded nil)
4147 (org-startup-align-all-tables nil))
4148 (org-mode)
4149 (org-overview))
4150 (setq buffer-read-only t)
4151 (if (and (boundp 'org-goto-start-pos)
4152 (integer-or-marker-p org-goto-start-pos))
4153 (let ((org-show-hierarchy-above t)
4154 (org-show-siblings t)
4155 (org-show-following-heading t))
4156 (goto-char org-goto-start-pos)
4157 (and (org-invisible-p) (org-show-context)))
4158 (goto-char (point-min)))
4159 (org-beginning-of-line)
4160 (message "Select location and press RET")
4161 (use-local-map org-goto-map)
4162 (recursive-edit)
4164 (kill-buffer "*org-goto*")
4165 (cons org-goto-selected-point org-goto-exit-command)))
4167 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4168 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4169 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4170 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4172 (defun org-goto-local-search-forward-headings (string bound noerror)
4173 "Search and make sure that anu matches are in headlines."
4174 (catch 'return
4175 (while (search-forward string bound noerror)
4176 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4177 (and (member :headline context)
4178 (not (member :tags context))))
4179 (throw 'return (point))))))
4181 (defun org-goto-local-auto-isearch ()
4182 "Start isearch."
4183 (interactive)
4184 (goto-char (point-min))
4185 (let ((keys (this-command-keys)))
4186 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4187 (isearch-mode t)
4188 (isearch-process-search-char (string-to-char keys)))))
4190 (defun org-goto-ret (&optional arg)
4191 "Finish `org-goto' by going to the new location."
4192 (interactive "P")
4193 (setq org-goto-selected-point (point)
4194 org-goto-exit-command 'return)
4195 (throw 'exit nil))
4197 (defun org-goto-left ()
4198 "Finish `org-goto' by going to the new location."
4199 (interactive)
4200 (if (org-on-heading-p)
4201 (progn
4202 (beginning-of-line 1)
4203 (setq org-goto-selected-point (point)
4204 org-goto-exit-command 'left)
4205 (throw 'exit nil))
4206 (error "Not on a heading")))
4208 (defun org-goto-right ()
4209 "Finish `org-goto' by going to the new location."
4210 (interactive)
4211 (if (org-on-heading-p)
4212 (progn
4213 (setq org-goto-selected-point (point)
4214 org-goto-exit-command 'right)
4215 (throw 'exit nil))
4216 (error "Not on a heading")))
4218 (defun org-goto-quit ()
4219 "Finish `org-goto' without cursor motion."
4220 (interactive)
4221 (setq org-goto-selected-point nil)
4222 (setq org-goto-exit-command 'quit)
4223 (throw 'exit nil))
4225 ;;; Indirect buffer display of subtrees
4227 (defvar org-indirect-dedicated-frame nil
4228 "This is the frame being used for indirect tree display.")
4229 (defvar org-last-indirect-buffer nil)
4231 (defun org-tree-to-indirect-buffer (&optional arg)
4232 "Create indirect buffer and narrow it to current subtree.
4233 With numerical prefix ARG, go up to this level and then take that tree.
4234 If ARG is negative, go up that many levels.
4235 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4236 indirect buffer previously made with this command, to avoid proliferation of
4237 indirect buffers. However, when you call the command with a `C-u' prefix, or
4238 when `org-indirect-buffer-display' is `new-frame', the last buffer
4239 is kept so that you can work with several indirect buffers at the same time.
4240 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4241 requests that a new frame be made for the new buffer, so that the dedicated
4242 frame is not changed."
4243 (interactive "P")
4244 (let ((cbuf (current-buffer))
4245 (cwin (selected-window))
4246 (pos (point))
4247 beg end level heading ibuf)
4248 (save-excursion
4249 (org-back-to-heading t)
4250 (when (numberp arg)
4251 (setq level (org-outline-level))
4252 (if (< arg 0) (setq arg (+ level arg)))
4253 (while (> (setq level (org-outline-level)) arg)
4254 (outline-up-heading 1 t)))
4255 (setq beg (point)
4256 heading (org-get-heading))
4257 (org-end-of-subtree t) (setq end (point)))
4258 (if (and (buffer-live-p org-last-indirect-buffer)
4259 (not (eq org-indirect-buffer-display 'new-frame))
4260 (not arg))
4261 (kill-buffer org-last-indirect-buffer))
4262 (setq ibuf (org-get-indirect-buffer cbuf)
4263 org-last-indirect-buffer ibuf)
4264 (cond
4265 ((or (eq org-indirect-buffer-display 'new-frame)
4266 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4267 (select-frame (make-frame))
4268 (delete-other-windows)
4269 (switch-to-buffer ibuf)
4270 (org-set-frame-title heading))
4271 ((eq org-indirect-buffer-display 'dedicated-frame)
4272 (raise-frame
4273 (select-frame (or (and org-indirect-dedicated-frame
4274 (frame-live-p org-indirect-dedicated-frame)
4275 org-indirect-dedicated-frame)
4276 (setq org-indirect-dedicated-frame (make-frame)))))
4277 (delete-other-windows)
4278 (switch-to-buffer ibuf)
4279 (org-set-frame-title (concat "Indirect: " heading)))
4280 ((eq org-indirect-buffer-display 'current-window)
4281 (switch-to-buffer ibuf))
4282 ((eq org-indirect-buffer-display 'other-window)
4283 (pop-to-buffer ibuf))
4284 (t (error "Invalid value.")))
4285 (if (featurep 'xemacs)
4286 (save-excursion (org-mode) (turn-on-font-lock)))
4287 (narrow-to-region beg end)
4288 (show-all)
4289 (goto-char pos)
4290 (and (window-live-p cwin) (select-window cwin))))
4292 (defun org-get-indirect-buffer (&optional buffer)
4293 (setq buffer (or buffer (current-buffer)))
4294 (let ((n 1) (base (buffer-name buffer)) bname)
4295 (while (buffer-live-p
4296 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4297 (setq n (1+ n)))
4298 (condition-case nil
4299 (make-indirect-buffer buffer bname 'clone)
4300 (error (make-indirect-buffer buffer bname)))))
4302 (defun org-set-frame-title (title)
4303 "Set the title of the current frame to the string TITLE."
4304 ;; FIXME: how to name a single frame in XEmacs???
4305 (unless (featurep 'xemacs)
4306 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4308 ;;;; Structure editing
4310 ;;; Inserting headlines
4312 (defun org-insert-heading (&optional force-heading)
4313 "Insert a new heading or item with same depth at point.
4314 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4315 If point is at the beginning of a headline, insert a sibling before the
4316 current headline. If point is not at the beginning, do not split the line,
4317 but create the new hedline after the current line."
4318 (interactive "P")
4319 (if (= (buffer-size) 0)
4320 (insert "\n* ")
4321 (when (or force-heading (not (org-insert-item)))
4322 (let* ((head (save-excursion
4323 (condition-case nil
4324 (progn
4325 (org-back-to-heading)
4326 (match-string 0))
4327 (error "*"))))
4328 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4329 pos)
4330 (cond
4331 ((and (org-on-heading-p) (bolp)
4332 (or (bobp)
4333 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4334 ;; insert before the current line
4335 (open-line (if blank 2 1)))
4336 ((and (bolp)
4337 (or (bobp)
4338 (save-excursion
4339 (backward-char 1) (not (org-invisible-p)))))
4340 ;; insert right here
4341 nil)
4343 ;; in the middle of the line
4344 (org-show-entry)
4345 (let ((split
4346 (org-get-alist-option org-M-RET-may-split-line 'headline))
4347 tags pos)
4348 (if (org-on-heading-p)
4349 (progn
4350 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4351 (setq tags (and (match-end 2) (match-string 2)))
4352 (and (match-end 1)
4353 (delete-region (match-beginning 1) (match-end 1)))
4354 (setq pos (point-at-bol))
4355 (or split (end-of-line 1))
4356 (delete-horizontal-space)
4357 (newline (if blank 2 1))
4358 (when tags
4359 (save-excursion
4360 (goto-char pos)
4361 (end-of-line 1)
4362 (insert " " tags)
4363 (org-set-tags nil 'align))))
4364 (or split (end-of-line 1))
4365 (newline (if blank 2 1))))))
4366 (insert head) (just-one-space)
4367 (setq pos (point))
4368 (end-of-line 1)
4369 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4370 (run-hooks 'org-insert-heading-hook)))))
4372 (defun org-get-heading (&optional no-tags)
4373 "Return the heading of the current entry, without the stars."
4374 (save-excursion
4375 (org-back-to-heading t)
4376 (if (looking-at
4377 (if no-tags
4378 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4379 "\\*+[ \t]+\\([^\r\n]*\\)"))
4380 (match-string 1) "")))
4382 (defun org-insert-heading-after-current ()
4383 "Insert a new heading with same level as current, after current subtree."
4384 (interactive)
4385 (org-back-to-heading)
4386 (org-insert-heading)
4387 (org-move-subtree-down)
4388 (end-of-line 1))
4390 (defun org-insert-todo-heading (arg)
4391 "Insert a new heading with the same level and TODO state as current heading.
4392 If the heading has no TODO state, or if the state is DONE, use the first
4393 state (TODO by default). Also with prefix arg, force first state."
4394 (interactive "P")
4395 (when (not (org-insert-item 'checkbox))
4396 (org-insert-heading)
4397 (save-excursion
4398 (org-back-to-heading)
4399 (outline-previous-heading)
4400 (looking-at org-todo-line-regexp))
4401 (if (or arg
4402 (not (match-beginning 2))
4403 (member (match-string 2) org-done-keywords))
4404 (insert (car org-todo-keywords-1) " ")
4405 (insert (match-string 2) " "))))
4407 (defun org-insert-subheading (arg)
4408 "Insert a new subheading and demote it.
4409 Works for outline headings and for plain lists alike."
4410 (interactive "P")
4411 (org-insert-heading arg)
4412 (cond
4413 ((org-on-heading-p) (org-do-demote))
4414 ((org-at-item-p) (org-indent-item 1))))
4416 (defun org-insert-todo-subheading (arg)
4417 "Insert a new subheading with TODO keyword or checkbox and demote it.
4418 Works for outline headings and for plain lists alike."
4419 (interactive "P")
4420 (org-insert-todo-heading arg)
4421 (cond
4422 ((org-on-heading-p) (org-do-demote))
4423 ((org-at-item-p) (org-indent-item 1))))
4425 ;;; Promotion and Demotion
4427 (defun org-promote-subtree ()
4428 "Promote the entire subtree.
4429 See also `org-promote'."
4430 (interactive)
4431 (save-excursion
4432 (org-map-tree 'org-promote))
4433 (org-fix-position-after-promote))
4435 (defun org-demote-subtree ()
4436 "Demote the entire subtree. See `org-demote'.
4437 See also `org-promote'."
4438 (interactive)
4439 (save-excursion
4440 (org-map-tree 'org-demote))
4441 (org-fix-position-after-promote))
4444 (defun org-do-promote ()
4445 "Promote the current heading higher up the tree.
4446 If the region is active in `transient-mark-mode', promote all headings
4447 in the region."
4448 (interactive)
4449 (save-excursion
4450 (if (org-region-active-p)
4451 (org-map-region 'org-promote (region-beginning) (region-end))
4452 (org-promote)))
4453 (org-fix-position-after-promote))
4455 (defun org-do-demote ()
4456 "Demote the current heading lower down the tree.
4457 If the region is active in `transient-mark-mode', demote all headings
4458 in the region."
4459 (interactive)
4460 (save-excursion
4461 (if (org-region-active-p)
4462 (org-map-region 'org-demote (region-beginning) (region-end))
4463 (org-demote)))
4464 (org-fix-position-after-promote))
4466 (defun org-fix-position-after-promote ()
4467 "Make sure that after pro/demotion cursor position is right."
4468 (let ((pos (point)))
4469 (when (save-excursion
4470 (beginning-of-line 1)
4471 (looking-at org-todo-line-regexp)
4472 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4473 (cond ((eobp) (insert " "))
4474 ((eolp) (insert " "))
4475 ((equal (char-after) ?\ ) (forward-char 1))))))
4477 (defun org-reduced-level (l)
4478 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4480 (defun org-get-valid-level (level &optional change)
4481 "Rectify a level change under the influence of `org-odd-levels-only'
4482 LEVEL is a current level, CHANGE is by how much the level should be
4483 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4484 even level numbers will become the next higher odd number."
4485 (if org-odd-levels-only
4486 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4487 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4488 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4489 (max 1 (+ level change))))
4491 (if (boundp 'define-obsolete-function-alias)
4492 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4493 (define-obsolete-function-alias 'org-get-legal-level
4494 'org-get-valid-level)
4495 (define-obsolete-function-alias 'org-get-legal-level
4496 'org-get-valid-level "23.1")))
4498 (defun org-promote ()
4499 "Promote the current heading higher up the tree.
4500 If the region is active in `transient-mark-mode', promote all headings
4501 in the region."
4502 (org-back-to-heading t)
4503 (let* ((level (save-match-data (funcall outline-level)))
4504 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4505 (diff (abs (- level (length up-head) -1))))
4506 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4507 (replace-match up-head nil t)
4508 ;; Fixup tag positioning
4509 (and org-auto-align-tags (org-set-tags nil t))
4510 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4512 (defun org-demote ()
4513 "Demote the current heading lower down the tree.
4514 If the region is active in `transient-mark-mode', demote all headings
4515 in the region."
4516 (org-back-to-heading t)
4517 (let* ((level (save-match-data (funcall outline-level)))
4518 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4519 (diff (abs (- level (length down-head) -1))))
4520 (replace-match down-head nil t)
4521 ;; Fixup tag positioning
4522 (and org-auto-align-tags (org-set-tags nil t))
4523 (if org-adapt-indentation (org-fixup-indentation diff))))
4525 (defun org-map-tree (fun)
4526 "Call FUN for every heading underneath the current one."
4527 (org-back-to-heading)
4528 (let ((level (funcall outline-level)))
4529 (save-excursion
4530 (funcall fun)
4531 (while (and (progn
4532 (outline-next-heading)
4533 (> (funcall outline-level) level))
4534 (not (eobp)))
4535 (funcall fun)))))
4537 (defun org-map-region (fun beg end)
4538 "Call FUN for every heading between BEG and END."
4539 (let ((org-ignore-region t))
4540 (save-excursion
4541 (setq end (copy-marker end))
4542 (goto-char beg)
4543 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4544 (< (point) end))
4545 (funcall fun))
4546 (while (and (progn
4547 (outline-next-heading)
4548 (< (point) end))
4549 (not (eobp)))
4550 (funcall fun)))))
4552 (defun org-fixup-indentation (diff)
4553 "Change the indentation in the current entry by DIFF
4554 However, if any line in the current entry has no indentation, or if it
4555 would end up with no indentation after the change, nothing at all is done."
4556 (save-excursion
4557 (let ((end (save-excursion (outline-next-heading)
4558 (point-marker)))
4559 (prohibit (if (> diff 0)
4560 "^\\S-"
4561 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4562 col)
4563 (unless (save-excursion (end-of-line 1)
4564 (re-search-forward prohibit end t))
4565 (while (and (< (point) end)
4566 (re-search-forward "^[ \t]+" end t))
4567 (goto-char (match-end 0))
4568 (setq col (current-column))
4569 (if (< diff 0) (replace-match ""))
4570 (indent-to (+ diff col))))
4571 (move-marker end nil))))
4573 (defun org-convert-to-odd-levels ()
4574 "Convert an org-mode file with all levels allowed to one with odd levels.
4575 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4576 level 5 etc."
4577 (interactive)
4578 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4579 (let ((org-odd-levels-only nil) n)
4580 (save-excursion
4581 (goto-char (point-min))
4582 (while (re-search-forward "^\\*\\*+ " nil t)
4583 (setq n (- (length (match-string 0)) 2))
4584 (while (>= (setq n (1- n)) 0)
4585 (org-demote))
4586 (end-of-line 1))))))
4589 (defun org-convert-to-oddeven-levels ()
4590 "Convert an org-mode file with only odd levels to one with odd and even levels.
4591 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4592 section with an even level, conversion would destroy the structure of the file. An error
4593 is signaled in this case."
4594 (interactive)
4595 (goto-char (point-min))
4596 ;; First check if there are no even levels
4597 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4598 (org-show-context t)
4599 (error "Not all levels are odd in this file. Conversion not possible."))
4600 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4601 (let ((org-odd-levels-only nil) n)
4602 (save-excursion
4603 (goto-char (point-min))
4604 (while (re-search-forward "^\\*\\*+ " nil t)
4605 (setq n (/ (1- (length (match-string 0))) 2))
4606 (while (>= (setq n (1- n)) 0)
4607 (org-promote))
4608 (end-of-line 1))))))
4610 (defun org-tr-level (n)
4611 "Make N odd if required."
4612 (if org-odd-levels-only (1+ (/ n 2)) n))
4614 ;;; Vertical tree motion, cutting and pasting of subtrees
4616 (defun org-move-subtree-up (&optional arg)
4617 "Move the current subtree up past ARG headlines of the same level."
4618 (interactive "p")
4619 (org-move-subtree-down (- (prefix-numeric-value arg))))
4621 (defun org-move-subtree-down (&optional arg)
4622 "Move the current subtree down past ARG headlines of the same level."
4623 (interactive "p")
4624 (setq arg (prefix-numeric-value arg))
4625 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4626 'outline-get-last-sibling))
4627 (ins-point (make-marker))
4628 (cnt (abs arg))
4629 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4630 ;; Select the tree
4631 (org-back-to-heading)
4632 (setq beg0 (point))
4633 (save-excursion
4634 (setq ne-beg (org-back-over-empty-lines))
4635 (setq beg (point)))
4636 (save-match-data
4637 (save-excursion (outline-end-of-heading)
4638 (setq folded (org-invisible-p)))
4639 (outline-end-of-subtree))
4640 (outline-next-heading)
4641 (setq ne-end (org-back-over-empty-lines))
4642 (setq end (point))
4643 (goto-char beg0)
4644 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4645 ;; include less whitespace
4646 (save-excursion
4647 (goto-char beg)
4648 (forward-line (- ne-beg ne-end))
4649 (setq beg (point))))
4650 ;; Find insertion point, with error handling
4651 (while (> cnt 0)
4652 (or (and (funcall movfunc) (looking-at outline-regexp))
4653 (progn (goto-char beg0)
4654 (error "Cannot move past superior level or buffer limit")))
4655 (setq cnt (1- cnt)))
4656 (if (> arg 0)
4657 ;; Moving forward - still need to move over subtree
4658 (progn (org-end-of-subtree t t)
4659 (save-excursion
4660 (org-back-over-empty-lines)
4661 (or (bolp) (newline)))))
4662 (setq ne-ins (org-back-over-empty-lines))
4663 (move-marker ins-point (point))
4664 (setq txt (buffer-substring beg end))
4665 (delete-region beg end)
4666 (outline-flag-region (1- beg) beg nil)
4667 (outline-flag-region (1- (point)) (point) nil)
4668 (insert txt)
4669 (or (bolp) (insert "\n"))
4670 (setq ins-end (point))
4671 (goto-char ins-point)
4672 (org-skip-whitespace)
4673 (when (and (< arg 0)
4674 (org-first-sibling-p)
4675 (> ne-ins ne-beg))
4676 ;; Move whitespace back to beginning
4677 (save-excursion
4678 (goto-char ins-end)
4679 (let ((kill-whole-line t))
4680 (kill-line (- ne-ins ne-beg)) (point)))
4681 (insert (make-string (- ne-ins ne-beg) ?\n)))
4682 (move-marker ins-point nil)
4683 (org-compact-display-after-subtree-move)
4684 (unless folded
4685 (org-show-entry)
4686 (show-children)
4687 (org-cycle-hide-drawers 'children))))
4689 (defvar org-subtree-clip ""
4690 "Clipboard for cut and paste of subtrees.
4691 This is actually only a copy of the kill, because we use the normal kill
4692 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4694 (defvar org-subtree-clip-folded nil
4695 "Was the last copied subtree folded?
4696 This is used to fold the tree back after pasting.")
4698 (defun org-cut-subtree (&optional n)
4699 "Cut the current subtree into the clipboard.
4700 With prefix arg N, cut this many sequential subtrees.
4701 This is a short-hand for marking the subtree and then cutting it."
4702 (interactive "p")
4703 (org-copy-subtree n 'cut))
4705 (defun org-copy-subtree (&optional n cut)
4706 "Cut the current subtree into the clipboard.
4707 With prefix arg N, cut this many sequential subtrees.
4708 This is a short-hand for marking the subtree and then copying it.
4709 If CUT is non-nil, actually cut the subtree."
4710 (interactive "p")
4711 (let (beg end folded (beg0 (point)))
4712 (if (interactive-p)
4713 (org-back-to-heading nil) ; take what looks like a subtree
4714 (org-back-to-heading t)) ; take what is really there
4715 (org-back-over-empty-lines)
4716 (setq beg (point))
4717 (skip-chars-forward " \t\r\n")
4718 (save-match-data
4719 (save-excursion (outline-end-of-heading)
4720 (setq folded (org-invisible-p)))
4721 (condition-case nil
4722 (outline-forward-same-level (1- n))
4723 (error nil))
4724 (org-end-of-subtree t t))
4725 (org-back-over-empty-lines)
4726 (setq end (point))
4727 (goto-char beg0)
4728 (when (> end beg)
4729 (setq org-subtree-clip-folded folded)
4730 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4731 (setq org-subtree-clip (current-kill 0))
4732 (message "%s: Subtree(s) with %d characters"
4733 (if cut "Cut" "Copied")
4734 (length org-subtree-clip)))))
4736 (defun org-paste-subtree (&optional level tree)
4737 "Paste the clipboard as a subtree, with modification of headline level.
4738 The entire subtree is promoted or demoted in order to match a new headline
4739 level. By default, the new level is derived from the visible headings
4740 before and after the insertion point, and taken to be the inferior headline
4741 level of the two. So if the previous visible heading is level 3 and the
4742 next is level 4 (or vice versa), level 4 will be used for insertion.
4743 This makes sure that the subtree remains an independent subtree and does
4744 not swallow low level entries.
4746 You can also force a different level, either by using a numeric prefix
4747 argument, or by inserting the heading marker by hand. For example, if the
4748 cursor is after \"*****\", then the tree will be shifted to level 5.
4750 If you want to insert the tree as is, just use \\[yank].
4752 If optional TREE is given, use this text instead of the kill ring."
4753 (interactive "P")
4754 (unless (org-kill-is-subtree-p tree)
4755 (error "%s"
4756 (substitute-command-keys
4757 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4758 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4759 (^re (concat "^\\(" outline-regexp "\\)"))
4760 (re (concat "\\(" outline-regexp "\\)"))
4761 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4763 (old-level (if (string-match ^re txt)
4764 (- (match-end 0) (match-beginning 0) 1)
4765 -1))
4766 (force-level (cond (level (prefix-numeric-value level))
4767 ((string-match
4768 ^re_ (buffer-substring (point-at-bol) (point)))
4769 (- (match-end 1) (match-beginning 1)))
4770 (t nil)))
4771 (previous-level (save-excursion
4772 (condition-case nil
4773 (progn
4774 (outline-previous-visible-heading 1)
4775 (if (looking-at re)
4776 (- (match-end 0) (match-beginning 0) 1)
4778 (error 1))))
4779 (next-level (save-excursion
4780 (condition-case nil
4781 (progn
4782 (or (looking-at outline-regexp)
4783 (outline-next-visible-heading 1))
4784 (if (looking-at re)
4785 (- (match-end 0) (match-beginning 0) 1)
4787 (error 1))))
4788 (new-level (or force-level (max previous-level next-level)))
4789 (shift (if (or (= old-level -1)
4790 (= new-level -1)
4791 (= old-level new-level))
4793 (- new-level old-level)))
4794 (delta (if (> shift 0) -1 1))
4795 (func (if (> shift 0) 'org-demote 'org-promote))
4796 (org-odd-levels-only nil)
4797 beg end)
4798 ;; Remove the forced level indicator
4799 (if force-level
4800 (delete-region (point-at-bol) (point)))
4801 ;; Paste
4802 (beginning-of-line 1)
4803 (org-back-over-empty-lines)
4804 (setq beg (point))
4805 (insert-before-markers txt)
4806 (unless (string-match "\n\\'" txt) (insert "\n"))
4807 (setq end (point))
4808 (goto-char beg)
4809 (skip-chars-forward " \t\n\r")
4810 (setq beg (point))
4811 ;; Shift if necessary
4812 (unless (= shift 0)
4813 (save-restriction
4814 (narrow-to-region beg end)
4815 (while (not (= shift 0))
4816 (org-map-region func (point-min) (point-max))
4817 (setq shift (+ delta shift)))
4818 (goto-char (point-min))))
4819 (when (interactive-p)
4820 (message "Clipboard pasted as level %d subtree" new-level))
4821 (if (and kill-ring
4822 (eq org-subtree-clip (current-kill 0))
4823 org-subtree-clip-folded)
4824 ;; The tree was folded before it was killed/copied
4825 (hide-subtree))))
4827 (defun org-kill-is-subtree-p (&optional txt)
4828 "Check if the current kill is an outline subtree, or a set of trees.
4829 Returns nil if kill does not start with a headline, or if the first
4830 headline level is not the largest headline level in the tree.
4831 So this will actually accept several entries of equal levels as well,
4832 which is OK for `org-paste-subtree'.
4833 If optional TXT is given, check this string instead of the current kill."
4834 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4835 (start-level (and kill
4836 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
4837 org-outline-regexp "\\)")
4838 kill)
4839 (- (match-end 2) (match-beginning 2) 1)))
4840 (re (concat "^" org-outline-regexp))
4841 (start (1+ (match-beginning 2))))
4842 (if (not start-level)
4843 (progn
4844 nil) ;; does not even start with a heading
4845 (catch 'exit
4846 (while (setq start (string-match re kill (1+ start)))
4847 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
4848 (throw 'exit nil)))
4849 t))))
4851 (defun org-narrow-to-subtree ()
4852 "Narrow buffer to the current subtree."
4853 (interactive)
4854 (save-excursion
4855 (save-match-data
4856 (narrow-to-region
4857 (progn (org-back-to-heading) (point))
4858 (progn (org-end-of-subtree t t) (point))))))
4861 ;;; Outline Sorting
4863 (defun org-sort (with-case)
4864 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
4865 Optional argument WITH-CASE means sort case-sensitively."
4866 (interactive "P")
4867 (if (org-at-table-p)
4868 (org-call-with-arg 'org-table-sort-lines with-case)
4869 (org-call-with-arg 'org-sort-entries-or-items with-case)))
4871 (defun org-sort-remove-invisible (s)
4872 (remove-text-properties 0 (length s) org-rm-props s)
4873 (while (string-match org-bracket-link-regexp s)
4874 (setq s (replace-match (if (match-end 2)
4875 (match-string 3 s)
4876 (match-string 1 s)) t t s)))
4879 (defvar org-priority-regexp) ; defined later in the file
4881 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
4882 "Sort entries on a certain level of an outline tree.
4883 If there is an active region, the entries in the region are sorted.
4884 Else, if the cursor is before the first entry, sort the top-level items.
4885 Else, the children of the entry at point are sorted.
4887 Sorting can be alphabetically, numerically, and by date/time as given by
4888 the first time stamp in the entry. The command prompts for the sorting
4889 type unless it has been given to the function through the SORTING-TYPE
4890 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
4891 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
4892 called with point at the beginning of the record. It must return either
4893 a string or a number that should serve as the sorting key for that record.
4895 Comparing entries ignores case by default. However, with an optional argument
4896 WITH-CASE, the sorting considers case as well."
4897 (interactive "P")
4898 (let ((case-func (if with-case 'identity 'downcase))
4899 start beg end stars re re2
4900 txt what tmp plain-list-p)
4901 ;; Find beginning and end of region to sort
4902 (cond
4903 ((org-region-active-p)
4904 ;; we will sort the region
4905 (setq end (region-end)
4906 what "region")
4907 (goto-char (region-beginning))
4908 (if (not (org-on-heading-p)) (outline-next-heading))
4909 (setq start (point)))
4910 ((org-at-item-p)
4911 ;; we will sort this plain list
4912 (org-beginning-of-item-list) (setq start (point))
4913 (org-end-of-item-list) (setq end (point))
4914 (goto-char start)
4915 (setq plain-list-p t
4916 what "plain list"))
4917 ((or (org-on-heading-p)
4918 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
4919 ;; we will sort the children of the current headline
4920 (org-back-to-heading)
4921 (setq start (point)
4922 end (progn (org-end-of-subtree t t)
4923 (org-back-over-empty-lines)
4924 (point))
4925 what "children")
4926 (goto-char start)
4927 (show-subtree)
4928 (outline-next-heading))
4930 ;; we will sort the top-level entries in this file
4931 (goto-char (point-min))
4932 (or (org-on-heading-p) (outline-next-heading))
4933 (setq start (point) end (point-max) what "top-level")
4934 (goto-char start)
4935 (show-all)))
4937 (setq beg (point))
4938 (if (>= beg end) (error "Nothing to sort"))
4940 (unless plain-list-p
4941 (looking-at "\\(\\*+\\)")
4942 (setq stars (match-string 1)
4943 re (concat "^" (regexp-quote stars) " +")
4944 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
4945 txt (buffer-substring beg end))
4946 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
4947 (if (and (not (equal stars "*")) (string-match re2 txt))
4948 (error "Region to sort contains a level above the first entry")))
4950 (unless sorting-type
4951 (message
4952 (if plain-list-p
4953 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
4954 "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:")
4955 what)
4956 (setq sorting-type (read-char-exclusive))
4958 (and (= (downcase sorting-type) ?f)
4959 (setq getkey-func
4960 (completing-read "Sort using function: "
4961 obarray 'fboundp t nil nil))
4962 (setq getkey-func (intern getkey-func)))
4964 (and (= (downcase sorting-type) ?r)
4965 (setq property
4966 (completing-read "Property: "
4967 (mapcar 'list (org-buffer-property-keys t))
4968 nil t))))
4970 (message "Sorting entries...")
4972 (save-restriction
4973 (narrow-to-region start end)
4975 (let ((dcst (downcase sorting-type))
4976 (now (current-time)))
4977 (sort-subr
4978 (/= dcst sorting-type)
4979 ;; This function moves to the beginning character of the "record" to
4980 ;; be sorted.
4981 (if plain-list-p
4982 (lambda nil
4983 (if (org-at-item-p) t (goto-char (point-max))))
4984 (lambda nil
4985 (if (re-search-forward re nil t)
4986 (goto-char (match-beginning 0))
4987 (goto-char (point-max)))))
4988 ;; This function moves to the last character of the "record" being
4989 ;; sorted.
4990 (if plain-list-p
4991 'org-end-of-item
4992 (lambda nil
4993 (save-match-data
4994 (condition-case nil
4995 (outline-forward-same-level 1)
4996 (error
4997 (goto-char (point-max)))))))
4999 ;; This function returns the value that gets sorted against.
5000 (if plain-list-p
5001 (lambda nil
5002 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5003 (cond
5004 ((= dcst ?n)
5005 (string-to-number (buffer-substring (match-end 0)
5006 (point-at-eol))))
5007 ((= dcst ?a)
5008 (buffer-substring (match-end 0) (point-at-eol)))
5009 ((= dcst ?t)
5010 (if (re-search-forward org-ts-regexp
5011 (point-at-eol) t)
5012 (org-time-string-to-time (match-string 0))
5013 now))
5014 ((= dcst ?f)
5015 (if getkey-func
5016 (progn
5017 (setq tmp (funcall getkey-func))
5018 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5019 tmp)
5020 (error "Invalid key function `%s'" getkey-func)))
5021 (t (error "Invalid sorting type `%c'" sorting-type)))))
5022 (lambda nil
5023 (cond
5024 ((= dcst ?n)
5025 (if (looking-at outline-regexp)
5026 (string-to-number (buffer-substring (match-end 0)
5027 (point-at-eol)))
5028 nil))
5029 ((= dcst ?a)
5030 (funcall case-func (buffer-substring (point-at-bol)
5031 (point-at-eol))))
5032 ((= dcst ?t)
5033 (if (re-search-forward org-ts-regexp
5034 (save-excursion
5035 (forward-line 2)
5036 (point)) t)
5037 (org-time-string-to-time (match-string 0))
5038 now))
5039 ((= dcst ?p)
5040 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5041 (string-to-char (match-string 2))
5042 org-default-priority))
5043 ((= dcst ?r)
5044 (or (org-entry-get nil property) ""))
5045 ((= dcst ?o)
5046 (if (looking-at org-complex-heading-regexp)
5047 (- 9999 (length (member (match-string 2)
5048 org-todo-keywords-1)))))
5049 ((= dcst ?f)
5050 (if getkey-func
5051 (progn
5052 (setq tmp (funcall getkey-func))
5053 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5054 tmp)
5055 (error "Invalid key function `%s'" getkey-func)))
5056 (t (error "Invalid sorting type `%c'" sorting-type)))))
5058 (cond
5059 ((= dcst ?a) 'string<)
5060 ((= dcst ?t) 'time-less-p)
5061 (t nil)))))
5062 (message "Sorting entries...done")))
5064 (defun org-do-sort (table what &optional with-case sorting-type)
5065 "Sort TABLE of WHAT according to SORTING-TYPE.
5066 The user will be prompted for the SORTING-TYPE if the call to this
5067 function does not specify it. WHAT is only for the prompt, to indicate
5068 what is being sorted. The sorting key will be extracted from
5069 the car of the elements of the table.
5070 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5071 (unless sorting-type
5072 (message
5073 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5074 what)
5075 (setq sorting-type (read-char-exclusive)))
5076 (let ((dcst (downcase sorting-type))
5077 extractfun comparefun)
5078 ;; Define the appropriate functions
5079 (cond
5080 ((= dcst ?n)
5081 (setq extractfun 'string-to-number
5082 comparefun (if (= dcst sorting-type) '< '>)))
5083 ((= dcst ?a)
5084 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5085 (lambda(x) (downcase (org-sort-remove-invisible x))))
5086 comparefun (if (= dcst sorting-type)
5087 'string<
5088 (lambda (a b) (and (not (string< a b))
5089 (not (string= a b)))))))
5090 ((= dcst ?t)
5091 (setq extractfun
5092 (lambda (x)
5093 (if (string-match org-ts-regexp x)
5094 (time-to-seconds
5095 (org-time-string-to-time (match-string 0 x)))
5097 comparefun (if (= dcst sorting-type) '< '>)))
5098 (t (error "Invalid sorting type `%c'" sorting-type)))
5100 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5101 table)
5102 (lambda (a b) (funcall comparefun (car a) (car b))))))
5104 ;;;; Plain list items, including checkboxes
5106 ;;; Plain list items
5108 (defun org-at-item-p ()
5109 "Is point in a line starting a hand-formatted item?"
5110 (let ((llt org-plain-list-ordered-item-terminator))
5111 (save-excursion
5112 (goto-char (point-at-bol))
5113 (looking-at
5114 (cond
5115 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5116 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5117 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5118 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5120 (defun org-in-item-p ()
5121 "It the cursor inside a plain list item.
5122 Does not have to be the first line."
5123 (save-excursion
5124 (condition-case nil
5125 (progn
5126 (org-beginning-of-item)
5127 (org-at-item-p)
5129 (error nil))))
5131 (defun org-insert-item (&optional checkbox)
5132 "Insert a new item at the current level.
5133 Return t when things worked, nil when we are not in an item."
5134 (when (save-excursion
5135 (condition-case nil
5136 (progn
5137 (org-beginning-of-item)
5138 (org-at-item-p)
5139 (if (org-invisible-p) (error "Invisible item"))
5141 (error nil)))
5142 (let* ((bul (match-string 0))
5143 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5144 (match-end 0)))
5145 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5146 pos)
5147 (cond
5148 ((and (org-at-item-p) (<= (point) eow))
5149 ;; before the bullet
5150 (beginning-of-line 1)
5151 (open-line (if blank 2 1)))
5152 ((<= (point) eow)
5153 (beginning-of-line 1))
5155 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5156 (end-of-line 1)
5157 (delete-horizontal-space))
5158 (newline (if blank 2 1))))
5159 (insert bul (if checkbox "[ ]" ""))
5160 (just-one-space)
5161 (setq pos (point))
5162 (end-of-line 1)
5163 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5164 (org-maybe-renumber-ordered-list)
5165 (and checkbox (org-update-checkbox-count-maybe))
5168 ;;; Checkboxes
5170 (defun org-at-item-checkbox-p ()
5171 "Is point at a line starting a plain-list item with a checklet?"
5172 (and (org-at-item-p)
5173 (save-excursion
5174 (goto-char (match-end 0))
5175 (skip-chars-forward " \t")
5176 (looking-at "\\[[- X]\\]"))))
5178 (defun org-toggle-checkbox (&optional arg)
5179 "Toggle the checkbox in the current line."
5180 (interactive "P")
5181 (catch 'exit
5182 (let (beg end status (firstnew 'unknown))
5183 (cond
5184 ((org-region-active-p)
5185 (setq beg (region-beginning) end (region-end)))
5186 ((org-on-heading-p)
5187 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5188 ((org-at-item-checkbox-p)
5189 (let ((pos (point)))
5190 (replace-match
5191 (cond (arg "[-]")
5192 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5193 (t "[ ]"))
5194 t t)
5195 (goto-char pos))
5196 (throw 'exit t))
5197 (t (error "Not at a checkbox or heading, and no active region")))
5198 (save-excursion
5199 (goto-char beg)
5200 (while (< (point) end)
5201 (when (org-at-item-checkbox-p)
5202 (setq status (equal (match-string 0) "[X]"))
5203 (when (eq firstnew 'unknown)
5204 (setq firstnew (not status)))
5205 (replace-match
5206 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5207 (beginning-of-line 2)))))
5208 (org-update-checkbox-count-maybe))
5210 (defun org-update-checkbox-count-maybe ()
5211 "Update checkbox statistics unless turned off by user."
5212 (when org-provide-checkbox-statistics
5213 (org-update-checkbox-count)))
5215 (defun org-update-checkbox-count (&optional all)
5216 "Update the checkbox statistics in the current section.
5217 This will find all statistic cookies like [57%] and [6/12] and update them
5218 with the current numbers. With optional prefix argument ALL, do this for
5219 the whole buffer."
5220 (interactive "P")
5221 (save-excursion
5222 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5223 (beg (condition-case nil
5224 (progn (outline-back-to-heading) (point))
5225 (error (point-min))))
5226 (end (move-marker (make-marker)
5227 (progn (outline-next-heading) (point))))
5228 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5229 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5230 (re-find (concat re "\\|" re-box))
5231 beg-cookie end-cookie is-percent c-on c-off lim
5232 eline curr-ind next-ind continue-from startsearch
5233 (cstat 0)
5235 (when all
5236 (goto-char (point-min))
5237 (outline-next-heading)
5238 (setq beg (point) end (point-max)))
5239 (goto-char end)
5240 ;; find each statistic cookie
5241 (while (re-search-backward re-find beg t)
5242 (setq beg-cookie (match-beginning 1)
5243 end-cookie (match-end 1)
5244 cstat (+ cstat (if end-cookie 1 0))
5245 startsearch (point-at-eol)
5246 continue-from (point-at-bol)
5247 is-percent (match-beginning 2)
5248 lim (cond
5249 ((org-on-heading-p) (outline-next-heading) (point))
5250 ((org-at-item-p) (org-end-of-item) (point))
5251 (t nil))
5252 c-on 0
5253 c-off 0)
5254 (when lim
5255 ;; find first checkbox for this cookie and gather
5256 ;; statistics from all that are at this indentation level
5257 (goto-char startsearch)
5258 (if (re-search-forward re-box lim t)
5259 (progn
5260 (org-beginning-of-item)
5261 (setq curr-ind (org-get-indentation))
5262 (setq next-ind curr-ind)
5263 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5264 (save-excursion (end-of-line) (setq eline (point)))
5265 (if (re-search-forward re-box eline t)
5266 (if (member (match-string 2) '("[ ]" "[-]"))
5267 (setq c-off (1+ c-off))
5268 (setq c-on (1+ c-on))
5271 (org-end-of-item)
5272 (setq next-ind (org-get-indentation))
5274 (goto-char continue-from)
5275 ;; update cookie
5276 (when end-cookie
5277 (delete-region beg-cookie end-cookie)
5278 (goto-char beg-cookie)
5279 (insert
5280 (if is-percent
5281 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5282 (format "[%d/%d]" c-on (+ c-on c-off)))))
5283 ;; update items checkbox if it has one
5284 (when (org-at-item-p)
5285 (org-beginning-of-item)
5286 (when (and (> (+ c-on c-off) 0)
5287 (re-search-forward re-box (point-at-eol) t))
5288 (setq beg-cookie (match-beginning 2)
5289 end-cookie (match-end 2))
5290 (delete-region beg-cookie end-cookie)
5291 (goto-char beg-cookie)
5292 (cond ((= c-off 0) (insert "[X]"))
5293 ((= c-on 0) (insert "[ ]"))
5294 (t (insert "[-]")))
5296 (goto-char continue-from))
5297 (when (interactive-p)
5298 (message "Checkbox satistics updated %s (%d places)"
5299 (if all "in entire file" "in current outline entry") cstat)))))
5301 (defun org-get-checkbox-statistics-face ()
5302 "Select the face for checkbox statistics.
5303 The face will be `org-done' when all relevant boxes are checked. Otherwise
5304 it will be `org-todo'."
5305 (if (match-end 1)
5306 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5307 (if (and (> (match-end 2) (match-beginning 2))
5308 (equal (match-string 2) (match-string 3)))
5309 'org-done
5310 'org-todo)))
5312 (defun org-get-indentation (&optional line)
5313 "Get the indentation of the current line, interpreting tabs.
5314 When LINE is given, assume it represents a line and compute its indentation."
5315 (if line
5316 (if (string-match "^ *" (org-remove-tabs line))
5317 (match-end 0))
5318 (save-excursion
5319 (beginning-of-line 1)
5320 (skip-chars-forward " \t")
5321 (current-column))))
5323 (defun org-remove-tabs (s &optional width)
5324 "Replace tabulators in S with spaces.
5325 Assumes that s is a single line, starting in column 0."
5326 (setq width (or width tab-width))
5327 (while (string-match "\t" s)
5328 (setq s (replace-match
5329 (make-string
5330 (- (* width (/ (+ (match-beginning 0) width) width))
5331 (match-beginning 0)) ?\ )
5332 t t s)))
5335 (defun org-fix-indentation (line ind)
5336 "Fix indentation in LINE.
5337 IND is a cons cell with target and minimum indentation.
5338 If the current indenation in LINE is smaller than the minimum,
5339 leave it alone. If it is larger than ind, set it to the target."
5340 (let* ((l (org-remove-tabs line))
5341 (i (org-get-indentation l))
5342 (i1 (car ind)) (i2 (cdr ind)))
5343 (if (>= i i2) (setq l (substring line i2)))
5344 (if (> i1 0)
5345 (concat (make-string i1 ?\ ) l)
5346 l)))
5348 (defun org-beginning-of-item ()
5349 "Go to the beginning of the current hand-formatted item.
5350 If the cursor is not in an item, throw an error."
5351 (interactive)
5352 (let ((pos (point))
5353 (limit (save-excursion
5354 (condition-case nil
5355 (progn
5356 (org-back-to-heading)
5357 (beginning-of-line 2) (point))
5358 (error (point-min)))))
5359 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5360 ind ind1)
5361 (if (org-at-item-p)
5362 (beginning-of-line 1)
5363 (beginning-of-line 1)
5364 (skip-chars-forward " \t")
5365 (setq ind (current-column))
5366 (if (catch 'exit
5367 (while t
5368 (beginning-of-line 0)
5369 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5371 (if (looking-at "[ \t]*$")
5372 (setq ind1 ind-empty)
5373 (skip-chars-forward " \t")
5374 (setq ind1 (current-column)))
5375 (if (< ind1 ind)
5376 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5378 (goto-char pos)
5379 (error "Not in an item")))))
5381 (defun org-end-of-item ()
5382 "Go to the end of the current hand-formatted item.
5383 If the cursor is not in an item, throw an error."
5384 (interactive)
5385 (let* ((pos (point))
5386 ind1
5387 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5388 (limit (save-excursion (outline-next-heading) (point)))
5389 (ind (save-excursion
5390 (org-beginning-of-item)
5391 (skip-chars-forward " \t")
5392 (current-column)))
5393 (end (catch 'exit
5394 (while t
5395 (beginning-of-line 2)
5396 (if (eobp) (throw 'exit (point)))
5397 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5398 (if (looking-at "[ \t]*$")
5399 (setq ind1 ind-empty)
5400 (skip-chars-forward " \t")
5401 (setq ind1 (current-column)))
5402 (if (<= ind1 ind)
5403 (throw 'exit (point-at-bol)))))))
5404 (if end
5405 (goto-char end)
5406 (goto-char pos)
5407 (error "Not in an item"))))
5409 (defun org-next-item ()
5410 "Move to the beginning of the next item in the current plain list.
5411 Error if not at a plain list, or if this is the last item in the list."
5412 (interactive)
5413 (let (ind ind1 (pos (point)))
5414 (org-beginning-of-item)
5415 (setq ind (org-get-indentation))
5416 (org-end-of-item)
5417 (setq ind1 (org-get-indentation))
5418 (unless (and (org-at-item-p) (= ind ind1))
5419 (goto-char pos)
5420 (error "On last item"))))
5422 (defun org-previous-item ()
5423 "Move to the beginning of the previous item in the current plain list.
5424 Error if not at a plain list, or if this is the first item in the list."
5425 (interactive)
5426 (let (beg ind ind1 (pos (point)))
5427 (org-beginning-of-item)
5428 (setq beg (point))
5429 (setq ind (org-get-indentation))
5430 (goto-char beg)
5431 (catch 'exit
5432 (while t
5433 (beginning-of-line 0)
5434 (if (looking-at "[ \t]*$")
5436 (if (<= (setq ind1 (org-get-indentation)) ind)
5437 (throw 'exit t)))))
5438 (condition-case nil
5439 (if (or (not (org-at-item-p))
5440 (< ind1 (1- ind)))
5441 (error "")
5442 (org-beginning-of-item))
5443 (error (goto-char pos)
5444 (error "On first item")))))
5446 (defun org-first-list-item-p ()
5447 "Is this heading the item in a plain list?"
5448 (unless (org-at-item-p)
5449 (error "Not at a plain list item"))
5450 (org-beginning-of-item)
5451 (= (point) (save-excursion (org-beginning-of-item-list))))
5453 (defun org-move-item-down ()
5454 "Move the plain list item at point down, i.e. swap with following item.
5455 Subitems (items with larger indentation) are considered part of the item,
5456 so this really moves item trees."
5457 (interactive)
5458 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5459 (org-beginning-of-item)
5460 (setq beg0 (point))
5461 (save-excursion
5462 (setq ne-beg (org-back-over-empty-lines))
5463 (setq beg (point)))
5464 (goto-char beg0)
5465 (setq ind (org-get-indentation))
5466 (org-end-of-item)
5467 (setq end0 (point))
5468 (setq ind1 (org-get-indentation))
5469 (setq ne-end (org-back-over-empty-lines))
5470 (setq end (point))
5471 (goto-char beg0)
5472 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5473 ;; include less whitespace
5474 (save-excursion
5475 (goto-char beg)
5476 (forward-line (- ne-beg ne-end))
5477 (setq beg (point))))
5478 (goto-char end0)
5479 (if (and (org-at-item-p) (= ind ind1))
5480 (progn
5481 (org-end-of-item)
5482 (org-back-over-empty-lines)
5483 (setq txt (buffer-substring beg end))
5484 (save-excursion
5485 (delete-region beg end))
5486 (setq pos (point))
5487 (insert txt)
5488 (goto-char pos) (org-skip-whitespace)
5489 (org-maybe-renumber-ordered-list))
5490 (goto-char pos)
5491 (error "Cannot move this item further down"))))
5493 (defun org-move-item-up (arg)
5494 "Move the plain list item at point up, i.e. swap with previous item.
5495 Subitems (items with larger indentation) are considered part of the item,
5496 so this really moves item trees."
5497 (interactive "p")
5498 (let (beg beg0 end ind ind1 (pos (point)) txt
5499 ne-beg ne-ins ins-end)
5500 (org-beginning-of-item)
5501 (setq beg0 (point))
5502 (setq ind (org-get-indentation))
5503 (save-excursion
5504 (setq ne-beg (org-back-over-empty-lines))
5505 (setq beg (point)))
5506 (goto-char beg0)
5507 (org-end-of-item)
5508 (setq end (point))
5509 (goto-char beg0)
5510 (catch 'exit
5511 (while t
5512 (beginning-of-line 0)
5513 (if (looking-at "[ \t]*$")
5514 (if org-empty-line-terminates-plain-lists
5515 (progn
5516 (goto-char pos)
5517 (error "Cannot move this item further up"))
5518 nil)
5519 (if (<= (setq ind1 (org-get-indentation)) ind)
5520 (throw 'exit t)))))
5521 (condition-case nil
5522 (org-beginning-of-item)
5523 (error (goto-char beg)
5524 (error "Cannot move this item further up")))
5525 (setq ind1 (org-get-indentation))
5526 (if (and (org-at-item-p) (= ind ind1))
5527 (progn
5528 (setq ne-ins (org-back-over-empty-lines))
5529 (setq txt (buffer-substring beg end))
5530 (save-excursion
5531 (delete-region beg end))
5532 (setq pos (point))
5533 (insert txt)
5534 (setq ins-end (point))
5535 (goto-char pos) (org-skip-whitespace)
5537 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5538 ;; Move whitespace back to beginning
5539 (save-excursion
5540 (goto-char ins-end)
5541 (let ((kill-whole-line t))
5542 (kill-line (- ne-ins ne-beg)) (point)))
5543 (insert (make-string (- ne-ins ne-beg) ?\n)))
5545 (org-maybe-renumber-ordered-list))
5546 (goto-char pos)
5547 (error "Cannot move this item further up"))))
5549 (defun org-maybe-renumber-ordered-list ()
5550 "Renumber the ordered list at point if setup allows it.
5551 This tests the user option `org-auto-renumber-ordered-lists' before
5552 doing the renumbering."
5553 (interactive)
5554 (when (and org-auto-renumber-ordered-lists
5555 (org-at-item-p))
5556 (if (match-beginning 3)
5557 (org-renumber-ordered-list 1)
5558 (org-fix-bullet-type))))
5560 (defun org-maybe-renumber-ordered-list-safe ()
5561 (condition-case nil
5562 (save-excursion
5563 (org-maybe-renumber-ordered-list))
5564 (error nil)))
5566 (defun org-cycle-list-bullet (&optional which)
5567 "Cycle through the different itemize/enumerate bullets.
5568 This cycle the entire list level through the sequence:
5570 `-' -> `+' -> `*' -> `1.' -> `1)'
5572 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5573 0 meand `-', 1 means `+' etc."
5574 (interactive "P")
5575 (org-preserve-lc
5576 (org-beginning-of-item-list)
5577 (org-at-item-p)
5578 (beginning-of-line 1)
5579 (let ((current (match-string 0))
5580 (prevp (eq which 'previous))
5581 new)
5582 (setq new (cond
5583 ((and (numberp which)
5584 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5585 ((string-match "-" current) (if prevp "1)" "+"))
5586 ((string-match "\\+" current)
5587 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5588 ((string-match "\\*" current) (if prevp "+" "1."))
5589 ((string-match "\\." current) (if prevp "*" "1)"))
5590 ((string-match ")" current) (if prevp "1." "-"))
5591 (t (error "This should not happen"))))
5592 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5593 (org-fix-bullet-type)
5594 (org-maybe-renumber-ordered-list))))
5596 (defun org-get-string-indentation (s)
5597 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5598 (let ((n -1) (i 0) (w tab-width) c)
5599 (catch 'exit
5600 (while (< (setq n (1+ n)) (length s))
5601 (setq c (aref s n))
5602 (cond ((= c ?\ ) (setq i (1+ i)))
5603 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5604 (t (throw 'exit t)))))
5607 (defun org-renumber-ordered-list (arg)
5608 "Renumber an ordered plain list.
5609 Cursor needs to be in the first line of an item, the line that starts
5610 with something like \"1.\" or \"2)\"."
5611 (interactive "p")
5612 (unless (and (org-at-item-p)
5613 (match-beginning 3))
5614 (error "This is not an ordered list"))
5615 (let ((line (org-current-line))
5616 (col (current-column))
5617 (ind (org-get-string-indentation
5618 (buffer-substring (point-at-bol) (match-beginning 3))))
5619 ;; (term (substring (match-string 3) -1))
5620 ind1 (n (1- arg))
5621 fmt)
5622 ;; find where this list begins
5623 (org-beginning-of-item-list)
5624 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5625 (setq fmt (concat "%d" (match-string 1)))
5626 (beginning-of-line 0)
5627 ;; walk forward and replace these numbers
5628 (catch 'exit
5629 (while t
5630 (catch 'next
5631 (beginning-of-line 2)
5632 (if (eobp) (throw 'exit nil))
5633 (if (looking-at "[ \t]*$") (throw 'next nil))
5634 (skip-chars-forward " \t") (setq ind1 (current-column))
5635 (if (> ind1 ind) (throw 'next t))
5636 (if (< ind1 ind) (throw 'exit t))
5637 (if (not (org-at-item-p)) (throw 'exit nil))
5638 (delete-region (match-beginning 2) (match-end 2))
5639 (goto-char (match-beginning 2))
5640 (insert (format fmt (setq n (1+ n)))))))
5641 (goto-line line)
5642 (move-to-column col)))
5644 (defun org-fix-bullet-type ()
5645 "Make sure all items in this list have the same bullet as the firsst item."
5646 (interactive)
5647 (unless (org-at-item-p) (error "This is not a list"))
5648 (let ((line (org-current-line))
5649 (col (current-column))
5650 (ind (current-indentation))
5651 ind1 bullet)
5652 ;; find where this list begins
5653 (org-beginning-of-item-list)
5654 (beginning-of-line 1)
5655 ;; find out what the bullet type is
5656 (looking-at "[ \t]*\\(\\S-+\\)")
5657 (setq bullet (match-string 1))
5658 ;; walk forward and replace these numbers
5659 (beginning-of-line 0)
5660 (catch 'exit
5661 (while t
5662 (catch 'next
5663 (beginning-of-line 2)
5664 (if (eobp) (throw 'exit nil))
5665 (if (looking-at "[ \t]*$") (throw 'next nil))
5666 (skip-chars-forward " \t") (setq ind1 (current-column))
5667 (if (> ind1 ind) (throw 'next t))
5668 (if (< ind1 ind) (throw 'exit t))
5669 (if (not (org-at-item-p)) (throw 'exit nil))
5670 (skip-chars-forward " \t")
5671 (looking-at "\\S-+")
5672 (replace-match bullet))))
5673 (goto-line line)
5674 (move-to-column col)
5675 (if (string-match "[0-9]" bullet)
5676 (org-renumber-ordered-list 1))))
5678 (defun org-beginning-of-item-list ()
5679 "Go to the beginning of the current item list.
5680 I.e. to the first item in this list."
5681 (interactive)
5682 (org-beginning-of-item)
5683 (let ((pos (point-at-bol))
5684 (ind (org-get-indentation))
5685 ind1)
5686 ;; find where this list begins
5687 (catch 'exit
5688 (while t
5689 (catch 'next
5690 (beginning-of-line 0)
5691 (if (looking-at "[ \t]*$")
5692 (throw (if (bobp) 'exit 'next) t))
5693 (skip-chars-forward " \t") (setq ind1 (current-column))
5694 (if (or (< ind1 ind)
5695 (and (= ind1 ind)
5696 (not (org-at-item-p)))
5697 (bobp))
5698 (throw 'exit t)
5699 (when (org-at-item-p) (setq pos (point-at-bol)))))))
5700 (goto-char pos)))
5703 (defun org-end-of-item-list ()
5704 "Go to the end of the current item list.
5705 I.e. to the text after the last item."
5706 (interactive)
5707 (org-beginning-of-item)
5708 (let ((pos (point-at-bol))
5709 (ind (org-get-indentation))
5710 ind1)
5711 ;; find where this list begins
5712 (catch 'exit
5713 (while t
5714 (catch 'next
5715 (beginning-of-line 2)
5716 (if (looking-at "[ \t]*$")
5717 (throw (if (eobp) 'exit 'next) t))
5718 (skip-chars-forward " \t") (setq ind1 (current-column))
5719 (if (or (< ind1 ind)
5720 (and (= ind1 ind)
5721 (not (org-at-item-p)))
5722 (eobp))
5723 (progn
5724 (setq pos (point-at-bol))
5725 (throw 'exit t))))))
5726 (goto-char pos)))
5729 (defvar org-last-indent-begin-marker (make-marker))
5730 (defvar org-last-indent-end-marker (make-marker))
5732 (defun org-outdent-item (arg)
5733 "Outdent a local list item."
5734 (interactive "p")
5735 (org-indent-item (- arg)))
5737 (defun org-indent-item (arg)
5738 "Indent a local list item."
5739 (interactive "p")
5740 (unless (org-at-item-p)
5741 (error "Not on an item"))
5742 (save-excursion
5743 (let (beg end ind ind1 tmp delta ind-down ind-up)
5744 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5745 (setq beg org-last-indent-begin-marker
5746 end org-last-indent-end-marker)
5747 (org-beginning-of-item)
5748 (setq beg (move-marker org-last-indent-begin-marker (point)))
5749 (org-end-of-item)
5750 (setq end (move-marker org-last-indent-end-marker (point))))
5751 (goto-char beg)
5752 (setq tmp (org-item-indent-positions)
5753 ind (car tmp)
5754 ind-down (nth 2 tmp)
5755 ind-up (nth 1 tmp)
5756 delta (if (> arg 0)
5757 (if ind-down (- ind-down ind) 2)
5758 (if ind-up (- ind-up ind) -2)))
5759 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5760 (while (< (point) end)
5761 (beginning-of-line 1)
5762 (skip-chars-forward " \t") (setq ind1 (current-column))
5763 (delete-region (point-at-bol) (point))
5764 (or (eolp) (indent-to-column (+ ind1 delta)))
5765 (beginning-of-line 2))))
5766 (org-fix-bullet-type)
5767 (org-maybe-renumber-ordered-list-safe)
5768 (save-excursion
5769 (beginning-of-line 0)
5770 (condition-case nil (org-beginning-of-item) (error nil))
5771 (org-maybe-renumber-ordered-list-safe)))
5773 (defun org-item-indent-positions ()
5774 "Return indentation for plain list items.
5775 This returns a list with three values: The current indentation, the
5776 parent indentation and the indentation a child should habe.
5777 Assumes cursor in item line."
5778 (let* ((bolpos (point-at-bol))
5779 (ind (org-get-indentation))
5780 ind-down ind-up pos)
5781 (save-excursion
5782 (org-beginning-of-item-list)
5783 (skip-chars-backward "\n\r \t")
5784 (when (org-in-item-p)
5785 (org-beginning-of-item)
5786 (setq ind-up (org-get-indentation))))
5787 (setq pos (point))
5788 (save-excursion
5789 (cond
5790 ((and (condition-case nil (progn (org-previous-item) t)
5791 (error nil))
5792 (or (forward-char 1) t)
5793 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
5794 (setq ind-down (org-get-indentation)))
5795 ((and (goto-char pos)
5796 (org-at-item-p))
5797 (goto-char (match-end 0))
5798 (skip-chars-forward " \t")
5799 (setq ind-down (current-column)))))
5800 (list ind ind-up ind-down)))
5802 ;;; The orgstruct minor mode
5804 ;; Define a minor mode which can be used in other modes in order to
5805 ;; integrate the org-mode structure editing commands.
5807 ;; This is really a hack, because the org-mode structure commands use
5808 ;; keys which normally belong to the major mode. Here is how it
5809 ;; works: The minor mode defines all the keys necessary to operate the
5810 ;; structure commands, but wraps the commands into a function which
5811 ;; tests if the cursor is currently at a headline or a plain list
5812 ;; item. If that is the case, the structure command is used,
5813 ;; temporarily setting many Org-mode variables like regular
5814 ;; expressions for filling etc. However, when any of those keys is
5815 ;; used at a different location, function uses `key-binding' to look
5816 ;; up if the key has an associated command in another currently active
5817 ;; keymap (minor modes, major mode, global), and executes that
5818 ;; command. There might be problems if any of the keys is otherwise
5819 ;; used as a prefix key.
5821 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5822 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5823 ;; addresses this by checking explicitly for both bindings.
5825 (defvar orgstruct-mode-map (make-sparse-keymap)
5826 "Keymap for the minor `orgstruct-mode'.")
5828 (defvar org-local-vars nil
5829 "List of local variables, for use by `orgstruct-mode'")
5831 ;;;###autoload
5832 (define-minor-mode orgstruct-mode
5833 "Toggle the minor more `orgstruct-mode'.
5834 This mode is for using Org-mode structure commands in other modes.
5835 The following key behave as if Org-mode was active, if the cursor
5836 is on a headline, or on a plain list item (both in the definition
5837 of Org-mode).
5839 M-up Move entry/item up
5840 M-down Move entry/item down
5841 M-left Promote
5842 M-right Demote
5843 M-S-up Move entry/item up
5844 M-S-down Move entry/item down
5845 M-S-left Promote subtree
5846 M-S-right Demote subtree
5847 M-q Fill paragraph and items like in Org-mode
5848 C-c ^ Sort entries
5849 C-c - Cycle list bullet
5850 TAB Cycle item visibility
5851 M-RET Insert new heading/item
5852 S-M-RET Insert new TODO heading / Chekbox item
5853 C-c C-c Set tags / toggle checkbox"
5854 nil " OrgStruct" nil
5855 (org-load-modules-maybe)
5856 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5858 ;;;###autoload
5859 (defun turn-on-orgstruct ()
5860 "Unconditionally turn on `orgstruct-mode'."
5861 (orgstruct-mode 1))
5863 ;;;###autoload
5864 (defun turn-on-orgstruct++ ()
5865 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5866 In addition to setting orgstruct-mode, this also exports all indentation and
5867 autofilling variables from org-mode into the buffer. Note that turning
5868 off orgstruct-mode will *not* remove these additional settings."
5869 (orgstruct-mode 1)
5870 (let (var val)
5871 (mapc
5872 (lambda (x)
5873 (when (string-match
5874 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5875 (symbol-name (car x)))
5876 (setq var (car x) val (nth 1 x))
5877 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5878 org-local-vars)))
5880 (defun orgstruct-error ()
5881 "Error when there is no default binding for a structure key."
5882 (interactive)
5883 (error "This key has no function outside structure elements"))
5885 (defun orgstruct-setup ()
5886 "Setup orgstruct keymaps."
5887 (let ((nfunc 0)
5888 (bindings
5889 (list
5890 '([(meta up)] org-metaup)
5891 '([(meta down)] org-metadown)
5892 '([(meta left)] org-metaleft)
5893 '([(meta right)] org-metaright)
5894 '([(meta shift up)] org-shiftmetaup)
5895 '([(meta shift down)] org-shiftmetadown)
5896 '([(meta shift left)] org-shiftmetaleft)
5897 '([(meta shift right)] org-shiftmetaright)
5898 '([(shift up)] org-shiftup)
5899 '([(shift down)] org-shiftdown)
5900 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5901 '("\M-q" fill-paragraph)
5902 '("\C-c^" org-sort)
5903 '("\C-c-" org-cycle-list-bullet)))
5904 elt key fun cmd)
5905 (while (setq elt (pop bindings))
5906 (setq nfunc (1+ nfunc))
5907 (setq key (org-key (car elt))
5908 fun (nth 1 elt)
5909 cmd (orgstruct-make-binding fun nfunc key))
5910 (org-defkey orgstruct-mode-map key cmd))
5912 ;; Special treatment needed for TAB and RET
5913 (org-defkey orgstruct-mode-map [(tab)]
5914 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5915 (org-defkey orgstruct-mode-map "\C-i"
5916 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5918 (org-defkey orgstruct-mode-map "\M-\C-m"
5919 (orgstruct-make-binding 'org-insert-heading 105
5920 "\M-\C-m" [(meta return)]))
5921 (org-defkey orgstruct-mode-map [(meta return)]
5922 (orgstruct-make-binding 'org-insert-heading 106
5923 [(meta return)] "\M-\C-m"))
5925 (org-defkey orgstruct-mode-map [(shift meta return)]
5926 (orgstruct-make-binding 'org-insert-todo-heading 107
5927 [(meta return)] "\M-\C-m"))
5929 (unless org-local-vars
5930 (setq org-local-vars (org-get-local-variables)))
5934 (defun orgstruct-make-binding (fun n &rest keys)
5935 "Create a function for binding in the structure minor mode.
5936 FUN is the command to call inside a table. N is used to create a unique
5937 command name. KEYS are keys that should be checked in for a command
5938 to execute outside of tables."
5939 (eval
5940 (list 'defun
5941 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5942 '(arg)
5943 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5944 "Outside of structure, run the binding of `"
5945 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5946 "'.")
5947 '(interactive "p")
5948 (list 'if
5949 '(org-context-p 'headline 'item)
5950 (list 'org-run-like-in-org-mode (list 'quote fun))
5951 (list 'let '(orgstruct-mode)
5952 (list 'call-interactively
5953 (append '(or)
5954 (mapcar (lambda (k)
5955 (list 'key-binding k))
5956 keys)
5957 '('orgstruct-error))))))))
5959 (defun org-context-p (&rest contexts)
5960 "Check if local context is and of CONTEXTS.
5961 Possible values in the list of contexts are `table', `headline', and `item'."
5962 (let ((pos (point)))
5963 (goto-char (point-at-bol))
5964 (prog1 (or (and (memq 'table contexts)
5965 (looking-at "[ \t]*|"))
5966 (and (memq 'headline contexts)
5967 (looking-at "\\*+"))
5968 (and (memq 'item contexts)
5969 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5970 (goto-char pos))))
5972 (defun org-get-local-variables ()
5973 "Return a list of all local variables in an org-mode buffer."
5974 (let (varlist)
5975 (with-current-buffer (get-buffer-create "*Org tmp*")
5976 (erase-buffer)
5977 (org-mode)
5978 (setq varlist (buffer-local-variables)))
5979 (kill-buffer "*Org tmp*")
5980 (delq nil
5981 (mapcar
5982 (lambda (x)
5983 (setq x
5984 (if (symbolp x)
5985 (list x)
5986 (list (car x) (list 'quote (cdr x)))))
5987 (if (string-match
5988 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5989 (symbol-name (car x)))
5990 x nil))
5991 varlist))))
5993 ;;;###autoload
5994 (defun org-run-like-in-org-mode (cmd)
5995 (org-load-modules-maybe)
5996 (unless org-local-vars
5997 (setq org-local-vars (org-get-local-variables)))
5998 (eval (list 'let org-local-vars
5999 (list 'call-interactively (list 'quote cmd)))))
6001 ;;;; Archiving
6003 (defun org-get-category (&optional pos)
6004 "Get the category applying to position POS."
6005 (get-text-property (or pos (point)) 'org-category))
6007 (defun org-refresh-category-properties ()
6008 "Refresh category text properties in the buffer."
6009 (let ((def-cat (cond
6010 ((null org-category)
6011 (if buffer-file-name
6012 (file-name-sans-extension
6013 (file-name-nondirectory buffer-file-name))
6014 "???"))
6015 ((symbolp org-category) (symbol-name org-category))
6016 (t org-category)))
6017 beg end cat pos optionp)
6018 (org-unmodified
6019 (save-excursion
6020 (save-restriction
6021 (widen)
6022 (goto-char (point-min))
6023 (put-text-property (point) (point-max) 'org-category def-cat)
6024 (while (re-search-forward
6025 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6026 (setq pos (match-end 0)
6027 optionp (equal (char-after (match-beginning 0)) ?#)
6028 cat (org-trim (match-string 2)))
6029 (if optionp
6030 (setq beg (point-at-bol) end (point-max))
6031 (org-back-to-heading t)
6032 (setq beg (point) end (org-end-of-subtree t t)))
6033 (put-text-property beg end 'org-category cat)
6034 (goto-char pos)))))))
6037 ;;;; Link Stuff
6039 ;;; Link abbreviations
6041 (defun org-link-expand-abbrev (link)
6042 "Apply replacements as defined in `org-link-abbrev-alist."
6043 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6044 (let* ((key (match-string 1 link))
6045 (as (or (assoc key org-link-abbrev-alist-local)
6046 (assoc key org-link-abbrev-alist)))
6047 (tag (and (match-end 2) (match-string 3 link)))
6048 rpl)
6049 (if (not as)
6050 link
6051 (setq rpl (cdr as))
6052 (cond
6053 ((symbolp rpl) (funcall rpl tag))
6054 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6055 (t (concat rpl tag)))))
6056 link))
6058 ;;; Storing and inserting links
6060 (defvar org-insert-link-history nil
6061 "Minibuffer history for links inserted with `org-insert-link'.")
6063 (defvar org-stored-links nil
6064 "Contains the links stored with `org-store-link'.")
6066 (defvar org-store-link-plist nil
6067 "Plist with info about the most recently link created with `org-store-link'.")
6069 (defvar org-link-protocols nil
6070 "Link protocols added to Org-mode using `org-add-link-type'.")
6072 (defvar org-store-link-functions nil
6073 "List of functions that are called to create and store a link.
6074 Each function will be called in turn until one returns a non-nil
6075 value. Each function should check if it is responsible for creating
6076 this link (for example by looking at the major mode).
6077 If not, it must exit and return nil.
6078 If yes, it should return a non-nil value after a calling
6079 `org-store-link-props' with a list of properties and values.
6080 Special properties are:
6082 :type The link prefix. like \"http\". This must be given.
6083 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6084 This is obligatory as well.
6085 :description Optional default description for the second pair
6086 of brackets in an Org-mode link. The user can still change
6087 this when inserting this link into an Org-mode buffer.
6089 In addition to these, any additional properties can be specified
6090 and then used in remember templates.")
6092 (defun org-add-link-type (type &optional follow export)
6093 "Add TYPE to the list of `org-link-types'.
6094 Re-compute all regular expressions depending on `org-link-types'
6096 FOLLOW and EXPORT are two functions.
6098 FOLLOW should take the link path as the single argument and do whatever
6099 is necessary to follow the link, for example find a file or display
6100 a mail message.
6102 EXPORT should format the link path for export to one of the export formats.
6103 It should be a function accepting three arguments:
6105 path the path of the link, the text after the prefix (like \"http:\")
6106 desc the description of the link, if any, nil if there was no descripton
6107 format the export format, a symbol like `html' or `latex'.
6109 The function may use the FORMAT information to return different values
6110 depending on the format. The return value will be put literally into
6111 the exported file.
6112 Org-mode has a built-in default for exporting links. If you are happy with
6113 this default, there is no need to define an export function for the link
6114 type. For a simple example of an export function, see `org-bbdb.el'."
6115 (add-to-list 'org-link-types type t)
6116 (org-make-link-regexps)
6117 (if (assoc type org-link-protocols)
6118 (setcdr (assoc type org-link-protocols) (list follow export))
6119 (push (list type follow export) org-link-protocols)))
6122 ;;;###autoload
6123 (defun org-store-link (arg)
6124 "\\<org-mode-map>Store an org-link to the current location.
6125 This link is added to `org-stored-links' and can later be inserted
6126 into an org-buffer with \\[org-insert-link].
6128 For some link types, a prefix arg is interpreted:
6129 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6130 For file links, arg negates `org-context-in-file-links'."
6131 (interactive "P")
6132 (org-load-modules-maybe)
6133 (setq org-store-link-plist nil) ; reset
6134 (let (link cpltxt desc description search txt)
6135 (cond
6137 ((run-hook-with-args-until-success 'org-store-link-functions)
6138 (setq link (plist-get org-store-link-plist :link)
6139 desc (or (plist-get org-store-link-plist :description) link)))
6141 ((eq major-mode 'calendar-mode)
6142 (let ((cd (calendar-cursor-to-date)))
6143 (setq link
6144 (format-time-string
6145 (car org-time-stamp-formats)
6146 (apply 'encode-time
6147 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6148 nil nil nil))))
6149 (org-store-link-props :type "calendar" :date cd)))
6151 ((eq major-mode 'w3-mode)
6152 (setq cpltxt (url-view-url t)
6153 link (org-make-link cpltxt))
6154 (org-store-link-props :type "w3" :url (url-view-url t)))
6156 ((eq major-mode 'w3m-mode)
6157 (setq cpltxt (or w3m-current-title w3m-current-url)
6158 link (org-make-link w3m-current-url))
6159 (org-store-link-props :type "w3m" :url (url-view-url t)))
6161 ((setq search (run-hook-with-args-until-success
6162 'org-create-file-search-functions))
6163 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6164 "::" search))
6165 (setq cpltxt (or description link)))
6167 ((eq major-mode 'image-mode)
6168 (setq cpltxt (concat "file:"
6169 (abbreviate-file-name buffer-file-name))
6170 link (org-make-link cpltxt))
6171 (org-store-link-props :type "image" :file buffer-file-name))
6173 ((eq major-mode 'dired-mode)
6174 ;; link to the file in the current line
6175 (setq cpltxt (concat "file:"
6176 (abbreviate-file-name
6177 (expand-file-name
6178 (dired-get-filename nil t))))
6179 link (org-make-link cpltxt)))
6181 ((and buffer-file-name (org-mode-p))
6182 ;; Just link to current headline
6183 (setq cpltxt (concat "file:"
6184 (abbreviate-file-name buffer-file-name)))
6185 ;; Add a context search string
6186 (when (org-xor org-context-in-file-links arg)
6187 ;; Check if we are on a target
6188 (if (org-in-regexp "<<\\(.*?\\)>>")
6189 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6190 (setq txt (cond
6191 ((org-on-heading-p) nil)
6192 ((org-region-active-p)
6193 (buffer-substring (region-beginning) (region-end)))
6194 (t nil)))
6195 (when (or (null txt) (string-match "\\S-" txt))
6196 (setq cpltxt
6197 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6198 desc "NONE"))))
6199 (if (string-match "::\\'" cpltxt)
6200 (setq cpltxt (substring cpltxt 0 -2)))
6201 (setq link (org-make-link cpltxt)))
6203 ((buffer-file-name (buffer-base-buffer))
6204 ;; Just link to this file here.
6205 (setq cpltxt (concat "file:"
6206 (abbreviate-file-name
6207 (buffer-file-name (buffer-base-buffer)))))
6208 ;; Add a context string
6209 (when (org-xor org-context-in-file-links arg)
6210 (setq txt (if (org-region-active-p)
6211 (buffer-substring (region-beginning) (region-end))
6212 (buffer-substring (point-at-bol) (point-at-eol))))
6213 ;; Only use search option if there is some text.
6214 (when (string-match "\\S-" txt)
6215 (setq cpltxt
6216 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6217 desc "NONE")))
6218 (setq link (org-make-link cpltxt)))
6220 ((interactive-p)
6221 (error "Cannot link to a buffer which is not visiting a file"))
6223 (t (setq link nil)))
6225 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6226 (setq link (or link cpltxt)
6227 desc (or desc cpltxt))
6228 (if (equal desc "NONE") (setq desc nil))
6230 (if (and (interactive-p) link)
6231 (progn
6232 (setq org-stored-links
6233 (cons (list link desc) org-stored-links))
6234 (message "Stored: %s" (or desc link)))
6235 (and link (org-make-link-string link desc)))))
6237 (defun org-store-link-props (&rest plist)
6238 "Store link properties, extract names and addresses."
6239 (let (x adr)
6240 (when (setq x (plist-get plist :from))
6241 (setq adr (mail-extract-address-components x))
6242 (plist-put plist :fromname (car adr))
6243 (plist-put plist :fromaddress (nth 1 adr)))
6244 (when (setq x (plist-get plist :to))
6245 (setq adr (mail-extract-address-components x))
6246 (plist-put plist :toname (car adr))
6247 (plist-put plist :toaddress (nth 1 adr))))
6248 (let ((from (plist-get plist :from))
6249 (to (plist-get plist :to)))
6250 (when (and from to org-from-is-user-regexp)
6251 (plist-put plist :fromto
6252 (if (string-match org-from-is-user-regexp from)
6253 (concat "to %t")
6254 (concat "from %f")))))
6255 (setq org-store-link-plist plist))
6257 (defun org-add-link-props (&rest plist)
6258 "Add these properties to the link property list."
6259 (let (key value)
6260 (while plist
6261 (setq key (pop plist) value (pop plist))
6262 (setq org-store-link-plist
6263 (plist-put org-store-link-plist key value)))))
6265 (defun org-email-link-description (&optional fmt)
6266 "Return the description part of an email link.
6267 This takes information from `org-store-link-plist' and formats it
6268 according to FMT (default from `org-email-link-description-format')."
6269 (setq fmt (or fmt org-email-link-description-format))
6270 (let* ((p org-store-link-plist)
6271 (to (plist-get p :toaddress))
6272 (from (plist-get p :fromaddress))
6273 (table
6274 (list
6275 (cons "%c" (plist-get p :fromto))
6276 (cons "%F" (plist-get p :from))
6277 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6278 (cons "%T" (plist-get p :to))
6279 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6280 (cons "%s" (plist-get p :subject))
6281 (cons "%m" (plist-get p :message-id)))))
6282 (when (string-match "%c" fmt)
6283 ;; Check if the user wrote this message
6284 (if (and org-from-is-user-regexp from to
6285 (save-match-data (string-match org-from-is-user-regexp from)))
6286 (setq fmt (replace-match "to %t" t t fmt))
6287 (setq fmt (replace-match "from %f" t t fmt))))
6288 (org-replace-escapes fmt table)))
6290 (defun org-make-org-heading-search-string (&optional string heading)
6291 "Make search string for STRING or current headline."
6292 (interactive)
6293 (let ((s (or string (org-get-heading))))
6294 (unless (and string (not heading))
6295 ;; We are using a headline, clean up garbage in there.
6296 (if (string-match org-todo-regexp s)
6297 (setq s (replace-match "" t t s)))
6298 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6299 (setq s (replace-match "" t t s)))
6300 (setq s (org-trim s))
6301 (if (string-match (concat "^\\(" org-quote-string "\\|"
6302 org-comment-string "\\)") s)
6303 (setq s (replace-match "" t t s)))
6304 (while (string-match org-ts-regexp s)
6305 (setq s (replace-match "" t t s))))
6306 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6307 (setq s (replace-match " " t t s)))
6308 (or string (setq s (concat "*" s))) ; Add * for headlines
6309 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6311 (defun org-make-link (&rest strings)
6312 "Concatenate STRINGS."
6313 (apply 'concat strings))
6315 (defun org-make-link-string (link &optional description)
6316 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6317 (unless (string-match "\\S-" link)
6318 (error "Empty link"))
6319 (when (stringp description)
6320 ;; Remove brackets from the description, they are fatal.
6321 (while (string-match "\\[" description)
6322 (setq description (replace-match "{" t t description)))
6323 (while (string-match "\\]" description)
6324 (setq description (replace-match "}" t t description))))
6325 (when (equal (org-link-escape link) description)
6326 ;; No description needed, it is identical
6327 (setq description nil))
6328 (when (and (not description)
6329 (not (equal link (org-link-escape link))))
6330 (setq description link))
6331 (concat "[[" (org-link-escape link) "]"
6332 (if description (concat "[" description "]") "")
6333 "]"))
6335 (defconst org-link-escape-chars
6336 '((?\ . "%20")
6337 (?\[ . "%5B")
6338 (?\] . "%5D")
6339 (?\340 . "%E0") ; `a
6340 (?\342 . "%E2") ; ^a
6341 (?\347 . "%E7") ; ,c
6342 (?\350 . "%E8") ; `e
6343 (?\351 . "%E9") ; 'e
6344 (?\352 . "%EA") ; ^e
6345 (?\356 . "%EE") ; ^i
6346 (?\364 . "%F4") ; ^o
6347 (?\371 . "%F9") ; `u
6348 (?\373 . "%FB") ; ^u
6349 (?\; . "%3B")
6350 (?? . "%3F")
6351 (?= . "%3D")
6352 (?+ . "%2B")
6354 "Association list of escapes for some characters problematic in links.
6355 This is the list that is used for internal purposes.")
6357 (defconst org-link-escape-chars-browser
6358 '((?\ . "%20")) ; 32 for the SPC char
6359 "Association list of escapes for some characters problematic in links.
6360 This is the list that is used before handing over to the browser.")
6362 (defun org-link-escape (text &optional table)
6363 "Escape charaters in TEXT that are problematic for links."
6364 (setq table (or table org-link-escape-chars))
6365 (when text
6366 (let ((re (mapconcat (lambda (x) (regexp-quote
6367 (char-to-string (car x))))
6368 table "\\|")))
6369 (while (string-match re text)
6370 (setq text
6371 (replace-match
6372 (cdr (assoc (string-to-char (match-string 0 text))
6373 table))
6374 t t text)))
6375 text)))
6377 (defun org-link-unescape (text &optional table)
6378 "Reverse the action of `org-link-escape'."
6379 (setq table (or table org-link-escape-chars))
6380 (when text
6381 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6382 table "\\|")))
6383 (while (string-match re text)
6384 (setq text
6385 (replace-match
6386 (char-to-string (car (rassoc (match-string 0 text) table)))
6387 t t text)))
6388 text)))
6390 (defun org-xor (a b)
6391 "Exclusive or."
6392 (if a (not b) b))
6394 (defun org-get-header (header)
6395 "Find a header field in the current buffer."
6396 (save-excursion
6397 (goto-char (point-min))
6398 (let ((case-fold-search t) s)
6399 (cond
6400 ((eq header 'from)
6401 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6402 (setq s (match-string 1)))
6403 (while (string-match "\"" s)
6404 (setq s (replace-match "" t t s)))
6405 (if (string-match "[<(].*" s)
6406 (setq s (replace-match "" t t s))))
6407 ((eq header 'message-id)
6408 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6409 (setq s (match-string 1))))
6410 ((eq header 'subject)
6411 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6412 (setq s (match-string 1)))))
6413 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6414 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6415 s)))
6418 (defun org-fixup-message-id-for-http (s)
6419 "Replace special characters in a message id, so it can be used in an http query."
6420 (while (string-match "<" s)
6421 (setq s (replace-match "%3C" t t s)))
6422 (while (string-match ">" s)
6423 (setq s (replace-match "%3E" t t s)))
6424 (while (string-match "@" s)
6425 (setq s (replace-match "%40" t t s)))
6428 ;;;###autoload
6429 (defun org-insert-link-global ()
6430 "Insert a link like Org-mode does.
6431 This command can be called in any mode to insert a link in Org-mode syntax."
6432 (interactive)
6433 (org-load-modules-maybe)
6434 (org-run-like-in-org-mode 'org-insert-link))
6436 (defun org-insert-link (&optional complete-file link-location)
6437 "Insert a link. At the prompt, enter the link.
6439 Completion can be used to select a link previously stored with
6440 `org-store-link'. When the empty string is entered (i.e. if you just
6441 press RET at the prompt), the link defaults to the most recently
6442 stored link. As SPC triggers completion in the minibuffer, you need to
6443 use M-SPC or C-q SPC to force the insertion of a space character.
6445 You will also be prompted for a description, and if one is given, it will
6446 be displayed in the buffer instead of the link.
6448 If there is already a link at point, this command will allow you to edit link
6449 and description parts.
6451 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6452 be selected using completion. The path to the file will be relative to the
6453 current directory if the file is in the current directory or a subdirectory.
6454 Otherwise, the link will be the absolute path as completed in the minibuffer
6455 \(i.e. normally ~/path/to/file).
6457 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6458 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6459 of `org-keep-stored-link-after-insertion'.
6461 If `org-make-link-description-function' is non-nil, this function will be
6462 called with the link target, and the result will be the default
6463 link description.
6465 If the LINK-LOCATION parameter is non-nil, this value will be
6466 used as the link location instead of reading one interactively."
6467 (interactive "P")
6468 (let* ((wcf (current-window-configuration))
6469 (region (if (org-region-active-p)
6470 (buffer-substring (region-beginning) (region-end))))
6471 (remove (and region (list (region-beginning) (region-end))))
6472 (desc region)
6473 tmphist ; byte-compile incorrectly complains about this
6474 (link link-location)
6475 entry file)
6476 (cond
6477 (link-location) ; specified by arg, just use it.
6478 ((org-in-regexp org-bracket-link-regexp 1)
6479 ;; We do have a link at point, and we are going to edit it.
6480 (setq remove (list (match-beginning 0) (match-end 0)))
6481 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6482 (setq link (read-string "Link: "
6483 (org-link-unescape
6484 (org-match-string-no-properties 1)))))
6485 ((or (org-in-regexp org-angle-link-re)
6486 (org-in-regexp org-plain-link-re))
6487 ;; Convert to bracket link
6488 (setq remove (list (match-beginning 0) (match-end 0))
6489 link (read-string "Link: "
6490 (org-remove-angle-brackets (match-string 0)))))
6491 ((equal complete-file '(4))
6492 ;; Completing read for file names.
6493 (setq file (read-file-name "File: "))
6494 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6495 (pwd1 (file-name-as-directory (abbreviate-file-name
6496 (expand-file-name ".")))))
6497 (cond
6498 ((equal complete-file '(16))
6499 (setq link (org-make-link
6500 "file:"
6501 (abbreviate-file-name (expand-file-name file)))))
6502 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6503 (setq link (org-make-link "file:" (match-string 1 file))))
6504 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6505 (expand-file-name file))
6506 (setq link (org-make-link
6507 "file:" (match-string 1 (expand-file-name file)))))
6508 (t (setq link (org-make-link "file:" file))))))
6510 ;; Read link, with completion for stored links.
6511 (with-output-to-temp-buffer "*Org Links*"
6512 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6513 (when org-stored-links
6514 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6515 (princ (mapconcat
6516 (lambda (x)
6517 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6518 (reverse org-stored-links) "\n"))))
6519 (let ((cw (selected-window)))
6520 (select-window (get-buffer-window "*Org Links*"))
6521 (shrink-window-if-larger-than-buffer)
6522 (setq truncate-lines t)
6523 (select-window cw))
6524 ;; Fake a link history, containing the stored links.
6525 (setq tmphist (append (mapcar 'car org-stored-links)
6526 org-insert-link-history))
6527 (unwind-protect
6528 (setq link (org-completing-read
6529 "Link: "
6530 (append
6531 (mapcar (lambda (x) (list (concat (car x) ":")))
6532 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6533 (mapcar (lambda (x) (list (concat x ":")))
6534 org-link-types))
6535 nil nil nil
6536 'tmphist
6537 (or (car (car org-stored-links)))))
6538 (set-window-configuration wcf)
6539 (kill-buffer "*Org Links*"))
6540 (setq entry (assoc link org-stored-links))
6541 (or entry (push link org-insert-link-history))
6542 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6543 (not org-keep-stored-link-after-insertion))
6544 (setq org-stored-links (delq (assoc link org-stored-links)
6545 org-stored-links)))
6546 (setq desc (or desc (nth 1 entry)))))
6548 (if (string-match org-plain-link-re link)
6549 ;; URL-like link, normalize the use of angular brackets.
6550 (setq link (org-make-link (org-remove-angle-brackets link))))
6552 ;; Check if we are linking to the current file with a search option
6553 ;; If yes, simplify the link by using only the search option.
6554 (when (and buffer-file-name
6555 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6556 (let* ((path (match-string 1 link))
6557 (case-fold-search nil)
6558 (search (match-string 2 link)))
6559 (save-match-data
6560 (if (equal (file-truename buffer-file-name) (file-truename path))
6561 ;; We are linking to this same file, with a search option
6562 (setq link search)))))
6564 ;; Check if we can/should use a relative path. If yes, simplify the link
6565 (when (string-match "\\<file:\\(.*\\)" link)
6566 (let* ((path (match-string 1 link))
6567 (origpath path)
6568 (case-fold-search nil))
6569 (cond
6570 ((eq org-link-file-path-type 'absolute)
6571 (setq path (abbreviate-file-name (expand-file-name path))))
6572 ((eq org-link-file-path-type 'noabbrev)
6573 (setq path (expand-file-name path)))
6574 ((eq org-link-file-path-type 'relative)
6575 (setq path (file-relative-name path)))
6577 (save-match-data
6578 (if (string-match (concat "^" (regexp-quote
6579 (file-name-as-directory
6580 (expand-file-name "."))))
6581 (expand-file-name path))
6582 ;; We are linking a file with relative path name.
6583 (setq path (substring (expand-file-name path)
6584 (match-end 0)))))))
6585 (setq link (concat "file:" path))
6586 (if (equal desc origpath)
6587 (setq desc path))))
6589 (if org-make-link-description-function
6590 (setq desc (funcall org-make-link-description-function link desc)))
6592 (setq desc (read-string "Description: " desc))
6593 (unless (string-match "\\S-" desc) (setq desc nil))
6594 (if remove (apply 'delete-region remove))
6595 (insert (org-make-link-string link desc))))
6597 (defun org-completing-read (&rest args)
6598 (let ((minibuffer-local-completion-map
6599 (copy-keymap minibuffer-local-completion-map)))
6600 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6601 (apply 'completing-read args)))
6603 ;;; Opening/following a link
6605 (defvar org-link-search-failed nil)
6607 (defun org-next-link ()
6608 "Move forward to the next link.
6609 If the link is in hidden text, expose it."
6610 (interactive)
6611 (when (and org-link-search-failed (eq this-command last-command))
6612 (goto-char (point-min))
6613 (message "Link search wrapped back to beginning of buffer"))
6614 (setq org-link-search-failed nil)
6615 (let* ((pos (point))
6616 (ct (org-context))
6617 (a (assoc :link ct)))
6618 (if a (goto-char (nth 2 a)))
6619 (if (re-search-forward org-any-link-re nil t)
6620 (progn
6621 (goto-char (match-beginning 0))
6622 (if (org-invisible-p) (org-show-context)))
6623 (goto-char pos)
6624 (setq org-link-search-failed t)
6625 (error "No further link found"))))
6627 (defun org-previous-link ()
6628 "Move backward to the previous link.
6629 If the link is in hidden text, expose it."
6630 (interactive)
6631 (when (and org-link-search-failed (eq this-command last-command))
6632 (goto-char (point-max))
6633 (message "Link search wrapped back to end of buffer"))
6634 (setq org-link-search-failed nil)
6635 (let* ((pos (point))
6636 (ct (org-context))
6637 (a (assoc :link ct)))
6638 (if a (goto-char (nth 1 a)))
6639 (if (re-search-backward org-any-link-re nil t)
6640 (progn
6641 (goto-char (match-beginning 0))
6642 (if (org-invisible-p) (org-show-context)))
6643 (goto-char pos)
6644 (setq org-link-search-failed t)
6645 (error "No further link found"))))
6647 (defun org-find-file-at-mouse (ev)
6648 "Open file link or URL at mouse."
6649 (interactive "e")
6650 (mouse-set-point ev)
6651 (org-open-at-point 'in-emacs))
6653 (defun org-open-at-mouse (ev)
6654 "Open file link or URL at mouse."
6655 (interactive "e")
6656 (mouse-set-point ev)
6657 (org-open-at-point))
6659 (defvar org-window-config-before-follow-link nil
6660 "The window configuration before following a link.
6661 This is saved in case the need arises to restore it.")
6663 (defvar org-open-link-marker (make-marker)
6664 "Marker pointing to the location where `org-open-at-point; was called.")
6666 ;;;###autoload
6667 (defun org-open-at-point-global ()
6668 "Follow a link like Org-mode does.
6669 This command can be called in any mode to follow a link that has
6670 Org-mode syntax."
6671 (interactive)
6672 (org-run-like-in-org-mode 'org-open-at-point))
6674 ;;;###autoload
6675 (defun org-open-link-from-string (s &optional arg)
6676 "Open a link in the string S, as if it was in Org-mode."
6677 (interactive "sLink: \nP")
6678 (with-temp-buffer
6679 (let ((org-inhibit-startup t))
6680 (org-mode)
6681 (insert s)
6682 (goto-char (point-min))
6683 (org-open-at-point arg))))
6685 (defun org-open-at-point (&optional in-emacs)
6686 "Open link at or after point.
6687 If there is no link at point, this function will search forward up to
6688 the end of the current subtree.
6689 Normally, files will be opened by an appropriate application. If the
6690 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6691 (interactive "P")
6692 (org-load-modules-maybe)
6693 (move-marker org-open-link-marker (point))
6694 (setq org-window-config-before-follow-link (current-window-configuration))
6695 (org-remove-occur-highlights nil nil t)
6696 (if (org-at-timestamp-p t)
6697 (org-follow-timestamp-link)
6698 (let (type path link line search (pos (point)))
6699 (catch 'match
6700 (save-excursion
6701 (skip-chars-forward "^]\n\r")
6702 (when (org-in-regexp org-bracket-link-regexp)
6703 (setq link (org-link-unescape (org-match-string-no-properties 1)))
6704 (while (string-match " *\n *" link)
6705 (setq link (replace-match " " t t link)))
6706 (setq link (org-link-expand-abbrev link))
6707 (if (string-match org-link-re-with-space2 link)
6708 (setq type (match-string 1 link) path (match-string 2 link))
6709 (setq type "thisfile" path link))
6710 (throw 'match t)))
6712 (when (get-text-property (point) 'org-linked-text)
6713 (setq type "thisfile"
6714 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6715 (1+ (point)) (point))
6716 path (buffer-substring
6717 (previous-single-property-change pos 'org-linked-text)
6718 (next-single-property-change pos 'org-linked-text)))
6719 (throw 'match t))
6721 (save-excursion
6722 (when (or (org-in-regexp org-angle-link-re)
6723 (org-in-regexp org-plain-link-re))
6724 (setq type (match-string 1) path (match-string 2))
6725 (throw 'match t)))
6726 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6727 (setq type "tree-match"
6728 path (match-string 1))
6729 (throw 'match t))
6730 (save-excursion
6731 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6732 (setq type "tags"
6733 path (match-string 1))
6734 (while (string-match ":" path)
6735 (setq path (replace-match "+" t t path)))
6736 (throw 'match t))))
6737 (unless path
6738 (error "No link found"))
6739 ;; Remove any trailing spaces in path
6740 (if (string-match " +\\'" path)
6741 (setq path (replace-match "" t t path)))
6743 (cond
6745 ((assoc type org-link-protocols)
6746 (funcall (nth 1 (assoc type org-link-protocols)) path))
6748 ((equal type "mailto")
6749 (let ((cmd (car org-link-mailto-program))
6750 (args (cdr org-link-mailto-program)) args1
6751 (address path) (subject "") a)
6752 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6753 (setq address (match-string 1 path)
6754 subject (org-link-escape (match-string 2 path))))
6755 (while args
6756 (cond
6757 ((not (stringp (car args))) (push (pop args) args1))
6758 (t (setq a (pop args))
6759 (if (string-match "%a" a)
6760 (setq a (replace-match address t t a)))
6761 (if (string-match "%s" a)
6762 (setq a (replace-match subject t t a)))
6763 (push a args1))))
6764 (apply cmd (nreverse args1))))
6766 ((member type '("http" "https" "ftp" "news"))
6767 (browse-url (concat type ":" (org-link-escape
6768 path org-link-escape-chars-browser))))
6770 ((member type '("message"))
6771 (browse-url (concat type ":" path)))
6773 ((string= type "tags")
6774 (org-tags-view in-emacs path))
6775 ((string= type "thisfile")
6776 (if in-emacs
6777 (switch-to-buffer-other-window
6778 (org-get-buffer-for-internal-link (current-buffer)))
6779 (org-mark-ring-push))
6780 (let ((cmd `(org-link-search
6781 ,path
6782 ,(cond ((equal in-emacs '(4)) 'occur)
6783 ((equal in-emacs '(16)) 'org-occur)
6784 (t nil))
6785 ,pos)))
6786 (condition-case nil (eval cmd)
6787 (error (progn (widen) (eval cmd))))))
6789 ((string= type "tree-match")
6790 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6792 ((string= type "file")
6793 (if (string-match "::\\([0-9]+\\)\\'" path)
6794 (setq line (string-to-number (match-string 1 path))
6795 path (substring path 0 (match-beginning 0)))
6796 (if (string-match "::\\(.+\\)\\'" path)
6797 (setq search (match-string 1 path)
6798 path (substring path 0 (match-beginning 0)))))
6799 (if (string-match "[*?{]" (file-name-nondirectory path))
6800 (dired path)
6801 (org-open-file path in-emacs line search)))
6803 ((string= type "news")
6804 (require 'org-gnus)
6805 (org-gnus-follow-link path))
6807 ((string= type "shell")
6808 (let ((cmd path))
6809 (if (or (not org-confirm-shell-link-function)
6810 (funcall org-confirm-shell-link-function
6811 (format "Execute \"%s\" in shell? "
6812 (org-add-props cmd nil
6813 'face 'org-warning))))
6814 (progn
6815 (message "Executing %s" cmd)
6816 (shell-command cmd))
6817 (error "Abort"))))
6819 ((string= type "elisp")
6820 (let ((cmd path))
6821 (if (or (not org-confirm-elisp-link-function)
6822 (funcall org-confirm-elisp-link-function
6823 (format "Execute \"%s\" as elisp? "
6824 (org-add-props cmd nil
6825 'face 'org-warning))))
6826 (message "%s => %s" cmd (eval (read cmd)))
6827 (error "Abort"))))
6830 (browse-url-at-point)))))
6831 (move-marker org-open-link-marker nil)
6832 (run-hook-with-args 'org-follow-link-hook))
6834 ;;;; Time estimates
6836 (defun org-get-effort (&optional pom)
6837 "Get the effort estimate for the current entry."
6838 (org-entry-get pom org-effort-property))
6840 ;;; File search
6842 (defvar org-create-file-search-functions nil
6843 "List of functions to construct the right search string for a file link.
6844 These functions are called in turn with point at the location to
6845 which the link should point.
6847 A function in the hook should first test if it would like to
6848 handle this file type, for example by checking the major-mode or
6849 the file extension. If it decides not to handle this file, it
6850 should just return nil to give other functions a chance. If it
6851 does handle the file, it must return the search string to be used
6852 when following the link. The search string will be part of the
6853 file link, given after a double colon, and `org-open-at-point'
6854 will automatically search for it. If special measures must be
6855 taken to make the search successful, another function should be
6856 added to the companion hook `org-execute-file-search-functions',
6857 which see.
6859 A function in this hook may also use `setq' to set the variable
6860 `description' to provide a suggestion for the descriptive text to
6861 be used for this link when it gets inserted into an Org-mode
6862 buffer with \\[org-insert-link].")
6864 (defvar org-execute-file-search-functions nil
6865 "List of functions to execute a file search triggered by a link.
6867 Functions added to this hook must accept a single argument, the
6868 search string that was part of the file link, the part after the
6869 double colon. The function must first check if it would like to
6870 handle this search, for example by checking the major-mode or the
6871 file extension. If it decides not to handle this search, it
6872 should just return nil to give other functions a chance. If it
6873 does handle the search, it must return a non-nil value to keep
6874 other functions from trying.
6876 Each function can access the current prefix argument through the
6877 variable `current-prefix-argument'. Note that a single prefix is
6878 used to force opening a link in Emacs, so it may be good to only
6879 use a numeric or double prefix to guide the search function.
6881 In case this is needed, a function in this hook can also restore
6882 the window configuration before `org-open-at-point' was called using:
6884 (set-window-configuration org-window-config-before-follow-link)")
6886 (defun org-link-search (s &optional type avoid-pos)
6887 "Search for a link search option.
6888 If S is surrounded by forward slashes, it is interpreted as a
6889 regular expression. In org-mode files, this will create an `org-occur'
6890 sparse tree. In ordinary files, `occur' will be used to list matches.
6891 If the current buffer is in `dired-mode', grep will be used to search
6892 in all files. If AVOID-POS is given, ignore matches near that position."
6893 (let ((case-fold-search t)
6894 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6895 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6896 (append '(("") (" ") ("\t") ("\n"))
6897 org-emphasis-alist)
6898 "\\|") "\\)"))
6899 (pos (point))
6900 (pre nil) (post nil)
6901 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6902 (cond
6903 ;; First check if there are any special
6904 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6905 ;; Now try the builtin stuff
6906 ((save-excursion
6907 (goto-char (point-min))
6908 (and
6909 (re-search-forward
6910 (concat "<<" (regexp-quote s0) ">>") nil t)
6911 (setq type 'dedicated
6912 pos (match-beginning 0))))
6913 ;; There is an exact target for this
6914 (goto-char pos))
6915 ((string-match "^/\\(.*\\)/$" s)
6916 ;; A regular expression
6917 (cond
6918 ((org-mode-p)
6919 (org-occur (match-string 1 s)))
6920 ;;((eq major-mode 'dired-mode)
6921 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6922 (t (org-do-occur (match-string 1 s)))))
6924 ;; A normal search strings
6925 (when (equal (string-to-char s) ?*)
6926 ;; Anchor on headlines, post may include tags.
6927 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6928 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6929 s (substring s 1)))
6930 (remove-text-properties
6931 0 (length s)
6932 '(face nil mouse-face nil keymap nil fontified nil) s)
6933 ;; Make a series of regular expressions to find a match
6934 (setq words (org-split-string s "[ \n\r\t]+")
6936 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6937 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6938 "\\)" markers)
6939 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6940 re2a (concat "[ \t\r\n]" re2a_)
6941 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6942 re4 (concat "[^a-zA-Z_]" re4_)
6944 re1 (concat pre re2 post)
6945 re3 (concat pre (if pre re4_ re4) post)
6946 re5 (concat pre ".*" re4)
6947 re2 (concat pre re2)
6948 re2a (concat pre (if pre re2a_ re2a))
6949 re4 (concat pre (if pre re4_ re4))
6950 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6951 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6952 re5 "\\)"
6954 (cond
6955 ((eq type 'org-occur) (org-occur reall))
6956 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6957 (t (goto-char (point-min))
6958 (setq type 'fuzzy)
6959 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
6960 (org-search-not-self 1 re1 nil t)
6961 (org-search-not-self 1 re2 nil t)
6962 (org-search-not-self 1 re2a nil t)
6963 (org-search-not-self 1 re3 nil t)
6964 (org-search-not-self 1 re4 nil t)
6965 (org-search-not-self 1 re5 nil t)
6967 (goto-char (match-beginning 1))
6968 (goto-char pos)
6969 (error "No match")))))
6971 ;; Normal string-search
6972 (goto-char (point-min))
6973 (if (search-forward s nil t)
6974 (goto-char (match-beginning 0))
6975 (error "No match"))))
6976 (and (org-mode-p) (org-show-context 'link-search))
6977 type))
6979 (defun org-search-not-self (group &rest args)
6980 "Execute `re-search-forward', but only accept matches that do not
6981 enclose the position of `org-open-link-marker'."
6982 (let ((m org-open-link-marker))
6983 (catch 'exit
6984 (while (apply 're-search-forward args)
6985 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
6986 (goto-char (match-end group))
6987 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
6988 (> (match-beginning 0) (marker-position m))
6989 (< (match-end 0) (marker-position m)))
6990 (save-match-data
6991 (or (not (org-in-regexp
6992 org-bracket-link-analytic-regexp 1))
6993 (not (match-end 4)) ; no description
6994 (and (<= (match-beginning 4) (point))
6995 (>= (match-end 4) (point))))))
6996 (throw 'exit (point))))))))
6998 (defun org-get-buffer-for-internal-link (buffer)
6999 "Return a buffer to be used for displaying the link target of internal links."
7000 (cond
7001 ((not org-display-internal-link-with-indirect-buffer)
7002 buffer)
7003 ((string-match "(Clone)$" (buffer-name buffer))
7004 (message "Buffer is already a clone, not making another one")
7005 ;; we also do not modify visibility in this case
7006 buffer)
7007 (t ; make a new indirect buffer for displaying the link
7008 (let* ((bn (buffer-name buffer))
7009 (ibn (concat bn "(Clone)"))
7010 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7011 (with-current-buffer ib (org-overview))
7012 ib))))
7014 (defun org-do-occur (regexp &optional cleanup)
7015 "Call the Emacs command `occur'.
7016 If CLEANUP is non-nil, remove the printout of the regular expression
7017 in the *Occur* buffer. This is useful if the regex is long and not useful
7018 to read."
7019 (occur regexp)
7020 (when cleanup
7021 (let ((cwin (selected-window)) win beg end)
7022 (when (setq win (get-buffer-window "*Occur*"))
7023 (select-window win))
7024 (goto-char (point-min))
7025 (when (re-search-forward "match[a-z]+" nil t)
7026 (setq beg (match-end 0))
7027 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7028 (setq end (1- (match-beginning 0)))))
7029 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7030 (goto-char (point-min))
7031 (select-window cwin))))
7033 ;;; The mark ring for links jumps
7035 (defvar org-mark-ring nil
7036 "Mark ring for positions before jumps in Org-mode.")
7037 (defvar org-mark-ring-last-goto nil
7038 "Last position in the mark ring used to go back.")
7039 ;; Fill and close the ring
7040 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7041 (loop for i from 1 to org-mark-ring-length do
7042 (push (make-marker) org-mark-ring))
7043 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7044 org-mark-ring)
7046 (defun org-mark-ring-push (&optional pos buffer)
7047 "Put the current position or POS into the mark ring and rotate it."
7048 (interactive)
7049 (setq pos (or pos (point)))
7050 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7051 (move-marker (car org-mark-ring)
7052 (or pos (point))
7053 (or buffer (current-buffer)))
7054 (message "%s"
7055 (substitute-command-keys
7056 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7058 (defun org-mark-ring-goto (&optional n)
7059 "Jump to the previous position in the mark ring.
7060 With prefix arg N, jump back that many stored positions. When
7061 called several times in succession, walk through the entire ring.
7062 Org-mode commands jumping to a different position in the current file,
7063 or to another Org-mode file, automatically push the old position
7064 onto the ring."
7065 (interactive "p")
7066 (let (p m)
7067 (if (eq last-command this-command)
7068 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7069 (setq p org-mark-ring))
7070 (setq org-mark-ring-last-goto p)
7071 (setq m (car p))
7072 (switch-to-buffer (marker-buffer m))
7073 (goto-char m)
7074 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7076 (defun org-remove-angle-brackets (s)
7077 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7078 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7080 (defun org-add-angle-brackets (s)
7081 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7082 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7085 ;;; Following specific links
7087 (defun org-follow-timestamp-link ()
7088 (cond
7089 ((org-at-date-range-p t)
7090 (let ((org-agenda-start-on-weekday)
7091 (t1 (match-string 1))
7092 (t2 (match-string 2)))
7093 (setq t1 (time-to-days (org-time-string-to-time t1))
7094 t2 (time-to-days (org-time-string-to-time t2)))
7095 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7096 ((org-at-timestamp-p t)
7097 (org-agenda-list nil (time-to-days (org-time-string-to-time
7098 (substring (match-string 1) 0 10)))
7100 (t (error "This should not happen"))))
7103 ;;; Following file links
7104 (defvar org-wait nil)
7105 (defun org-open-file (path &optional in-emacs line search)
7106 "Open the file at PATH.
7107 First, this expands any special file name abbreviations. Then the
7108 configuration variable `org-file-apps' is checked if it contains an
7109 entry for this file type, and if yes, the corresponding command is launched.
7110 If no application is found, Emacs simply visits the file.
7111 With optional argument IN-EMACS, Emacs will visit the file.
7112 Optional LINE specifies a line to go to, optional SEARCH a string to
7113 search for. If LINE or SEARCH is given, the file will always be
7114 opened in Emacs.
7115 If the file does not exist, an error is thrown."
7116 (setq in-emacs (or in-emacs line search))
7117 (let* ((file (if (equal path "")
7118 buffer-file-name
7119 (substitute-in-file-name (expand-file-name path))))
7120 (apps (append org-file-apps (org-default-apps)))
7121 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7122 (dirp (if remp nil (file-directory-p file)))
7123 (dfile (downcase file))
7124 (old-buffer (current-buffer))
7125 (old-pos (point))
7126 (old-mode major-mode)
7127 ext cmd)
7128 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7129 (setq ext (match-string 1 dfile))
7130 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7131 (setq ext (match-string 1 dfile))))
7132 (if in-emacs
7133 (setq cmd 'emacs)
7134 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7135 (and dirp (cdr (assoc 'directory apps)))
7136 (cdr (assoc ext apps))
7137 (cdr (assoc t apps)))))
7138 (when (eq cmd 'mailcap)
7139 (require 'mailcap)
7140 (mailcap-parse-mailcaps)
7141 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7142 (command (mailcap-mime-info mime-type)))
7143 (if (stringp command)
7144 (setq cmd command)
7145 (setq cmd 'emacs))))
7146 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7147 (not (file-exists-p file))
7148 (not org-open-non-existing-files))
7149 (error "No such file: %s" file))
7150 (cond
7151 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7152 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7153 (while (string-match "['\"]%s['\"]" cmd)
7154 (setq cmd (replace-match "%s" t t cmd)))
7155 (while (string-match "%s" cmd)
7156 (setq cmd (replace-match
7157 (save-match-data (shell-quote-argument file))
7158 t t cmd)))
7159 (save-window-excursion
7160 (start-process-shell-command cmd nil cmd)
7161 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7163 ((or (stringp cmd)
7164 (eq cmd 'emacs))
7165 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7166 (widen)
7167 (if line (goto-line line)
7168 (if search (org-link-search search))))
7169 ((consp cmd)
7170 (eval cmd))
7171 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7172 (and (org-mode-p) (eq old-mode 'org-mode)
7173 (or (not (equal old-buffer (current-buffer)))
7174 (not (equal old-pos (point))))
7175 (org-mark-ring-push old-pos old-buffer))))
7177 (defun org-default-apps ()
7178 "Return the default applications for this operating system."
7179 (cond
7180 ((eq system-type 'darwin)
7181 org-file-apps-defaults-macosx)
7182 ((eq system-type 'windows-nt)
7183 org-file-apps-defaults-windowsnt)
7184 (t org-file-apps-defaults-gnu)))
7186 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7187 (defun org-file-remote-p (file)
7188 "Test whether FILE specifies a location on a remote system.
7189 Return non-nil if the location is indeed remote.
7191 For example, the filename \"/user@host:/foo\" specifies a location
7192 on the system \"/user@host:\"."
7193 (cond ((fboundp 'file-remote-p)
7194 (file-remote-p file))
7195 ((fboundp 'tramp-handle-file-remote-p)
7196 (tramp-handle-file-remote-p file))
7197 ((and (boundp 'ange-ftp-name-format)
7198 (string-match (car ange-ftp-name-format) file))
7200 (t nil)))
7203 ;;;; Refiling
7205 (defun org-get-org-file ()
7206 "Read a filename, with default directory `org-directory'."
7207 (let ((default (or org-default-notes-file remember-data-file)))
7208 (read-file-name (format "File name [%s]: " default)
7209 (file-name-as-directory org-directory)
7210 default)))
7212 (defun org-notes-order-reversed-p ()
7213 "Check if the current file should receive notes in reversed order."
7214 (cond
7215 ((not org-reverse-note-order) nil)
7216 ((eq t org-reverse-note-order) t)
7217 ((not (listp org-reverse-note-order)) nil)
7218 (t (catch 'exit
7219 (let ((all org-reverse-note-order)
7220 entry)
7221 (while (setq entry (pop all))
7222 (if (string-match (car entry) buffer-file-name)
7223 (throw 'exit (cdr entry))))
7224 nil)))))
7226 (defvar org-refile-target-table nil
7227 "The list of refile targets, created by `org-refile'.")
7229 (defvar org-agenda-new-buffers nil
7230 "Buffers created to visit agenda files.")
7232 (defun org-get-refile-targets (&optional default-buffer)
7233 "Produce a table with refile targets."
7234 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7235 targets txt re files f desc descre)
7236 (with-current-buffer (or default-buffer (current-buffer))
7237 (while (setq entry (pop entries))
7238 (setq files (car entry) desc (cdr entry))
7239 (cond
7240 ((null files) (setq files (list (current-buffer))))
7241 ((eq files 'org-agenda-files)
7242 (setq files (org-agenda-files 'unrestricted)))
7243 ((and (symbolp files) (fboundp files))
7244 (setq files (funcall files)))
7245 ((and (symbolp files) (boundp files))
7246 (setq files (symbol-value files))))
7247 (if (stringp files) (setq files (list files)))
7248 (cond
7249 ((eq (car desc) :tag)
7250 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7251 ((eq (car desc) :todo)
7252 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7253 ((eq (car desc) :regexp)
7254 (setq descre (cdr desc)))
7255 ((eq (car desc) :level)
7256 (setq descre (concat "^\\*\\{" (number-to-string
7257 (if org-odd-levels-only
7258 (1- (* 2 (cdr desc)))
7259 (cdr desc)))
7260 "\\}[ \t]")))
7261 ((eq (car desc) :maxlevel)
7262 (setq descre (concat "^\\*\\{1," (number-to-string
7263 (if org-odd-levels-only
7264 (1- (* 2 (cdr desc)))
7265 (cdr desc)))
7266 "\\}[ \t]")))
7267 (t (error "Bad refiling target description %s" desc)))
7268 (while (setq f (pop files))
7269 (save-excursion
7270 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7271 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7272 (save-excursion
7273 (save-restriction
7274 (widen)
7275 (goto-char (point-min))
7276 (while (re-search-forward descre nil t)
7277 (goto-char (point-at-bol))
7278 (when (looking-at org-complex-heading-regexp)
7279 (setq txt (match-string 4)
7280 re (concat "^" (regexp-quote
7281 (buffer-substring (match-beginning 1)
7282 (match-end 4)))))
7283 (if (match-end 5) (setq re (concat re "[ \t]+"
7284 (regexp-quote
7285 (match-string 5)))))
7286 (setq re (concat re "[ \t]*$"))
7287 (when org-refile-use-outline-path
7288 (setq txt (mapconcat 'identity
7289 (append
7290 (if (eq org-refile-use-outline-path 'file)
7291 (list (file-name-nondirectory
7292 (buffer-file-name (buffer-base-buffer))))
7293 (if (eq org-refile-use-outline-path 'full-file-path)
7294 (list (buffer-file-name (buffer-base-buffer)))))
7295 (org-get-outline-path)
7296 (list txt))
7297 "/")))
7298 (push (list txt f re (point)) targets))
7299 (goto-char (point-at-eol))))))))
7300 (nreverse targets))))
7302 (defun org-get-outline-path ()
7303 "Return the outline path to the current entry, as a list."
7304 (let (rtn)
7305 (save-excursion
7306 (while (org-up-heading-safe)
7307 (when (looking-at org-complex-heading-regexp)
7308 (push (org-match-string-no-properties 4) rtn)))
7309 rtn)))
7311 (defvar org-refile-history nil
7312 "History for refiling operations.")
7314 (defun org-refile (&optional goto default-buffer)
7315 "Move the entry at point to another heading.
7316 The list of target headings is compiled using the information in
7317 `org-refile-targets', which see. This list is created before each use
7318 and will therefore always be up-to-date.
7320 At the target location, the entry is filed as a subitem of the target heading.
7321 Depending on `org-reverse-note-order', the new subitem will either be the
7322 first of the last subitem.
7324 With prefix arg GOTO, the command will only visit the target location,
7325 not actually move anything.
7326 With a double prefix `C-c C-c', go to the location where the last refiling
7327 operation has put the subtree."
7328 (interactive "P")
7329 (let* ((cbuf (current-buffer))
7330 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7331 pos it nbuf file re level reversed)
7332 (if (equal goto '(16))
7333 (org-refile-goto-last-stored)
7334 (when (setq it (org-refile-get-location
7335 (if goto "Goto: " "Refile to: ") default-buffer))
7336 (setq file (nth 1 it)
7337 re (nth 2 it)
7338 pos (nth 3 it))
7339 (setq nbuf (or (find-buffer-visiting file)
7340 (find-file-noselect file)))
7341 (if goto
7342 (progn
7343 (switch-to-buffer nbuf)
7344 (goto-char pos)
7345 (org-show-context 'org-goto))
7346 (org-copy-special)
7347 (save-excursion
7348 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7349 (find-file-noselect file))))
7350 (setq reversed (org-notes-order-reversed-p))
7351 (save-excursion
7352 (save-restriction
7353 (widen)
7354 (goto-char pos)
7355 (looking-at outline-regexp)
7356 (setq level (org-get-valid-level (funcall outline-level) 1))
7357 (goto-char
7358 (if reversed
7359 (outline-next-heading)
7360 (or (save-excursion (outline-get-next-sibling))
7361 (org-end-of-subtree t t)
7362 (point-max))))
7363 (bookmark-set "org-refile-last-stored")
7364 (org-paste-subtree level))))
7365 (org-cut-special)
7366 (message "Entry refiled to \"%s\"" (car it)))))))
7368 (defun org-refile-goto-last-stored ()
7369 "Go to the location where the last refile was stored."
7370 (interactive)
7371 (bookmark-jump "org-refile-last-stored")
7372 (message "This is the location of the last refile"))
7374 (defun org-refile-get-location (&optional prompt default-buffer)
7375 "Prompt the user for a refile location, using PROMPT."
7376 (let ((org-refile-targets org-refile-targets)
7377 (org-refile-use-outline-path org-refile-use-outline-path))
7378 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7379 (unless org-refile-target-table
7380 (error "No refile targets"))
7381 (let* ((cbuf (current-buffer))
7382 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7383 (fname (and filename (file-truename filename)))
7384 (tbl (mapcar
7385 (lambda (x)
7386 (if (not (equal fname (file-truename (nth 1 x))))
7387 (cons (concat (car x) " (" (file-name-nondirectory
7388 (nth 1 x)) ")")
7389 (cdr x))
7391 org-refile-target-table))
7392 (completion-ignore-case t))
7393 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
7394 tbl)))
7396 ;;;; Dynamic blocks
7398 (defun org-find-dblock (name)
7399 "Find the first dynamic block with name NAME in the buffer.
7400 If not found, stay at current position and return nil."
7401 (let (pos)
7402 (save-excursion
7403 (goto-char (point-min))
7404 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7405 nil t)
7406 (match-beginning 0))))
7407 (if pos (goto-char pos))
7408 pos))
7410 (defconst org-dblock-start-re
7411 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7412 "Matches the startline of a dynamic block, with parameters.")
7414 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7415 "Matches the end of a dyhamic block.")
7417 (defun org-create-dblock (plist)
7418 "Create a dynamic block section, with parameters taken from PLIST.
7419 PLIST must containe a :name entry which is used as name of the block."
7420 (unless (bolp) (newline))
7421 (let ((name (plist-get plist :name)))
7422 (insert "#+BEGIN: " name)
7423 (while plist
7424 (if (eq (car plist) :name)
7425 (setq plist (cddr plist))
7426 (insert " " (prin1-to-string (pop plist)))))
7427 (insert "\n\n#+END:\n")
7428 (beginning-of-line -2)))
7430 (defun org-prepare-dblock ()
7431 "Prepare dynamic block for refresh.
7432 This empties the block, puts the cursor at the insert position and returns
7433 the property list including an extra property :name with the block name."
7434 (unless (looking-at org-dblock-start-re)
7435 (error "Not at a dynamic block"))
7436 (let* ((begdel (1+ (match-end 0)))
7437 (name (org-no-properties (match-string 1)))
7438 (params (append (list :name name)
7439 (read (concat "(" (match-string 3) ")")))))
7440 (unless (re-search-forward org-dblock-end-re nil t)
7441 (error "Dynamic block not terminated"))
7442 (setq params
7443 (append params
7444 (list :content (buffer-substring
7445 begdel (match-beginning 0)))))
7446 (delete-region begdel (match-beginning 0))
7447 (goto-char begdel)
7448 (open-line 1)
7449 params))
7451 (defun org-map-dblocks (&optional command)
7452 "Apply COMMAND to all dynamic blocks in the current buffer.
7453 If COMMAND is not given, use `org-update-dblock'."
7454 (let ((cmd (or command 'org-update-dblock))
7455 pos)
7456 (save-excursion
7457 (goto-char (point-min))
7458 (while (re-search-forward org-dblock-start-re nil t)
7459 (goto-char (setq pos (match-beginning 0)))
7460 (condition-case nil
7461 (funcall cmd)
7462 (error (message "Error during update of dynamic block")))
7463 (goto-char pos)
7464 (unless (re-search-forward org-dblock-end-re nil t)
7465 (error "Dynamic block not terminated"))))))
7467 (defun org-dblock-update (&optional arg)
7468 "User command for updating dynamic blocks.
7469 Update the dynamic block at point. With prefix ARG, update all dynamic
7470 blocks in the buffer."
7471 (interactive "P")
7472 (if arg
7473 (org-update-all-dblocks)
7474 (or (looking-at org-dblock-start-re)
7475 (org-beginning-of-dblock))
7476 (org-update-dblock)))
7478 (defun org-update-dblock ()
7479 "Update the dynamic block at point
7480 This means to empty the block, parse for parameters and then call
7481 the correct writing function."
7482 (save-window-excursion
7483 (let* ((pos (point))
7484 (line (org-current-line))
7485 (params (org-prepare-dblock))
7486 (name (plist-get params :name))
7487 (cmd (intern (concat "org-dblock-write:" name))))
7488 (message "Updating dynamic block `%s' at line %d..." name line)
7489 (funcall cmd params)
7490 (message "Updating dynamic block `%s' at line %d...done" name line)
7491 (goto-char pos))))
7493 (defun org-beginning-of-dblock ()
7494 "Find the beginning of the dynamic block at point.
7495 Error if there is no scuh block at point."
7496 (let ((pos (point))
7497 beg)
7498 (end-of-line 1)
7499 (if (and (re-search-backward org-dblock-start-re nil t)
7500 (setq beg (match-beginning 0))
7501 (re-search-forward org-dblock-end-re nil t)
7502 (> (match-end 0) pos))
7503 (goto-char beg)
7504 (goto-char pos)
7505 (error "Not in a dynamic block"))))
7507 (defun org-update-all-dblocks ()
7508 "Update all dynamic blocks in the buffer.
7509 This function can be used in a hook."
7510 (when (org-mode-p)
7511 (org-map-dblocks 'org-update-dblock)))
7514 ;;;; Completion
7516 (defconst org-additional-option-like-keywords
7517 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7518 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7519 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7521 (defun org-complete (&optional arg)
7522 "Perform completion on word at point.
7523 At the beginning of a headline, this completes TODO keywords as given in
7524 `org-todo-keywords'.
7525 If the current word is preceded by a backslash, completes the TeX symbols
7526 that are supported for HTML support.
7527 If the current word is preceded by \"#+\", completes special words for
7528 setting file options.
7529 In the line after \"#+STARTUP:, complete valid keywords.\"
7530 At all other locations, this simply calls the value of
7531 `org-completion-fallback-command'."
7532 (interactive "P")
7533 (org-without-partial-completion
7534 (catch 'exit
7535 (let* ((end (point))
7536 (beg1 (save-excursion
7537 (skip-chars-backward (org-re "[:alnum:]_@"))
7538 (point)))
7539 (beg (save-excursion
7540 (skip-chars-backward "a-zA-Z0-9_:$")
7541 (point)))
7542 (confirm (lambda (x) (stringp (car x))))
7543 (searchhead (equal (char-before beg) ?*))
7544 (tag (and (equal (char-before beg1) ?:)
7545 (equal (char-after (point-at-bol)) ?*)))
7546 (prop (and (equal (char-before beg1) ?:)
7547 (not (equal (char-after (point-at-bol)) ?*))))
7548 (texp (equal (char-before beg) ?\\))
7549 (link (equal (char-before beg) ?\[))
7550 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7551 beg)
7552 "#+"))
7553 (startup (string-match "^#\\+STARTUP:.*"
7554 (buffer-substring (point-at-bol) (point))))
7555 (completion-ignore-case opt)
7556 (type nil)
7557 (tbl nil)
7558 (table (cond
7559 (opt
7560 (setq type :opt)
7561 (require 'org-exp)
7562 (append
7563 (mapcar
7564 (lambda (x)
7565 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7566 (cons (match-string 2 x) (match-string 1 x)))
7567 (org-split-string (org-get-current-options) "\n"))
7568 (mapcar 'list org-additional-option-like-keywords)))
7569 (startup
7570 (setq type :startup)
7571 org-startup-options)
7572 (link (append org-link-abbrev-alist-local
7573 org-link-abbrev-alist))
7574 (texp
7575 (setq type :tex)
7576 org-html-entities)
7577 ((string-match "\\`\\*+[ \t]+\\'"
7578 (buffer-substring (point-at-bol) beg))
7579 (setq type :todo)
7580 (mapcar 'list org-todo-keywords-1))
7581 (searchhead
7582 (setq type :searchhead)
7583 (save-excursion
7584 (goto-char (point-min))
7585 (while (re-search-forward org-todo-line-regexp nil t)
7586 (push (list
7587 (org-make-org-heading-search-string
7588 (match-string 3) t))
7589 tbl)))
7590 tbl)
7591 (tag (setq type :tag beg beg1)
7592 (or org-tag-alist (org-get-buffer-tags)))
7593 (prop (setq type :prop beg beg1)
7594 (mapcar 'list (org-buffer-property-keys nil t t)))
7595 (t (progn
7596 (call-interactively org-completion-fallback-command)
7597 (throw 'exit nil)))))
7598 (pattern (buffer-substring-no-properties beg end))
7599 (completion (try-completion pattern table confirm)))
7600 (cond ((eq completion t)
7601 (if (not (assoc (upcase pattern) table))
7602 (message "Already complete")
7603 (if (and (equal type :opt)
7604 (not (member (car (assoc (upcase pattern) table))
7605 org-additional-option-like-keywords)))
7606 (insert (substring (cdr (assoc (upcase pattern) table))
7607 (length pattern)))
7608 (if (memq type '(:tag :prop)) (insert ":")))))
7609 ((null completion)
7610 (message "Can't find completion for \"%s\"" pattern)
7611 (ding))
7612 ((not (string= pattern completion))
7613 (delete-region beg end)
7614 (if (string-match " +$" completion)
7615 (setq completion (replace-match "" t t completion)))
7616 (insert completion)
7617 (if (get-buffer-window "*Completions*")
7618 (delete-window (get-buffer-window "*Completions*")))
7619 (if (assoc completion table)
7620 (if (eq type :todo) (insert " ")
7621 (if (memq type '(:tag :prop)) (insert ":"))))
7622 (if (and (equal type :opt) (assoc completion table))
7623 (message "%s" (substitute-command-keys
7624 "Press \\[org-complete] again to insert example settings"))))
7626 (message "Making completion list...")
7627 (let ((list (sort (all-completions pattern table confirm)
7628 'string<)))
7629 (with-output-to-temp-buffer "*Completions*"
7630 (condition-case nil
7631 ;; Protection needed for XEmacs and emacs 21
7632 (display-completion-list list pattern)
7633 (error (display-completion-list list)))))
7634 (message "Making completion list...%s" "done")))))))
7636 ;;;; TODO, DEADLINE, Comments
7638 (defun org-toggle-comment ()
7639 "Change the COMMENT state of an entry."
7640 (interactive)
7641 (save-excursion
7642 (org-back-to-heading)
7643 (let (case-fold-search)
7644 (if (looking-at (concat outline-regexp
7645 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7646 (replace-match "" t t nil 1)
7647 (if (looking-at outline-regexp)
7648 (progn
7649 (goto-char (match-end 0))
7650 (insert org-comment-string " ")))))))
7652 (defvar org-last-todo-state-is-todo nil
7653 "This is non-nil when the last TODO state change led to a TODO state.
7654 If the last change removed the TODO tag or switched to DONE, then
7655 this is nil.")
7657 (defvar org-setting-tags nil) ; dynamically skiped
7659 (defun org-parse-local-options (string var)
7660 "Parse STRING for startup setting relevant for variable VAR."
7661 (let ((rtn (symbol-value var))
7662 e opts)
7663 (save-match-data
7664 (if (or (not string) (not (string-match "\\S-" string)))
7666 (setq opts (delq nil (mapcar (lambda (x)
7667 (setq e (assoc x org-startup-options))
7668 (if (eq (nth 1 e) var) e nil))
7669 (org-split-string string "[ \t]+"))))
7670 (if (not opts)
7672 (setq rtn nil)
7673 (while (setq e (pop opts))
7674 (if (not (nth 3 e))
7675 (setq rtn (nth 2 e))
7676 (if (not (listp rtn)) (setq rtn nil))
7677 (push (nth 2 e) rtn)))
7678 rtn)))))
7680 (defvar org-blocker-hook nil
7681 "Hook for functions that are allowed to block a state change.
7683 Each function gets as its single argument a property list, see
7684 `org-trigger-hook' for more information about this list.
7686 If any of the functions in this hook returns nil, the state change
7687 is blocked.")
7689 (defvar org-trigger-hook nil
7690 "Hook for functions that are triggered by a state change.
7692 Each function gets as its single argument a property list with at least
7693 the following elements:
7695 (:type type-of-change :position pos-at-entry-start
7696 :from old-state :to new-state)
7698 Depending on the type, more properties may be present.
7700 This mechanism is currently implemented for:
7702 TODO state changes
7703 ------------------
7704 :type todo-state-change
7705 :from previous state (keyword as a string), or nil
7706 :to new state (keyword as a string), or nil")
7709 (defun org-todo (&optional arg)
7710 "Change the TODO state of an item.
7711 The state of an item is given by a keyword at the start of the heading,
7712 like
7713 *** TODO Write paper
7714 *** DONE Call mom
7716 The different keywords are specified in the variable `org-todo-keywords'.
7717 By default the available states are \"TODO\" and \"DONE\".
7718 So for this example: when the item starts with TODO, it is changed to DONE.
7719 When it starts with DONE, the DONE is removed. And when neither TODO nor
7720 DONE are present, add TODO at the beginning of the heading.
7722 With C-u prefix arg, use completion to determine the new state.
7723 With numeric prefix arg, switch to that state.
7725 For calling through lisp, arg is also interpreted in the following way:
7726 'none -> empty state
7727 \"\"(empty string) -> switch to empty state
7728 'done -> switch to DONE
7729 'nextset -> switch to the next set of keywords
7730 'previousset -> switch to the previous set of keywords
7731 \"WAITING\" -> switch to the specified keyword, but only if it
7732 really is a member of `org-todo-keywords'."
7733 (interactive "P")
7734 (save-excursion
7735 (catch 'exit
7736 (org-back-to-heading)
7737 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7738 (or (looking-at (concat " +" org-todo-regexp " *"))
7739 (looking-at " *"))
7740 (let* ((match-data (match-data))
7741 (startpos (point-at-bol))
7742 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7743 (org-log-done org-log-done)
7744 (org-log-repeat org-log-repeat)
7745 (org-todo-log-states org-todo-log-states)
7746 (this (match-string 1))
7747 (hl-pos (match-beginning 0))
7748 (head (org-get-todo-sequence-head this))
7749 (ass (assoc head org-todo-kwd-alist))
7750 (interpret (nth 1 ass))
7751 (done-word (nth 3 ass))
7752 (final-done-word (nth 4 ass))
7753 (last-state (or this ""))
7754 (completion-ignore-case t)
7755 (member (member this org-todo-keywords-1))
7756 (tail (cdr member))
7757 (state (cond
7758 ((and org-todo-key-trigger
7759 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7760 (and (not arg) org-use-fast-todo-selection
7761 (not (eq org-use-fast-todo-selection 'prefix)))))
7762 ;; Use fast selection
7763 (org-fast-todo-selection))
7764 ((and (equal arg '(4))
7765 (or (not org-use-fast-todo-selection)
7766 (not org-todo-key-trigger)))
7767 ;; Read a state with completion
7768 (completing-read "State: " (mapcar (lambda(x) (list x))
7769 org-todo-keywords-1)
7770 nil t))
7771 ((eq arg 'right)
7772 (if this
7773 (if tail (car tail) nil)
7774 (car org-todo-keywords-1)))
7775 ((eq arg 'left)
7776 (if (equal member org-todo-keywords-1)
7778 (if this
7779 (nth (- (length org-todo-keywords-1) (length tail) 2)
7780 org-todo-keywords-1)
7781 (org-last org-todo-keywords-1))))
7782 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7783 (setq arg nil))) ; hack to fall back to cycling
7784 (arg
7785 ;; user or caller requests a specific state
7786 (cond
7787 ((equal arg "") nil)
7788 ((eq arg 'none) nil)
7789 ((eq arg 'done) (or done-word (car org-done-keywords)))
7790 ((eq arg 'nextset)
7791 (or (car (cdr (member head org-todo-heads)))
7792 (car org-todo-heads)))
7793 ((eq arg 'previousset)
7794 (let ((org-todo-heads (reverse org-todo-heads)))
7795 (or (car (cdr (member head org-todo-heads)))
7796 (car org-todo-heads))))
7797 ((car (member arg org-todo-keywords-1)))
7798 ((nth (1- (prefix-numeric-value arg))
7799 org-todo-keywords-1))))
7800 ((null member) (or head (car org-todo-keywords-1)))
7801 ((equal this final-done-word) nil) ;; -> make empty
7802 ((null tail) nil) ;; -> first entry
7803 ((eq interpret 'sequence)
7804 (car tail))
7805 ((memq interpret '(type priority))
7806 (if (eq this-command last-command)
7807 (car tail)
7808 (if (> (length tail) 0)
7809 (or done-word (car org-done-keywords))
7810 nil)))
7811 (t nil)))
7812 (next (if state (concat " " state " ") " "))
7813 (change-plist (list :type 'todo-state-change :from this :to state
7814 :position startpos))
7815 dolog now-done-p)
7816 (when org-blocker-hook
7817 (unless (save-excursion
7818 (save-match-data
7819 (run-hook-with-args-until-failure
7820 'org-blocker-hook change-plist)))
7821 (if (interactive-p)
7822 (error "TODO state change from %s to %s blocked" this state)
7823 ;; fail silently
7824 (message "TODO state change from %s to %s blocked" this state)
7825 (throw 'exit nil))))
7826 (store-match-data match-data)
7827 (replace-match next t t)
7828 (unless (pos-visible-in-window-p hl-pos)
7829 (message "TODO state changed to %s" (org-trim next)))
7830 (unless head
7831 (setq head (org-get-todo-sequence-head state)
7832 ass (assoc head org-todo-kwd-alist)
7833 interpret (nth 1 ass)
7834 done-word (nth 3 ass)
7835 final-done-word (nth 4 ass)))
7836 (when (memq arg '(nextset previousset))
7837 (message "Keyword-Set %d/%d: %s"
7838 (- (length org-todo-sets) -1
7839 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7840 (length org-todo-sets)
7841 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7842 (setq org-last-todo-state-is-todo
7843 (not (member state org-done-keywords)))
7844 (setq now-done-p (and (member state org-done-keywords)
7845 (not (member this org-done-keywords))))
7846 (and logging (org-local-logging logging))
7847 (when (and (or org-todo-log-states org-log-done)
7848 (not (memq arg '(nextset previousset))))
7849 ;; we need to look at recording a time and note
7850 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7851 (nth 2 (assoc this org-todo-log-states))))
7852 (when (and state
7853 (member state org-not-done-keywords)
7854 (not (member this org-not-done-keywords)))
7855 ;; This is now a todo state and was not one before
7856 ;; If there was a CLOSED time stamp, get rid of it.
7857 (org-add-planning-info nil nil 'closed))
7858 (when (and now-done-p org-log-done)
7859 ;; It is now done, and it was not done before
7860 (org-add-planning-info 'closed (org-current-time))
7861 (if (and (not dolog) (eq 'note org-log-done))
7862 (org-add-log-setup 'done state 'findpos 'note)))
7863 (when (and state dolog)
7864 ;; This is a non-nil state, and we need to log it
7865 (org-add-log-setup 'state state 'findpos dolog)))
7866 ;; Fixup tag positioning
7867 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7868 (run-hooks 'org-after-todo-state-change-hook)
7869 (if (and arg (not (member state org-done-keywords)))
7870 (setq head (org-get-todo-sequence-head state)))
7871 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7872 ;; Do we need to trigger a repeat?
7873 (when now-done-p (org-auto-repeat-maybe state))
7874 ;; Fixup cursor location if close to the keyword
7875 (if (and (outline-on-heading-p)
7876 (not (bolp))
7877 (save-excursion (beginning-of-line 1)
7878 (looking-at org-todo-line-regexp))
7879 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7880 (progn
7881 (goto-char (or (match-end 2) (match-end 1)))
7882 (just-one-space)))
7883 (when org-trigger-hook
7884 (save-excursion
7885 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7887 (defun org-local-logging (value)
7888 "Get logging settings from a property VALUE."
7889 (let* (words w a)
7890 ;; directly set the variables, they are already local.
7891 (setq org-log-done nil
7892 org-log-repeat nil
7893 org-todo-log-states nil)
7894 (setq words (org-split-string value))
7895 (while (setq w (pop words))
7896 (cond
7897 ((setq a (assoc w org-startup-options))
7898 (and (member (nth 1 a) '(org-log-done org-log-repeat))
7899 (set (nth 1 a) (nth 2 a))))
7900 ((setq a (org-extract-log-state-settings w))
7901 (and (member (car a) org-todo-keywords-1)
7902 (push a org-todo-log-states)))))))
7904 (defun org-get-todo-sequence-head (kwd)
7905 "Return the head of the TODO sequence to which KWD belongs.
7906 If KWD is not set, check if there is a text property remembering the
7907 right sequence."
7908 (let (p)
7909 (cond
7910 ((not kwd)
7911 (or (get-text-property (point-at-bol) 'org-todo-head)
7912 (progn
7913 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
7914 nil (point-at-eol)))
7915 (get-text-property p 'org-todo-head))))
7916 ((not (member kwd org-todo-keywords-1))
7917 (car org-todo-keywords-1))
7918 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
7920 (defun org-fast-todo-selection ()
7921 "Fast TODO keyword selection with single keys.
7922 Returns the new TODO keyword, or nil if no state change should occur."
7923 (let* ((fulltable org-todo-key-alist)
7924 (done-keywords org-done-keywords) ;; needed for the faces.
7925 (maxlen (apply 'max (mapcar
7926 (lambda (x)
7927 (if (stringp (car x)) (string-width (car x)) 0))
7928 fulltable)))
7929 (expert nil)
7930 (fwidth (+ maxlen 3 1 3))
7931 (ncol (/ (- (window-width) 4) fwidth))
7932 tg cnt e c tbl
7933 groups ingroup)
7934 (save-window-excursion
7935 (if expert
7936 (set-buffer (get-buffer-create " *Org todo*"))
7937 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
7938 (erase-buffer)
7939 (org-set-local 'org-done-keywords done-keywords)
7940 (setq tbl fulltable cnt 0)
7941 (while (setq e (pop tbl))
7942 (cond
7943 ((equal e '(:startgroup))
7944 (push '() groups) (setq ingroup t)
7945 (when (not (= cnt 0))
7946 (setq cnt 0)
7947 (insert "\n"))
7948 (insert "{ "))
7949 ((equal e '(:endgroup))
7950 (setq ingroup nil cnt 0)
7951 (insert "}\n"))
7953 (setq tg (car e) c (cdr e))
7954 (if ingroup (push tg (car groups)))
7955 (setq tg (org-add-props tg nil 'face
7956 (org-get-todo-face tg)))
7957 (if (and (= cnt 0) (not ingroup)) (insert " "))
7958 (insert "[" c "] " tg (make-string
7959 (- fwidth 4 (length tg)) ?\ ))
7960 (when (= (setq cnt (1+ cnt)) ncol)
7961 (insert "\n")
7962 (if ingroup (insert " "))
7963 (setq cnt 0)))))
7964 (insert "\n")
7965 (goto-char (point-min))
7966 (if (and (not expert) (fboundp 'fit-window-to-buffer))
7967 (fit-window-to-buffer))
7968 (message "[a-z..]:Set [SPC]:clear")
7969 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
7970 (cond
7971 ((or (= c ?\C-g)
7972 (and (= c ?q) (not (rassoc c fulltable))))
7973 (setq quit-flag t))
7974 ((= c ?\ ) nil)
7975 ((setq e (rassoc c fulltable) tg (car e))
7977 (t (setq quit-flag t))))))
7979 (defun org-entry-is-todo-p ()
7980 (member (org-get-todo-state) org-not-done-keywords))
7982 (defun org-entry-is-done-p ()
7983 (member (org-get-todo-state) org-done-keywords))
7985 (defun org-get-todo-state ()
7986 (save-excursion
7987 (org-back-to-heading t)
7988 (and (looking-at org-todo-line-regexp)
7989 (match-end 2)
7990 (match-string 2))))
7992 (defun org-at-date-range-p (&optional inactive-ok)
7993 "Is the cursor inside a date range?"
7994 (interactive)
7995 (save-excursion
7996 (catch 'exit
7997 (let ((pos (point)))
7998 (skip-chars-backward "^[<\r\n")
7999 (skip-chars-backward "<[")
8000 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8001 (>= (match-end 0) pos)
8002 (throw 'exit t))
8003 (skip-chars-backward "^<[\r\n")
8004 (skip-chars-backward "<[")
8005 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8006 (>= (match-end 0) pos)
8007 (throw 'exit t)))
8008 nil)))
8010 (defun org-get-repeat ()
8011 "Check if tere is a deadline/schedule with repeater in this entry."
8012 (save-match-data
8013 (save-excursion
8014 (org-back-to-heading t)
8015 (if (re-search-forward
8016 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8017 (match-string 1)))))
8019 (defvar org-last-changed-timestamp)
8020 (defvar org-log-post-message)
8021 (defvar org-log-note-purpose)
8022 (defvar org-log-note-how)
8023 (defun org-auto-repeat-maybe (done-word)
8024 "Check if the current headline contains a repeated deadline/schedule.
8025 If yes, set TODO state back to what it was and change the base date
8026 of repeating deadline/scheduled time stamps to new date.
8027 This function is run automatically after each state change to a DONE state."
8028 ;; last-state is dynamically scoped into this function
8029 (let* ((repeat (org-get-repeat))
8030 (aa (assoc last-state org-todo-kwd-alist))
8031 (interpret (nth 1 aa))
8032 (head (nth 2 aa))
8033 (whata '(("d" . day) ("m" . month) ("y" . year)))
8034 (msg "Entry repeats: ")
8035 (org-log-done nil)
8036 (org-todo-log-states nil)
8037 (nshiftmax 10) (nshift 0)
8038 re type n what ts mb0 time)
8039 (when repeat
8040 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8041 (org-todo (if (eq interpret 'type) last-state head))
8042 (when org-log-repeat
8043 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8044 (memq 'org-add-log-note post-command-hook))
8045 ;; OK, we are already setup for some record
8046 (if (eq org-log-repeat 'note)
8047 ;; make sure we take a note, not only a time stamp
8048 (setq org-log-note-how 'note))
8049 ;; Set up for taking a record
8050 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8051 'findpos org-log-repeat)))
8052 (org-back-to-heading t)
8053 (org-add-planning-info nil nil 'closed)
8054 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8055 org-deadline-time-regexp "\\)\\|\\("
8056 org-ts-regexp "\\)"))
8057 (while (re-search-forward
8058 re (save-excursion (outline-next-heading) (point)) t)
8059 (setq type (if (match-end 1) org-scheduled-string
8060 (if (match-end 3) org-deadline-string "Plain:"))
8061 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8062 mb0 (match-beginning 0))
8063 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8064 (setq n (string-to-number (match-string 2 ts))
8065 what (match-string 3 ts))
8066 (if (equal what "w") (setq n (* n 7) what "d"))
8067 ;; Preparation, see if we need to modify the start date for the change
8068 (when (match-end 1)
8069 (setq time (save-match-data (org-time-string-to-time ts)))
8070 (cond
8071 ((equal (match-string 1 ts) ".")
8072 ;; Shift starting date to today
8073 (org-timestamp-change
8074 (- (time-to-days (current-time)) (time-to-days time))
8075 'day))
8076 ((equal (match-string 1 ts) "+")
8077 (while (or (= nshift 0)
8078 (<= (time-to-days time) (time-to-days (current-time))))
8079 (when (= (incf nshift) nshiftmax)
8080 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8081 (error "Abort")))
8082 (org-timestamp-change n (cdr (assoc what whata)))
8083 (org-at-timestamp-p t)
8084 (setq ts (match-string 1))
8085 (setq time (save-match-data (org-time-string-to-time ts))))
8086 (org-timestamp-change (- n) (cdr (assoc what whata)))
8087 ;; rematch, so that we have everything in place for the real shift
8088 (org-at-timestamp-p t)
8089 (setq ts (match-string 1))
8090 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8091 (org-timestamp-change n (cdr (assoc what whata)))
8092 (setq msg (concat msg type org-last-changed-timestamp " "))))
8093 (setq org-log-post-message msg)
8094 (message "%s" msg))))
8096 (defun org-show-todo-tree (arg)
8097 "Make a compact tree which shows all headlines marked with TODO.
8098 The tree will show the lines where the regexp matches, and all higher
8099 headlines above the match.
8100 With a \\[universal-argument] prefix, also show the DONE entries.
8101 With a numeric prefix N, construct a sparse tree for the Nth element
8102 of `org-todo-keywords-1'."
8103 (interactive "P")
8104 (let ((case-fold-search nil)
8105 (kwd-re
8106 (cond ((null arg) org-not-done-regexp)
8107 ((equal arg '(4))
8108 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8109 (mapcar 'list org-todo-keywords-1))))
8110 (concat "\\("
8111 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8112 "\\)\\>")))
8113 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8114 (regexp-quote (nth (1- (prefix-numeric-value arg))
8115 org-todo-keywords-1)))
8116 (t (error "Invalid prefix argument: %s" arg)))))
8117 (message "%d TODO entries found"
8118 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8120 (defun org-deadline (&optional remove)
8121 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8122 With argument REMOVE, remove any deadline from the item."
8123 (interactive "P")
8124 (if remove
8125 (progn
8126 (org-remove-timestamp-with-keyword org-deadline-string)
8127 (message "Item no longer has a deadline."))
8128 (org-add-planning-info 'deadline nil 'closed)))
8130 (defun org-schedule (&optional remove)
8131 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8132 With argument REMOVE, remove any scheduling date from the item."
8133 (interactive "P")
8134 (if remove
8135 (progn
8136 (org-remove-timestamp-with-keyword org-scheduled-string)
8137 (message "Item is no longer scheduled."))
8138 (org-add-planning-info 'scheduled nil 'closed)))
8140 (defun org-remove-timestamp-with-keyword (keyword)
8141 "Remove all time stamps with KEYWORD in the current entry."
8142 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8143 beg)
8144 (save-excursion
8145 (org-back-to-heading t)
8146 (setq beg (point))
8147 (org-end-of-subtree t t)
8148 (while (re-search-backward re beg t)
8149 (replace-match "")
8150 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8151 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
8153 (defun org-add-planning-info (what &optional time &rest remove)
8154 "Insert new timestamp with keyword in the line directly after the headline.
8155 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8156 If non is given, the user is prompted for a date.
8157 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8158 be removed."
8159 (interactive)
8160 (let (org-time-was-given org-end-time-was-given ts
8161 end default-time default-input)
8163 (when (and (not time) (memq what '(scheduled deadline)))
8164 ;; Try to get a default date/time from existing timestamp
8165 (save-excursion
8166 (org-back-to-heading t)
8167 (setq end (save-excursion (outline-next-heading) (point)))
8168 (when (re-search-forward (if (eq what 'scheduled)
8169 org-scheduled-time-regexp
8170 org-deadline-time-regexp)
8171 end t)
8172 (setq ts (match-string 1)
8173 default-time
8174 (apply 'encode-time (org-parse-time-string ts))
8175 default-input (and ts (org-get-compact-tod ts))))))
8176 (when what
8177 ;; If necessary, get the time from the user
8178 (setq time (or time (org-read-date nil 'to-time nil nil
8179 default-time default-input))))
8181 (when (and org-insert-labeled-timestamps-at-point
8182 (member what '(scheduled deadline)))
8183 (insert
8184 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8185 (org-insert-time-stamp time org-time-was-given
8186 nil nil nil (list org-end-time-was-given))
8187 (setq what nil))
8188 (save-excursion
8189 (save-restriction
8190 (let (col list elt ts buffer-invisibility-spec)
8191 (org-back-to-heading t)
8192 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8193 (goto-char (match-end 1))
8194 (setq col (current-column))
8195 (goto-char (match-end 0))
8196 (if (eobp) (insert "\n") (forward-char 1))
8197 (if (and (not (looking-at outline-regexp))
8198 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8199 "[^\r\n]*"))
8200 (not (equal (match-string 1) org-clock-string)))
8201 (narrow-to-region (match-beginning 0) (match-end 0))
8202 (insert-before-markers "\n")
8203 (backward-char 1)
8204 (narrow-to-region (point) (point))
8205 (indent-to-column col))
8206 ;; Check if we have to remove something.
8207 (setq list (cons what remove))
8208 (while list
8209 (setq elt (pop list))
8210 (goto-char (point-min))
8211 (when (or (and (eq elt 'scheduled)
8212 (re-search-forward org-scheduled-time-regexp nil t))
8213 (and (eq elt 'deadline)
8214 (re-search-forward org-deadline-time-regexp nil t))
8215 (and (eq elt 'closed)
8216 (re-search-forward org-closed-time-regexp nil t)))
8217 (replace-match "")
8218 (if (looking-at "--+<[^>]+>") (replace-match ""))
8219 (if (looking-at " +") (replace-match ""))))
8220 (goto-char (point-max))
8221 (when what
8222 (insert
8223 (if (not (equal (char-before) ?\ )) " " "")
8224 (cond ((eq what 'scheduled) org-scheduled-string)
8225 ((eq what 'deadline) org-deadline-string)
8226 ((eq what 'closed) org-closed-string))
8227 " ")
8228 (setq ts (org-insert-time-stamp
8229 time
8230 (or org-time-was-given
8231 (and (eq what 'closed) org-log-done-with-time))
8232 (eq what 'closed)
8233 nil nil (list org-end-time-was-given)))
8234 (end-of-line 1))
8235 (goto-char (point-min))
8236 (widen)
8237 (if (looking-at "[ \t]+\r?\n")
8238 (replace-match ""))
8239 ts)))))
8241 (defvar org-log-note-marker (make-marker))
8242 (defvar org-log-note-purpose nil)
8243 (defvar org-log-note-state nil)
8244 (defvar org-log-note-how nil)
8245 (defvar org-log-note-window-configuration nil)
8246 (defvar org-log-note-return-to (make-marker))
8247 (defvar org-log-post-message nil
8248 "Message to be displayed after a log note has been stored.
8249 The auto-repeater uses this.")
8251 (defun org-add-note ()
8252 "Add a note to the current entry.
8253 This is done in the same way as adding a state change note."
8254 (interactive)
8255 (org-add-log-setup 'note nil t nil))
8257 (defun org-add-log-setup (&optional purpose state findpos how)
8258 "Set up the post command hook to take a note.
8259 If this is about to TODO state change, the new state is expected in STATE.
8260 When FINDPOS is non-nil, find the correct position for the note in
8261 the current entry. If not, assume that it can be inserted at point."
8262 (save-excursion
8263 (when findpos
8264 (org-back-to-heading t)
8265 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8266 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8267 "[^\r\n]*\\)?"))
8268 (goto-char (match-end 0))
8269 (unless org-log-states-order-reversed
8270 (and (= (char-after) ?\n) (forward-char 1))
8271 (org-skip-over-state-notes)
8272 (skip-chars-backward " \t\n\r")))
8273 (move-marker org-log-note-marker (point))
8274 (setq org-log-note-purpose purpose
8275 org-log-note-state state
8276 org-log-note-how how)
8277 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8279 (defun org-skip-over-state-notes ()
8280 "Skip past the list of State notes in an entry."
8281 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8282 (while (looking-at "[ \t]*- State")
8283 (condition-case nil
8284 (org-next-item)
8285 (error (org-end-of-item)))))
8287 (defun org-add-log-note (&optional purpose)
8288 "Pop up a window for taking a note, and add this note later at point."
8289 (remove-hook 'post-command-hook 'org-add-log-note)
8290 (setq org-log-note-window-configuration (current-window-configuration))
8291 (delete-other-windows)
8292 (move-marker org-log-note-return-to (point))
8293 (switch-to-buffer (marker-buffer org-log-note-marker))
8294 (goto-char org-log-note-marker)
8295 (org-switch-to-buffer-other-window "*Org Note*")
8296 (erase-buffer)
8297 (if (memq org-log-note-how '(time state))
8298 (org-store-log-note)
8299 (let ((org-inhibit-startup t)) (org-mode))
8300 (insert (format "# Insert note for %s.
8301 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8302 (cond
8303 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8304 ((eq org-log-note-purpose 'done) "closed todo item")
8305 ((eq org-log-note-purpose 'state)
8306 (format "state change to \"%s\"" org-log-note-state))
8307 ((eq org-log-note-purpose 'note)
8308 "this entry")
8309 (t (error "This should not happen")))))
8310 (org-set-local 'org-finish-function 'org-store-log-note)))
8312 (defvar org-note-abort nil) ; dynamically scoped
8313 (defun org-store-log-note ()
8314 "Finish taking a log note, and insert it to where it belongs."
8315 (let ((txt (buffer-string))
8316 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8317 lines ind)
8318 (kill-buffer (current-buffer))
8319 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8320 (setq txt (replace-match "" t t txt)))
8321 (if (string-match "\\s-+\\'" txt)
8322 (setq txt (replace-match "" t t txt)))
8323 (setq lines (org-split-string txt "\n"))
8324 (when (and note (string-match "\\S-" note))
8325 (setq note
8326 (org-replace-escapes
8327 note
8328 (list (cons "%u" (user-login-name))
8329 (cons "%U" user-full-name)
8330 (cons "%t" (format-time-string
8331 (org-time-stamp-format 'long 'inactive)
8332 (current-time)))
8333 (cons "%s" (if org-log-note-state
8334 (concat "\"" org-log-note-state "\"")
8335 "")))))
8336 (if lines (setq note (concat note " \\\\")))
8337 (push note lines))
8338 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8339 (when lines
8340 (save-excursion
8341 (set-buffer (marker-buffer org-log-note-marker))
8342 (save-excursion
8343 (goto-char org-log-note-marker)
8344 (move-marker org-log-note-marker nil)
8345 (end-of-line 1)
8346 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8347 (indent-relative nil)
8348 (insert "- " (pop lines))
8349 (org-indent-line-function)
8350 (beginning-of-line 1)
8351 (looking-at "[ \t]*")
8352 (setq ind (concat (match-string 0) " "))
8353 (end-of-line 1)
8354 (while lines (insert "\n" ind (pop lines)))))))
8355 (set-window-configuration org-log-note-window-configuration)
8356 (with-current-buffer (marker-buffer org-log-note-return-to)
8357 (goto-char org-log-note-return-to))
8358 (move-marker org-log-note-return-to nil)
8359 (and org-log-post-message (message "%s" org-log-post-message)))
8361 (defun org-sparse-tree (&optional arg)
8362 "Create a sparse tree, prompt for the details.
8363 This command can create sparse trees. You first need to select the type
8364 of match used to create the tree:
8366 t Show entries with a specific TODO keyword.
8367 T Show entries selected by a tags match.
8368 p Enter a property name and its value (both with completion on existing
8369 names/values) and show entries with that property.
8370 r Show entries matching a regular expression
8371 d Show deadlines due within `org-deadline-warning-days'."
8372 (interactive "P")
8373 (let (ans kwd value)
8374 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8375 (setq ans (read-char-exclusive))
8376 (cond
8377 ((equal ans ?d)
8378 (call-interactively 'org-check-deadlines))
8379 ((equal ans ?b)
8380 (call-interactively 'org-check-before-date))
8381 ((equal ans ?t)
8382 (org-show-todo-tree '(4)))
8383 ((equal ans ?T)
8384 (call-interactively 'org-tags-sparse-tree))
8385 ((member ans '(?p ?P))
8386 (setq kwd (completing-read "Property: "
8387 (mapcar 'list (org-buffer-property-keys))))
8388 (setq value (completing-read "Value: "
8389 (mapcar 'list (org-property-values kwd))))
8390 (unless (string-match "\\`{.*}\\'" value)
8391 (setq value (concat "\"" value "\"")))
8392 (org-tags-sparse-tree arg (concat kwd "=" value)))
8393 ((member ans '(?r ?R ?/))
8394 (call-interactively 'org-occur))
8395 (t (error "No such sparse tree command \"%c\"" ans)))))
8397 (defvar org-occur-highlights nil
8398 "List of overlays used for occur matches.")
8399 (make-variable-buffer-local 'org-occur-highlights)
8400 (defvar org-occur-parameters nil
8401 "Parameters of the active org-occur calls.
8402 This is a list, each call to org-occur pushes as cons cell,
8403 containing the regular expression and the callback, onto the list.
8404 The list can contain several entries if `org-occur' has been called
8405 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8406 will only contain one set of parameters. When the highlights are
8407 removed (for example with `C-c C-c', or with the next edit (depending
8408 on `org-remove-highlights-with-change'), this variable is emptied
8409 as well.")
8410 (make-variable-buffer-local 'org-occur-parameters)
8412 (defun org-occur (regexp &optional keep-previous callback)
8413 "Make a compact tree which shows all matches of REGEXP.
8414 The tree will show the lines where the regexp matches, and all higher
8415 headlines above the match. It will also show the heading after the match,
8416 to make sure editing the matching entry is easy.
8417 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8418 call to `org-occur' will be kept, to allow stacking of calls to this
8419 command.
8420 If CALLBACK is non-nil, it is a function which is called to confirm
8421 that the match should indeed be shown."
8422 (interactive "sRegexp: \nP")
8423 (unless keep-previous
8424 (org-remove-occur-highlights nil nil t))
8425 (push (cons regexp callback) org-occur-parameters)
8426 (let ((cnt 0))
8427 (save-excursion
8428 (goto-char (point-min))
8429 (if (or (not keep-previous) ; do not want to keep
8430 (not org-occur-highlights)) ; no previous matches
8431 ;; hide everything
8432 (org-overview))
8433 (while (re-search-forward regexp nil t)
8434 (when (or (not callback)
8435 (save-match-data (funcall callback)))
8436 (setq cnt (1+ cnt))
8437 (when org-highlight-sparse-tree-matches
8438 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8439 (org-show-context 'occur-tree))))
8440 (when org-remove-highlights-with-change
8441 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8442 nil 'local))
8443 (unless org-sparse-tree-open-archived-trees
8444 (org-hide-archived-subtrees (point-min) (point-max)))
8445 (run-hooks 'org-occur-hook)
8446 (if (interactive-p)
8447 (message "%d match(es) for regexp %s" cnt regexp))
8448 cnt))
8450 (defun org-show-context (&optional key)
8451 "Make sure point and context and visible.
8452 How much context is shown depends upon the variables
8453 `org-show-hierarchy-above', `org-show-following-heading'. and
8454 `org-show-siblings'."
8455 (let ((heading-p (org-on-heading-p t))
8456 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8457 (following-p (org-get-alist-option org-show-following-heading key))
8458 (entry-p (org-get-alist-option org-show-entry-below key))
8459 (siblings-p (org-get-alist-option org-show-siblings key)))
8460 (catch 'exit
8461 ;; Show heading or entry text
8462 (if (and heading-p (not entry-p))
8463 (org-flag-heading nil) ; only show the heading
8464 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8465 (org-show-hidden-entry))) ; show entire entry
8466 (when following-p
8467 ;; Show next sibling, or heading below text
8468 (save-excursion
8469 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8470 (org-flag-heading nil))))
8471 (when siblings-p (org-show-siblings))
8472 (when hierarchy-p
8473 ;; show all higher headings, possibly with siblings
8474 (save-excursion
8475 (while (and (condition-case nil
8476 (progn (org-up-heading-all 1) t)
8477 (error nil))
8478 (not (bobp)))
8479 (org-flag-heading nil)
8480 (when siblings-p (org-show-siblings))))))))
8482 (defun org-reveal (&optional siblings)
8483 "Show current entry, hierarchy above it, and the following headline.
8484 This can be used to show a consistent set of context around locations
8485 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8486 not t for the search context.
8488 With optional argument SIBLINGS, on each level of the hierarchy all
8489 siblings are shown. This repairs the tree structure to what it would
8490 look like when opened with hierarchical calls to `org-cycle'."
8491 (interactive "P")
8492 (let ((org-show-hierarchy-above t)
8493 (org-show-following-heading t)
8494 (org-show-siblings (if siblings t org-show-siblings)))
8495 (org-show-context nil)))
8497 (defun org-highlight-new-match (beg end)
8498 "Highlight from BEG to END and mark the highlight is an occur headline."
8499 (let ((ov (org-make-overlay beg end)))
8500 (org-overlay-put ov 'face 'secondary-selection)
8501 (push ov org-occur-highlights)))
8503 (defun org-remove-occur-highlights (&optional beg end noremove)
8504 "Remove the occur highlights from the buffer.
8505 BEG and END are ignored. If NOREMOVE is nil, remove this function
8506 from the `before-change-functions' in the current buffer."
8507 (interactive)
8508 (unless org-inhibit-highlight-removal
8509 (mapc 'org-delete-overlay org-occur-highlights)
8510 (setq org-occur-highlights nil)
8511 (setq org-occur-parameters nil)
8512 (unless noremove
8513 (remove-hook 'before-change-functions
8514 'org-remove-occur-highlights 'local))))
8516 ;;;; Priorities
8518 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8519 "Regular expression matching the priority indicator.")
8521 (defvar org-remove-priority-next-time nil)
8523 (defun org-priority-up ()
8524 "Increase the priority of the current item."
8525 (interactive)
8526 (org-priority 'up))
8528 (defun org-priority-down ()
8529 "Decrease the priority of the current item."
8530 (interactive)
8531 (org-priority 'down))
8533 (defun org-priority (&optional action)
8534 "Change the priority of an item by ARG.
8535 ACTION can be `set', `up', `down', or a character."
8536 (interactive)
8537 (setq action (or action 'set))
8538 (let (current new news have remove)
8539 (save-excursion
8540 (org-back-to-heading)
8541 (if (looking-at org-priority-regexp)
8542 (setq current (string-to-char (match-string 2))
8543 have t)
8544 (setq current org-default-priority))
8545 (cond
8546 ((or (eq action 'set)
8547 (if (featurep 'xemacs) (characterp action) (integerp action)))
8548 (if (not (eq action 'set))
8549 (setq new action)
8550 (message "Priority %c-%c, SPC to remove: "
8551 org-highest-priority org-lowest-priority)
8552 (setq new (read-char-exclusive)))
8553 (if (and (= (upcase org-highest-priority) org-highest-priority)
8554 (= (upcase org-lowest-priority) org-lowest-priority))
8555 (setq new (upcase new)))
8556 (cond ((equal new ?\ ) (setq remove t))
8557 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8558 (error "Priority must be between `%c' and `%c'"
8559 org-highest-priority org-lowest-priority))))
8560 ((eq action 'up)
8561 (if (and (not have) (eq last-command this-command))
8562 (setq new org-lowest-priority)
8563 (setq new (if (and org-priority-start-cycle-with-default (not have))
8564 org-default-priority (1- current)))))
8565 ((eq action 'down)
8566 (if (and (not have) (eq last-command this-command))
8567 (setq new org-highest-priority)
8568 (setq new (if (and org-priority-start-cycle-with-default (not have))
8569 org-default-priority (1+ current)))))
8570 (t (error "Invalid action")))
8571 (if (or (< (upcase new) org-highest-priority)
8572 (> (upcase new) org-lowest-priority))
8573 (setq remove t))
8574 (setq news (format "%c" new))
8575 (if have
8576 (if remove
8577 (replace-match "" t t nil 1)
8578 (replace-match news t t nil 2))
8579 (if remove
8580 (error "No priority cookie found in line")
8581 (looking-at org-todo-line-regexp)
8582 (if (match-end 2)
8583 (progn
8584 (goto-char (match-end 2))
8585 (insert " [#" news "]"))
8586 (goto-char (match-beginning 3))
8587 (insert "[#" news "] ")))))
8588 (org-preserve-lc (org-set-tags nil 'align))
8589 (if remove
8590 (message "Priority removed")
8591 (message "Priority of current item set to %s" news))))
8594 (defun org-get-priority (s)
8595 "Find priority cookie and return priority."
8596 (save-match-data
8597 (if (not (string-match org-priority-regexp s))
8598 (* 1000 (- org-lowest-priority org-default-priority))
8599 (* 1000 (- org-lowest-priority
8600 (string-to-char (match-string 2 s)))))))
8602 ;;;; Tags
8604 (defun org-scan-tags (action matcher &optional todo-only)
8605 "Scan headline tags with inheritance and produce output ACTION.
8606 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8607 evaluated, testing if a given set of tags qualifies a headline for
8608 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8609 are included in the output."
8610 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8611 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8612 (org-re
8613 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8614 (props (list 'face nil
8615 'done-face 'org-done
8616 'undone-face nil
8617 'mouse-face 'highlight
8618 'org-not-done-regexp org-not-done-regexp
8619 'org-todo-regexp org-todo-regexp
8620 'keymap org-agenda-keymap
8621 'help-echo
8622 (format "mouse-2 or RET jump to org file %s"
8623 (abbreviate-file-name
8624 (or (buffer-file-name (buffer-base-buffer))
8625 (buffer-name (buffer-base-buffer)))))))
8626 (case-fold-search nil)
8627 lspos
8628 tags tags-list tags-alist (llast 0) rtn level category i txt
8629 todo marker entry priority)
8630 (save-excursion
8631 (goto-char (point-min))
8632 (when (eq action 'sparse-tree)
8633 (org-overview)
8634 (org-remove-occur-highlights))
8635 (while (re-search-forward re nil t)
8636 (catch :skip
8637 (setq todo (if (match-end 1) (match-string 2))
8638 tags (if (match-end 4) (match-string 4)))
8639 (goto-char (setq lspos (1+ (match-beginning 0))))
8640 (setq level (org-reduced-level (funcall outline-level))
8641 category (org-get-category))
8642 (setq i llast llast level)
8643 ;; remove tag lists from same and sublevels
8644 (while (>= i level)
8645 (when (setq entry (assoc i tags-alist))
8646 (setq tags-alist (delete entry tags-alist)))
8647 (setq i (1- i)))
8648 ;; add the next tags
8649 (when tags
8650 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8651 tags-alist
8652 (cons (cons level tags) tags-alist)))
8653 ;; compile tags for current headline
8654 (setq tags-list
8655 (if org-use-tag-inheritance
8656 (apply 'append (mapcar 'cdr tags-alist))
8657 tags))
8658 (when (and tags org-use-tag-inheritance
8659 (not (eq t org-use-tag-inheritance)))
8660 ;; selective inheritance, remove uninherited ones
8661 (setcdr (car tags-alist)
8662 (org-remove-uniherited-tags (cdar tags-alist))))
8663 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8664 (eval matcher)
8665 (or (not org-agenda-skip-archived-trees)
8666 (not (member org-archive-tag tags-list))))
8667 (and (eq action 'agenda) (org-agenda-skip))
8668 ;; list this headline
8670 (if (eq action 'sparse-tree)
8671 (progn
8672 (and org-highlight-sparse-tree-matches
8673 (org-get-heading) (match-end 0)
8674 (org-highlight-new-match
8675 (match-beginning 0) (match-beginning 1)))
8676 (org-show-context 'tags-tree))
8677 (setq txt (org-format-agenda-item
8679 (concat
8680 (if org-tags-match-list-sublevels
8681 (make-string (1- level) ?.) "")
8682 (org-get-heading))
8683 category tags-list)
8684 priority (org-get-priority txt))
8685 (goto-char lspos)
8686 (setq marker (org-agenda-new-marker))
8687 (org-add-props txt props
8688 'org-marker marker 'org-hd-marker marker 'org-category category
8689 'priority priority 'type "tagsmatch")
8690 (push txt rtn))
8691 ;; if we are to skip sublevels, jump to end of subtree
8692 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8693 (when (and (eq action 'sparse-tree)
8694 (not org-sparse-tree-open-archived-trees))
8695 (org-hide-archived-subtrees (point-min) (point-max)))
8696 (nreverse rtn)))
8698 (defun org-remove-uniherited-tags (tags)
8699 "Remove all tags that are not inherited from the list TAGS."
8700 (cond
8701 ((eq org-use-tag-inheritance t) tags)
8702 ((not org-use-tag-inheritance) nil)
8703 ((stringp org-use-tag-inheritance)
8704 (delq nil (mapcar
8705 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8706 tags)))
8707 ((listp org-use-tag-inheritance)
8708 (org-delete-all org-use-tag-inheritance tags))))
8710 (defvar todo-only) ;; dynamically scoped
8712 (defun org-tags-sparse-tree (&optional todo-only match)
8713 "Create a sparse tree according to tags string MATCH.
8714 MATCH can contain positive and negative selection of tags, like
8715 \"+WORK+URGENT-WITHBOSS\".
8716 If optional argument TODO_ONLY is non-nil, only select lines that are
8717 also TODO lines."
8718 (interactive "P")
8719 (org-prepare-agenda-buffers (list (current-buffer)))
8720 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8722 (defvar org-cached-props nil)
8723 (defun org-cached-entry-get (pom property)
8724 (if (or (eq t org-use-property-inheritance)
8725 (and (stringp org-use-property-inheritance)
8726 (string-match org-use-property-inheritance property))
8727 (and (listp org-use-property-inheritance)
8728 (member property org-use-property-inheritance)))
8729 ;; Caching is not possible, check it directly
8730 (org-entry-get pom property 'inherit)
8731 ;; Get all properties, so that we can do complicated checks easily
8732 (cdr (assoc property (or org-cached-props
8733 (setq org-cached-props
8734 (org-entry-properties pom)))))))
8736 (defun org-global-tags-completion-table (&optional files)
8737 "Return the list of all tags in all agenda buffer/files."
8738 (save-excursion
8739 (org-uniquify
8740 (delq nil
8741 (apply 'append
8742 (mapcar
8743 (lambda (file)
8744 (set-buffer (find-file-noselect file))
8745 (append (org-get-buffer-tags)
8746 (mapcar (lambda (x) (if (stringp (car-safe x))
8747 (list (car-safe x)) nil))
8748 org-tag-alist)))
8749 (if (and files (car files))
8750 files
8751 (org-agenda-files))))))))
8753 (defun org-make-tags-matcher (match)
8754 "Create the TAGS//TODO matcher form for the selection string MATCH."
8755 ;; todo-only is scoped dynamically into this function, and the function
8756 ;; may change it it the matcher asksk for it.
8757 (unless match
8758 ;; Get a new match request, with completion
8759 (let ((org-last-tags-completion-table
8760 (org-global-tags-completion-table)))
8761 (setq match (completing-read
8762 "Match: " 'org-tags-completion-function nil nil nil
8763 'org-tags-history))))
8765 ;; Parse the string and create a lisp form
8766 (let ((match0 match)
8767 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8768 minus tag mm
8769 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8770 orterms term orlist re-p str-p level-p level-op
8771 prop-p pn pv po cat-p gv)
8772 (if (string-match "/+" match)
8773 ;; match contains also a todo-matching request
8774 (progn
8775 (setq tagsmatch (substring match 0 (match-beginning 0))
8776 todomatch (substring match (match-end 0)))
8777 (if (string-match "^!" todomatch)
8778 (setq todo-only t todomatch (substring todomatch 1)))
8779 (if (string-match "^\\s-*$" todomatch)
8780 (setq todomatch nil)))
8781 ;; only matching tags
8782 (setq tagsmatch match todomatch nil))
8784 ;; Make the tags matcher
8785 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8786 (setq tagsmatcher t)
8787 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8788 (while (setq term (pop orterms))
8789 (while (and (equal (substring term -1) "\\") orterms)
8790 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8791 (while (string-match re term)
8792 (setq minus (and (match-end 1)
8793 (equal (match-string 1 term) "-"))
8794 tag (match-string 2 term)
8795 re-p (equal (string-to-char tag) ?{)
8796 level-p (match-end 4)
8797 prop-p (match-end 5)
8798 mm (cond
8799 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8800 (level-p
8801 (setq level-op (org-op-to-function (match-string 3 term)))
8802 `(,level-op level ,(string-to-number
8803 (match-string 4 term))))
8804 (prop-p
8805 (setq pn (match-string 5 term)
8806 po (match-string 6 term)
8807 pv (match-string 7 term)
8808 cat-p (equal pn "CATEGORY")
8809 re-p (equal (string-to-char pv) ?{)
8810 str-p (equal (string-to-char pv) ?\")
8811 pv (if (or re-p str-p) (substring pv 1 -1) pv))
8812 (setq po (org-op-to-function po str-p))
8813 (if (equal pn "CATEGORY")
8814 (setq gv '(get-text-property (point) 'org-category))
8815 (setq gv `(org-cached-entry-get nil ,pn)))
8816 (if re-p
8817 `(string-match ,pv (or ,gv ""))
8818 (if str-p
8819 `(,po (or ,gv "") ,pv)
8820 `(,po (string-to-number (or ,gv ""))
8821 ,(string-to-number pv) ))))
8822 (t `(member ,(downcase tag) tags-list)))
8823 mm (if minus (list 'not mm) mm)
8824 term (substring term (match-end 0)))
8825 (push mm tagsmatcher))
8826 (push (if (> (length tagsmatcher) 1)
8827 (cons 'and tagsmatcher)
8828 (car tagsmatcher))
8829 orlist)
8830 (setq tagsmatcher nil))
8831 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8832 (setq tagsmatcher
8833 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
8834 (debug)
8835 ;; Make the todo matcher
8836 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
8837 (setq todomatcher t)
8838 (setq orterms (org-split-string todomatch "|") orlist nil)
8839 (while (setq term (pop orterms))
8840 (while (string-match re term)
8841 (setq minus (and (match-end 1)
8842 (equal (match-string 1 term) "-"))
8843 kwd (match-string 2 term)
8844 re-p (equal (string-to-char kwd) ?{)
8845 term (substring term (match-end 0))
8846 mm (if re-p
8847 `(string-match ,(substring kwd 1 -1) todo)
8848 (list 'equal 'todo kwd))
8849 mm (if minus (list 'not mm) mm))
8850 (push mm todomatcher))
8851 (push (if (> (length todomatcher) 1)
8852 (cons 'and todomatcher)
8853 (car todomatcher))
8854 orlist)
8855 (setq todomatcher nil))
8856 (setq todomatcher (if (> (length orlist) 1)
8857 (cons 'or orlist) (car orlist))))
8859 ;; Return the string and lisp forms of the matcher
8860 (setq matcher (if todomatcher
8861 (list 'and tagsmatcher todomatcher)
8862 tagsmatcher))
8863 (cons match0 matcher)))
8865 (defun org-op-to-function (op &optional stringp)
8866 (setq op
8867 (cond
8868 ((equal op "<" ) '(< string< ))
8869 ((equal op ">" ) '(> string> ))
8870 ((member op '("<=" "=<")) '(<= org-string<= ))
8871 ((member op '(">=" "=>")) '(>= org-string>= ))
8872 ((member op '("=" "==")) '(= string= ))
8873 ((member op '("<>" "!=")) '(org<> org-string<> ))))
8874 (nth (if stringp 1 0) op))
8876 (defun org<> (a b) (not (= a b)))
8877 (defun org-string<= (a b) (or (string= a b) (string< a b)))
8878 (defun org-string>= (a b) (or (string= a b) (string> a b)))
8879 (defun org-string<> (a b) (not (string= a b)))
8881 (defun org-match-any-p (re list)
8882 "Does re match any element of list?"
8883 (setq list (mapcar (lambda (x) (string-match re x)) list))
8884 (delq nil list))
8886 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8887 (defvar org-tags-overlay (org-make-overlay 1 1))
8888 (org-detach-overlay org-tags-overlay)
8890 (defun org-get-tags-at (&optional pos)
8891 "Get a list of all headline tags applicable at POS.
8892 POS defaults to point. If tags are inherited, the list contains
8893 the targets in the same sequence as the headlines appear, i.e.
8894 sthe tags of the current headline come last."
8895 (interactive)
8896 (let (tags ltags lastpos parent)
8897 (save-excursion
8898 (save-restriction
8899 (widen)
8900 (goto-char (or pos (point)))
8901 (save-match-data
8902 (condition-case nil
8903 (progn
8904 (org-back-to-heading t)
8905 (while (not (equal lastpos (point)))
8906 (setq lastpos (point))
8907 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
8908 (setq ltags (org-split-string
8909 (org-match-string-no-properties 1) ":"))
8910 (setq tags (append (org-remove-uniherited-tags ltags)
8911 tags)))
8912 (or org-use-tag-inheritance (error ""))
8913 (org-up-heading-all 1)
8914 (setq parent t)))
8915 (error nil))))
8916 tags)))
8918 (defun org-toggle-tag (tag &optional onoff)
8919 "Toggle the tag TAG for the current line.
8920 If ONOFF is `on' or `off', don't toggle but set to this state."
8921 (unless (org-on-heading-p t) (error "Not on headling"))
8922 (let (res current)
8923 (save-excursion
8924 (beginning-of-line)
8925 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8926 (point-at-eol) t)
8927 (progn
8928 (setq current (match-string 1))
8929 (replace-match ""))
8930 (setq current ""))
8931 (setq current (nreverse (org-split-string current ":")))
8932 (cond
8933 ((eq onoff 'on)
8934 (setq res t)
8935 (or (member tag current) (push tag current)))
8936 ((eq onoff 'off)
8937 (or (not (member tag current)) (setq current (delete tag current))))
8938 (t (if (member tag current)
8939 (setq current (delete tag current))
8940 (setq res t)
8941 (push tag current))))
8942 (end-of-line 1)
8943 (if current
8944 (progn
8945 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8946 (org-set-tags nil t))
8947 (delete-horizontal-space))
8948 (run-hooks 'org-after-tags-change-hook))
8949 res))
8951 (defun org-align-tags-here (to-col)
8952 ;; Assumes that this is a headline
8953 (let ((pos (point)) (col (current-column)) tags)
8954 (beginning-of-line 1)
8955 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
8956 (< pos (match-beginning 2)))
8957 (progn
8958 (setq tags (match-string 2))
8959 (goto-char (match-beginning 1))
8960 (insert " ")
8961 (delete-region (point) (1+ (match-end 0)))
8962 (backward-char 1)
8963 (move-to-column
8964 (max (1+ (current-column))
8965 (1+ col)
8966 (if (> to-col 0)
8967 to-col
8968 (- (abs to-col) (length tags))))
8970 (insert tags)
8971 (move-to-column (min (current-column) col) t))
8972 (goto-char pos))))
8974 (defun org-set-tags (&optional arg just-align)
8975 "Set the tags for the current headline.
8976 With prefix ARG, realign all tags in headings in the current buffer."
8977 (interactive "P")
8978 (let* ((re (concat "^" outline-regexp))
8979 (current (org-get-tags-string))
8980 (col (current-column))
8981 (org-setting-tags t)
8982 table current-tags inherited-tags ; computed below when needed
8983 tags p0 c0 c1 rpl)
8984 (if arg
8985 (save-excursion
8986 (goto-char (point-min))
8987 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
8988 (while (re-search-forward re nil t)
8989 (org-set-tags nil t)
8990 (end-of-line 1)))
8991 (message "All tags realigned to column %d" org-tags-column))
8992 (if just-align
8993 (setq tags current)
8994 ;; Get a new set of tags from the user
8995 (save-excursion
8996 (setq table (or org-tag-alist (org-get-buffer-tags))
8997 org-last-tags-completion-table table
8998 current-tags (org-split-string current ":")
8999 inherited-tags (nreverse
9000 (nthcdr (length current-tags)
9001 (nreverse (org-get-tags-at))))
9002 tags
9003 (if (or (eq t org-use-fast-tag-selection)
9004 (and org-use-fast-tag-selection
9005 (delq nil (mapcar 'cdr table))))
9006 (org-fast-tag-selection
9007 current-tags inherited-tags table
9008 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9009 (let ((org-add-colon-after-tag-completion t))
9010 (org-trim
9011 (org-without-partial-completion
9012 (completing-read "Tags: " 'org-tags-completion-function
9013 nil nil current 'org-tags-history)))))))
9014 (while (string-match "[-+&]+" tags)
9015 ;; No boolean logic, just a list
9016 (setq tags (replace-match ":" t t tags))))
9018 (if (string-match "\\`[\t ]*\\'" tags)
9019 (setq tags "")
9020 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9021 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9023 ;; Insert new tags at the correct column
9024 (beginning-of-line 1)
9025 (cond
9026 ((and (equal current "") (equal tags "")))
9027 ((re-search-forward
9028 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9029 (point-at-eol) t)
9030 (if (equal tags "")
9031 (setq rpl "")
9032 (goto-char (match-beginning 0))
9033 (setq c0 (current-column) p0 (point)
9034 c1 (max (1+ c0) (if (> org-tags-column 0)
9035 org-tags-column
9036 (- (- org-tags-column) (length tags))))
9037 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9038 (replace-match rpl t t)
9039 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9040 tags)
9041 (t (error "Tags alignment failed")))
9042 (move-to-column col)
9043 (unless just-align
9044 (run-hooks 'org-after-tags-change-hook)))))
9046 (defun org-change-tag-in-region (beg end tag off)
9047 "Add or remove TAG for each entry in the region.
9048 This works in the agenda, and also in an org-mode buffer."
9049 (interactive
9050 (list (region-beginning) (region-end)
9051 (let ((org-last-tags-completion-table
9052 (if (org-mode-p)
9053 (org-get-buffer-tags)
9054 (org-global-tags-completion-table))))
9055 (completing-read
9056 "Tag: " 'org-tags-completion-function nil nil nil
9057 'org-tags-history))
9058 (progn
9059 (message "[s]et or [r]emove? ")
9060 (equal (read-char-exclusive) ?r))))
9061 (if (fboundp 'deactivate-mark) (deactivate-mark))
9062 (let ((agendap (equal major-mode 'org-agenda-mode))
9063 l1 l2 m buf pos newhead (cnt 0))
9064 (goto-char end)
9065 (setq l2 (1- (org-current-line)))
9066 (goto-char beg)
9067 (setq l1 (org-current-line))
9068 (loop for l from l1 to l2 do
9069 (goto-line l)
9070 (setq m (get-text-property (point) 'org-hd-marker))
9071 (when (or (and (org-mode-p) (org-on-heading-p))
9072 (and agendap m))
9073 (setq buf (if agendap (marker-buffer m) (current-buffer))
9074 pos (if agendap m (point)))
9075 (with-current-buffer buf
9076 (save-excursion
9077 (save-restriction
9078 (goto-char pos)
9079 (setq cnt (1+ cnt))
9080 (org-toggle-tag tag (if off 'off 'on))
9081 (setq newhead (org-get-heading)))))
9082 (and agendap (org-agenda-change-all-lines newhead m))))
9083 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9085 (defun org-tags-completion-function (string predicate &optional flag)
9086 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9087 (confirm (lambda (x) (stringp (car x)))))
9088 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9089 (setq s1 (match-string 1 string)
9090 s2 (match-string 2 string))
9091 (setq s1 "" s2 string))
9092 (cond
9093 ((eq flag nil)
9094 ;; try completion
9095 (setq rtn (try-completion s2 ctable confirm))
9096 (if (stringp rtn)
9097 (setq rtn
9098 (concat s1 s2 (substring rtn (length s2))
9099 (if (and org-add-colon-after-tag-completion
9100 (assoc rtn ctable))
9101 ":" ""))))
9102 rtn)
9103 ((eq flag t)
9104 ;; all-completions
9105 (all-completions s2 ctable confirm)
9107 ((eq flag 'lambda)
9108 ;; exact match?
9109 (assoc s2 ctable)))
9112 (defun org-fast-tag-insert (kwd tags face &optional end)
9113 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9114 (insert (format "%-12s" (concat kwd ":"))
9115 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9116 (or end "")))
9118 (defun org-fast-tag-show-exit (flag)
9119 (save-excursion
9120 (goto-line 3)
9121 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9122 (replace-match ""))
9123 (when flag
9124 (end-of-line 1)
9125 (move-to-column (- (window-width) 19) t)
9126 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9128 (defun org-set-current-tags-overlay (current prefix)
9129 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9130 (if (featurep 'xemacs)
9131 (org-overlay-display org-tags-overlay (concat prefix s)
9132 'secondary-selection)
9133 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9134 (org-overlay-display org-tags-overlay (concat prefix s)))))
9136 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9137 "Fast tag selection with single keys.
9138 CURRENT is the current list of tags in the headline, INHERITED is the
9139 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9140 possibly with grouping information. TODO-TABLE is a similar table with
9141 TODO keywords, should these have keys assigned to them.
9142 If the keys are nil, a-z are automatically assigned.
9143 Returns the new tags string, or nil to not change the current settings."
9144 (let* ((fulltable (append table todo-table))
9145 (maxlen (apply 'max (mapcar
9146 (lambda (x)
9147 (if (stringp (car x)) (string-width (car x)) 0))
9148 fulltable)))
9149 (buf (current-buffer))
9150 (expert (eq org-fast-tag-selection-single-key 'expert))
9151 (buffer-tags nil)
9152 (fwidth (+ maxlen 3 1 3))
9153 (ncol (/ (- (window-width) 4) fwidth))
9154 (i-face 'org-done)
9155 (c-face 'org-todo)
9156 tg cnt e c char c1 c2 ntable tbl rtn
9157 ov-start ov-end ov-prefix
9158 (exit-after-next org-fast-tag-selection-single-key)
9159 (done-keywords org-done-keywords)
9160 groups ingroup)
9161 (save-excursion
9162 (beginning-of-line 1)
9163 (if (looking-at
9164 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9165 (setq ov-start (match-beginning 1)
9166 ov-end (match-end 1)
9167 ov-prefix "")
9168 (setq ov-start (1- (point-at-eol))
9169 ov-end (1+ ov-start))
9170 (skip-chars-forward "^\n\r")
9171 (setq ov-prefix
9172 (concat
9173 (buffer-substring (1- (point)) (point))
9174 (if (> (current-column) org-tags-column)
9176 (make-string (- org-tags-column (current-column)) ?\ ))))))
9177 (org-move-overlay org-tags-overlay ov-start ov-end)
9178 (save-window-excursion
9179 (if expert
9180 (set-buffer (get-buffer-create " *Org tags*"))
9181 (delete-other-windows)
9182 (split-window-vertically)
9183 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9184 (erase-buffer)
9185 (org-set-local 'org-done-keywords done-keywords)
9186 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9187 (org-fast-tag-insert "Current" current c-face "\n\n")
9188 (org-fast-tag-show-exit exit-after-next)
9189 (org-set-current-tags-overlay current ov-prefix)
9190 (setq tbl fulltable char ?a cnt 0)
9191 (while (setq e (pop tbl))
9192 (cond
9193 ((equal e '(:startgroup))
9194 (push '() groups) (setq ingroup t)
9195 (when (not (= cnt 0))
9196 (setq cnt 0)
9197 (insert "\n"))
9198 (insert "{ "))
9199 ((equal e '(:endgroup))
9200 (setq ingroup nil cnt 0)
9201 (insert "}\n"))
9203 (setq tg (car e) c2 nil)
9204 (if (cdr e)
9205 (setq c (cdr e))
9206 ;; automatically assign a character.
9207 (setq c1 (string-to-char
9208 (downcase (substring
9209 tg (if (= (string-to-char tg) ?@) 1 0)))))
9210 (if (or (rassoc c1 ntable) (rassoc c1 table))
9211 (while (or (rassoc char ntable) (rassoc char table))
9212 (setq char (1+ char)))
9213 (setq c2 c1))
9214 (setq c (or c2 char)))
9215 (if ingroup (push tg (car groups)))
9216 (setq tg (org-add-props tg nil 'face
9217 (cond
9218 ((not (assoc tg table))
9219 (org-get-todo-face tg))
9220 ((member tg current) c-face)
9221 ((member tg inherited) i-face)
9222 (t nil))))
9223 (if (and (= cnt 0) (not ingroup)) (insert " "))
9224 (insert "[" c "] " tg (make-string
9225 (- fwidth 4 (length tg)) ?\ ))
9226 (push (cons tg c) ntable)
9227 (when (= (setq cnt (1+ cnt)) ncol)
9228 (insert "\n")
9229 (if ingroup (insert " "))
9230 (setq cnt 0)))))
9231 (setq ntable (nreverse ntable))
9232 (insert "\n")
9233 (goto-char (point-min))
9234 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9235 (fit-window-to-buffer))
9236 (setq rtn
9237 (catch 'exit
9238 (while t
9239 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9240 (if groups " [!] no groups" " [!]groups")
9241 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9242 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9243 (cond
9244 ((= c ?\r) (throw 'exit t))
9245 ((= c ?!)
9246 (setq groups (not groups))
9247 (goto-char (point-min))
9248 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9249 ((= c ?\C-c)
9250 (if (not expert)
9251 (org-fast-tag-show-exit
9252 (setq exit-after-next (not exit-after-next)))
9253 (setq expert nil)
9254 (delete-other-windows)
9255 (split-window-vertically)
9256 (org-switch-to-buffer-other-window " *Org tags*")
9257 (and (fboundp 'fit-window-to-buffer)
9258 (fit-window-to-buffer))))
9259 ((or (= c ?\C-g)
9260 (and (= c ?q) (not (rassoc c ntable))))
9261 (org-detach-overlay org-tags-overlay)
9262 (setq quit-flag t))
9263 ((= c ?\ )
9264 (setq current nil)
9265 (if exit-after-next (setq exit-after-next 'now)))
9266 ((= c ?\t)
9267 (condition-case nil
9268 (setq tg (completing-read
9269 "Tag: "
9270 (or buffer-tags
9271 (with-current-buffer buf
9272 (org-get-buffer-tags)))))
9273 (quit (setq tg "")))
9274 (when (string-match "\\S-" tg)
9275 (add-to-list 'buffer-tags (list tg))
9276 (if (member tg current)
9277 (setq current (delete tg current))
9278 (push tg current)))
9279 (if exit-after-next (setq exit-after-next 'now)))
9280 ((setq e (rassoc c todo-table) tg (car e))
9281 (with-current-buffer buf
9282 (save-excursion (org-todo tg)))
9283 (if exit-after-next (setq exit-after-next 'now)))
9284 ((setq e (rassoc c ntable) tg (car e))
9285 (if (member tg current)
9286 (setq current (delete tg current))
9287 (loop for g in groups do
9288 (if (member tg g)
9289 (mapc (lambda (x)
9290 (setq current (delete x current)))
9291 g)))
9292 (push tg current))
9293 (if exit-after-next (setq exit-after-next 'now))))
9295 ;; Create a sorted list
9296 (setq current
9297 (sort current
9298 (lambda (a b)
9299 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9300 (if (eq exit-after-next 'now) (throw 'exit t))
9301 (goto-char (point-min))
9302 (beginning-of-line 2)
9303 (delete-region (point) (point-at-eol))
9304 (org-fast-tag-insert "Current" current c-face)
9305 (org-set-current-tags-overlay current ov-prefix)
9306 (while (re-search-forward
9307 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9308 (setq tg (match-string 1))
9309 (add-text-properties
9310 (match-beginning 1) (match-end 1)
9311 (list 'face
9312 (cond
9313 ((member tg current) c-face)
9314 ((member tg inherited) i-face)
9315 (t (get-text-property (match-beginning 1) 'face))))))
9316 (goto-char (point-min)))))
9317 (org-detach-overlay org-tags-overlay)
9318 (if rtn
9319 (mapconcat 'identity current ":")
9320 nil))))
9322 (defun org-get-tags-string ()
9323 "Get the TAGS string in the current headline."
9324 (unless (org-on-heading-p t)
9325 (error "Not on a heading"))
9326 (save-excursion
9327 (beginning-of-line 1)
9328 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9329 (org-match-string-no-properties 1)
9330 "")))
9332 (defun org-get-tags ()
9333 "Get the list of tags specified in the current headline."
9334 (org-split-string (org-get-tags-string) ":"))
9336 (defun org-get-buffer-tags ()
9337 "Get a table of all tags used in the buffer, for completion."
9338 (let (tags)
9339 (save-excursion
9340 (goto-char (point-min))
9341 (while (re-search-forward
9342 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9343 (when (equal (char-after (point-at-bol 0)) ?*)
9344 (mapc (lambda (x) (add-to-list 'tags x))
9345 (org-split-string (org-match-string-no-properties 1) ":")))))
9346 (mapcar 'list tags)))
9349 ;;;; Properties
9351 ;;; Setting and retrieving properties
9353 (defconst org-special-properties
9354 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9355 "TIMESTAMP" "TIMESTAMP_IA")
9356 "The special properties valid in Org-mode.
9358 These are properties that are not defined in the property drawer,
9359 but in some other way.")
9361 (defconst org-default-properties
9362 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9363 "LOCATION" "LOGGING" "COLUMNS")
9364 "Some properties that are used by Org-mode for various purposes.
9365 Being in this list makes sure that they are offered for completion.")
9367 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9368 "Regular expression matching the first line of a property drawer.")
9370 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9371 "Regular expression matching the first line of a property drawer.")
9373 (defun org-property-action ()
9374 "Do an action on properties."
9375 (interactive)
9376 (let (c)
9377 (org-at-property-p)
9378 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9379 (setq c (read-char-exclusive))
9380 (cond
9381 ((equal c ?s)
9382 (call-interactively 'org-set-property))
9383 ((equal c ?d)
9384 (call-interactively 'org-delete-property))
9385 ((equal c ?D)
9386 (call-interactively 'org-delete-property-globally))
9387 ((equal c ?c)
9388 (call-interactively 'org-compute-property-at-point))
9389 (t (error "No such property action %c" c)))))
9391 (defun org-at-property-p ()
9392 "Is the cursor in a property line?"
9393 ;; FIXME: Does not check if we are actually in the drawer.
9394 ;; FIXME: also returns true on any drawers.....
9395 ;; This is used by C-c C-c for property action.
9396 (save-excursion
9397 (beginning-of-line 1)
9398 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9400 (defun org-get-property-block (&optional beg end force)
9401 "Return the (beg . end) range of the body of the property drawer.
9402 BEG and END can be beginning and end of subtree, if not given
9403 they will be found.
9404 If the drawer does not exist and FORCE is non-nil, create the drawer."
9405 (catch 'exit
9406 (save-excursion
9407 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9408 (end (or end (progn (outline-next-heading) (point)))))
9409 (goto-char beg)
9410 (if (re-search-forward org-property-start-re end t)
9411 (setq beg (1+ (match-end 0)))
9412 (if force
9413 (save-excursion
9414 (org-insert-property-drawer)
9415 (setq end (progn (outline-next-heading) (point))))
9416 (throw 'exit nil))
9417 (goto-char beg)
9418 (if (re-search-forward org-property-start-re end t)
9419 (setq beg (1+ (match-end 0)))))
9420 (if (re-search-forward org-property-end-re end t)
9421 (setq end (match-beginning 0))
9422 (or force (throw 'exit nil))
9423 (goto-char beg)
9424 (setq end beg)
9425 (org-indent-line-function)
9426 (insert ":END:\n"))
9427 (cons beg end)))))
9429 (defun org-entry-properties (&optional pom which)
9430 "Get all properties of the entry at point-or-marker POM.
9431 This includes the TODO keyword, the tags, time strings for deadline,
9432 scheduled, and clocking, and any additional properties defined in the
9433 entry. The return value is an alist, keys may occur multiple times
9434 if the property key was used several times.
9435 POM may also be nil, in which case the current entry is used.
9436 If WHICH is nil or `all', get all properties. If WHICH is
9437 `special' or `standard', only get that subclass."
9438 (setq which (or which 'all))
9439 (org-with-point-at pom
9440 (let ((clockstr (substring org-clock-string 0 -1))
9441 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9442 beg end range props sum-props key value string clocksum)
9443 (save-excursion
9444 (when (condition-case nil (org-back-to-heading t) (error nil))
9445 (setq beg (point))
9446 (setq sum-props (get-text-property (point) 'org-summaries))
9447 (setq clocksum (get-text-property (point) :org-clock-minutes))
9448 (outline-next-heading)
9449 (setq end (point))
9450 (when (memq which '(all special))
9451 ;; Get the special properties, like TODO and tags
9452 (goto-char beg)
9453 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9454 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9455 (when (looking-at org-priority-regexp)
9456 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9457 (when (and (setq value (org-get-tags-string))
9458 (string-match "\\S-" value))
9459 (push (cons "TAGS" value) props))
9460 (when (setq value (org-get-tags-at))
9461 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9462 props))
9463 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9464 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9465 string (if (equal key clockstr)
9466 (org-no-properties
9467 (org-trim
9468 (buffer-substring
9469 (match-beginning 3) (goto-char (point-at-eol)))))
9470 (substring (org-match-string-no-properties 3) 1 -1)))
9471 (unless key
9472 (if (= (char-after (match-beginning 3)) ?\[)
9473 (setq key "TIMESTAMP_IA")
9474 (setq key "TIMESTAMP")))
9475 (when (or (equal key clockstr) (not (assoc key props)))
9476 (push (cons key string) props)))
9480 (when (memq which '(all standard))
9481 ;; Get the standard properties, like :PORP: ...
9482 (setq range (org-get-property-block beg end))
9483 (when range
9484 (goto-char (car range))
9485 (while (re-search-forward
9486 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9487 (cdr range) t)
9488 (setq key (org-match-string-no-properties 1)
9489 value (org-trim (or (org-match-string-no-properties 2) "")))
9490 (unless (member key excluded)
9491 (push (cons key (or value "")) props)))))
9492 (if clocksum
9493 (push (cons "CLOCKSUM"
9494 (org-columns-number-to-string (/ (float clocksum) 60.)
9495 'add_times))
9496 props))
9497 (append sum-props (nreverse props)))))))
9499 (defun org-entry-get (pom property &optional inherit)
9500 "Get value of PROPERTY for entry at point-or-marker POM.
9501 If INHERIT is non-nil and the entry does not have the property,
9502 then also check higher levels of the hierarchy.
9503 If INHERIT is the symbol `selective', use inheritance only if the setting
9504 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9505 If the property is present but empty, the return value is the empty string.
9506 If the property is not present at all, nil is returned."
9507 (org-with-point-at pom
9508 (if (and inherit (if (eq inherit 'selective)
9509 (org-property-inherit-p property)
9511 (org-entry-get-with-inheritance property)
9512 (if (member property org-special-properties)
9513 ;; We need a special property. Use brute force, get all properties.
9514 (cdr (assoc property (org-entry-properties nil 'special)))
9515 (let ((range (org-get-property-block)))
9516 (if (and range
9517 (goto-char (car range))
9518 (re-search-forward
9519 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9520 (cdr range) t))
9521 ;; Found the property, return it.
9522 (if (match-end 1)
9523 (org-match-string-no-properties 1)
9524 "")))))))
9526 (defun org-property-or-variable-value (var &optional inherit)
9527 "Check if there is a property fixing the value of VAR.
9528 If yes, return this value. If not, return the current value of the variable."
9529 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9530 (if (and prop (stringp prop) (string-match "\\S-" prop))
9531 (read prop)
9532 (symbol-value var))))
9534 (defun org-entry-delete (pom property)
9535 "Delete the property PROPERTY from entry at point-or-marker POM."
9536 (org-with-point-at pom
9537 (if (member property org-special-properties)
9538 nil ; cannot delete these properties.
9539 (let ((range (org-get-property-block)))
9540 (if (and range
9541 (goto-char (car range))
9542 (re-search-forward
9543 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9544 (cdr range) t))
9545 (progn
9546 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9548 nil)))))
9550 ;; Multi-values properties are properties that contain multiple values
9551 ;; These values are assumed to be single words, separated by whitespace.
9552 (defun org-entry-add-to-multivalued-property (pom property value)
9553 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9554 (let* ((old (org-entry-get pom property))
9555 (values (and old (org-split-string old "[ \t]"))))
9556 (unless (member value values)
9557 (setq values (cons value values))
9558 (org-entry-put pom property
9559 (mapconcat 'identity values " ")))))
9561 (defun org-entry-remove-from-multivalued-property (pom property value)
9562 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9563 (let* ((old (org-entry-get pom property))
9564 (values (and old (org-split-string old "[ \t]"))))
9565 (when (member value values)
9566 (setq values (delete value values))
9567 (org-entry-put pom property
9568 (mapconcat 'identity values " ")))))
9570 (defun org-entry-member-in-multivalued-property (pom property value)
9571 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9572 (let* ((old (org-entry-get pom property))
9573 (values (and old (org-split-string old "[ \t]"))))
9574 (member value values)))
9576 (defvar org-entry-property-inherited-from (make-marker))
9578 (defun org-entry-get-with-inheritance (property)
9579 "Get entry property, and search higher levels if not present."
9580 (let (tmp)
9581 (save-excursion
9582 (save-restriction
9583 (widen)
9584 (catch 'ex
9585 (while t
9586 (when (setq tmp (org-entry-get nil property))
9587 (org-back-to-heading t)
9588 (move-marker org-entry-property-inherited-from (point))
9589 (throw 'ex tmp))
9590 (or (org-up-heading-safe) (throw 'ex nil)))))
9591 (or tmp (cdr (assoc property org-local-properties))
9592 (cdr (assoc property org-global-properties))))))
9594 (defun org-entry-put (pom property value)
9595 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9596 (org-with-point-at pom
9597 (org-back-to-heading t)
9598 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9599 range)
9600 (cond
9601 ((equal property "TODO")
9602 (when (and (stringp value) (string-match "\\S-" value)
9603 (not (member value org-todo-keywords-1)))
9604 (error "\"%s\" is not a valid TODO state" value))
9605 (if (or (not value)
9606 (not (string-match "\\S-" value)))
9607 (setq value 'none))
9608 (org-todo value)
9609 (org-set-tags nil 'align))
9610 ((equal property "PRIORITY")
9611 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9612 (string-to-char value) ?\ ))
9613 (org-set-tags nil 'align))
9614 ((equal property "SCHEDULED")
9615 (if (re-search-forward org-scheduled-time-regexp end t)
9616 (cond
9617 ((eq value 'earlier) (org-timestamp-change -1 'day))
9618 ((eq value 'later) (org-timestamp-change 1 'day))
9619 (t (call-interactively 'org-schedule)))
9620 (call-interactively 'org-schedule)))
9621 ((equal property "DEADLINE")
9622 (if (re-search-forward org-deadline-time-regexp end t)
9623 (cond
9624 ((eq value 'earlier) (org-timestamp-change -1 'day))
9625 ((eq value 'later) (org-timestamp-change 1 'day))
9626 (t (call-interactively 'org-deadline)))
9627 (call-interactively 'org-deadline)))
9628 ((member property org-special-properties)
9629 (error "The %s property can not yet be set with `org-entry-put'"
9630 property))
9631 (t ; a non-special property
9632 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9633 (setq range (org-get-property-block beg end 'force))
9634 (goto-char (car range))
9635 (if (re-search-forward
9636 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9637 (progn
9638 (delete-region (match-beginning 1) (match-end 1))
9639 (goto-char (match-beginning 1)))
9640 (goto-char (cdr range))
9641 (insert "\n")
9642 (backward-char 1)
9643 (org-indent-line-function)
9644 (insert ":" property ":"))
9645 (and value (insert " " value))
9646 (org-indent-line-function)))))))
9648 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9649 "Get all property keys in the current buffer.
9650 With INCLUDE-SPECIALS, also list the special properties that relect things
9651 like tags and TODO state.
9652 With INCLUDE-DEFAULTS, also include properties that has special meaning
9653 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9654 With INCLUDE-COLUMNS, also include property names given in COLUMN
9655 formats in the current buffer."
9656 (let (rtn range cfmt cols s p)
9657 (save-excursion
9658 (save-restriction
9659 (widen)
9660 (goto-char (point-min))
9661 (while (re-search-forward org-property-start-re nil t)
9662 (setq range (org-get-property-block))
9663 (goto-char (car range))
9664 (while (re-search-forward
9665 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9666 (cdr range) t)
9667 (add-to-list 'rtn (org-match-string-no-properties 1)))
9668 (outline-next-heading))))
9670 (when include-specials
9671 (setq rtn (append org-special-properties rtn)))
9673 (when include-defaults
9674 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9676 (when include-columns
9677 (save-excursion
9678 (save-restriction
9679 (widen)
9680 (goto-char (point-min))
9681 (while (re-search-forward
9682 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9683 nil t)
9684 (setq cfmt (match-string 2) s 0)
9685 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9686 cfmt s)
9687 (setq s (match-end 0)
9688 p (match-string 1 cfmt))
9689 (unless (or (equal p "ITEM")
9690 (member p org-special-properties))
9691 (add-to-list 'rtn (match-string 1 cfmt))))))))
9693 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9695 (defun org-property-values (key)
9696 "Return a list of all values of property KEY."
9697 (save-excursion
9698 (save-restriction
9699 (widen)
9700 (goto-char (point-min))
9701 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9702 values)
9703 (while (re-search-forward re nil t)
9704 (add-to-list 'values (org-trim (match-string 1))))
9705 (delete "" values)))))
9707 (defun org-insert-property-drawer ()
9708 "Insert a property drawer into the current entry."
9709 (interactive)
9710 (org-back-to-heading t)
9711 (looking-at outline-regexp)
9712 (let ((indent (- (match-end 0)(match-beginning 0)))
9713 (beg (point))
9714 (re (concat "^[ \t]*" org-keyword-time-regexp))
9715 end hiddenp)
9716 (outline-next-heading)
9717 (setq end (point))
9718 (goto-char beg)
9719 (while (re-search-forward re end t))
9720 (setq hiddenp (org-invisible-p))
9721 (end-of-line 1)
9722 (and (equal (char-after) ?\n) (forward-char 1))
9723 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
9724 (beginning-of-line 2))
9725 (org-skip-over-state-notes)
9726 (skip-chars-backward " \t\n\r")
9727 (if (eq (char-before) ?*) (forward-char 1))
9728 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
9729 (beginning-of-line 0)
9730 (indent-to-column indent)
9731 (beginning-of-line 2)
9732 (indent-to-column indent)
9733 (beginning-of-line 0)
9734 (if hiddenp
9735 (save-excursion
9736 (org-back-to-heading t)
9737 (hide-entry))
9738 (org-flag-drawer t))))
9740 (defun org-set-property (property value)
9741 "In the current entry, set PROPERTY to VALUE.
9742 When called interactively, this will prompt for a property name, offering
9743 completion on existing and default properties. And then it will prompt
9744 for a value, offering competion either on allowed values (via an inherited
9745 xxx_ALL property) or on existing values in other instances of this property
9746 in the current file."
9747 (interactive
9748 (let* ((prop (completing-read
9749 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
9750 (cur (org-entry-get nil prop))
9751 (allowed (org-property-get-allowed-values nil prop 'table))
9752 (existing (mapcar 'list (org-property-values prop)))
9753 (val (if allowed
9754 (completing-read "Value: " allowed nil 'req-match)
9755 (completing-read
9756 (concat "Value" (if (and cur (string-match "\\S-" cur))
9757 (concat "[" cur "]") "")
9758 ": ")
9759 existing nil nil "" nil cur))))
9760 (list prop (if (equal val "") cur val))))
9761 (unless (equal (org-entry-get nil property) value)
9762 (org-entry-put nil property value)))
9764 (defun org-delete-property (property)
9765 "In the current entry, delete PROPERTY."
9766 (interactive
9767 (let* ((prop (completing-read
9768 "Property: " (org-entry-properties nil 'standard))))
9769 (list prop)))
9770 (message "Property %s %s" property
9771 (if (org-entry-delete nil property)
9772 "deleted"
9773 "was not present in the entry")))
9775 (defun org-delete-property-globally (property)
9776 "Remove PROPERTY globally, from all entries."
9777 (interactive
9778 (let* ((prop (completing-read
9779 "Globally remove property: "
9780 (mapcar 'list (org-buffer-property-keys)))))
9781 (list prop)))
9782 (save-excursion
9783 (save-restriction
9784 (widen)
9785 (goto-char (point-min))
9786 (let ((cnt 0))
9787 (while (re-search-forward
9788 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
9789 nil t)
9790 (setq cnt (1+ cnt))
9791 (replace-match ""))
9792 (message "Property \"%s\" removed from %d entries" property cnt)))))
9794 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
9796 (defun org-compute-property-at-point ()
9797 "Compute the property at point.
9798 This looks for an enclosing column format, extracts the operator and
9799 then applies it to the proerty in the column format's scope."
9800 (interactive)
9801 (unless (org-at-property-p)
9802 (error "Not at a property"))
9803 (let ((prop (org-match-string-no-properties 2)))
9804 (org-columns-get-format-and-top-level)
9805 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
9806 (error "No operator defined for property %s" prop))
9807 (org-columns-compute prop)))
9809 (defun org-property-get-allowed-values (pom property &optional table)
9810 "Get allowed values for the property PROPERTY.
9811 When TABLE is non-nil, return an alist that can directly be used for
9812 completion."
9813 (let (vals)
9814 (cond
9815 ((equal property "TODO")
9816 (setq vals (org-with-point-at pom
9817 (append org-todo-keywords-1 '("")))))
9818 ((equal property "PRIORITY")
9819 (let ((n org-lowest-priority))
9820 (while (>= n org-highest-priority)
9821 (push (char-to-string n) vals)
9822 (setq n (1- n)))))
9823 ((member property org-special-properties))
9825 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
9827 (when (and vals (string-match "\\S-" vals))
9828 (setq vals (car (read-from-string (concat "(" vals ")"))))
9829 (setq vals (mapcar (lambda (x)
9830 (cond ((stringp x) x)
9831 ((numberp x) (number-to-string x))
9832 ((symbolp x) (symbol-name x))
9833 (t "???")))
9834 vals)))))
9835 (if table (mapcar 'list vals) vals)))
9837 (defun org-property-previous-allowed-value (&optional previous)
9838 "Switch to the next allowed value for this property."
9839 (interactive)
9840 (org-property-next-allowed-value t))
9842 (defun org-property-next-allowed-value (&optional previous)
9843 "Switch to the next allowed value for this property."
9844 (interactive)
9845 (unless (org-at-property-p)
9846 (error "Not at a property"))
9847 (let* ((key (match-string 2))
9848 (value (match-string 3))
9849 (allowed (or (org-property-get-allowed-values (point) key)
9850 (and (member value '("[ ]" "[-]" "[X]"))
9851 '("[ ]" "[X]"))))
9852 nval)
9853 (unless allowed
9854 (error "Allowed values for this property have not been defined"))
9855 (if previous (setq allowed (reverse allowed)))
9856 (if (member value allowed)
9857 (setq nval (car (cdr (member value allowed)))))
9858 (setq nval (or nval (car allowed)))
9859 (if (equal nval value)
9860 (error "Only one allowed value for this property"))
9861 (org-at-property-p)
9862 (replace-match (concat " :" key ": " nval) t t)
9863 (org-indent-line-function)
9864 (beginning-of-line 1)
9865 (skip-chars-forward " \t")))
9867 (defun org-find-entry-with-id (ident)
9868 "Locate the entry that contains the ID property with exact value IDENT.
9869 IDENT can be a string, a symbol or a number, this function will search for
9870 the string representation of it.
9871 Return the position where this entry starts, or nil if there is no such entry."
9872 (let ((id (cond
9873 ((stringp ident) ident)
9874 ((symbol-name ident) (symbol-name ident))
9875 ((numberp ident) (number-to-string ident))
9876 (t (error "IDENT %s must be a string, symbol or number" ident))))
9877 (case-fold-search nil))
9878 (save-excursion
9879 (save-restriction
9880 (widen)
9881 (goto-char (point-min))
9882 (when (re-search-forward
9883 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
9884 nil t)
9885 (org-back-to-heading)
9886 (point))))))
9888 ;;;; Timestamps
9890 (defvar org-last-changed-timestamp nil)
9891 (defvar org-time-was-given) ; dynamically scoped parameter
9892 (defvar org-end-time-was-given) ; dynamically scoped parameter
9893 (defvar org-ts-what) ; dynamically scoped parameter
9895 (defun org-time-stamp (arg)
9896 "Prompt for a date/time and insert a time stamp.
9897 If the user specifies a time like HH:MM, or if this command is called
9898 with a prefix argument, the time stamp will contain date and time.
9899 Otherwise, only the date will be included. All parts of a date not
9900 specified by the user will be filled in from the current date/time.
9901 So if you press just return without typing anything, the time stamp
9902 will represent the current date/time. If there is already a timestamp
9903 at the cursor, it will be modified."
9904 (interactive "P")
9905 (let* ((ts nil)
9906 (default-time
9907 ;; Default time is either today, or, when entering a range,
9908 ;; the range start.
9909 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
9910 (save-excursion
9911 (re-search-backward
9912 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
9913 (- (point) 20) t)))
9914 (apply 'encode-time (org-parse-time-string (match-string 1)))
9915 (current-time)))
9916 (default-input (and ts (org-get-compact-tod ts)))
9917 org-time-was-given org-end-time-was-given time)
9918 (cond
9919 ((and (org-at-timestamp-p)
9920 (eq last-command 'org-time-stamp)
9921 (eq this-command 'org-time-stamp))
9922 (insert "--")
9923 (setq time (let ((this-command this-command))
9924 (org-read-date arg 'totime nil nil default-time default-input)))
9925 (org-insert-time-stamp time (or org-time-was-given arg)))
9926 ((org-at-timestamp-p)
9927 (setq time (let ((this-command this-command))
9928 (org-read-date arg 'totime nil nil default-time default-input)))
9929 (when (org-at-timestamp-p) ; just to get the match data
9930 (replace-match "")
9931 (setq org-last-changed-timestamp
9932 (org-insert-time-stamp
9933 time (or org-time-was-given arg)
9934 nil nil nil (list org-end-time-was-given))))
9935 (message "Timestamp updated"))
9937 (setq time (let ((this-command this-command))
9938 (org-read-date arg 'totime nil nil default-time default-input)))
9939 (org-insert-time-stamp time (or org-time-was-given arg)
9940 nil nil nil (list org-end-time-was-given))))))
9942 ;; FIXME: can we use this for something else, like computing time differences?
9943 (defun org-get-compact-tod (s)
9944 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
9945 (let* ((t1 (match-string 1 s))
9946 (h1 (string-to-number (match-string 2 s)))
9947 (m1 (string-to-number (match-string 3 s)))
9948 (t2 (and (match-end 4) (match-string 5 s)))
9949 (h2 (and t2 (string-to-number (match-string 6 s))))
9950 (m2 (and t2 (string-to-number (match-string 7 s))))
9951 dh dm)
9952 (if (not t2)
9954 (setq dh (- h2 h1) dm (- m2 m1))
9955 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
9956 (concat t1 "+" (number-to-string dh)
9957 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
9959 (defun org-time-stamp-inactive (&optional arg)
9960 "Insert an inactive time stamp.
9961 An inactive time stamp is enclosed in square brackets instead of angle
9962 brackets. It is inactive in the sense that it does not trigger agenda entries,
9963 does not link to the calendar and cannot be changed with the S-cursor keys.
9964 So these are more for recording a certain time/date."
9965 (interactive "P")
9966 (let (org-time-was-given org-end-time-was-given time)
9967 (setq time (org-read-date arg 'totime))
9968 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
9969 nil nil (list org-end-time-was-given))))
9971 (defvar org-date-ovl (org-make-overlay 1 1))
9972 (org-overlay-put org-date-ovl 'face 'org-warning)
9973 (org-detach-overlay org-date-ovl)
9975 (defvar org-ans1) ; dynamically scoped parameter
9976 (defvar org-ans2) ; dynamically scoped parameter
9978 (defvar org-plain-time-of-day-regexp) ; defined below
9980 (defvar org-read-date-overlay nil)
9981 (defvar org-dcst nil) ; dynamically scoped
9983 (defun org-read-date (&optional with-time to-time from-string prompt
9984 default-time default-input)
9985 "Read a date, possibly a time, and make things smooth for the user.
9986 The prompt will suggest to enter an ISO date, but you can also enter anything
9987 which will at least partially be understood by `parse-time-string'.
9988 Unrecognized parts of the date will default to the current day, month, year,
9989 hour and minute. If this command is called to replace a timestamp at point,
9990 of to enter the second timestamp of a range, the default time is taken from the
9991 existing stamp. For example,
9992 3-2-5 --> 2003-02-05
9993 feb 15 --> currentyear-02-15
9994 sep 12 9 --> 2009-09-12
9995 12:45 --> today 12:45
9996 22 sept 0:34 --> currentyear-09-22 0:34
9997 12 --> currentyear-currentmonth-12
9998 Fri --> nearest Friday (today or later)
9999 etc.
10001 Furthermore you can specify a relative date by giving, as the *first* thing
10002 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10003 change in days weeks, months, years.
10004 With a single plus or minus, the date is relative to today. With a double
10005 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10006 +4d --> four days from today
10007 +4 --> same as above
10008 +2w --> two weeks from today
10009 ++5 --> five days from default date
10011 The function understands only English month and weekday abbreviations,
10012 but this can be configured with the variables `parse-time-months' and
10013 `parse-time-weekdays'.
10015 While prompting, a calendar is popped up - you can also select the
10016 date with the mouse (button 1). The calendar shows a period of three
10017 months. To scroll it to other months, use the keys `>' and `<'.
10018 If you don't like the calendar, turn it off with
10019 \(setq org-read-date-popup-calendar nil)
10021 With optional argument TO-TIME, the date will immediately be converted
10022 to an internal time.
10023 With an optional argument WITH-TIME, the prompt will suggest to also
10024 insert a time. Note that when WITH-TIME is not set, you can still
10025 enter a time, and this function will inform the calling routine about
10026 this change. The calling routine may then choose to change the format
10027 used to insert the time stamp into the buffer to include the time.
10028 With optional argument FROM-STRING, read from this string instead from
10029 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10030 the time/date that is used for everything that is not specified by the
10031 user."
10032 (require 'parse-time)
10033 (let* ((org-time-stamp-rounding-minutes
10034 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10035 (org-dcst org-display-custom-times)
10036 (ct (org-current-time))
10037 (def (or default-time ct))
10038 (defdecode (decode-time def))
10039 (dummy (progn
10040 (when (< (nth 2 defdecode) org-extend-today-until)
10041 (setcar (nthcdr 2 defdecode) -1)
10042 (setcar (nthcdr 1 defdecode) 59)
10043 (setq def (apply 'encode-time defdecode)
10044 defdecode (decode-time def)))))
10045 (calendar-move-hook nil)
10046 (calendar-view-diary-initially-flag nil)
10047 (view-diary-entries-initially nil)
10048 (calendar-view-holidays-initially-flag nil)
10049 (view-calendar-holidays-initially nil)
10050 (timestr (format-time-string
10051 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10052 (prompt (concat (if prompt (concat prompt " ") "")
10053 (format "Date+time [%s]: " timestr)))
10054 ans (org-ans0 "") org-ans1 org-ans2 final)
10056 (cond
10057 (from-string (setq ans from-string))
10058 (org-read-date-popup-calendar
10059 (save-excursion
10060 (save-window-excursion
10061 (calendar)
10062 (calendar-forward-day (- (time-to-days def)
10063 (calendar-absolute-from-gregorian
10064 (calendar-current-date))))
10065 (org-eval-in-calendar nil t)
10066 (let* ((old-map (current-local-map))
10067 (map (copy-keymap calendar-mode-map))
10068 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10069 (org-defkey map (kbd "RET") 'org-calendar-select)
10070 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10071 'org-calendar-select-mouse)
10072 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10073 'org-calendar-select-mouse)
10074 (org-defkey minibuffer-local-map [(meta shift left)]
10075 (lambda () (interactive)
10076 (org-eval-in-calendar '(calendar-backward-month 1))))
10077 (org-defkey minibuffer-local-map [(meta shift right)]
10078 (lambda () (interactive)
10079 (org-eval-in-calendar '(calendar-forward-month 1))))
10080 (org-defkey minibuffer-local-map [(meta shift up)]
10081 (lambda () (interactive)
10082 (org-eval-in-calendar '(calendar-backward-year 1))))
10083 (org-defkey minibuffer-local-map [(meta shift down)]
10084 (lambda () (interactive)
10085 (org-eval-in-calendar '(calendar-forward-year 1))))
10086 (org-defkey minibuffer-local-map [(shift up)]
10087 (lambda () (interactive)
10088 (org-eval-in-calendar '(calendar-backward-week 1))))
10089 (org-defkey minibuffer-local-map [(shift down)]
10090 (lambda () (interactive)
10091 (org-eval-in-calendar '(calendar-forward-week 1))))
10092 (org-defkey minibuffer-local-map [(shift left)]
10093 (lambda () (interactive)
10094 (org-eval-in-calendar '(calendar-backward-day 1))))
10095 (org-defkey minibuffer-local-map [(shift right)]
10096 (lambda () (interactive)
10097 (org-eval-in-calendar '(calendar-forward-day 1))))
10098 (org-defkey minibuffer-local-map ">"
10099 (lambda () (interactive)
10100 (org-eval-in-calendar '(scroll-calendar-left 1))))
10101 (org-defkey minibuffer-local-map "<"
10102 (lambda () (interactive)
10103 (org-eval-in-calendar '(scroll-calendar-right 1))))
10104 (unwind-protect
10105 (progn
10106 (use-local-map map)
10107 (add-hook 'post-command-hook 'org-read-date-display)
10108 (setq org-ans0 (read-string prompt default-input nil nil))
10109 ;; org-ans0: from prompt
10110 ;; org-ans1: from mouse click
10111 ;; org-ans2: from calendar motion
10112 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10113 (remove-hook 'post-command-hook 'org-read-date-display)
10114 (use-local-map old-map)
10115 (when org-read-date-overlay
10116 (org-delete-overlay org-read-date-overlay)
10117 (setq org-read-date-overlay nil)))))))
10119 (t ; Naked prompt only
10120 (unwind-protect
10121 (setq ans (read-string prompt default-input nil timestr))
10122 (when org-read-date-overlay
10123 (org-delete-overlay org-read-date-overlay)
10124 (setq org-read-date-overlay nil)))))
10126 (setq final (org-read-date-analyze ans def defdecode))
10128 (if to-time
10129 (apply 'encode-time final)
10130 (if (and (boundp 'org-time-was-given) org-time-was-given)
10131 (format "%04d-%02d-%02d %02d:%02d"
10132 (nth 5 final) (nth 4 final) (nth 3 final)
10133 (nth 2 final) (nth 1 final))
10134 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10135 (defvar def)
10136 (defvar defdecode)
10137 (defvar with-time)
10138 (defun org-read-date-display ()
10139 "Display the currrent date prompt interpretation in the minibuffer."
10140 (when org-read-date-display-live
10141 (when org-read-date-overlay
10142 (org-delete-overlay org-read-date-overlay))
10143 (let ((p (point)))
10144 (end-of-line 1)
10145 (while (not (equal (buffer-substring
10146 (max (point-min) (- (point) 4)) (point))
10147 " "))
10148 (insert " "))
10149 (goto-char p))
10150 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10151 " " (or org-ans1 org-ans2)))
10152 (org-end-time-was-given nil)
10153 (f (org-read-date-analyze ans def defdecode))
10154 (fmts (if org-dcst
10155 org-time-stamp-custom-formats
10156 org-time-stamp-formats))
10157 (fmt (if (or with-time
10158 (and (boundp 'org-time-was-given) org-time-was-given))
10159 (cdr fmts)
10160 (car fmts)))
10161 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10162 (when (and org-end-time-was-given
10163 (string-match org-plain-time-of-day-regexp txt))
10164 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10165 org-end-time-was-given
10166 (substring txt (match-end 0)))))
10167 (setq org-read-date-overlay
10168 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10169 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10171 (defun org-read-date-analyze (ans def defdecode)
10172 "Analyze the combined answer of the date prompt."
10173 ;; FIXME: cleanup and comment
10174 (let (delta deltan deltaw deltadef year month day
10175 hour minute second wday pm h2 m2 tl wday1
10176 iso-year iso-weekday iso-week iso-year iso-date)
10178 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10179 (setq ans (replace-match "" t t ans)
10180 deltan (car delta)
10181 deltaw (nth 1 delta)
10182 deltadef (nth 2 delta)))
10184 ;; Check if there is an iso week date in there
10185 ;; If yes, sore the info and ostpone interpreting it until the rest
10186 ;; of the parsing is done
10187 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10188 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10189 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10190 iso-week (string-to-number (match-string 2 ans)))
10191 (setq ans (replace-match "" t t ans)))
10193 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10194 (when (string-match
10195 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10196 (setq year (if (match-end 2)
10197 (string-to-number (match-string 2 ans))
10198 (string-to-number (format-time-string "%Y")))
10199 month (string-to-number (match-string 3 ans))
10200 day (string-to-number (match-string 4 ans)))
10201 (if (< year 100) (setq year (+ 2000 year)))
10202 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10203 t nil ans)))
10204 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10205 ;; If there is a time with am/pm, and *no* time without it, we convert
10206 ;; so that matching will be successful.
10207 (loop for i from 1 to 2 do ; twice, for end time as well
10208 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10209 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10210 (setq hour (string-to-number (match-string 1 ans))
10211 minute (if (match-end 3)
10212 (string-to-number (match-string 3 ans))
10214 pm (equal ?p
10215 (string-to-char (downcase (match-string 4 ans)))))
10216 (if (and (= hour 12) (not pm))
10217 (setq hour 0)
10218 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10219 (setq ans (replace-match (format "%02d:%02d" hour minute)
10220 t t ans))))
10222 ;; Check if a time range is given as a duration
10223 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10224 (setq hour (string-to-number (match-string 1 ans))
10225 h2 (+ hour (string-to-number (match-string 3 ans)))
10226 minute (string-to-number (match-string 2 ans))
10227 m2 (+ minute (if (match-end 5) (string-to-number
10228 (match-string 5 ans))0)))
10229 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10230 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10231 t t ans)))
10233 ;; Check if there is a time range
10234 (when (boundp 'org-end-time-was-given)
10235 (setq org-time-was-given nil)
10236 (when (and (string-match org-plain-time-of-day-regexp ans)
10237 (match-end 8))
10238 (setq org-end-time-was-given (match-string 8 ans))
10239 (setq ans (concat (substring ans 0 (match-beginning 7))
10240 (substring ans (match-end 7))))))
10242 (setq tl (parse-time-string ans)
10243 day (or (nth 3 tl) (nth 3 defdecode))
10244 month (or (nth 4 tl)
10245 (if (and org-read-date-prefer-future
10246 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10247 (1+ (nth 4 defdecode))
10248 (nth 4 defdecode)))
10249 year (or (nth 5 tl)
10250 (if (and org-read-date-prefer-future
10251 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10252 (1+ (nth 5 defdecode))
10253 (nth 5 defdecode)))
10254 hour (or (nth 2 tl) (nth 2 defdecode))
10255 minute (or (nth 1 tl) (nth 1 defdecode))
10256 second (or (nth 0 tl) 0)
10257 wday (nth 6 tl))
10259 ;; Special date definitions below
10260 (cond
10261 (iso-week
10262 ;; There was an iso week
10263 (setq year (or iso-year year)
10264 day (or iso-weekday wday 1)
10265 wday nil ; to make sure that the trigger below does not match
10266 iso-date (calendar-gregorian-from-absolute
10267 (calendar-absolute-from-iso
10268 (list iso-week day year))))
10269 ; FIXME: Should we also push ISO weeks into the future?
10270 ; (when (and org-read-date-prefer-future
10271 ; (not iso-year)
10272 ; (< (calendar-absolute-from-gregorian iso-date)
10273 ; (time-to-days (current-time))))
10274 ; (setq year (1+ year)
10275 ; iso-date (calendar-gregorian-from-absolute
10276 ; (calendar-absolute-from-iso
10277 ; (list iso-week day year)))))
10278 (setq month (car iso-date)
10279 year (nth 2 iso-date)
10280 day (nth 1 iso-date)))
10281 (deltan
10282 (unless deltadef
10283 (let ((now (decode-time (current-time))))
10284 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10285 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10286 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10287 ((equal deltaw "m") (setq month (+ month deltan)))
10288 ((equal deltaw "y") (setq year (+ year deltan)))))
10289 ((and wday (not (nth 3 tl)))
10290 ;; Weekday was given, but no day, so pick that day in the week
10291 ;; on or after the derived date.
10292 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10293 (unless (equal wday wday1)
10294 (setq day (+ day (% (- wday wday1 -7) 7))))))
10295 (if (and (boundp 'org-time-was-given)
10296 (nth 2 tl))
10297 (setq org-time-was-given t))
10298 (if (< year 100) (setq year (+ 2000 year)))
10299 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10300 (list second minute hour day month year)))
10302 (defvar parse-time-weekdays)
10304 (defun org-read-date-get-relative (s today default)
10305 "Check string S for special relative date string.
10306 TODAY and DEFAULT are internal times, for today and for a default.
10307 Return shift list (N what def-flag)
10308 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10309 N is the number of WHATs to shift.
10310 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10311 the DEFAULT date rather than TODAY."
10312 (when (string-match
10313 (concat
10314 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
10315 "\\([0-9]+\\)?"
10316 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10317 "\\([ \t]\\|$\\)") s)
10318 (let* ((dir (if (match-end 1)
10319 (string-to-char (substring (match-string 1 s) -1))
10320 ?+))
10321 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10322 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10323 (what (if (match-end 3) (match-string 3 s) "d"))
10324 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10325 (date (if rel default today))
10326 (wday (nth 6 (decode-time date)))
10327 delta)
10328 (if wday1
10329 (progn
10330 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10331 (if (= dir ?-) (setq delta (- delta 7)))
10332 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10333 (list delta "d" rel))
10334 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10336 (defun org-eval-in-calendar (form &optional keepdate)
10337 "Eval FORM in the calendar window and return to current window.
10338 Also, store the cursor date in variable org-ans2."
10339 (let ((sw (selected-window)))
10340 (select-window (get-buffer-window "*Calendar*"))
10341 (eval form)
10342 (when (and (not keepdate) (calendar-cursor-to-date))
10343 (let* ((date (calendar-cursor-to-date))
10344 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10345 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10346 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10347 (select-window sw)))
10349 ; ;; Update the prompt to show new default date
10350 ; (save-excursion
10351 ; (goto-char (point-min))
10352 ; (when (and org-ans2
10353 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10354 ; (get-text-property (match-end 0) 'field))
10355 ; (let ((inhibit-read-only t))
10356 ; (replace-match (concat "[" org-ans2 "]") t t)
10357 ; (add-text-properties (point-min) (1+ (match-end 0))
10358 ; (text-properties-at (1+ (point-min)))))))))
10360 (defun org-calendar-select ()
10361 "Return to `org-read-date' with the date currently selected.
10362 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10363 (interactive)
10364 (when (calendar-cursor-to-date)
10365 (let* ((date (calendar-cursor-to-date))
10366 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10367 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10368 (if (active-minibuffer-window) (exit-minibuffer))))
10370 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10371 "Insert a date stamp for the date given by the internal TIME.
10372 WITH-HM means, use the stamp format that includes the time of the day.
10373 INACTIVE means use square brackets instead of angular ones, so that the
10374 stamp will not contribute to the agenda.
10375 PRE and POST are optional strings to be inserted before and after the
10376 stamp.
10377 The command returns the inserted time stamp."
10378 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10379 stamp)
10380 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10381 (insert-before-markers (or pre ""))
10382 (insert-before-markers (setq stamp (format-time-string fmt time)))
10383 (when (listp extra)
10384 (setq extra (car extra))
10385 (if (and (stringp extra)
10386 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10387 (setq extra (format "-%02d:%02d"
10388 (string-to-number (match-string 1 extra))
10389 (string-to-number (match-string 2 extra))))
10390 (setq extra nil)))
10391 (when extra
10392 (backward-char 1)
10393 (insert-before-markers extra)
10394 (forward-char 1))
10395 (insert-before-markers (or post ""))
10396 stamp))
10398 (defun org-toggle-time-stamp-overlays ()
10399 "Toggle the use of custom time stamp formats."
10400 (interactive)
10401 (setq org-display-custom-times (not org-display-custom-times))
10402 (unless org-display-custom-times
10403 (let ((p (point-min)) (bmp (buffer-modified-p)))
10404 (while (setq p (next-single-property-change p 'display))
10405 (if (and (get-text-property p 'display)
10406 (eq (get-text-property p 'face) 'org-date))
10407 (remove-text-properties
10408 p (setq p (next-single-property-change p 'display))
10409 '(display t))))
10410 (set-buffer-modified-p bmp)))
10411 (if (featurep 'xemacs)
10412 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10413 (org-restart-font-lock)
10414 (setq org-table-may-need-update t)
10415 (if org-display-custom-times
10416 (message "Time stamps are overlayed with custom format")
10417 (message "Time stamp overlays removed")))
10419 (defun org-display-custom-time (beg end)
10420 "Overlay modified time stamp format over timestamp between BED and END."
10421 (let* ((ts (buffer-substring beg end))
10422 t1 w1 with-hm tf time str w2 (off 0))
10423 (save-match-data
10424 (setq t1 (org-parse-time-string ts t))
10425 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10426 (setq off (- (match-end 0) (match-beginning 0)))))
10427 (setq end (- end off))
10428 (setq w1 (- end beg)
10429 with-hm (and (nth 1 t1) (nth 2 t1))
10430 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10431 time (org-fix-decoded-time t1)
10432 str (org-add-props
10433 (format-time-string
10434 (substring tf 1 -1) (apply 'encode-time time))
10435 nil 'mouse-face 'highlight)
10436 w2 (length str))
10437 (if (not (= w2 w1))
10438 (add-text-properties (1+ beg) (+ 2 beg)
10439 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10440 (if (featurep 'xemacs)
10441 (progn
10442 (put-text-property beg end 'invisible t)
10443 (put-text-property beg end 'end-glyph (make-glyph str)))
10444 (put-text-property beg end 'display str))))
10446 (defun org-translate-time (string)
10447 "Translate all timestamps in STRING to custom format.
10448 But do this only if the variable `org-display-custom-times' is set."
10449 (when org-display-custom-times
10450 (save-match-data
10451 (let* ((start 0)
10452 (re org-ts-regexp-both)
10453 t1 with-hm inactive tf time str beg end)
10454 (while (setq start (string-match re string start))
10455 (setq beg (match-beginning 0)
10456 end (match-end 0)
10457 t1 (save-match-data
10458 (org-parse-time-string (substring string beg end) t))
10459 with-hm (and (nth 1 t1) (nth 2 t1))
10460 inactive (equal (substring string beg (1+ beg)) "[")
10461 tf (funcall (if with-hm 'cdr 'car)
10462 org-time-stamp-custom-formats)
10463 time (org-fix-decoded-time t1)
10464 str (format-time-string
10465 (concat
10466 (if inactive "[" "<") (substring tf 1 -1)
10467 (if inactive "]" ">"))
10468 (apply 'encode-time time))
10469 string (replace-match str t t string)
10470 start (+ start (length str)))))))
10471 string)
10473 (defun org-fix-decoded-time (time)
10474 "Set 0 instead of nil for the first 6 elements of time.
10475 Don't touch the rest."
10476 (let ((n 0))
10477 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10479 (defun org-days-to-time (timestamp-string)
10480 "Difference between TIMESTAMP-STRING and now in days."
10481 (- (time-to-days (org-time-string-to-time timestamp-string))
10482 (time-to-days (current-time))))
10484 (defun org-deadline-close (timestamp-string &optional ndays)
10485 "Is the time in TIMESTAMP-STRING close to the current date?"
10486 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10487 (and (< (org-days-to-time timestamp-string) ndays)
10488 (not (org-entry-is-done-p))))
10490 (defun org-get-wdays (ts)
10491 "Get the deadline lead time appropriate for timestring TS."
10492 (cond
10493 ((<= org-deadline-warning-days 0)
10494 ;; 0 or negative, enforce this value no matter what
10495 (- org-deadline-warning-days))
10496 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10497 ;; lead time is specified.
10498 (floor (* (string-to-number (match-string 1 ts))
10499 (cdr (assoc (match-string 2 ts)
10500 '(("d" . 1) ("w" . 7)
10501 ("m" . 30.4) ("y" . 365.25)))))))
10502 ;; go for the default.
10503 (t org-deadline-warning-days)))
10505 (defun org-calendar-select-mouse (ev)
10506 "Return to `org-read-date' with the date currently selected.
10507 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10508 (interactive "e")
10509 (mouse-set-point ev)
10510 (when (calendar-cursor-to-date)
10511 (let* ((date (calendar-cursor-to-date))
10512 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10513 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10514 (if (active-minibuffer-window) (exit-minibuffer))))
10516 (defun org-check-deadlines (ndays)
10517 "Check if there are any deadlines due or past due.
10518 A deadline is considered due if it happens within `org-deadline-warning-days'
10519 days from today's date. If the deadline appears in an entry marked DONE,
10520 it is not shown. The prefix arg NDAYS can be used to test that many
10521 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10522 (interactive "P")
10523 (let* ((org-warn-days
10524 (cond
10525 ((equal ndays '(4)) 100000)
10526 (ndays (prefix-numeric-value ndays))
10527 (t (abs org-deadline-warning-days))))
10528 (case-fold-search nil)
10529 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10530 (callback
10531 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10533 (message "%d deadlines past-due or due within %d days"
10534 (org-occur regexp nil callback)
10535 org-warn-days)))
10537 (defun org-check-before-date (date)
10538 "Check if there are deadlines or scheduled entries before DATE."
10539 (interactive (list (org-read-date)))
10540 (let ((case-fold-search nil)
10541 (regexp (concat "\\<\\(" org-deadline-string
10542 "\\|" org-scheduled-string
10543 "\\) *<\\([^>]+\\)>"))
10544 (callback
10545 (lambda () (time-less-p
10546 (org-time-string-to-time (match-string 2))
10547 (org-time-string-to-time date)))))
10548 (message "%d entries before %s"
10549 (org-occur regexp nil callback) date)))
10551 (defun org-evaluate-time-range (&optional to-buffer)
10552 "Evaluate a time range by computing the difference between start and end.
10553 Normally the result is just printed in the echo area, but with prefix arg
10554 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10555 If the time range is actually in a table, the result is inserted into the
10556 next column.
10557 For time difference computation, a year is assumed to be exactly 365
10558 days in order to avoid rounding problems."
10559 (interactive "P")
10561 (org-clock-update-time-maybe)
10562 (save-excursion
10563 (unless (org-at-date-range-p t)
10564 (goto-char (point-at-bol))
10565 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10566 (if (not (org-at-date-range-p t))
10567 (error "Not at a time-stamp range, and none found in current line")))
10568 (let* ((ts1 (match-string 1))
10569 (ts2 (match-string 2))
10570 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10571 (match-end (match-end 0))
10572 (time1 (org-time-string-to-time ts1))
10573 (time2 (org-time-string-to-time ts2))
10574 (t1 (time-to-seconds time1))
10575 (t2 (time-to-seconds time2))
10576 (diff (abs (- t2 t1)))
10577 (negative (< (- t2 t1) 0))
10578 ;; (ys (floor (* 365 24 60 60)))
10579 (ds (* 24 60 60))
10580 (hs (* 60 60))
10581 (fy "%dy %dd %02d:%02d")
10582 (fy1 "%dy %dd")
10583 (fd "%dd %02d:%02d")
10584 (fd1 "%dd")
10585 (fh "%02d:%02d")
10586 y d h m align)
10587 (if havetime
10588 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10590 d (floor (/ diff ds)) diff (mod diff ds)
10591 h (floor (/ diff hs)) diff (mod diff hs)
10592 m (floor (/ diff 60)))
10593 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10595 d (floor (+ (/ diff ds) 0.5))
10596 h 0 m 0))
10597 (if (not to-buffer)
10598 (message "%s" (org-make-tdiff-string y d h m))
10599 (if (org-at-table-p)
10600 (progn
10601 (goto-char match-end)
10602 (setq align t)
10603 (and (looking-at " *|") (goto-char (match-end 0))))
10604 (goto-char match-end))
10605 (if (looking-at
10606 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10607 (replace-match ""))
10608 (if negative (insert " -"))
10609 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10610 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10611 (insert " " (format fh h m))))
10612 (if align (org-table-align))
10613 (message "Time difference inserted")))))
10615 (defun org-make-tdiff-string (y d h m)
10616 (let ((fmt "")
10617 (l nil))
10618 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10619 l (push y l)))
10620 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10621 l (push d l)))
10622 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10623 l (push h l)))
10624 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10625 l (push m l)))
10626 (apply 'format fmt (nreverse l))))
10628 (defun org-time-string-to-time (s)
10629 (apply 'encode-time (org-parse-time-string s)))
10631 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10632 "Convert a time stamp to an absolute day number.
10633 If there is a specifyer for a cyclic time stamp, get the closest date to
10634 DAYNR.
10635 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10636 (cond
10637 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10638 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10639 daynr
10640 (+ daynr 1000)))
10641 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10642 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10643 (time-to-days (current-time))) (match-string 0 s)
10644 prefer show-all))
10645 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10647 (defun org-days-to-iso-week (days)
10648 "Return the iso week number."
10649 (require 'cal-iso)
10650 (car (calendar-iso-from-absolute days)))
10652 (defun org-small-year-to-year (year)
10653 "Convert 2-digit years into 4-digit years.
10654 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10655 The year 2000 cannot be abbreviated. Any year lager than 99
10656 is retrned unchanged."
10657 (if (< year 38)
10658 (setq year (+ 2000 year))
10659 (if (< year 100)
10660 (setq year (+ 1900 year))))
10661 year)
10663 (defun org-time-from-absolute (d)
10664 "Return the time corresponding to date D.
10665 D may be an absolute day number, or a calendar-type list (month day year)."
10666 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10667 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10669 (defun org-calendar-holiday ()
10670 "List of holidays, for Diary display in Org-mode."
10671 (require 'holidays)
10672 (let ((hl (funcall
10673 (if (fboundp 'calendar-check-holidays)
10674 'calendar-check-holidays 'check-calendar-holidays) date)))
10675 (if hl (mapconcat 'identity hl "; "))))
10677 (defun org-diary-sexp-entry (sexp entry date)
10678 "Process a SEXP diary ENTRY for DATE."
10679 (require 'diary-lib)
10680 (let ((result (if calendar-debug-sexp
10681 (let ((stack-trace-on-error t))
10682 (eval (car (read-from-string sexp))))
10683 (condition-case nil
10684 (eval (car (read-from-string sexp)))
10685 (error
10686 (beep)
10687 (message "Bad sexp at line %d in %s: %s"
10688 (org-current-line)
10689 (buffer-file-name) sexp)
10690 (sleep-for 2))))))
10691 (cond ((stringp result) result)
10692 ((and (consp result)
10693 (stringp (cdr result))) (cdr result))
10694 (result entry)
10695 (t nil))))
10697 (defun org-diary-to-ical-string (frombuf)
10698 "Get iCalendar entries from diary entries in buffer FROMBUF.
10699 This uses the icalendar.el library."
10700 (let* ((tmpdir (if (featurep 'xemacs)
10701 (temp-directory)
10702 temporary-file-directory))
10703 (tmpfile (make-temp-name
10704 (expand-file-name "orgics" tmpdir)))
10705 buf rtn b e)
10706 (save-excursion
10707 (set-buffer frombuf)
10708 (icalendar-export-region (point-min) (point-max) tmpfile)
10709 (setq buf (find-buffer-visiting tmpfile))
10710 (set-buffer buf)
10711 (goto-char (point-min))
10712 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10713 (setq b (match-beginning 0)))
10714 (goto-char (point-max))
10715 (if (re-search-backward "^END:VEVENT" nil t)
10716 (setq e (match-end 0)))
10717 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
10718 (kill-buffer buf)
10719 (kill-buffer frombuf)
10720 (delete-file tmpfile)
10721 rtn))
10723 (defun org-closest-date (start current change prefer show-all)
10724 "Find the date closest to CURRENT that is consistent with START and CHANGE.
10725 When PREFER is `past' return a date that is either CURRENT or past.
10726 When PREFER is `future', return a date that is either CURRENT or future.
10727 When SHOW-ALL is nil, only return the current occurence of a time stamp."
10728 ;; Make the proper lists from the dates
10729 (catch 'exit
10730 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
10731 dn dw sday cday n1 n2
10732 d m y y1 y2 date1 date2 nmonths nm ny m2)
10734 (setq start (org-date-to-gregorian start)
10735 current (org-date-to-gregorian
10736 (if show-all
10737 current
10738 (time-to-days (current-time))))
10739 sday (calendar-absolute-from-gregorian start)
10740 cday (calendar-absolute-from-gregorian current))
10742 (if (<= cday sday) (throw 'exit sday))
10744 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
10745 (setq dn (string-to-number (match-string 1 change))
10746 dw (cdr (assoc (match-string 2 change) a1)))
10747 (error "Invalid change specifyer: %s" change))
10748 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
10749 (cond
10750 ((eq dw 'day)
10751 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
10752 n2 (+ n1 dn)))
10753 ((eq dw 'year)
10754 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
10755 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
10756 (setq date1 (list m d y1)
10757 n1 (calendar-absolute-from-gregorian date1)
10758 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
10759 n2 (calendar-absolute-from-gregorian date2)))
10760 ((eq dw 'month)
10761 ;; approx number of month between the tow dates
10762 (setq nmonths (floor (/ (- cday sday) 30.436875)))
10763 ;; How often does dn fit in there?
10764 (setq d (nth 1 start) m (car start) y (nth 2 start)
10765 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
10766 m (+ m nm)
10767 ny (floor (/ m 12))
10768 y (+ y ny)
10769 m (- m (* ny 12)))
10770 (while (> m 12) (setq m (- m 12) y (1+ y)))
10771 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
10772 (setq m2 (+ m dn) y2 y)
10773 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10774 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
10775 (while (< n2 cday)
10776 (setq n1 n2 m m2 y y2)
10777 (setq m2 (+ m dn) y2 y)
10778 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10779 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
10781 (if show-all
10782 (cond
10783 ((eq prefer 'past) n1)
10784 ((eq prefer 'future) (if (= cday n1) n1 n2))
10785 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
10786 (cond
10787 ((eq prefer 'past) n1)
10788 ((eq prefer 'future) (if (= cday n1) n1 n2))
10789 (t (if (= cday n1) n1 n2)))))))
10791 (defun org-date-to-gregorian (date)
10792 "Turn any specification of DATE into a gregorian date for the calendar."
10793 (cond ((integerp date) (calendar-gregorian-from-absolute date))
10794 ((and (listp date) (= (length date) 3)) date)
10795 ((stringp date)
10796 (setq date (org-parse-time-string date))
10797 (list (nth 4 date) (nth 3 date) (nth 5 date)))
10798 ((listp date)
10799 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
10801 (defun org-parse-time-string (s &optional nodefault)
10802 "Parse the standard Org-mode time string.
10803 This should be a lot faster than the normal `parse-time-string'.
10804 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
10805 hour and minute fields will be nil if not given."
10806 (if (string-match org-ts-regexp0 s)
10807 (list 0
10808 (if (or (match-beginning 8) (not nodefault))
10809 (string-to-number (or (match-string 8 s) "0")))
10810 (if (or (match-beginning 7) (not nodefault))
10811 (string-to-number (or (match-string 7 s) "0")))
10812 (string-to-number (match-string 4 s))
10813 (string-to-number (match-string 3 s))
10814 (string-to-number (match-string 2 s))
10815 nil nil nil)
10816 (make-list 9 0)))
10818 (defun org-timestamp-up (&optional arg)
10819 "Increase the date item at the cursor by one.
10820 If the cursor is on the year, change the year. If it is on the month or
10821 the day, change that.
10822 With prefix ARG, change by that many units."
10823 (interactive "p")
10824 (org-timestamp-change (prefix-numeric-value arg)))
10826 (defun org-timestamp-down (&optional arg)
10827 "Decrease the date item at the cursor by one.
10828 If the cursor is on the year, change the year. If it is on the month or
10829 the day, change that.
10830 With prefix ARG, change by that many units."
10831 (interactive "p")
10832 (org-timestamp-change (- (prefix-numeric-value arg))))
10834 (defun org-timestamp-up-day (&optional arg)
10835 "Increase the date in the time stamp by one day.
10836 With prefix ARG, change that many days."
10837 (interactive "p")
10838 (if (and (not (org-at-timestamp-p t))
10839 (org-on-heading-p))
10840 (org-todo 'up)
10841 (org-timestamp-change (prefix-numeric-value arg) 'day)))
10843 (defun org-timestamp-down-day (&optional arg)
10844 "Decrease the date in the time stamp by one day.
10845 With prefix ARG, change that many days."
10846 (interactive "p")
10847 (if (and (not (org-at-timestamp-p t))
10848 (org-on-heading-p))
10849 (org-todo 'down)
10850 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
10852 (defun org-at-timestamp-p (&optional inactive-ok)
10853 "Determine if the cursor is in or at a timestamp."
10854 (interactive)
10855 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
10856 (pos (point))
10857 (ans (or (looking-at tsr)
10858 (save-excursion
10859 (skip-chars-backward "^[<\n\r\t")
10860 (if (> (point) (point-min)) (backward-char 1))
10861 (and (looking-at tsr)
10862 (> (- (match-end 0) pos) -1))))))
10863 (and ans
10864 (boundp 'org-ts-what)
10865 (setq org-ts-what
10866 (cond
10867 ((= pos (match-beginning 0)) 'bracket)
10868 ((= pos (1- (match-end 0))) 'bracket)
10869 ((org-pos-in-match-range pos 2) 'year)
10870 ((org-pos-in-match-range pos 3) 'month)
10871 ((org-pos-in-match-range pos 7) 'hour)
10872 ((org-pos-in-match-range pos 8) 'minute)
10873 ((or (org-pos-in-match-range pos 4)
10874 (org-pos-in-match-range pos 5)) 'day)
10875 ((and (> pos (or (match-end 8) (match-end 5)))
10876 (< pos (match-end 0)))
10877 (- pos (or (match-end 8) (match-end 5))))
10878 (t 'day))))
10879 ans))
10881 (defun org-toggle-timestamp-type ()
10882 "Toggle the type (<active> or [inactive]) of a time stamp."
10883 (interactive)
10884 (when (org-at-timestamp-p t)
10885 (save-excursion
10886 (goto-char (match-beginning 0))
10887 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
10888 (goto-char (1- (match-end 0)))
10889 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
10890 (message "Timestamp is now %sactive"
10891 (if (equal (char-before) ?>) "in" ""))))
10893 (defun org-timestamp-change (n &optional what)
10894 "Change the date in the time stamp at point.
10895 The date will be changed by N times WHAT. WHAT can be `day', `month',
10896 `year', `minute', `second'. If WHAT is not given, the cursor position
10897 in the timestamp determines what will be changed."
10898 (let ((pos (point))
10899 with-hm inactive
10900 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
10901 org-ts-what
10902 extra rem
10903 ts time time0)
10904 (if (not (org-at-timestamp-p t))
10905 (error "Not at a timestamp"))
10906 (if (and (not what) (eq org-ts-what 'bracket))
10907 (org-toggle-timestamp-type)
10908 (if (and (not what) (not (eq org-ts-what 'day))
10909 org-display-custom-times
10910 (get-text-property (point) 'display)
10911 (not (get-text-property (1- (point)) 'display)))
10912 (setq org-ts-what 'day))
10913 (setq org-ts-what (or what org-ts-what)
10914 inactive (= (char-after (match-beginning 0)) ?\[)
10915 ts (match-string 0))
10916 (replace-match "")
10917 (if (string-match
10918 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
10920 (setq extra (match-string 1 ts)))
10921 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
10922 (setq with-hm t))
10923 (setq time0 (org-parse-time-string ts))
10924 (when (and (eq org-ts-what 'minute)
10925 (eq current-prefix-arg nil))
10926 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
10927 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
10928 (setcar (cdr time0) (+ (nth 1 time0)
10929 (if (> n 0) (- rem) (- dm rem))))))
10930 (setq time
10931 (encode-time (or (car time0) 0)
10932 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
10933 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
10934 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
10935 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
10936 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
10937 (nthcdr 6 time0)))
10938 (when (integerp org-ts-what)
10939 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
10940 (if (eq what 'calendar)
10941 (let ((cal-date (org-get-date-from-calendar)))
10942 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
10943 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
10944 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
10945 (setcar time0 (or (car time0) 0))
10946 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
10947 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
10948 (setq time (apply 'encode-time time0))))
10949 (setq org-last-changed-timestamp
10950 (org-insert-time-stamp time with-hm inactive nil nil extra))
10951 (org-clock-update-time-maybe)
10952 (goto-char pos)
10953 ;; Try to recenter the calendar window, if any
10954 (if (and org-calendar-follow-timestamp-change
10955 (get-buffer-window "*Calendar*" t)
10956 (memq org-ts-what '(day month year)))
10957 (org-recenter-calendar (time-to-days time))))))
10959 (defun org-modify-ts-extra (s pos n dm)
10960 "Change the different parts of the lead-time and repeat fields in timestamp."
10961 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
10962 ng h m new rem)
10963 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
10964 (cond
10965 ((or (org-pos-in-match-range pos 2)
10966 (org-pos-in-match-range pos 3))
10967 (setq m (string-to-number (match-string 3 s))
10968 h (string-to-number (match-string 2 s)))
10969 (if (org-pos-in-match-range pos 2)
10970 (setq h (+ h n))
10971 (setq n (* dm (org-no-warnings (signum n))))
10972 (when (not (= 0 (setq rem (% m dm))))
10973 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
10974 (setq m (+ m n)))
10975 (if (< m 0) (setq m (+ m 60) h (1- h)))
10976 (if (> m 59) (setq m (- m 60) h (1+ h)))
10977 (setq h (min 24 (max 0 h)))
10978 (setq ng 1 new (format "-%02d:%02d" h m)))
10979 ((org-pos-in-match-range pos 6)
10980 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
10981 ((org-pos-in-match-range pos 5)
10982 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
10984 ((org-pos-in-match-range pos 9)
10985 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
10986 ((org-pos-in-match-range pos 8)
10987 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
10989 (when ng
10990 (setq s (concat
10991 (substring s 0 (match-beginning ng))
10993 (substring s (match-end ng))))))
10996 (defun org-recenter-calendar (date)
10997 "If the calendar is visible, recenter it to DATE."
10998 (let* ((win (selected-window))
10999 (cwin (get-buffer-window "*Calendar*" t))
11000 (calendar-move-hook nil))
11001 (when cwin
11002 (select-window cwin)
11003 (calendar-goto-date (if (listp date) date
11004 (calendar-gregorian-from-absolute date)))
11005 (select-window win))))
11007 (defun org-goto-calendar (&optional arg)
11008 "Go to the Emacs calendar at the current date.
11009 If there is a time stamp in the current line, go to that date.
11010 A prefix ARG can be used to force the current date."
11011 (interactive "P")
11012 (let ((tsr org-ts-regexp) diff
11013 (calendar-move-hook nil)
11014 (calendar-view-holidays-initially-flag nil)
11015 (view-calendar-holidays-initially nil)
11016 (calendar-view-diary-initially-flag nil)
11017 (view-diary-entries-initially nil))
11018 (if (or (org-at-timestamp-p)
11019 (save-excursion
11020 (beginning-of-line 1)
11021 (looking-at (concat ".*" tsr))))
11022 (let ((d1 (time-to-days (current-time)))
11023 (d2 (time-to-days
11024 (org-time-string-to-time (match-string 1)))))
11025 (setq diff (- d2 d1))))
11026 (calendar)
11027 (calendar-goto-today)
11028 (if (and diff (not arg)) (calendar-forward-day diff))))
11030 (defun org-get-date-from-calendar ()
11031 "Return a list (month day year) of date at point in calendar."
11032 (with-current-buffer "*Calendar*"
11033 (save-match-data
11034 (calendar-cursor-to-date))))
11036 (defun org-date-from-calendar ()
11037 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11038 If there is already a time stamp at the cursor position, update it."
11039 (interactive)
11040 (if (org-at-timestamp-p t)
11041 (org-timestamp-change 0 'calendar)
11042 (let ((cal-date (org-get-date-from-calendar)))
11043 (org-insert-time-stamp
11044 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11046 (defun org-minutes-to-hh:mm-string (m)
11047 "Compute H:MM from a number of minutes."
11048 (let ((h (/ m 60)))
11049 (setq m (- m (* 60 h)))
11050 (format "%d:%02d" h m)))
11052 (defun org-hh:mm-string-to-minutes (s)
11053 "Convert a string H:MM to a number of minutes."
11054 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11055 (+ (* (string-to-number (match-string 1 s)) 60)
11056 (string-to-number (match-string 2 s)))
11059 ;;;; Agenda files
11061 ;;;###autoload
11062 (defun org-iswitchb (&optional arg)
11063 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11064 With a prefix argument, restrict available to files.
11065 With two prefix arguments, restrict available buffers to agenda files.
11067 Due to some yet unresolved reason, global function
11068 `iswitchb-mode' needs to be active for this function to work."
11069 (interactive "P")
11070 (require 'iswitchb)
11071 (let ((enabled iswitchb-mode) blist)
11072 (or enabled (iswitchb-mode 1))
11073 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11074 ((equal arg '(16)) (org-buffer-list 'agenda))
11075 (t (org-buffer-list))))
11076 (unwind-protect
11077 (let ((iswitchb-make-buflist-hook
11078 (lambda ()
11079 (setq iswitchb-temp-buflist
11080 (mapcar 'buffer-name blist)))))
11081 (switch-to-buffer
11082 (iswitchb-read-buffer
11083 "Switch-to: " nil t))
11084 (or enabled (iswitchb-mode -1))))))
11086 (defun org-buffer-list (&optional predicate tmp)
11087 "Return a list of Org buffers.
11088 PREDICATE can be either 'export, 'files or 'agenda.
11090 'export restrict the list to Export buffers.
11091 'files restrict the list to buffers visiting Org files.
11092 'agenda restrict the list to buffers visiting agenda files.
11094 If TMP is non-nil, don't include temporary buffers."
11095 (let (filter blist)
11096 (setq filter
11097 (cond ((eq predicate 'files) "\.org$")
11098 ((eq predicate 'export) "\*Org .*Export")
11099 (t "\*Org \\|\.org$")))
11100 (setq blist
11101 (mapcar
11102 (lambda(b)
11103 (let ((bname (buffer-name b))
11104 (bfile (buffer-file-name b)))
11105 (if (and (string-match filter bname)
11106 (if (eq predicate 'agenda)
11107 (member bfile
11108 (mapcar (lambda(f) (file-truename f))
11109 org-agenda-files)) t)
11110 (if tmp (not (string-match "tmp" bname)) t)) b)))
11111 (buffer-list)))
11112 (delete nil blist)))
11114 (defun org-agenda-files (&optional unrestricted ext)
11115 "Get the list of agenda files.
11116 Optional UNRESTRICTED means return the full list even if a restriction
11117 is currently in place.
11118 When EXT is non-nil, try to add all files that are created by adding EXT
11119 to the file nemes. Basically, this is a way to add the archive files
11120 to the list, by setting EXT to \"_archive\" If EXT is non-nil, but not
11121 a string, \"_archive\" will be used."
11122 (let ((files
11123 (cond
11124 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11125 ((stringp org-agenda-files) (org-read-agenda-file-list))
11126 ((listp org-agenda-files) org-agenda-files)
11127 (t (error "Invalid value of `org-agenda-files'")))))
11128 (setq files (apply 'append
11129 (mapcar (lambda (f)
11130 (if (file-directory-p f)
11131 (directory-files
11132 f t org-agenda-file-regexp)
11133 (list f)))
11134 files)))
11135 (when org-agenda-skip-unavailable-files
11136 (setq files (delq nil
11137 (mapcar (function
11138 (lambda (file)
11139 (and (file-readable-p file) file)))
11140 files))))
11141 (when ext
11142 (setq ext (if (and (stringp ext) (string-match "\\S-" ext))
11143 ext "_archive"))
11144 (setq files (apply 'append
11145 (mapcar
11146 (lambda (f)
11147 (if (file-exists-p (concat f ext))
11148 (list f (concat f ext))
11149 (list f)))
11150 files))))
11151 files))
11153 (defun org-edit-agenda-file-list ()
11154 "Edit the list of agenda files.
11155 Depending on setup, this either uses customize to edit the variable
11156 `org-agenda-files', or it visits the file that is holding the list. In the
11157 latter case, the buffer is set up in a way that saving it automatically kills
11158 the buffer and restores the previous window configuration."
11159 (interactive)
11160 (if (stringp org-agenda-files)
11161 (let ((cw (current-window-configuration)))
11162 (find-file org-agenda-files)
11163 (org-set-local 'org-window-configuration cw)
11164 (org-add-hook 'after-save-hook
11165 (lambda ()
11166 (set-window-configuration
11167 (prog1 org-window-configuration
11168 (kill-buffer (current-buffer))))
11169 (org-install-agenda-files-menu)
11170 (message "New agenda file list installed"))
11171 nil 'local)
11172 (message "%s" (substitute-command-keys
11173 "Edit list and finish with \\[save-buffer]")))
11174 (customize-variable 'org-agenda-files)))
11176 (defun org-store-new-agenda-file-list (list)
11177 "Set new value for the agenda file list and save it correcly."
11178 (if (stringp org-agenda-files)
11179 (let ((f org-agenda-files) b)
11180 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11181 (with-temp-file f
11182 (insert (mapconcat 'identity list "\n") "\n")))
11183 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11184 (setq org-agenda-files list)
11185 (customize-save-variable 'org-agenda-files org-agenda-files))))
11187 (defun org-read-agenda-file-list ()
11188 "Read the list of agenda files from a file."
11189 (when (file-directory-p org-agenda-files)
11190 (error "`org-agenda-files' cannot be a single directory"))
11191 (when (stringp org-agenda-files)
11192 (with-temp-buffer
11193 (insert-file-contents org-agenda-files)
11194 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11197 ;;;###autoload
11198 (defun org-cycle-agenda-files ()
11199 "Cycle through the files in `org-agenda-files'.
11200 If the current buffer visits an agenda file, find the next one in the list.
11201 If the current buffer does not, find the first agenda file."
11202 (interactive)
11203 (let* ((fs (org-agenda-files t))
11204 (files (append fs (list (car fs))))
11205 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11206 file)
11207 (unless files (error "No agenda files"))
11208 (catch 'exit
11209 (while (setq file (pop files))
11210 (if (equal (file-truename file) tcf)
11211 (when (car files)
11212 (find-file (car files))
11213 (throw 'exit t))))
11214 (find-file (car fs)))
11215 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11217 (defun org-agenda-file-to-front (&optional to-end)
11218 "Move/add the current file to the top of the agenda file list.
11219 If the file is not present in the list, it is added to the front. If it is
11220 present, it is moved there. With optional argument TO-END, add/move to the
11221 end of the list."
11222 (interactive "P")
11223 (let ((org-agenda-skip-unavailable-files nil)
11224 (file-alist (mapcar (lambda (x)
11225 (cons (file-truename x) x))
11226 (org-agenda-files t)))
11227 (ctf (file-truename buffer-file-name))
11228 x had)
11229 (setq x (assoc ctf file-alist) had x)
11231 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11232 (if to-end
11233 (setq file-alist (append (delq x file-alist) (list x)))
11234 (setq file-alist (cons x (delq x file-alist))))
11235 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11236 (org-install-agenda-files-menu)
11237 (message "File %s to %s of agenda file list"
11238 (if had "moved" "added") (if to-end "end" "front"))))
11240 (defun org-remove-file (&optional file)
11241 "Remove current file from the list of files in variable `org-agenda-files'.
11242 These are the files which are being checked for agenda entries.
11243 Optional argument FILE means, use this file instead of the current."
11244 (interactive)
11245 (let* ((org-agenda-skip-unavailable-files nil)
11246 (file (or file buffer-file-name))
11247 (true-file (file-truename file))
11248 (afile (abbreviate-file-name file))
11249 (files (delq nil (mapcar
11250 (lambda (x)
11251 (if (equal true-file
11252 (file-truename x))
11253 nil x))
11254 (org-agenda-files t)))))
11255 (if (not (= (length files) (length (org-agenda-files t))))
11256 (progn
11257 (org-store-new-agenda-file-list files)
11258 (org-install-agenda-files-menu)
11259 (message "Removed file: %s" afile))
11260 (message "File was not in list: %s (not removed)" afile))))
11262 (defun org-file-menu-entry (file)
11263 (vector file (list 'find-file file) t))
11265 (defun org-check-agenda-file (file)
11266 "Make sure FILE exists. If not, ask user what to do."
11267 (when (not (file-exists-p file))
11268 (message "non-existent file %s. [R]emove from list or [A]bort?"
11269 (abbreviate-file-name file))
11270 (let ((r (downcase (read-char-exclusive))))
11271 (cond
11272 ((equal r ?r)
11273 (org-remove-file file)
11274 (throw 'nextfile t))
11275 (t (error "Abort"))))))
11277 (defun org-get-agenda-file-buffer (file)
11278 "Get a buffer visiting FILE. If the buffer needs to be created, add
11279 it to the list of buffers which might be released later."
11280 (let ((buf (org-find-base-buffer-visiting file)))
11281 (if buf
11282 buf ; just return it
11283 ;; Make a new buffer and remember it
11284 (setq buf (find-file-noselect file))
11285 (if buf (push buf org-agenda-new-buffers))
11286 buf)))
11288 (defun org-release-buffers (blist)
11289 "Release all buffers in list, asking the user for confirmation when needed.
11290 When a buffer is unmodified, it is just killed. When modified, it is saved
11291 \(if the user agrees) and then killed."
11292 (let (buf file)
11293 (while (setq buf (pop blist))
11294 (setq file (buffer-file-name buf))
11295 (when (and (buffer-modified-p buf)
11296 file
11297 (y-or-n-p (format "Save file %s? " file)))
11298 (with-current-buffer buf (save-buffer)))
11299 (kill-buffer buf))))
11301 (defun org-prepare-agenda-buffers (files)
11302 "Create buffers for all agenda files, protect archived trees and comments."
11303 (interactive)
11304 (let ((pa '(:org-archived t))
11305 (pc '(:org-comment t))
11306 (pall '(:org-archived t :org-comment t))
11307 (inhibit-read-only t)
11308 (rea (concat ":" org-archive-tag ":"))
11309 bmp file re)
11310 (save-excursion
11311 (save-restriction
11312 (while (setq file (pop files))
11313 (if (bufferp file)
11314 (set-buffer file)
11315 (org-check-agenda-file file)
11316 (set-buffer (org-get-agenda-file-buffer file)))
11317 (widen)
11318 (setq bmp (buffer-modified-p))
11319 (org-refresh-category-properties)
11320 (setq org-todo-keywords-for-agenda
11321 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11322 (setq org-done-keywords-for-agenda
11323 (append org-done-keywords-for-agenda org-done-keywords))
11324 (save-excursion
11325 (remove-text-properties (point-min) (point-max) pall)
11326 (when org-agenda-skip-archived-trees
11327 (goto-char (point-min))
11328 (while (re-search-forward rea nil t)
11329 (if (org-on-heading-p t)
11330 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11331 (goto-char (point-min))
11332 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11333 (while (re-search-forward re nil t)
11334 (add-text-properties
11335 (match-beginning 0) (org-end-of-subtree t) pc)))
11336 (set-buffer-modified-p bmp))))))
11338 ;;;; Embedded LaTeX
11340 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11341 "Keymap for the minor `org-cdlatex-mode'.")
11343 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11344 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11345 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11346 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11347 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11349 (defvar org-cdlatex-texmathp-advice-is-done nil
11350 "Flag remembering if we have applied the advice to texmathp already.")
11352 (define-minor-mode org-cdlatex-mode
11353 "Toggle the minor `org-cdlatex-mode'.
11354 This mode supports entering LaTeX environment and math in LaTeX fragments
11355 in Org-mode.
11356 \\{org-cdlatex-mode-map}"
11357 nil " OCDL" nil
11358 (when org-cdlatex-mode (require 'cdlatex))
11359 (unless org-cdlatex-texmathp-advice-is-done
11360 (setq org-cdlatex-texmathp-advice-is-done t)
11361 (defadvice texmathp (around org-math-always-on activate)
11362 "Always return t in org-mode buffers.
11363 This is because we want to insert math symbols without dollars even outside
11364 the LaTeX math segments. If Orgmode thinks that point is actually inside
11365 en embedded LaTeX fragement, let texmathp do its job.
11366 \\[org-cdlatex-mode-map]"
11367 (interactive)
11368 (let (p)
11369 (cond
11370 ((not (org-mode-p)) ad-do-it)
11371 ((eq this-command 'cdlatex-math-symbol)
11372 (setq ad-return-value t
11373 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11375 (let ((p (org-inside-LaTeX-fragment-p)))
11376 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11377 (setq ad-return-value t
11378 texmathp-why '("Org-mode embedded math" . 0))
11379 (if p ad-do-it)))))))))
11381 (defun turn-on-org-cdlatex ()
11382 "Unconditionally turn on `org-cdlatex-mode'."
11383 (org-cdlatex-mode 1))
11385 (defun org-inside-LaTeX-fragment-p ()
11386 "Test if point is inside a LaTeX fragment.
11387 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11388 sequence appearing also before point.
11389 Even though the matchers for math are configurable, this function assumes
11390 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11391 delimiters are skipped when they have been removed by customization.
11392 The return value is nil, or a cons cell with the delimiter and
11393 and the position of this delimiter.
11395 This function does a reasonably good job, but can locally be fooled by
11396 for example currency specifications. For example it will assume being in
11397 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11398 fragments that are properly closed, but during editing, we have to live
11399 with the uncertainty caused by missing closing delimiters. This function
11400 looks only before point, not after."
11401 (catch 'exit
11402 (let ((pos (point))
11403 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11404 (lim (progn
11405 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11406 (point)))
11407 dd-on str (start 0) m re)
11408 (goto-char pos)
11409 (when dodollar
11410 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11411 re (nth 1 (assoc "$" org-latex-regexps)))
11412 (while (string-match re str start)
11413 (cond
11414 ((= (match-end 0) (length str))
11415 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11416 ((= (match-end 0) (- (length str) 5))
11417 (throw 'exit nil))
11418 (t (setq start (match-end 0))))))
11419 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11420 (goto-char pos)
11421 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11422 (and (match-beginning 2) (throw 'exit nil))
11423 ;; count $$
11424 (while (re-search-backward "\\$\\$" lim t)
11425 (setq dd-on (not dd-on)))
11426 (goto-char pos)
11427 (if dd-on (cons "$$" m))))))
11430 (defun org-try-cdlatex-tab ()
11431 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11432 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11433 - inside a LaTeX fragment, or
11434 - after the first word in a line, where an abbreviation expansion could
11435 insert a LaTeX environment."
11436 (when org-cdlatex-mode
11437 (cond
11438 ((save-excursion
11439 (skip-chars-backward "a-zA-Z0-9*")
11440 (skip-chars-backward " \t")
11441 (bolp))
11442 (cdlatex-tab) t)
11443 ((org-inside-LaTeX-fragment-p)
11444 (cdlatex-tab) t)
11445 (t nil))))
11447 (defun org-cdlatex-underscore-caret (&optional arg)
11448 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11449 Revert to the normal definition outside of these fragments."
11450 (interactive "P")
11451 (if (org-inside-LaTeX-fragment-p)
11452 (call-interactively 'cdlatex-sub-superscript)
11453 (let (org-cdlatex-mode)
11454 (call-interactively (key-binding (vector last-input-event))))))
11456 (defun org-cdlatex-math-modify (&optional arg)
11457 "Execute `cdlatex-math-modify' in LaTeX fragments.
11458 Revert to the normal definition outside of these fragments."
11459 (interactive "P")
11460 (if (org-inside-LaTeX-fragment-p)
11461 (call-interactively 'cdlatex-math-modify)
11462 (let (org-cdlatex-mode)
11463 (call-interactively (key-binding (vector last-input-event))))))
11465 (defvar org-latex-fragment-image-overlays nil
11466 "List of overlays carrying the images of latex fragments.")
11467 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11469 (defun org-remove-latex-fragment-image-overlays ()
11470 "Remove all overlays with LaTeX fragment images in current buffer."
11471 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11472 (setq org-latex-fragment-image-overlays nil))
11474 (defun org-preview-latex-fragment (&optional subtree)
11475 "Preview the LaTeX fragment at point, or all locally or globally.
11476 If the cursor is in a LaTeX fragment, create the image and overlay
11477 it over the source code. If there is no fragment at point, display
11478 all fragments in the current text, from one headline to the next. With
11479 prefix SUBTREE, display all fragments in the current subtree. With a
11480 double prefix `C-u C-u', or when the cursor is before the first headline,
11481 display all fragments in the buffer.
11482 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11483 (interactive "P")
11484 (org-remove-latex-fragment-image-overlays)
11485 (save-excursion
11486 (save-restriction
11487 (let (beg end at msg)
11488 (cond
11489 ((or (equal subtree '(16))
11490 (not (save-excursion
11491 (re-search-backward (concat "^" outline-regexp) nil t))))
11492 (setq beg (point-min) end (point-max)
11493 msg "Creating images for buffer...%s"))
11494 ((equal subtree '(4))
11495 (org-back-to-heading)
11496 (setq beg (point) end (org-end-of-subtree t)
11497 msg "Creating images for subtree...%s"))
11499 (if (setq at (org-inside-LaTeX-fragment-p))
11500 (goto-char (max (point-min) (- (cdr at) 2)))
11501 (org-back-to-heading))
11502 (setq beg (point) end (progn (outline-next-heading) (point))
11503 msg (if at "Creating image...%s"
11504 "Creating images for entry...%s"))))
11505 (message msg "")
11506 (narrow-to-region beg end)
11507 (goto-char beg)
11508 (org-format-latex
11509 (concat "ltxpng/" (file-name-sans-extension
11510 (file-name-nondirectory
11511 buffer-file-name)))
11512 default-directory 'overlays msg at 'forbuffer)
11513 (message msg "done. Use `C-c C-c' to remove images.")))))
11515 (defvar org-latex-regexps
11516 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11517 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11518 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11519 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11520 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11521 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11522 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11523 "Regular expressions for matching embedded LaTeX.")
11525 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11526 "Replace LaTeX fragments with links to an image, and produce images."
11527 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11528 (let* ((prefixnodir (file-name-nondirectory prefix))
11529 (absprefix (expand-file-name prefix dir))
11530 (todir (file-name-directory absprefix))
11531 (opt org-format-latex-options)
11532 (matchers (plist-get opt :matchers))
11533 (re-list org-latex-regexps)
11534 (cnt 0) txt link beg end re e checkdir
11535 m n block linkfile movefile ov)
11536 ;; Check if there are old images files with this prefix, and remove them
11537 (when (file-directory-p todir)
11538 (mapc 'delete-file
11539 (directory-files
11540 todir 'full
11541 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11542 ;; Check the different regular expressions
11543 (while (setq e (pop re-list))
11544 (setq m (car e) re (nth 1 e) n (nth 2 e)
11545 block (if (nth 3 e) "\n\n" ""))
11546 (when (member m matchers)
11547 (goto-char (point-min))
11548 (while (re-search-forward re nil t)
11549 (when (or (not at) (equal (cdr at) (match-beginning n)))
11550 (setq txt (match-string n)
11551 beg (match-beginning n) end (match-end n)
11552 cnt (1+ cnt)
11553 linkfile (format "%s_%04d.png" prefix cnt)
11554 movefile (format "%s_%04d.png" absprefix cnt)
11555 link (concat block "[[file:" linkfile "]]" block))
11556 (if msg (message msg cnt))
11557 (goto-char beg)
11558 (unless checkdir ; make sure the directory exists
11559 (setq checkdir t)
11560 (or (file-directory-p todir) (make-directory todir)))
11561 (org-create-formula-image
11562 txt movefile opt forbuffer)
11563 (if overlays
11564 (progn
11565 (setq ov (org-make-overlay beg end))
11566 (if (featurep 'xemacs)
11567 (progn
11568 (org-overlay-put ov 'invisible t)
11569 (org-overlay-put
11570 ov 'end-glyph
11571 (make-glyph (vector 'png :file movefile))))
11572 (org-overlay-put
11573 ov 'display
11574 (list 'image :type 'png :file movefile :ascent 'center)))
11575 (push ov org-latex-fragment-image-overlays)
11576 (goto-char end))
11577 (delete-region beg end)
11578 (insert link))))))))
11580 ;; This function borrows from Ganesh Swami's latex2png.el
11581 (defun org-create-formula-image (string tofile options buffer)
11582 (let* ((tmpdir (if (featurep 'xemacs)
11583 (temp-directory)
11584 temporary-file-directory))
11585 (texfilebase (make-temp-name
11586 (expand-file-name "orgtex" tmpdir)))
11587 (texfile (concat texfilebase ".tex"))
11588 (dvifile (concat texfilebase ".dvi"))
11589 (pngfile (concat texfilebase ".png"))
11590 (fnh (if (featurep 'xemacs)
11591 (font-height (get-face-font 'default))
11592 (face-attribute 'default :height nil)))
11593 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11594 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11595 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11596 "Black"))
11597 (bg (or (plist-get options (if buffer :background :html-background))
11598 "Transparent")))
11599 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11600 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11601 (with-temp-file texfile
11602 (insert org-format-latex-header
11603 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11604 (let ((dir default-directory))
11605 (condition-case nil
11606 (progn
11607 (cd tmpdir)
11608 (call-process "latex" nil nil nil texfile))
11609 (error nil))
11610 (cd dir))
11611 (if (not (file-exists-p dvifile))
11612 (progn (message "Failed to create dvi file from %s" texfile) nil)
11613 (call-process "dvipng" nil nil nil
11614 "-E" "-fg" fg "-bg" bg
11615 "-D" dpi
11616 ;;"-x" scale "-y" scale
11617 "-T" "tight"
11618 "-o" pngfile
11619 dvifile)
11620 (if (not (file-exists-p pngfile))
11621 (progn (message "Failed to create png file from %s" texfile) nil)
11622 ;; Use the requested file name and clean up
11623 (copy-file pngfile tofile 'replace)
11624 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11625 (delete-file (concat texfilebase e)))
11626 pngfile))))
11628 (defun org-dvipng-color (attr)
11629 "Return an rgb color specification for dvipng."
11630 (apply 'format "rgb %s %s %s"
11631 (mapcar 'org-normalize-color
11632 (color-values (face-attribute 'default attr nil)))))
11634 (defun org-normalize-color (value)
11635 "Return string to be used as color value for an RGB component."
11636 (format "%g" (/ value 65535.0)))
11639 ;;;; Key bindings
11641 ;; Make `C-c C-x' a prefix key
11642 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11644 ;; TAB key with modifiers
11645 (org-defkey org-mode-map "\C-i" 'org-cycle)
11646 (org-defkey org-mode-map [(tab)] 'org-cycle)
11647 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11648 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11649 (org-defkey org-mode-map "\M-\t" 'org-complete)
11650 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11651 ;; The following line is necessary under Suse GNU/Linux
11652 (unless (featurep 'xemacs)
11653 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11654 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11655 (define-key org-mode-map [backtab] 'org-shifttab)
11657 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11658 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11659 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11661 ;; Cursor keys with modifiers
11662 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11663 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11664 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11665 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11667 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11668 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11669 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11670 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11672 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11673 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11674 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11675 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11677 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11678 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11680 ;;; Extra keys for tty access.
11681 ;; We only set them when really needed because otherwise the
11682 ;; menus don't show the simple keys
11684 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11685 (not window-system))
11686 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11687 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11688 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11689 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11690 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11691 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11692 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11693 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11694 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11695 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11696 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11697 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11698 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11699 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11700 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11701 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11702 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11703 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11704 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11705 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11706 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11707 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11709 ;; All the other keys
11711 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
11712 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
11713 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
11714 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
11715 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
11716 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
11717 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
11718 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
11719 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
11720 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
11721 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
11722 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
11723 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
11724 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
11725 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11726 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
11727 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
11728 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11729 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
11730 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
11731 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
11732 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
11733 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
11734 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
11735 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
11736 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
11737 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
11738 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
11739 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11740 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11741 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11742 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11743 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
11744 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
11745 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11746 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
11747 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
11748 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
11749 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
11750 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
11751 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
11752 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
11753 (org-defkey org-mode-map "\C-c^" 'org-sort)
11754 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11755 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
11756 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
11757 (org-defkey org-mode-map "\C-m" 'org-return)
11758 (org-defkey org-mode-map "\C-j" 'org-return-indent)
11759 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
11760 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
11761 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
11762 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
11763 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
11764 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
11765 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
11766 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11767 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
11768 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11769 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
11770 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
11771 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
11772 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11773 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
11775 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
11776 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11777 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11778 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11780 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
11781 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
11782 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
11783 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
11784 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
11785 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
11786 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
11787 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
11788 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
11789 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
11790 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
11791 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
11793 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
11795 (when (featurep 'xemacs)
11796 (org-defkey org-mode-map 'button3 'popup-mode-menu))
11798 (defvar org-table-auto-blank-field) ; defined in org-table.el
11799 (defun org-self-insert-command (N)
11800 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11801 If the cursor is in a table looking at whitespace, the whitespace is
11802 overwritten, and the table is not marked as requiring realignment."
11803 (interactive "p")
11804 (if (and (org-table-p)
11805 (progn
11806 ;; check if we blank the field, and if that triggers align
11807 (and (featurep 'org-table) org-table-auto-blank-field
11808 (member last-command
11809 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11810 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
11811 ;; got extra space, this field does not determine column width
11812 (let (org-table-may-need-update) (org-table-blank-field))
11813 ;; no extra space, this field may determine column width
11814 (org-table-blank-field)))
11816 (eq N 1)
11817 (looking-at "[^|\n]* |"))
11818 (let (org-table-may-need-update)
11819 (goto-char (1- (match-end 0)))
11820 (delete-backward-char 1)
11821 (goto-char (match-beginning 0))
11822 (self-insert-command N))
11823 (setq org-table-may-need-update t)
11824 (self-insert-command N)
11825 (org-fix-tags-on-the-fly)))
11827 (defun org-fix-tags-on-the-fly ()
11828 (when (and (equal (char-after (point-at-bol)) ?*)
11829 (org-on-heading-p))
11830 (org-align-tags-here org-tags-column)))
11832 (defun org-delete-backward-char (N)
11833 "Like `delete-backward-char', insert whitespace at field end in tables.
11834 When deleting backwards, in tables this function will insert whitespace in
11835 front of the next \"|\" separator, to keep the table aligned. The table will
11836 still be marked for re-alignment if the field did fill the entire column,
11837 because, in this case the deletion might narrow the column."
11838 (interactive "p")
11839 (if (and (org-table-p)
11840 (eq N 1)
11841 (string-match "|" (buffer-substring (point-at-bol) (point)))
11842 (looking-at ".*?|"))
11843 (let ((pos (point))
11844 (noalign (looking-at "[^|\n\r]* |"))
11845 (c org-table-may-need-update))
11846 (backward-delete-char N)
11847 (skip-chars-forward "^|")
11848 (insert " ")
11849 (goto-char (1- pos))
11850 ;; noalign: if there were two spaces at the end, this field
11851 ;; does not determine the width of the column.
11852 (if noalign (setq org-table-may-need-update c)))
11853 (backward-delete-char N)
11854 (org-fix-tags-on-the-fly)))
11856 (defun org-delete-char (N)
11857 "Like `delete-char', but insert whitespace at field end in tables.
11858 When deleting characters, in tables this function will insert whitespace in
11859 front of the next \"|\" separator, to keep the table aligned. The table will
11860 still be marked for re-alignment if the field did fill the entire column,
11861 because, in this case the deletion might narrow the column."
11862 (interactive "p")
11863 (if (and (org-table-p)
11864 (not (bolp))
11865 (not (= (char-after) ?|))
11866 (eq N 1))
11867 (if (looking-at ".*?|")
11868 (let ((pos (point))
11869 (noalign (looking-at "[^|\n\r]* |"))
11870 (c org-table-may-need-update))
11871 (replace-match (concat
11872 (substring (match-string 0) 1 -1)
11873 " |"))
11874 (goto-char pos)
11875 ;; noalign: if there were two spaces at the end, this field
11876 ;; does not determine the width of the column.
11877 (if noalign (setq org-table-may-need-update c)))
11878 (delete-char N))
11879 (delete-char N)
11880 (org-fix-tags-on-the-fly)))
11882 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
11883 (put 'org-self-insert-command 'delete-selection t)
11884 (put 'orgtbl-self-insert-command 'delete-selection t)
11885 (put 'org-delete-char 'delete-selection 'supersede)
11886 (put 'org-delete-backward-char 'delete-selection 'supersede)
11888 ;; Make `flyspell-mode' delay after some commands
11889 (put 'org-self-insert-command 'flyspell-delayed t)
11890 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
11891 (put 'org-delete-char 'flyspell-delayed t)
11892 (put 'org-delete-backward-char 'flyspell-delayed t)
11894 ;; Make pabbrev-mode expand after org-mode commands
11895 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
11896 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
11898 ;; How to do this: Measure non-white length of current string
11899 ;; If equal to column width, we should realign.
11901 (defun org-remap (map &rest commands)
11902 "In MAP, remap the functions given in COMMANDS.
11903 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11904 (let (new old)
11905 (while commands
11906 (setq old (pop commands) new (pop commands))
11907 (if (fboundp 'command-remapping)
11908 (org-defkey map (vector 'remap old) new)
11909 (substitute-key-definition old new map global-map)))))
11911 (when (eq org-enable-table-editor 'optimized)
11912 ;; If the user wants maximum table support, we need to hijack
11913 ;; some standard editing functions
11914 (org-remap org-mode-map
11915 'self-insert-command 'org-self-insert-command
11916 'delete-char 'org-delete-char
11917 'delete-backward-char 'org-delete-backward-char)
11918 (org-defkey org-mode-map "|" 'org-force-self-insert))
11920 (defun org-shiftcursor-error ()
11921 "Throw an error because Shift-Cursor command was applied in wrong context."
11922 (error "This command is active in special context like tables, headlines or timestamps"))
11924 (defun org-shifttab (&optional arg)
11925 "Global visibility cycling or move to previous table field.
11926 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
11927 on context.
11928 See the individual commands for more information."
11929 (interactive "P")
11930 (cond
11931 ((org-at-table-p) (call-interactively 'org-table-previous-field))
11932 (arg (message "Content view to level: ")
11933 (org-content (prefix-numeric-value arg))
11934 (setq org-cycle-global-status 'overview))
11935 (t (call-interactively 'org-global-cycle))))
11937 (defun org-shiftmetaleft ()
11938 "Promote subtree or delete table column.
11939 Calls `org-promote-subtree', `org-outdent-item',
11940 or `org-table-delete-column', depending on context.
11941 See the individual commands for more information."
11942 (interactive)
11943 (cond
11944 ((org-at-table-p) (call-interactively 'org-table-delete-column))
11945 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
11946 ((org-at-item-p) (call-interactively 'org-outdent-item))
11947 (t (org-shiftcursor-error))))
11949 (defun org-shiftmetaright ()
11950 "Demote subtree or insert table column.
11951 Calls `org-demote-subtree', `org-indent-item',
11952 or `org-table-insert-column', depending on context.
11953 See the individual commands for more information."
11954 (interactive)
11955 (cond
11956 ((org-at-table-p) (call-interactively 'org-table-insert-column))
11957 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
11958 ((org-at-item-p) (call-interactively 'org-indent-item))
11959 (t (org-shiftcursor-error))))
11961 (defun org-shiftmetaup (&optional arg)
11962 "Move subtree up or kill table row.
11963 Calls `org-move-subtree-up' or `org-table-kill-row' or
11964 `org-move-item-up' depending on context. See the individual commands
11965 for more information."
11966 (interactive "P")
11967 (cond
11968 ((org-at-table-p) (call-interactively 'org-table-kill-row))
11969 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
11970 ((org-at-item-p) (call-interactively 'org-move-item-up))
11971 (t (org-shiftcursor-error))))
11972 (defun org-shiftmetadown (&optional arg)
11973 "Move subtree down or insert table row.
11974 Calls `org-move-subtree-down' or `org-table-insert-row' or
11975 `org-move-item-down', depending on context. See the individual
11976 commands for more information."
11977 (interactive "P")
11978 (cond
11979 ((org-at-table-p) (call-interactively 'org-table-insert-row))
11980 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
11981 ((org-at-item-p) (call-interactively 'org-move-item-down))
11982 (t (org-shiftcursor-error))))
11984 (defun org-metaleft (&optional arg)
11985 "Promote heading or move table column to left.
11986 Calls `org-do-promote' or `org-table-move-column', depending on context.
11987 With no specific context, calls the Emacs default `backward-word'.
11988 See the individual commands for more information."
11989 (interactive "P")
11990 (cond
11991 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
11992 ((or (org-on-heading-p) (org-region-active-p))
11993 (call-interactively 'org-do-promote))
11994 ((org-at-item-p) (call-interactively 'org-outdent-item))
11995 (t (call-interactively 'backward-word))))
11997 (defun org-metaright (&optional arg)
11998 "Demote subtree or move table column to right.
11999 Calls `org-do-demote' or `org-table-move-column', depending on context.
12000 With no specific context, calls the Emacs default `forward-word'.
12001 See the individual commands for more information."
12002 (interactive "P")
12003 (cond
12004 ((org-at-table-p) (call-interactively 'org-table-move-column))
12005 ((or (org-on-heading-p) (org-region-active-p))
12006 (call-interactively 'org-do-demote))
12007 ((org-at-item-p) (call-interactively 'org-indent-item))
12008 (t (call-interactively 'forward-word))))
12010 (defun org-metaup (&optional arg)
12011 "Move subtree up or move table row up.
12012 Calls `org-move-subtree-up' or `org-table-move-row' or
12013 `org-move-item-up', depending on context. See the individual commands
12014 for more information."
12015 (interactive "P")
12016 (cond
12017 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12018 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12019 ((org-at-item-p) (call-interactively 'org-move-item-up))
12020 (t (transpose-lines 1) (beginning-of-line -1))))
12022 (defun org-metadown (&optional arg)
12023 "Move subtree down or move table row down.
12024 Calls `org-move-subtree-down' or `org-table-move-row' or
12025 `org-move-item-down', depending on context. See the individual
12026 commands for more information."
12027 (interactive "P")
12028 (cond
12029 ((org-at-table-p) (call-interactively 'org-table-move-row))
12030 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12031 ((org-at-item-p) (call-interactively 'org-move-item-down))
12032 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12034 (defun org-shiftup (&optional arg)
12035 "Increase item in timestamp or increase priority of current headline.
12036 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12037 depending on context. See the individual commands for more information."
12038 (interactive "P")
12039 (cond
12040 ((org-at-timestamp-p t)
12041 (call-interactively (if org-edit-timestamp-down-means-later
12042 'org-timestamp-down 'org-timestamp-up)))
12043 ((org-on-heading-p) (call-interactively 'org-priority-up))
12044 ((org-at-item-p) (call-interactively 'org-previous-item))
12045 ((org-clocktable-try-shift 'up arg))
12046 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12048 (defun org-shiftdown (&optional arg)
12049 "Decrease item in timestamp or decrease priority of current headline.
12050 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12051 depending on context. See the individual commands for more information."
12052 (interactive "P")
12053 (cond
12054 ((org-at-timestamp-p t)
12055 (call-interactively (if org-edit-timestamp-down-means-later
12056 'org-timestamp-up 'org-timestamp-down)))
12057 ((org-on-heading-p) (call-interactively 'org-priority-down))
12058 ((org-clocktable-try-shift 'down arg))
12059 (t (call-interactively 'org-next-item))))
12061 (defun org-shiftright (&optional arg)
12062 "Next TODO keyword or timestamp one day later, depending on context."
12063 (interactive "P")
12064 (cond
12065 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12066 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12067 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12068 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12069 ((org-clocktable-try-shift 'right arg))
12070 (t (org-shiftcursor-error))))
12072 (defun org-shiftleft (&optional arg)
12073 "Previous TODO keyword or timestamp one day earlier, depending on context."
12074 (interactive "P")
12075 (cond
12076 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12077 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12078 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12079 ((org-at-property-p)
12080 (call-interactively 'org-property-previous-allowed-value))
12081 ((org-clocktable-try-shift 'left arg))
12082 (t (org-shiftcursor-error))))
12084 (defun org-shiftcontrolright ()
12085 "Switch to next TODO set."
12086 (interactive)
12087 (cond
12088 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12089 (t (org-shiftcursor-error))))
12091 (defun org-shiftcontrolleft ()
12092 "Switch to previous TODO set."
12093 (interactive)
12094 (cond
12095 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12096 (t (org-shiftcursor-error))))
12098 (defun org-ctrl-c-ret ()
12099 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12100 (interactive)
12101 (cond
12102 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12103 (t (call-interactively 'org-insert-heading))))
12105 (defun org-copy-special ()
12106 "Copy region in table or copy current subtree.
12107 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12108 See the individual commands for more information."
12109 (interactive)
12110 (call-interactively
12111 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12113 (defun org-cut-special ()
12114 "Cut region in table or cut current subtree.
12115 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12116 See the individual commands for more information."
12117 (interactive)
12118 (call-interactively
12119 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12121 (defun org-paste-special (arg)
12122 "Paste rectangular region into table, or past subtree relative to level.
12123 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12124 See the individual commands for more information."
12125 (interactive "P")
12126 (if (org-at-table-p)
12127 (org-table-paste-rectangle)
12128 (org-paste-subtree arg)))
12130 (defun org-ctrl-c-ctrl-c (&optional arg)
12131 "Set tags in headline, or update according to changed information at point.
12133 This command does many different things, depending on context:
12135 - If the cursor is in a headline, prompt for tags and insert them
12136 into the current line, aligned to `org-tags-column'. When called
12137 with prefix arg, realign all tags in the current buffer.
12139 - If the cursor is in one of the special #+KEYWORD lines, this
12140 triggers scanning the buffer for these lines and updating the
12141 information.
12143 - If the cursor is inside a table, realign the table. This command
12144 works even if the automatic table editor has been turned off.
12146 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12147 the entire table.
12149 - If the cursor is a the beginning of a dynamic block, update it.
12151 - If the cursor is inside a table created by the table.el package,
12152 activate that table.
12154 - If the current buffer is a remember buffer, close note and file it.
12155 with a prefix argument, file it without further interaction to the default
12156 location.
12158 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12159 links in this buffer.
12161 - If the cursor is on a numbered item in a plain list, renumber the
12162 ordered list.
12164 - If the cursor is on a checkbox, toggle it."
12165 (interactive "P")
12166 (let ((org-enable-table-editor t))
12167 (cond
12168 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12169 org-occur-highlights
12170 org-latex-fragment-image-overlays)
12171 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12172 (org-remove-occur-highlights)
12173 (org-remove-latex-fragment-image-overlays)
12174 (message "Temporary highlights/overlays removed from current buffer"))
12175 ((and (local-variable-p 'org-finish-function (current-buffer))
12176 (fboundp org-finish-function))
12177 (funcall org-finish-function))
12178 ((org-at-property-p)
12179 (call-interactively 'org-property-action))
12180 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12181 ((org-on-heading-p) (call-interactively 'org-set-tags))
12182 ((org-at-table.el-p)
12183 (require 'table)
12184 (beginning-of-line 1)
12185 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12186 (call-interactively 'table-recognize-table))
12187 ((org-at-table-p)
12188 (org-table-maybe-eval-formula)
12189 (if arg
12190 (call-interactively 'org-table-recalculate)
12191 (org-table-maybe-recalculate-line))
12192 (call-interactively 'org-table-align))
12193 ((org-at-item-checkbox-p)
12194 (call-interactively 'org-toggle-checkbox))
12195 ((org-at-item-p)
12196 (call-interactively 'org-maybe-renumber-ordered-list))
12197 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12198 ;; Dynamic block
12199 (beginning-of-line 1)
12200 (org-update-dblock))
12201 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12202 (cond
12203 ((equal (match-string 1) "TBLFM")
12204 ;; Recalculate the table before this line
12205 (save-excursion
12206 (beginning-of-line 1)
12207 (skip-chars-backward " \r\n\t")
12208 (if (org-at-table-p)
12209 (org-call-with-arg 'org-table-recalculate t))))
12211 (call-interactively 'org-mode-restart))))
12212 (t (error "C-c C-c can do nothing useful at this location.")))))
12214 (defun org-mode-restart ()
12215 "Restart Org-mode, to scan again for special lines.
12216 Also updates the keyword regular expressions."
12217 (interactive)
12218 (let ((org-inhibit-startup t)) (org-mode))
12219 (message "Org-mode restarted to refresh keyword and special line setup"))
12221 (defun org-kill-note-or-show-branches ()
12222 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12223 (interactive)
12224 (if (not org-finish-function)
12225 (call-interactively 'show-branches)
12226 (let ((org-note-abort t))
12227 (funcall org-finish-function))))
12229 (defun org-return (&optional indent)
12230 "Goto next table row or insert a newline.
12231 Calls `org-table-next-row' or `newline', depending on context.
12232 See the individual commands for more information."
12233 (interactive)
12234 (cond
12235 ((bobp) (if indent (newline-and-indent) (newline)))
12236 ((and (org-at-heading-p)
12237 (looking-at
12238 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12239 (org-show-entry)
12240 (end-of-line 1)
12241 (newline))
12242 ((org-at-table-p)
12243 (org-table-justify-field-maybe)
12244 (call-interactively 'org-table-next-row))
12245 (t (if indent (newline-and-indent) (newline)))))
12247 (defun org-return-indent ()
12248 "Goto next table row or insert a newline and indent.
12249 Calls `org-table-next-row' or `newline-and-indent', depending on
12250 context. See the individual commands for more information."
12251 (interactive)
12252 (org-return t))
12254 (defun org-ctrl-c-star ()
12255 "Compute table, or change heading status of lines.
12256 Calls `org-table-recalculate' or `org-toggle-region-headlines',
12257 depending on context. This will also turn a plain list item or a normal
12258 line into a subheading."
12259 (interactive)
12260 (cond
12261 ((org-at-table-p)
12262 (call-interactively 'org-table-recalculate))
12263 ((org-region-active-p)
12264 ;; Convert all lines in region to list items
12265 (call-interactively 'org-toggle-region-headings))
12266 ((org-on-heading-p)
12267 (org-toggle-region-headings (point-at-bol)
12268 (min (1+ (point-at-eol)) (point-max))))
12269 ((org-at-item-p)
12270 ;; Convert to heading
12271 (let ((level (save-match-data
12272 (save-excursion
12273 (condition-case nil
12274 (progn
12275 (org-back-to-heading t)
12276 (funcall outline-level))
12277 (error 0))))))
12278 (replace-match
12279 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12280 (t (org-toggle-region-headings (point-at-bol)
12281 (min (1+ (point-at-eol)) (point-max))))))
12283 (defun org-ctrl-c-minus ()
12284 "Insert separator line in table or modify bullet status of line.
12285 Also turns a plain line or a region of lines into list items.
12286 Calls `org-table-insert-hline', `org-toggle-region-items', or
12287 `org-cycle-list-bullet', depending on context."
12288 (interactive)
12289 (cond
12290 ((org-at-table-p)
12291 (call-interactively 'org-table-insert-hline))
12292 ((org-on-heading-p)
12293 ;; Convert to item
12294 (save-excursion
12295 (beginning-of-line 1)
12296 (if (looking-at "\\*+ ")
12297 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12298 ((org-region-active-p)
12299 ;; Convert all lines in region to list items
12300 (call-interactively 'org-toggle-region-items))
12301 ((org-in-item-p)
12302 (call-interactively 'org-cycle-list-bullet))
12303 (t (org-toggle-region-items (point-at-bol)
12304 (min (1+ (point-at-eol)) (point-max))))))
12306 (defun org-toggle-region-items (beg end)
12307 "Convert all lines in region to list items.
12308 If the first line is already an item, convert all list items in the region
12309 to normal lines."
12310 (interactive "r")
12311 (let (l2 l)
12312 (save-excursion
12313 (goto-char end)
12314 (setq l2 (org-current-line))
12315 (goto-char beg)
12316 (beginning-of-line 1)
12317 (setq l (1- (org-current-line)))
12318 (if (org-at-item-p)
12319 ;; We already have items, de-itemize
12320 (while (< (setq l (1+ l)) l2)
12321 (when (org-at-item-p)
12322 (goto-char (match-beginning 2))
12323 (delete-region (match-beginning 2) (match-end 2))
12324 (and (looking-at "[ \t]+") (replace-match "")))
12325 (beginning-of-line 2))
12326 (while (< (setq l (1+ l)) l2)
12327 (unless (org-at-item-p)
12328 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12329 (replace-match "\\1- \\2")))
12330 (beginning-of-line 2))))))
12332 (defun org-toggle-region-headings (beg end)
12333 "Convert all lines in region to list items.
12334 If the first line is already an item, convert all list items in the region
12335 to normal lines."
12336 (interactive "r")
12337 (let (l2 l)
12338 (save-excursion
12339 (goto-char end)
12340 (setq l2 (org-current-line))
12341 (goto-char beg)
12342 (beginning-of-line 1)
12343 (setq l (1- (org-current-line)))
12344 (if (org-on-heading-p)
12345 ;; We already have headlines, de-star them
12346 (while (< (setq l (1+ l)) l2)
12347 (when (org-on-heading-p t)
12348 (and (looking-at outline-regexp) (replace-match "")))
12349 (beginning-of-line 2))
12350 (let* ((stars (save-excursion
12351 (re-search-backward org-complex-heading-regexp nil t)
12352 (or (match-string 1) "*")))
12353 (add-stars (if org-odd-levels-only "**" "*"))
12354 (rpl (concat stars add-stars " \\2")))
12355 (while (< (setq l (1+ l)) l2)
12356 (unless (org-on-heading-p)
12357 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12358 (replace-match rpl)))
12359 (beginning-of-line 2)))))))
12361 (defun org-meta-return (&optional arg)
12362 "Insert a new heading or wrap a region in a table.
12363 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12364 See the individual commands for more information."
12365 (interactive "P")
12366 (cond
12367 ((org-at-table-p)
12368 (call-interactively 'org-table-wrap-region))
12369 (t (call-interactively 'org-insert-heading))))
12371 ;;; Menu entries
12373 ;; Define the Org-mode menus
12374 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12375 '("Tbl"
12376 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12377 ["Next Field" org-cycle (org-at-table-p)]
12378 ["Previous Field" org-shifttab (org-at-table-p)]
12379 ["Next Row" org-return (org-at-table-p)]
12380 "--"
12381 ["Blank Field" org-table-blank-field (org-at-table-p)]
12382 ["Edit Field" org-table-edit-field (org-at-table-p)]
12383 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12384 "--"
12385 ("Column"
12386 ["Move Column Left" org-metaleft (org-at-table-p)]
12387 ["Move Column Right" org-metaright (org-at-table-p)]
12388 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12389 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12390 ("Row"
12391 ["Move Row Up" org-metaup (org-at-table-p)]
12392 ["Move Row Down" org-metadown (org-at-table-p)]
12393 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12394 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12395 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12396 "--"
12397 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12398 ("Rectangle"
12399 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12400 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12401 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12402 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12403 "--"
12404 ("Calculate"
12405 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12406 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12407 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12408 "--"
12409 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12410 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12411 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12412 "--"
12413 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12414 "--"
12415 ["Sum Column/Rectangle" org-table-sum
12416 (or (org-at-table-p) (org-region-active-p))]
12417 ["Which Column?" org-table-current-column (org-at-table-p)])
12418 ["Debug Formulas"
12419 org-table-toggle-formula-debugger
12420 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12421 ["Show Col/Row Numbers"
12422 org-table-toggle-coordinate-overlays
12423 :style toggle
12424 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12425 "--"
12426 ["Create" org-table-create (and (not (org-at-table-p))
12427 org-enable-table-editor)]
12428 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12429 ["Import from File" org-table-import (not (org-at-table-p))]
12430 ["Export to File" org-table-export (org-at-table-p)]
12431 "--"
12432 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12434 (easy-menu-define org-org-menu org-mode-map "Org menu"
12435 '("Org"
12436 ("Show/Hide"
12437 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12438 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12439 ["Sparse Tree..." org-sparse-tree t]
12440 ["Reveal Context" org-reveal t]
12441 ["Show All" show-all t]
12442 "--"
12443 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12444 "--"
12445 ["New Heading" org-insert-heading t]
12446 ("Navigate Headings"
12447 ["Up" outline-up-heading t]
12448 ["Next" outline-next-visible-heading t]
12449 ["Previous" outline-previous-visible-heading t]
12450 ["Next Same Level" outline-forward-same-level t]
12451 ["Previous Same Level" outline-backward-same-level t]
12452 "--"
12453 ["Jump" org-goto t])
12454 ("Edit Structure"
12455 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12456 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12457 "--"
12458 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12459 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12460 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12461 "--"
12462 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12463 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12464 ["Demote Heading" org-metaright (not (org-at-table-p))]
12465 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12466 "--"
12467 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12468 "--"
12469 ["Convert to odd levels" org-convert-to-odd-levels t]
12470 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12471 ("Editing"
12472 ["Emphasis..." org-emphasize t])
12473 ("Archive"
12474 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12475 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12476 ; :active t :keys "C-u C-c C-x C-a"]
12477 ["Sparse trees open ARCHIVE trees"
12478 (setq org-sparse-tree-open-archived-trees
12479 (not org-sparse-tree-open-archived-trees))
12480 :style toggle :selected org-sparse-tree-open-archived-trees]
12481 ["Cycling opens ARCHIVE trees"
12482 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12483 :style toggle :selected org-cycle-open-archived-trees]
12484 ["Agenda includes ARCHIVE trees"
12485 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
12486 :style toggle :selected (not org-agenda-skip-archived-trees)]
12487 "--"
12488 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12489 ; ["Check and Move Children" (org-archive-subtree '(4))
12490 ; :active t :keys "C-u C-c C-x C-s"]
12492 "--"
12493 ("TODO Lists"
12494 ["TODO/DONE/-" org-todo t]
12495 ("Select keyword"
12496 ["Next keyword" org-shiftright (org-on-heading-p)]
12497 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12498 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12499 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12500 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12501 ["Show TODO Tree" org-show-todo-tree t]
12502 ["Global TODO list" org-todo-list t]
12503 "--"
12504 ["Set Priority" org-priority t]
12505 ["Priority Up" org-shiftup t]
12506 ["Priority Down" org-shiftdown t])
12507 ("TAGS and Properties"
12508 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12509 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12510 "--"
12511 ["Set property" 'org-set-property t]
12512 ["Column view of properties" org-columns t]
12513 ["Insert Column View DBlock" org-insert-columns-dblock t])
12514 ("Dates and Scheduling"
12515 ["Timestamp" org-time-stamp t]
12516 ["Timestamp (inactive)" org-time-stamp-inactive t]
12517 ("Change Date"
12518 ["1 Day Later" org-shiftright t]
12519 ["1 Day Earlier" org-shiftleft t]
12520 ["1 ... Later" org-shiftup t]
12521 ["1 ... Earlier" org-shiftdown t])
12522 ["Compute Time Range" org-evaluate-time-range t]
12523 ["Schedule Item" org-schedule t]
12524 ["Deadline" org-deadline t]
12525 "--"
12526 ["Custom time format" org-toggle-time-stamp-overlays
12527 :style radio :selected org-display-custom-times]
12528 "--"
12529 ["Goto Calendar" org-goto-calendar t]
12530 ["Date from Calendar" org-date-from-calendar t])
12531 ("Logging work"
12532 ["Clock in" org-clock-in t]
12533 ["Clock out" org-clock-out t]
12534 ["Clock cancel" org-clock-cancel t]
12535 ["Goto running clock" org-clock-goto t]
12536 ["Display times" org-clock-display t]
12537 ["Create clock table" org-clock-report t]
12538 "--"
12539 ["Record DONE time"
12540 (progn (setq org-log-done (not org-log-done))
12541 (message "Switching to %s will %s record a timestamp"
12542 (car org-done-keywords)
12543 (if org-log-done "automatically" "not")))
12544 :style toggle :selected org-log-done])
12545 "--"
12546 ["Agenda Command..." org-agenda t]
12547 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12548 ("File List for Agenda")
12549 ("Special views current file"
12550 ["TODO Tree" org-show-todo-tree t]
12551 ["Check Deadlines" org-check-deadlines t]
12552 ["Timeline" org-timeline t]
12553 ["Tags Tree" org-tags-sparse-tree t])
12554 "--"
12555 ("Hyperlinks"
12556 ["Store Link (Global)" org-store-link t]
12557 ["Insert Link" org-insert-link t]
12558 ["Follow Link" org-open-at-point t]
12559 "--"
12560 ["Next link" org-next-link t]
12561 ["Previous link" org-previous-link t]
12562 "--"
12563 ["Descriptive Links"
12564 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12565 :style radio
12566 :selected (member '(org-link) buffer-invisibility-spec)]
12567 ["Literal Links"
12568 (progn
12569 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12570 :style radio
12571 :selected (not (member '(org-link) buffer-invisibility-spec))])
12572 "--"
12573 ["Export/Publish..." org-export t]
12574 ("LaTeX"
12575 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12576 :selected org-cdlatex-mode]
12577 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12578 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12579 ["Modify math symbol" org-cdlatex-math-modify
12580 (org-inside-LaTeX-fragment-p)]
12581 ["Export LaTeX fragments as images"
12582 (if (featurep 'org-exp)
12583 (setq org-export-with-LaTeX-fragments
12584 (not org-export-with-LaTeX-fragments))
12585 (require 'org-exp))
12586 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12587 org-export-with-LaTeX-fragments)])
12588 "--"
12589 ("Documentation"
12590 ["Show Version" org-version t]
12591 ["Info Documentation" org-info t])
12592 ("Customize"
12593 ["Browse Org Group" org-customize t]
12594 "--"
12595 ["Expand This Menu" org-create-customize-menu
12596 (fboundp 'customize-menu-create)])
12597 "--"
12598 ["Refresh setup" org-mode-restart t]
12601 (defun org-info (&optional node)
12602 "Read documentation for Org-mode in the info system.
12603 With optional NODE, go directly to that node."
12604 (interactive)
12605 (info (format "(org)%s" (or node ""))))
12607 (defun org-install-agenda-files-menu ()
12608 (let ((bl (buffer-list)))
12609 (save-excursion
12610 (while bl
12611 (set-buffer (pop bl))
12612 (if (org-mode-p) (setq bl nil)))
12613 (when (org-mode-p)
12614 (easy-menu-change
12615 '("Org") "File List for Agenda"
12616 (append
12617 (list
12618 ["Edit File List" (org-edit-agenda-file-list) t]
12619 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12620 ["Remove Current File from List" org-remove-file t]
12621 ["Cycle through agenda files" org-cycle-agenda-files t]
12622 ["Occur in all agenda files" org-occur-in-agenda-files t]
12623 "--")
12624 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12626 ;;;; Documentation
12628 (defun org-require-autoloaded-modules ()
12629 (interactive)
12630 (mapc 'require
12631 '(org-agenda org-archive org-clock org-colview
12632 org-exp org-export-latex org-publish
12633 org-remember org-table)))
12635 (defun org-customize ()
12636 "Call the customize function with org as argument."
12637 (interactive)
12638 (org-load-modules-maybe)
12639 (org-require-autoloaded-modules)
12640 (customize-browse 'org))
12642 (defun org-create-customize-menu ()
12643 "Create a full customization menu for Org-mode, insert it into the menu."
12644 (interactive)
12645 (org-load-modules-maybe)
12646 (org-require-autoloaded-modules)
12647 (if (fboundp 'customize-menu-create)
12648 (progn
12649 (easy-menu-change
12650 '("Org") "Customize"
12651 `(["Browse Org group" org-customize t]
12652 "--"
12653 ,(customize-menu-create 'org)
12654 ["Set" Custom-set t]
12655 ["Save" Custom-save t]
12656 ["Reset to Current" Custom-reset-current t]
12657 ["Reset to Saved" Custom-reset-saved t]
12658 ["Reset to Standard Settings" Custom-reset-standard t]))
12659 (message "\"Org\"-menu now contains full customization menu"))
12660 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12662 ;;;; Miscellaneous stuff
12664 ;;; Generally useful functions
12666 (defun org-plist-delete (plist property)
12667 "Delete PROPERTY from PLIST.
12668 This is in contrast to merely setting it to 0."
12669 (let (p)
12670 (while plist
12671 (if (not (eq property (car plist)))
12672 (setq p (plist-put p (car plist) (nth 1 plist))))
12673 (setq plist (cddr plist)))
12676 (defun org-force-self-insert (N)
12677 "Needed to enforce self-insert under remapping."
12678 (interactive "p")
12679 (self-insert-command N))
12681 (defun org-string-width (s)
12682 "Compute width of string, ignoring invisible characters.
12683 This ignores character with invisibility property `org-link', and also
12684 characters with property `org-cwidth', because these will become invisible
12685 upon the next fontification round."
12686 (let (b l)
12687 (when (or (eq t buffer-invisibility-spec)
12688 (assq 'org-link buffer-invisibility-spec))
12689 (while (setq b (text-property-any 0 (length s)
12690 'invisible 'org-link s))
12691 (setq s (concat (substring s 0 b)
12692 (substring s (or (next-single-property-change
12693 b 'invisible s) (length s)))))))
12694 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
12695 (setq s (concat (substring s 0 b)
12696 (substring s (or (next-single-property-change
12697 b 'org-cwidth s) (length s))))))
12698 (setq l (string-width s) b -1)
12699 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
12700 (setq l (- l (get-text-property b 'org-dwidth-n s))))
12704 (defun org-trim (s)
12705 "Remove whitespace at beginning and end of string."
12706 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
12707 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
12710 (defun org-wrap (string &optional width lines)
12711 "Wrap string to either a number of lines, or a width in characters.
12712 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12713 that costs. If there is a word longer than WIDTH, the text is actually
12714 wrapped to the length of that word.
12715 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12716 many lines, whatever width that takes.
12717 The return value is a list of lines, without newlines at the end."
12718 (let* ((words (org-split-string string "[ \t\n]+"))
12719 (maxword (apply 'max (mapcar 'org-string-width words)))
12720 w ll)
12721 (cond (width
12722 (org-do-wrap words (max maxword width)))
12723 (lines
12724 (setq w maxword)
12725 (setq ll (org-do-wrap words maxword))
12726 (if (<= (length ll) lines)
12728 (setq ll words)
12729 (while (> (length ll) lines)
12730 (setq w (1+ w))
12731 (setq ll (org-do-wrap words w)))
12732 ll))
12733 (t (error "Cannot wrap this")))))
12735 (defun org-do-wrap (words width)
12736 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12737 (let (lines line)
12738 (while words
12739 (setq line (pop words))
12740 (while (and words (< (+ (length line) (length (car words))) width))
12741 (setq line (concat line " " (pop words))))
12742 (setq lines (push line lines)))
12743 (nreverse lines)))
12745 (defun org-split-string (string &optional separators)
12746 "Splits STRING into substrings at SEPARATORS.
12747 No empty strings are returned if there are matches at the beginning
12748 and end of string."
12749 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
12750 (start 0)
12751 notfirst
12752 (list nil))
12753 (while (and (string-match rexp string
12754 (if (and notfirst
12755 (= start (match-beginning 0))
12756 (< start (length string)))
12757 (1+ start) start))
12758 (< (match-beginning 0) (length string)))
12759 (setq notfirst t)
12760 (or (eq (match-beginning 0) 0)
12761 (and (eq (match-beginning 0) (match-end 0))
12762 (eq (match-beginning 0) start))
12763 (setq list
12764 (cons (substring string start (match-beginning 0))
12765 list)))
12766 (setq start (match-end 0)))
12767 (or (eq start (length string))
12768 (setq list
12769 (cons (substring string start)
12770 list)))
12771 (nreverse list)))
12773 (defun org-context ()
12774 "Return a list of contexts of the current cursor position.
12775 If several contexts apply, all are returned.
12776 Each context entry is a list with a symbol naming the context, and
12777 two positions indicating start and end of the context. Possible
12778 contexts are:
12780 :headline anywhere in a headline
12781 :headline-stars on the leading stars in a headline
12782 :todo-keyword on a TODO keyword (including DONE) in a headline
12783 :tags on the TAGS in a headline
12784 :priority on the priority cookie in a headline
12785 :item on the first line of a plain list item
12786 :item-bullet on the bullet/number of a plain list item
12787 :checkbox on the checkbox in a plain list item
12788 :table in an org-mode table
12789 :table-special on a special filed in a table
12790 :table-table in a table.el table
12791 :link on a hyperlink
12792 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
12793 :target on a <<target>>
12794 :radio-target on a <<<radio-target>>>
12795 :latex-fragment on a LaTeX fragment
12796 :latex-preview on a LaTeX fragment with overlayed preview image
12798 This function expects the position to be visible because it uses font-lock
12799 faces as a help to recognize the following contexts: :table-special, :link,
12800 and :keyword."
12801 (let* ((f (get-text-property (point) 'face))
12802 (faces (if (listp f) f (list f)))
12803 (p (point)) clist o)
12804 ;; First the large context
12805 (cond
12806 ((org-on-heading-p t)
12807 (push (list :headline (point-at-bol) (point-at-eol)) clist)
12808 (when (progn
12809 (beginning-of-line 1)
12810 (looking-at org-todo-line-tags-regexp))
12811 (push (org-point-in-group p 1 :headline-stars) clist)
12812 (push (org-point-in-group p 2 :todo-keyword) clist)
12813 (push (org-point-in-group p 4 :tags) clist))
12814 (goto-char p)
12815 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
12816 (if (looking-at "\\[#[A-Z0-9]\\]")
12817 (push (org-point-in-group p 0 :priority) clist)))
12819 ((org-at-item-p)
12820 (push (org-point-in-group p 2 :item-bullet) clist)
12821 (push (list :item (point-at-bol)
12822 (save-excursion (org-end-of-item) (point)))
12823 clist)
12824 (and (org-at-item-checkbox-p)
12825 (push (org-point-in-group p 0 :checkbox) clist)))
12827 ((org-at-table-p)
12828 (push (list :table (org-table-begin) (org-table-end)) clist)
12829 (if (memq 'org-formula faces)
12830 (push (list :table-special
12831 (previous-single-property-change p 'face)
12832 (next-single-property-change p 'face)) clist)))
12833 ((org-at-table-p 'any)
12834 (push (list :table-table) clist)))
12835 (goto-char p)
12837 ;; Now the small context
12838 (cond
12839 ((org-at-timestamp-p)
12840 (push (org-point-in-group p 0 :timestamp) clist))
12841 ((memq 'org-link faces)
12842 (push (list :link
12843 (previous-single-property-change p 'face)
12844 (next-single-property-change p 'face)) clist))
12845 ((memq 'org-special-keyword faces)
12846 (push (list :keyword
12847 (previous-single-property-change p 'face)
12848 (next-single-property-change p 'face)) clist))
12849 ((org-on-target-p)
12850 (push (org-point-in-group p 0 :target) clist)
12851 (goto-char (1- (match-beginning 0)))
12852 (if (looking-at org-radio-target-regexp)
12853 (push (org-point-in-group p 0 :radio-target) clist))
12854 (goto-char p))
12855 ((setq o (car (delq nil
12856 (mapcar
12857 (lambda (x)
12858 (if (memq x org-latex-fragment-image-overlays) x))
12859 (org-overlays-at (point))))))
12860 (push (list :latex-fragment
12861 (org-overlay-start o) (org-overlay-end o)) clist)
12862 (push (list :latex-preview
12863 (org-overlay-start o) (org-overlay-end o)) clist))
12864 ((org-inside-LaTeX-fragment-p)
12865 ;; FIXME: positions wrong.
12866 (push (list :latex-fragment (point) (point)) clist)))
12868 (setq clist (nreverse (delq nil clist)))
12869 clist))
12871 ;; FIXME: Compare with at-regexp-p Do we need both?
12872 (defun org-in-regexp (re &optional nlines visually)
12873 "Check if point is inside a match of regexp.
12874 Normally only the current line is checked, but you can include NLINES extra
12875 lines both before and after point into the search.
12876 If VISUALLY is set, require that the cursor is not after the match but
12877 really on, so that the block visually is on the match."
12878 (catch 'exit
12879 (let ((pos (point))
12880 (eol (point-at-eol (+ 1 (or nlines 0))))
12881 (inc (if visually 1 0)))
12882 (save-excursion
12883 (beginning-of-line (- 1 (or nlines 0)))
12884 (while (re-search-forward re eol t)
12885 (if (and (<= (match-beginning 0) pos)
12886 (>= (+ inc (match-end 0)) pos))
12887 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
12889 (defun org-at-regexp-p (regexp)
12890 "Is point inside a match of REGEXP in the current line?"
12891 (catch 'exit
12892 (save-excursion
12893 (let ((pos (point)) (end (point-at-eol)))
12894 (beginning-of-line 1)
12895 (while (re-search-forward regexp end t)
12896 (if (and (<= (match-beginning 0) pos)
12897 (>= (match-end 0) pos))
12898 (throw 'exit t)))
12899 nil))))
12901 (defun org-occur-in-agenda-files (regexp &optional nlines)
12902 "Call `multi-occur' with buffers for all agenda files."
12903 (interactive "sOrg-files matching: \np")
12904 (let* ((files (org-agenda-files))
12905 (tnames (mapcar 'file-truename files))
12906 (extra org-agenda-text-search-extra-files)
12908 (when (eq (car extra) 'agenda-archives)
12909 (setq extra (cdr extra))
12910 (setq files (org-add-archive-files files)))
12911 (while (setq f (pop extra))
12912 (unless (member (file-truename f) tnames)
12913 (add-to-list 'files f 'append)
12914 (add-to-list 'tnames (file-truename f) 'append)))
12915 (multi-occur
12916 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
12917 regexp)))
12919 (if (boundp 'occur-mode-find-occurrence-hook)
12920 ;; Emacs 23
12921 (add-hook 'occur-mode-find-occurrence-hook
12922 (lambda ()
12923 (when (org-mode-p)
12924 (org-reveal))))
12925 ;; Emacs 22
12926 (defadvice occur-mode-goto-occurrence
12927 (after org-occur-reveal activate)
12928 (and (org-mode-p) (org-reveal)))
12929 (defadvice occur-mode-goto-occurrence-other-window
12930 (after org-occur-reveal activate)
12931 (and (org-mode-p) (org-reveal)))
12932 (defadvice occur-mode-display-occurrence
12933 (after org-occur-reveal activate)
12934 (when (org-mode-p)
12935 (let ((pos (occur-mode-find-occurrence)))
12936 (with-current-buffer (marker-buffer pos)
12937 (save-excursion
12938 (goto-char pos)
12939 (org-reveal)))))))
12941 (defun org-uniquify (list)
12942 "Remove duplicate elements from LIST."
12943 (let (res)
12944 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
12945 res))
12947 (defun org-delete-all (elts list)
12948 "Remove all elements in ELTS from LIST."
12949 (while elts
12950 (setq list (delete (pop elts) list)))
12951 list)
12953 (defun org-back-over-empty-lines ()
12954 "Move backwards over witespace, to the beginning of the first empty line.
12955 Returns the number of empty lines passed."
12956 (let ((pos (point)))
12957 (skip-chars-backward " \t\n\r")
12958 (beginning-of-line 2)
12959 (goto-char (min (point) pos))
12960 (count-lines (point) pos)))
12962 (defun org-skip-whitespace ()
12963 (skip-chars-forward " \t\n\r"))
12965 (defun org-point-in-group (point group &optional context)
12966 "Check if POINT is in match-group GROUP.
12967 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
12968 match. If the match group does ot exist or point is not inside it,
12969 return nil."
12970 (and (match-beginning group)
12971 (>= point (match-beginning group))
12972 (<= point (match-end group))
12973 (if context
12974 (list context (match-beginning group) (match-end group))
12975 t)))
12977 (defun org-switch-to-buffer-other-window (&rest args)
12978 "Switch to buffer in a second window on the current frame.
12979 In particular, do not allow pop-up frames."
12980 (let (pop-up-frames special-display-buffer-names special-display-regexps
12981 special-display-function)
12982 (apply 'switch-to-buffer-other-window args)))
12984 (defun org-combine-plists (&rest plists)
12985 "Create a single property list from all plists in PLISTS.
12986 The process starts by copying the first list, and then setting properties
12987 from the other lists. Settings in the last list are the most significant
12988 ones and overrule settings in the other lists."
12989 (let ((rtn (copy-sequence (pop plists)))
12990 p v ls)
12991 (while plists
12992 (setq ls (pop plists))
12993 (while ls
12994 (setq p (pop ls) v (pop ls))
12995 (setq rtn (plist-put rtn p v))))
12996 rtn))
12998 (defun org-move-line-down (arg)
12999 "Move the current line down. With prefix argument, move it past ARG lines."
13000 (interactive "p")
13001 (let ((col (current-column))
13002 beg end pos)
13003 (beginning-of-line 1) (setq beg (point))
13004 (beginning-of-line 2) (setq end (point))
13005 (beginning-of-line (+ 1 arg))
13006 (setq pos (move-marker (make-marker) (point)))
13007 (insert (delete-and-extract-region beg end))
13008 (goto-char pos)
13009 (move-to-column col)))
13011 (defun org-move-line-up (arg)
13012 "Move the current line up. With prefix argument, move it past ARG lines."
13013 (interactive "p")
13014 (let ((col (current-column))
13015 beg end pos)
13016 (beginning-of-line 1) (setq beg (point))
13017 (beginning-of-line 2) (setq end (point))
13018 (beginning-of-line (- arg))
13019 (setq pos (move-marker (make-marker) (point)))
13020 (insert (delete-and-extract-region beg end))
13021 (goto-char pos)
13022 (move-to-column col)))
13024 (defun org-replace-escapes (string table)
13025 "Replace %-escapes in STRING with values in TABLE.
13026 TABLE is an association list with keys like \"%a\" and string values.
13027 The sequences in STRING may contain normal field width and padding information,
13028 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13029 so values can contain further %-escapes if they are define later in TABLE."
13030 (let ((case-fold-search nil)
13031 e re rpl)
13032 (while (setq e (pop table))
13033 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13034 (while (string-match re string)
13035 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13036 (cdr e)))
13037 (setq string (replace-match rpl t t string))))
13038 string))
13041 (defun org-sublist (list start end)
13042 "Return a section of LIST, from START to END.
13043 Counting starts at 1."
13044 (let (rtn (c start))
13045 (setq list (nthcdr (1- start) list))
13046 (while (and list (<= c end))
13047 (push (pop list) rtn)
13048 (setq c (1+ c)))
13049 (nreverse rtn)))
13051 (defun org-find-base-buffer-visiting (file)
13052 "Like `find-buffer-visiting' but alway return the base buffer and
13053 not an indirect buffer."
13054 (let ((buf (find-buffer-visiting file)))
13055 (if buf
13056 (or (buffer-base-buffer buf) buf)
13057 nil)))
13059 (defun org-image-file-name-regexp ()
13060 "Return regexp matching the file names of images."
13061 (if (fboundp 'image-file-name-regexp)
13062 (image-file-name-regexp)
13063 (let ((image-file-name-extensions
13064 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13065 "xbm" "xpm" "pbm" "pgm" "ppm")))
13066 (concat "\\."
13067 (regexp-opt (nconc (mapcar 'upcase
13068 image-file-name-extensions)
13069 image-file-name-extensions)
13071 "\\'"))))
13073 (defun org-file-image-p (file)
13074 "Return non-nil if FILE is an image."
13075 (save-match-data
13076 (string-match (org-image-file-name-regexp) file)))
13078 ;;; Paragraph filling stuff.
13079 ;; We want this to be just right, so use the full arsenal.
13081 (defun org-indent-line-function ()
13082 "Indent line like previous, but further if previous was headline or item."
13083 (interactive)
13084 (let* ((pos (point))
13085 (itemp (org-at-item-p))
13086 column bpos bcol tpos tcol bullet btype bullet-type)
13087 ;; Find the previous relevant line
13088 (beginning-of-line 1)
13089 (cond
13090 ((looking-at "#") (setq column 0))
13091 ((looking-at "\\*+ ") (setq column 0))
13093 (beginning-of-line 0)
13094 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13095 (beginning-of-line 0))
13096 (cond
13097 ((looking-at "\\*+[ \t]+")
13098 (goto-char (match-end 0))
13099 (setq column (current-column)))
13100 ((org-in-item-p)
13101 (org-beginning-of-item)
13102 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13103 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
13104 (setq bpos (match-beginning 1) tpos (match-end 0)
13105 bcol (progn (goto-char bpos) (current-column))
13106 tcol (progn (goto-char tpos) (current-column))
13107 bullet (match-string 1)
13108 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13109 (if (not itemp)
13110 (setq column tcol)
13111 (goto-char pos)
13112 (beginning-of-line 1)
13113 (if (looking-at "\\S-")
13114 (progn
13115 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13116 (setq bullet (match-string 1)
13117 btype (if (string-match "[0-9]" bullet) "n" bullet))
13118 (setq column (if (equal btype bullet-type) bcol tcol)))
13119 (setq column (org-get-indentation)))))
13120 (t (setq column (org-get-indentation))))))
13121 (goto-char pos)
13122 (if (<= (current-column) (current-indentation))
13123 (indent-line-to column)
13124 (save-excursion (indent-line-to column)))
13125 (setq column (current-column))
13126 (beginning-of-line 1)
13127 (if (looking-at
13128 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13129 (replace-match (concat "\\1" (format org-property-format
13130 (match-string 2) (match-string 3)))
13131 t nil))
13132 (move-to-column column)))
13134 (defun org-set-autofill-regexps ()
13135 (interactive)
13136 ;; In the paragraph separator we include headlines, because filling
13137 ;; text in a line directly attached to a headline would otherwise
13138 ;; fill the headline as well.
13139 (org-set-local 'comment-start-skip "^#+[ \t]*")
13140 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13141 ;; The paragraph starter includes hand-formatted lists.
13142 (org-set-local 'paragraph-start
13143 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13144 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13145 ;; But only if the user has not turned off tables or fixed-width regions
13146 (org-set-local
13147 'auto-fill-inhibit-regexp
13148 (concat "\\*+ \\|#\\+"
13149 "\\|[ \t]*" org-keyword-time-regexp
13150 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13151 (concat
13152 "\\|[ \t]*["
13153 (if org-enable-table-editor "|" "")
13154 (if org-enable-fixed-width-editor ":" "")
13155 "]"))))
13156 ;; We use our own fill-paragraph function, to make sure that tables
13157 ;; and fixed-width regions are not wrapped. That function will pass
13158 ;; through to `fill-paragraph' when appropriate.
13159 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13160 ; Adaptive filling: To get full control, first make sure that
13161 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13162 (org-set-local 'adaptive-fill-regexp "\000")
13163 (org-set-local 'adaptive-fill-function
13164 'org-adaptive-fill-function)
13165 (org-set-local
13166 'align-mode-rules-list
13167 '((org-in-buffer-settings
13168 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13169 (modes . '(org-mode))))))
13171 (defun org-fill-paragraph (&optional justify)
13172 "Re-align a table, pass through to fill-paragraph if no table."
13173 (let ((table-p (org-at-table-p))
13174 (table.el-p (org-at-table.el-p)))
13175 (cond ((and (equal (char-after (point-at-bol)) ?*)
13176 (save-excursion (goto-char (point-at-bol))
13177 (looking-at outline-regexp)))
13178 t) ; skip headlines
13179 (table.el-p t) ; skip table.el tables
13180 (table-p (org-table-align) t) ; align org-mode tables
13181 (t nil)))) ; call paragraph-fill
13183 ;; For reference, this is the default value of adaptive-fill-regexp
13184 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13186 (defun org-adaptive-fill-function ()
13187 "Return a fill prefix for org-mode files.
13188 In particular, this makes sure hanging paragraphs for hand-formatted lists
13189 work correctly."
13190 (cond ((looking-at "#[ \t]+")
13191 (match-string 0))
13192 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13193 (save-excursion
13194 (goto-char (match-end 0))
13195 (make-string (current-column) ?\ )))
13196 (t nil)))
13198 ;;; Other stuff.
13200 (defun org-toggle-fixed-width-section (arg)
13201 "Toggle the fixed-width export.
13202 If there is no active region, the QUOTE keyword at the current headline is
13203 inserted or removed. When present, it causes the text between this headline
13204 and the next to be exported as fixed-width text, and unmodified.
13205 If there is an active region, this command adds or removes a colon as the
13206 first character of this line. If the first character of a line is a colon,
13207 this line is also exported in fixed-width font."
13208 (interactive "P")
13209 (let* ((cc 0)
13210 (regionp (org-region-active-p))
13211 (beg (if regionp (region-beginning) (point)))
13212 (end (if regionp (region-end)))
13213 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13214 (case-fold-search nil)
13215 (re "[ \t]*\\(:\\)")
13216 off)
13217 (if regionp
13218 (save-excursion
13219 (goto-char beg)
13220 (setq cc (current-column))
13221 (beginning-of-line 1)
13222 (setq off (looking-at re))
13223 (while (> nlines 0)
13224 (setq nlines (1- nlines))
13225 (beginning-of-line 1)
13226 (cond
13227 (arg
13228 (move-to-column cc t)
13229 (insert ":\n")
13230 (forward-line -1))
13231 ((and off (looking-at re))
13232 (replace-match "" t t nil 1))
13233 ((not off) (move-to-column cc t) (insert ":")))
13234 (forward-line 1)))
13235 (save-excursion
13236 (org-back-to-heading)
13237 (if (looking-at (concat outline-regexp
13238 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13239 (replace-match "" t t nil 1)
13240 (if (looking-at outline-regexp)
13241 (progn
13242 (goto-char (match-end 0))
13243 (insert org-quote-string " "))))))))
13245 ;;;; Functions extending outline functionality
13247 (defun org-beginning-of-line (&optional arg)
13248 "Go to the beginning of the current line. If that is invisible, continue
13249 to a visible line beginning. This makes the function of C-a more intuitive.
13250 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13251 first attempt, and only move to after the tags when the cursor is already
13252 beyond the end of the headline."
13253 (interactive "P")
13254 (let ((pos (point)))
13255 (beginning-of-line 1)
13256 (if (bobp)
13258 (backward-char 1)
13259 (if (org-invisible-p)
13260 (while (and (not (bobp)) (org-invisible-p))
13261 (backward-char 1)
13262 (beginning-of-line 1))
13263 (forward-char 1)))
13264 (when org-special-ctrl-a/e
13265 (cond
13266 ((and (looking-at org-todo-line-regexp)
13267 (= (char-after (match-end 1)) ?\ ))
13268 (goto-char
13269 (if (eq org-special-ctrl-a/e t)
13270 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13271 ((= pos (point)) (match-beginning 3))
13272 (t (point)))
13273 (cond ((> pos (point)) (point))
13274 ((not (eq last-command this-command)) (point))
13275 (t (match-beginning 3))))))
13276 ((org-at-item-p)
13277 (goto-char
13278 (if (eq org-special-ctrl-a/e t)
13279 (cond ((> pos (match-end 4)) (match-end 4))
13280 ((= pos (point)) (match-end 4))
13281 (t (point)))
13282 (cond ((> pos (point)) (point))
13283 ((not (eq last-command this-command)) (point))
13284 (t (match-end 4))))))))))
13286 (defun org-end-of-line (&optional arg)
13287 "Go to the end of the line.
13288 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13289 first attempt, and only move to after the tags when the cursor is already
13290 beyond the end of the headline."
13291 (interactive "P")
13292 (if (or (not org-special-ctrl-a/e)
13293 (not (org-on-heading-p)))
13294 (end-of-line arg)
13295 (let ((pos (point)))
13296 (beginning-of-line 1)
13297 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13298 (if (eq org-special-ctrl-a/e t)
13299 (if (or (< pos (match-beginning 1))
13300 (= pos (match-end 0)))
13301 (goto-char (match-beginning 1))
13302 (goto-char (match-end 0)))
13303 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13304 (goto-char (match-end 0))
13305 (goto-char (match-beginning 1))))
13306 (end-of-line arg)))))
13308 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13309 (define-key org-mode-map "\C-e" 'org-end-of-line)
13311 (defun org-kill-line (&optional arg)
13312 "Kill line, to tags or end of line."
13313 (interactive "P")
13314 (cond
13315 ((or (not org-special-ctrl-k)
13316 (bolp)
13317 (not (org-on-heading-p)))
13318 (call-interactively 'kill-line))
13319 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13320 (kill-region (point) (match-beginning 1))
13321 (org-set-tags nil t))
13322 (t (kill-region (point) (point-at-eol)))))
13324 (define-key org-mode-map "\C-k" 'org-kill-line)
13326 (defun org-invisible-p ()
13327 "Check if point is at a character currently not visible."
13328 ;; Early versions of noutline don't have `outline-invisible-p'.
13329 (if (fboundp 'outline-invisible-p)
13330 (outline-invisible-p)
13331 (get-char-property (point) 'invisible)))
13333 (defun org-invisible-p2 ()
13334 "Check if point is at a character currently not visible."
13335 (save-excursion
13336 (if (and (eolp) (not (bobp))) (backward-char 1))
13337 ;; Early versions of noutline don't have `outline-invisible-p'.
13338 (if (fboundp 'outline-invisible-p)
13339 (outline-invisible-p)
13340 (get-char-property (point) 'invisible))))
13342 (defalias 'org-back-to-heading 'outline-back-to-heading)
13343 (defalias 'org-on-heading-p 'outline-on-heading-p)
13344 (defalias 'org-at-heading-p 'outline-on-heading-p)
13345 (defun org-at-heading-or-item-p ()
13346 (or (org-on-heading-p) (org-at-item-p)))
13348 (defun org-on-target-p ()
13349 (or (org-in-regexp org-radio-target-regexp)
13350 (org-in-regexp org-target-regexp)))
13352 (defun org-up-heading-all (arg)
13353 "Move to the heading line of which the present line is a subheading.
13354 This function considers both visible and invisible heading lines.
13355 With argument, move up ARG levels."
13356 (if (fboundp 'outline-up-heading-all)
13357 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13358 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13360 (defun org-up-heading-safe ()
13361 "Move to the heading line of which the present line is a subheading.
13362 This version will not throw an error. It will return the level of the
13363 headline found, or nil if no higher level is found."
13364 (let ((pos (point)) start-level level
13365 (re (concat "^" outline-regexp)))
13366 (catch 'exit
13367 (outline-back-to-heading t)
13368 (setq start-level (funcall outline-level))
13369 (if (equal start-level 1) (throw 'exit nil))
13370 (while (re-search-backward re nil t)
13371 (setq level (funcall outline-level))
13372 (if (< level start-level) (throw 'exit level)))
13373 nil)))
13375 (defun org-first-sibling-p ()
13376 "Is this heading the first child of its parents?"
13377 (interactive)
13378 (let ((re (concat "^" outline-regexp))
13379 level l)
13380 (unless (org-at-heading-p t)
13381 (error "Not at a heading"))
13382 (setq level (funcall outline-level))
13383 (save-excursion
13384 (if (not (re-search-backward re nil t))
13386 (setq l (funcall outline-level))
13387 (< l level)))))
13389 (defun org-goto-sibling (&optional previous)
13390 "Goto the next sibling, even if it is invisible.
13391 When PREVIOUS is set, go to the previous sibling instead. Returns t
13392 when a sibling was found. When none is found, return nil and don't
13393 move point."
13394 (let ((fun (if previous 're-search-backward 're-search-forward))
13395 (pos (point))
13396 (re (concat "^" outline-regexp))
13397 level l)
13398 (when (condition-case nil (org-back-to-heading t) (error nil))
13399 (setq level (funcall outline-level))
13400 (catch 'exit
13401 (or previous (forward-char 1))
13402 (while (funcall fun re nil t)
13403 (setq l (funcall outline-level))
13404 (when (< l level) (goto-char pos) (throw 'exit nil))
13405 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13406 (goto-char pos)
13407 nil))))
13409 (defun org-show-siblings ()
13410 "Show all siblings of the current headline."
13411 (save-excursion
13412 (while (org-goto-sibling) (org-flag-heading nil)))
13413 (save-excursion
13414 (while (org-goto-sibling 'previous)
13415 (org-flag-heading nil))))
13417 (defun org-show-hidden-entry ()
13418 "Show an entry where even the heading is hidden."
13419 (save-excursion
13420 (org-show-entry)))
13422 (defun org-flag-heading (flag &optional entry)
13423 "Flag the current heading. FLAG non-nil means make invisible.
13424 When ENTRY is non-nil, show the entire entry."
13425 (save-excursion
13426 (org-back-to-heading t)
13427 ;; Check if we should show the entire entry
13428 (if entry
13429 (progn
13430 (org-show-entry)
13431 (save-excursion
13432 (and (outline-next-heading)
13433 (org-flag-heading nil))))
13434 (outline-flag-region (max (point-min) (1- (point)))
13435 (save-excursion (outline-end-of-heading) (point))
13436 flag))))
13438 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13439 ;; This is an exact copy of the original function, but it uses
13440 ;; `org-back-to-heading', to make it work also in invisible
13441 ;; trees. And is uses an invisible-OK argument.
13442 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13443 (org-back-to-heading invisible-OK)
13444 (let ((first t)
13445 (level (funcall outline-level)))
13446 (while (and (not (eobp))
13447 (or first (> (funcall outline-level) level)))
13448 (setq first nil)
13449 (outline-next-heading))
13450 (unless to-heading
13451 (if (memq (preceding-char) '(?\n ?\^M))
13452 (progn
13453 ;; Go to end of line before heading
13454 (forward-char -1)
13455 (if (memq (preceding-char) '(?\n ?\^M))
13456 ;; leave blank line before heading
13457 (forward-char -1))))))
13458 (point))
13460 (defun org-show-subtree ()
13461 "Show everything after this heading at deeper levels."
13462 (outline-flag-region
13463 (point)
13464 (save-excursion
13465 (outline-end-of-subtree) (outline-next-heading) (point))
13466 nil))
13468 (defun org-show-entry ()
13469 "Show the body directly following this heading.
13470 Show the heading too, if it is currently invisible."
13471 (interactive)
13472 (save-excursion
13473 (condition-case nil
13474 (progn
13475 (org-back-to-heading t)
13476 (outline-flag-region
13477 (max (point-min) (1- (point)))
13478 (save-excursion
13479 (re-search-forward
13480 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13481 (or (match-beginning 1) (point-max)))
13482 nil))
13483 (error nil))))
13485 (defun org-make-options-regexp (kwds)
13486 "Make a regular expression for keyword lines."
13487 (concat
13489 "#?[ \t]*\\+\\("
13490 (mapconcat 'regexp-quote kwds "\\|")
13491 "\\):[ \t]*"
13492 "\\(.+\\)"))
13494 ;; Make isearch reveal the necessary context
13495 (defun org-isearch-end ()
13496 "Reveal context after isearch exits."
13497 (when isearch-success ; only if search was successful
13498 (if (featurep 'xemacs)
13499 ;; Under XEmacs, the hook is run in the correct place,
13500 ;; we directly show the context.
13501 (org-show-context 'isearch)
13502 ;; In Emacs the hook runs *before* restoring the overlays.
13503 ;; So we have to use a one-time post-command-hook to do this.
13504 ;; (Emacs 22 has a special variable, see function `org-mode')
13505 (unless (and (boundp 'isearch-mode-end-hook-quit)
13506 isearch-mode-end-hook-quit)
13507 ;; Only when the isearch was not quitted.
13508 (org-add-hook 'post-command-hook 'org-isearch-post-command
13509 'append 'local)))))
13511 (defun org-isearch-post-command ()
13512 "Remove self from hook, and show context."
13513 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13514 (org-show-context 'isearch))
13517 ;;;; Integration with and fixes for other packages
13519 ;;; Imenu support
13521 (defvar org-imenu-markers nil
13522 "All markers currently used by Imenu.")
13523 (make-variable-buffer-local 'org-imenu-markers)
13525 (defun org-imenu-new-marker (&optional pos)
13526 "Return a new marker for use by Imenu, and remember the marker."
13527 (let ((m (make-marker)))
13528 (move-marker m (or pos (point)))
13529 (push m org-imenu-markers)
13532 (defun org-imenu-get-tree ()
13533 "Produce the index for Imenu."
13534 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
13535 (setq org-imenu-markers nil)
13536 (let* ((n org-imenu-depth)
13537 (re (concat "^" outline-regexp))
13538 (subs (make-vector (1+ n) nil))
13539 (last-level 0)
13540 m tree level head)
13541 (save-excursion
13542 (save-restriction
13543 (widen)
13544 (goto-char (point-max))
13545 (while (re-search-backward re nil t)
13546 (setq level (org-reduced-level (funcall outline-level)))
13547 (when (<= level n)
13548 (looking-at org-complex-heading-regexp)
13549 (setq head (org-match-string-no-properties 4)
13550 m (org-imenu-new-marker))
13551 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
13552 (if (>= level last-level)
13553 (push (cons head m) (aref subs level))
13554 (push (cons head (aref subs (1+ level))) (aref subs level))
13555 (loop for i from (1+ level) to n do (aset subs i nil)))
13556 (setq last-level level)))))
13557 (aref subs 1)))
13559 (eval-after-load "imenu"
13560 '(progn
13561 (add-hook 'imenu-after-jump-hook
13562 (lambda () (org-show-context 'org-goto)))))
13564 ;; Speedbar support
13566 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
13567 "Overlay marking the agenda restriction line in speedbar.")
13568 (org-overlay-put org-speedbar-restriction-lock-overlay
13569 'face 'org-agenda-restriction-lock)
13570 (org-overlay-put org-speedbar-restriction-lock-overlay
13571 'help-echo "Agendas are currently limited to this item.")
13572 (org-detach-overlay org-speedbar-restriction-lock-overlay)
13574 (defun org-speedbar-set-agenda-restriction ()
13575 "Restrict future agenda commands to the location at point in speedbar.
13576 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
13577 (interactive)
13578 (require 'org-agenda)
13579 (let (p m tp np dir txt w)
13580 (cond
13581 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13582 'org-imenu t))
13583 (setq m (get-text-property p 'org-imenu-marker))
13584 (save-excursion
13585 (save-restriction
13586 (set-buffer (marker-buffer m))
13587 (goto-char m)
13588 (org-agenda-set-restriction-lock 'subtree))))
13589 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13590 'speedbar-function 'speedbar-find-file))
13591 (setq tp (previous-single-property-change
13592 (1+ p) 'speedbar-function)
13593 np (next-single-property-change
13594 tp 'speedbar-function)
13595 dir (speedbar-line-directory)
13596 txt (buffer-substring-no-properties (or tp (point-min))
13597 (or np (point-max))))
13598 (save-excursion
13599 (save-restriction
13600 (set-buffer (find-file-noselect
13601 (let ((default-directory dir))
13602 (expand-file-name txt))))
13603 (unless (org-mode-p)
13604 (error "Cannot restrict to non-Org-mode file"))
13605 (org-agenda-set-restriction-lock 'file))))
13606 (t (error "Don't know how to restrict Org-mode's agenda")))
13607 (org-move-overlay org-speedbar-restriction-lock-overlay
13608 (point-at-bol) (point-at-eol))
13609 (setq current-prefix-arg nil)
13610 (org-agenda-maybe-redo)))
13612 (eval-after-load "speedbar"
13613 '(progn
13614 (speedbar-add-supported-extension ".org")
13615 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
13616 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
13617 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
13618 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13619 (add-hook 'speedbar-visiting-tag-hook
13620 (lambda () (org-show-context 'org-goto)))))
13623 ;;; Fixes and Hacks for problems with other packages
13625 ;; Make flyspell not check words in links, to not mess up our keymap
13626 (defun org-mode-flyspell-verify ()
13627 "Don't let flyspell put overlays at active buttons."
13628 (not (get-text-property (point) 'keymap)))
13630 ;; Make `bookmark-jump' show the jump location if it was hidden.
13631 (eval-after-load "bookmark"
13632 '(if (boundp 'bookmark-after-jump-hook)
13633 ;; We can use the hook
13634 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13635 ;; Hook not available, use advice
13636 (defadvice bookmark-jump (after org-make-visible activate)
13637 "Make the position visible."
13638 (org-bookmark-jump-unhide))))
13640 (defun org-bookmark-jump-unhide ()
13641 "Unhide the current position, to show the bookmark location."
13642 (and (org-mode-p)
13643 (or (org-invisible-p)
13644 (save-excursion (goto-char (max (point-min) (1- (point))))
13645 (org-invisible-p)))
13646 (org-show-context 'bookmark-jump)))
13648 ;; Make session.el ignore our circular variable
13649 (eval-after-load "session"
13650 '(add-to-list 'session-globals-exclude 'org-mark-ring))
13652 ;;;; Experimental code
13654 (defun org-closed-in-range ()
13655 "Sparse tree of items closed in a certain time range.
13656 Still experimental, may disappear in the future."
13657 (interactive)
13658 ;; Get the time interval from the user.
13659 (let* ((time1 (time-to-seconds
13660 (org-read-date nil 'to-time nil "Starting date: ")))
13661 (time2 (time-to-seconds
13662 (org-read-date nil 'to-time nil "End date:")))
13663 ;; callback function
13664 (callback (lambda ()
13665 (let ((time
13666 (time-to-seconds
13667 (apply 'encode-time
13668 (org-parse-time-string
13669 (match-string 1))))))
13670 ;; check if time in interval
13671 (and (>= time time1) (<= time time2))))))
13672 ;; make tree, check each match with the callback
13673 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
13676 ;;;; Finish up
13678 (provide 'org)
13680 (run-hooks 'org-load-hook)
13682 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13683 ;;; org.el ends here