Release 6.02b.
[org-mode.git] / lisp / org.el
blob0c1bf201f478df036852a19460071e7b11cacdd7
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.02b
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.02b"
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 (if (featurep 'xemacs) -79 -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 ("+" ,(if (featurep 'xemacs) 'org-table '(:strike-through t))
2133 "<del>" "</del>")
2135 "Special syntax for emphasized text.
2136 Text starting and ending with a special character will be emphasized, for
2137 example *bold*, _underlined_ and /italic/. This variable sets the marker
2138 characters, the face to be used by font-lock for highlighting in Org-mode
2139 Emacs buffers, and the HTML tags to be used for this.
2140 Use customize to modify this, or restart Emacs after changing it."
2141 :group 'org-font-lock
2142 :set 'org-set-emph-re
2143 :type '(repeat
2144 (list
2145 (string :tag "Marker character")
2146 (choice
2147 (face :tag "Font-lock-face")
2148 (plist :tag "Face property list"))
2149 (string :tag "HTML start tag")
2150 (string :tag "HTML end tag")
2151 (option (const verbatim)))))
2153 ;;; Miscellaneous options
2155 (defgroup org-completion nil
2156 "Completion in Org-mode."
2157 :tag "Org Completion"
2158 :group 'org)
2160 (defcustom org-completion-fallback-command 'hippie-expand
2161 "The expansion command called by \\[org-complete] in normal context.
2162 Normal means, no org-mode-specific context."
2163 :group 'org-completion
2164 :type 'function)
2166 ;;; Functions and variables from ther packages
2167 ;; Declared here to avoid compiler warnings
2169 ;; XEmacs only
2170 (defvar outline-mode-menu-heading)
2171 (defvar outline-mode-menu-show)
2172 (defvar outline-mode-menu-hide)
2173 (defvar zmacs-regions) ; XEmacs regions
2175 ;; Emacs only
2176 (defvar mark-active)
2178 ;; Various packages
2179 (declare-function calendar-absolute-from-iso "cal-iso" (&optional date))
2180 (declare-function calendar-forward-day "cal-move" (arg))
2181 (declare-function calendar-goto-date "cal-move" (date))
2182 (declare-function calendar-goto-today "cal-move" ())
2183 (declare-function calendar-iso-from-absolute "cal-iso" (&optional date))
2184 (defvar calc-embedded-close-formula)
2185 (defvar calc-embedded-open-formula)
2186 (declare-function cdlatex-tab "ext:cdlatex" ())
2187 (declare-function dired-get-filename "dired" (&optional localp no-error-if-not-filep))
2188 (defvar font-lock-unfontify-region-function)
2189 (declare-function iswitchb-mode "iswitchb" (&optional arg))
2190 (declare-function iswitchb-read-buffer (prompt &optional default require-match start matches-set))
2191 (defvar iswitchb-temp-buflist)
2192 (declare-function org-gnus-follow-link "org-gnus" (&optional group article))
2193 (declare-function org-agenda-skip "org-agenda" ())
2194 (declare-function org-format-agenda-item "org-agenda"
2195 (extra txt &optional category tags dotime noprefix remove-re))
2196 (declare-function org-agenda-new-marker "org-agenda" (&optional pos))
2197 (declare-function org-agenda-change-all-lines "org-agenda"
2198 (newhead hdmarker &optional fixface))
2199 (declare-function org-agenda-set-restriction-lock "org-agenda" (&optional type))
2200 (declare-function org-agenda-maybe-redo "org-agenda" ())
2201 (declare-function parse-time-string "parse-time" (string))
2202 (declare-function remember "remember" (&optional initial))
2203 (declare-function remember-buffer-desc "remember" ())
2204 (declare-function remember-finalize "remember" ())
2205 (defvar remember-save-after-remembering)
2206 (defvar remember-data-file)
2207 (defvar remember-register)
2208 (defvar remember-buffer)
2209 (defvar remember-handler-functions)
2210 (defvar remember-annotation-functions)
2211 (defvar texmathp-why)
2212 (declare-function speedbar-line-directory "speedbar" (&optional depth))
2213 (declare-function table--at-cell-p "table" (position &optional object at-column))
2215 (defvar w3m-current-url)
2216 (defvar w3m-current-title)
2218 (defvar org-latex-regexps)
2220 ;;; Autoload and prepare some org modules
2222 ;; Some table stuff that needs to be defined here, because it is used
2223 ;; by the functions setting up org-mode or checking for table context.
2225 (defconst org-table-any-line-regexp "^[ \t]*\\(|\\|\\+-[-+]\\)"
2226 "Detects an org-type or table-type table.")
2227 (defconst org-table-line-regexp "^[ \t]*|"
2228 "Detects an org-type table line.")
2229 (defconst org-table-dataline-regexp "^[ \t]*|[^-]"
2230 "Detects an org-type table line.")
2231 (defconst org-table-hline-regexp "^[ \t]*|-"
2232 "Detects an org-type table hline.")
2233 (defconst org-table1-hline-regexp "^[ \t]*\\+-[-+]"
2234 "Detects a table-type table hline.")
2235 (defconst org-table-any-border-regexp "^[ \t]*[^|+ \t]"
2236 "Searching from within a table (any type) this finds the first line
2237 outside the table.")
2239 ;; Autoload the functions in org-table.el that are needed by functions here.
2241 (eval-and-compile
2242 (org-autoload "org-table"
2243 '(org-table-align org-table-begin org-table-blank-field
2244 org-table-convert org-table-convert-region org-table-copy-down
2245 org-table-copy-region org-table-create
2246 org-table-create-or-convert-from-region
2247 org-table-create-with-table.el org-table-current-dline
2248 org-table-cut-region org-table-delete-column org-table-edit-field
2249 org-table-edit-formulas org-table-end org-table-eval-formula
2250 org-table-export org-table-field-info
2251 org-table-get-stored-formulas org-table-goto-column
2252 org-table-hline-and-move org-table-import org-table-insert-column
2253 org-table-insert-hline org-table-insert-row org-table-iterate
2254 org-table-justify-field-maybe org-table-kill-row
2255 org-table-maybe-eval-formula org-table-maybe-recalculate-line
2256 org-table-move-column org-table-move-column-left
2257 org-table-move-column-right org-table-move-row
2258 org-table-move-row-down org-table-move-row-up
2259 org-table-next-field org-table-next-row org-table-paste-rectangle
2260 org-table-previous-field org-table-recalculate
2261 org-table-rotate-recalc-marks org-table-sort-lines org-table-sum
2262 org-table-toggle-coordinate-overlays
2263 org-table-toggle-formula-debugger org-table-wrap-region
2264 orgtbl-mode turn-on-orgtbl)))
2266 (defun org-at-table-p (&optional table-type)
2267 "Return t if the cursor is inside an org-type table.
2268 If TABLE-TYPE is non-nil, also check for table.el-type tables."
2269 (if org-enable-table-editor
2270 (save-excursion
2271 (beginning-of-line 1)
2272 (looking-at (if table-type org-table-any-line-regexp
2273 org-table-line-regexp)))
2274 nil))
2275 (defsubst org-table-p () (org-at-table-p))
2277 (defun org-at-table.el-p ()
2278 "Return t if and only if we are at a table.el table."
2279 (and (org-at-table-p 'any)
2280 (save-excursion
2281 (goto-char (org-table-begin 'any))
2282 (looking-at org-table1-hline-regexp))))
2283 (defun org-table-recognize-table.el ()
2284 "If there is a table.el table nearby, recognize it and move into it."
2285 (if org-table-tab-recognizes-table.el
2286 (if (org-at-table.el-p)
2287 (progn
2288 (beginning-of-line 1)
2289 (if (looking-at org-table-dataline-regexp)
2291 (if (looking-at org-table1-hline-regexp)
2292 (progn
2293 (beginning-of-line 2)
2294 (if (looking-at org-table-any-border-regexp)
2295 (beginning-of-line -1)))))
2296 (if (re-search-forward "|" (org-table-end t) t)
2297 (progn
2298 (require 'table)
2299 (if (table--at-cell-p (point))
2301 (message "recognizing table.el table...")
2302 (table-recognize-table)
2303 (message "recognizing table.el table...done")))
2304 (error "This should not happen..."))
2306 nil)
2307 nil))
2309 (defun org-at-table-hline-p ()
2310 "Return t if the cursor is inside a hline in a table."
2311 (if org-enable-table-editor
2312 (save-excursion
2313 (beginning-of-line 1)
2314 (looking-at org-table-hline-regexp))
2315 nil))
2317 (defvar org-table-clean-did-remove-column nil)
2319 (defun org-table-map-tables (function)
2320 "Apply FUNCTION to the start of all tables in the buffer."
2321 (save-excursion
2322 (save-restriction
2323 (widen)
2324 (goto-char (point-min))
2325 (while (re-search-forward org-table-any-line-regexp nil t)
2326 (message "Mapping tables: %d%%" (/ (* 100.0 (point)) (buffer-size)))
2327 (beginning-of-line 1)
2328 (if (looking-at org-table-line-regexp)
2329 (save-excursion (funcall function)))
2330 (re-search-forward org-table-any-border-regexp nil 1))))
2331 (message "Mapping tables: done"))
2333 ;; Declare and autoload functions from org-exp.el
2335 (declare-function org-default-export-plist "org-exp")
2336 (declare-function org-infile-export-plist "org-exp")
2337 (declare-function org-get-current-options "org-exp")
2338 (eval-and-compile
2339 (org-autoload "org-exp"
2340 '(org-export org-export-as-ascii org-export-visible
2341 org-insert-export-options-template org-export-as-html-and-open
2342 org-export-as-html-batch org-export-as-html-to-buffer
2343 org-replace-region-by-html org-export-region-as-html
2344 org-export-as-html org-export-icalendar-this-file
2345 org-export-icalendar-all-agenda-files
2346 org-export-icalendar-combine-agenda-files org-export-as-xoxo)))
2348 ;; Declare and autoload functions from org-exp.el
2350 (eval-and-compile
2351 (org-autoload "org-exp"
2352 '(org-agenda org-agenda-list org-search-view
2353 org-todo-list org-tags-view org-agenda-list-stuck-projects
2354 org-diary org-agenda-to-appt)))
2356 ;; Autoload org-remember
2358 (eval-and-compile
2359 (org-autoload "org-remember"
2360 '(org-remember-insinuate org-remember-annotation
2361 org-remember-apply-template org-remember org-remember-handler)))
2363 ;; Autoload org-clock.el
2365 (defvar org-clock-marker (make-marker)
2366 "Marker recording the last clock-in.")
2368 (eval-and-compile
2369 (org-autoload
2370 "org-clock"
2371 '(org-clock-in org-clock-out org-clock-cancel
2372 org-clock-goto org-clock-sum org-clock-display
2373 org-remove-clock-overlays org-clock-report
2374 org-clocktable-shift org-dblock-write:clocktable
2375 org-get-clocktable)))
2377 (defun org-clock-update-time-maybe ()
2378 "If this is a CLOCK line, update it and return t.
2379 Otherwise, return nil."
2380 (interactive)
2381 (save-excursion
2382 (beginning-of-line 1)
2383 (skip-chars-forward " \t")
2384 (when (looking-at org-clock-string)
2385 (let ((re (concat "[ \t]*" org-clock-string
2386 " *[[<]\\([^]>]+\\)[]>]-+[[<]\\([^]>]+\\)[]>]"
2387 "\\([ \t]*=>.*\\)?"))
2388 ts te h m s)
2389 (if (not (looking-at re))
2391 (and (match-end 3) (delete-region (match-beginning 3) (match-end 3)))
2392 (end-of-line 1)
2393 (setq ts (match-string 1)
2394 te (match-string 2))
2395 (setq s (- (time-to-seconds
2396 (apply 'encode-time (org-parse-time-string te)))
2397 (time-to-seconds
2398 (apply 'encode-time (org-parse-time-string ts))))
2399 h (floor (/ s 3600))
2400 s (- s (* 3600 h))
2401 m (floor (/ s 60))
2402 s (- s (* 60 s)))
2403 (insert " => " (format "%2d:%02d" h m))
2404 t)))))
2406 (defun org-check-running-clock ()
2407 "Check if the current buffer contains the running clock.
2408 If yes, offer to stop it and to save the buffer with the changes."
2409 (when (and (equal (marker-buffer org-clock-marker) (current-buffer))
2410 (y-or-n-p (format "Clock-out in buffer %s before killing it? "
2411 (buffer-name))))
2412 (org-clock-out)
2413 (when (y-or-n-p "Save changed buffer?")
2414 (save-buffer))))
2416 (defun org-clocktable-try-shift (dir n)
2417 "Check if this line starts a clock table, if yes, shift the time block."
2418 (when (org-match-line "#\\+BEGIN: clocktable\\>")
2419 (org-clocktable-shift dir n)))
2421 ;; Autoload archiving code
2422 ;; The stuff that is needed for cycling and tags has to be defined here.
2424 (defgroup org-archive nil
2425 "Options concerning archiving in Org-mode."
2426 :tag "Org Archive"
2427 :group 'org-structure)
2429 (defcustom org-archive-location "%s_archive::"
2430 "The location where subtrees should be archived.
2432 Otherwise, the value of this variable is a string, consisting of two
2433 parts, separated by a double-colon.
2435 The first part is a file name - when omitted, archiving happens in the same
2436 file. %s will be replaced by the current file name (without directory part).
2437 Archiving to a different file is useful to keep archived entries from
2438 contributing to the Org-mode Agenda.
2440 The part after the double colon is a headline. The archived entries will be
2441 filed under that headline. When omitted, the subtrees are simply filed away
2442 at the end of the file, as top-level entries.
2444 Here are a few examples:
2445 \"%s_archive::\"
2446 If the current file is Projects.org, archive in file
2447 Projects.org_archive, as top-level trees. This is the default.
2449 \"::* Archived Tasks\"
2450 Archive in the current file, under the top-level headline
2451 \"* Archived Tasks\".
2453 \"~/org/archive.org::\"
2454 Archive in file ~/org/archive.org (absolute path), as top-level trees.
2456 \"basement::** Finished Tasks\"
2457 Archive in file ./basement (relative path), as level 3 trees
2458 below the level 2 heading \"** Finished Tasks\".
2460 You may set this option on a per-file basis by adding to the buffer a
2461 line like
2463 #+ARCHIVE: basement::** Finished Tasks
2465 You may also define it locally for a subtree by setting an ARCHIVE property
2466 in the entry. If such a property is found in an entry, or anywhere up
2467 the hierarchy, it will be used."
2468 :group 'org-archive
2469 :type 'string)
2471 (defcustom org-archive-tag "ARCHIVE"
2472 "The tag that marks a subtree as archived.
2473 An archived subtree does not open during visibility cycling, and does
2474 not contribute to the agenda listings.
2475 After changing this, font-lock must be restarted in the relevant buffers to
2476 get the proper fontification."
2477 :group 'org-archive
2478 :group 'org-keywords
2479 :type 'string)
2481 (defcustom org-agenda-skip-archived-trees t
2482 "Non-nil means, the agenda will skip any items located in archived trees.
2483 An archived tree is a tree marked with the tag ARCHIVE."
2484 :group 'org-archive
2485 :group 'org-agenda-skip
2486 :type 'boolean)
2488 (defcustom org-cycle-open-archived-trees nil
2489 "Non-nil means, `org-cycle' will open archived trees.
2490 An archived tree is a tree marked with the tag ARCHIVE.
2491 When nil, archived trees will stay folded. You can still open them with
2492 normal outline commands like `show-all', but not with the cycling commands."
2493 :group 'org-archive
2494 :group 'org-cycle
2495 :type 'boolean)
2497 (defcustom org-sparse-tree-open-archived-trees nil
2498 "Non-nil means sparse tree construction shows matches in archived trees.
2499 When nil, matches in these trees are highlighted, but the trees are kept in
2500 collapsed state."
2501 :group 'org-archive
2502 :group 'org-sparse-trees
2503 :type 'boolean)
2505 (defun org-cycle-hide-archived-subtrees (state)
2506 "Re-hide all archived subtrees after a visibility state change."
2507 (when (and (not org-cycle-open-archived-trees)
2508 (not (memq state '(overview folded))))
2509 (save-excursion
2510 (let* ((globalp (memq state '(contents all)))
2511 (beg (if globalp (point-min) (point)))
2512 (end (if globalp (point-max) (org-end-of-subtree t))))
2513 (org-hide-archived-subtrees beg end)
2514 (goto-char beg)
2515 (if (looking-at (concat ".*:" org-archive-tag ":"))
2516 (message "%s" (substitute-command-keys
2517 "Subtree is archived and stays closed. Use \\[org-force-cycle-archived] to cycle it anyway.")))))))
2519 (defun org-force-cycle-archived ()
2520 "Cycle subtree even if it is archived."
2521 (interactive)
2522 (setq this-command 'org-cycle)
2523 (let ((org-cycle-open-archived-trees t))
2524 (call-interactively 'org-cycle)))
2526 (defun org-hide-archived-subtrees (beg end)
2527 "Re-hide all archived subtrees after a visibility state change."
2528 (save-excursion
2529 (let* ((re (concat ":" org-archive-tag ":")))
2530 (goto-char beg)
2531 (while (re-search-forward re end t)
2532 (and (org-on-heading-p) (hide-subtree))
2533 (org-end-of-subtree t)))))
2535 (defalias 'org-advertized-archive-subtree 'org-archive-subtree)
2537 (eval-and-compile
2538 (org-autoload "org-archive"
2539 '(org-add-archive-files org-archive-subtree
2540 org-archive-to-archive-sibling org-toggle-archive-tag)))
2542 ;; Autoload Column View Code
2544 (declare-function org-columns-number-to-string "org-colview")
2545 (declare-function org-columns-get-format-and-top-level "org-colview")
2546 (declare-function org-columns-compute "org-colview")
2548 (org-autoload (if (featurep 'xemacs) "org-colview-xemacs" "org-colview")
2549 '(org-columns-number-to-string org-columns-get-format-and-top-level
2550 org-columns-compute org-agenda-columns org-columns-remove-overlays
2551 org-columns org-insert-columns-dblock))
2553 ;;; Variables for pre-computed regular expressions, all buffer local
2555 (defvar org-drawer-regexp nil
2556 "Matches first line of a hidden block.")
2557 (make-variable-buffer-local 'org-drawer-regexp)
2558 (defvar org-todo-regexp nil
2559 "Matches any of the TODO state keywords.")
2560 (make-variable-buffer-local 'org-todo-regexp)
2561 (defvar org-not-done-regexp nil
2562 "Matches any of the TODO state keywords except the last one.")
2563 (make-variable-buffer-local 'org-not-done-regexp)
2564 (defvar org-todo-line-regexp nil
2565 "Matches a headline and puts TODO state into group 2 if present.")
2566 (make-variable-buffer-local 'org-todo-line-regexp)
2567 (defvar org-complex-heading-regexp nil
2568 "Matches a headline and puts everything into groups:
2569 group 1: the stars
2570 group 2: The todo keyword, maybe
2571 group 3: Priority cookie
2572 group 4: True headline
2573 group 5: Tags")
2574 (make-variable-buffer-local 'org-complex-heading-regexp)
2575 (defvar org-todo-line-tags-regexp nil
2576 "Matches a headline and puts TODO state into group 2 if present.
2577 Also put tags into group 4 if tags are present.")
2578 (make-variable-buffer-local 'org-todo-line-tags-regexp)
2579 (defvar org-nl-done-regexp nil
2580 "Matches newline followed by a headline with the DONE keyword.")
2581 (make-variable-buffer-local 'org-nl-done-regexp)
2582 (defvar org-looking-at-done-regexp nil
2583 "Matches the DONE keyword a point.")
2584 (make-variable-buffer-local 'org-looking-at-done-regexp)
2585 (defvar org-ds-keyword-length 12
2586 "Maximum length of the Deadline and SCHEDULED keywords.")
2587 (make-variable-buffer-local 'org-ds-keyword-length)
2588 (defvar org-deadline-regexp nil
2589 "Matches the DEADLINE keyword.")
2590 (make-variable-buffer-local 'org-deadline-regexp)
2591 (defvar org-deadline-time-regexp nil
2592 "Matches the DEADLINE keyword together with a time stamp.")
2593 (make-variable-buffer-local 'org-deadline-time-regexp)
2594 (defvar org-deadline-line-regexp nil
2595 "Matches the DEADLINE keyword and the rest of the line.")
2596 (make-variable-buffer-local 'org-deadline-line-regexp)
2597 (defvar org-scheduled-regexp nil
2598 "Matches the SCHEDULED keyword.")
2599 (make-variable-buffer-local 'org-scheduled-regexp)
2600 (defvar org-scheduled-time-regexp nil
2601 "Matches the SCHEDULED keyword together with a time stamp.")
2602 (make-variable-buffer-local 'org-scheduled-time-regexp)
2603 (defvar org-closed-time-regexp nil
2604 "Matches the CLOSED keyword together with a time stamp.")
2605 (make-variable-buffer-local 'org-closed-time-regexp)
2607 (defvar org-keyword-time-regexp nil
2608 "Matches any of the 4 keywords, together with the time stamp.")
2609 (make-variable-buffer-local 'org-keyword-time-regexp)
2610 (defvar org-keyword-time-not-clock-regexp nil
2611 "Matches any of the 3 keywords, together with the time stamp.")
2612 (make-variable-buffer-local 'org-keyword-time-not-clock-regexp)
2613 (defvar org-maybe-keyword-time-regexp nil
2614 "Matches a timestamp, possibly preceeded by a keyword.")
2615 (make-variable-buffer-local 'org-maybe-keyword-time-regexp)
2616 (defvar org-planning-or-clock-line-re nil
2617 "Matches a line with planning or clock info.")
2618 (make-variable-buffer-local 'org-planning-or-clock-line-re)
2620 (defconst org-plain-time-of-day-regexp
2621 (concat
2622 "\\(\\<[012]?[0-9]"
2623 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2624 "\\(--?"
2625 "\\(\\<[012]?[0-9]"
2626 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2627 "\\)?")
2628 "Regular expression to match a plain time or time range.
2629 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2630 groups carry important information:
2631 0 the full match
2632 1 the first time, range or not
2633 8 the second time, if it is a range.")
2635 (defconst org-plain-time-extension-regexp
2636 (concat
2637 "\\(\\<[012]?[0-9]"
2638 "\\(\\(:\\([0-5][0-9]\\([AaPp][Mm]\\)?\\)\\)\\|\\([AaPp][Mm]\\)\\)\\>\\)"
2639 "\\+\\([0-9]+\\)\\(:\\([0-5][0-9]\\)\\)?")
2640 "Regular expression to match a time range like 13:30+2:10 = 13:30-15:40.
2641 Examples: 11:45 or 8am-13:15 or 2:45-2:45pm. After a match, the following
2642 groups carry important information:
2643 0 the full match
2644 7 hours of duration
2645 9 minutes of duration")
2647 (defconst org-stamp-time-of-day-regexp
2648 (concat
2649 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} +\\sw+ +\\)"
2650 "\\([012][0-9]:[0-5][0-9]\\(-\\([012][0-9]:[0-5][0-9]\\)\\)?[^\n\r>]*?\\)>"
2651 "\\(--?"
2652 "<\\1\\([012][0-9]:[0-5][0-9]\\)>\\)?")
2653 "Regular expression to match a timestamp time or time range.
2654 After a match, the following groups carry important information:
2655 0 the full match
2656 1 date plus weekday, for backreferencing to make sure both times on same day
2657 2 the first time, range or not
2658 4 the second time, if it is a range.")
2660 (defconst org-startup-options
2661 '(("fold" org-startup-folded t)
2662 ("overview" org-startup-folded t)
2663 ("nofold" org-startup-folded nil)
2664 ("showall" org-startup-folded nil)
2665 ("content" org-startup-folded content)
2666 ("hidestars" org-hide-leading-stars t)
2667 ("showstars" org-hide-leading-stars nil)
2668 ("odd" org-odd-levels-only t)
2669 ("oddeven" org-odd-levels-only nil)
2670 ("align" org-startup-align-all-tables t)
2671 ("noalign" org-startup-align-all-tables nil)
2672 ("customtime" org-display-custom-times t)
2673 ("logdone" org-log-done time)
2674 ("lognotedone" org-log-done note)
2675 ("nologdone" org-log-done nil)
2676 ("lognoteclock-out" org-log-note-clock-out t)
2677 ("nolognoteclock-out" org-log-note-clock-out nil)
2678 ("logrepeat" org-log-repeat state)
2679 ("lognoterepeat" org-log-repeat note)
2680 ("nologrepeat" org-log-repeat nil)
2681 ("constcgs" constants-unit-system cgs)
2682 ("constSI" constants-unit-system SI))
2683 "Variable associated with STARTUP options for org-mode.
2684 Each element is a list of three items: The startup options as written
2685 in the #+STARTUP line, the corresponding variable, and the value to
2686 set this variable to if the option is found. An optional forth element PUSH
2687 means to push this value onto the list in the variable.")
2689 (defun org-set-regexps-and-options ()
2690 "Precompute regular expressions for current buffer."
2691 (when (org-mode-p)
2692 (org-set-local 'org-todo-kwd-alist nil)
2693 (org-set-local 'org-todo-key-alist nil)
2694 (org-set-local 'org-todo-key-trigger nil)
2695 (org-set-local 'org-todo-keywords-1 nil)
2696 (org-set-local 'org-done-keywords nil)
2697 (org-set-local 'org-todo-heads nil)
2698 (org-set-local 'org-todo-sets nil)
2699 (org-set-local 'org-todo-log-states nil)
2700 (let ((re (org-make-options-regexp
2701 '("CATEGORY" "SEQ_TODO" "TYP_TODO" "TODO" "COLUMNS"
2702 "STARTUP" "ARCHIVE" "TAGS" "LINK" "PRIORITIES"
2703 "CONSTANTS" "PROPERTY" "DRAWERS")))
2704 (splitre "[ \t]+")
2705 kwds kws0 kwsa key log value cat arch tags const links hw dws
2706 tail sep kws1 prio props drawers)
2707 (save-excursion
2708 (save-restriction
2709 (widen)
2710 (goto-char (point-min))
2711 (while (re-search-forward re nil t)
2712 (setq key (match-string 1) value (org-match-string-no-properties 2))
2713 (cond
2714 ((equal key "CATEGORY")
2715 (if (string-match "[ \t]+$" value)
2716 (setq value (replace-match "" t t value)))
2717 (setq cat value))
2718 ((member key '("SEQ_TODO" "TODO"))
2719 (push (cons 'sequence (org-split-string value splitre)) kwds))
2720 ((equal key "TYP_TODO")
2721 (push (cons 'type (org-split-string value splitre)) kwds))
2722 ((equal key "TAGS")
2723 (setq tags (append tags (org-split-string value splitre))))
2724 ((equal key "COLUMNS")
2725 (org-set-local 'org-columns-default-format value))
2726 ((equal key "LINK")
2727 (when (string-match "^\\(\\S-+\\)[ \t]+\\(.+\\)" value)
2728 (push (cons (match-string 1 value)
2729 (org-trim (match-string 2 value)))
2730 links)))
2731 ((equal key "PRIORITIES")
2732 (setq prio (org-split-string value " +")))
2733 ((equal key "PROPERTY")
2734 (when (string-match "\\(\\S-+\\)\\s-+\\(.*\\)" value)
2735 (push (cons (match-string 1 value) (match-string 2 value))
2736 props)))
2737 ((equal key "DRAWERS")
2738 (setq drawers (org-split-string value splitre)))
2739 ((equal key "CONSTANTS")
2740 (setq const (append const (org-split-string value splitre))))
2741 ((equal key "STARTUP")
2742 (let ((opts (org-split-string value splitre))
2743 l var val)
2744 (while (setq l (pop opts))
2745 (when (setq l (assoc l org-startup-options))
2746 (setq var (nth 1 l) val (nth 2 l))
2747 (if (not (nth 3 l))
2748 (set (make-local-variable var) val)
2749 (if (not (listp (symbol-value var)))
2750 (set (make-local-variable var) nil))
2751 (set (make-local-variable var) (symbol-value var))
2752 (add-to-list var val))))))
2753 ((equal key "ARCHIVE")
2754 (string-match " *$" value)
2755 (setq arch (replace-match "" t t value))
2756 (remove-text-properties 0 (length arch)
2757 '(face t fontified t) arch)))
2759 (when cat
2760 (org-set-local 'org-category (intern cat))
2761 (push (cons "CATEGORY" cat) props))
2762 (when prio
2763 (if (< (length prio) 3) (setq prio '("A" "C" "B")))
2764 (setq prio (mapcar 'string-to-char prio))
2765 (org-set-local 'org-highest-priority (nth 0 prio))
2766 (org-set-local 'org-lowest-priority (nth 1 prio))
2767 (org-set-local 'org-default-priority (nth 2 prio)))
2768 (and props (org-set-local 'org-local-properties (nreverse props)))
2769 (and drawers (org-set-local 'org-drawers drawers))
2770 (and arch (org-set-local 'org-archive-location arch))
2771 (and links (setq org-link-abbrev-alist-local (nreverse links)))
2772 ;; Process the TODO keywords
2773 (unless kwds
2774 ;; Use the global values as if they had been given locally.
2775 (setq kwds (default-value 'org-todo-keywords))
2776 (if (stringp (car kwds))
2777 (setq kwds (list (cons org-todo-interpretation
2778 (default-value 'org-todo-keywords)))))
2779 (setq kwds (reverse kwds)))
2780 (setq kwds (nreverse kwds))
2781 (let (inter kws kw)
2782 (while (setq kws (pop kwds))
2783 (setq inter (pop kws) sep (member "|" kws)
2784 kws0 (delete "|" (copy-sequence kws))
2785 kwsa nil
2786 kws1 (mapcar
2787 (lambda (x)
2788 ;; 1 2
2789 (if (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?.*?)\\)?$" x)
2790 (progn
2791 (setq kw (match-string 1 x)
2792 key (and (match-end 2) (match-string 2 x))
2793 log (org-extract-log-state-settings x))
2794 (push (cons kw (and key (string-to-char key))) kwsa)
2795 (and log (push log org-todo-log-states))
2797 (error "Invalid TODO keyword %s" x)))
2798 kws0)
2799 kwsa (if kwsa (append '((:startgroup))
2800 (nreverse kwsa)
2801 '((:endgroup))))
2802 hw (car kws1)
2803 dws (if sep (org-remove-keyword-keys (cdr sep)) (last kws1))
2804 tail (list inter hw (car dws) (org-last dws)))
2805 (add-to-list 'org-todo-heads hw 'append)
2806 (push kws1 org-todo-sets)
2807 (setq org-done-keywords (append org-done-keywords dws nil))
2808 (setq org-todo-key-alist (append org-todo-key-alist kwsa))
2809 (mapc (lambda (x) (push (cons x tail) org-todo-kwd-alist)) kws1)
2810 (setq org-todo-keywords-1 (append org-todo-keywords-1 kws1 nil)))
2811 (setq org-todo-sets (nreverse org-todo-sets)
2812 org-todo-kwd-alist (nreverse org-todo-kwd-alist)
2813 org-todo-key-trigger (delq nil (mapcar 'cdr org-todo-key-alist))
2814 org-todo-key-alist (org-assign-fast-keys org-todo-key-alist)))
2815 ;; Process the constants
2816 (when const
2817 (let (e cst)
2818 (while (setq e (pop const))
2819 (if (string-match "^\\([a-zA-Z0][_a-zA-Z0-9]*\\)=\\(.*\\)" e)
2820 (push (cons (match-string 1 e) (match-string 2 e)) cst)))
2821 (setq org-table-formula-constants-local cst)))
2823 ;; Process the tags.
2824 (when tags
2825 (let (e tgs)
2826 (while (setq e (pop tags))
2827 (cond
2828 ((equal e "{") (push '(:startgroup) tgs))
2829 ((equal e "}") (push '(:endgroup) tgs))
2830 ((string-match (org-re "^\\([[:alnum:]_@]+\\)(\\(.\\))$") e)
2831 (push (cons (match-string 1 e)
2832 (string-to-char (match-string 2 e)))
2833 tgs))
2834 (t (push (list e) tgs))))
2835 (org-set-local 'org-tag-alist nil)
2836 (while (setq e (pop tgs))
2837 (or (and (stringp (car e))
2838 (assoc (car e) org-tag-alist))
2839 (push e org-tag-alist))))))
2841 ;; Compute the regular expressions and other local variables
2842 (if (not org-done-keywords)
2843 (setq org-done-keywords (list (org-last org-todo-keywords-1))))
2844 (setq org-ds-keyword-length (+ 2 (max (length org-deadline-string)
2845 (length org-scheduled-string)
2846 (length org-clock-string)
2847 (length org-closed-string)))
2848 org-drawer-regexp
2849 (concat "^[ \t]*:\\("
2850 (mapconcat 'regexp-quote org-drawers "\\|")
2851 "\\):[ \t]*$")
2852 org-not-done-keywords
2853 (org-delete-all org-done-keywords (copy-sequence org-todo-keywords-1))
2854 org-todo-regexp
2855 (concat "\\<\\(" (mapconcat 'regexp-quote org-todo-keywords-1
2856 "\\|") "\\)\\>")
2857 org-not-done-regexp
2858 (concat "\\<\\("
2859 (mapconcat 'regexp-quote org-not-done-keywords "\\|")
2860 "\\)\\>")
2861 org-todo-line-regexp
2862 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2863 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2864 "\\)\\>\\)?[ \t]*\\(.*\\)")
2865 org-complex-heading-regexp
2866 (concat "^\\(\\*+\\)\\(?:[ \t]+\\("
2867 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2868 "\\)\\>\\)?\\(?:[ \t]*\\(\\[#.\\]\\)\\)?[ \t]*\\(.*?\\)"
2869 "\\(?:[ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
2870 org-nl-done-regexp
2871 (concat "\n\\*+[ \t]+"
2872 "\\(?:" (mapconcat 'regexp-quote org-done-keywords "\\|")
2873 "\\)" "\\>")
2874 org-todo-line-tags-regexp
2875 (concat "^\\(\\*+\\)[ \t]+\\(?:\\("
2876 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
2877 (org-re
2878 "\\)\\>\\)? *\\(.*?\\([ \t]:[[:alnum:]:_@]+:[ \t]*\\)?$\\)"))
2879 org-looking-at-done-regexp
2880 (concat "^" "\\(?:"
2881 (mapconcat 'regexp-quote org-done-keywords "\\|") "\\)"
2882 "\\>")
2883 org-deadline-regexp (concat "\\<" org-deadline-string)
2884 org-deadline-time-regexp
2885 (concat "\\<" org-deadline-string " *<\\([^>]+\\)>")
2886 org-deadline-line-regexp
2887 (concat "\\<\\(" org-deadline-string "\\).*")
2888 org-scheduled-regexp
2889 (concat "\\<" org-scheduled-string)
2890 org-scheduled-time-regexp
2891 (concat "\\<" org-scheduled-string " *<\\([^>]+\\)>")
2892 org-closed-time-regexp
2893 (concat "\\<" org-closed-string " *\\[\\([^]]+\\)\\]")
2894 org-keyword-time-regexp
2895 (concat "\\<\\(" org-scheduled-string
2896 "\\|" org-deadline-string
2897 "\\|" org-closed-string
2898 "\\|" org-clock-string "\\)"
2899 " *[[<]\\([^]>]+\\)[]>]")
2900 org-keyword-time-not-clock-regexp
2901 (concat "\\<\\(" org-scheduled-string
2902 "\\|" org-deadline-string
2903 "\\|" org-closed-string
2904 "\\)"
2905 " *[[<]\\([^]>]+\\)[]>]")
2906 org-maybe-keyword-time-regexp
2907 (concat "\\(\\<\\(" org-scheduled-string
2908 "\\|" org-deadline-string
2909 "\\|" org-closed-string
2910 "\\|" org-clock-string "\\)\\)?"
2911 " *\\([[<][0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^]\r\n>]*?[]>]\\|<%%([^\r\n>]*>\\)")
2912 org-planning-or-clock-line-re
2913 (concat "\\(?:^[ \t]*\\(" org-scheduled-string
2914 "\\|" org-deadline-string
2915 "\\|" org-closed-string "\\|" org-clock-string
2916 "\\)\\>\\)")
2918 (org-compute-latex-and-specials-regexp)
2919 (org-set-font-lock-defaults)))
2921 (defun org-extract-log-state-settings (x)
2922 "Extract the log state setting from a TODO keyword string.
2923 This will extract info from a string like \"WAIT(w@/!)\"."
2924 (let (kw key log1 log2)
2925 (when (string-match "^\\(.*?\\)\\(?:(\\([^!@/]\\)?\\([!@]\\)?\\(?:/\\([!@]\\)\\)?)\\)?$" x)
2926 (setq kw (match-string 1 x)
2927 key (and (match-end 2) (match-string 2 x))
2928 log1 (and (match-end 3) (match-string 3 x))
2929 log2 (and (match-end 4) (match-string 4 x)))
2930 (and (or log1 log2)
2931 (list kw
2932 (and log1 (if (equal log1 "!") 'time 'note))
2933 (and log2 (if (equal log2 "!") 'time 'note)))))))
2935 (defun org-remove-keyword-keys (list)
2936 "Remove a pair of parenthesis at the end of each string in LIST."
2937 (mapcar (lambda (x)
2938 (if (string-match "(.*)$" x)
2939 (substring x 0 (match-beginning 0))
2941 list))
2943 ;; FIXME: this could be done much better, using second characters etc.
2944 (defun org-assign-fast-keys (alist)
2945 "Assign fast keys to a keyword-key alist.
2946 Respect keys that are already there."
2947 (let (new e k c c1 c2 (char ?a))
2948 (while (setq e (pop alist))
2949 (cond
2950 ((equal e '(:startgroup)) (push e new))
2951 ((equal e '(:endgroup)) (push e new))
2953 (setq k (car e) c2 nil)
2954 (if (cdr e)
2955 (setq c (cdr e))
2956 ;; automatically assign a character.
2957 (setq c1 (string-to-char
2958 (downcase (substring
2959 k (if (= (string-to-char k) ?@) 1 0)))))
2960 (if (or (rassoc c1 new) (rassoc c1 alist))
2961 (while (or (rassoc char new) (rassoc char alist))
2962 (setq char (1+ char)))
2963 (setq c2 c1))
2964 (setq c (or c2 char)))
2965 (push (cons k c) new))))
2966 (nreverse new)))
2968 ;;; Some variables used in various places
2970 (defvar org-window-configuration nil
2971 "Used in various places to store a window configuration.")
2972 (defvar org-finish-function nil
2973 "Function to be called when `C-c C-c' is used.
2974 This is for getting out of special buffers like remember.")
2977 ;; FIXME: Occasionally check by commenting these, to make sure
2978 ;; no other functions uses these, forgetting to let-bind them.
2979 (defvar entry)
2980 (defvar state)
2981 (defvar last-state)
2982 (defvar date)
2983 (defvar description)
2985 ;; Defined somewhere in this file, but used before definition.
2986 (defvar org-html-entities)
2987 (defvar org-struct-menu)
2988 (defvar org-org-menu)
2989 (defvar org-tbl-menu)
2990 (defvar org-agenda-keymap)
2992 ;;;; Define the Org-mode
2994 (if (and (not (keymapp outline-mode-map)) (featurep 'allout))
2995 (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."))
2998 ;; We use a before-change function to check if a table might need
2999 ;; an update.
3000 (defvar org-table-may-need-update t
3001 "Indicates that a table might need an update.
3002 This variable is set by `org-before-change-function'.
3003 `org-table-align' sets it back to nil.")
3004 (defun org-before-change-function (beg end)
3005 "Every change indicates that a table might need an update."
3006 (setq org-table-may-need-update t))
3007 (defvar org-mode-map)
3008 (defvar org-mode-hook nil)
3009 (defvar org-inhibit-startup nil) ; Dynamically-scoped param.
3010 (defvar org-agenda-keep-modes nil) ; Dynamically-scoped param.
3011 (defvar org-table-buffer-is-an nil)
3012 (defconst org-outline-regexp "\\*+ ")
3014 ;;;###autoload
3015 (define-derived-mode org-mode outline-mode "Org"
3016 "Outline-based notes management and organizer, alias
3017 \"Carsten's outline-mode for keeping track of everything.\"
3019 Org-mode develops organizational tasks around a NOTES file which
3020 contains information about projects as plain text. Org-mode is
3021 implemented on top of outline-mode, which is ideal to keep the content
3022 of large files well structured. It supports ToDo items, deadlines and
3023 time stamps, which magically appear in the diary listing of the Emacs
3024 calendar. Tables are easily created with a built-in table editor.
3025 Plain text URL-like links connect to websites, emails (VM), Usenet
3026 messages (Gnus), BBDB entries, and any files related to the project.
3027 For printing and sharing of notes, an Org-mode file (or a part of it)
3028 can be exported as a structured ASCII or HTML file.
3030 The following commands are available:
3032 \\{org-mode-map}"
3034 ;; Get rid of Outline menus, they are not needed
3035 ;; Need to do this here because define-derived-mode sets up
3036 ;; the keymap so late. Still, it is a waste to call this each time
3037 ;; we switch another buffer into org-mode.
3038 (if (featurep 'xemacs)
3039 (when (boundp 'outline-mode-menu-heading)
3040 ;; Assume this is Greg's port, it used easymenu
3041 (easy-menu-remove outline-mode-menu-heading)
3042 (easy-menu-remove outline-mode-menu-show)
3043 (easy-menu-remove outline-mode-menu-hide))
3044 (define-key org-mode-map [menu-bar headings] 'undefined)
3045 (define-key org-mode-map [menu-bar hide] 'undefined)
3046 (define-key org-mode-map [menu-bar show] 'undefined))
3048 (org-load-modules-maybe)
3049 (easy-menu-add org-org-menu)
3050 (easy-menu-add org-tbl-menu)
3051 (org-install-agenda-files-menu)
3052 (if org-descriptive-links (org-add-to-invisibility-spec '(org-link)))
3053 (org-add-to-invisibility-spec '(org-cwidth))
3054 (when (featurep 'xemacs)
3055 (org-set-local 'line-move-ignore-invisible t))
3056 (org-set-local 'outline-regexp org-outline-regexp)
3057 (org-set-local 'outline-level 'org-outline-level)
3058 (when (and org-ellipsis
3059 (fboundp 'set-display-table-slot) (boundp 'buffer-display-table)
3060 (fboundp 'make-glyph-code))
3061 (unless org-display-table
3062 (setq org-display-table (make-display-table)))
3063 (set-display-table-slot
3064 org-display-table 4
3065 (vconcat (mapcar
3066 (lambda (c) (make-glyph-code c (and (not (stringp org-ellipsis))
3067 org-ellipsis)))
3068 (if (stringp org-ellipsis) org-ellipsis "..."))))
3069 (setq buffer-display-table org-display-table))
3070 (org-set-regexps-and-options)
3071 ;; Calc embedded
3072 (org-set-local 'calc-embedded-open-mode "# ")
3073 (modify-syntax-entry ?# "<")
3074 (modify-syntax-entry ?@ "w")
3075 (if org-startup-truncated (setq truncate-lines t))
3076 (org-set-local 'font-lock-unfontify-region-function
3077 'org-unfontify-region)
3078 ;; Activate before-change-function
3079 (org-set-local 'org-table-may-need-update t)
3080 (org-add-hook 'before-change-functions 'org-before-change-function nil
3081 'local)
3082 ;; Check for running clock before killing a buffer
3083 (org-add-hook 'kill-buffer-hook 'org-check-running-clock nil 'local)
3084 ;; Paragraphs and auto-filling
3085 (org-set-autofill-regexps)
3086 (setq indent-line-function 'org-indent-line-function)
3087 (org-update-radio-target-regexp)
3089 ;; Comment characters
3090 ; (org-set-local 'comment-start "#") ;; FIXME: this breaks wrapping
3091 (org-set-local 'comment-padding " ")
3093 ;; Align options lines
3094 (org-set-local
3095 'align-mode-rules-list
3096 '((org-in-buffer-settings
3097 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
3098 (modes . '(org-mode)))))
3100 ;; Imenu
3101 (org-set-local 'imenu-create-index-function
3102 'org-imenu-get-tree)
3104 ;; Make isearch reveal context
3105 (if (or (featurep 'xemacs)
3106 (not (boundp 'outline-isearch-open-invisible-function)))
3107 ;; Emacs 21 and XEmacs make use of the hook
3108 (org-add-hook 'isearch-mode-end-hook 'org-isearch-end 'append 'local)
3109 ;; Emacs 22 deals with this through a special variable
3110 (org-set-local 'outline-isearch-open-invisible-function
3111 (lambda (&rest ignore) (org-show-context 'isearch))))
3113 ;; If empty file that did not turn on org-mode automatically, make it to.
3114 (if (and org-insert-mode-line-in-empty-file
3115 (interactive-p)
3116 (= (point-min) (point-max)))
3117 (insert "# -*- mode: org -*-\n\n"))
3119 (unless org-inhibit-startup
3120 (when org-startup-align-all-tables
3121 (let ((bmp (buffer-modified-p)))
3122 (org-table-map-tables 'org-table-align)
3123 (set-buffer-modified-p bmp)))
3124 (org-cycle-hide-drawers 'all)
3125 (cond
3126 ((eq org-startup-folded t)
3127 (org-cycle '(4)))
3128 ((eq org-startup-folded 'content)
3129 (let ((this-command 'org-cycle) (last-command 'org-cycle))
3130 (org-cycle '(4)) (org-cycle '(4)))))))
3132 (put 'org-mode 'flyspell-mode-predicate 'org-mode-flyspell-verify)
3134 (defun org-current-time ()
3135 "Current time, possibly rounded to `org-time-stamp-rounding-minutes'."
3136 (if (> (car org-time-stamp-rounding-minutes) 1)
3137 (let ((r (car org-time-stamp-rounding-minutes))
3138 (time (decode-time)))
3139 (apply 'encode-time
3140 (append (list 0 (* r (floor (+ .5 (/ (float (nth 1 time)) r)))))
3141 (nthcdr 2 time))))
3142 (current-time)))
3144 ;;;; Font-Lock stuff, including the activators
3146 (defvar org-mouse-map (make-sparse-keymap))
3147 (org-defkey org-mouse-map
3148 (if (featurep 'xemacs) [button2] [mouse-2]) 'org-open-at-mouse)
3149 (org-defkey org-mouse-map
3150 (if (featurep 'xemacs) [button3] [mouse-3]) 'org-find-file-at-mouse)
3151 (when org-mouse-1-follows-link
3152 (org-defkey org-mouse-map [follow-link] 'mouse-face))
3153 (when org-tab-follows-link
3154 (org-defkey org-mouse-map [(tab)] 'org-open-at-point)
3155 (org-defkey org-mouse-map "\C-i" 'org-open-at-point))
3156 (when org-return-follows-link
3157 (org-defkey org-mouse-map [(return)] 'org-open-at-point)
3158 (org-defkey org-mouse-map "\C-m" 'org-open-at-point))
3160 (require 'font-lock)
3162 (defconst org-non-link-chars "]\t\n\r<>")
3163 (defvar org-link-types '("http" "https" "ftp" "mailto" "file" "news"
3164 "shell" "elisp"))
3165 (defvar org-link-types-re nil
3166 "Matches a link that has a url-like prefix like \"http:\"")
3167 (defvar org-link-re-with-space nil
3168 "Matches a link with spaces, optional angular brackets around it.")
3169 (defvar org-link-re-with-space2 nil
3170 "Matches a link with spaces, optional angular brackets around it.")
3171 (defvar org-angle-link-re nil
3172 "Matches link with angular brackets, spaces are allowed.")
3173 (defvar org-plain-link-re nil
3174 "Matches plain link, without spaces.")
3175 (defvar org-bracket-link-regexp nil
3176 "Matches a link in double brackets.")
3177 (defvar org-bracket-link-analytic-regexp nil
3178 "Regular expression used to analyze links.
3179 Here is what the match groups contain after a match:
3180 1: http:
3181 2: http
3182 3: path
3183 4: [desc]
3184 5: desc")
3185 (defvar org-any-link-re nil
3186 "Regular expression matching any link.")
3188 (defun org-make-link-regexps ()
3189 "Update the link regular expressions.
3190 This should be called after the variable `org-link-types' has changed."
3191 (setq org-link-types-re
3192 (concat
3193 "\\`\\(" (mapconcat 'identity org-link-types "\\|") "\\):")
3194 org-link-re-with-space
3195 (concat
3196 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3197 "\\([^" org-non-link-chars " ]"
3198 "[^" org-non-link-chars "]*"
3199 "[^" org-non-link-chars " ]\\)>?")
3200 org-link-re-with-space2
3201 (concat
3202 "<?\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3203 "\\([^" org-non-link-chars " ]"
3204 "[^]\t\n\r]*"
3205 "[^" org-non-link-chars " ]\\)>?")
3206 org-angle-link-re
3207 (concat
3208 "<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3209 "\\([^" org-non-link-chars " ]"
3210 "[^" org-non-link-chars "]*"
3211 "\\)>")
3212 org-plain-link-re
3213 (concat
3214 "\\<\\(" (mapconcat 'identity org-link-types "\\|") "\\):"
3215 "\\([^]\t\n\r<>() ]+[^]\t\n\r<>,.;() ]\\)")
3216 org-bracket-link-regexp
3217 "\\[\\[\\([^][]+\\)\\]\\(\\[\\([^][]+\\)\\]\\)?\\]"
3218 org-bracket-link-analytic-regexp
3219 (concat
3220 "\\[\\["
3221 "\\(\\(" (mapconcat 'identity org-link-types "\\|") "\\):\\)?"
3222 "\\([^]]+\\)"
3223 "\\]"
3224 "\\(\\[" "\\([^]]+\\)" "\\]\\)?"
3225 "\\]")
3226 org-any-link-re
3227 (concat "\\(" org-bracket-link-regexp "\\)\\|\\("
3228 org-angle-link-re "\\)\\|\\("
3229 org-plain-link-re "\\)")))
3231 (org-make-link-regexps)
3233 (defconst org-ts-regexp "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)>"
3234 "Regular expression for fast time stamp matching.")
3235 (defconst org-ts-regexp-both "[[<]\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} [^\r\n>]*?\\)[]>]"
3236 "Regular expression for fast time stamp matching.")
3237 (defconst org-ts-regexp0 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) *\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3238 "Regular expression matching time strings for analysis.
3239 This one does not require the space after the date, so it can be used
3240 on a string that terminates immediately after the date.")
3241 (defconst org-ts-regexp1 "\\(\\([0-9]\\{4\\}\\)-\\([0-9]\\{2\\}\\)-\\([0-9]\\{2\\}\\) +\\([^]-+0-9>\r\n ]*\\)\\( \\([0-9]\\{2\\}\\):\\([0-9]\\{2\\}\\)\\)?\\)"
3242 "Regular expression matching time strings for analysis.")
3243 (defconst org-ts-regexp2 (concat "<" org-ts-regexp1 "[^>\n]\\{0,16\\}>")
3244 "Regular expression matching time stamps, with groups.")
3245 (defconst org-ts-regexp3 (concat "[[<]" org-ts-regexp1 "[^]>\n]\\{0,16\\}[]>]")
3246 "Regular expression matching time stamps (also [..]), with groups.")
3247 (defconst org-tr-regexp (concat org-ts-regexp "--?-?" org-ts-regexp)
3248 "Regular expression matching a time stamp range.")
3249 (defconst org-tr-regexp-both
3250 (concat org-ts-regexp-both "--?-?" org-ts-regexp-both)
3251 "Regular expression matching a time stamp range.")
3252 (defconst org-tsr-regexp (concat org-ts-regexp "\\(--?-?"
3253 org-ts-regexp "\\)?")
3254 "Regular expression matching a time stamp or time stamp range.")
3255 (defconst org-tsr-regexp-both (concat org-ts-regexp-both "\\(--?-?"
3256 org-ts-regexp-both "\\)?")
3257 "Regular expression matching a time stamp or time stamp range.
3258 The time stamps may be either active or inactive.")
3260 (defvar org-emph-face nil)
3262 (defun org-do-emphasis-faces (limit)
3263 "Run through the buffer and add overlays to links."
3264 (let (rtn)
3265 (while (and (not rtn) (re-search-forward org-emph-re limit t))
3266 (if (not (= (char-after (match-beginning 3))
3267 (char-after (match-beginning 4))))
3268 (progn
3269 (setq rtn t)
3270 (font-lock-prepend-text-property (match-beginning 2) (match-end 2)
3271 'face
3272 (nth 1 (assoc (match-string 3)
3273 org-emphasis-alist)))
3274 (add-text-properties (match-beginning 2) (match-end 2)
3275 '(font-lock-multiline t))
3276 (when org-hide-emphasis-markers
3277 (add-text-properties (match-end 4) (match-beginning 5)
3278 '(invisible org-link))
3279 (add-text-properties (match-beginning 3) (match-end 3)
3280 '(invisible org-link)))))
3281 (backward-char 1))
3282 rtn))
3284 (defun org-emphasize (&optional char)
3285 "Insert or change an emphasis, i.e. a font like bold or italic.
3286 If there is an active region, change that region to a new emphasis.
3287 If there is no region, just insert the marker characters and position
3288 the cursor between them.
3289 CHAR should be either the marker character, or the first character of the
3290 HTML tag associated with that emphasis. If CHAR is a space, the means
3291 to remove the emphasis of the selected region.
3292 If char is not given (for example in an interactive call) it
3293 will be prompted for."
3294 (interactive)
3295 (let ((eal org-emphasis-alist) e det
3296 (erc org-emphasis-regexp-components)
3297 (prompt "")
3298 (string "") beg end move tag c s)
3299 (if (org-region-active-p)
3300 (setq beg (region-beginning) end (region-end)
3301 string (buffer-substring beg end))
3302 (setq move t))
3304 (while (setq e (pop eal))
3305 (setq tag (car (org-split-string (nth 2 e) "[ <>/]+"))
3306 c (aref tag 0))
3307 (push (cons c (string-to-char (car e))) det)
3308 (setq prompt (concat prompt (format " [%s%c]%s" (car e) c
3309 (substring tag 1)))))
3310 (unless char
3311 (message "%s" (concat "Emphasis marker or tag:" prompt))
3312 (setq char (read-char-exclusive)))
3313 (setq char (or (cdr (assoc char det)) char))
3314 (if (equal char ?\ )
3315 (setq s "" move nil)
3316 (unless (assoc (char-to-string char) org-emphasis-alist)
3317 (error "No such emphasis marker: \"%c\"" char))
3318 (setq s (char-to-string char)))
3319 (while (and (> (length string) 1)
3320 (equal (substring string 0 1) (substring string -1))
3321 (assoc (substring string 0 1) org-emphasis-alist))
3322 (setq string (substring string 1 -1)))
3323 (setq string (concat s string s))
3324 (if beg (delete-region beg end))
3325 (unless (or (bolp)
3326 (string-match (concat "[" (nth 0 erc) "\n]")
3327 (char-to-string (char-before (point)))))
3328 (insert " "))
3329 (unless (string-match (concat "[" (nth 1 erc) "\n]")
3330 (char-to-string (char-after (point))))
3331 (insert " ") (backward-char 1))
3332 (insert string)
3333 (and move (backward-char 1))))
3335 (defconst org-nonsticky-props
3336 '(mouse-face highlight keymap invisible intangible help-echo org-linked-text))
3339 (defun org-activate-plain-links (limit)
3340 "Run through the buffer and add overlays to links."
3341 (catch 'exit
3342 (let (f)
3343 (while (re-search-forward org-plain-link-re limit t)
3344 (setq f (get-text-property (match-beginning 0) 'face))
3345 (if (or (eq f 'org-tag)
3346 (and (listp f) (memq 'org-tag f)))
3348 (add-text-properties (match-beginning 0) (match-end 0)
3349 (list 'mouse-face 'highlight
3350 'rear-nonsticky org-nonsticky-props
3351 'keymap org-mouse-map
3353 (throw 'exit t))))))
3355 (defun org-activate-code (limit)
3356 (if (re-search-forward "^[ \t]*\\(:.*\\)" limit t)
3357 (unless (get-text-property (match-beginning 1) 'face)
3358 (remove-text-properties (match-beginning 0) (match-end 0)
3359 '(display t invisible t intangible t))
3360 t)))
3362 (defun org-activate-angle-links (limit)
3363 "Run through the buffer and add overlays to links."
3364 (if (re-search-forward org-angle-link-re limit t)
3365 (progn
3366 (add-text-properties (match-beginning 0) (match-end 0)
3367 (list 'mouse-face 'highlight
3368 'rear-nonsticky org-nonsticky-props
3369 'keymap org-mouse-map
3371 t)))
3373 (defun org-activate-bracket-links (limit)
3374 "Run through the buffer and add overlays to bracketed links."
3375 (if (re-search-forward org-bracket-link-regexp limit t)
3376 (let* ((help (concat "LINK: "
3377 (org-match-string-no-properties 1)))
3378 ;; FIXME: above we should remove the escapes.
3379 ;; but that requires another match, protecting match data,
3380 ;; a lot of overhead for font-lock.
3381 (ip (org-maybe-intangible
3382 (list 'invisible 'org-link 'rear-nonsticky org-nonsticky-props
3383 'keymap org-mouse-map 'mouse-face 'highlight
3384 'font-lock-multiline t 'help-echo help)))
3385 (vp (list 'rear-nonsticky org-nonsticky-props
3386 'keymap org-mouse-map 'mouse-face 'highlight
3387 ' font-lock-multiline t 'help-echo help)))
3388 ;; We need to remove the invisible property here. Table narrowing
3389 ;; may have made some of this invisible.
3390 (remove-text-properties (match-beginning 0) (match-end 0)
3391 '(invisible nil))
3392 (if (match-end 3)
3393 (progn
3394 (add-text-properties (match-beginning 0) (match-beginning 3) ip)
3395 (add-text-properties (match-beginning 3) (match-end 3) vp)
3396 (add-text-properties (match-end 3) (match-end 0) ip))
3397 (add-text-properties (match-beginning 0) (match-beginning 1) ip)
3398 (add-text-properties (match-beginning 1) (match-end 1) vp)
3399 (add-text-properties (match-end 1) (match-end 0) ip))
3400 t)))
3402 (defun org-activate-dates (limit)
3403 "Run through the buffer and add overlays to dates."
3404 (if (re-search-forward org-tsr-regexp-both limit t)
3405 (progn
3406 (add-text-properties (match-beginning 0) (match-end 0)
3407 (list 'mouse-face 'highlight
3408 'rear-nonsticky org-nonsticky-props
3409 'keymap org-mouse-map))
3410 (when org-display-custom-times
3411 (if (match-end 3)
3412 (org-display-custom-time (match-beginning 3) (match-end 3)))
3413 (org-display-custom-time (match-beginning 1) (match-end 1)))
3414 t)))
3416 (defvar org-target-link-regexp nil
3417 "Regular expression matching radio targets in plain text.")
3418 (defvar org-target-regexp "<<\\([^<>\n\r]+\\)>>"
3419 "Regular expression matching a link target.")
3420 (defvar org-radio-target-regexp "<<<\\([^<>\n\r]+\\)>>>"
3421 "Regular expression matching a radio target.")
3422 (defvar org-any-target-regexp "<<<?\\([^<>\n\r]+\\)>>>?" ; FIXME, not exact, would match <<<aaa>> as a radio target.
3423 "Regular expression matching any target.")
3425 (defun org-activate-target-links (limit)
3426 "Run through the buffer and add overlays to target matches."
3427 (when org-target-link-regexp
3428 (let ((case-fold-search t))
3429 (if (re-search-forward org-target-link-regexp limit t)
3430 (progn
3431 (add-text-properties (match-beginning 0) (match-end 0)
3432 (list 'mouse-face 'highlight
3433 'rear-nonsticky org-nonsticky-props
3434 'keymap org-mouse-map
3435 'help-echo "Radio target link"
3436 'org-linked-text t))
3437 t)))))
3439 (defun org-update-radio-target-regexp ()
3440 "Find all radio targets in this file and update the regular expression."
3441 (interactive)
3442 (when (memq 'radio org-activate-links)
3443 (setq org-target-link-regexp
3444 (org-make-target-link-regexp (org-all-targets 'radio)))
3445 (org-restart-font-lock)))
3447 (defun org-hide-wide-columns (limit)
3448 (let (s e)
3449 (setq s (text-property-any (point) (or limit (point-max))
3450 'org-cwidth t))
3451 (when s
3452 (setq e (next-single-property-change s 'org-cwidth))
3453 (add-text-properties s e (org-maybe-intangible '(invisible org-cwidth)))
3454 (goto-char e)
3455 t)))
3457 (defvar org-latex-and-specials-regexp nil
3458 "Regular expression for highlighting export special stuff.")
3459 (defvar org-match-substring-regexp)
3460 (defvar org-match-substring-with-braces-regexp)
3461 (defvar org-export-html-special-string-regexps)
3463 (defun org-compute-latex-and-specials-regexp ()
3464 "Compute regular expression for stuff treated specially by exporters."
3465 (if (not org-highlight-latex-fragments-and-specials)
3466 (org-set-local 'org-latex-and-specials-regexp nil)
3467 (require 'org-exp)
3468 (let*
3469 ((matchers (plist-get org-format-latex-options :matchers))
3470 (latexs (delq nil (mapcar (lambda (x) (if (member (car x) matchers) x))
3471 org-latex-regexps)))
3472 (options (org-combine-plists (org-default-export-plist)
3473 (org-infile-export-plist)))
3474 (org-export-with-sub-superscripts (plist-get options :sub-superscript))
3475 (org-export-with-LaTeX-fragments (plist-get options :LaTeX-fragments))
3476 (org-export-with-TeX-macros (plist-get options :TeX-macros))
3477 (org-export-html-expand (plist-get options :expand-quoted-html))
3478 (org-export-with-special-strings (plist-get options :special-strings))
3479 (re-sub
3480 (cond
3481 ((equal org-export-with-sub-superscripts '{})
3482 (list org-match-substring-with-braces-regexp))
3483 (org-export-with-sub-superscripts
3484 (list org-match-substring-regexp))
3485 (t nil)))
3486 (re-latex
3487 (if org-export-with-LaTeX-fragments
3488 (mapcar (lambda (x) (nth 1 x)) latexs)))
3489 (re-macros
3490 (if org-export-with-TeX-macros
3491 (list (concat "\\\\"
3492 (regexp-opt
3493 (append (mapcar 'car org-html-entities)
3494 (if (boundp 'org-latex-entities)
3495 org-latex-entities nil))
3496 'words))) ; FIXME
3498 ;; (list "\\\\\\(?:[a-zA-Z]+\\)")))
3499 (re-special (if org-export-with-special-strings
3500 (mapcar (lambda (x) (car x))
3501 org-export-html-special-string-regexps)))
3502 (re-rest
3503 (delq nil
3504 (list
3505 (if org-export-html-expand "@<[^>\n]+>")
3506 ))))
3507 (org-set-local
3508 'org-latex-and-specials-regexp
3509 (mapconcat 'identity (append re-latex re-sub re-macros re-special
3510 re-rest) "\\|")))))
3512 (defun org-do-latex-and-special-faces (limit)
3513 "Run through the buffer and add overlays to links."
3514 (when org-latex-and-specials-regexp
3515 (let (rtn d)
3516 (while (and (not rtn) (re-search-forward org-latex-and-specials-regexp
3517 limit t))
3518 (if (not (memq (car-safe (get-text-property (1+ (match-beginning 0))
3519 'face))
3520 '(org-code org-verbatim underline)))
3521 (progn
3522 (setq rtn t
3523 d (cond ((member (char-after (1+ (match-beginning 0)))
3524 '(?_ ?^)) 1)
3525 (t 0)))
3526 (font-lock-prepend-text-property
3527 (+ d (match-beginning 0)) (match-end 0)
3528 'face 'org-latex-and-export-specials)
3529 (add-text-properties (+ d (match-beginning 0)) (match-end 0)
3530 '(font-lock-multiline t)))))
3531 rtn)))
3533 (defun org-restart-font-lock ()
3534 "Restart font-lock-mode, to force refontification."
3535 (when (and (boundp 'font-lock-mode) font-lock-mode)
3536 (font-lock-mode -1)
3537 (font-lock-mode 1)))
3539 (defun org-all-targets (&optional radio)
3540 "Return a list of all targets in this file.
3541 With optional argument RADIO, only find radio targets."
3542 (let ((re (if radio org-radio-target-regexp org-target-regexp))
3543 rtn)
3544 (save-excursion
3545 (goto-char (point-min))
3546 (while (re-search-forward re nil t)
3547 (add-to-list 'rtn (downcase (org-match-string-no-properties 1))))
3548 rtn)))
3550 (defun org-make-target-link-regexp (targets)
3551 "Make regular expression matching all strings in TARGETS.
3552 The regular expression finds the targets also if there is a line break
3553 between words."
3554 (and targets
3555 (concat
3556 "\\<\\("
3557 (mapconcat
3558 (lambda (x)
3559 (while (string-match " +" x)
3560 (setq x (replace-match "\\s-+" t t x)))
3562 targets
3563 "\\|")
3564 "\\)\\>")))
3566 (defun org-activate-tags (limit)
3567 (if (re-search-forward (org-re "^\\*+.*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \r\n]") limit t)
3568 (progn
3569 (add-text-properties (match-beginning 1) (match-end 1)
3570 (list 'mouse-face 'highlight
3571 'rear-nonsticky org-nonsticky-props
3572 'keymap org-mouse-map))
3573 t)))
3575 (defun org-outline-level ()
3576 (save-excursion
3577 (looking-at outline-regexp)
3578 (if (match-beginning 1)
3579 (+ (org-get-string-indentation (match-string 1)) 1000)
3580 (1- (- (match-end 0) (match-beginning 0))))))
3582 (defvar org-font-lock-keywords nil)
3584 (defconst org-property-re (org-re "^[ \t]*\\(:\\([[:alnum:]_]+\\):\\)[ \t]*\\([^ \t\r\n].*\\)")
3585 "Regular expression matching a property line.")
3587 (defun org-set-font-lock-defaults ()
3588 (let* ((em org-fontify-emphasized-text)
3589 (lk org-activate-links)
3590 (org-font-lock-extra-keywords
3591 (list
3592 ;; Headlines
3593 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3594 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3595 ;; Table lines
3596 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3597 (1 'org-table t))
3598 ;; Table internals
3599 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3600 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3601 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3602 ;; Drawers
3603 (list org-drawer-regexp '(0 'org-special-keyword t))
3604 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3605 ;; Properties
3606 (list org-property-re
3607 '(1 'org-special-keyword t)
3608 '(3 'org-property-value t))
3609 (if org-format-transports-properties-p
3610 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3611 ;; Links
3612 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3613 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3614 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3615 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3616 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3617 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3618 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3619 '(org-hide-wide-columns (0 nil append))
3620 ;; TODO lines
3621 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3622 '(1 (org-get-todo-face 1) t))
3623 ;; DONE
3624 (if org-fontify-done-headline
3625 (list (concat "^[*]+ +\\<\\("
3626 (mapconcat 'regexp-quote org-done-keywords "\\|")
3627 "\\)\\(.*\\)")
3628 '(2 'org-headline-done t))
3629 nil)
3630 ;; Priorities
3631 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3632 ;; Special keywords
3633 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3634 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3635 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3636 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3637 ;; Emphasis
3638 (if em
3639 (if (featurep 'xemacs)
3640 '(org-do-emphasis-faces (0 nil append))
3641 '(org-do-emphasis-faces)))
3642 ;; Checkboxes
3643 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3644 2 'bold prepend)
3645 (if org-provide-checkbox-statistics
3646 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3647 (0 (org-get-checkbox-statistics-face) t)))
3648 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3649 '(1 'org-archived prepend))
3650 ;; Specials
3651 '(org-do-latex-and-special-faces)
3652 ;; Code
3653 '(org-activate-code (1 'org-code t))
3654 ;; COMMENT
3655 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3656 "\\|" org-quote-string "\\)\\>")
3657 '(1 'org-special-keyword t))
3658 '("^#.*" (0 'font-lock-comment-face t))
3660 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3661 ;; Now set the full font-lock-keywords
3662 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3663 (org-set-local 'font-lock-defaults
3664 '(org-font-lock-keywords t nil nil backward-paragraph))
3665 (kill-local-variable 'font-lock-keywords) nil))
3667 (defvar org-m nil)
3668 (defvar org-l nil)
3669 (defvar org-f nil)
3670 (defun org-get-level-face (n)
3671 "Get the right face for match N in font-lock matching of healdines."
3672 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3673 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3674 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3675 (cond
3676 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3677 ((eq n 2) org-f)
3678 (t (if org-level-color-stars-only nil org-f))))
3680 (defun org-get-todo-face (kwd)
3681 "Get the right face for a TODO keyword KWD.
3682 If KWD is a number, get the corresponding match group."
3683 (if (numberp kwd) (setq kwd (match-string kwd)))
3684 (or (cdr (assoc kwd org-todo-keyword-faces))
3685 (and (member kwd org-done-keywords) 'org-done)
3686 'org-todo))
3688 (defun org-unfontify-region (beg end &optional maybe_loudly)
3689 "Remove fontification and activation overlays from links."
3690 (font-lock-default-unfontify-region beg end)
3691 (let* ((buffer-undo-list t)
3692 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3693 (inhibit-modification-hooks t)
3694 deactivate-mark buffer-file-name buffer-file-truename)
3695 (remove-text-properties beg end
3696 '(mouse-face t keymap t org-linked-text t
3697 invisible t intangible t))))
3699 ;;;; Visibility cycling, including org-goto and indirect buffer
3701 ;;; Cycling
3703 (defvar org-cycle-global-status nil)
3704 (make-variable-buffer-local 'org-cycle-global-status)
3705 (defvar org-cycle-subtree-status nil)
3706 (make-variable-buffer-local 'org-cycle-subtree-status)
3708 ;;;###autoload
3709 (defun org-cycle (&optional arg)
3710 "Visibility cycling for Org-mode.
3712 - When this function is called with a prefix argument, rotate the entire
3713 buffer through 3 states (global cycling)
3714 1. OVERVIEW: Show only top-level headlines.
3715 2. CONTENTS: Show all headlines of all levels, but no body text.
3716 3. SHOW ALL: Show everything.
3718 - When point is at the beginning of a headline, rotate the subtree started
3719 by this line through 3 different states (local cycling)
3720 1. FOLDED: Only the main headline is shown.
3721 2. CHILDREN: The main headline and the direct children are shown.
3722 From this state, you can move to one of the children
3723 and zoom in further.
3724 3. SUBTREE: Show the entire subtree, including body text.
3726 - When there is a numeric prefix, go up to a heading with level ARG, do
3727 a `show-subtree' and return to the previous cursor position. If ARG
3728 is negative, go up that many levels.
3730 - When point is not at the beginning of a headline, execute
3731 `indent-relative', like TAB normally does. See the option
3732 `org-cycle-emulate-tab' for details.
3734 - Special case: if point is at the beginning of the buffer and there is
3735 no headline in line 1, this function will act as if called with prefix arg.
3736 But only if also the variable `org-cycle-global-at-bob' is t."
3737 (interactive "P")
3738 (org-load-modules-maybe)
3739 (let* ((outline-regexp
3740 (if (and (org-mode-p) org-cycle-include-plain-lists)
3741 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3742 outline-regexp))
3743 (bob-special (and org-cycle-global-at-bob (bobp)
3744 (not (looking-at outline-regexp))))
3745 (org-cycle-hook
3746 (if bob-special
3747 (delq 'org-optimize-window-after-visibility-change
3748 (copy-sequence org-cycle-hook))
3749 org-cycle-hook))
3750 (pos (point)))
3752 (if (or bob-special (equal arg '(4)))
3753 ;; special case: use global cycling
3754 (setq arg t))
3756 (cond
3758 ((org-at-table-p 'any)
3759 ;; Enter the table or move to the next field in the table
3760 (or (org-table-recognize-table.el)
3761 (progn
3762 (if arg (org-table-edit-field t)
3763 (org-table-justify-field-maybe)
3764 (call-interactively 'org-table-next-field)))))
3766 ((eq arg t) ;; Global cycling
3768 (cond
3769 ((and (eq last-command this-command)
3770 (eq org-cycle-global-status 'overview))
3771 ;; We just created the overview - now do table of contents
3772 ;; This can be slow in very large buffers, so indicate action
3773 (message "CONTENTS...")
3774 (org-content)
3775 (message "CONTENTS...done")
3776 (setq org-cycle-global-status 'contents)
3777 (run-hook-with-args 'org-cycle-hook 'contents))
3779 ((and (eq last-command this-command)
3780 (eq org-cycle-global-status 'contents))
3781 ;; We just showed the table of contents - now show everything
3782 (show-all)
3783 (message "SHOW ALL")
3784 (setq org-cycle-global-status 'all)
3785 (run-hook-with-args 'org-cycle-hook 'all))
3788 ;; Default action: go to overview
3789 (org-overview)
3790 (message "OVERVIEW")
3791 (setq org-cycle-global-status 'overview)
3792 (run-hook-with-args 'org-cycle-hook 'overview))))
3794 ((and org-drawers org-drawer-regexp
3795 (save-excursion
3796 (beginning-of-line 1)
3797 (looking-at org-drawer-regexp)))
3798 ;; Toggle block visibility
3799 (org-flag-drawer
3800 (not (get-char-property (match-end 0) 'invisible))))
3802 ((integerp arg)
3803 ;; Show-subtree, ARG levels up from here.
3804 (save-excursion
3805 (org-back-to-heading)
3806 (outline-up-heading (if (< arg 0) (- arg)
3807 (- (funcall outline-level) arg)))
3808 (org-show-subtree)))
3810 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3811 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3812 ;; At a heading: rotate between three different views
3813 (org-back-to-heading)
3814 (let ((goal-column 0) eoh eol eos)
3815 ;; First, some boundaries
3816 (save-excursion
3817 (org-back-to-heading)
3818 (save-excursion
3819 (beginning-of-line 2)
3820 (while (and (not (eobp)) ;; this is like `next-line'
3821 (get-char-property (1- (point)) 'invisible))
3822 (beginning-of-line 2)) (setq eol (point)))
3823 (outline-end-of-heading) (setq eoh (point))
3824 (org-end-of-subtree t)
3825 (unless (eobp)
3826 (skip-chars-forward " \t\n")
3827 (beginning-of-line 1) ; in case this is an item
3829 (setq eos (1- (point))))
3830 ;; Find out what to do next and set `this-command'
3831 (cond
3832 ((= eos eoh)
3833 ;; Nothing is hidden behind this heading
3834 (message "EMPTY ENTRY")
3835 (setq org-cycle-subtree-status nil)
3836 (save-excursion
3837 (goto-char eos)
3838 (outline-next-heading)
3839 (if (org-invisible-p) (org-flag-heading nil))))
3840 ((or (>= eol eos)
3841 (not (string-match "\\S-" (buffer-substring eol eos))))
3842 ;; Entire subtree is hidden in one line: open it
3843 (org-show-entry)
3844 (show-children)
3845 (message "CHILDREN")
3846 (save-excursion
3847 (goto-char eos)
3848 (outline-next-heading)
3849 (if (org-invisible-p) (org-flag-heading nil)))
3850 (setq org-cycle-subtree-status 'children)
3851 (run-hook-with-args 'org-cycle-hook 'children))
3852 ((and (eq last-command this-command)
3853 (eq org-cycle-subtree-status 'children))
3854 ;; We just showed the children, now show everything.
3855 (org-show-subtree)
3856 (message "SUBTREE")
3857 (setq org-cycle-subtree-status 'subtree)
3858 (run-hook-with-args 'org-cycle-hook 'subtree))
3860 ;; Default action: hide the subtree.
3861 (hide-subtree)
3862 (message "FOLDED")
3863 (setq org-cycle-subtree-status 'folded)
3864 (run-hook-with-args 'org-cycle-hook 'folded)))))
3866 ;; TAB emulation
3867 (buffer-read-only (org-back-to-heading))
3869 ((org-try-cdlatex-tab))
3871 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
3872 (or (not (bolp))
3873 (not (looking-at outline-regexp))))
3874 (call-interactively (global-key-binding "\t")))
3876 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3877 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3878 (or (and (eq org-cycle-emulate-tab 'white)
3879 (= (match-end 0) (point-at-eol)))
3880 (and (eq org-cycle-emulate-tab 'whitestart)
3881 (>= (match-end 0) pos))))
3883 (eq org-cycle-emulate-tab t))
3884 (call-interactively (global-key-binding "\t")))
3886 (t (save-excursion
3887 (org-back-to-heading)
3888 (org-cycle))))))
3890 ;;;###autoload
3891 (defun org-global-cycle (&optional arg)
3892 "Cycle the global visibility. For details see `org-cycle'."
3893 (interactive "P")
3894 (let ((org-cycle-include-plain-lists
3895 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3896 (if (integerp arg)
3897 (progn
3898 (show-all)
3899 (hide-sublevels arg)
3900 (setq org-cycle-global-status 'contents))
3901 (org-cycle '(4)))))
3903 (defun org-overview ()
3904 "Switch to overview mode, shoing only top-level headlines.
3905 Really, this shows all headlines with level equal or greater than the level
3906 of the first headline in the buffer. This is important, because if the
3907 first headline is not level one, then (hide-sublevels 1) gives confusing
3908 results."
3909 (interactive)
3910 (let ((level (save-excursion
3911 (goto-char (point-min))
3912 (if (re-search-forward (concat "^" outline-regexp) nil t)
3913 (progn
3914 (goto-char (match-beginning 0))
3915 (funcall outline-level))))))
3916 (and level (hide-sublevels level))))
3918 (defun org-content (&optional arg)
3919 "Show all headlines in the buffer, like a table of contents.
3920 With numerical argument N, show content up to level N."
3921 (interactive "P")
3922 (save-excursion
3923 ;; Visit all headings and show their offspring
3924 (and (integerp arg) (org-overview))
3925 (goto-char (point-max))
3926 (catch 'exit
3927 (while (and (progn (condition-case nil
3928 (outline-previous-visible-heading 1)
3929 (error (goto-char (point-min))))
3931 (looking-at outline-regexp))
3932 (if (integerp arg)
3933 (show-children (1- arg))
3934 (show-branches))
3935 (if (bobp) (throw 'exit nil))))))
3938 (defun org-optimize-window-after-visibility-change (state)
3939 "Adjust the window after a change in outline visibility.
3940 This function is the default value of the hook `org-cycle-hook'."
3941 (when (get-buffer-window (current-buffer))
3942 (cond
3943 ; ((eq state 'overview) (org-first-headline-recenter 1))
3944 ; ((eq state 'overview) (org-beginning-of-line))
3945 ((eq state 'content) nil)
3946 ((eq state 'all) nil)
3947 ((eq state 'folded) nil)
3948 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3949 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3951 (defun org-compact-display-after-subtree-move ()
3952 (let (beg end)
3953 (save-excursion
3954 (if (org-up-heading-safe)
3955 (progn
3956 (hide-subtree)
3957 (show-entry)
3958 (show-children)
3959 (org-cycle-show-empty-lines 'children)
3960 (org-cycle-hide-drawers 'children))
3961 (org-overview)))))
3963 (defun org-cycle-show-empty-lines (state)
3964 "Show empty lines above all visible headlines.
3965 The region to be covered depends on STATE when called through
3966 `org-cycle-hook'. Lisp program can use t for STATE to get the
3967 entire buffer covered. Note that an empty line is only shown if there
3968 are at least `org-cycle-separator-lines' empty lines before the headeline."
3969 (when (> org-cycle-separator-lines 0)
3970 (save-excursion
3971 (let* ((n org-cycle-separator-lines)
3972 (re (cond
3973 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
3974 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
3975 (t (let ((ns (number-to-string (- n 2))))
3976 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
3977 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
3978 beg end)
3979 (cond
3980 ((memq state '(overview contents t))
3981 (setq beg (point-min) end (point-max)))
3982 ((memq state '(children folded))
3983 (setq beg (point) end (progn (org-end-of-subtree t t)
3984 (beginning-of-line 2)
3985 (point)))))
3986 (when beg
3987 (goto-char beg)
3988 (while (re-search-forward re end t)
3989 (if (not (get-char-property (match-end 1) 'invisible))
3990 (outline-flag-region
3991 (match-beginning 1) (match-end 1) nil)))))))
3992 ;; Never hide empty lines at the end of the file.
3993 (save-excursion
3994 (goto-char (point-max))
3995 (outline-previous-heading)
3996 (outline-end-of-heading)
3997 (if (and (looking-at "[ \t\n]+")
3998 (= (match-end 0) (point-max)))
3999 (outline-flag-region (point) (match-end 0) nil))))
4001 (defun org-cycle-hide-drawers (state)
4002 "Re-hide all drawers after a visibility state change."
4003 (when (and (org-mode-p)
4004 (not (memq state '(overview folded))))
4005 (save-excursion
4006 (let* ((globalp (memq state '(contents all)))
4007 (beg (if globalp (point-min) (point)))
4008 (end (if globalp (point-max) (org-end-of-subtree t))))
4009 (goto-char beg)
4010 (while (re-search-forward org-drawer-regexp end t)
4011 (org-flag-drawer t))))))
4013 (defun org-flag-drawer (flag)
4014 (save-excursion
4015 (beginning-of-line 1)
4016 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4017 (let ((b (match-end 0))
4018 (outline-regexp org-outline-regexp))
4019 (if (re-search-forward
4020 "^[ \t]*:END:"
4021 (save-excursion (outline-next-heading) (point)) t)
4022 (outline-flag-region b (point-at-eol) flag)
4023 (error ":END: line missing"))))))
4027 (defun org-subtree-end-visible-p ()
4028 "Is the end of the current subtree visible?"
4029 (pos-visible-in-window-p
4030 (save-excursion (org-end-of-subtree t) (point))))
4032 (defun org-first-headline-recenter (&optional N)
4033 "Move cursor to the first headline and recenter the headline.
4034 Optional argument N means, put the headline into the Nth line of the window."
4035 (goto-char (point-min))
4036 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4037 (beginning-of-line)
4038 (recenter (prefix-numeric-value N))))
4040 ;;; Org-goto
4042 (defvar org-goto-window-configuration nil)
4043 (defvar org-goto-marker nil)
4044 (defvar org-goto-map
4045 (let ((map (make-sparse-keymap)))
4046 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4047 (while (setq cmd (pop cmds))
4048 (substitute-key-definition cmd cmd map global-map)))
4049 (suppress-keymap map)
4050 (org-defkey map "\C-m" 'org-goto-ret)
4051 (org-defkey map [(return)] 'org-goto-ret)
4052 (org-defkey map [(left)] 'org-goto-left)
4053 (org-defkey map [(right)] 'org-goto-right)
4054 (org-defkey map [(control ?g)] 'org-goto-quit)
4055 (org-defkey map "\C-i" 'org-cycle)
4056 (org-defkey map [(tab)] 'org-cycle)
4057 (org-defkey map [(down)] 'outline-next-visible-heading)
4058 (org-defkey map [(up)] 'outline-previous-visible-heading)
4059 (if org-goto-auto-isearch
4060 (if (fboundp 'define-key-after)
4061 (define-key-after map [t] 'org-goto-local-auto-isearch)
4062 nil)
4063 (org-defkey map "q" 'org-goto-quit)
4064 (org-defkey map "n" 'outline-next-visible-heading)
4065 (org-defkey map "p" 'outline-previous-visible-heading)
4066 (org-defkey map "f" 'outline-forward-same-level)
4067 (org-defkey map "b" 'outline-backward-same-level)
4068 (org-defkey map "u" 'outline-up-heading))
4069 (org-defkey map "/" 'org-occur)
4070 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4071 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4072 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4073 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4074 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4075 map))
4077 (defconst org-goto-help
4078 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4079 RET=jump to location [Q]uit and return to previous location
4080 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4082 (defvar org-goto-start-pos) ; dynamically scoped parameter
4084 (defun org-goto (&optional alternative-interface)
4085 "Look up a different location in the current file, keeping current visibility.
4087 When you want look-up or go to a different location in a document, the
4088 fastest way is often to fold the entire buffer and then dive into the tree.
4089 This method has the disadvantage, that the previous location will be folded,
4090 which may not be what you want.
4092 This command works around this by showing a copy of the current buffer
4093 in an indirect buffer, in overview mode. You can dive into the tree in
4094 that copy, use org-occur and incremental search to find a location.
4095 When pressing RET or `Q', the command returns to the original buffer in
4096 which the visibility is still unchanged. After RET is will also jump to
4097 the location selected in the indirect buffer and expose the
4098 the headline hierarchy above."
4099 (interactive "P")
4100 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4101 (org-refile-use-outline-path t)
4102 (interface
4103 (if (not alternative-interface)
4104 org-goto-interface
4105 (if (eq org-goto-interface 'outline)
4106 'outline-path-completion
4107 'outline)))
4108 (org-goto-start-pos (point))
4109 (selected-point
4110 (if (eq interface 'outline)
4111 (car (org-get-location (current-buffer) org-goto-help))
4112 (nth 3 (org-refile-get-location "Goto: ")))))
4113 (if selected-point
4114 (progn
4115 (org-mark-ring-push org-goto-start-pos)
4116 (goto-char selected-point)
4117 (if (or (org-invisible-p) (org-invisible-p2))
4118 (org-show-context 'org-goto)))
4119 (message "Quit"))))
4121 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4122 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4123 (defvar org-goto-local-auto-isearch-map) ; defined below
4125 (defun org-get-location (buf help)
4126 "Let the user select a location in the Org-mode buffer BUF.
4127 This function uses a recursive edit. It returns the selected position
4128 or nil."
4129 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4130 (isearch-hide-immediately nil)
4131 (isearch-search-fun-function
4132 (lambda () 'org-goto-local-search-forward-headings))
4133 (org-goto-selected-point org-goto-exit-command))
4134 (save-excursion
4135 (save-window-excursion
4136 (delete-other-windows)
4137 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4138 (switch-to-buffer
4139 (condition-case nil
4140 (make-indirect-buffer (current-buffer) "*org-goto*")
4141 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4142 (with-output-to-temp-buffer "*Help*"
4143 (princ help))
4144 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4145 (setq buffer-read-only nil)
4146 (let ((org-startup-truncated t)
4147 (org-startup-folded nil)
4148 (org-startup-align-all-tables nil))
4149 (org-mode)
4150 (org-overview))
4151 (setq buffer-read-only t)
4152 (if (and (boundp 'org-goto-start-pos)
4153 (integer-or-marker-p org-goto-start-pos))
4154 (let ((org-show-hierarchy-above t)
4155 (org-show-siblings t)
4156 (org-show-following-heading t))
4157 (goto-char org-goto-start-pos)
4158 (and (org-invisible-p) (org-show-context)))
4159 (goto-char (point-min)))
4160 (org-beginning-of-line)
4161 (message "Select location and press RET")
4162 (use-local-map org-goto-map)
4163 (recursive-edit)
4165 (kill-buffer "*org-goto*")
4166 (cons org-goto-selected-point org-goto-exit-command)))
4168 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4169 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4170 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4171 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4173 (defun org-goto-local-search-forward-headings (string bound noerror)
4174 "Search and make sure that anu matches are in headlines."
4175 (catch 'return
4176 (while (search-forward string bound noerror)
4177 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4178 (and (member :headline context)
4179 (not (member :tags context))))
4180 (throw 'return (point))))))
4182 (defun org-goto-local-auto-isearch ()
4183 "Start isearch."
4184 (interactive)
4185 (goto-char (point-min))
4186 (let ((keys (this-command-keys)))
4187 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4188 (isearch-mode t)
4189 (isearch-process-search-char (string-to-char keys)))))
4191 (defun org-goto-ret (&optional arg)
4192 "Finish `org-goto' by going to the new location."
4193 (interactive "P")
4194 (setq org-goto-selected-point (point)
4195 org-goto-exit-command 'return)
4196 (throw 'exit nil))
4198 (defun org-goto-left ()
4199 "Finish `org-goto' by going to the new location."
4200 (interactive)
4201 (if (org-on-heading-p)
4202 (progn
4203 (beginning-of-line 1)
4204 (setq org-goto-selected-point (point)
4205 org-goto-exit-command 'left)
4206 (throw 'exit nil))
4207 (error "Not on a heading")))
4209 (defun org-goto-right ()
4210 "Finish `org-goto' by going to the new location."
4211 (interactive)
4212 (if (org-on-heading-p)
4213 (progn
4214 (setq org-goto-selected-point (point)
4215 org-goto-exit-command 'right)
4216 (throw 'exit nil))
4217 (error "Not on a heading")))
4219 (defun org-goto-quit ()
4220 "Finish `org-goto' without cursor motion."
4221 (interactive)
4222 (setq org-goto-selected-point nil)
4223 (setq org-goto-exit-command 'quit)
4224 (throw 'exit nil))
4226 ;;; Indirect buffer display of subtrees
4228 (defvar org-indirect-dedicated-frame nil
4229 "This is the frame being used for indirect tree display.")
4230 (defvar org-last-indirect-buffer nil)
4232 (defun org-tree-to-indirect-buffer (&optional arg)
4233 "Create indirect buffer and narrow it to current subtree.
4234 With numerical prefix ARG, go up to this level and then take that tree.
4235 If ARG is negative, go up that many levels.
4236 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4237 indirect buffer previously made with this command, to avoid proliferation of
4238 indirect buffers. However, when you call the command with a `C-u' prefix, or
4239 when `org-indirect-buffer-display' is `new-frame', the last buffer
4240 is kept so that you can work with several indirect buffers at the same time.
4241 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4242 requests that a new frame be made for the new buffer, so that the dedicated
4243 frame is not changed."
4244 (interactive "P")
4245 (let ((cbuf (current-buffer))
4246 (cwin (selected-window))
4247 (pos (point))
4248 beg end level heading ibuf)
4249 (save-excursion
4250 (org-back-to-heading t)
4251 (when (numberp arg)
4252 (setq level (org-outline-level))
4253 (if (< arg 0) (setq arg (+ level arg)))
4254 (while (> (setq level (org-outline-level)) arg)
4255 (outline-up-heading 1 t)))
4256 (setq beg (point)
4257 heading (org-get-heading))
4258 (org-end-of-subtree t) (setq end (point)))
4259 (if (and (buffer-live-p org-last-indirect-buffer)
4260 (not (eq org-indirect-buffer-display 'new-frame))
4261 (not arg))
4262 (kill-buffer org-last-indirect-buffer))
4263 (setq ibuf (org-get-indirect-buffer cbuf)
4264 org-last-indirect-buffer ibuf)
4265 (cond
4266 ((or (eq org-indirect-buffer-display 'new-frame)
4267 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4268 (select-frame (make-frame))
4269 (delete-other-windows)
4270 (switch-to-buffer ibuf)
4271 (org-set-frame-title heading))
4272 ((eq org-indirect-buffer-display 'dedicated-frame)
4273 (raise-frame
4274 (select-frame (or (and org-indirect-dedicated-frame
4275 (frame-live-p org-indirect-dedicated-frame)
4276 org-indirect-dedicated-frame)
4277 (setq org-indirect-dedicated-frame (make-frame)))))
4278 (delete-other-windows)
4279 (switch-to-buffer ibuf)
4280 (org-set-frame-title (concat "Indirect: " heading)))
4281 ((eq org-indirect-buffer-display 'current-window)
4282 (switch-to-buffer ibuf))
4283 ((eq org-indirect-buffer-display 'other-window)
4284 (pop-to-buffer ibuf))
4285 (t (error "Invalid value.")))
4286 (if (featurep 'xemacs)
4287 (save-excursion (org-mode) (turn-on-font-lock)))
4288 (narrow-to-region beg end)
4289 (show-all)
4290 (goto-char pos)
4291 (and (window-live-p cwin) (select-window cwin))))
4293 (defun org-get-indirect-buffer (&optional buffer)
4294 (setq buffer (or buffer (current-buffer)))
4295 (let ((n 1) (base (buffer-name buffer)) bname)
4296 (while (buffer-live-p
4297 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4298 (setq n (1+ n)))
4299 (condition-case nil
4300 (make-indirect-buffer buffer bname 'clone)
4301 (error (make-indirect-buffer buffer bname)))))
4303 (defun org-set-frame-title (title)
4304 "Set the title of the current frame to the string TITLE."
4305 ;; FIXME: how to name a single frame in XEmacs???
4306 (unless (featurep 'xemacs)
4307 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4309 ;;;; Structure editing
4311 ;;; Inserting headlines
4313 (defun org-insert-heading (&optional force-heading)
4314 "Insert a new heading or item with same depth at point.
4315 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4316 If point is at the beginning of a headline, insert a sibling before the
4317 current headline. If point is not at the beginning, do not split the line,
4318 but create the new hedline after the current line."
4319 (interactive "P")
4320 (if (= (buffer-size) 0)
4321 (insert "\n* ")
4322 (when (or force-heading (not (org-insert-item)))
4323 (let* ((head (save-excursion
4324 (condition-case nil
4325 (progn
4326 (org-back-to-heading)
4327 (match-string 0))
4328 (error "*"))))
4329 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4330 pos)
4331 (cond
4332 ((and (org-on-heading-p) (bolp)
4333 (or (bobp)
4334 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4335 ;; insert before the current line
4336 (open-line (if blank 2 1)))
4337 ((and (bolp)
4338 (or (bobp)
4339 (save-excursion
4340 (backward-char 1) (not (org-invisible-p)))))
4341 ;; insert right here
4342 nil)
4344 ;; in the middle of the line
4345 (org-show-entry)
4346 (let ((split
4347 (org-get-alist-option org-M-RET-may-split-line 'headline))
4348 tags pos)
4349 (if (org-on-heading-p)
4350 (progn
4351 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4352 (setq tags (and (match-end 2) (match-string 2)))
4353 (and (match-end 1)
4354 (delete-region (match-beginning 1) (match-end 1)))
4355 (setq pos (point-at-bol))
4356 (or split (end-of-line 1))
4357 (delete-horizontal-space)
4358 (newline (if blank 2 1))
4359 (when tags
4360 (save-excursion
4361 (goto-char pos)
4362 (end-of-line 1)
4363 (insert " " tags)
4364 (org-set-tags nil 'align))))
4365 (or split (end-of-line 1))
4366 (newline (if blank 2 1))))))
4367 (insert head) (just-one-space)
4368 (setq pos (point))
4369 (end-of-line 1)
4370 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4371 (run-hooks 'org-insert-heading-hook)))))
4373 (defun org-get-heading (&optional no-tags)
4374 "Return the heading of the current entry, without the stars."
4375 (save-excursion
4376 (org-back-to-heading t)
4377 (if (looking-at
4378 (if no-tags
4379 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4380 "\\*+[ \t]+\\([^\r\n]*\\)"))
4381 (match-string 1) "")))
4383 (defun org-insert-heading-after-current ()
4384 "Insert a new heading with same level as current, after current subtree."
4385 (interactive)
4386 (org-back-to-heading)
4387 (org-insert-heading)
4388 (org-move-subtree-down)
4389 (end-of-line 1))
4391 (defun org-insert-todo-heading (arg)
4392 "Insert a new heading with the same level and TODO state as current heading.
4393 If the heading has no TODO state, or if the state is DONE, use the first
4394 state (TODO by default). Also with prefix arg, force first state."
4395 (interactive "P")
4396 (when (not (org-insert-item 'checkbox))
4397 (org-insert-heading)
4398 (save-excursion
4399 (org-back-to-heading)
4400 (outline-previous-heading)
4401 (looking-at org-todo-line-regexp))
4402 (if (or arg
4403 (not (match-beginning 2))
4404 (member (match-string 2) org-done-keywords))
4405 (insert (car org-todo-keywords-1) " ")
4406 (insert (match-string 2) " "))))
4408 (defun org-insert-subheading (arg)
4409 "Insert a new subheading and demote it.
4410 Works for outline headings and for plain lists alike."
4411 (interactive "P")
4412 (org-insert-heading arg)
4413 (cond
4414 ((org-on-heading-p) (org-do-demote))
4415 ((org-at-item-p) (org-indent-item 1))))
4417 (defun org-insert-todo-subheading (arg)
4418 "Insert a new subheading with TODO keyword or checkbox and demote it.
4419 Works for outline headings and for plain lists alike."
4420 (interactive "P")
4421 (org-insert-todo-heading arg)
4422 (cond
4423 ((org-on-heading-p) (org-do-demote))
4424 ((org-at-item-p) (org-indent-item 1))))
4426 ;;; Promotion and Demotion
4428 (defun org-promote-subtree ()
4429 "Promote the entire subtree.
4430 See also `org-promote'."
4431 (interactive)
4432 (save-excursion
4433 (org-map-tree 'org-promote))
4434 (org-fix-position-after-promote))
4436 (defun org-demote-subtree ()
4437 "Demote the entire subtree. See `org-demote'.
4438 See also `org-promote'."
4439 (interactive)
4440 (save-excursion
4441 (org-map-tree 'org-demote))
4442 (org-fix-position-after-promote))
4445 (defun org-do-promote ()
4446 "Promote the current heading higher up the tree.
4447 If the region is active in `transient-mark-mode', promote all headings
4448 in the region."
4449 (interactive)
4450 (save-excursion
4451 (if (org-region-active-p)
4452 (org-map-region 'org-promote (region-beginning) (region-end))
4453 (org-promote)))
4454 (org-fix-position-after-promote))
4456 (defun org-do-demote ()
4457 "Demote the current heading lower down the tree.
4458 If the region is active in `transient-mark-mode', demote all headings
4459 in the region."
4460 (interactive)
4461 (save-excursion
4462 (if (org-region-active-p)
4463 (org-map-region 'org-demote (region-beginning) (region-end))
4464 (org-demote)))
4465 (org-fix-position-after-promote))
4467 (defun org-fix-position-after-promote ()
4468 "Make sure that after pro/demotion cursor position is right."
4469 (let ((pos (point)))
4470 (when (save-excursion
4471 (beginning-of-line 1)
4472 (looking-at org-todo-line-regexp)
4473 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4474 (cond ((eobp) (insert " "))
4475 ((eolp) (insert " "))
4476 ((equal (char-after) ?\ ) (forward-char 1))))))
4478 (defun org-reduced-level (l)
4479 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4481 (defun org-get-valid-level (level &optional change)
4482 "Rectify a level change under the influence of `org-odd-levels-only'
4483 LEVEL is a current level, CHANGE is by how much the level should be
4484 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4485 even level numbers will become the next higher odd number."
4486 (if org-odd-levels-only
4487 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4488 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4489 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4490 (max 1 (+ level change))))
4492 (if (boundp 'define-obsolete-function-alias)
4493 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4494 (define-obsolete-function-alias 'org-get-legal-level
4495 'org-get-valid-level)
4496 (define-obsolete-function-alias 'org-get-legal-level
4497 'org-get-valid-level "23.1")))
4499 (defun org-promote ()
4500 "Promote the current heading higher up the tree.
4501 If the region is active in `transient-mark-mode', promote all headings
4502 in the region."
4503 (org-back-to-heading t)
4504 (let* ((level (save-match-data (funcall outline-level)))
4505 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4506 (diff (abs (- level (length up-head) -1))))
4507 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4508 (replace-match up-head nil t)
4509 ;; Fixup tag positioning
4510 (and org-auto-align-tags (org-set-tags nil t))
4511 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4513 (defun org-demote ()
4514 "Demote the current heading lower down the tree.
4515 If the region is active in `transient-mark-mode', demote all headings
4516 in the region."
4517 (org-back-to-heading t)
4518 (let* ((level (save-match-data (funcall outline-level)))
4519 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4520 (diff (abs (- level (length down-head) -1))))
4521 (replace-match down-head nil t)
4522 ;; Fixup tag positioning
4523 (and org-auto-align-tags (org-set-tags nil t))
4524 (if org-adapt-indentation (org-fixup-indentation diff))))
4526 (defun org-map-tree (fun)
4527 "Call FUN for every heading underneath the current one."
4528 (org-back-to-heading)
4529 (let ((level (funcall outline-level)))
4530 (save-excursion
4531 (funcall fun)
4532 (while (and (progn
4533 (outline-next-heading)
4534 (> (funcall outline-level) level))
4535 (not (eobp)))
4536 (funcall fun)))))
4538 (defun org-map-region (fun beg end)
4539 "Call FUN for every heading between BEG and END."
4540 (let ((org-ignore-region t))
4541 (save-excursion
4542 (setq end (copy-marker end))
4543 (goto-char beg)
4544 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4545 (< (point) end))
4546 (funcall fun))
4547 (while (and (progn
4548 (outline-next-heading)
4549 (< (point) end))
4550 (not (eobp)))
4551 (funcall fun)))))
4553 (defun org-fixup-indentation (diff)
4554 "Change the indentation in the current entry by DIFF
4555 However, if any line in the current entry has no indentation, or if it
4556 would end up with no indentation after the change, nothing at all is done."
4557 (save-excursion
4558 (let ((end (save-excursion (outline-next-heading)
4559 (point-marker)))
4560 (prohibit (if (> diff 0)
4561 "^\\S-"
4562 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4563 col)
4564 (unless (save-excursion (end-of-line 1)
4565 (re-search-forward prohibit end t))
4566 (while (and (< (point) end)
4567 (re-search-forward "^[ \t]+" end t))
4568 (goto-char (match-end 0))
4569 (setq col (current-column))
4570 (if (< diff 0) (replace-match ""))
4571 (indent-to (+ diff col))))
4572 (move-marker end nil))))
4574 (defun org-convert-to-odd-levels ()
4575 "Convert an org-mode file with all levels allowed to one with odd levels.
4576 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4577 level 5 etc."
4578 (interactive)
4579 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4580 (let ((org-odd-levels-only nil) n)
4581 (save-excursion
4582 (goto-char (point-min))
4583 (while (re-search-forward "^\\*\\*+ " nil t)
4584 (setq n (- (length (match-string 0)) 2))
4585 (while (>= (setq n (1- n)) 0)
4586 (org-demote))
4587 (end-of-line 1))))))
4590 (defun org-convert-to-oddeven-levels ()
4591 "Convert an org-mode file with only odd levels to one with odd and even levels.
4592 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4593 section with an even level, conversion would destroy the structure of the file. An error
4594 is signaled in this case."
4595 (interactive)
4596 (goto-char (point-min))
4597 ;; First check if there are no even levels
4598 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4599 (org-show-context t)
4600 (error "Not all levels are odd in this file. Conversion not possible."))
4601 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4602 (let ((org-odd-levels-only nil) n)
4603 (save-excursion
4604 (goto-char (point-min))
4605 (while (re-search-forward "^\\*\\*+ " nil t)
4606 (setq n (/ (1- (length (match-string 0))) 2))
4607 (while (>= (setq n (1- n)) 0)
4608 (org-promote))
4609 (end-of-line 1))))))
4611 (defun org-tr-level (n)
4612 "Make N odd if required."
4613 (if org-odd-levels-only (1+ (/ n 2)) n))
4615 ;;; Vertical tree motion, cutting and pasting of subtrees
4617 (defun org-move-subtree-up (&optional arg)
4618 "Move the current subtree up past ARG headlines of the same level."
4619 (interactive "p")
4620 (org-move-subtree-down (- (prefix-numeric-value arg))))
4622 (defun org-move-subtree-down (&optional arg)
4623 "Move the current subtree down past ARG headlines of the same level."
4624 (interactive "p")
4625 (setq arg (prefix-numeric-value arg))
4626 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4627 'outline-get-last-sibling))
4628 (ins-point (make-marker))
4629 (cnt (abs arg))
4630 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4631 ;; Select the tree
4632 (org-back-to-heading)
4633 (setq beg0 (point))
4634 (save-excursion
4635 (setq ne-beg (org-back-over-empty-lines))
4636 (setq beg (point)))
4637 (save-match-data
4638 (save-excursion (outline-end-of-heading)
4639 (setq folded (org-invisible-p)))
4640 (outline-end-of-subtree))
4641 (outline-next-heading)
4642 (setq ne-end (org-back-over-empty-lines))
4643 (setq end (point))
4644 (goto-char beg0)
4645 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4646 ;; include less whitespace
4647 (save-excursion
4648 (goto-char beg)
4649 (forward-line (- ne-beg ne-end))
4650 (setq beg (point))))
4651 ;; Find insertion point, with error handling
4652 (while (> cnt 0)
4653 (or (and (funcall movfunc) (looking-at outline-regexp))
4654 (progn (goto-char beg0)
4655 (error "Cannot move past superior level or buffer limit")))
4656 (setq cnt (1- cnt)))
4657 (if (> arg 0)
4658 ;; Moving forward - still need to move over subtree
4659 (progn (org-end-of-subtree t t)
4660 (save-excursion
4661 (org-back-over-empty-lines)
4662 (or (bolp) (newline)))))
4663 (setq ne-ins (org-back-over-empty-lines))
4664 (move-marker ins-point (point))
4665 (setq txt (buffer-substring beg end))
4666 (delete-region beg end)
4667 (outline-flag-region (1- beg) beg nil)
4668 (outline-flag-region (1- (point)) (point) nil)
4669 (insert txt)
4670 (or (bolp) (insert "\n"))
4671 (setq ins-end (point))
4672 (goto-char ins-point)
4673 (org-skip-whitespace)
4674 (when (and (< arg 0)
4675 (org-first-sibling-p)
4676 (> ne-ins ne-beg))
4677 ;; Move whitespace back to beginning
4678 (save-excursion
4679 (goto-char ins-end)
4680 (let ((kill-whole-line t))
4681 (kill-line (- ne-ins ne-beg)) (point)))
4682 (insert (make-string (- ne-ins ne-beg) ?\n)))
4683 (move-marker ins-point nil)
4684 (org-compact-display-after-subtree-move)
4685 (unless folded
4686 (org-show-entry)
4687 (show-children)
4688 (org-cycle-hide-drawers 'children))))
4690 (defvar org-subtree-clip ""
4691 "Clipboard for cut and paste of subtrees.
4692 This is actually only a copy of the kill, because we use the normal kill
4693 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4695 (defvar org-subtree-clip-folded nil
4696 "Was the last copied subtree folded?
4697 This is used to fold the tree back after pasting.")
4699 (defun org-cut-subtree (&optional n)
4700 "Cut the current subtree into the clipboard.
4701 With prefix arg N, cut this many sequential subtrees.
4702 This is a short-hand for marking the subtree and then cutting it."
4703 (interactive "p")
4704 (org-copy-subtree n 'cut))
4706 (defun org-copy-subtree (&optional n cut)
4707 "Cut the current subtree into the clipboard.
4708 With prefix arg N, cut this many sequential subtrees.
4709 This is a short-hand for marking the subtree and then copying it.
4710 If CUT is non-nil, actually cut the subtree."
4711 (interactive "p")
4712 (let (beg end folded (beg0 (point)))
4713 (if (interactive-p)
4714 (org-back-to-heading nil) ; take what looks like a subtree
4715 (org-back-to-heading t)) ; take what is really there
4716 (org-back-over-empty-lines)
4717 (setq beg (point))
4718 (skip-chars-forward " \t\r\n")
4719 (save-match-data
4720 (save-excursion (outline-end-of-heading)
4721 (setq folded (org-invisible-p)))
4722 (condition-case nil
4723 (outline-forward-same-level (1- n))
4724 (error nil))
4725 (org-end-of-subtree t t))
4726 (org-back-over-empty-lines)
4727 (setq end (point))
4728 (goto-char beg0)
4729 (when (> end beg)
4730 (setq org-subtree-clip-folded folded)
4731 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4732 (setq org-subtree-clip (current-kill 0))
4733 (message "%s: Subtree(s) with %d characters"
4734 (if cut "Cut" "Copied")
4735 (length org-subtree-clip)))))
4737 (defun org-paste-subtree (&optional level tree)
4738 "Paste the clipboard as a subtree, with modification of headline level.
4739 The entire subtree is promoted or demoted in order to match a new headline
4740 level. By default, the new level is derived from the visible headings
4741 before and after the insertion point, and taken to be the inferior headline
4742 level of the two. So if the previous visible heading is level 3 and the
4743 next is level 4 (or vice versa), level 4 will be used for insertion.
4744 This makes sure that the subtree remains an independent subtree and does
4745 not swallow low level entries.
4747 You can also force a different level, either by using a numeric prefix
4748 argument, or by inserting the heading marker by hand. For example, if the
4749 cursor is after \"*****\", then the tree will be shifted to level 5.
4751 If you want to insert the tree as is, just use \\[yank].
4753 If optional TREE is given, use this text instead of the kill ring."
4754 (interactive "P")
4755 (unless (org-kill-is-subtree-p tree)
4756 (error "%s"
4757 (substitute-command-keys
4758 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4759 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4760 (^re (concat "^\\(" outline-regexp "\\)"))
4761 (re (concat "\\(" outline-regexp "\\)"))
4762 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4764 (old-level (if (string-match ^re txt)
4765 (- (match-end 0) (match-beginning 0) 1)
4766 -1))
4767 (force-level (cond (level (prefix-numeric-value level))
4768 ((string-match
4769 ^re_ (buffer-substring (point-at-bol) (point)))
4770 (- (match-end 1) (match-beginning 1)))
4771 (t nil)))
4772 (previous-level (save-excursion
4773 (condition-case nil
4774 (progn
4775 (outline-previous-visible-heading 1)
4776 (if (looking-at re)
4777 (- (match-end 0) (match-beginning 0) 1)
4779 (error 1))))
4780 (next-level (save-excursion
4781 (condition-case nil
4782 (progn
4783 (or (looking-at outline-regexp)
4784 (outline-next-visible-heading 1))
4785 (if (looking-at re)
4786 (- (match-end 0) (match-beginning 0) 1)
4788 (error 1))))
4789 (new-level (or force-level (max previous-level next-level)))
4790 (shift (if (or (= old-level -1)
4791 (= new-level -1)
4792 (= old-level new-level))
4794 (- new-level old-level)))
4795 (delta (if (> shift 0) -1 1))
4796 (func (if (> shift 0) 'org-demote 'org-promote))
4797 (org-odd-levels-only nil)
4798 beg end)
4799 ;; Remove the forced level indicator
4800 (if force-level
4801 (delete-region (point-at-bol) (point)))
4802 ;; Paste
4803 (beginning-of-line 1)
4804 (org-back-over-empty-lines)
4805 (setq beg (point))
4806 (insert-before-markers txt)
4807 (unless (string-match "\n\\'" txt) (insert "\n"))
4808 (setq end (point))
4809 (goto-char beg)
4810 (skip-chars-forward " \t\n\r")
4811 (setq beg (point))
4812 ;; Shift if necessary
4813 (unless (= shift 0)
4814 (save-restriction
4815 (narrow-to-region beg end)
4816 (while (not (= shift 0))
4817 (org-map-region func (point-min) (point-max))
4818 (setq shift (+ delta shift)))
4819 (goto-char (point-min))))
4820 (when (interactive-p)
4821 (message "Clipboard pasted as level %d subtree" new-level))
4822 (if (and kill-ring
4823 (eq org-subtree-clip (current-kill 0))
4824 org-subtree-clip-folded)
4825 ;; The tree was folded before it was killed/copied
4826 (hide-subtree))))
4828 (defun org-kill-is-subtree-p (&optional txt)
4829 "Check if the current kill is an outline subtree, or a set of trees.
4830 Returns nil if kill does not start with a headline, or if the first
4831 headline level is not the largest headline level in the tree.
4832 So this will actually accept several entries of equal levels as well,
4833 which is OK for `org-paste-subtree'.
4834 If optional TXT is given, check this string instead of the current kill."
4835 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4836 (start-level (and kill
4837 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
4838 org-outline-regexp "\\)")
4839 kill)
4840 (- (match-end 2) (match-beginning 2) 1)))
4841 (re (concat "^" org-outline-regexp))
4842 (start (1+ (match-beginning 2))))
4843 (if (not start-level)
4844 (progn
4845 nil) ;; does not even start with a heading
4846 (catch 'exit
4847 (while (setq start (string-match re kill (1+ start)))
4848 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
4849 (throw 'exit nil)))
4850 t))))
4852 (defun org-narrow-to-subtree ()
4853 "Narrow buffer to the current subtree."
4854 (interactive)
4855 (save-excursion
4856 (save-match-data
4857 (narrow-to-region
4858 (progn (org-back-to-heading) (point))
4859 (progn (org-end-of-subtree t t) (point))))))
4862 ;;; Outline Sorting
4864 (defun org-sort (with-case)
4865 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
4866 Optional argument WITH-CASE means sort case-sensitively."
4867 (interactive "P")
4868 (if (org-at-table-p)
4869 (org-call-with-arg 'org-table-sort-lines with-case)
4870 (org-call-with-arg 'org-sort-entries-or-items with-case)))
4872 (defun org-sort-remove-invisible (s)
4873 (remove-text-properties 0 (length s) org-rm-props s)
4874 (while (string-match org-bracket-link-regexp s)
4875 (setq s (replace-match (if (match-end 2)
4876 (match-string 3 s)
4877 (match-string 1 s)) t t s)))
4880 (defvar org-priority-regexp) ; defined later in the file
4882 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
4883 "Sort entries on a certain level of an outline tree.
4884 If there is an active region, the entries in the region are sorted.
4885 Else, if the cursor is before the first entry, sort the top-level items.
4886 Else, the children of the entry at point are sorted.
4888 Sorting can be alphabetically, numerically, and by date/time as given by
4889 the first time stamp in the entry. The command prompts for the sorting
4890 type unless it has been given to the function through the SORTING-TYPE
4891 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
4892 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
4893 called with point at the beginning of the record. It must return either
4894 a string or a number that should serve as the sorting key for that record.
4896 Comparing entries ignores case by default. However, with an optional argument
4897 WITH-CASE, the sorting considers case as well."
4898 (interactive "P")
4899 (let ((case-func (if with-case 'identity 'downcase))
4900 start beg end stars re re2
4901 txt what tmp plain-list-p)
4902 ;; Find beginning and end of region to sort
4903 (cond
4904 ((org-region-active-p)
4905 ;; we will sort the region
4906 (setq end (region-end)
4907 what "region")
4908 (goto-char (region-beginning))
4909 (if (not (org-on-heading-p)) (outline-next-heading))
4910 (setq start (point)))
4911 ((org-at-item-p)
4912 ;; we will sort this plain list
4913 (org-beginning-of-item-list) (setq start (point))
4914 (org-end-of-item-list) (setq end (point))
4915 (goto-char start)
4916 (setq plain-list-p t
4917 what "plain list"))
4918 ((or (org-on-heading-p)
4919 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
4920 ;; we will sort the children of the current headline
4921 (org-back-to-heading)
4922 (setq start (point)
4923 end (progn (org-end-of-subtree t t)
4924 (org-back-over-empty-lines)
4925 (point))
4926 what "children")
4927 (goto-char start)
4928 (show-subtree)
4929 (outline-next-heading))
4931 ;; we will sort the top-level entries in this file
4932 (goto-char (point-min))
4933 (or (org-on-heading-p) (outline-next-heading))
4934 (setq start (point) end (point-max) what "top-level")
4935 (goto-char start)
4936 (show-all)))
4938 (setq beg (point))
4939 (if (>= beg end) (error "Nothing to sort"))
4941 (unless plain-list-p
4942 (looking-at "\\(\\*+\\)")
4943 (setq stars (match-string 1)
4944 re (concat "^" (regexp-quote stars) " +")
4945 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
4946 txt (buffer-substring beg end))
4947 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
4948 (if (and (not (equal stars "*")) (string-match re2 txt))
4949 (error "Region to sort contains a level above the first entry")))
4951 (unless sorting-type
4952 (message
4953 (if plain-list-p
4954 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
4955 "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:")
4956 what)
4957 (setq sorting-type (read-char-exclusive))
4959 (and (= (downcase sorting-type) ?f)
4960 (setq getkey-func
4961 (completing-read "Sort using function: "
4962 obarray 'fboundp t nil nil))
4963 (setq getkey-func (intern getkey-func)))
4965 (and (= (downcase sorting-type) ?r)
4966 (setq property
4967 (completing-read "Property: "
4968 (mapcar 'list (org-buffer-property-keys t))
4969 nil t))))
4971 (message "Sorting entries...")
4973 (save-restriction
4974 (narrow-to-region start end)
4976 (let ((dcst (downcase sorting-type))
4977 (now (current-time)))
4978 (sort-subr
4979 (/= dcst sorting-type)
4980 ;; This function moves to the beginning character of the "record" to
4981 ;; be sorted.
4982 (if plain-list-p
4983 (lambda nil
4984 (if (org-at-item-p) t (goto-char (point-max))))
4985 (lambda nil
4986 (if (re-search-forward re nil t)
4987 (goto-char (match-beginning 0))
4988 (goto-char (point-max)))))
4989 ;; This function moves to the last character of the "record" being
4990 ;; sorted.
4991 (if plain-list-p
4992 'org-end-of-item
4993 (lambda nil
4994 (save-match-data
4995 (condition-case nil
4996 (outline-forward-same-level 1)
4997 (error
4998 (goto-char (point-max)))))))
5000 ;; This function returns the value that gets sorted against.
5001 (if plain-list-p
5002 (lambda nil
5003 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5004 (cond
5005 ((= dcst ?n)
5006 (string-to-number (buffer-substring (match-end 0)
5007 (point-at-eol))))
5008 ((= dcst ?a)
5009 (buffer-substring (match-end 0) (point-at-eol)))
5010 ((= dcst ?t)
5011 (if (re-search-forward org-ts-regexp
5012 (point-at-eol) t)
5013 (org-time-string-to-time (match-string 0))
5014 now))
5015 ((= dcst ?f)
5016 (if getkey-func
5017 (progn
5018 (setq tmp (funcall getkey-func))
5019 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5020 tmp)
5021 (error "Invalid key function `%s'" getkey-func)))
5022 (t (error "Invalid sorting type `%c'" sorting-type)))))
5023 (lambda nil
5024 (cond
5025 ((= dcst ?n)
5026 (if (looking-at outline-regexp)
5027 (string-to-number (buffer-substring (match-end 0)
5028 (point-at-eol)))
5029 nil))
5030 ((= dcst ?a)
5031 (funcall case-func (buffer-substring (point-at-bol)
5032 (point-at-eol))))
5033 ((= dcst ?t)
5034 (if (re-search-forward org-ts-regexp
5035 (save-excursion
5036 (forward-line 2)
5037 (point)) t)
5038 (org-time-string-to-time (match-string 0))
5039 now))
5040 ((= dcst ?p)
5041 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5042 (string-to-char (match-string 2))
5043 org-default-priority))
5044 ((= dcst ?r)
5045 (or (org-entry-get nil property) ""))
5046 ((= dcst ?o)
5047 (if (looking-at org-complex-heading-regexp)
5048 (- 9999 (length (member (match-string 2)
5049 org-todo-keywords-1)))))
5050 ((= dcst ?f)
5051 (if getkey-func
5052 (progn
5053 (setq tmp (funcall getkey-func))
5054 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5055 tmp)
5056 (error "Invalid key function `%s'" getkey-func)))
5057 (t (error "Invalid sorting type `%c'" sorting-type)))))
5059 (cond
5060 ((= dcst ?a) 'string<)
5061 ((= dcst ?t) 'time-less-p)
5062 (t nil)))))
5063 (message "Sorting entries...done")))
5065 (defun org-do-sort (table what &optional with-case sorting-type)
5066 "Sort TABLE of WHAT according to SORTING-TYPE.
5067 The user will be prompted for the SORTING-TYPE if the call to this
5068 function does not specify it. WHAT is only for the prompt, to indicate
5069 what is being sorted. The sorting key will be extracted from
5070 the car of the elements of the table.
5071 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5072 (unless sorting-type
5073 (message
5074 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5075 what)
5076 (setq sorting-type (read-char-exclusive)))
5077 (let ((dcst (downcase sorting-type))
5078 extractfun comparefun)
5079 ;; Define the appropriate functions
5080 (cond
5081 ((= dcst ?n)
5082 (setq extractfun 'string-to-number
5083 comparefun (if (= dcst sorting-type) '< '>)))
5084 ((= dcst ?a)
5085 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5086 (lambda(x) (downcase (org-sort-remove-invisible x))))
5087 comparefun (if (= dcst sorting-type)
5088 'string<
5089 (lambda (a b) (and (not (string< a b))
5090 (not (string= a b)))))))
5091 ((= dcst ?t)
5092 (setq extractfun
5093 (lambda (x)
5094 (if (string-match org-ts-regexp x)
5095 (time-to-seconds
5096 (org-time-string-to-time (match-string 0 x)))
5098 comparefun (if (= dcst sorting-type) '< '>)))
5099 (t (error "Invalid sorting type `%c'" sorting-type)))
5101 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5102 table)
5103 (lambda (a b) (funcall comparefun (car a) (car b))))))
5105 ;;;; Plain list items, including checkboxes
5107 ;;; Plain list items
5109 (defun org-at-item-p ()
5110 "Is point in a line starting a hand-formatted item?"
5111 (let ((llt org-plain-list-ordered-item-terminator))
5112 (save-excursion
5113 (goto-char (point-at-bol))
5114 (looking-at
5115 (cond
5116 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5117 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5118 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5119 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5121 (defun org-in-item-p ()
5122 "It the cursor inside a plain list item.
5123 Does not have to be the first line."
5124 (save-excursion
5125 (condition-case nil
5126 (progn
5127 (org-beginning-of-item)
5128 (org-at-item-p)
5130 (error nil))))
5132 (defun org-insert-item (&optional checkbox)
5133 "Insert a new item at the current level.
5134 Return t when things worked, nil when we are not in an item."
5135 (when (save-excursion
5136 (condition-case nil
5137 (progn
5138 (org-beginning-of-item)
5139 (org-at-item-p)
5140 (if (org-invisible-p) (error "Invisible item"))
5142 (error nil)))
5143 (let* ((bul (match-string 0))
5144 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5145 (match-end 0)))
5146 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5147 pos)
5148 (cond
5149 ((and (org-at-item-p) (<= (point) eow))
5150 ;; before the bullet
5151 (beginning-of-line 1)
5152 (open-line (if blank 2 1)))
5153 ((<= (point) eow)
5154 (beginning-of-line 1))
5156 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5157 (end-of-line 1)
5158 (delete-horizontal-space))
5159 (newline (if blank 2 1))))
5160 (insert bul (if checkbox "[ ]" ""))
5161 (just-one-space)
5162 (setq pos (point))
5163 (end-of-line 1)
5164 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5165 (org-maybe-renumber-ordered-list)
5166 (and checkbox (org-update-checkbox-count-maybe))
5169 ;;; Checkboxes
5171 (defun org-at-item-checkbox-p ()
5172 "Is point at a line starting a plain-list item with a checklet?"
5173 (and (org-at-item-p)
5174 (save-excursion
5175 (goto-char (match-end 0))
5176 (skip-chars-forward " \t")
5177 (looking-at "\\[[- X]\\]"))))
5179 (defun org-toggle-checkbox (&optional arg)
5180 "Toggle the checkbox in the current line."
5181 (interactive "P")
5182 (catch 'exit
5183 (let (beg end status (firstnew 'unknown))
5184 (cond
5185 ((org-region-active-p)
5186 (setq beg (region-beginning) end (region-end)))
5187 ((org-on-heading-p)
5188 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5189 ((org-at-item-checkbox-p)
5190 (let ((pos (point)))
5191 (replace-match
5192 (cond (arg "[-]")
5193 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5194 (t "[ ]"))
5195 t t)
5196 (goto-char pos))
5197 (throw 'exit t))
5198 (t (error "Not at a checkbox or heading, and no active region")))
5199 (save-excursion
5200 (goto-char beg)
5201 (while (< (point) end)
5202 (when (org-at-item-checkbox-p)
5203 (setq status (equal (match-string 0) "[X]"))
5204 (when (eq firstnew 'unknown)
5205 (setq firstnew (not status)))
5206 (replace-match
5207 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5208 (beginning-of-line 2)))))
5209 (org-update-checkbox-count-maybe))
5211 (defun org-update-checkbox-count-maybe ()
5212 "Update checkbox statistics unless turned off by user."
5213 (when org-provide-checkbox-statistics
5214 (org-update-checkbox-count)))
5216 (defun org-update-checkbox-count (&optional all)
5217 "Update the checkbox statistics in the current section.
5218 This will find all statistic cookies like [57%] and [6/12] and update them
5219 with the current numbers. With optional prefix argument ALL, do this for
5220 the whole buffer."
5221 (interactive "P")
5222 (save-excursion
5223 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5224 (beg (condition-case nil
5225 (progn (outline-back-to-heading) (point))
5226 (error (point-min))))
5227 (end (move-marker (make-marker)
5228 (progn (outline-next-heading) (point))))
5229 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5230 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5231 (re-find (concat re "\\|" re-box))
5232 beg-cookie end-cookie is-percent c-on c-off lim
5233 eline curr-ind next-ind continue-from startsearch
5234 (cstat 0)
5236 (when all
5237 (goto-char (point-min))
5238 (outline-next-heading)
5239 (setq beg (point) end (point-max)))
5240 (goto-char end)
5241 ;; find each statistic cookie
5242 (while (re-search-backward re-find beg t)
5243 (setq beg-cookie (match-beginning 1)
5244 end-cookie (match-end 1)
5245 cstat (+ cstat (if end-cookie 1 0))
5246 startsearch (point-at-eol)
5247 continue-from (point-at-bol)
5248 is-percent (match-beginning 2)
5249 lim (cond
5250 ((org-on-heading-p) (outline-next-heading) (point))
5251 ((org-at-item-p) (org-end-of-item) (point))
5252 (t nil))
5253 c-on 0
5254 c-off 0)
5255 (when lim
5256 ;; find first checkbox for this cookie and gather
5257 ;; statistics from all that are at this indentation level
5258 (goto-char startsearch)
5259 (if (re-search-forward re-box lim t)
5260 (progn
5261 (org-beginning-of-item)
5262 (setq curr-ind (org-get-indentation))
5263 (setq next-ind curr-ind)
5264 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5265 (save-excursion (end-of-line) (setq eline (point)))
5266 (if (re-search-forward re-box eline t)
5267 (if (member (match-string 2) '("[ ]" "[-]"))
5268 (setq c-off (1+ c-off))
5269 (setq c-on (1+ c-on))
5272 (org-end-of-item)
5273 (setq next-ind (org-get-indentation))
5275 (goto-char continue-from)
5276 ;; update cookie
5277 (when end-cookie
5278 (delete-region beg-cookie end-cookie)
5279 (goto-char beg-cookie)
5280 (insert
5281 (if is-percent
5282 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5283 (format "[%d/%d]" c-on (+ c-on c-off)))))
5284 ;; update items checkbox if it has one
5285 (when (org-at-item-p)
5286 (org-beginning-of-item)
5287 (when (and (> (+ c-on c-off) 0)
5288 (re-search-forward re-box (point-at-eol) t))
5289 (setq beg-cookie (match-beginning 2)
5290 end-cookie (match-end 2))
5291 (delete-region beg-cookie end-cookie)
5292 (goto-char beg-cookie)
5293 (cond ((= c-off 0) (insert "[X]"))
5294 ((= c-on 0) (insert "[ ]"))
5295 (t (insert "[-]")))
5297 (goto-char continue-from))
5298 (when (interactive-p)
5299 (message "Checkbox satistics updated %s (%d places)"
5300 (if all "in entire file" "in current outline entry") cstat)))))
5302 (defun org-get-checkbox-statistics-face ()
5303 "Select the face for checkbox statistics.
5304 The face will be `org-done' when all relevant boxes are checked. Otherwise
5305 it will be `org-todo'."
5306 (if (match-end 1)
5307 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5308 (if (and (> (match-end 2) (match-beginning 2))
5309 (equal (match-string 2) (match-string 3)))
5310 'org-done
5311 'org-todo)))
5313 (defun org-get-indentation (&optional line)
5314 "Get the indentation of the current line, interpreting tabs.
5315 When LINE is given, assume it represents a line and compute its indentation."
5316 (if line
5317 (if (string-match "^ *" (org-remove-tabs line))
5318 (match-end 0))
5319 (save-excursion
5320 (beginning-of-line 1)
5321 (skip-chars-forward " \t")
5322 (current-column))))
5324 (defun org-remove-tabs (s &optional width)
5325 "Replace tabulators in S with spaces.
5326 Assumes that s is a single line, starting in column 0."
5327 (setq width (or width tab-width))
5328 (while (string-match "\t" s)
5329 (setq s (replace-match
5330 (make-string
5331 (- (* width (/ (+ (match-beginning 0) width) width))
5332 (match-beginning 0)) ?\ )
5333 t t s)))
5336 (defun org-fix-indentation (line ind)
5337 "Fix indentation in LINE.
5338 IND is a cons cell with target and minimum indentation.
5339 If the current indenation in LINE is smaller than the minimum,
5340 leave it alone. If it is larger than ind, set it to the target."
5341 (let* ((l (org-remove-tabs line))
5342 (i (org-get-indentation l))
5343 (i1 (car ind)) (i2 (cdr ind)))
5344 (if (>= i i2) (setq l (substring line i2)))
5345 (if (> i1 0)
5346 (concat (make-string i1 ?\ ) l)
5347 l)))
5349 (defun org-beginning-of-item ()
5350 "Go to the beginning of the current hand-formatted item.
5351 If the cursor is not in an item, throw an error."
5352 (interactive)
5353 (let ((pos (point))
5354 (limit (save-excursion
5355 (condition-case nil
5356 (progn
5357 (org-back-to-heading)
5358 (beginning-of-line 2) (point))
5359 (error (point-min)))))
5360 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5361 ind ind1)
5362 (if (org-at-item-p)
5363 (beginning-of-line 1)
5364 (beginning-of-line 1)
5365 (skip-chars-forward " \t")
5366 (setq ind (current-column))
5367 (if (catch 'exit
5368 (while t
5369 (beginning-of-line 0)
5370 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5372 (if (looking-at "[ \t]*$")
5373 (setq ind1 ind-empty)
5374 (skip-chars-forward " \t")
5375 (setq ind1 (current-column)))
5376 (if (< ind1 ind)
5377 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5379 (goto-char pos)
5380 (error "Not in an item")))))
5382 (defun org-end-of-item ()
5383 "Go to the end of the current hand-formatted item.
5384 If the cursor is not in an item, throw an error."
5385 (interactive)
5386 (let* ((pos (point))
5387 ind1
5388 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5389 (limit (save-excursion (outline-next-heading) (point)))
5390 (ind (save-excursion
5391 (org-beginning-of-item)
5392 (skip-chars-forward " \t")
5393 (current-column)))
5394 (end (catch 'exit
5395 (while t
5396 (beginning-of-line 2)
5397 (if (eobp) (throw 'exit (point)))
5398 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5399 (if (looking-at "[ \t]*$")
5400 (setq ind1 ind-empty)
5401 (skip-chars-forward " \t")
5402 (setq ind1 (current-column)))
5403 (if (<= ind1 ind)
5404 (throw 'exit (point-at-bol)))))))
5405 (if end
5406 (goto-char end)
5407 (goto-char pos)
5408 (error "Not in an item"))))
5410 (defun org-next-item ()
5411 "Move to the beginning of the next item in the current plain list.
5412 Error if not at a plain list, or if this is the last item in the list."
5413 (interactive)
5414 (let (ind ind1 (pos (point)))
5415 (org-beginning-of-item)
5416 (setq ind (org-get-indentation))
5417 (org-end-of-item)
5418 (setq ind1 (org-get-indentation))
5419 (unless (and (org-at-item-p) (= ind ind1))
5420 (goto-char pos)
5421 (error "On last item"))))
5423 (defun org-previous-item ()
5424 "Move to the beginning of the previous item in the current plain list.
5425 Error if not at a plain list, or if this is the first item in the list."
5426 (interactive)
5427 (let (beg ind ind1 (pos (point)))
5428 (org-beginning-of-item)
5429 (setq beg (point))
5430 (setq ind (org-get-indentation))
5431 (goto-char beg)
5432 (catch 'exit
5433 (while t
5434 (beginning-of-line 0)
5435 (if (looking-at "[ \t]*$")
5437 (if (<= (setq ind1 (org-get-indentation)) ind)
5438 (throw 'exit t)))))
5439 (condition-case nil
5440 (if (or (not (org-at-item-p))
5441 (< ind1 (1- ind)))
5442 (error "")
5443 (org-beginning-of-item))
5444 (error (goto-char pos)
5445 (error "On first item")))))
5447 (defun org-first-list-item-p ()
5448 "Is this heading the item in a plain list?"
5449 (unless (org-at-item-p)
5450 (error "Not at a plain list item"))
5451 (org-beginning-of-item)
5452 (= (point) (save-excursion (org-beginning-of-item-list))))
5454 (defun org-move-item-down ()
5455 "Move the plain list item at point down, i.e. swap with following item.
5456 Subitems (items with larger indentation) are considered part of the item,
5457 so this really moves item trees."
5458 (interactive)
5459 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5460 (org-beginning-of-item)
5461 (setq beg0 (point))
5462 (save-excursion
5463 (setq ne-beg (org-back-over-empty-lines))
5464 (setq beg (point)))
5465 (goto-char beg0)
5466 (setq ind (org-get-indentation))
5467 (org-end-of-item)
5468 (setq end0 (point))
5469 (setq ind1 (org-get-indentation))
5470 (setq ne-end (org-back-over-empty-lines))
5471 (setq end (point))
5472 (goto-char beg0)
5473 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5474 ;; include less whitespace
5475 (save-excursion
5476 (goto-char beg)
5477 (forward-line (- ne-beg ne-end))
5478 (setq beg (point))))
5479 (goto-char end0)
5480 (if (and (org-at-item-p) (= ind ind1))
5481 (progn
5482 (org-end-of-item)
5483 (org-back-over-empty-lines)
5484 (setq txt (buffer-substring beg end))
5485 (save-excursion
5486 (delete-region beg end))
5487 (setq pos (point))
5488 (insert txt)
5489 (goto-char pos) (org-skip-whitespace)
5490 (org-maybe-renumber-ordered-list))
5491 (goto-char pos)
5492 (error "Cannot move this item further down"))))
5494 (defun org-move-item-up (arg)
5495 "Move the plain list item at point up, i.e. swap with previous item.
5496 Subitems (items with larger indentation) are considered part of the item,
5497 so this really moves item trees."
5498 (interactive "p")
5499 (let (beg beg0 end ind ind1 (pos (point)) txt
5500 ne-beg ne-ins ins-end)
5501 (org-beginning-of-item)
5502 (setq beg0 (point))
5503 (setq ind (org-get-indentation))
5504 (save-excursion
5505 (setq ne-beg (org-back-over-empty-lines))
5506 (setq beg (point)))
5507 (goto-char beg0)
5508 (org-end-of-item)
5509 (setq end (point))
5510 (goto-char beg0)
5511 (catch 'exit
5512 (while t
5513 (beginning-of-line 0)
5514 (if (looking-at "[ \t]*$")
5515 (if org-empty-line-terminates-plain-lists
5516 (progn
5517 (goto-char pos)
5518 (error "Cannot move this item further up"))
5519 nil)
5520 (if (<= (setq ind1 (org-get-indentation)) ind)
5521 (throw 'exit t)))))
5522 (condition-case nil
5523 (org-beginning-of-item)
5524 (error (goto-char beg)
5525 (error "Cannot move this item further up")))
5526 (setq ind1 (org-get-indentation))
5527 (if (and (org-at-item-p) (= ind ind1))
5528 (progn
5529 (setq ne-ins (org-back-over-empty-lines))
5530 (setq txt (buffer-substring beg end))
5531 (save-excursion
5532 (delete-region beg end))
5533 (setq pos (point))
5534 (insert txt)
5535 (setq ins-end (point))
5536 (goto-char pos) (org-skip-whitespace)
5538 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5539 ;; Move whitespace back to beginning
5540 (save-excursion
5541 (goto-char ins-end)
5542 (let ((kill-whole-line t))
5543 (kill-line (- ne-ins ne-beg)) (point)))
5544 (insert (make-string (- ne-ins ne-beg) ?\n)))
5546 (org-maybe-renumber-ordered-list))
5547 (goto-char pos)
5548 (error "Cannot move this item further up"))))
5550 (defun org-maybe-renumber-ordered-list ()
5551 "Renumber the ordered list at point if setup allows it.
5552 This tests the user option `org-auto-renumber-ordered-lists' before
5553 doing the renumbering."
5554 (interactive)
5555 (when (and org-auto-renumber-ordered-lists
5556 (org-at-item-p))
5557 (if (match-beginning 3)
5558 (org-renumber-ordered-list 1)
5559 (org-fix-bullet-type))))
5561 (defun org-maybe-renumber-ordered-list-safe ()
5562 (condition-case nil
5563 (save-excursion
5564 (org-maybe-renumber-ordered-list))
5565 (error nil)))
5567 (defun org-cycle-list-bullet (&optional which)
5568 "Cycle through the different itemize/enumerate bullets.
5569 This cycle the entire list level through the sequence:
5571 `-' -> `+' -> `*' -> `1.' -> `1)'
5573 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5574 0 meand `-', 1 means `+' etc."
5575 (interactive "P")
5576 (org-preserve-lc
5577 (org-beginning-of-item-list)
5578 (org-at-item-p)
5579 (beginning-of-line 1)
5580 (let ((current (match-string 0))
5581 (prevp (eq which 'previous))
5582 new)
5583 (setq new (cond
5584 ((and (numberp which)
5585 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5586 ((string-match "-" current) (if prevp "1)" "+"))
5587 ((string-match "\\+" current)
5588 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5589 ((string-match "\\*" current) (if prevp "+" "1."))
5590 ((string-match "\\." current) (if prevp "*" "1)"))
5591 ((string-match ")" current) (if prevp "1." "-"))
5592 (t (error "This should not happen"))))
5593 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5594 (org-fix-bullet-type)
5595 (org-maybe-renumber-ordered-list))))
5597 (defun org-get-string-indentation (s)
5598 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5599 (let ((n -1) (i 0) (w tab-width) c)
5600 (catch 'exit
5601 (while (< (setq n (1+ n)) (length s))
5602 (setq c (aref s n))
5603 (cond ((= c ?\ ) (setq i (1+ i)))
5604 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5605 (t (throw 'exit t)))))
5608 (defun org-renumber-ordered-list (arg)
5609 "Renumber an ordered plain list.
5610 Cursor needs to be in the first line of an item, the line that starts
5611 with something like \"1.\" or \"2)\"."
5612 (interactive "p")
5613 (unless (and (org-at-item-p)
5614 (match-beginning 3))
5615 (error "This is not an ordered list"))
5616 (let ((line (org-current-line))
5617 (col (current-column))
5618 (ind (org-get-string-indentation
5619 (buffer-substring (point-at-bol) (match-beginning 3))))
5620 ;; (term (substring (match-string 3) -1))
5621 ind1 (n (1- arg))
5622 fmt)
5623 ;; find where this list begins
5624 (org-beginning-of-item-list)
5625 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5626 (setq fmt (concat "%d" (match-string 1)))
5627 (beginning-of-line 0)
5628 ;; walk forward and replace these numbers
5629 (catch 'exit
5630 (while t
5631 (catch 'next
5632 (beginning-of-line 2)
5633 (if (eobp) (throw 'exit nil))
5634 (if (looking-at "[ \t]*$") (throw 'next nil))
5635 (skip-chars-forward " \t") (setq ind1 (current-column))
5636 (if (> ind1 ind) (throw 'next t))
5637 (if (< ind1 ind) (throw 'exit t))
5638 (if (not (org-at-item-p)) (throw 'exit nil))
5639 (delete-region (match-beginning 2) (match-end 2))
5640 (goto-char (match-beginning 2))
5641 (insert (format fmt (setq n (1+ n)))))))
5642 (goto-line line)
5643 (org-move-to-column col)))
5645 (defun org-fix-bullet-type ()
5646 "Make sure all items in this list have the same bullet as the firsst item."
5647 (interactive)
5648 (unless (org-at-item-p) (error "This is not a list"))
5649 (let ((line (org-current-line))
5650 (col (current-column))
5651 (ind (current-indentation))
5652 ind1 bullet)
5653 ;; find where this list begins
5654 (org-beginning-of-item-list)
5655 (beginning-of-line 1)
5656 ;; find out what the bullet type is
5657 (looking-at "[ \t]*\\(\\S-+\\)")
5658 (setq bullet (match-string 1))
5659 ;; walk forward and replace these numbers
5660 (beginning-of-line 0)
5661 (catch 'exit
5662 (while t
5663 (catch 'next
5664 (beginning-of-line 2)
5665 (if (eobp) (throw 'exit nil))
5666 (if (looking-at "[ \t]*$") (throw 'next nil))
5667 (skip-chars-forward " \t") (setq ind1 (current-column))
5668 (if (> ind1 ind) (throw 'next t))
5669 (if (< ind1 ind) (throw 'exit t))
5670 (if (not (org-at-item-p)) (throw 'exit nil))
5671 (skip-chars-forward " \t")
5672 (looking-at "\\S-+")
5673 (replace-match bullet))))
5674 (goto-line line)
5675 (org-move-to-column col)
5676 (if (string-match "[0-9]" bullet)
5677 (org-renumber-ordered-list 1))))
5679 (defun org-beginning-of-item-list ()
5680 "Go to the beginning of the current item list.
5681 I.e. to the first item in this list."
5682 (interactive)
5683 (org-beginning-of-item)
5684 (let ((pos (point-at-bol))
5685 (ind (org-get-indentation))
5686 ind1)
5687 ;; find where this list begins
5688 (catch 'exit
5689 (while t
5690 (catch 'next
5691 (beginning-of-line 0)
5692 (if (looking-at "[ \t]*$")
5693 (throw (if (bobp) 'exit 'next) t))
5694 (skip-chars-forward " \t") (setq ind1 (current-column))
5695 (if (or (< ind1 ind)
5696 (and (= ind1 ind)
5697 (not (org-at-item-p)))
5698 (bobp))
5699 (throw 'exit t)
5700 (when (org-at-item-p) (setq pos (point-at-bol)))))))
5701 (goto-char pos)))
5704 (defun org-end-of-item-list ()
5705 "Go to the end of the current item list.
5706 I.e. to the text after the last item."
5707 (interactive)
5708 (org-beginning-of-item)
5709 (let ((pos (point-at-bol))
5710 (ind (org-get-indentation))
5711 ind1)
5712 ;; find where this list begins
5713 (catch 'exit
5714 (while t
5715 (catch 'next
5716 (beginning-of-line 2)
5717 (if (looking-at "[ \t]*$")
5718 (throw (if (eobp) 'exit 'next) t))
5719 (skip-chars-forward " \t") (setq ind1 (current-column))
5720 (if (or (< ind1 ind)
5721 (and (= ind1 ind)
5722 (not (org-at-item-p)))
5723 (eobp))
5724 (progn
5725 (setq pos (point-at-bol))
5726 (throw 'exit t))))))
5727 (goto-char pos)))
5730 (defvar org-last-indent-begin-marker (make-marker))
5731 (defvar org-last-indent-end-marker (make-marker))
5733 (defun org-outdent-item (arg)
5734 "Outdent a local list item."
5735 (interactive "p")
5736 (org-indent-item (- arg)))
5738 (defun org-indent-item (arg)
5739 "Indent a local list item."
5740 (interactive "p")
5741 (unless (org-at-item-p)
5742 (error "Not on an item"))
5743 (save-excursion
5744 (let (beg end ind ind1 tmp delta ind-down ind-up)
5745 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5746 (setq beg org-last-indent-begin-marker
5747 end org-last-indent-end-marker)
5748 (org-beginning-of-item)
5749 (setq beg (move-marker org-last-indent-begin-marker (point)))
5750 (org-end-of-item)
5751 (setq end (move-marker org-last-indent-end-marker (point))))
5752 (goto-char beg)
5753 (setq tmp (org-item-indent-positions)
5754 ind (car tmp)
5755 ind-down (nth 2 tmp)
5756 ind-up (nth 1 tmp)
5757 delta (if (> arg 0)
5758 (if ind-down (- ind-down ind) 2)
5759 (if ind-up (- ind-up ind) -2)))
5760 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5761 (while (< (point) end)
5762 (beginning-of-line 1)
5763 (skip-chars-forward " \t") (setq ind1 (current-column))
5764 (delete-region (point-at-bol) (point))
5765 (or (eolp) (org-indent-to-column (+ ind1 delta)))
5766 (beginning-of-line 2))))
5767 (org-fix-bullet-type)
5768 (org-maybe-renumber-ordered-list-safe)
5769 (save-excursion
5770 (beginning-of-line 0)
5771 (condition-case nil (org-beginning-of-item) (error nil))
5772 (org-maybe-renumber-ordered-list-safe)))
5774 (defun org-item-indent-positions ()
5775 "Return indentation for plain list items.
5776 This returns a list with three values: The current indentation, the
5777 parent indentation and the indentation a child should habe.
5778 Assumes cursor in item line."
5779 (let* ((bolpos (point-at-bol))
5780 (ind (org-get-indentation))
5781 ind-down ind-up pos)
5782 (save-excursion
5783 (org-beginning-of-item-list)
5784 (skip-chars-backward "\n\r \t")
5785 (when (org-in-item-p)
5786 (org-beginning-of-item)
5787 (setq ind-up (org-get-indentation))))
5788 (setq pos (point))
5789 (save-excursion
5790 (cond
5791 ((and (condition-case nil (progn (org-previous-item) t)
5792 (error nil))
5793 (or (forward-char 1) t)
5794 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
5795 (setq ind-down (org-get-indentation)))
5796 ((and (goto-char pos)
5797 (org-at-item-p))
5798 (goto-char (match-end 0))
5799 (skip-chars-forward " \t")
5800 (setq ind-down (current-column)))))
5801 (list ind ind-up ind-down)))
5803 ;;; The orgstruct minor mode
5805 ;; Define a minor mode which can be used in other modes in order to
5806 ;; integrate the org-mode structure editing commands.
5808 ;; This is really a hack, because the org-mode structure commands use
5809 ;; keys which normally belong to the major mode. Here is how it
5810 ;; works: The minor mode defines all the keys necessary to operate the
5811 ;; structure commands, but wraps the commands into a function which
5812 ;; tests if the cursor is currently at a headline or a plain list
5813 ;; item. If that is the case, the structure command is used,
5814 ;; temporarily setting many Org-mode variables like regular
5815 ;; expressions for filling etc. However, when any of those keys is
5816 ;; used at a different location, function uses `key-binding' to look
5817 ;; up if the key has an associated command in another currently active
5818 ;; keymap (minor modes, major mode, global), and executes that
5819 ;; command. There might be problems if any of the keys is otherwise
5820 ;; used as a prefix key.
5822 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5823 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5824 ;; addresses this by checking explicitly for both bindings.
5826 (defvar orgstruct-mode-map (make-sparse-keymap)
5827 "Keymap for the minor `orgstruct-mode'.")
5829 (defvar org-local-vars nil
5830 "List of local variables, for use by `orgstruct-mode'")
5832 ;;;###autoload
5833 (define-minor-mode orgstruct-mode
5834 "Toggle the minor more `orgstruct-mode'.
5835 This mode is for using Org-mode structure commands in other modes.
5836 The following key behave as if Org-mode was active, if the cursor
5837 is on a headline, or on a plain list item (both in the definition
5838 of Org-mode).
5840 M-up Move entry/item up
5841 M-down Move entry/item down
5842 M-left Promote
5843 M-right Demote
5844 M-S-up Move entry/item up
5845 M-S-down Move entry/item down
5846 M-S-left Promote subtree
5847 M-S-right Demote subtree
5848 M-q Fill paragraph and items like in Org-mode
5849 C-c ^ Sort entries
5850 C-c - Cycle list bullet
5851 TAB Cycle item visibility
5852 M-RET Insert new heading/item
5853 S-M-RET Insert new TODO heading / Chekbox item
5854 C-c C-c Set tags / toggle checkbox"
5855 nil " OrgStruct" nil
5856 (org-load-modules-maybe)
5857 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5859 ;;;###autoload
5860 (defun turn-on-orgstruct ()
5861 "Unconditionally turn on `orgstruct-mode'."
5862 (orgstruct-mode 1))
5864 ;;;###autoload
5865 (defun turn-on-orgstruct++ ()
5866 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5867 In addition to setting orgstruct-mode, this also exports all indentation and
5868 autofilling variables from org-mode into the buffer. Note that turning
5869 off orgstruct-mode will *not* remove these additional settings."
5870 (orgstruct-mode 1)
5871 (let (var val)
5872 (mapc
5873 (lambda (x)
5874 (when (string-match
5875 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5876 (symbol-name (car x)))
5877 (setq var (car x) val (nth 1 x))
5878 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5879 org-local-vars)))
5881 (defun orgstruct-error ()
5882 "Error when there is no default binding for a structure key."
5883 (interactive)
5884 (error "This key has no function outside structure elements"))
5886 (defun orgstruct-setup ()
5887 "Setup orgstruct keymaps."
5888 (let ((nfunc 0)
5889 (bindings
5890 (list
5891 '([(meta up)] org-metaup)
5892 '([(meta down)] org-metadown)
5893 '([(meta left)] org-metaleft)
5894 '([(meta right)] org-metaright)
5895 '([(meta shift up)] org-shiftmetaup)
5896 '([(meta shift down)] org-shiftmetadown)
5897 '([(meta shift left)] org-shiftmetaleft)
5898 '([(meta shift right)] org-shiftmetaright)
5899 '([(shift up)] org-shiftup)
5900 '([(shift down)] org-shiftdown)
5901 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5902 '("\M-q" fill-paragraph)
5903 '("\C-c^" org-sort)
5904 '("\C-c-" org-cycle-list-bullet)))
5905 elt key fun cmd)
5906 (while (setq elt (pop bindings))
5907 (setq nfunc (1+ nfunc))
5908 (setq key (org-key (car elt))
5909 fun (nth 1 elt)
5910 cmd (orgstruct-make-binding fun nfunc key))
5911 (org-defkey orgstruct-mode-map key cmd))
5913 ;; Special treatment needed for TAB and RET
5914 (org-defkey orgstruct-mode-map [(tab)]
5915 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5916 (org-defkey orgstruct-mode-map "\C-i"
5917 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5919 (org-defkey orgstruct-mode-map "\M-\C-m"
5920 (orgstruct-make-binding 'org-insert-heading 105
5921 "\M-\C-m" [(meta return)]))
5922 (org-defkey orgstruct-mode-map [(meta return)]
5923 (orgstruct-make-binding 'org-insert-heading 106
5924 [(meta return)] "\M-\C-m"))
5926 (org-defkey orgstruct-mode-map [(shift meta return)]
5927 (orgstruct-make-binding 'org-insert-todo-heading 107
5928 [(meta return)] "\M-\C-m"))
5930 (unless org-local-vars
5931 (setq org-local-vars (org-get-local-variables)))
5935 (defun orgstruct-make-binding (fun n &rest keys)
5936 "Create a function for binding in the structure minor mode.
5937 FUN is the command to call inside a table. N is used to create a unique
5938 command name. KEYS are keys that should be checked in for a command
5939 to execute outside of tables."
5940 (eval
5941 (list 'defun
5942 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5943 '(arg)
5944 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5945 "Outside of structure, run the binding of `"
5946 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5947 "'.")
5948 '(interactive "p")
5949 (list 'if
5950 '(org-context-p 'headline 'item)
5951 (list 'org-run-like-in-org-mode (list 'quote fun))
5952 (list 'let '(orgstruct-mode)
5953 (list 'call-interactively
5954 (append '(or)
5955 (mapcar (lambda (k)
5956 (list 'key-binding k))
5957 keys)
5958 '('orgstruct-error))))))))
5960 (defun org-context-p (&rest contexts)
5961 "Check if local context is and of CONTEXTS.
5962 Possible values in the list of contexts are `table', `headline', and `item'."
5963 (let ((pos (point)))
5964 (goto-char (point-at-bol))
5965 (prog1 (or (and (memq 'table contexts)
5966 (looking-at "[ \t]*|"))
5967 (and (memq 'headline contexts)
5968 (looking-at "\\*+"))
5969 (and (memq 'item contexts)
5970 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5971 (goto-char pos))))
5973 (defun org-get-local-variables ()
5974 "Return a list of all local variables in an org-mode buffer."
5975 (let (varlist)
5976 (with-current-buffer (get-buffer-create "*Org tmp*")
5977 (erase-buffer)
5978 (org-mode)
5979 (setq varlist (buffer-local-variables)))
5980 (kill-buffer "*Org tmp*")
5981 (delq nil
5982 (mapcar
5983 (lambda (x)
5984 (setq x
5985 (if (symbolp x)
5986 (list x)
5987 (list (car x) (list 'quote (cdr x)))))
5988 (if (string-match
5989 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5990 (symbol-name (car x)))
5991 x nil))
5992 varlist))))
5994 ;;;###autoload
5995 (defun org-run-like-in-org-mode (cmd)
5996 (org-load-modules-maybe)
5997 (unless org-local-vars
5998 (setq org-local-vars (org-get-local-variables)))
5999 (eval (list 'let org-local-vars
6000 (list 'call-interactively (list 'quote cmd)))))
6002 ;;;; Archiving
6004 (defun org-get-category (&optional pos)
6005 "Get the category applying to position POS."
6006 (get-text-property (or pos (point)) 'org-category))
6008 (defun org-refresh-category-properties ()
6009 "Refresh category text properties in the buffer."
6010 (let ((def-cat (cond
6011 ((null org-category)
6012 (if buffer-file-name
6013 (file-name-sans-extension
6014 (file-name-nondirectory buffer-file-name))
6015 "???"))
6016 ((symbolp org-category) (symbol-name org-category))
6017 (t org-category)))
6018 beg end cat pos optionp)
6019 (org-unmodified
6020 (save-excursion
6021 (save-restriction
6022 (widen)
6023 (goto-char (point-min))
6024 (put-text-property (point) (point-max) 'org-category def-cat)
6025 (while (re-search-forward
6026 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6027 (setq pos (match-end 0)
6028 optionp (equal (char-after (match-beginning 0)) ?#)
6029 cat (org-trim (match-string 2)))
6030 (if optionp
6031 (setq beg (point-at-bol) end (point-max))
6032 (org-back-to-heading t)
6033 (setq beg (point) end (org-end-of-subtree t t)))
6034 (put-text-property beg end 'org-category cat)
6035 (goto-char pos)))))))
6038 ;;;; Link Stuff
6040 ;;; Link abbreviations
6042 (defun org-link-expand-abbrev (link)
6043 "Apply replacements as defined in `org-link-abbrev-alist."
6044 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6045 (let* ((key (match-string 1 link))
6046 (as (or (assoc key org-link-abbrev-alist-local)
6047 (assoc key org-link-abbrev-alist)))
6048 (tag (and (match-end 2) (match-string 3 link)))
6049 rpl)
6050 (if (not as)
6051 link
6052 (setq rpl (cdr as))
6053 (cond
6054 ((symbolp rpl) (funcall rpl tag))
6055 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6056 (t (concat rpl tag)))))
6057 link))
6059 ;;; Storing and inserting links
6061 (defvar org-insert-link-history nil
6062 "Minibuffer history for links inserted with `org-insert-link'.")
6064 (defvar org-stored-links nil
6065 "Contains the links stored with `org-store-link'.")
6067 (defvar org-store-link-plist nil
6068 "Plist with info about the most recently link created with `org-store-link'.")
6070 (defvar org-link-protocols nil
6071 "Link protocols added to Org-mode using `org-add-link-type'.")
6073 (defvar org-store-link-functions nil
6074 "List of functions that are called to create and store a link.
6075 Each function will be called in turn until one returns a non-nil
6076 value. Each function should check if it is responsible for creating
6077 this link (for example by looking at the major mode).
6078 If not, it must exit and return nil.
6079 If yes, it should return a non-nil value after a calling
6080 `org-store-link-props' with a list of properties and values.
6081 Special properties are:
6083 :type The link prefix. like \"http\". This must be given.
6084 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6085 This is obligatory as well.
6086 :description Optional default description for the second pair
6087 of brackets in an Org-mode link. The user can still change
6088 this when inserting this link into an Org-mode buffer.
6090 In addition to these, any additional properties can be specified
6091 and then used in remember templates.")
6093 (defun org-add-link-type (type &optional follow export)
6094 "Add TYPE to the list of `org-link-types'.
6095 Re-compute all regular expressions depending on `org-link-types'
6097 FOLLOW and EXPORT are two functions.
6099 FOLLOW should take the link path as the single argument and do whatever
6100 is necessary to follow the link, for example find a file or display
6101 a mail message.
6103 EXPORT should format the link path for export to one of the export formats.
6104 It should be a function accepting three arguments:
6106 path the path of the link, the text after the prefix (like \"http:\")
6107 desc the description of the link, if any, nil if there was no descripton
6108 format the export format, a symbol like `html' or `latex'.
6110 The function may use the FORMAT information to return different values
6111 depending on the format. The return value will be put literally into
6112 the exported file.
6113 Org-mode has a built-in default for exporting links. If you are happy with
6114 this default, there is no need to define an export function for the link
6115 type. For a simple example of an export function, see `org-bbdb.el'."
6116 (add-to-list 'org-link-types type t)
6117 (org-make-link-regexps)
6118 (if (assoc type org-link-protocols)
6119 (setcdr (assoc type org-link-protocols) (list follow export))
6120 (push (list type follow export) org-link-protocols)))
6123 ;;;###autoload
6124 (defun org-store-link (arg)
6125 "\\<org-mode-map>Store an org-link to the current location.
6126 This link is added to `org-stored-links' and can later be inserted
6127 into an org-buffer with \\[org-insert-link].
6129 For some link types, a prefix arg is interpreted:
6130 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6131 For file links, arg negates `org-context-in-file-links'."
6132 (interactive "P")
6133 (org-load-modules-maybe)
6134 (setq org-store-link-plist nil) ; reset
6135 (let (link cpltxt desc description search txt)
6136 (cond
6138 ((run-hook-with-args-until-success 'org-store-link-functions)
6139 (setq link (plist-get org-store-link-plist :link)
6140 desc (or (plist-get org-store-link-plist :description) link)))
6142 ((eq major-mode 'calendar-mode)
6143 (let ((cd (calendar-cursor-to-date)))
6144 (setq link
6145 (format-time-string
6146 (car org-time-stamp-formats)
6147 (apply 'encode-time
6148 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6149 nil nil nil))))
6150 (org-store-link-props :type "calendar" :date cd)))
6152 ((eq major-mode 'w3-mode)
6153 (setq cpltxt (url-view-url t)
6154 link (org-make-link cpltxt))
6155 (org-store-link-props :type "w3" :url (url-view-url t)))
6157 ((eq major-mode 'w3m-mode)
6158 (setq cpltxt (or w3m-current-title w3m-current-url)
6159 link (org-make-link w3m-current-url))
6160 (org-store-link-props :type "w3m" :url (url-view-url t)))
6162 ((setq search (run-hook-with-args-until-success
6163 'org-create-file-search-functions))
6164 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6165 "::" search))
6166 (setq cpltxt (or description link)))
6168 ((eq major-mode 'image-mode)
6169 (setq cpltxt (concat "file:"
6170 (abbreviate-file-name buffer-file-name))
6171 link (org-make-link cpltxt))
6172 (org-store-link-props :type "image" :file buffer-file-name))
6174 ((eq major-mode 'dired-mode)
6175 ;; link to the file in the current line
6176 (setq cpltxt (concat "file:"
6177 (abbreviate-file-name
6178 (expand-file-name
6179 (dired-get-filename nil t))))
6180 link (org-make-link cpltxt)))
6182 ((and buffer-file-name (org-mode-p))
6183 ;; Just link to current headline
6184 (setq cpltxt (concat "file:"
6185 (abbreviate-file-name buffer-file-name)))
6186 ;; Add a context search string
6187 (when (org-xor org-context-in-file-links arg)
6188 ;; Check if we are on a target
6189 (if (org-in-regexp "<<\\(.*?\\)>>")
6190 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6191 (setq txt (cond
6192 ((org-on-heading-p) nil)
6193 ((org-region-active-p)
6194 (buffer-substring (region-beginning) (region-end)))
6195 (t nil)))
6196 (when (or (null txt) (string-match "\\S-" txt))
6197 (setq cpltxt
6198 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6199 desc "NONE"))))
6200 (if (string-match "::\\'" cpltxt)
6201 (setq cpltxt (substring cpltxt 0 -2)))
6202 (setq link (org-make-link cpltxt)))
6204 ((buffer-file-name (buffer-base-buffer))
6205 ;; Just link to this file here.
6206 (setq cpltxt (concat "file:"
6207 (abbreviate-file-name
6208 (buffer-file-name (buffer-base-buffer)))))
6209 ;; Add a context string
6210 (when (org-xor org-context-in-file-links arg)
6211 (setq txt (if (org-region-active-p)
6212 (buffer-substring (region-beginning) (region-end))
6213 (buffer-substring (point-at-bol) (point-at-eol))))
6214 ;; Only use search option if there is some text.
6215 (when (string-match "\\S-" txt)
6216 (setq cpltxt
6217 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6218 desc "NONE")))
6219 (setq link (org-make-link cpltxt)))
6221 ((interactive-p)
6222 (error "Cannot link to a buffer which is not visiting a file"))
6224 (t (setq link nil)))
6226 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6227 (setq link (or link cpltxt)
6228 desc (or desc cpltxt))
6229 (if (equal desc "NONE") (setq desc nil))
6231 (if (and (interactive-p) link)
6232 (progn
6233 (setq org-stored-links
6234 (cons (list link desc) org-stored-links))
6235 (message "Stored: %s" (or desc link)))
6236 (and link (org-make-link-string link desc)))))
6238 (defun org-store-link-props (&rest plist)
6239 "Store link properties, extract names and addresses."
6240 (let (x adr)
6241 (when (setq x (plist-get plist :from))
6242 (setq adr (mail-extract-address-components x))
6243 (plist-put plist :fromname (car adr))
6244 (plist-put plist :fromaddress (nth 1 adr)))
6245 (when (setq x (plist-get plist :to))
6246 (setq adr (mail-extract-address-components x))
6247 (plist-put plist :toname (car adr))
6248 (plist-put plist :toaddress (nth 1 adr))))
6249 (let ((from (plist-get plist :from))
6250 (to (plist-get plist :to)))
6251 (when (and from to org-from-is-user-regexp)
6252 (plist-put plist :fromto
6253 (if (string-match org-from-is-user-regexp from)
6254 (concat "to %t")
6255 (concat "from %f")))))
6256 (setq org-store-link-plist plist))
6258 (defun org-add-link-props (&rest plist)
6259 "Add these properties to the link property list."
6260 (let (key value)
6261 (while plist
6262 (setq key (pop plist) value (pop plist))
6263 (setq org-store-link-plist
6264 (plist-put org-store-link-plist key value)))))
6266 (defun org-email-link-description (&optional fmt)
6267 "Return the description part of an email link.
6268 This takes information from `org-store-link-plist' and formats it
6269 according to FMT (default from `org-email-link-description-format')."
6270 (setq fmt (or fmt org-email-link-description-format))
6271 (let* ((p org-store-link-plist)
6272 (to (plist-get p :toaddress))
6273 (from (plist-get p :fromaddress))
6274 (table
6275 (list
6276 (cons "%c" (plist-get p :fromto))
6277 (cons "%F" (plist-get p :from))
6278 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6279 (cons "%T" (plist-get p :to))
6280 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6281 (cons "%s" (plist-get p :subject))
6282 (cons "%m" (plist-get p :message-id)))))
6283 (when (string-match "%c" fmt)
6284 ;; Check if the user wrote this message
6285 (if (and org-from-is-user-regexp from to
6286 (save-match-data (string-match org-from-is-user-regexp from)))
6287 (setq fmt (replace-match "to %t" t t fmt))
6288 (setq fmt (replace-match "from %f" t t fmt))))
6289 (org-replace-escapes fmt table)))
6291 (defun org-make-org-heading-search-string (&optional string heading)
6292 "Make search string for STRING or current headline."
6293 (interactive)
6294 (let ((s (or string (org-get-heading))))
6295 (unless (and string (not heading))
6296 ;; We are using a headline, clean up garbage in there.
6297 (if (string-match org-todo-regexp s)
6298 (setq s (replace-match "" t t s)))
6299 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6300 (setq s (replace-match "" t t s)))
6301 (setq s (org-trim s))
6302 (if (string-match (concat "^\\(" org-quote-string "\\|"
6303 org-comment-string "\\)") s)
6304 (setq s (replace-match "" t t s)))
6305 (while (string-match org-ts-regexp s)
6306 (setq s (replace-match "" t t s))))
6307 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6308 (setq s (replace-match " " t t s)))
6309 (or string (setq s (concat "*" s))) ; Add * for headlines
6310 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6312 (defun org-make-link (&rest strings)
6313 "Concatenate STRINGS."
6314 (apply 'concat strings))
6316 (defun org-make-link-string (link &optional description)
6317 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6318 (unless (string-match "\\S-" link)
6319 (error "Empty link"))
6320 (when (stringp description)
6321 ;; Remove brackets from the description, they are fatal.
6322 (while (string-match "\\[" description)
6323 (setq description (replace-match "{" t t description)))
6324 (while (string-match "\\]" description)
6325 (setq description (replace-match "}" t t description))))
6326 (when (equal (org-link-escape link) description)
6327 ;; No description needed, it is identical
6328 (setq description nil))
6329 (when (and (not description)
6330 (not (equal link (org-link-escape link))))
6331 (setq description link))
6332 (concat "[[" (org-link-escape link) "]"
6333 (if description (concat "[" description "]") "")
6334 "]"))
6336 (defconst org-link-escape-chars
6337 '((?\ . "%20")
6338 (?\[ . "%5B")
6339 (?\] . "%5D")
6340 (?\340 . "%E0") ; `a
6341 (?\342 . "%E2") ; ^a
6342 (?\347 . "%E7") ; ,c
6343 (?\350 . "%E8") ; `e
6344 (?\351 . "%E9") ; 'e
6345 (?\352 . "%EA") ; ^e
6346 (?\356 . "%EE") ; ^i
6347 (?\364 . "%F4") ; ^o
6348 (?\371 . "%F9") ; `u
6349 (?\373 . "%FB") ; ^u
6350 (?\; . "%3B")
6351 (?? . "%3F")
6352 (?= . "%3D")
6353 (?+ . "%2B")
6355 "Association list of escapes for some characters problematic in links.
6356 This is the list that is used for internal purposes.")
6358 (defconst org-link-escape-chars-browser
6359 '((?\ . "%20")) ; 32 for the SPC char
6360 "Association list of escapes for some characters problematic in links.
6361 This is the list that is used before handing over to the browser.")
6363 (defun org-link-escape (text &optional table)
6364 "Escape charaters in TEXT that are problematic for links."
6365 (setq table (or table org-link-escape-chars))
6366 (when text
6367 (let ((re (mapconcat (lambda (x) (regexp-quote
6368 (char-to-string (car x))))
6369 table "\\|")))
6370 (while (string-match re text)
6371 (setq text
6372 (replace-match
6373 (cdr (assoc (string-to-char (match-string 0 text))
6374 table))
6375 t t text)))
6376 text)))
6378 (defun org-link-unescape (text &optional table)
6379 "Reverse the action of `org-link-escape'."
6380 (setq table (or table org-link-escape-chars))
6381 (when text
6382 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6383 table "\\|")))
6384 (while (string-match re text)
6385 (setq text
6386 (replace-match
6387 (char-to-string (car (rassoc (match-string 0 text) table)))
6388 t t text)))
6389 text)))
6391 (defun org-xor (a b)
6392 "Exclusive or."
6393 (if a (not b) b))
6395 (defun org-get-header (header)
6396 "Find a header field in the current buffer."
6397 (save-excursion
6398 (goto-char (point-min))
6399 (let ((case-fold-search t) s)
6400 (cond
6401 ((eq header 'from)
6402 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6403 (setq s (match-string 1)))
6404 (while (string-match "\"" s)
6405 (setq s (replace-match "" t t s)))
6406 (if (string-match "[<(].*" s)
6407 (setq s (replace-match "" t t s))))
6408 ((eq header 'message-id)
6409 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6410 (setq s (match-string 1))))
6411 ((eq header 'subject)
6412 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6413 (setq s (match-string 1)))))
6414 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6415 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6416 s)))
6419 (defun org-fixup-message-id-for-http (s)
6420 "Replace special characters in a message id, so it can be used in an http query."
6421 (while (string-match "<" s)
6422 (setq s (replace-match "%3C" t t s)))
6423 (while (string-match ">" s)
6424 (setq s (replace-match "%3E" t t s)))
6425 (while (string-match "@" s)
6426 (setq s (replace-match "%40" t t s)))
6429 ;;;###autoload
6430 (defun org-insert-link-global ()
6431 "Insert a link like Org-mode does.
6432 This command can be called in any mode to insert a link in Org-mode syntax."
6433 (interactive)
6434 (org-load-modules-maybe)
6435 (org-run-like-in-org-mode 'org-insert-link))
6437 (defun org-insert-link (&optional complete-file link-location)
6438 "Insert a link. At the prompt, enter the link.
6440 Completion can be used to select a link previously stored with
6441 `org-store-link'. When the empty string is entered (i.e. if you just
6442 press RET at the prompt), the link defaults to the most recently
6443 stored link. As SPC triggers completion in the minibuffer, you need to
6444 use M-SPC or C-q SPC to force the insertion of a space character.
6446 You will also be prompted for a description, and if one is given, it will
6447 be displayed in the buffer instead of the link.
6449 If there is already a link at point, this command will allow you to edit link
6450 and description parts.
6452 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6453 be selected using completion. The path to the file will be relative to the
6454 current directory if the file is in the current directory or a subdirectory.
6455 Otherwise, the link will be the absolute path as completed in the minibuffer
6456 \(i.e. normally ~/path/to/file).
6458 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6459 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6460 of `org-keep-stored-link-after-insertion'.
6462 If `org-make-link-description-function' is non-nil, this function will be
6463 called with the link target, and the result will be the default
6464 link description.
6466 If the LINK-LOCATION parameter is non-nil, this value will be
6467 used as the link location instead of reading one interactively."
6468 (interactive "P")
6469 (let* ((wcf (current-window-configuration))
6470 (region (if (org-region-active-p)
6471 (buffer-substring (region-beginning) (region-end))))
6472 (remove (and region (list (region-beginning) (region-end))))
6473 (desc region)
6474 tmphist ; byte-compile incorrectly complains about this
6475 (link link-location)
6476 entry file)
6477 (cond
6478 (link-location) ; specified by arg, just use it.
6479 ((org-in-regexp org-bracket-link-regexp 1)
6480 ;; We do have a link at point, and we are going to edit it.
6481 (setq remove (list (match-beginning 0) (match-end 0)))
6482 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6483 (setq link (read-string "Link: "
6484 (org-link-unescape
6485 (org-match-string-no-properties 1)))))
6486 ((or (org-in-regexp org-angle-link-re)
6487 (org-in-regexp org-plain-link-re))
6488 ;; Convert to bracket link
6489 (setq remove (list (match-beginning 0) (match-end 0))
6490 link (read-string "Link: "
6491 (org-remove-angle-brackets (match-string 0)))))
6492 ((equal complete-file '(4))
6493 ;; Completing read for file names.
6494 (setq file (read-file-name "File: "))
6495 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6496 (pwd1 (file-name-as-directory (abbreviate-file-name
6497 (expand-file-name ".")))))
6498 (cond
6499 ((equal complete-file '(16))
6500 (setq link (org-make-link
6501 "file:"
6502 (abbreviate-file-name (expand-file-name file)))))
6503 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6504 (setq link (org-make-link "file:" (match-string 1 file))))
6505 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6506 (expand-file-name file))
6507 (setq link (org-make-link
6508 "file:" (match-string 1 (expand-file-name file)))))
6509 (t (setq link (org-make-link "file:" file))))))
6511 ;; Read link, with completion for stored links.
6512 (with-output-to-temp-buffer "*Org Links*"
6513 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6514 (when org-stored-links
6515 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6516 (princ (mapconcat
6517 (lambda (x)
6518 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6519 (reverse org-stored-links) "\n"))))
6520 (let ((cw (selected-window)))
6521 (select-window (get-buffer-window "*Org Links*"))
6522 (shrink-window-if-larger-than-buffer)
6523 (setq truncate-lines t)
6524 (select-window cw))
6525 ;; Fake a link history, containing the stored links.
6526 (setq tmphist (append (mapcar 'car org-stored-links)
6527 org-insert-link-history))
6528 (unwind-protect
6529 (setq link (org-completing-read
6530 "Link: "
6531 (append
6532 (mapcar (lambda (x) (list (concat (car x) ":")))
6533 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6534 (mapcar (lambda (x) (list (concat x ":")))
6535 org-link-types))
6536 nil nil nil
6537 'tmphist
6538 (or (car (car org-stored-links)))))
6539 (set-window-configuration wcf)
6540 (kill-buffer "*Org Links*"))
6541 (setq entry (assoc link org-stored-links))
6542 (or entry (push link org-insert-link-history))
6543 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6544 (not org-keep-stored-link-after-insertion))
6545 (setq org-stored-links (delq (assoc link org-stored-links)
6546 org-stored-links)))
6547 (setq desc (or desc (nth 1 entry)))))
6549 (if (string-match org-plain-link-re link)
6550 ;; URL-like link, normalize the use of angular brackets.
6551 (setq link (org-make-link (org-remove-angle-brackets link))))
6553 ;; Check if we are linking to the current file with a search option
6554 ;; If yes, simplify the link by using only the search option.
6555 (when (and buffer-file-name
6556 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6557 (let* ((path (match-string 1 link))
6558 (case-fold-search nil)
6559 (search (match-string 2 link)))
6560 (save-match-data
6561 (if (equal (file-truename buffer-file-name) (file-truename path))
6562 ;; We are linking to this same file, with a search option
6563 (setq link search)))))
6565 ;; Check if we can/should use a relative path. If yes, simplify the link
6566 (when (string-match "\\<file:\\(.*\\)" link)
6567 (let* ((path (match-string 1 link))
6568 (origpath path)
6569 (case-fold-search nil))
6570 (cond
6571 ((eq org-link-file-path-type 'absolute)
6572 (setq path (abbreviate-file-name (expand-file-name path))))
6573 ((eq org-link-file-path-type 'noabbrev)
6574 (setq path (expand-file-name path)))
6575 ((eq org-link-file-path-type 'relative)
6576 (setq path (file-relative-name path)))
6578 (save-match-data
6579 (if (string-match (concat "^" (regexp-quote
6580 (file-name-as-directory
6581 (expand-file-name "."))))
6582 (expand-file-name path))
6583 ;; We are linking a file with relative path name.
6584 (setq path (substring (expand-file-name path)
6585 (match-end 0)))))))
6586 (setq link (concat "file:" path))
6587 (if (equal desc origpath)
6588 (setq desc path))))
6590 (if org-make-link-description-function
6591 (setq desc (funcall org-make-link-description-function link desc)))
6593 (setq desc (read-string "Description: " desc))
6594 (unless (string-match "\\S-" desc) (setq desc nil))
6595 (if remove (apply 'delete-region remove))
6596 (insert (org-make-link-string link desc))))
6598 (defun org-completing-read (&rest args)
6599 (let ((minibuffer-local-completion-map
6600 (copy-keymap minibuffer-local-completion-map)))
6601 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6602 (apply 'completing-read args)))
6604 ;;; Opening/following a link
6606 (defvar org-link-search-failed nil)
6608 (defun org-next-link ()
6609 "Move forward to the next link.
6610 If the link is in hidden text, expose it."
6611 (interactive)
6612 (when (and org-link-search-failed (eq this-command last-command))
6613 (goto-char (point-min))
6614 (message "Link search wrapped back to beginning of buffer"))
6615 (setq org-link-search-failed nil)
6616 (let* ((pos (point))
6617 (ct (org-context))
6618 (a (assoc :link ct)))
6619 (if a (goto-char (nth 2 a)))
6620 (if (re-search-forward org-any-link-re nil t)
6621 (progn
6622 (goto-char (match-beginning 0))
6623 (if (org-invisible-p) (org-show-context)))
6624 (goto-char pos)
6625 (setq org-link-search-failed t)
6626 (error "No further link found"))))
6628 (defun org-previous-link ()
6629 "Move backward to the previous link.
6630 If the link is in hidden text, expose it."
6631 (interactive)
6632 (when (and org-link-search-failed (eq this-command last-command))
6633 (goto-char (point-max))
6634 (message "Link search wrapped back to end of buffer"))
6635 (setq org-link-search-failed nil)
6636 (let* ((pos (point))
6637 (ct (org-context))
6638 (a (assoc :link ct)))
6639 (if a (goto-char (nth 1 a)))
6640 (if (re-search-backward org-any-link-re nil t)
6641 (progn
6642 (goto-char (match-beginning 0))
6643 (if (org-invisible-p) (org-show-context)))
6644 (goto-char pos)
6645 (setq org-link-search-failed t)
6646 (error "No further link found"))))
6648 (defun org-find-file-at-mouse (ev)
6649 "Open file link or URL at mouse."
6650 (interactive "e")
6651 (mouse-set-point ev)
6652 (org-open-at-point 'in-emacs))
6654 (defun org-open-at-mouse (ev)
6655 "Open file link or URL at mouse."
6656 (interactive "e")
6657 (mouse-set-point ev)
6658 (org-open-at-point))
6660 (defvar org-window-config-before-follow-link nil
6661 "The window configuration before following a link.
6662 This is saved in case the need arises to restore it.")
6664 (defvar org-open-link-marker (make-marker)
6665 "Marker pointing to the location where `org-open-at-point; was called.")
6667 ;;;###autoload
6668 (defun org-open-at-point-global ()
6669 "Follow a link like Org-mode does.
6670 This command can be called in any mode to follow a link that has
6671 Org-mode syntax."
6672 (interactive)
6673 (org-run-like-in-org-mode 'org-open-at-point))
6675 ;;;###autoload
6676 (defun org-open-link-from-string (s &optional arg)
6677 "Open a link in the string S, as if it was in Org-mode."
6678 (interactive "sLink: \nP")
6679 (with-temp-buffer
6680 (let ((org-inhibit-startup t))
6681 (org-mode)
6682 (insert s)
6683 (goto-char (point-min))
6684 (org-open-at-point arg))))
6686 (defun org-open-at-point (&optional in-emacs)
6687 "Open link at or after point.
6688 If there is no link at point, this function will search forward up to
6689 the end of the current subtree.
6690 Normally, files will be opened by an appropriate application. If the
6691 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6692 (interactive "P")
6693 (org-load-modules-maybe)
6694 (move-marker org-open-link-marker (point))
6695 (setq org-window-config-before-follow-link (current-window-configuration))
6696 (org-remove-occur-highlights nil nil t)
6697 (if (org-at-timestamp-p t)
6698 (org-follow-timestamp-link)
6699 (let (type path link line search (pos (point)))
6700 (catch 'match
6701 (save-excursion
6702 (skip-chars-forward "^]\n\r")
6703 (when (org-in-regexp org-bracket-link-regexp)
6704 (setq link (org-link-unescape (org-match-string-no-properties 1)))
6705 (while (string-match " *\n *" link)
6706 (setq link (replace-match " " t t link)))
6707 (setq link (org-link-expand-abbrev link))
6708 (if (string-match org-link-re-with-space2 link)
6709 (setq type (match-string 1 link) path (match-string 2 link))
6710 (setq type "thisfile" path link))
6711 (throw 'match t)))
6713 (when (get-text-property (point) 'org-linked-text)
6714 (setq type "thisfile"
6715 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6716 (1+ (point)) (point))
6717 path (buffer-substring
6718 (previous-single-property-change pos 'org-linked-text)
6719 (next-single-property-change pos 'org-linked-text)))
6720 (throw 'match t))
6722 (save-excursion
6723 (when (or (org-in-regexp org-angle-link-re)
6724 (org-in-regexp org-plain-link-re))
6725 (setq type (match-string 1) path (match-string 2))
6726 (throw 'match t)))
6727 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6728 (setq type "tree-match"
6729 path (match-string 1))
6730 (throw 'match t))
6731 (save-excursion
6732 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6733 (setq type "tags"
6734 path (match-string 1))
6735 (while (string-match ":" path)
6736 (setq path (replace-match "+" t t path)))
6737 (throw 'match t))))
6738 (unless path
6739 (error "No link found"))
6740 ;; Remove any trailing spaces in path
6741 (if (string-match " +\\'" path)
6742 (setq path (replace-match "" t t path)))
6744 (cond
6746 ((assoc type org-link-protocols)
6747 (funcall (nth 1 (assoc type org-link-protocols)) path))
6749 ((equal type "mailto")
6750 (let ((cmd (car org-link-mailto-program))
6751 (args (cdr org-link-mailto-program)) args1
6752 (address path) (subject "") a)
6753 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6754 (setq address (match-string 1 path)
6755 subject (org-link-escape (match-string 2 path))))
6756 (while args
6757 (cond
6758 ((not (stringp (car args))) (push (pop args) args1))
6759 (t (setq a (pop args))
6760 (if (string-match "%a" a)
6761 (setq a (replace-match address t t a)))
6762 (if (string-match "%s" a)
6763 (setq a (replace-match subject t t a)))
6764 (push a args1))))
6765 (apply cmd (nreverse args1))))
6767 ((member type '("http" "https" "ftp" "news"))
6768 (browse-url (concat type ":" (org-link-escape
6769 path org-link-escape-chars-browser))))
6771 ((member type '("message"))
6772 (browse-url (concat type ":" path)))
6774 ((string= type "tags")
6775 (org-tags-view in-emacs path))
6776 ((string= type "thisfile")
6777 (if in-emacs
6778 (switch-to-buffer-other-window
6779 (org-get-buffer-for-internal-link (current-buffer)))
6780 (org-mark-ring-push))
6781 (let ((cmd `(org-link-search
6782 ,path
6783 ,(cond ((equal in-emacs '(4)) 'occur)
6784 ((equal in-emacs '(16)) 'org-occur)
6785 (t nil))
6786 ,pos)))
6787 (condition-case nil (eval cmd)
6788 (error (progn (widen) (eval cmd))))))
6790 ((string= type "tree-match")
6791 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6793 ((string= type "file")
6794 (if (string-match "::\\([0-9]+\\)\\'" path)
6795 (setq line (string-to-number (match-string 1 path))
6796 path (substring path 0 (match-beginning 0)))
6797 (if (string-match "::\\(.+\\)\\'" path)
6798 (setq search (match-string 1 path)
6799 path (substring path 0 (match-beginning 0)))))
6800 (if (string-match "[*?{]" (file-name-nondirectory path))
6801 (dired path)
6802 (org-open-file path in-emacs line search)))
6804 ((string= type "news")
6805 (require 'org-gnus)
6806 (org-gnus-follow-link path))
6808 ((string= type "shell")
6809 (let ((cmd path))
6810 (if (or (not org-confirm-shell-link-function)
6811 (funcall org-confirm-shell-link-function
6812 (format "Execute \"%s\" in shell? "
6813 (org-add-props cmd nil
6814 'face 'org-warning))))
6815 (progn
6816 (message "Executing %s" cmd)
6817 (shell-command cmd))
6818 (error "Abort"))))
6820 ((string= type "elisp")
6821 (let ((cmd path))
6822 (if (or (not org-confirm-elisp-link-function)
6823 (funcall org-confirm-elisp-link-function
6824 (format "Execute \"%s\" as elisp? "
6825 (org-add-props cmd nil
6826 'face 'org-warning))))
6827 (message "%s => %s" cmd (eval (read cmd)))
6828 (error "Abort"))))
6831 (browse-url-at-point)))))
6832 (move-marker org-open-link-marker nil)
6833 (run-hook-with-args 'org-follow-link-hook))
6835 ;;;; Time estimates
6837 (defun org-get-effort (&optional pom)
6838 "Get the effort estimate for the current entry."
6839 (org-entry-get pom org-effort-property))
6841 ;;; File search
6843 (defvar org-create-file-search-functions nil
6844 "List of functions to construct the right search string for a file link.
6845 These functions are called in turn with point at the location to
6846 which the link should point.
6848 A function in the hook should first test if it would like to
6849 handle this file type, for example by checking the major-mode or
6850 the file extension. If it decides not to handle this file, it
6851 should just return nil to give other functions a chance. If it
6852 does handle the file, it must return the search string to be used
6853 when following the link. The search string will be part of the
6854 file link, given after a double colon, and `org-open-at-point'
6855 will automatically search for it. If special measures must be
6856 taken to make the search successful, another function should be
6857 added to the companion hook `org-execute-file-search-functions',
6858 which see.
6860 A function in this hook may also use `setq' to set the variable
6861 `description' to provide a suggestion for the descriptive text to
6862 be used for this link when it gets inserted into an Org-mode
6863 buffer with \\[org-insert-link].")
6865 (defvar org-execute-file-search-functions nil
6866 "List of functions to execute a file search triggered by a link.
6868 Functions added to this hook must accept a single argument, the
6869 search string that was part of the file link, the part after the
6870 double colon. The function must first check if it would like to
6871 handle this search, for example by checking the major-mode or the
6872 file extension. If it decides not to handle this search, it
6873 should just return nil to give other functions a chance. If it
6874 does handle the search, it must return a non-nil value to keep
6875 other functions from trying.
6877 Each function can access the current prefix argument through the
6878 variable `current-prefix-argument'. Note that a single prefix is
6879 used to force opening a link in Emacs, so it may be good to only
6880 use a numeric or double prefix to guide the search function.
6882 In case this is needed, a function in this hook can also restore
6883 the window configuration before `org-open-at-point' was called using:
6885 (set-window-configuration org-window-config-before-follow-link)")
6887 (defun org-link-search (s &optional type avoid-pos)
6888 "Search for a link search option.
6889 If S is surrounded by forward slashes, it is interpreted as a
6890 regular expression. In org-mode files, this will create an `org-occur'
6891 sparse tree. In ordinary files, `occur' will be used to list matches.
6892 If the current buffer is in `dired-mode', grep will be used to search
6893 in all files. If AVOID-POS is given, ignore matches near that position."
6894 (let ((case-fold-search t)
6895 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6896 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6897 (append '(("") (" ") ("\t") ("\n"))
6898 org-emphasis-alist)
6899 "\\|") "\\)"))
6900 (pos (point))
6901 (pre nil) (post nil)
6902 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6903 (cond
6904 ;; First check if there are any special
6905 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6906 ;; Now try the builtin stuff
6907 ((save-excursion
6908 (goto-char (point-min))
6909 (and
6910 (re-search-forward
6911 (concat "<<" (regexp-quote s0) ">>") nil t)
6912 (setq type 'dedicated
6913 pos (match-beginning 0))))
6914 ;; There is an exact target for this
6915 (goto-char pos))
6916 ((string-match "^/\\(.*\\)/$" s)
6917 ;; A regular expression
6918 (cond
6919 ((org-mode-p)
6920 (org-occur (match-string 1 s)))
6921 ;;((eq major-mode 'dired-mode)
6922 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6923 (t (org-do-occur (match-string 1 s)))))
6925 ;; A normal search strings
6926 (when (equal (string-to-char s) ?*)
6927 ;; Anchor on headlines, post may include tags.
6928 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6929 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6930 s (substring s 1)))
6931 (remove-text-properties
6932 0 (length s)
6933 '(face nil mouse-face nil keymap nil fontified nil) s)
6934 ;; Make a series of regular expressions to find a match
6935 (setq words (org-split-string s "[ \n\r\t]+")
6937 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6938 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6939 "\\)" markers)
6940 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6941 re2a (concat "[ \t\r\n]" re2a_)
6942 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6943 re4 (concat "[^a-zA-Z_]" re4_)
6945 re1 (concat pre re2 post)
6946 re3 (concat pre (if pre re4_ re4) post)
6947 re5 (concat pre ".*" re4)
6948 re2 (concat pre re2)
6949 re2a (concat pre (if pre re2a_ re2a))
6950 re4 (concat pre (if pre re4_ re4))
6951 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6952 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6953 re5 "\\)"
6955 (cond
6956 ((eq type 'org-occur) (org-occur reall))
6957 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6958 (t (goto-char (point-min))
6959 (setq type 'fuzzy)
6960 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
6961 (org-search-not-self 1 re1 nil t)
6962 (org-search-not-self 1 re2 nil t)
6963 (org-search-not-self 1 re2a nil t)
6964 (org-search-not-self 1 re3 nil t)
6965 (org-search-not-self 1 re4 nil t)
6966 (org-search-not-self 1 re5 nil t)
6968 (goto-char (match-beginning 1))
6969 (goto-char pos)
6970 (error "No match")))))
6972 ;; Normal string-search
6973 (goto-char (point-min))
6974 (if (search-forward s nil t)
6975 (goto-char (match-beginning 0))
6976 (error "No match"))))
6977 (and (org-mode-p) (org-show-context 'link-search))
6978 type))
6980 (defun org-search-not-self (group &rest args)
6981 "Execute `re-search-forward', but only accept matches that do not
6982 enclose the position of `org-open-link-marker'."
6983 (let ((m org-open-link-marker))
6984 (catch 'exit
6985 (while (apply 're-search-forward args)
6986 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
6987 (goto-char (match-end group))
6988 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
6989 (> (match-beginning 0) (marker-position m))
6990 (< (match-end 0) (marker-position m)))
6991 (save-match-data
6992 (or (not (org-in-regexp
6993 org-bracket-link-analytic-regexp 1))
6994 (not (match-end 4)) ; no description
6995 (and (<= (match-beginning 4) (point))
6996 (>= (match-end 4) (point))))))
6997 (throw 'exit (point))))))))
6999 (defun org-get-buffer-for-internal-link (buffer)
7000 "Return a buffer to be used for displaying the link target of internal links."
7001 (cond
7002 ((not org-display-internal-link-with-indirect-buffer)
7003 buffer)
7004 ((string-match "(Clone)$" (buffer-name buffer))
7005 (message "Buffer is already a clone, not making another one")
7006 ;; we also do not modify visibility in this case
7007 buffer)
7008 (t ; make a new indirect buffer for displaying the link
7009 (let* ((bn (buffer-name buffer))
7010 (ibn (concat bn "(Clone)"))
7011 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7012 (with-current-buffer ib (org-overview))
7013 ib))))
7015 (defun org-do-occur (regexp &optional cleanup)
7016 "Call the Emacs command `occur'.
7017 If CLEANUP is non-nil, remove the printout of the regular expression
7018 in the *Occur* buffer. This is useful if the regex is long and not useful
7019 to read."
7020 (occur regexp)
7021 (when cleanup
7022 (let ((cwin (selected-window)) win beg end)
7023 (when (setq win (get-buffer-window "*Occur*"))
7024 (select-window win))
7025 (goto-char (point-min))
7026 (when (re-search-forward "match[a-z]+" nil t)
7027 (setq beg (match-end 0))
7028 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7029 (setq end (1- (match-beginning 0)))))
7030 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7031 (goto-char (point-min))
7032 (select-window cwin))))
7034 ;;; The mark ring for links jumps
7036 (defvar org-mark-ring nil
7037 "Mark ring for positions before jumps in Org-mode.")
7038 (defvar org-mark-ring-last-goto nil
7039 "Last position in the mark ring used to go back.")
7040 ;; Fill and close the ring
7041 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7042 (loop for i from 1 to org-mark-ring-length do
7043 (push (make-marker) org-mark-ring))
7044 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7045 org-mark-ring)
7047 (defun org-mark-ring-push (&optional pos buffer)
7048 "Put the current position or POS into the mark ring and rotate it."
7049 (interactive)
7050 (setq pos (or pos (point)))
7051 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7052 (move-marker (car org-mark-ring)
7053 (or pos (point))
7054 (or buffer (current-buffer)))
7055 (message "%s"
7056 (substitute-command-keys
7057 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7059 (defun org-mark-ring-goto (&optional n)
7060 "Jump to the previous position in the mark ring.
7061 With prefix arg N, jump back that many stored positions. When
7062 called several times in succession, walk through the entire ring.
7063 Org-mode commands jumping to a different position in the current file,
7064 or to another Org-mode file, automatically push the old position
7065 onto the ring."
7066 (interactive "p")
7067 (let (p m)
7068 (if (eq last-command this-command)
7069 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7070 (setq p org-mark-ring))
7071 (setq org-mark-ring-last-goto p)
7072 (setq m (car p))
7073 (switch-to-buffer (marker-buffer m))
7074 (goto-char m)
7075 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7077 (defun org-remove-angle-brackets (s)
7078 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7079 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7081 (defun org-add-angle-brackets (s)
7082 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7083 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7086 ;;; Following specific links
7088 (defun org-follow-timestamp-link ()
7089 (cond
7090 ((org-at-date-range-p t)
7091 (let ((org-agenda-start-on-weekday)
7092 (t1 (match-string 1))
7093 (t2 (match-string 2)))
7094 (setq t1 (time-to-days (org-time-string-to-time t1))
7095 t2 (time-to-days (org-time-string-to-time t2)))
7096 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7097 ((org-at-timestamp-p t)
7098 (org-agenda-list nil (time-to-days (org-time-string-to-time
7099 (substring (match-string 1) 0 10)))
7101 (t (error "This should not happen"))))
7104 ;;; Following file links
7105 (defvar org-wait nil)
7106 (defun org-open-file (path &optional in-emacs line search)
7107 "Open the file at PATH.
7108 First, this expands any special file name abbreviations. Then the
7109 configuration variable `org-file-apps' is checked if it contains an
7110 entry for this file type, and if yes, the corresponding command is launched.
7111 If no application is found, Emacs simply visits the file.
7112 With optional argument IN-EMACS, Emacs will visit the file.
7113 Optional LINE specifies a line to go to, optional SEARCH a string to
7114 search for. If LINE or SEARCH is given, the file will always be
7115 opened in Emacs.
7116 If the file does not exist, an error is thrown."
7117 (setq in-emacs (or in-emacs line search))
7118 (let* ((file (if (equal path "")
7119 buffer-file-name
7120 (substitute-in-file-name (expand-file-name path))))
7121 (apps (append org-file-apps (org-default-apps)))
7122 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7123 (dirp (if remp nil (file-directory-p file)))
7124 (dfile (downcase file))
7125 (old-buffer (current-buffer))
7126 (old-pos (point))
7127 (old-mode major-mode)
7128 ext cmd)
7129 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7130 (setq ext (match-string 1 dfile))
7131 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7132 (setq ext (match-string 1 dfile))))
7133 (if in-emacs
7134 (setq cmd 'emacs)
7135 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7136 (and dirp (cdr (assoc 'directory apps)))
7137 (cdr (assoc ext apps))
7138 (cdr (assoc t apps)))))
7139 (when (eq cmd 'mailcap)
7140 (require 'mailcap)
7141 (mailcap-parse-mailcaps)
7142 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7143 (command (mailcap-mime-info mime-type)))
7144 (if (stringp command)
7145 (setq cmd command)
7146 (setq cmd 'emacs))))
7147 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7148 (not (file-exists-p file))
7149 (not org-open-non-existing-files))
7150 (error "No such file: %s" file))
7151 (cond
7152 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7153 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7154 (while (string-match "['\"]%s['\"]" cmd)
7155 (setq cmd (replace-match "%s" t t cmd)))
7156 (while (string-match "%s" cmd)
7157 (setq cmd (replace-match
7158 (save-match-data (shell-quote-argument file))
7159 t t cmd)))
7160 (save-window-excursion
7161 (start-process-shell-command cmd nil cmd)
7162 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7164 ((or (stringp cmd)
7165 (eq cmd 'emacs))
7166 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7167 (widen)
7168 (if line (goto-line line)
7169 (if search (org-link-search search))))
7170 ((consp cmd)
7171 (eval cmd))
7172 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7173 (and (org-mode-p) (eq old-mode 'org-mode)
7174 (or (not (equal old-buffer (current-buffer)))
7175 (not (equal old-pos (point))))
7176 (org-mark-ring-push old-pos old-buffer))))
7178 (defun org-default-apps ()
7179 "Return the default applications for this operating system."
7180 (cond
7181 ((eq system-type 'darwin)
7182 org-file-apps-defaults-macosx)
7183 ((eq system-type 'windows-nt)
7184 org-file-apps-defaults-windowsnt)
7185 (t org-file-apps-defaults-gnu)))
7187 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7188 (defun org-file-remote-p (file)
7189 "Test whether FILE specifies a location on a remote system.
7190 Return non-nil if the location is indeed remote.
7192 For example, the filename \"/user@host:/foo\" specifies a location
7193 on the system \"/user@host:\"."
7194 (cond ((fboundp 'file-remote-p)
7195 (file-remote-p file))
7196 ((fboundp 'tramp-handle-file-remote-p)
7197 (tramp-handle-file-remote-p file))
7198 ((and (boundp 'ange-ftp-name-format)
7199 (string-match (car ange-ftp-name-format) file))
7201 (t nil)))
7204 ;;;; Refiling
7206 (defun org-get-org-file ()
7207 "Read a filename, with default directory `org-directory'."
7208 (let ((default (or org-default-notes-file remember-data-file)))
7209 (read-file-name (format "File name [%s]: " default)
7210 (file-name-as-directory org-directory)
7211 default)))
7213 (defun org-notes-order-reversed-p ()
7214 "Check if the current file should receive notes in reversed order."
7215 (cond
7216 ((not org-reverse-note-order) nil)
7217 ((eq t org-reverse-note-order) t)
7218 ((not (listp org-reverse-note-order)) nil)
7219 (t (catch 'exit
7220 (let ((all org-reverse-note-order)
7221 entry)
7222 (while (setq entry (pop all))
7223 (if (string-match (car entry) buffer-file-name)
7224 (throw 'exit (cdr entry))))
7225 nil)))))
7227 (defvar org-refile-target-table nil
7228 "The list of refile targets, created by `org-refile'.")
7230 (defvar org-agenda-new-buffers nil
7231 "Buffers created to visit agenda files.")
7233 (defun org-get-refile-targets (&optional default-buffer)
7234 "Produce a table with refile targets."
7235 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7236 targets txt re files f desc descre)
7237 (with-current-buffer (or default-buffer (current-buffer))
7238 (while (setq entry (pop entries))
7239 (setq files (car entry) desc (cdr entry))
7240 (cond
7241 ((null files) (setq files (list (current-buffer))))
7242 ((eq files 'org-agenda-files)
7243 (setq files (org-agenda-files 'unrestricted)))
7244 ((and (symbolp files) (fboundp files))
7245 (setq files (funcall files)))
7246 ((and (symbolp files) (boundp files))
7247 (setq files (symbol-value files))))
7248 (if (stringp files) (setq files (list files)))
7249 (cond
7250 ((eq (car desc) :tag)
7251 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7252 ((eq (car desc) :todo)
7253 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7254 ((eq (car desc) :regexp)
7255 (setq descre (cdr desc)))
7256 ((eq (car desc) :level)
7257 (setq descre (concat "^\\*\\{" (number-to-string
7258 (if org-odd-levels-only
7259 (1- (* 2 (cdr desc)))
7260 (cdr desc)))
7261 "\\}[ \t]")))
7262 ((eq (car desc) :maxlevel)
7263 (setq descre (concat "^\\*\\{1," (number-to-string
7264 (if org-odd-levels-only
7265 (1- (* 2 (cdr desc)))
7266 (cdr desc)))
7267 "\\}[ \t]")))
7268 (t (error "Bad refiling target description %s" desc)))
7269 (while (setq f (pop files))
7270 (save-excursion
7271 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7272 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7273 (save-excursion
7274 (save-restriction
7275 (widen)
7276 (goto-char (point-min))
7277 (while (re-search-forward descre nil t)
7278 (goto-char (point-at-bol))
7279 (when (looking-at org-complex-heading-regexp)
7280 (setq txt (match-string 4)
7281 re (concat "^" (regexp-quote
7282 (buffer-substring (match-beginning 1)
7283 (match-end 4)))))
7284 (if (match-end 5) (setq re (concat re "[ \t]+"
7285 (regexp-quote
7286 (match-string 5)))))
7287 (setq re (concat re "[ \t]*$"))
7288 (when org-refile-use-outline-path
7289 (setq txt (mapconcat 'identity
7290 (append
7291 (if (eq org-refile-use-outline-path 'file)
7292 (list (file-name-nondirectory
7293 (buffer-file-name (buffer-base-buffer))))
7294 (if (eq org-refile-use-outline-path 'full-file-path)
7295 (list (buffer-file-name (buffer-base-buffer)))))
7296 (org-get-outline-path)
7297 (list txt))
7298 "/")))
7299 (push (list txt f re (point)) targets))
7300 (goto-char (point-at-eol))))))))
7301 (nreverse targets))))
7303 (defun org-get-outline-path ()
7304 "Return the outline path to the current entry, as a list."
7305 (let (rtn)
7306 (save-excursion
7307 (while (org-up-heading-safe)
7308 (when (looking-at org-complex-heading-regexp)
7309 (push (org-match-string-no-properties 4) rtn)))
7310 rtn)))
7312 (defvar org-refile-history nil
7313 "History for refiling operations.")
7315 (defun org-refile (&optional goto default-buffer)
7316 "Move the entry at point to another heading.
7317 The list of target headings is compiled using the information in
7318 `org-refile-targets', which see. This list is created before each use
7319 and will therefore always be up-to-date.
7321 At the target location, the entry is filed as a subitem of the target heading.
7322 Depending on `org-reverse-note-order', the new subitem will either be the
7323 first of the last subitem.
7325 With prefix arg GOTO, the command will only visit the target location,
7326 not actually move anything.
7327 With a double prefix `C-c C-c', go to the location where the last refiling
7328 operation has put the subtree."
7329 (interactive "P")
7330 (let* ((cbuf (current-buffer))
7331 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7332 pos it nbuf file re level reversed)
7333 (if (equal goto '(16))
7334 (org-refile-goto-last-stored)
7335 (when (setq it (org-refile-get-location
7336 (if goto "Goto: " "Refile to: ") default-buffer))
7337 (setq file (nth 1 it)
7338 re (nth 2 it)
7339 pos (nth 3 it))
7340 (setq nbuf (or (find-buffer-visiting file)
7341 (find-file-noselect file)))
7342 (if goto
7343 (progn
7344 (switch-to-buffer nbuf)
7345 (goto-char pos)
7346 (org-show-context 'org-goto))
7347 (org-copy-special)
7348 (save-excursion
7349 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7350 (find-file-noselect file))))
7351 (setq reversed (org-notes-order-reversed-p))
7352 (save-excursion
7353 (save-restriction
7354 (widen)
7355 (goto-char pos)
7356 (looking-at outline-regexp)
7357 (setq level (org-get-valid-level (funcall outline-level) 1))
7358 (goto-char
7359 (if reversed
7360 (outline-next-heading)
7361 (or (save-excursion (outline-get-next-sibling))
7362 (org-end-of-subtree t t)
7363 (point-max))))
7364 (bookmark-set "org-refile-last-stored")
7365 (org-paste-subtree level))))
7366 (org-cut-special)
7367 (message "Entry refiled to \"%s\"" (car it)))))))
7369 (defun org-refile-goto-last-stored ()
7370 "Go to the location where the last refile was stored."
7371 (interactive)
7372 (bookmark-jump "org-refile-last-stored")
7373 (message "This is the location of the last refile"))
7375 (defun org-refile-get-location (&optional prompt default-buffer)
7376 "Prompt the user for a refile location, using PROMPT."
7377 (let ((org-refile-targets org-refile-targets)
7378 (org-refile-use-outline-path org-refile-use-outline-path))
7379 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7380 (unless org-refile-target-table
7381 (error "No refile targets"))
7382 (let* ((cbuf (current-buffer))
7383 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7384 (fname (and filename (file-truename filename)))
7385 (tbl (mapcar
7386 (lambda (x)
7387 (if (not (equal fname (file-truename (nth 1 x))))
7388 (cons (concat (car x) " (" (file-name-nondirectory
7389 (nth 1 x)) ")")
7390 (cdr x))
7392 org-refile-target-table))
7393 (completion-ignore-case t))
7394 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
7395 tbl)))
7397 ;;;; Dynamic blocks
7399 (defun org-find-dblock (name)
7400 "Find the first dynamic block with name NAME in the buffer.
7401 If not found, stay at current position and return nil."
7402 (let (pos)
7403 (save-excursion
7404 (goto-char (point-min))
7405 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7406 nil t)
7407 (match-beginning 0))))
7408 (if pos (goto-char pos))
7409 pos))
7411 (defconst org-dblock-start-re
7412 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7413 "Matches the startline of a dynamic block, with parameters.")
7415 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7416 "Matches the end of a dyhamic block.")
7418 (defun org-create-dblock (plist)
7419 "Create a dynamic block section, with parameters taken from PLIST.
7420 PLIST must containe a :name entry which is used as name of the block."
7421 (unless (bolp) (newline))
7422 (let ((name (plist-get plist :name)))
7423 (insert "#+BEGIN: " name)
7424 (while plist
7425 (if (eq (car plist) :name)
7426 (setq plist (cddr plist))
7427 (insert " " (prin1-to-string (pop plist)))))
7428 (insert "\n\n#+END:\n")
7429 (beginning-of-line -2)))
7431 (defun org-prepare-dblock ()
7432 "Prepare dynamic block for refresh.
7433 This empties the block, puts the cursor at the insert position and returns
7434 the property list including an extra property :name with the block name."
7435 (unless (looking-at org-dblock-start-re)
7436 (error "Not at a dynamic block"))
7437 (let* ((begdel (1+ (match-end 0)))
7438 (name (org-no-properties (match-string 1)))
7439 (params (append (list :name name)
7440 (read (concat "(" (match-string 3) ")")))))
7441 (unless (re-search-forward org-dblock-end-re nil t)
7442 (error "Dynamic block not terminated"))
7443 (setq params
7444 (append params
7445 (list :content (buffer-substring
7446 begdel (match-beginning 0)))))
7447 (delete-region begdel (match-beginning 0))
7448 (goto-char begdel)
7449 (open-line 1)
7450 params))
7452 (defun org-map-dblocks (&optional command)
7453 "Apply COMMAND to all dynamic blocks in the current buffer.
7454 If COMMAND is not given, use `org-update-dblock'."
7455 (let ((cmd (or command 'org-update-dblock))
7456 pos)
7457 (save-excursion
7458 (goto-char (point-min))
7459 (while (re-search-forward org-dblock-start-re nil t)
7460 (goto-char (setq pos (match-beginning 0)))
7461 (condition-case nil
7462 (funcall cmd)
7463 (error (message "Error during update of dynamic block")))
7464 (goto-char pos)
7465 (unless (re-search-forward org-dblock-end-re nil t)
7466 (error "Dynamic block not terminated"))))))
7468 (defun org-dblock-update (&optional arg)
7469 "User command for updating dynamic blocks.
7470 Update the dynamic block at point. With prefix ARG, update all dynamic
7471 blocks in the buffer."
7472 (interactive "P")
7473 (if arg
7474 (org-update-all-dblocks)
7475 (or (looking-at org-dblock-start-re)
7476 (org-beginning-of-dblock))
7477 (org-update-dblock)))
7479 (defun org-update-dblock ()
7480 "Update the dynamic block at point
7481 This means to empty the block, parse for parameters and then call
7482 the correct writing function."
7483 (save-window-excursion
7484 (let* ((pos (point))
7485 (line (org-current-line))
7486 (params (org-prepare-dblock))
7487 (name (plist-get params :name))
7488 (cmd (intern (concat "org-dblock-write:" name))))
7489 (message "Updating dynamic block `%s' at line %d..." name line)
7490 (funcall cmd params)
7491 (message "Updating dynamic block `%s' at line %d...done" name line)
7492 (goto-char pos))))
7494 (defun org-beginning-of-dblock ()
7495 "Find the beginning of the dynamic block at point.
7496 Error if there is no scuh block at point."
7497 (let ((pos (point))
7498 beg)
7499 (end-of-line 1)
7500 (if (and (re-search-backward org-dblock-start-re nil t)
7501 (setq beg (match-beginning 0))
7502 (re-search-forward org-dblock-end-re nil t)
7503 (> (match-end 0) pos))
7504 (goto-char beg)
7505 (goto-char pos)
7506 (error "Not in a dynamic block"))))
7508 (defun org-update-all-dblocks ()
7509 "Update all dynamic blocks in the buffer.
7510 This function can be used in a hook."
7511 (when (org-mode-p)
7512 (org-map-dblocks 'org-update-dblock)))
7515 ;;;; Completion
7517 (defconst org-additional-option-like-keywords
7518 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7519 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7520 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7522 (defun org-complete (&optional arg)
7523 "Perform completion on word at point.
7524 At the beginning of a headline, this completes TODO keywords as given in
7525 `org-todo-keywords'.
7526 If the current word is preceded by a backslash, completes the TeX symbols
7527 that are supported for HTML support.
7528 If the current word is preceded by \"#+\", completes special words for
7529 setting file options.
7530 In the line after \"#+STARTUP:, complete valid keywords.\"
7531 At all other locations, this simply calls the value of
7532 `org-completion-fallback-command'."
7533 (interactive "P")
7534 (org-without-partial-completion
7535 (catch 'exit
7536 (let* ((end (point))
7537 (beg1 (save-excursion
7538 (skip-chars-backward (org-re "[:alnum:]_@"))
7539 (point)))
7540 (beg (save-excursion
7541 (skip-chars-backward "a-zA-Z0-9_:$")
7542 (point)))
7543 (confirm (lambda (x) (stringp (car x))))
7544 (searchhead (equal (char-before beg) ?*))
7545 (tag (and (equal (char-before beg1) ?:)
7546 (equal (char-after (point-at-bol)) ?*)))
7547 (prop (and (equal (char-before beg1) ?:)
7548 (not (equal (char-after (point-at-bol)) ?*))))
7549 (texp (equal (char-before beg) ?\\))
7550 (link (equal (char-before beg) ?\[))
7551 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7552 beg)
7553 "#+"))
7554 (startup (string-match "^#\\+STARTUP:.*"
7555 (buffer-substring (point-at-bol) (point))))
7556 (completion-ignore-case opt)
7557 (type nil)
7558 (tbl nil)
7559 (table (cond
7560 (opt
7561 (setq type :opt)
7562 (require 'org-exp)
7563 (append
7564 (mapcar
7565 (lambda (x)
7566 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7567 (cons (match-string 2 x) (match-string 1 x)))
7568 (org-split-string (org-get-current-options) "\n"))
7569 (mapcar 'list org-additional-option-like-keywords)))
7570 (startup
7571 (setq type :startup)
7572 org-startup-options)
7573 (link (append org-link-abbrev-alist-local
7574 org-link-abbrev-alist))
7575 (texp
7576 (setq type :tex)
7577 org-html-entities)
7578 ((string-match "\\`\\*+[ \t]+\\'"
7579 (buffer-substring (point-at-bol) beg))
7580 (setq type :todo)
7581 (mapcar 'list org-todo-keywords-1))
7582 (searchhead
7583 (setq type :searchhead)
7584 (save-excursion
7585 (goto-char (point-min))
7586 (while (re-search-forward org-todo-line-regexp nil t)
7587 (push (list
7588 (org-make-org-heading-search-string
7589 (match-string 3) t))
7590 tbl)))
7591 tbl)
7592 (tag (setq type :tag beg beg1)
7593 (or org-tag-alist (org-get-buffer-tags)))
7594 (prop (setq type :prop beg beg1)
7595 (mapcar 'list (org-buffer-property-keys nil t t)))
7596 (t (progn
7597 (call-interactively org-completion-fallback-command)
7598 (throw 'exit nil)))))
7599 (pattern (buffer-substring-no-properties beg end))
7600 (completion (try-completion pattern table confirm)))
7601 (cond ((eq completion t)
7602 (if (not (assoc (upcase pattern) table))
7603 (message "Already complete")
7604 (if (and (equal type :opt)
7605 (not (member (car (assoc (upcase pattern) table))
7606 org-additional-option-like-keywords)))
7607 (insert (substring (cdr (assoc (upcase pattern) table))
7608 (length pattern)))
7609 (if (memq type '(:tag :prop)) (insert ":")))))
7610 ((null completion)
7611 (message "Can't find completion for \"%s\"" pattern)
7612 (ding))
7613 ((not (string= pattern completion))
7614 (delete-region beg end)
7615 (if (string-match " +$" completion)
7616 (setq completion (replace-match "" t t completion)))
7617 (insert completion)
7618 (if (get-buffer-window "*Completions*")
7619 (delete-window (get-buffer-window "*Completions*")))
7620 (if (assoc completion table)
7621 (if (eq type :todo) (insert " ")
7622 (if (memq type '(:tag :prop)) (insert ":"))))
7623 (if (and (equal type :opt) (assoc completion table))
7624 (message "%s" (substitute-command-keys
7625 "Press \\[org-complete] again to insert example settings"))))
7627 (message "Making completion list...")
7628 (let ((list (sort (all-completions pattern table confirm)
7629 'string<)))
7630 (with-output-to-temp-buffer "*Completions*"
7631 (condition-case nil
7632 ;; Protection needed for XEmacs and emacs 21
7633 (display-completion-list list pattern)
7634 (error (display-completion-list list)))))
7635 (message "Making completion list...%s" "done")))))))
7637 ;;;; TODO, DEADLINE, Comments
7639 (defun org-toggle-comment ()
7640 "Change the COMMENT state of an entry."
7641 (interactive)
7642 (save-excursion
7643 (org-back-to-heading)
7644 (let (case-fold-search)
7645 (if (looking-at (concat outline-regexp
7646 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7647 (replace-match "" t t nil 1)
7648 (if (looking-at outline-regexp)
7649 (progn
7650 (goto-char (match-end 0))
7651 (insert org-comment-string " ")))))))
7653 (defvar org-last-todo-state-is-todo nil
7654 "This is non-nil when the last TODO state change led to a TODO state.
7655 If the last change removed the TODO tag or switched to DONE, then
7656 this is nil.")
7658 (defvar org-setting-tags nil) ; dynamically skiped
7660 (defun org-parse-local-options (string var)
7661 "Parse STRING for startup setting relevant for variable VAR."
7662 (let ((rtn (symbol-value var))
7663 e opts)
7664 (save-match-data
7665 (if (or (not string) (not (string-match "\\S-" string)))
7667 (setq opts (delq nil (mapcar (lambda (x)
7668 (setq e (assoc x org-startup-options))
7669 (if (eq (nth 1 e) var) e nil))
7670 (org-split-string string "[ \t]+"))))
7671 (if (not opts)
7673 (setq rtn nil)
7674 (while (setq e (pop opts))
7675 (if (not (nth 3 e))
7676 (setq rtn (nth 2 e))
7677 (if (not (listp rtn)) (setq rtn nil))
7678 (push (nth 2 e) rtn)))
7679 rtn)))))
7681 (defvar org-blocker-hook nil
7682 "Hook for functions that are allowed to block a state change.
7684 Each function gets as its single argument a property list, see
7685 `org-trigger-hook' for more information about this list.
7687 If any of the functions in this hook returns nil, the state change
7688 is blocked.")
7690 (defvar org-trigger-hook nil
7691 "Hook for functions that are triggered by a state change.
7693 Each function gets as its single argument a property list with at least
7694 the following elements:
7696 (:type type-of-change :position pos-at-entry-start
7697 :from old-state :to new-state)
7699 Depending on the type, more properties may be present.
7701 This mechanism is currently implemented for:
7703 TODO state changes
7704 ------------------
7705 :type todo-state-change
7706 :from previous state (keyword as a string), or nil
7707 :to new state (keyword as a string), or nil")
7710 (defun org-todo (&optional arg)
7711 "Change the TODO state of an item.
7712 The state of an item is given by a keyword at the start of the heading,
7713 like
7714 *** TODO Write paper
7715 *** DONE Call mom
7717 The different keywords are specified in the variable `org-todo-keywords'.
7718 By default the available states are \"TODO\" and \"DONE\".
7719 So for this example: when the item starts with TODO, it is changed to DONE.
7720 When it starts with DONE, the DONE is removed. And when neither TODO nor
7721 DONE are present, add TODO at the beginning of the heading.
7723 With C-u prefix arg, use completion to determine the new state.
7724 With numeric prefix arg, switch to that state.
7726 For calling through lisp, arg is also interpreted in the following way:
7727 'none -> empty state
7728 \"\"(empty string) -> switch to empty state
7729 'done -> switch to DONE
7730 'nextset -> switch to the next set of keywords
7731 'previousset -> switch to the previous set of keywords
7732 \"WAITING\" -> switch to the specified keyword, but only if it
7733 really is a member of `org-todo-keywords'."
7734 (interactive "P")
7735 (save-excursion
7736 (catch 'exit
7737 (org-back-to-heading)
7738 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7739 (or (looking-at (concat " +" org-todo-regexp " *"))
7740 (looking-at " *"))
7741 (let* ((match-data (match-data))
7742 (startpos (point-at-bol))
7743 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7744 (org-log-done org-log-done)
7745 (org-log-repeat org-log-repeat)
7746 (org-todo-log-states org-todo-log-states)
7747 (this (match-string 1))
7748 (hl-pos (match-beginning 0))
7749 (head (org-get-todo-sequence-head this))
7750 (ass (assoc head org-todo-kwd-alist))
7751 (interpret (nth 1 ass))
7752 (done-word (nth 3 ass))
7753 (final-done-word (nth 4 ass))
7754 (last-state (or this ""))
7755 (completion-ignore-case t)
7756 (member (member this org-todo-keywords-1))
7757 (tail (cdr member))
7758 (state (cond
7759 ((and org-todo-key-trigger
7760 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7761 (and (not arg) org-use-fast-todo-selection
7762 (not (eq org-use-fast-todo-selection 'prefix)))))
7763 ;; Use fast selection
7764 (org-fast-todo-selection))
7765 ((and (equal arg '(4))
7766 (or (not org-use-fast-todo-selection)
7767 (not org-todo-key-trigger)))
7768 ;; Read a state with completion
7769 (completing-read "State: " (mapcar (lambda(x) (list x))
7770 org-todo-keywords-1)
7771 nil t))
7772 ((eq arg 'right)
7773 (if this
7774 (if tail (car tail) nil)
7775 (car org-todo-keywords-1)))
7776 ((eq arg 'left)
7777 (if (equal member org-todo-keywords-1)
7779 (if this
7780 (nth (- (length org-todo-keywords-1) (length tail) 2)
7781 org-todo-keywords-1)
7782 (org-last org-todo-keywords-1))))
7783 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7784 (setq arg nil))) ; hack to fall back to cycling
7785 (arg
7786 ;; user or caller requests a specific state
7787 (cond
7788 ((equal arg "") nil)
7789 ((eq arg 'none) nil)
7790 ((eq arg 'done) (or done-word (car org-done-keywords)))
7791 ((eq arg 'nextset)
7792 (or (car (cdr (member head org-todo-heads)))
7793 (car org-todo-heads)))
7794 ((eq arg 'previousset)
7795 (let ((org-todo-heads (reverse org-todo-heads)))
7796 (or (car (cdr (member head org-todo-heads)))
7797 (car org-todo-heads))))
7798 ((car (member arg org-todo-keywords-1)))
7799 ((nth (1- (prefix-numeric-value arg))
7800 org-todo-keywords-1))))
7801 ((null member) (or head (car org-todo-keywords-1)))
7802 ((equal this final-done-word) nil) ;; -> make empty
7803 ((null tail) nil) ;; -> first entry
7804 ((eq interpret 'sequence)
7805 (car tail))
7806 ((memq interpret '(type priority))
7807 (if (eq this-command last-command)
7808 (car tail)
7809 (if (> (length tail) 0)
7810 (or done-word (car org-done-keywords))
7811 nil)))
7812 (t nil)))
7813 (next (if state (concat " " state " ") " "))
7814 (change-plist (list :type 'todo-state-change :from this :to state
7815 :position startpos))
7816 dolog now-done-p)
7817 (when org-blocker-hook
7818 (unless (save-excursion
7819 (save-match-data
7820 (run-hook-with-args-until-failure
7821 'org-blocker-hook change-plist)))
7822 (if (interactive-p)
7823 (error "TODO state change from %s to %s blocked" this state)
7824 ;; fail silently
7825 (message "TODO state change from %s to %s blocked" this state)
7826 (throw 'exit nil))))
7827 (store-match-data match-data)
7828 (replace-match next t t)
7829 (unless (pos-visible-in-window-p hl-pos)
7830 (message "TODO state changed to %s" (org-trim next)))
7831 (unless head
7832 (setq head (org-get-todo-sequence-head state)
7833 ass (assoc head org-todo-kwd-alist)
7834 interpret (nth 1 ass)
7835 done-word (nth 3 ass)
7836 final-done-word (nth 4 ass)))
7837 (when (memq arg '(nextset previousset))
7838 (message "Keyword-Set %d/%d: %s"
7839 (- (length org-todo-sets) -1
7840 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7841 (length org-todo-sets)
7842 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7843 (setq org-last-todo-state-is-todo
7844 (not (member state org-done-keywords)))
7845 (setq now-done-p (and (member state org-done-keywords)
7846 (not (member this org-done-keywords))))
7847 (and logging (org-local-logging logging))
7848 (when (and (or org-todo-log-states org-log-done)
7849 (not (memq arg '(nextset previousset))))
7850 ;; we need to look at recording a time and note
7851 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7852 (nth 2 (assoc this org-todo-log-states))))
7853 (when (and state
7854 (member state org-not-done-keywords)
7855 (not (member this org-not-done-keywords)))
7856 ;; This is now a todo state and was not one before
7857 ;; If there was a CLOSED time stamp, get rid of it.
7858 (org-add-planning-info nil nil 'closed))
7859 (when (and now-done-p org-log-done)
7860 ;; It is now done, and it was not done before
7861 (org-add-planning-info 'closed (org-current-time))
7862 (if (and (not dolog) (eq 'note org-log-done))
7863 (org-add-log-setup 'done state 'findpos 'note)))
7864 (when (and state dolog)
7865 ;; This is a non-nil state, and we need to log it
7866 (org-add-log-setup 'state state 'findpos dolog)))
7867 ;; Fixup tag positioning
7868 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7869 (run-hooks 'org-after-todo-state-change-hook)
7870 (if (and arg (not (member state org-done-keywords)))
7871 (setq head (org-get-todo-sequence-head state)))
7872 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7873 ;; Do we need to trigger a repeat?
7874 (when now-done-p (org-auto-repeat-maybe state))
7875 ;; Fixup cursor location if close to the keyword
7876 (if (and (outline-on-heading-p)
7877 (not (bolp))
7878 (save-excursion (beginning-of-line 1)
7879 (looking-at org-todo-line-regexp))
7880 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7881 (progn
7882 (goto-char (or (match-end 2) (match-end 1)))
7883 (just-one-space)))
7884 (when org-trigger-hook
7885 (save-excursion
7886 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7888 (defun org-local-logging (value)
7889 "Get logging settings from a property VALUE."
7890 (let* (words w a)
7891 ;; directly set the variables, they are already local.
7892 (setq org-log-done nil
7893 org-log-repeat nil
7894 org-todo-log-states nil)
7895 (setq words (org-split-string value))
7896 (while (setq w (pop words))
7897 (cond
7898 ((setq a (assoc w org-startup-options))
7899 (and (member (nth 1 a) '(org-log-done org-log-repeat))
7900 (set (nth 1 a) (nth 2 a))))
7901 ((setq a (org-extract-log-state-settings w))
7902 (and (member (car a) org-todo-keywords-1)
7903 (push a org-todo-log-states)))))))
7905 (defun org-get-todo-sequence-head (kwd)
7906 "Return the head of the TODO sequence to which KWD belongs.
7907 If KWD is not set, check if there is a text property remembering the
7908 right sequence."
7909 (let (p)
7910 (cond
7911 ((not kwd)
7912 (or (get-text-property (point-at-bol) 'org-todo-head)
7913 (progn
7914 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
7915 nil (point-at-eol)))
7916 (get-text-property p 'org-todo-head))))
7917 ((not (member kwd org-todo-keywords-1))
7918 (car org-todo-keywords-1))
7919 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
7921 (defun org-fast-todo-selection ()
7922 "Fast TODO keyword selection with single keys.
7923 Returns the new TODO keyword, or nil if no state change should occur."
7924 (let* ((fulltable org-todo-key-alist)
7925 (done-keywords org-done-keywords) ;; needed for the faces.
7926 (maxlen (apply 'max (mapcar
7927 (lambda (x)
7928 (if (stringp (car x)) (string-width (car x)) 0))
7929 fulltable)))
7930 (expert nil)
7931 (fwidth (+ maxlen 3 1 3))
7932 (ncol (/ (- (window-width) 4) fwidth))
7933 tg cnt e c tbl
7934 groups ingroup)
7935 (save-window-excursion
7936 (if expert
7937 (set-buffer (get-buffer-create " *Org todo*"))
7938 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
7939 (erase-buffer)
7940 (org-set-local 'org-done-keywords done-keywords)
7941 (setq tbl fulltable cnt 0)
7942 (while (setq e (pop tbl))
7943 (cond
7944 ((equal e '(:startgroup))
7945 (push '() groups) (setq ingroup t)
7946 (when (not (= cnt 0))
7947 (setq cnt 0)
7948 (insert "\n"))
7949 (insert "{ "))
7950 ((equal e '(:endgroup))
7951 (setq ingroup nil cnt 0)
7952 (insert "}\n"))
7954 (setq tg (car e) c (cdr e))
7955 (if ingroup (push tg (car groups)))
7956 (setq tg (org-add-props tg nil 'face
7957 (org-get-todo-face tg)))
7958 (if (and (= cnt 0) (not ingroup)) (insert " "))
7959 (insert "[" c "] " tg (make-string
7960 (- fwidth 4 (length tg)) ?\ ))
7961 (when (= (setq cnt (1+ cnt)) ncol)
7962 (insert "\n")
7963 (if ingroup (insert " "))
7964 (setq cnt 0)))))
7965 (insert "\n")
7966 (goto-char (point-min))
7967 (if (and (not expert) (fboundp 'fit-window-to-buffer))
7968 (fit-window-to-buffer))
7969 (message "[a-z..]:Set [SPC]:clear")
7970 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
7971 (cond
7972 ((or (= c ?\C-g)
7973 (and (= c ?q) (not (rassoc c fulltable))))
7974 (setq quit-flag t))
7975 ((= c ?\ ) nil)
7976 ((setq e (rassoc c fulltable) tg (car e))
7978 (t (setq quit-flag t))))))
7980 (defun org-entry-is-todo-p ()
7981 (member (org-get-todo-state) org-not-done-keywords))
7983 (defun org-entry-is-done-p ()
7984 (member (org-get-todo-state) org-done-keywords))
7986 (defun org-get-todo-state ()
7987 (save-excursion
7988 (org-back-to-heading t)
7989 (and (looking-at org-todo-line-regexp)
7990 (match-end 2)
7991 (match-string 2))))
7993 (defun org-at-date-range-p (&optional inactive-ok)
7994 "Is the cursor inside a date range?"
7995 (interactive)
7996 (save-excursion
7997 (catch 'exit
7998 (let ((pos (point)))
7999 (skip-chars-backward "^[<\r\n")
8000 (skip-chars-backward "<[")
8001 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8002 (>= (match-end 0) pos)
8003 (throw 'exit t))
8004 (skip-chars-backward "^<[\r\n")
8005 (skip-chars-backward "<[")
8006 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8007 (>= (match-end 0) pos)
8008 (throw 'exit t)))
8009 nil)))
8011 (defun org-get-repeat ()
8012 "Check if tere is a deadline/schedule with repeater in this entry."
8013 (save-match-data
8014 (save-excursion
8015 (org-back-to-heading t)
8016 (if (re-search-forward
8017 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8018 (match-string 1)))))
8020 (defvar org-last-changed-timestamp)
8021 (defvar org-log-post-message)
8022 (defvar org-log-note-purpose)
8023 (defvar org-log-note-how)
8024 (defun org-auto-repeat-maybe (done-word)
8025 "Check if the current headline contains a repeated deadline/schedule.
8026 If yes, set TODO state back to what it was and change the base date
8027 of repeating deadline/scheduled time stamps to new date.
8028 This function is run automatically after each state change to a DONE state."
8029 ;; last-state is dynamically scoped into this function
8030 (let* ((repeat (org-get-repeat))
8031 (aa (assoc last-state org-todo-kwd-alist))
8032 (interpret (nth 1 aa))
8033 (head (nth 2 aa))
8034 (whata '(("d" . day) ("m" . month) ("y" . year)))
8035 (msg "Entry repeats: ")
8036 (org-log-done nil)
8037 (org-todo-log-states nil)
8038 (nshiftmax 10) (nshift 0)
8039 re type n what ts mb0 time)
8040 (when repeat
8041 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8042 (org-todo (if (eq interpret 'type) last-state head))
8043 (when org-log-repeat
8044 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8045 (memq 'org-add-log-note post-command-hook))
8046 ;; OK, we are already setup for some record
8047 (if (eq org-log-repeat 'note)
8048 ;; make sure we take a note, not only a time stamp
8049 (setq org-log-note-how 'note))
8050 ;; Set up for taking a record
8051 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8052 'findpos org-log-repeat)))
8053 (org-back-to-heading t)
8054 (org-add-planning-info nil nil 'closed)
8055 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8056 org-deadline-time-regexp "\\)\\|\\("
8057 org-ts-regexp "\\)"))
8058 (while (re-search-forward
8059 re (save-excursion (outline-next-heading) (point)) t)
8060 (setq type (if (match-end 1) org-scheduled-string
8061 (if (match-end 3) org-deadline-string "Plain:"))
8062 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8063 mb0 (match-beginning 0))
8064 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8065 (setq n (string-to-number (match-string 2 ts))
8066 what (match-string 3 ts))
8067 (if (equal what "w") (setq n (* n 7) what "d"))
8068 ;; Preparation, see if we need to modify the start date for the change
8069 (when (match-end 1)
8070 (setq time (save-match-data (org-time-string-to-time ts)))
8071 (cond
8072 ((equal (match-string 1 ts) ".")
8073 ;; Shift starting date to today
8074 (org-timestamp-change
8075 (- (time-to-days (current-time)) (time-to-days time))
8076 'day))
8077 ((equal (match-string 1 ts) "+")
8078 (while (or (= nshift 0)
8079 (<= (time-to-days time) (time-to-days (current-time))))
8080 (when (= (incf nshift) nshiftmax)
8081 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8082 (error "Abort")))
8083 (org-timestamp-change n (cdr (assoc what whata)))
8084 (org-at-timestamp-p t)
8085 (setq ts (match-string 1))
8086 (setq time (save-match-data (org-time-string-to-time ts))))
8087 (org-timestamp-change (- n) (cdr (assoc what whata)))
8088 ;; rematch, so that we have everything in place for the real shift
8089 (org-at-timestamp-p t)
8090 (setq ts (match-string 1))
8091 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8092 (org-timestamp-change n (cdr (assoc what whata)))
8093 (setq msg (concat msg type org-last-changed-timestamp " "))))
8094 (setq org-log-post-message msg)
8095 (message "%s" msg))))
8097 (defun org-show-todo-tree (arg)
8098 "Make a compact tree which shows all headlines marked with TODO.
8099 The tree will show the lines where the regexp matches, and all higher
8100 headlines above the match.
8101 With a \\[universal-argument] prefix, also show the DONE entries.
8102 With a numeric prefix N, construct a sparse tree for the Nth element
8103 of `org-todo-keywords-1'."
8104 (interactive "P")
8105 (let ((case-fold-search nil)
8106 (kwd-re
8107 (cond ((null arg) org-not-done-regexp)
8108 ((equal arg '(4))
8109 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8110 (mapcar 'list org-todo-keywords-1))))
8111 (concat "\\("
8112 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8113 "\\)\\>")))
8114 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8115 (regexp-quote (nth (1- (prefix-numeric-value arg))
8116 org-todo-keywords-1)))
8117 (t (error "Invalid prefix argument: %s" arg)))))
8118 (message "%d TODO entries found"
8119 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8121 (defun org-deadline (&optional remove)
8122 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8123 With argument REMOVE, remove any deadline from the item."
8124 (interactive "P")
8125 (if remove
8126 (progn
8127 (org-remove-timestamp-with-keyword org-deadline-string)
8128 (message "Item no longer has a deadline."))
8129 (org-add-planning-info 'deadline nil 'closed)))
8131 (defun org-schedule (&optional remove)
8132 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8133 With argument REMOVE, remove any scheduling date from the item."
8134 (interactive "P")
8135 (if remove
8136 (progn
8137 (org-remove-timestamp-with-keyword org-scheduled-string)
8138 (message "Item is no longer scheduled."))
8139 (org-add-planning-info 'scheduled nil 'closed)))
8141 (defun org-remove-timestamp-with-keyword (keyword)
8142 "Remove all time stamps with KEYWORD in the current entry."
8143 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8144 beg)
8145 (save-excursion
8146 (org-back-to-heading t)
8147 (setq beg (point))
8148 (org-end-of-subtree t t)
8149 (while (re-search-backward re beg t)
8150 (replace-match "")
8151 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8152 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
8154 (defun org-add-planning-info (what &optional time &rest remove)
8155 "Insert new timestamp with keyword in the line directly after the headline.
8156 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8157 If non is given, the user is prompted for a date.
8158 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8159 be removed."
8160 (interactive)
8161 (let (org-time-was-given org-end-time-was-given ts
8162 end default-time default-input)
8164 (when (and (not time) (memq what '(scheduled deadline)))
8165 ;; Try to get a default date/time from existing timestamp
8166 (save-excursion
8167 (org-back-to-heading t)
8168 (setq end (save-excursion (outline-next-heading) (point)))
8169 (when (re-search-forward (if (eq what 'scheduled)
8170 org-scheduled-time-regexp
8171 org-deadline-time-regexp)
8172 end t)
8173 (setq ts (match-string 1)
8174 default-time
8175 (apply 'encode-time (org-parse-time-string ts))
8176 default-input (and ts (org-get-compact-tod ts))))))
8177 (when what
8178 ;; If necessary, get the time from the user
8179 (setq time (or time (org-read-date nil 'to-time nil nil
8180 default-time default-input))))
8182 (when (and org-insert-labeled-timestamps-at-point
8183 (member what '(scheduled deadline)))
8184 (insert
8185 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8186 (org-insert-time-stamp time org-time-was-given
8187 nil nil nil (list org-end-time-was-given))
8188 (setq what nil))
8189 (save-excursion
8190 (save-restriction
8191 (let (col list elt ts buffer-invisibility-spec)
8192 (org-back-to-heading t)
8193 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8194 (goto-char (match-end 1))
8195 (setq col (current-column))
8196 (goto-char (match-end 0))
8197 (if (eobp) (insert "\n") (forward-char 1))
8198 (if (and (not (looking-at outline-regexp))
8199 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8200 "[^\r\n]*"))
8201 (not (equal (match-string 1) org-clock-string)))
8202 (narrow-to-region (match-beginning 0) (match-end 0))
8203 (insert-before-markers "\n")
8204 (backward-char 1)
8205 (narrow-to-region (point) (point))
8206 (org-indent-to-column col))
8207 ;; Check if we have to remove something.
8208 (setq list (cons what remove))
8209 (while list
8210 (setq elt (pop list))
8211 (goto-char (point-min))
8212 (when (or (and (eq elt 'scheduled)
8213 (re-search-forward org-scheduled-time-regexp nil t))
8214 (and (eq elt 'deadline)
8215 (re-search-forward org-deadline-time-regexp nil t))
8216 (and (eq elt 'closed)
8217 (re-search-forward org-closed-time-regexp nil t)))
8218 (replace-match "")
8219 (if (looking-at "--+<[^>]+>") (replace-match ""))
8220 (if (looking-at " +") (replace-match ""))))
8221 (goto-char (point-max))
8222 (when what
8223 (insert
8224 (if (not (equal (char-before) ?\ )) " " "")
8225 (cond ((eq what 'scheduled) org-scheduled-string)
8226 ((eq what 'deadline) org-deadline-string)
8227 ((eq what 'closed) org-closed-string))
8228 " ")
8229 (setq ts (org-insert-time-stamp
8230 time
8231 (or org-time-was-given
8232 (and (eq what 'closed) org-log-done-with-time))
8233 (eq what 'closed)
8234 nil nil (list org-end-time-was-given)))
8235 (end-of-line 1))
8236 (goto-char (point-min))
8237 (widen)
8238 (if (and (looking-at "[ \t]+\n")
8239 (equal (char-before) ?\n))
8240 (backward-delete-char 1))
8241 ts)))))
8243 (defvar org-log-note-marker (make-marker))
8244 (defvar org-log-note-purpose nil)
8245 (defvar org-log-note-state nil)
8246 (defvar org-log-note-how nil)
8247 (defvar org-log-note-window-configuration nil)
8248 (defvar org-log-note-return-to (make-marker))
8249 (defvar org-log-post-message nil
8250 "Message to be displayed after a log note has been stored.
8251 The auto-repeater uses this.")
8253 (defun org-add-note ()
8254 "Add a note to the current entry.
8255 This is done in the same way as adding a state change note."
8256 (interactive)
8257 (org-add-log-setup 'note nil t nil))
8259 (defun org-add-log-setup (&optional purpose state findpos how)
8260 "Set up the post command hook to take a note.
8261 If this is about to TODO state change, the new state is expected in STATE.
8262 When FINDPOS is non-nil, find the correct position for the note in
8263 the current entry. If not, assume that it can be inserted at point."
8264 (save-excursion
8265 (when findpos
8266 (org-back-to-heading t)
8267 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8268 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8269 "[^\r\n]*\\)?"))
8270 (goto-char (match-end 0))
8271 (unless org-log-states-order-reversed
8272 (and (= (char-after) ?\n) (forward-char 1))
8273 (org-skip-over-state-notes)
8274 (skip-chars-backward " \t\n\r")))
8275 (move-marker org-log-note-marker (point))
8276 (setq org-log-note-purpose purpose
8277 org-log-note-state state
8278 org-log-note-how how)
8279 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8281 (defun org-skip-over-state-notes ()
8282 "Skip past the list of State notes in an entry."
8283 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8284 (while (looking-at "[ \t]*- State")
8285 (condition-case nil
8286 (org-next-item)
8287 (error (org-end-of-item)))))
8289 (defun org-add-log-note (&optional purpose)
8290 "Pop up a window for taking a note, and add this note later at point."
8291 (remove-hook 'post-command-hook 'org-add-log-note)
8292 (setq org-log-note-window-configuration (current-window-configuration))
8293 (delete-other-windows)
8294 (move-marker org-log-note-return-to (point))
8295 (switch-to-buffer (marker-buffer org-log-note-marker))
8296 (goto-char org-log-note-marker)
8297 (org-switch-to-buffer-other-window "*Org Note*")
8298 (erase-buffer)
8299 (if (memq org-log-note-how '(time state))
8300 (org-store-log-note)
8301 (let ((org-inhibit-startup t)) (org-mode))
8302 (insert (format "# Insert note for %s.
8303 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8304 (cond
8305 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8306 ((eq org-log-note-purpose 'done) "closed todo item")
8307 ((eq org-log-note-purpose 'state)
8308 (format "state change to \"%s\"" org-log-note-state))
8309 ((eq org-log-note-purpose 'note)
8310 "this entry")
8311 (t (error "This should not happen")))))
8312 (org-set-local 'org-finish-function 'org-store-log-note)))
8314 (defvar org-note-abort nil) ; dynamically scoped
8315 (defun org-store-log-note ()
8316 "Finish taking a log note, and insert it to where it belongs."
8317 (let ((txt (buffer-string))
8318 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8319 lines ind)
8320 (kill-buffer (current-buffer))
8321 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8322 (setq txt (replace-match "" t t txt)))
8323 (if (string-match "\\s-+\\'" txt)
8324 (setq txt (replace-match "" t t txt)))
8325 (setq lines (org-split-string txt "\n"))
8326 (when (and note (string-match "\\S-" note))
8327 (setq note
8328 (org-replace-escapes
8329 note
8330 (list (cons "%u" (user-login-name))
8331 (cons "%U" user-full-name)
8332 (cons "%t" (format-time-string
8333 (org-time-stamp-format 'long 'inactive)
8334 (current-time)))
8335 (cons "%s" (if org-log-note-state
8336 (concat "\"" org-log-note-state "\"")
8337 "")))))
8338 (if lines (setq note (concat note " \\\\")))
8339 (push note lines))
8340 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8341 (when lines
8342 (save-excursion
8343 (set-buffer (marker-buffer org-log-note-marker))
8344 (save-excursion
8345 (goto-char org-log-note-marker)
8346 (move-marker org-log-note-marker nil)
8347 (end-of-line 1)
8348 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8349 (indent-relative nil)
8350 (insert "- " (pop lines))
8351 (org-indent-line-function)
8352 (beginning-of-line 1)
8353 (looking-at "[ \t]*")
8354 (setq ind (concat (match-string 0) " "))
8355 (end-of-line 1)
8356 (while lines (insert "\n" ind (pop lines)))))))
8357 (set-window-configuration org-log-note-window-configuration)
8358 (with-current-buffer (marker-buffer org-log-note-return-to)
8359 (goto-char org-log-note-return-to))
8360 (move-marker org-log-note-return-to nil)
8361 (and org-log-post-message (message "%s" org-log-post-message)))
8363 (defun org-sparse-tree (&optional arg)
8364 "Create a sparse tree, prompt for the details.
8365 This command can create sparse trees. You first need to select the type
8366 of match used to create the tree:
8368 t Show entries with a specific TODO keyword.
8369 T Show entries selected by a tags match.
8370 p Enter a property name and its value (both with completion on existing
8371 names/values) and show entries with that property.
8372 r Show entries matching a regular expression
8373 d Show deadlines due within `org-deadline-warning-days'."
8374 (interactive "P")
8375 (let (ans kwd value)
8376 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8377 (setq ans (read-char-exclusive))
8378 (cond
8379 ((equal ans ?d)
8380 (call-interactively 'org-check-deadlines))
8381 ((equal ans ?b)
8382 (call-interactively 'org-check-before-date))
8383 ((equal ans ?t)
8384 (org-show-todo-tree '(4)))
8385 ((equal ans ?T)
8386 (call-interactively 'org-tags-sparse-tree))
8387 ((member ans '(?p ?P))
8388 (setq kwd (completing-read "Property: "
8389 (mapcar 'list (org-buffer-property-keys))))
8390 (setq value (completing-read "Value: "
8391 (mapcar 'list (org-property-values kwd))))
8392 (unless (string-match "\\`{.*}\\'" value)
8393 (setq value (concat "\"" value "\"")))
8394 (org-tags-sparse-tree arg (concat kwd "=" value)))
8395 ((member ans '(?r ?R ?/))
8396 (call-interactively 'org-occur))
8397 (t (error "No such sparse tree command \"%c\"" ans)))))
8399 (defvar org-occur-highlights nil
8400 "List of overlays used for occur matches.")
8401 (make-variable-buffer-local 'org-occur-highlights)
8402 (defvar org-occur-parameters nil
8403 "Parameters of the active org-occur calls.
8404 This is a list, each call to org-occur pushes as cons cell,
8405 containing the regular expression and the callback, onto the list.
8406 The list can contain several entries if `org-occur' has been called
8407 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8408 will only contain one set of parameters. When the highlights are
8409 removed (for example with `C-c C-c', or with the next edit (depending
8410 on `org-remove-highlights-with-change'), this variable is emptied
8411 as well.")
8412 (make-variable-buffer-local 'org-occur-parameters)
8414 (defun org-occur (regexp &optional keep-previous callback)
8415 "Make a compact tree which shows all matches of REGEXP.
8416 The tree will show the lines where the regexp matches, and all higher
8417 headlines above the match. It will also show the heading after the match,
8418 to make sure editing the matching entry is easy.
8419 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8420 call to `org-occur' will be kept, to allow stacking of calls to this
8421 command.
8422 If CALLBACK is non-nil, it is a function which is called to confirm
8423 that the match should indeed be shown."
8424 (interactive "sRegexp: \nP")
8425 (unless keep-previous
8426 (org-remove-occur-highlights nil nil t))
8427 (push (cons regexp callback) org-occur-parameters)
8428 (let ((cnt 0))
8429 (save-excursion
8430 (goto-char (point-min))
8431 (if (or (not keep-previous) ; do not want to keep
8432 (not org-occur-highlights)) ; no previous matches
8433 ;; hide everything
8434 (org-overview))
8435 (while (re-search-forward regexp nil t)
8436 (when (or (not callback)
8437 (save-match-data (funcall callback)))
8438 (setq cnt (1+ cnt))
8439 (when org-highlight-sparse-tree-matches
8440 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8441 (org-show-context 'occur-tree))))
8442 (when org-remove-highlights-with-change
8443 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8444 nil 'local))
8445 (unless org-sparse-tree-open-archived-trees
8446 (org-hide-archived-subtrees (point-min) (point-max)))
8447 (run-hooks 'org-occur-hook)
8448 (if (interactive-p)
8449 (message "%d match(es) for regexp %s" cnt regexp))
8450 cnt))
8452 (defun org-show-context (&optional key)
8453 "Make sure point and context and visible.
8454 How much context is shown depends upon the variables
8455 `org-show-hierarchy-above', `org-show-following-heading'. and
8456 `org-show-siblings'."
8457 (let ((heading-p (org-on-heading-p t))
8458 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8459 (following-p (org-get-alist-option org-show-following-heading key))
8460 (entry-p (org-get-alist-option org-show-entry-below key))
8461 (siblings-p (org-get-alist-option org-show-siblings key)))
8462 (catch 'exit
8463 ;; Show heading or entry text
8464 (if (and heading-p (not entry-p))
8465 (org-flag-heading nil) ; only show the heading
8466 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8467 (org-show-hidden-entry))) ; show entire entry
8468 (when following-p
8469 ;; Show next sibling, or heading below text
8470 (save-excursion
8471 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8472 (org-flag-heading nil))))
8473 (when siblings-p (org-show-siblings))
8474 (when hierarchy-p
8475 ;; show all higher headings, possibly with siblings
8476 (save-excursion
8477 (while (and (condition-case nil
8478 (progn (org-up-heading-all 1) t)
8479 (error nil))
8480 (not (bobp)))
8481 (org-flag-heading nil)
8482 (when siblings-p (org-show-siblings))))))))
8484 (defun org-reveal (&optional siblings)
8485 "Show current entry, hierarchy above it, and the following headline.
8486 This can be used to show a consistent set of context around locations
8487 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8488 not t for the search context.
8490 With optional argument SIBLINGS, on each level of the hierarchy all
8491 siblings are shown. This repairs the tree structure to what it would
8492 look like when opened with hierarchical calls to `org-cycle'."
8493 (interactive "P")
8494 (let ((org-show-hierarchy-above t)
8495 (org-show-following-heading t)
8496 (org-show-siblings (if siblings t org-show-siblings)))
8497 (org-show-context nil)))
8499 (defun org-highlight-new-match (beg end)
8500 "Highlight from BEG to END and mark the highlight is an occur headline."
8501 (let ((ov (org-make-overlay beg end)))
8502 (org-overlay-put ov 'face 'secondary-selection)
8503 (push ov org-occur-highlights)))
8505 (defun org-remove-occur-highlights (&optional beg end noremove)
8506 "Remove the occur highlights from the buffer.
8507 BEG and END are ignored. If NOREMOVE is nil, remove this function
8508 from the `before-change-functions' in the current buffer."
8509 (interactive)
8510 (unless org-inhibit-highlight-removal
8511 (mapc 'org-delete-overlay org-occur-highlights)
8512 (setq org-occur-highlights nil)
8513 (setq org-occur-parameters nil)
8514 (unless noremove
8515 (remove-hook 'before-change-functions
8516 'org-remove-occur-highlights 'local))))
8518 ;;;; Priorities
8520 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8521 "Regular expression matching the priority indicator.")
8523 (defvar org-remove-priority-next-time nil)
8525 (defun org-priority-up ()
8526 "Increase the priority of the current item."
8527 (interactive)
8528 (org-priority 'up))
8530 (defun org-priority-down ()
8531 "Decrease the priority of the current item."
8532 (interactive)
8533 (org-priority 'down))
8535 (defun org-priority (&optional action)
8536 "Change the priority of an item by ARG.
8537 ACTION can be `set', `up', `down', or a character."
8538 (interactive)
8539 (setq action (or action 'set))
8540 (let (current new news have remove)
8541 (save-excursion
8542 (org-back-to-heading)
8543 (if (looking-at org-priority-regexp)
8544 (setq current (string-to-char (match-string 2))
8545 have t)
8546 (setq current org-default-priority))
8547 (cond
8548 ((or (eq action 'set)
8549 (if (featurep 'xemacs) (characterp action) (integerp action)))
8550 (if (not (eq action 'set))
8551 (setq new action)
8552 (message "Priority %c-%c, SPC to remove: "
8553 org-highest-priority org-lowest-priority)
8554 (setq new (read-char-exclusive)))
8555 (if (and (= (upcase org-highest-priority) org-highest-priority)
8556 (= (upcase org-lowest-priority) org-lowest-priority))
8557 (setq new (upcase new)))
8558 (cond ((equal new ?\ ) (setq remove t))
8559 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8560 (error "Priority must be between `%c' and `%c'"
8561 org-highest-priority org-lowest-priority))))
8562 ((eq action 'up)
8563 (if (and (not have) (eq last-command this-command))
8564 (setq new org-lowest-priority)
8565 (setq new (if (and org-priority-start-cycle-with-default (not have))
8566 org-default-priority (1- current)))))
8567 ((eq action 'down)
8568 (if (and (not have) (eq last-command this-command))
8569 (setq new org-highest-priority)
8570 (setq new (if (and org-priority-start-cycle-with-default (not have))
8571 org-default-priority (1+ current)))))
8572 (t (error "Invalid action")))
8573 (if (or (< (upcase new) org-highest-priority)
8574 (> (upcase new) org-lowest-priority))
8575 (setq remove t))
8576 (setq news (format "%c" new))
8577 (if have
8578 (if remove
8579 (replace-match "" t t nil 1)
8580 (replace-match news t t nil 2))
8581 (if remove
8582 (error "No priority cookie found in line")
8583 (looking-at org-todo-line-regexp)
8584 (if (match-end 2)
8585 (progn
8586 (goto-char (match-end 2))
8587 (insert " [#" news "]"))
8588 (goto-char (match-beginning 3))
8589 (insert "[#" news "] ")))))
8590 (org-preserve-lc (org-set-tags nil 'align))
8591 (if remove
8592 (message "Priority removed")
8593 (message "Priority of current item set to %s" news))))
8596 (defun org-get-priority (s)
8597 "Find priority cookie and return priority."
8598 (save-match-data
8599 (if (not (string-match org-priority-regexp s))
8600 (* 1000 (- org-lowest-priority org-default-priority))
8601 (* 1000 (- org-lowest-priority
8602 (string-to-char (match-string 2 s)))))))
8604 ;;;; Tags
8606 (defun org-scan-tags (action matcher &optional todo-only)
8607 "Scan headline tags with inheritance and produce output ACTION.
8608 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8609 evaluated, testing if a given set of tags qualifies a headline for
8610 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8611 are included in the output."
8612 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8613 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8614 (org-re
8615 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8616 (props (list 'face nil
8617 'done-face 'org-done
8618 'undone-face nil
8619 'mouse-face 'highlight
8620 'org-not-done-regexp org-not-done-regexp
8621 'org-todo-regexp org-todo-regexp
8622 'keymap org-agenda-keymap
8623 'help-echo
8624 (format "mouse-2 or RET jump to org file %s"
8625 (abbreviate-file-name
8626 (or (buffer-file-name (buffer-base-buffer))
8627 (buffer-name (buffer-base-buffer)))))))
8628 (case-fold-search nil)
8629 lspos
8630 tags tags-list tags-alist (llast 0) rtn level category i txt
8631 todo marker entry priority)
8632 (save-excursion
8633 (goto-char (point-min))
8634 (when (eq action 'sparse-tree)
8635 (org-overview)
8636 (org-remove-occur-highlights))
8637 (while (re-search-forward re nil t)
8638 (catch :skip
8639 (setq todo (if (match-end 1) (match-string 2))
8640 tags (if (match-end 4) (match-string 4)))
8641 (goto-char (setq lspos (1+ (match-beginning 0))))
8642 (setq level (org-reduced-level (funcall outline-level))
8643 category (org-get-category))
8644 (setq i llast llast level)
8645 ;; remove tag lists from same and sublevels
8646 (while (>= i level)
8647 (when (setq entry (assoc i tags-alist))
8648 (setq tags-alist (delete entry tags-alist)))
8649 (setq i (1- i)))
8650 ;; add the next tags
8651 (when tags
8652 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8653 tags-alist
8654 (cons (cons level tags) tags-alist)))
8655 ;; compile tags for current headline
8656 (setq tags-list
8657 (if org-use-tag-inheritance
8658 (apply 'append (mapcar 'cdr tags-alist))
8659 tags))
8660 (when (and tags org-use-tag-inheritance
8661 (not (eq t org-use-tag-inheritance)))
8662 ;; selective inheritance, remove uninherited ones
8663 (setcdr (car tags-alist)
8664 (org-remove-uniherited-tags (cdar tags-alist))))
8665 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8666 (eval matcher)
8667 (or (not org-agenda-skip-archived-trees)
8668 (not (member org-archive-tag tags-list))))
8669 (and (eq action 'agenda) (org-agenda-skip))
8670 ;; list this headline
8672 (if (eq action 'sparse-tree)
8673 (progn
8674 (and org-highlight-sparse-tree-matches
8675 (org-get-heading) (match-end 0)
8676 (org-highlight-new-match
8677 (match-beginning 0) (match-beginning 1)))
8678 (org-show-context 'tags-tree))
8679 (setq txt (org-format-agenda-item
8681 (concat
8682 (if org-tags-match-list-sublevels
8683 (make-string (1- level) ?.) "")
8684 (org-get-heading))
8685 category tags-list)
8686 priority (org-get-priority txt))
8687 (goto-char lspos)
8688 (setq marker (org-agenda-new-marker))
8689 (org-add-props txt props
8690 'org-marker marker 'org-hd-marker marker 'org-category category
8691 'priority priority 'type "tagsmatch")
8692 (push txt rtn))
8693 ;; if we are to skip sublevels, jump to end of subtree
8694 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8695 (when (and (eq action 'sparse-tree)
8696 (not org-sparse-tree-open-archived-trees))
8697 (org-hide-archived-subtrees (point-min) (point-max)))
8698 (nreverse rtn)))
8700 (defun org-remove-uniherited-tags (tags)
8701 "Remove all tags that are not inherited from the list TAGS."
8702 (cond
8703 ((eq org-use-tag-inheritance t) tags)
8704 ((not org-use-tag-inheritance) nil)
8705 ((stringp org-use-tag-inheritance)
8706 (delq nil (mapcar
8707 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8708 tags)))
8709 ((listp org-use-tag-inheritance)
8710 (org-delete-all org-use-tag-inheritance tags))))
8712 (defvar todo-only) ;; dynamically scoped
8714 (defun org-tags-sparse-tree (&optional todo-only match)
8715 "Create a sparse tree according to tags string MATCH.
8716 MATCH can contain positive and negative selection of tags, like
8717 \"+WORK+URGENT-WITHBOSS\".
8718 If optional argument TODO_ONLY is non-nil, only select lines that are
8719 also TODO lines."
8720 (interactive "P")
8721 (org-prepare-agenda-buffers (list (current-buffer)))
8722 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8724 (defvar org-cached-props nil)
8725 (defun org-cached-entry-get (pom property)
8726 (if (or (eq t org-use-property-inheritance)
8727 (and (stringp org-use-property-inheritance)
8728 (string-match org-use-property-inheritance property))
8729 (and (listp org-use-property-inheritance)
8730 (member property org-use-property-inheritance)))
8731 ;; Caching is not possible, check it directly
8732 (org-entry-get pom property 'inherit)
8733 ;; Get all properties, so that we can do complicated checks easily
8734 (cdr (assoc property (or org-cached-props
8735 (setq org-cached-props
8736 (org-entry-properties pom)))))))
8738 (defun org-global-tags-completion-table (&optional files)
8739 "Return the list of all tags in all agenda buffer/files."
8740 (save-excursion
8741 (org-uniquify
8742 (delq nil
8743 (apply 'append
8744 (mapcar
8745 (lambda (file)
8746 (set-buffer (find-file-noselect file))
8747 (append (org-get-buffer-tags)
8748 (mapcar (lambda (x) (if (stringp (car-safe x))
8749 (list (car-safe x)) nil))
8750 org-tag-alist)))
8751 (if (and files (car files))
8752 files
8753 (org-agenda-files))))))))
8755 (defun org-make-tags-matcher (match)
8756 "Create the TAGS//TODO matcher form for the selection string MATCH."
8757 ;; todo-only is scoped dynamically into this function, and the function
8758 ;; may change it it the matcher asksk for it.
8759 (unless match
8760 ;; Get a new match request, with completion
8761 (let ((org-last-tags-completion-table
8762 (org-global-tags-completion-table)))
8763 (setq match (completing-read
8764 "Match: " 'org-tags-completion-function nil nil nil
8765 'org-tags-history))))
8767 ;; Parse the string and create a lisp form
8768 (let ((match0 match)
8769 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8770 minus tag mm
8771 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8772 orterms term orlist re-p str-p level-p level-op
8773 prop-p pn pv po cat-p gv)
8774 (if (string-match "/+" match)
8775 ;; match contains also a todo-matching request
8776 (progn
8777 (setq tagsmatch (substring match 0 (match-beginning 0))
8778 todomatch (substring match (match-end 0)))
8779 (if (string-match "^!" todomatch)
8780 (setq todo-only t todomatch (substring todomatch 1)))
8781 (if (string-match "^\\s-*$" todomatch)
8782 (setq todomatch nil)))
8783 ;; only matching tags
8784 (setq tagsmatch match todomatch nil))
8786 ;; Make the tags matcher
8787 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8788 (setq tagsmatcher t)
8789 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8790 (while (setq term (pop orterms))
8791 (while (and (equal (substring term -1) "\\") orterms)
8792 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8793 (while (string-match re term)
8794 (setq minus (and (match-end 1)
8795 (equal (match-string 1 term) "-"))
8796 tag (match-string 2 term)
8797 re-p (equal (string-to-char tag) ?{)
8798 level-p (match-end 4)
8799 prop-p (match-end 5)
8800 mm (cond
8801 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8802 (level-p
8803 (setq level-op (org-op-to-function (match-string 3 term)))
8804 `(,level-op level ,(string-to-number
8805 (match-string 4 term))))
8806 (prop-p
8807 (setq pn (match-string 5 term)
8808 po (match-string 6 term)
8809 pv (match-string 7 term)
8810 cat-p (equal pn "CATEGORY")
8811 re-p (equal (string-to-char pv) ?{)
8812 str-p (equal (string-to-char pv) ?\")
8813 pv (if (or re-p str-p) (substring pv 1 -1) pv))
8814 (setq po (org-op-to-function po str-p))
8815 (if (equal pn "CATEGORY")
8816 (setq gv '(get-text-property (point) 'org-category))
8817 (setq gv `(org-cached-entry-get nil ,pn)))
8818 (if re-p
8819 (if (eq po 'org<>)
8820 `(not (string-match ,pv (or ,gv "")))
8821 `(string-match ,pv (or ,gv "")))
8822 (if str-p
8823 `(,po (or ,gv "") ,pv)
8824 `(,po (string-to-number (or ,gv ""))
8825 ,(string-to-number pv) ))))
8826 (t `(member ,(downcase tag) tags-list)))
8827 mm (if minus (list 'not mm) mm)
8828 term (substring term (match-end 0)))
8829 (push mm tagsmatcher))
8830 (push (if (> (length tagsmatcher) 1)
8831 (cons 'and tagsmatcher)
8832 (car tagsmatcher))
8833 orlist)
8834 (setq tagsmatcher nil))
8835 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8836 (setq tagsmatcher
8837 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
8838 ;; Make the todo matcher
8839 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
8840 (setq todomatcher t)
8841 (setq orterms (org-split-string todomatch "|") orlist nil)
8842 (while (setq term (pop orterms))
8843 (while (string-match re term)
8844 (setq minus (and (match-end 1)
8845 (equal (match-string 1 term) "-"))
8846 kwd (match-string 2 term)
8847 re-p (equal (string-to-char kwd) ?{)
8848 term (substring term (match-end 0))
8849 mm (if re-p
8850 `(string-match ,(substring kwd 1 -1) todo)
8851 (list 'equal 'todo kwd))
8852 mm (if minus (list 'not mm) mm))
8853 (push mm todomatcher))
8854 (push (if (> (length todomatcher) 1)
8855 (cons 'and todomatcher)
8856 (car todomatcher))
8857 orlist)
8858 (setq todomatcher nil))
8859 (setq todomatcher (if (> (length orlist) 1)
8860 (cons 'or orlist) (car orlist))))
8862 ;; Return the string and lisp forms of the matcher
8863 (setq matcher (if todomatcher
8864 (list 'and tagsmatcher todomatcher)
8865 tagsmatcher))
8866 (cons match0 matcher)))
8868 (defun org-op-to-function (op &optional stringp)
8869 (setq op
8870 (cond
8871 ((equal op "<" ) '(< string< ))
8872 ((equal op ">" ) '(> org-string> ))
8873 ((member op '("<=" "=<")) '(<= org-string<= ))
8874 ((member op '(">=" "=>")) '(>= org-string>= ))
8875 ((member op '("=" "==")) '(= string= ))
8876 ((member op '("<>" "!=")) '(org<> org-string<> ))))
8877 (nth (if stringp 1 0) op))
8879 (defun org<> (a b) (not (= a b)))
8880 (defun org-string<= (a b) (or (string= a b) (string< a b)))
8881 (defun org-string>= (a b) (not (string< a b)))
8882 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
8883 (defun org-string<> (a b) (not (string= a b)))
8885 (defun org-match-any-p (re list)
8886 "Does re match any element of list?"
8887 (setq list (mapcar (lambda (x) (string-match re x)) list))
8888 (delq nil list))
8890 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8891 (defvar org-tags-overlay (org-make-overlay 1 1))
8892 (org-detach-overlay org-tags-overlay)
8894 (defun org-get-tags-at (&optional pos)
8895 "Get a list of all headline tags applicable at POS.
8896 POS defaults to point. If tags are inherited, the list contains
8897 the targets in the same sequence as the headlines appear, i.e.
8898 sthe tags of the current headline come last."
8899 (interactive)
8900 (let (tags ltags lastpos parent)
8901 (save-excursion
8902 (save-restriction
8903 (widen)
8904 (goto-char (or pos (point)))
8905 (save-match-data
8906 (condition-case nil
8907 (progn
8908 (org-back-to-heading t)
8909 (while (not (equal lastpos (point)))
8910 (setq lastpos (point))
8911 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
8912 (setq ltags (org-split-string
8913 (org-match-string-no-properties 1) ":"))
8914 (setq tags (append (org-remove-uniherited-tags ltags)
8915 tags)))
8916 (or org-use-tag-inheritance (error ""))
8917 (org-up-heading-all 1)
8918 (setq parent t)))
8919 (error nil))))
8920 tags)))
8922 (defun org-toggle-tag (tag &optional onoff)
8923 "Toggle the tag TAG for the current line.
8924 If ONOFF is `on' or `off', don't toggle but set to this state."
8925 (unless (org-on-heading-p t) (error "Not on headling"))
8926 (let (res current)
8927 (save-excursion
8928 (beginning-of-line)
8929 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8930 (point-at-eol) t)
8931 (progn
8932 (setq current (match-string 1))
8933 (replace-match ""))
8934 (setq current ""))
8935 (setq current (nreverse (org-split-string current ":")))
8936 (cond
8937 ((eq onoff 'on)
8938 (setq res t)
8939 (or (member tag current) (push tag current)))
8940 ((eq onoff 'off)
8941 (or (not (member tag current)) (setq current (delete tag current))))
8942 (t (if (member tag current)
8943 (setq current (delete tag current))
8944 (setq res t)
8945 (push tag current))))
8946 (end-of-line 1)
8947 (if current
8948 (progn
8949 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8950 (org-set-tags nil t))
8951 (delete-horizontal-space))
8952 (run-hooks 'org-after-tags-change-hook))
8953 res))
8955 (defun org-align-tags-here (to-col)
8956 ;; Assumes that this is a headline
8957 (let ((pos (point)) (col (current-column)) ncol tags-l p)
8958 (beginning-of-line 1)
8959 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
8960 (< pos (match-beginning 2)))
8961 (progn
8962 (setq tags-l (- (match-end 2) (match-beginning 2)))
8963 (goto-char (match-beginning 1))
8964 (insert " ")
8965 (delete-region (point) (1+ (match-beginning 2)))
8966 (setq ncol (max (1+ (current-column))
8967 (1+ col)
8968 (if (> to-col 0)
8969 to-col
8970 (- (abs to-col) tags-l))))
8971 (setq p (point))
8972 (insert (make-string (- ncol (current-column)) ?\ ))
8973 (setq ncol (current-column))
8974 (tabify p (point-at-eol))
8975 (org-move-to-column (min ncol col) t))
8976 (goto-char pos))))
8978 (defun org-set-tags (&optional arg just-align)
8979 "Set the tags for the current headline.
8980 With prefix ARG, realign all tags in headings in the current buffer."
8981 (interactive "P")
8982 (let* ((re (concat "^" outline-regexp))
8983 (current (org-get-tags-string))
8984 (col (current-column))
8985 (org-setting-tags t)
8986 table current-tags inherited-tags ; computed below when needed
8987 tags p0 c0 c1 rpl)
8988 (if arg
8989 (save-excursion
8990 (goto-char (point-min))
8991 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
8992 (while (re-search-forward re nil t)
8993 (org-set-tags nil t)
8994 (end-of-line 1)))
8995 (message "All tags realigned to column %d" org-tags-column))
8996 (if just-align
8997 (setq tags current)
8998 ;; Get a new set of tags from the user
8999 (save-excursion
9000 (setq table (or org-tag-alist (org-get-buffer-tags))
9001 org-last-tags-completion-table table
9002 current-tags (org-split-string current ":")
9003 inherited-tags (nreverse
9004 (nthcdr (length current-tags)
9005 (nreverse (org-get-tags-at))))
9006 tags
9007 (if (or (eq t org-use-fast-tag-selection)
9008 (and org-use-fast-tag-selection
9009 (delq nil (mapcar 'cdr table))))
9010 (org-fast-tag-selection
9011 current-tags inherited-tags table
9012 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9013 (let ((org-add-colon-after-tag-completion t))
9014 (org-trim
9015 (org-without-partial-completion
9016 (completing-read "Tags: " 'org-tags-completion-function
9017 nil nil current 'org-tags-history)))))))
9018 (while (string-match "[-+&]+" tags)
9019 ;; No boolean logic, just a list
9020 (setq tags (replace-match ":" t t tags))))
9022 (if (string-match "\\`[\t ]*\\'" tags)
9023 (setq tags "")
9024 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9025 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9027 ;; Insert new tags at the correct column
9028 (beginning-of-line 1)
9029 (cond
9030 ((and (equal current "") (equal tags "")))
9031 ((re-search-forward
9032 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9033 (point-at-eol) t)
9034 (if (equal tags "")
9035 (setq rpl "")
9036 (goto-char (match-beginning 0))
9037 (setq c0 (current-column) p0 (point)
9038 c1 (max (1+ c0) (if (> org-tags-column 0)
9039 org-tags-column
9040 (- (- org-tags-column) (length tags))))
9041 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9042 (replace-match rpl t t)
9043 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9044 tags)
9045 (t (error "Tags alignment failed")))
9046 (org-move-to-column col)
9047 (unless just-align
9048 (run-hooks 'org-after-tags-change-hook)))))
9050 (defun org-change-tag-in-region (beg end tag off)
9051 "Add or remove TAG for each entry in the region.
9052 This works in the agenda, and also in an org-mode buffer."
9053 (interactive
9054 (list (region-beginning) (region-end)
9055 (let ((org-last-tags-completion-table
9056 (if (org-mode-p)
9057 (org-get-buffer-tags)
9058 (org-global-tags-completion-table))))
9059 (completing-read
9060 "Tag: " 'org-tags-completion-function nil nil nil
9061 'org-tags-history))
9062 (progn
9063 (message "[s]et or [r]emove? ")
9064 (equal (read-char-exclusive) ?r))))
9065 (if (fboundp 'deactivate-mark) (deactivate-mark))
9066 (let ((agendap (equal major-mode 'org-agenda-mode))
9067 l1 l2 m buf pos newhead (cnt 0))
9068 (goto-char end)
9069 (setq l2 (1- (org-current-line)))
9070 (goto-char beg)
9071 (setq l1 (org-current-line))
9072 (loop for l from l1 to l2 do
9073 (goto-line l)
9074 (setq m (get-text-property (point) 'org-hd-marker))
9075 (when (or (and (org-mode-p) (org-on-heading-p))
9076 (and agendap m))
9077 (setq buf (if agendap (marker-buffer m) (current-buffer))
9078 pos (if agendap m (point)))
9079 (with-current-buffer buf
9080 (save-excursion
9081 (save-restriction
9082 (goto-char pos)
9083 (setq cnt (1+ cnt))
9084 (org-toggle-tag tag (if off 'off 'on))
9085 (setq newhead (org-get-heading)))))
9086 (and agendap (org-agenda-change-all-lines newhead m))))
9087 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9089 (defun org-tags-completion-function (string predicate &optional flag)
9090 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9091 (confirm (lambda (x) (stringp (car x)))))
9092 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9093 (setq s1 (match-string 1 string)
9094 s2 (match-string 2 string))
9095 (setq s1 "" s2 string))
9096 (cond
9097 ((eq flag nil)
9098 ;; try completion
9099 (setq rtn (try-completion s2 ctable confirm))
9100 (if (stringp rtn)
9101 (setq rtn
9102 (concat s1 s2 (substring rtn (length s2))
9103 (if (and org-add-colon-after-tag-completion
9104 (assoc rtn ctable))
9105 ":" ""))))
9106 rtn)
9107 ((eq flag t)
9108 ;; all-completions
9109 (all-completions s2 ctable confirm)
9111 ((eq flag 'lambda)
9112 ;; exact match?
9113 (assoc s2 ctable)))
9116 (defun org-fast-tag-insert (kwd tags face &optional end)
9117 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9118 (insert (format "%-12s" (concat kwd ":"))
9119 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9120 (or end "")))
9122 (defun org-fast-tag-show-exit (flag)
9123 (save-excursion
9124 (goto-line 3)
9125 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9126 (replace-match ""))
9127 (when flag
9128 (end-of-line 1)
9129 (org-move-to-column (- (window-width) 19) t)
9130 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9132 (defun org-set-current-tags-overlay (current prefix)
9133 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9134 (if (featurep 'xemacs)
9135 (org-overlay-display org-tags-overlay (concat prefix s)
9136 'secondary-selection)
9137 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9138 (org-overlay-display org-tags-overlay (concat prefix s)))))
9140 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9141 "Fast tag selection with single keys.
9142 CURRENT is the current list of tags in the headline, INHERITED is the
9143 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9144 possibly with grouping information. TODO-TABLE is a similar table with
9145 TODO keywords, should these have keys assigned to them.
9146 If the keys are nil, a-z are automatically assigned.
9147 Returns the new tags string, or nil to not change the current settings."
9148 (let* ((fulltable (append table todo-table))
9149 (maxlen (apply 'max (mapcar
9150 (lambda (x)
9151 (if (stringp (car x)) (string-width (car x)) 0))
9152 fulltable)))
9153 (buf (current-buffer))
9154 (expert (eq org-fast-tag-selection-single-key 'expert))
9155 (buffer-tags nil)
9156 (fwidth (+ maxlen 3 1 3))
9157 (ncol (/ (- (window-width) 4) fwidth))
9158 (i-face 'org-done)
9159 (c-face 'org-todo)
9160 tg cnt e c char c1 c2 ntable tbl rtn
9161 ov-start ov-end ov-prefix
9162 (exit-after-next org-fast-tag-selection-single-key)
9163 (done-keywords org-done-keywords)
9164 groups ingroup)
9165 (save-excursion
9166 (beginning-of-line 1)
9167 (if (looking-at
9168 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9169 (setq ov-start (match-beginning 1)
9170 ov-end (match-end 1)
9171 ov-prefix "")
9172 (setq ov-start (1- (point-at-eol))
9173 ov-end (1+ ov-start))
9174 (skip-chars-forward "^\n\r")
9175 (setq ov-prefix
9176 (concat
9177 (buffer-substring (1- (point)) (point))
9178 (if (> (current-column) org-tags-column)
9180 (make-string (- org-tags-column (current-column)) ?\ ))))))
9181 (org-move-overlay org-tags-overlay ov-start ov-end)
9182 (save-window-excursion
9183 (if expert
9184 (set-buffer (get-buffer-create " *Org tags*"))
9185 (delete-other-windows)
9186 (split-window-vertically)
9187 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9188 (erase-buffer)
9189 (org-set-local 'org-done-keywords done-keywords)
9190 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9191 (org-fast-tag-insert "Current" current c-face "\n\n")
9192 (org-fast-tag-show-exit exit-after-next)
9193 (org-set-current-tags-overlay current ov-prefix)
9194 (setq tbl fulltable char ?a cnt 0)
9195 (while (setq e (pop tbl))
9196 (cond
9197 ((equal e '(:startgroup))
9198 (push '() groups) (setq ingroup t)
9199 (when (not (= cnt 0))
9200 (setq cnt 0)
9201 (insert "\n"))
9202 (insert "{ "))
9203 ((equal e '(:endgroup))
9204 (setq ingroup nil cnt 0)
9205 (insert "}\n"))
9207 (setq tg (car e) c2 nil)
9208 (if (cdr e)
9209 (setq c (cdr e))
9210 ;; automatically assign a character.
9211 (setq c1 (string-to-char
9212 (downcase (substring
9213 tg (if (= (string-to-char tg) ?@) 1 0)))))
9214 (if (or (rassoc c1 ntable) (rassoc c1 table))
9215 (while (or (rassoc char ntable) (rassoc char table))
9216 (setq char (1+ char)))
9217 (setq c2 c1))
9218 (setq c (or c2 char)))
9219 (if ingroup (push tg (car groups)))
9220 (setq tg (org-add-props tg nil 'face
9221 (cond
9222 ((not (assoc tg table))
9223 (org-get-todo-face tg))
9224 ((member tg current) c-face)
9225 ((member tg inherited) i-face)
9226 (t nil))))
9227 (if (and (= cnt 0) (not ingroup)) (insert " "))
9228 (insert "[" c "] " tg (make-string
9229 (- fwidth 4 (length tg)) ?\ ))
9230 (push (cons tg c) ntable)
9231 (when (= (setq cnt (1+ cnt)) ncol)
9232 (insert "\n")
9233 (if ingroup (insert " "))
9234 (setq cnt 0)))))
9235 (setq ntable (nreverse ntable))
9236 (insert "\n")
9237 (goto-char (point-min))
9238 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9239 (fit-window-to-buffer))
9240 (setq rtn
9241 (catch 'exit
9242 (while t
9243 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9244 (if groups " [!] no groups" " [!]groups")
9245 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9246 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9247 (cond
9248 ((= c ?\r) (throw 'exit t))
9249 ((= c ?!)
9250 (setq groups (not groups))
9251 (goto-char (point-min))
9252 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9253 ((= c ?\C-c)
9254 (if (not expert)
9255 (org-fast-tag-show-exit
9256 (setq exit-after-next (not exit-after-next)))
9257 (setq expert nil)
9258 (delete-other-windows)
9259 (split-window-vertically)
9260 (org-switch-to-buffer-other-window " *Org tags*")
9261 (and (fboundp 'fit-window-to-buffer)
9262 (fit-window-to-buffer))))
9263 ((or (= c ?\C-g)
9264 (and (= c ?q) (not (rassoc c ntable))))
9265 (org-detach-overlay org-tags-overlay)
9266 (setq quit-flag t))
9267 ((= c ?\ )
9268 (setq current nil)
9269 (if exit-after-next (setq exit-after-next 'now)))
9270 ((= c ?\t)
9271 (condition-case nil
9272 (setq tg (completing-read
9273 "Tag: "
9274 (or buffer-tags
9275 (with-current-buffer buf
9276 (org-get-buffer-tags)))))
9277 (quit (setq tg "")))
9278 (when (string-match "\\S-" tg)
9279 (add-to-list 'buffer-tags (list tg))
9280 (if (member tg current)
9281 (setq current (delete tg current))
9282 (push tg current)))
9283 (if exit-after-next (setq exit-after-next 'now)))
9284 ((setq e (rassoc c todo-table) tg (car e))
9285 (with-current-buffer buf
9286 (save-excursion (org-todo tg)))
9287 (if exit-after-next (setq exit-after-next 'now)))
9288 ((setq e (rassoc c ntable) tg (car e))
9289 (if (member tg current)
9290 (setq current (delete tg current))
9291 (loop for g in groups do
9292 (if (member tg g)
9293 (mapc (lambda (x)
9294 (setq current (delete x current)))
9295 g)))
9296 (push tg current))
9297 (if exit-after-next (setq exit-after-next 'now))))
9299 ;; Create a sorted list
9300 (setq current
9301 (sort current
9302 (lambda (a b)
9303 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9304 (if (eq exit-after-next 'now) (throw 'exit t))
9305 (goto-char (point-min))
9306 (beginning-of-line 2)
9307 (delete-region (point) (point-at-eol))
9308 (org-fast-tag-insert "Current" current c-face)
9309 (org-set-current-tags-overlay current ov-prefix)
9310 (while (re-search-forward
9311 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9312 (setq tg (match-string 1))
9313 (add-text-properties
9314 (match-beginning 1) (match-end 1)
9315 (list 'face
9316 (cond
9317 ((member tg current) c-face)
9318 ((member tg inherited) i-face)
9319 (t (get-text-property (match-beginning 1) 'face))))))
9320 (goto-char (point-min)))))
9321 (org-detach-overlay org-tags-overlay)
9322 (if rtn
9323 (mapconcat 'identity current ":")
9324 nil))))
9326 (defun org-get-tags-string ()
9327 "Get the TAGS string in the current headline."
9328 (unless (org-on-heading-p t)
9329 (error "Not on a heading"))
9330 (save-excursion
9331 (beginning-of-line 1)
9332 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9333 (org-match-string-no-properties 1)
9334 "")))
9336 (defun org-get-tags ()
9337 "Get the list of tags specified in the current headline."
9338 (org-split-string (org-get-tags-string) ":"))
9340 (defun org-get-buffer-tags ()
9341 "Get a table of all tags used in the buffer, for completion."
9342 (let (tags)
9343 (save-excursion
9344 (goto-char (point-min))
9345 (while (re-search-forward
9346 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9347 (when (equal (char-after (point-at-bol 0)) ?*)
9348 (mapc (lambda (x) (add-to-list 'tags x))
9349 (org-split-string (org-match-string-no-properties 1) ":")))))
9350 (mapcar 'list tags)))
9353 ;;;; Properties
9355 ;;; Setting and retrieving properties
9357 (defconst org-special-properties
9358 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9359 "TIMESTAMP" "TIMESTAMP_IA")
9360 "The special properties valid in Org-mode.
9362 These are properties that are not defined in the property drawer,
9363 but in some other way.")
9365 (defconst org-default-properties
9366 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9367 "LOCATION" "LOGGING" "COLUMNS")
9368 "Some properties that are used by Org-mode for various purposes.
9369 Being in this list makes sure that they are offered for completion.")
9371 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9372 "Regular expression matching the first line of a property drawer.")
9374 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9375 "Regular expression matching the first line of a property drawer.")
9377 (defun org-property-action ()
9378 "Do an action on properties."
9379 (interactive)
9380 (let (c)
9381 (org-at-property-p)
9382 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9383 (setq c (read-char-exclusive))
9384 (cond
9385 ((equal c ?s)
9386 (call-interactively 'org-set-property))
9387 ((equal c ?d)
9388 (call-interactively 'org-delete-property))
9389 ((equal c ?D)
9390 (call-interactively 'org-delete-property-globally))
9391 ((equal c ?c)
9392 (call-interactively 'org-compute-property-at-point))
9393 (t (error "No such property action %c" c)))))
9395 (defun org-at-property-p ()
9396 "Is the cursor in a property line?"
9397 ;; FIXME: Does not check if we are actually in the drawer.
9398 ;; FIXME: also returns true on any drawers.....
9399 ;; This is used by C-c C-c for property action.
9400 (save-excursion
9401 (beginning-of-line 1)
9402 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9404 (defun org-get-property-block (&optional beg end force)
9405 "Return the (beg . end) range of the body of the property drawer.
9406 BEG and END can be beginning and end of subtree, if not given
9407 they will be found.
9408 If the drawer does not exist and FORCE is non-nil, create the drawer."
9409 (catch 'exit
9410 (save-excursion
9411 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9412 (end (or end (progn (outline-next-heading) (point)))))
9413 (goto-char beg)
9414 (if (re-search-forward org-property-start-re end t)
9415 (setq beg (1+ (match-end 0)))
9416 (if force
9417 (save-excursion
9418 (org-insert-property-drawer)
9419 (setq end (progn (outline-next-heading) (point))))
9420 (throw 'exit nil))
9421 (goto-char beg)
9422 (if (re-search-forward org-property-start-re end t)
9423 (setq beg (1+ (match-end 0)))))
9424 (if (re-search-forward org-property-end-re end t)
9425 (setq end (match-beginning 0))
9426 (or force (throw 'exit nil))
9427 (goto-char beg)
9428 (setq end beg)
9429 (org-indent-line-function)
9430 (insert ":END:\n"))
9431 (cons beg end)))))
9433 (defun org-entry-properties (&optional pom which)
9434 "Get all properties of the entry at point-or-marker POM.
9435 This includes the TODO keyword, the tags, time strings for deadline,
9436 scheduled, and clocking, and any additional properties defined in the
9437 entry. The return value is an alist, keys may occur multiple times
9438 if the property key was used several times.
9439 POM may also be nil, in which case the current entry is used.
9440 If WHICH is nil or `all', get all properties. If WHICH is
9441 `special' or `standard', only get that subclass."
9442 (setq which (or which 'all))
9443 (org-with-point-at pom
9444 (let ((clockstr (substring org-clock-string 0 -1))
9445 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9446 beg end range props sum-props key value string clocksum)
9447 (save-excursion
9448 (when (condition-case nil (org-back-to-heading t) (error nil))
9449 (setq beg (point))
9450 (setq sum-props (get-text-property (point) 'org-summaries))
9451 (setq clocksum (get-text-property (point) :org-clock-minutes))
9452 (outline-next-heading)
9453 (setq end (point))
9454 (when (memq which '(all special))
9455 ;; Get the special properties, like TODO and tags
9456 (goto-char beg)
9457 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9458 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9459 (when (looking-at org-priority-regexp)
9460 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9461 (when (and (setq value (org-get-tags-string))
9462 (string-match "\\S-" value))
9463 (push (cons "TAGS" value) props))
9464 (when (setq value (org-get-tags-at))
9465 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9466 props))
9467 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9468 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9469 string (if (equal key clockstr)
9470 (org-no-properties
9471 (org-trim
9472 (buffer-substring
9473 (match-beginning 3) (goto-char (point-at-eol)))))
9474 (substring (org-match-string-no-properties 3) 1 -1)))
9475 (unless key
9476 (if (= (char-after (match-beginning 3)) ?\[)
9477 (setq key "TIMESTAMP_IA")
9478 (setq key "TIMESTAMP")))
9479 (when (or (equal key clockstr) (not (assoc key props)))
9480 (push (cons key string) props)))
9484 (when (memq which '(all standard))
9485 ;; Get the standard properties, like :PORP: ...
9486 (setq range (org-get-property-block beg end))
9487 (when range
9488 (goto-char (car range))
9489 (while (re-search-forward
9490 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9491 (cdr range) t)
9492 (setq key (org-match-string-no-properties 1)
9493 value (org-trim (or (org-match-string-no-properties 2) "")))
9494 (unless (member key excluded)
9495 (push (cons key (or value "")) props)))))
9496 (if clocksum
9497 (push (cons "CLOCKSUM"
9498 (org-columns-number-to-string (/ (float clocksum) 60.)
9499 'add_times))
9500 props))
9501 (append sum-props (nreverse props)))))))
9503 (defun org-entry-get (pom property &optional inherit)
9504 "Get value of PROPERTY for entry at point-or-marker POM.
9505 If INHERIT is non-nil and the entry does not have the property,
9506 then also check higher levels of the hierarchy.
9507 If INHERIT is the symbol `selective', use inheritance only if the setting
9508 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9509 If the property is present but empty, the return value is the empty string.
9510 If the property is not present at all, nil is returned."
9511 (org-with-point-at pom
9512 (if (and inherit (if (eq inherit 'selective)
9513 (org-property-inherit-p property)
9515 (org-entry-get-with-inheritance property)
9516 (if (member property org-special-properties)
9517 ;; We need a special property. Use brute force, get all properties.
9518 (cdr (assoc property (org-entry-properties nil 'special)))
9519 (let ((range (org-get-property-block)))
9520 (if (and range
9521 (goto-char (car range))
9522 (re-search-forward
9523 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9524 (cdr range) t))
9525 ;; Found the property, return it.
9526 (if (match-end 1)
9527 (org-match-string-no-properties 1)
9528 "")))))))
9530 (defun org-property-or-variable-value (var &optional inherit)
9531 "Check if there is a property fixing the value of VAR.
9532 If yes, return this value. If not, return the current value of the variable."
9533 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9534 (if (and prop (stringp prop) (string-match "\\S-" prop))
9535 (read prop)
9536 (symbol-value var))))
9538 (defun org-entry-delete (pom property)
9539 "Delete the property PROPERTY from entry at point-or-marker POM."
9540 (org-with-point-at pom
9541 (if (member property org-special-properties)
9542 nil ; cannot delete these properties.
9543 (let ((range (org-get-property-block)))
9544 (if (and range
9545 (goto-char (car range))
9546 (re-search-forward
9547 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9548 (cdr range) t))
9549 (progn
9550 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9552 nil)))))
9554 ;; Multi-values properties are properties that contain multiple values
9555 ;; These values are assumed to be single words, separated by whitespace.
9556 (defun org-entry-add-to-multivalued-property (pom property value)
9557 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9558 (let* ((old (org-entry-get pom property))
9559 (values (and old (org-split-string old "[ \t]"))))
9560 (unless (member value values)
9561 (setq values (cons value values))
9562 (org-entry-put pom property
9563 (mapconcat 'identity values " ")))))
9565 (defun org-entry-remove-from-multivalued-property (pom property value)
9566 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9567 (let* ((old (org-entry-get pom property))
9568 (values (and old (org-split-string old "[ \t]"))))
9569 (when (member value values)
9570 (setq values (delete value values))
9571 (org-entry-put pom property
9572 (mapconcat 'identity values " ")))))
9574 (defun org-entry-member-in-multivalued-property (pom property value)
9575 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9576 (let* ((old (org-entry-get pom property))
9577 (values (and old (org-split-string old "[ \t]"))))
9578 (member value values)))
9580 (defvar org-entry-property-inherited-from (make-marker))
9582 (defun org-entry-get-with-inheritance (property)
9583 "Get entry property, and search higher levels if not present."
9584 (let (tmp)
9585 (save-excursion
9586 (save-restriction
9587 (widen)
9588 (catch 'ex
9589 (while t
9590 (when (setq tmp (org-entry-get nil property))
9591 (org-back-to-heading t)
9592 (move-marker org-entry-property-inherited-from (point))
9593 (throw 'ex tmp))
9594 (or (org-up-heading-safe) (throw 'ex nil)))))
9595 (or tmp (cdr (assoc property org-local-properties))
9596 (cdr (assoc property org-global-properties))))))
9598 (defun org-entry-put (pom property value)
9599 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9600 (org-with-point-at pom
9601 (org-back-to-heading t)
9602 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9603 range)
9604 (cond
9605 ((equal property "TODO")
9606 (when (and (stringp value) (string-match "\\S-" value)
9607 (not (member value org-todo-keywords-1)))
9608 (error "\"%s\" is not a valid TODO state" value))
9609 (if (or (not value)
9610 (not (string-match "\\S-" value)))
9611 (setq value 'none))
9612 (org-todo value)
9613 (org-set-tags nil 'align))
9614 ((equal property "PRIORITY")
9615 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9616 (string-to-char value) ?\ ))
9617 (org-set-tags nil 'align))
9618 ((equal property "SCHEDULED")
9619 (if (re-search-forward org-scheduled-time-regexp end t)
9620 (cond
9621 ((eq value 'earlier) (org-timestamp-change -1 'day))
9622 ((eq value 'later) (org-timestamp-change 1 'day))
9623 (t (call-interactively 'org-schedule)))
9624 (call-interactively 'org-schedule)))
9625 ((equal property "DEADLINE")
9626 (if (re-search-forward org-deadline-time-regexp end t)
9627 (cond
9628 ((eq value 'earlier) (org-timestamp-change -1 'day))
9629 ((eq value 'later) (org-timestamp-change 1 'day))
9630 (t (call-interactively 'org-deadline)))
9631 (call-interactively 'org-deadline)))
9632 ((member property org-special-properties)
9633 (error "The %s property can not yet be set with `org-entry-put'"
9634 property))
9635 (t ; a non-special property
9636 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9637 (setq range (org-get-property-block beg end 'force))
9638 (goto-char (car range))
9639 (if (re-search-forward
9640 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9641 (progn
9642 (delete-region (match-beginning 1) (match-end 1))
9643 (goto-char (match-beginning 1)))
9644 (goto-char (cdr range))
9645 (insert "\n")
9646 (backward-char 1)
9647 (org-indent-line-function)
9648 (insert ":" property ":"))
9649 (and value (insert " " value))
9650 (org-indent-line-function)))))))
9652 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9653 "Get all property keys in the current buffer.
9654 With INCLUDE-SPECIALS, also list the special properties that relect things
9655 like tags and TODO state.
9656 With INCLUDE-DEFAULTS, also include properties that has special meaning
9657 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9658 With INCLUDE-COLUMNS, also include property names given in COLUMN
9659 formats in the current buffer."
9660 (let (rtn range cfmt cols s p)
9661 (save-excursion
9662 (save-restriction
9663 (widen)
9664 (goto-char (point-min))
9665 (while (re-search-forward org-property-start-re nil t)
9666 (setq range (org-get-property-block))
9667 (goto-char (car range))
9668 (while (re-search-forward
9669 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9670 (cdr range) t)
9671 (add-to-list 'rtn (org-match-string-no-properties 1)))
9672 (outline-next-heading))))
9674 (when include-specials
9675 (setq rtn (append org-special-properties rtn)))
9677 (when include-defaults
9678 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9680 (when include-columns
9681 (save-excursion
9682 (save-restriction
9683 (widen)
9684 (goto-char (point-min))
9685 (while (re-search-forward
9686 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9687 nil t)
9688 (setq cfmt (match-string 2) s 0)
9689 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9690 cfmt s)
9691 (setq s (match-end 0)
9692 p (match-string 1 cfmt))
9693 (unless (or (equal p "ITEM")
9694 (member p org-special-properties))
9695 (add-to-list 'rtn (match-string 1 cfmt))))))))
9697 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9699 (defun org-property-values (key)
9700 "Return a list of all values of property KEY."
9701 (save-excursion
9702 (save-restriction
9703 (widen)
9704 (goto-char (point-min))
9705 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9706 values)
9707 (while (re-search-forward re nil t)
9708 (add-to-list 'values (org-trim (match-string 1))))
9709 (delete "" values)))))
9711 (defun org-insert-property-drawer ()
9712 "Insert a property drawer into the current entry."
9713 (interactive)
9714 (org-back-to-heading t)
9715 (looking-at outline-regexp)
9716 (let ((indent (- (match-end 0)(match-beginning 0)))
9717 (beg (point))
9718 (re (concat "^[ \t]*" org-keyword-time-regexp))
9719 end hiddenp)
9720 (outline-next-heading)
9721 (setq end (point))
9722 (goto-char beg)
9723 (while (re-search-forward re end t))
9724 (setq hiddenp (org-invisible-p))
9725 (end-of-line 1)
9726 (and (equal (char-after) ?\n) (forward-char 1))
9727 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
9728 (beginning-of-line 2))
9729 (org-skip-over-state-notes)
9730 (skip-chars-backward " \t\n\r")
9731 (if (eq (char-before) ?*) (forward-char 1))
9732 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
9733 (beginning-of-line 0)
9734 (org-indent-to-column indent)
9735 (beginning-of-line 2)
9736 (org-indent-to-column indent)
9737 (beginning-of-line 0)
9738 (if hiddenp
9739 (save-excursion
9740 (org-back-to-heading t)
9741 (hide-entry))
9742 (org-flag-drawer t))))
9744 (defun org-set-property (property value)
9745 "In the current entry, set PROPERTY to VALUE.
9746 When called interactively, this will prompt for a property name, offering
9747 completion on existing and default properties. And then it will prompt
9748 for a value, offering competion either on allowed values (via an inherited
9749 xxx_ALL property) or on existing values in other instances of this property
9750 in the current file."
9751 (interactive
9752 (let* ((prop (completing-read
9753 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
9754 (cur (org-entry-get nil prop))
9755 (allowed (org-property-get-allowed-values nil prop 'table))
9756 (existing (mapcar 'list (org-property-values prop)))
9757 (val (if allowed
9758 (completing-read "Value: " allowed nil 'req-match)
9759 (completing-read
9760 (concat "Value" (if (and cur (string-match "\\S-" cur))
9761 (concat "[" cur "]") "")
9762 ": ")
9763 existing nil nil "" nil cur))))
9764 (list prop (if (equal val "") cur val))))
9765 (unless (equal (org-entry-get nil property) value)
9766 (org-entry-put nil property value)))
9768 (defun org-delete-property (property)
9769 "In the current entry, delete PROPERTY."
9770 (interactive
9771 (let* ((prop (completing-read
9772 "Property: " (org-entry-properties nil 'standard))))
9773 (list prop)))
9774 (message "Property %s %s" property
9775 (if (org-entry-delete nil property)
9776 "deleted"
9777 "was not present in the entry")))
9779 (defun org-delete-property-globally (property)
9780 "Remove PROPERTY globally, from all entries."
9781 (interactive
9782 (let* ((prop (completing-read
9783 "Globally remove property: "
9784 (mapcar 'list (org-buffer-property-keys)))))
9785 (list prop)))
9786 (save-excursion
9787 (save-restriction
9788 (widen)
9789 (goto-char (point-min))
9790 (let ((cnt 0))
9791 (while (re-search-forward
9792 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
9793 nil t)
9794 (setq cnt (1+ cnt))
9795 (replace-match ""))
9796 (message "Property \"%s\" removed from %d entries" property cnt)))))
9798 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
9800 (defun org-compute-property-at-point ()
9801 "Compute the property at point.
9802 This looks for an enclosing column format, extracts the operator and
9803 then applies it to the proerty in the column format's scope."
9804 (interactive)
9805 (unless (org-at-property-p)
9806 (error "Not at a property"))
9807 (let ((prop (org-match-string-no-properties 2)))
9808 (org-columns-get-format-and-top-level)
9809 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
9810 (error "No operator defined for property %s" prop))
9811 (org-columns-compute prop)))
9813 (defun org-property-get-allowed-values (pom property &optional table)
9814 "Get allowed values for the property PROPERTY.
9815 When TABLE is non-nil, return an alist that can directly be used for
9816 completion."
9817 (let (vals)
9818 (cond
9819 ((equal property "TODO")
9820 (setq vals (org-with-point-at pom
9821 (append org-todo-keywords-1 '("")))))
9822 ((equal property "PRIORITY")
9823 (let ((n org-lowest-priority))
9824 (while (>= n org-highest-priority)
9825 (push (char-to-string n) vals)
9826 (setq n (1- n)))))
9827 ((member property org-special-properties))
9829 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
9831 (when (and vals (string-match "\\S-" vals))
9832 (setq vals (car (read-from-string (concat "(" vals ")"))))
9833 (setq vals (mapcar (lambda (x)
9834 (cond ((stringp x) x)
9835 ((numberp x) (number-to-string x))
9836 ((symbolp x) (symbol-name x))
9837 (t "???")))
9838 vals)))))
9839 (if table (mapcar 'list vals) vals)))
9841 (defun org-property-previous-allowed-value (&optional previous)
9842 "Switch to the next allowed value for this property."
9843 (interactive)
9844 (org-property-next-allowed-value t))
9846 (defun org-property-next-allowed-value (&optional previous)
9847 "Switch to the next allowed value for this property."
9848 (interactive)
9849 (unless (org-at-property-p)
9850 (error "Not at a property"))
9851 (let* ((key (match-string 2))
9852 (value (match-string 3))
9853 (allowed (or (org-property-get-allowed-values (point) key)
9854 (and (member value '("[ ]" "[-]" "[X]"))
9855 '("[ ]" "[X]"))))
9856 nval)
9857 (unless allowed
9858 (error "Allowed values for this property have not been defined"))
9859 (if previous (setq allowed (reverse allowed)))
9860 (if (member value allowed)
9861 (setq nval (car (cdr (member value allowed)))))
9862 (setq nval (or nval (car allowed)))
9863 (if (equal nval value)
9864 (error "Only one allowed value for this property"))
9865 (org-at-property-p)
9866 (replace-match (concat " :" key ": " nval) t t)
9867 (org-indent-line-function)
9868 (beginning-of-line 1)
9869 (skip-chars-forward " \t")))
9871 (defun org-find-entry-with-id (ident)
9872 "Locate the entry that contains the ID property with exact value IDENT.
9873 IDENT can be a string, a symbol or a number, this function will search for
9874 the string representation of it.
9875 Return the position where this entry starts, or nil if there is no such entry."
9876 (let ((id (cond
9877 ((stringp ident) ident)
9878 ((symbol-name ident) (symbol-name ident))
9879 ((numberp ident) (number-to-string ident))
9880 (t (error "IDENT %s must be a string, symbol or number" ident))))
9881 (case-fold-search nil))
9882 (save-excursion
9883 (save-restriction
9884 (widen)
9885 (goto-char (point-min))
9886 (when (re-search-forward
9887 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
9888 nil t)
9889 (org-back-to-heading)
9890 (point))))))
9892 ;;;; Timestamps
9894 (defvar org-last-changed-timestamp nil)
9895 (defvar org-time-was-given) ; dynamically scoped parameter
9896 (defvar org-end-time-was-given) ; dynamically scoped parameter
9897 (defvar org-ts-what) ; dynamically scoped parameter
9899 (defun org-time-stamp (arg)
9900 "Prompt for a date/time and insert a time stamp.
9901 If the user specifies a time like HH:MM, or if this command is called
9902 with a prefix argument, the time stamp will contain date and time.
9903 Otherwise, only the date will be included. All parts of a date not
9904 specified by the user will be filled in from the current date/time.
9905 So if you press just return without typing anything, the time stamp
9906 will represent the current date/time. If there is already a timestamp
9907 at the cursor, it will be modified."
9908 (interactive "P")
9909 (let* ((ts nil)
9910 (default-time
9911 ;; Default time is either today, or, when entering a range,
9912 ;; the range start.
9913 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
9914 (save-excursion
9915 (re-search-backward
9916 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
9917 (- (point) 20) t)))
9918 (apply 'encode-time (org-parse-time-string (match-string 1)))
9919 (current-time)))
9920 (default-input (and ts (org-get-compact-tod ts)))
9921 org-time-was-given org-end-time-was-given time)
9922 (cond
9923 ((and (org-at-timestamp-p)
9924 (eq last-command 'org-time-stamp)
9925 (eq this-command 'org-time-stamp))
9926 (insert "--")
9927 (setq time (let ((this-command this-command))
9928 (org-read-date arg 'totime nil nil default-time default-input)))
9929 (org-insert-time-stamp time (or org-time-was-given arg)))
9930 ((org-at-timestamp-p)
9931 (setq time (let ((this-command this-command))
9932 (org-read-date arg 'totime nil nil default-time default-input)))
9933 (when (org-at-timestamp-p) ; just to get the match data
9934 (replace-match "")
9935 (setq org-last-changed-timestamp
9936 (org-insert-time-stamp
9937 time (or org-time-was-given arg)
9938 nil nil nil (list org-end-time-was-given))))
9939 (message "Timestamp updated"))
9941 (setq time (let ((this-command this-command))
9942 (org-read-date arg 'totime nil nil default-time default-input)))
9943 (org-insert-time-stamp time (or org-time-was-given arg)
9944 nil nil nil (list org-end-time-was-given))))))
9946 ;; FIXME: can we use this for something else, like computing time differences?
9947 (defun org-get-compact-tod (s)
9948 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
9949 (let* ((t1 (match-string 1 s))
9950 (h1 (string-to-number (match-string 2 s)))
9951 (m1 (string-to-number (match-string 3 s)))
9952 (t2 (and (match-end 4) (match-string 5 s)))
9953 (h2 (and t2 (string-to-number (match-string 6 s))))
9954 (m2 (and t2 (string-to-number (match-string 7 s))))
9955 dh dm)
9956 (if (not t2)
9958 (setq dh (- h2 h1) dm (- m2 m1))
9959 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
9960 (concat t1 "+" (number-to-string dh)
9961 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
9963 (defun org-time-stamp-inactive (&optional arg)
9964 "Insert an inactive time stamp.
9965 An inactive time stamp is enclosed in square brackets instead of angle
9966 brackets. It is inactive in the sense that it does not trigger agenda entries,
9967 does not link to the calendar and cannot be changed with the S-cursor keys.
9968 So these are more for recording a certain time/date."
9969 (interactive "P")
9970 (let (org-time-was-given org-end-time-was-given time)
9971 (setq time (org-read-date arg 'totime))
9972 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
9973 nil nil (list org-end-time-was-given))))
9975 (defvar org-date-ovl (org-make-overlay 1 1))
9976 (org-overlay-put org-date-ovl 'face 'org-warning)
9977 (org-detach-overlay org-date-ovl)
9979 (defvar org-ans1) ; dynamically scoped parameter
9980 (defvar org-ans2) ; dynamically scoped parameter
9982 (defvar org-plain-time-of-day-regexp) ; defined below
9984 (defvar org-read-date-overlay nil)
9985 (defvar org-dcst nil) ; dynamically scoped
9987 (defun org-read-date (&optional with-time to-time from-string prompt
9988 default-time default-input)
9989 "Read a date, possibly a time, and make things smooth for the user.
9990 The prompt will suggest to enter an ISO date, but you can also enter anything
9991 which will at least partially be understood by `parse-time-string'.
9992 Unrecognized parts of the date will default to the current day, month, year,
9993 hour and minute. If this command is called to replace a timestamp at point,
9994 of to enter the second timestamp of a range, the default time is taken from the
9995 existing stamp. For example,
9996 3-2-5 --> 2003-02-05
9997 feb 15 --> currentyear-02-15
9998 sep 12 9 --> 2009-09-12
9999 12:45 --> today 12:45
10000 22 sept 0:34 --> currentyear-09-22 0:34
10001 12 --> currentyear-currentmonth-12
10002 Fri --> nearest Friday (today or later)
10003 etc.
10005 Furthermore you can specify a relative date by giving, as the *first* thing
10006 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10007 change in days weeks, months, years.
10008 With a single plus or minus, the date is relative to today. With a double
10009 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10010 +4d --> four days from today
10011 +4 --> same as above
10012 +2w --> two weeks from today
10013 ++5 --> five days from default date
10015 The function understands only English month and weekday abbreviations,
10016 but this can be configured with the variables `parse-time-months' and
10017 `parse-time-weekdays'.
10019 While prompting, a calendar is popped up - you can also select the
10020 date with the mouse (button 1). The calendar shows a period of three
10021 months. To scroll it to other months, use the keys `>' and `<'.
10022 If you don't like the calendar, turn it off with
10023 \(setq org-read-date-popup-calendar nil)
10025 With optional argument TO-TIME, the date will immediately be converted
10026 to an internal time.
10027 With an optional argument WITH-TIME, the prompt will suggest to also
10028 insert a time. Note that when WITH-TIME is not set, you can still
10029 enter a time, and this function will inform the calling routine about
10030 this change. The calling routine may then choose to change the format
10031 used to insert the time stamp into the buffer to include the time.
10032 With optional argument FROM-STRING, read from this string instead from
10033 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10034 the time/date that is used for everything that is not specified by the
10035 user."
10036 (require 'parse-time)
10037 (let* ((org-time-stamp-rounding-minutes
10038 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10039 (org-dcst org-display-custom-times)
10040 (ct (org-current-time))
10041 (def (or default-time ct))
10042 (defdecode (decode-time def))
10043 (dummy (progn
10044 (when (< (nth 2 defdecode) org-extend-today-until)
10045 (setcar (nthcdr 2 defdecode) -1)
10046 (setcar (nthcdr 1 defdecode) 59)
10047 (setq def (apply 'encode-time defdecode)
10048 defdecode (decode-time def)))))
10049 (calendar-move-hook nil)
10050 (calendar-view-diary-initially-flag nil)
10051 (view-diary-entries-initially nil)
10052 (calendar-view-holidays-initially-flag nil)
10053 (view-calendar-holidays-initially nil)
10054 (timestr (format-time-string
10055 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10056 (prompt (concat (if prompt (concat prompt " ") "")
10057 (format "Date+time [%s]: " timestr)))
10058 ans (org-ans0 "") org-ans1 org-ans2 final)
10060 (cond
10061 (from-string (setq ans from-string))
10062 (org-read-date-popup-calendar
10063 (save-excursion
10064 (save-window-excursion
10065 (calendar)
10066 (calendar-forward-day (- (time-to-days def)
10067 (calendar-absolute-from-gregorian
10068 (calendar-current-date))))
10069 (org-eval-in-calendar nil t)
10070 (let* ((old-map (current-local-map))
10071 (map (copy-keymap calendar-mode-map))
10072 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10073 (org-defkey map (kbd "RET") 'org-calendar-select)
10074 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10075 'org-calendar-select-mouse)
10076 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10077 'org-calendar-select-mouse)
10078 (org-defkey minibuffer-local-map [(meta shift left)]
10079 (lambda () (interactive)
10080 (org-eval-in-calendar '(calendar-backward-month 1))))
10081 (org-defkey minibuffer-local-map [(meta shift right)]
10082 (lambda () (interactive)
10083 (org-eval-in-calendar '(calendar-forward-month 1))))
10084 (org-defkey minibuffer-local-map [(meta shift up)]
10085 (lambda () (interactive)
10086 (org-eval-in-calendar '(calendar-backward-year 1))))
10087 (org-defkey minibuffer-local-map [(meta shift down)]
10088 (lambda () (interactive)
10089 (org-eval-in-calendar '(calendar-forward-year 1))))
10090 (org-defkey minibuffer-local-map [(shift up)]
10091 (lambda () (interactive)
10092 (org-eval-in-calendar '(calendar-backward-week 1))))
10093 (org-defkey minibuffer-local-map [(shift down)]
10094 (lambda () (interactive)
10095 (org-eval-in-calendar '(calendar-forward-week 1))))
10096 (org-defkey minibuffer-local-map [(shift left)]
10097 (lambda () (interactive)
10098 (org-eval-in-calendar '(calendar-backward-day 1))))
10099 (org-defkey minibuffer-local-map [(shift right)]
10100 (lambda () (interactive)
10101 (org-eval-in-calendar '(calendar-forward-day 1))))
10102 (org-defkey minibuffer-local-map ">"
10103 (lambda () (interactive)
10104 (org-eval-in-calendar '(scroll-calendar-left 1))))
10105 (org-defkey minibuffer-local-map "<"
10106 (lambda () (interactive)
10107 (org-eval-in-calendar '(scroll-calendar-right 1))))
10108 (unwind-protect
10109 (progn
10110 (use-local-map map)
10111 (add-hook 'post-command-hook 'org-read-date-display)
10112 (setq org-ans0 (read-string prompt default-input nil nil))
10113 ;; org-ans0: from prompt
10114 ;; org-ans1: from mouse click
10115 ;; org-ans2: from calendar motion
10116 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10117 (remove-hook 'post-command-hook 'org-read-date-display)
10118 (use-local-map old-map)
10119 (when org-read-date-overlay
10120 (org-delete-overlay org-read-date-overlay)
10121 (setq org-read-date-overlay nil)))))))
10123 (t ; Naked prompt only
10124 (unwind-protect
10125 (setq ans (read-string prompt default-input nil timestr))
10126 (when org-read-date-overlay
10127 (org-delete-overlay org-read-date-overlay)
10128 (setq org-read-date-overlay nil)))))
10130 (setq final (org-read-date-analyze ans def defdecode))
10132 (if to-time
10133 (apply 'encode-time final)
10134 (if (and (boundp 'org-time-was-given) org-time-was-given)
10135 (format "%04d-%02d-%02d %02d:%02d"
10136 (nth 5 final) (nth 4 final) (nth 3 final)
10137 (nth 2 final) (nth 1 final))
10138 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10139 (defvar def)
10140 (defvar defdecode)
10141 (defvar with-time)
10142 (defun org-read-date-display ()
10143 "Display the currrent date prompt interpretation in the minibuffer."
10144 (when org-read-date-display-live
10145 (when org-read-date-overlay
10146 (org-delete-overlay org-read-date-overlay))
10147 (let ((p (point)))
10148 (end-of-line 1)
10149 (while (not (equal (buffer-substring
10150 (max (point-min) (- (point) 4)) (point))
10151 " "))
10152 (insert " "))
10153 (goto-char p))
10154 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10155 " " (or org-ans1 org-ans2)))
10156 (org-end-time-was-given nil)
10157 (f (org-read-date-analyze ans def defdecode))
10158 (fmts (if org-dcst
10159 org-time-stamp-custom-formats
10160 org-time-stamp-formats))
10161 (fmt (if (or with-time
10162 (and (boundp 'org-time-was-given) org-time-was-given))
10163 (cdr fmts)
10164 (car fmts)))
10165 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10166 (when (and org-end-time-was-given
10167 (string-match org-plain-time-of-day-regexp txt))
10168 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10169 org-end-time-was-given
10170 (substring txt (match-end 0)))))
10171 (setq org-read-date-overlay
10172 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10173 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10175 (defun org-read-date-analyze (ans def defdecode)
10176 "Analyze the combined answer of the date prompt."
10177 ;; FIXME: cleanup and comment
10178 (let (delta deltan deltaw deltadef year month day
10179 hour minute second wday pm h2 m2 tl wday1
10180 iso-year iso-weekday iso-week iso-year iso-date)
10182 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10183 (setq ans (replace-match "" t t ans)
10184 deltan (car delta)
10185 deltaw (nth 1 delta)
10186 deltadef (nth 2 delta)))
10188 ;; Check if there is an iso week date in there
10189 ;; If yes, sore the info and ostpone interpreting it until the rest
10190 ;; of the parsing is done
10191 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10192 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10193 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10194 iso-week (string-to-number (match-string 2 ans)))
10195 (setq ans (replace-match "" t t ans)))
10197 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10198 (when (string-match
10199 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10200 (setq year (if (match-end 2)
10201 (string-to-number (match-string 2 ans))
10202 (string-to-number (format-time-string "%Y")))
10203 month (string-to-number (match-string 3 ans))
10204 day (string-to-number (match-string 4 ans)))
10205 (if (< year 100) (setq year (+ 2000 year)))
10206 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10207 t nil ans)))
10208 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10209 ;; If there is a time with am/pm, and *no* time without it, we convert
10210 ;; so that matching will be successful.
10211 (loop for i from 1 to 2 do ; twice, for end time as well
10212 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10213 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10214 (setq hour (string-to-number (match-string 1 ans))
10215 minute (if (match-end 3)
10216 (string-to-number (match-string 3 ans))
10218 pm (equal ?p
10219 (string-to-char (downcase (match-string 4 ans)))))
10220 (if (and (= hour 12) (not pm))
10221 (setq hour 0)
10222 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10223 (setq ans (replace-match (format "%02d:%02d" hour minute)
10224 t t ans))))
10226 ;; Check if a time range is given as a duration
10227 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10228 (setq hour (string-to-number (match-string 1 ans))
10229 h2 (+ hour (string-to-number (match-string 3 ans)))
10230 minute (string-to-number (match-string 2 ans))
10231 m2 (+ minute (if (match-end 5) (string-to-number
10232 (match-string 5 ans))0)))
10233 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10234 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10235 t t ans)))
10237 ;; Check if there is a time range
10238 (when (boundp 'org-end-time-was-given)
10239 (setq org-time-was-given nil)
10240 (when (and (string-match org-plain-time-of-day-regexp ans)
10241 (match-end 8))
10242 (setq org-end-time-was-given (match-string 8 ans))
10243 (setq ans (concat (substring ans 0 (match-beginning 7))
10244 (substring ans (match-end 7))))))
10246 (setq tl (parse-time-string ans)
10247 day (or (nth 3 tl) (nth 3 defdecode))
10248 month (or (nth 4 tl)
10249 (if (and org-read-date-prefer-future
10250 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10251 (1+ (nth 4 defdecode))
10252 (nth 4 defdecode)))
10253 year (or (nth 5 tl)
10254 (if (and org-read-date-prefer-future
10255 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10256 (1+ (nth 5 defdecode))
10257 (nth 5 defdecode)))
10258 hour (or (nth 2 tl) (nth 2 defdecode))
10259 minute (or (nth 1 tl) (nth 1 defdecode))
10260 second (or (nth 0 tl) 0)
10261 wday (nth 6 tl))
10263 ;; Special date definitions below
10264 (cond
10265 (iso-week
10266 ;; There was an iso week
10267 (setq year (or iso-year year)
10268 day (or iso-weekday wday 1)
10269 wday nil ; to make sure that the trigger below does not match
10270 iso-date (calendar-gregorian-from-absolute
10271 (calendar-absolute-from-iso
10272 (list iso-week day year))))
10273 ; FIXME: Should we also push ISO weeks into the future?
10274 ; (when (and org-read-date-prefer-future
10275 ; (not iso-year)
10276 ; (< (calendar-absolute-from-gregorian iso-date)
10277 ; (time-to-days (current-time))))
10278 ; (setq year (1+ year)
10279 ; iso-date (calendar-gregorian-from-absolute
10280 ; (calendar-absolute-from-iso
10281 ; (list iso-week day year)))))
10282 (setq month (car iso-date)
10283 year (nth 2 iso-date)
10284 day (nth 1 iso-date)))
10285 (deltan
10286 (unless deltadef
10287 (let ((now (decode-time (current-time))))
10288 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10289 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10290 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10291 ((equal deltaw "m") (setq month (+ month deltan)))
10292 ((equal deltaw "y") (setq year (+ year deltan)))))
10293 ((and wday (not (nth 3 tl)))
10294 ;; Weekday was given, but no day, so pick that day in the week
10295 ;; on or after the derived date.
10296 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10297 (unless (equal wday wday1)
10298 (setq day (+ day (% (- wday wday1 -7) 7))))))
10299 (if (and (boundp 'org-time-was-given)
10300 (nth 2 tl))
10301 (setq org-time-was-given t))
10302 (if (< year 100) (setq year (+ 2000 year)))
10303 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10304 (list second minute hour day month year)))
10306 (defvar parse-time-weekdays)
10308 (defun org-read-date-get-relative (s today default)
10309 "Check string S for special relative date string.
10310 TODAY and DEFAULT are internal times, for today and for a default.
10311 Return shift list (N what def-flag)
10312 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10313 N is the number of WHATs to shift.
10314 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10315 the DEFAULT date rather than TODAY."
10316 (when (string-match
10317 (concat
10318 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
10319 "\\([0-9]+\\)?"
10320 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10321 "\\([ \t]\\|$\\)") s)
10322 (let* ((dir (if (match-end 1)
10323 (string-to-char (substring (match-string 1 s) -1))
10324 ?+))
10325 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10326 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10327 (what (if (match-end 3) (match-string 3 s) "d"))
10328 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10329 (date (if rel default today))
10330 (wday (nth 6 (decode-time date)))
10331 delta)
10332 (if wday1
10333 (progn
10334 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10335 (if (= dir ?-) (setq delta (- delta 7)))
10336 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10337 (list delta "d" rel))
10338 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10340 (defun org-eval-in-calendar (form &optional keepdate)
10341 "Eval FORM in the calendar window and return to current window.
10342 Also, store the cursor date in variable org-ans2."
10343 (let ((sw (selected-window)))
10344 (select-window (get-buffer-window "*Calendar*"))
10345 (eval form)
10346 (when (and (not keepdate) (calendar-cursor-to-date))
10347 (let* ((date (calendar-cursor-to-date))
10348 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10349 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10350 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10351 (select-window sw)))
10353 ; ;; Update the prompt to show new default date
10354 ; (save-excursion
10355 ; (goto-char (point-min))
10356 ; (when (and org-ans2
10357 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10358 ; (get-text-property (match-end 0) 'field))
10359 ; (let ((inhibit-read-only t))
10360 ; (replace-match (concat "[" org-ans2 "]") t t)
10361 ; (add-text-properties (point-min) (1+ (match-end 0))
10362 ; (text-properties-at (1+ (point-min)))))))))
10364 (defun org-calendar-select ()
10365 "Return to `org-read-date' with the date currently selected.
10366 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10367 (interactive)
10368 (when (calendar-cursor-to-date)
10369 (let* ((date (calendar-cursor-to-date))
10370 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10371 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10372 (if (active-minibuffer-window) (exit-minibuffer))))
10374 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10375 "Insert a date stamp for the date given by the internal TIME.
10376 WITH-HM means, use the stamp format that includes the time of the day.
10377 INACTIVE means use square brackets instead of angular ones, so that the
10378 stamp will not contribute to the agenda.
10379 PRE and POST are optional strings to be inserted before and after the
10380 stamp.
10381 The command returns the inserted time stamp."
10382 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10383 stamp)
10384 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10385 (insert-before-markers (or pre ""))
10386 (insert-before-markers (setq stamp (format-time-string fmt time)))
10387 (when (listp extra)
10388 (setq extra (car extra))
10389 (if (and (stringp extra)
10390 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10391 (setq extra (format "-%02d:%02d"
10392 (string-to-number (match-string 1 extra))
10393 (string-to-number (match-string 2 extra))))
10394 (setq extra nil)))
10395 (when extra
10396 (backward-char 1)
10397 (insert-before-markers extra)
10398 (forward-char 1))
10399 (insert-before-markers (or post ""))
10400 stamp))
10402 (defun org-toggle-time-stamp-overlays ()
10403 "Toggle the use of custom time stamp formats."
10404 (interactive)
10405 (setq org-display-custom-times (not org-display-custom-times))
10406 (unless org-display-custom-times
10407 (let ((p (point-min)) (bmp (buffer-modified-p)))
10408 (while (setq p (next-single-property-change p 'display))
10409 (if (and (get-text-property p 'display)
10410 (eq (get-text-property p 'face) 'org-date))
10411 (remove-text-properties
10412 p (setq p (next-single-property-change p 'display))
10413 '(display t))))
10414 (set-buffer-modified-p bmp)))
10415 (if (featurep 'xemacs)
10416 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10417 (org-restart-font-lock)
10418 (setq org-table-may-need-update t)
10419 (if org-display-custom-times
10420 (message "Time stamps are overlayed with custom format")
10421 (message "Time stamp overlays removed")))
10423 (defun org-display-custom-time (beg end)
10424 "Overlay modified time stamp format over timestamp between BED and END."
10425 (let* ((ts (buffer-substring beg end))
10426 t1 w1 with-hm tf time str w2 (off 0))
10427 (save-match-data
10428 (setq t1 (org-parse-time-string ts t))
10429 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10430 (setq off (- (match-end 0) (match-beginning 0)))))
10431 (setq end (- end off))
10432 (setq w1 (- end beg)
10433 with-hm (and (nth 1 t1) (nth 2 t1))
10434 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10435 time (org-fix-decoded-time t1)
10436 str (org-add-props
10437 (format-time-string
10438 (substring tf 1 -1) (apply 'encode-time time))
10439 nil 'mouse-face 'highlight)
10440 w2 (length str))
10441 (if (not (= w2 w1))
10442 (add-text-properties (1+ beg) (+ 2 beg)
10443 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10444 (if (featurep 'xemacs)
10445 (progn
10446 (put-text-property beg end 'invisible t)
10447 (put-text-property beg end 'end-glyph (make-glyph str)))
10448 (put-text-property beg end 'display str))))
10450 (defun org-translate-time (string)
10451 "Translate all timestamps in STRING to custom format.
10452 But do this only if the variable `org-display-custom-times' is set."
10453 (when org-display-custom-times
10454 (save-match-data
10455 (let* ((start 0)
10456 (re org-ts-regexp-both)
10457 t1 with-hm inactive tf time str beg end)
10458 (while (setq start (string-match re string start))
10459 (setq beg (match-beginning 0)
10460 end (match-end 0)
10461 t1 (save-match-data
10462 (org-parse-time-string (substring string beg end) t))
10463 with-hm (and (nth 1 t1) (nth 2 t1))
10464 inactive (equal (substring string beg (1+ beg)) "[")
10465 tf (funcall (if with-hm 'cdr 'car)
10466 org-time-stamp-custom-formats)
10467 time (org-fix-decoded-time t1)
10468 str (format-time-string
10469 (concat
10470 (if inactive "[" "<") (substring tf 1 -1)
10471 (if inactive "]" ">"))
10472 (apply 'encode-time time))
10473 string (replace-match str t t string)
10474 start (+ start (length str)))))))
10475 string)
10477 (defun org-fix-decoded-time (time)
10478 "Set 0 instead of nil for the first 6 elements of time.
10479 Don't touch the rest."
10480 (let ((n 0))
10481 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10483 (defun org-days-to-time (timestamp-string)
10484 "Difference between TIMESTAMP-STRING and now in days."
10485 (- (time-to-days (org-time-string-to-time timestamp-string))
10486 (time-to-days (current-time))))
10488 (defun org-deadline-close (timestamp-string &optional ndays)
10489 "Is the time in TIMESTAMP-STRING close to the current date?"
10490 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10491 (and (< (org-days-to-time timestamp-string) ndays)
10492 (not (org-entry-is-done-p))))
10494 (defun org-get-wdays (ts)
10495 "Get the deadline lead time appropriate for timestring TS."
10496 (cond
10497 ((<= org-deadline-warning-days 0)
10498 ;; 0 or negative, enforce this value no matter what
10499 (- org-deadline-warning-days))
10500 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10501 ;; lead time is specified.
10502 (floor (* (string-to-number (match-string 1 ts))
10503 (cdr (assoc (match-string 2 ts)
10504 '(("d" . 1) ("w" . 7)
10505 ("m" . 30.4) ("y" . 365.25)))))))
10506 ;; go for the default.
10507 (t org-deadline-warning-days)))
10509 (defun org-calendar-select-mouse (ev)
10510 "Return to `org-read-date' with the date currently selected.
10511 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10512 (interactive "e")
10513 (mouse-set-point ev)
10514 (when (calendar-cursor-to-date)
10515 (let* ((date (calendar-cursor-to-date))
10516 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10517 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10518 (if (active-minibuffer-window) (exit-minibuffer))))
10520 (defun org-check-deadlines (ndays)
10521 "Check if there are any deadlines due or past due.
10522 A deadline is considered due if it happens within `org-deadline-warning-days'
10523 days from today's date. If the deadline appears in an entry marked DONE,
10524 it is not shown. The prefix arg NDAYS can be used to test that many
10525 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10526 (interactive "P")
10527 (let* ((org-warn-days
10528 (cond
10529 ((equal ndays '(4)) 100000)
10530 (ndays (prefix-numeric-value ndays))
10531 (t (abs org-deadline-warning-days))))
10532 (case-fold-search nil)
10533 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10534 (callback
10535 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10537 (message "%d deadlines past-due or due within %d days"
10538 (org-occur regexp nil callback)
10539 org-warn-days)))
10541 (defun org-check-before-date (date)
10542 "Check if there are deadlines or scheduled entries before DATE."
10543 (interactive (list (org-read-date)))
10544 (let ((case-fold-search nil)
10545 (regexp (concat "\\<\\(" org-deadline-string
10546 "\\|" org-scheduled-string
10547 "\\) *<\\([^>]+\\)>"))
10548 (callback
10549 (lambda () (time-less-p
10550 (org-time-string-to-time (match-string 2))
10551 (org-time-string-to-time date)))))
10552 (message "%d entries before %s"
10553 (org-occur regexp nil callback) date)))
10555 (defun org-evaluate-time-range (&optional to-buffer)
10556 "Evaluate a time range by computing the difference between start and end.
10557 Normally the result is just printed in the echo area, but with prefix arg
10558 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10559 If the time range is actually in a table, the result is inserted into the
10560 next column.
10561 For time difference computation, a year is assumed to be exactly 365
10562 days in order to avoid rounding problems."
10563 (interactive "P")
10565 (org-clock-update-time-maybe)
10566 (save-excursion
10567 (unless (org-at-date-range-p t)
10568 (goto-char (point-at-bol))
10569 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10570 (if (not (org-at-date-range-p t))
10571 (error "Not at a time-stamp range, and none found in current line")))
10572 (let* ((ts1 (match-string 1))
10573 (ts2 (match-string 2))
10574 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10575 (match-end (match-end 0))
10576 (time1 (org-time-string-to-time ts1))
10577 (time2 (org-time-string-to-time ts2))
10578 (t1 (time-to-seconds time1))
10579 (t2 (time-to-seconds time2))
10580 (diff (abs (- t2 t1)))
10581 (negative (< (- t2 t1) 0))
10582 ;; (ys (floor (* 365 24 60 60)))
10583 (ds (* 24 60 60))
10584 (hs (* 60 60))
10585 (fy "%dy %dd %02d:%02d")
10586 (fy1 "%dy %dd")
10587 (fd "%dd %02d:%02d")
10588 (fd1 "%dd")
10589 (fh "%02d:%02d")
10590 y d h m align)
10591 (if havetime
10592 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10594 d (floor (/ diff ds)) diff (mod diff ds)
10595 h (floor (/ diff hs)) diff (mod diff hs)
10596 m (floor (/ diff 60)))
10597 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10599 d (floor (+ (/ diff ds) 0.5))
10600 h 0 m 0))
10601 (if (not to-buffer)
10602 (message "%s" (org-make-tdiff-string y d h m))
10603 (if (org-at-table-p)
10604 (progn
10605 (goto-char match-end)
10606 (setq align t)
10607 (and (looking-at " *|") (goto-char (match-end 0))))
10608 (goto-char match-end))
10609 (if (looking-at
10610 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10611 (replace-match ""))
10612 (if negative (insert " -"))
10613 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10614 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10615 (insert " " (format fh h m))))
10616 (if align (org-table-align))
10617 (message "Time difference inserted")))))
10619 (defun org-make-tdiff-string (y d h m)
10620 (let ((fmt "")
10621 (l nil))
10622 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10623 l (push y l)))
10624 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10625 l (push d l)))
10626 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10627 l (push h l)))
10628 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10629 l (push m l)))
10630 (apply 'format fmt (nreverse l))))
10632 (defun org-time-string-to-time (s)
10633 (apply 'encode-time (org-parse-time-string s)))
10635 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10636 "Convert a time stamp to an absolute day number.
10637 If there is a specifyer for a cyclic time stamp, get the closest date to
10638 DAYNR.
10639 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10640 (cond
10641 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10642 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10643 daynr
10644 (+ daynr 1000)))
10645 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10646 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10647 (time-to-days (current-time))) (match-string 0 s)
10648 prefer show-all))
10649 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10651 (defun org-days-to-iso-week (days)
10652 "Return the iso week number."
10653 (require 'cal-iso)
10654 (car (calendar-iso-from-absolute days)))
10656 (defun org-small-year-to-year (year)
10657 "Convert 2-digit years into 4-digit years.
10658 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10659 The year 2000 cannot be abbreviated. Any year lager than 99
10660 is retrned unchanged."
10661 (if (< year 38)
10662 (setq year (+ 2000 year))
10663 (if (< year 100)
10664 (setq year (+ 1900 year))))
10665 year)
10667 (defun org-time-from-absolute (d)
10668 "Return the time corresponding to date D.
10669 D may be an absolute day number, or a calendar-type list (month day year)."
10670 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10671 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10673 (defun org-calendar-holiday ()
10674 "List of holidays, for Diary display in Org-mode."
10675 (require 'holidays)
10676 (let ((hl (funcall
10677 (if (fboundp 'calendar-check-holidays)
10678 'calendar-check-holidays 'check-calendar-holidays) date)))
10679 (if hl (mapconcat 'identity hl "; "))))
10681 (defun org-diary-sexp-entry (sexp entry date)
10682 "Process a SEXP diary ENTRY for DATE."
10683 (require 'diary-lib)
10684 (let ((result (if calendar-debug-sexp
10685 (let ((stack-trace-on-error t))
10686 (eval (car (read-from-string sexp))))
10687 (condition-case nil
10688 (eval (car (read-from-string sexp)))
10689 (error
10690 (beep)
10691 (message "Bad sexp at line %d in %s: %s"
10692 (org-current-line)
10693 (buffer-file-name) sexp)
10694 (sleep-for 2))))))
10695 (cond ((stringp result) result)
10696 ((and (consp result)
10697 (stringp (cdr result))) (cdr result))
10698 (result entry)
10699 (t nil))))
10701 (defun org-diary-to-ical-string (frombuf)
10702 "Get iCalendar entries from diary entries in buffer FROMBUF.
10703 This uses the icalendar.el library."
10704 (let* ((tmpdir (if (featurep 'xemacs)
10705 (temp-directory)
10706 temporary-file-directory))
10707 (tmpfile (make-temp-name
10708 (expand-file-name "orgics" tmpdir)))
10709 buf rtn b e)
10710 (save-excursion
10711 (set-buffer frombuf)
10712 (icalendar-export-region (point-min) (point-max) tmpfile)
10713 (setq buf (find-buffer-visiting tmpfile))
10714 (set-buffer buf)
10715 (goto-char (point-min))
10716 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10717 (setq b (match-beginning 0)))
10718 (goto-char (point-max))
10719 (if (re-search-backward "^END:VEVENT" nil t)
10720 (setq e (match-end 0)))
10721 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
10722 (kill-buffer buf)
10723 (kill-buffer frombuf)
10724 (delete-file tmpfile)
10725 rtn))
10727 (defun org-closest-date (start current change prefer show-all)
10728 "Find the date closest to CURRENT that is consistent with START and CHANGE.
10729 When PREFER is `past' return a date that is either CURRENT or past.
10730 When PREFER is `future', return a date that is either CURRENT or future.
10731 When SHOW-ALL is nil, only return the current occurence of a time stamp."
10732 ;; Make the proper lists from the dates
10733 (catch 'exit
10734 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
10735 dn dw sday cday n1 n2
10736 d m y y1 y2 date1 date2 nmonths nm ny m2)
10738 (setq start (org-date-to-gregorian start)
10739 current (org-date-to-gregorian
10740 (if show-all
10741 current
10742 (time-to-days (current-time))))
10743 sday (calendar-absolute-from-gregorian start)
10744 cday (calendar-absolute-from-gregorian current))
10746 (if (<= cday sday) (throw 'exit sday))
10748 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
10749 (setq dn (string-to-number (match-string 1 change))
10750 dw (cdr (assoc (match-string 2 change) a1)))
10751 (error "Invalid change specifyer: %s" change))
10752 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
10753 (cond
10754 ((eq dw 'day)
10755 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
10756 n2 (+ n1 dn)))
10757 ((eq dw 'year)
10758 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
10759 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
10760 (setq date1 (list m d y1)
10761 n1 (calendar-absolute-from-gregorian date1)
10762 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
10763 n2 (calendar-absolute-from-gregorian date2)))
10764 ((eq dw 'month)
10765 ;; approx number of month between the tow dates
10766 (setq nmonths (floor (/ (- cday sday) 30.436875)))
10767 ;; How often does dn fit in there?
10768 (setq d (nth 1 start) m (car start) y (nth 2 start)
10769 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
10770 m (+ m nm)
10771 ny (floor (/ m 12))
10772 y (+ y ny)
10773 m (- m (* ny 12)))
10774 (while (> m 12) (setq m (- m 12) y (1+ y)))
10775 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
10776 (setq m2 (+ m dn) y2 y)
10777 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10778 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
10779 (while (< n2 cday)
10780 (setq n1 n2 m m2 y y2)
10781 (setq m2 (+ m dn) y2 y)
10782 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10783 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
10785 (if show-all
10786 (cond
10787 ((eq prefer 'past) n1)
10788 ((eq prefer 'future) (if (= cday n1) n1 n2))
10789 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
10790 (cond
10791 ((eq prefer 'past) n1)
10792 ((eq prefer 'future) (if (= cday n1) n1 n2))
10793 (t (if (= cday n1) n1 n2)))))))
10795 (defun org-date-to-gregorian (date)
10796 "Turn any specification of DATE into a gregorian date for the calendar."
10797 (cond ((integerp date) (calendar-gregorian-from-absolute date))
10798 ((and (listp date) (= (length date) 3)) date)
10799 ((stringp date)
10800 (setq date (org-parse-time-string date))
10801 (list (nth 4 date) (nth 3 date) (nth 5 date)))
10802 ((listp date)
10803 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
10805 (defun org-parse-time-string (s &optional nodefault)
10806 "Parse the standard Org-mode time string.
10807 This should be a lot faster than the normal `parse-time-string'.
10808 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
10809 hour and minute fields will be nil if not given."
10810 (if (string-match org-ts-regexp0 s)
10811 (list 0
10812 (if (or (match-beginning 8) (not nodefault))
10813 (string-to-number (or (match-string 8 s) "0")))
10814 (if (or (match-beginning 7) (not nodefault))
10815 (string-to-number (or (match-string 7 s) "0")))
10816 (string-to-number (match-string 4 s))
10817 (string-to-number (match-string 3 s))
10818 (string-to-number (match-string 2 s))
10819 nil nil nil)
10820 (make-list 9 0)))
10822 (defun org-timestamp-up (&optional arg)
10823 "Increase the date item at the cursor by one.
10824 If the cursor is on the year, change the year. If it is on the month or
10825 the day, change that.
10826 With prefix ARG, change by that many units."
10827 (interactive "p")
10828 (org-timestamp-change (prefix-numeric-value arg)))
10830 (defun org-timestamp-down (&optional arg)
10831 "Decrease the date item at the cursor by one.
10832 If the cursor is on the year, change the year. If it is on the month or
10833 the day, change that.
10834 With prefix ARG, change by that many units."
10835 (interactive "p")
10836 (org-timestamp-change (- (prefix-numeric-value arg))))
10838 (defun org-timestamp-up-day (&optional arg)
10839 "Increase the date in the time stamp by one day.
10840 With prefix ARG, change that many days."
10841 (interactive "p")
10842 (if (and (not (org-at-timestamp-p t))
10843 (org-on-heading-p))
10844 (org-todo 'up)
10845 (org-timestamp-change (prefix-numeric-value arg) 'day)))
10847 (defun org-timestamp-down-day (&optional arg)
10848 "Decrease the date in the time stamp by one day.
10849 With prefix ARG, change that many days."
10850 (interactive "p")
10851 (if (and (not (org-at-timestamp-p t))
10852 (org-on-heading-p))
10853 (org-todo 'down)
10854 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
10856 (defun org-at-timestamp-p (&optional inactive-ok)
10857 "Determine if the cursor is in or at a timestamp."
10858 (interactive)
10859 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
10860 (pos (point))
10861 (ans (or (looking-at tsr)
10862 (save-excursion
10863 (skip-chars-backward "^[<\n\r\t")
10864 (if (> (point) (point-min)) (backward-char 1))
10865 (and (looking-at tsr)
10866 (> (- (match-end 0) pos) -1))))))
10867 (and ans
10868 (boundp 'org-ts-what)
10869 (setq org-ts-what
10870 (cond
10871 ((= pos (match-beginning 0)) 'bracket)
10872 ((= pos (1- (match-end 0))) 'bracket)
10873 ((org-pos-in-match-range pos 2) 'year)
10874 ((org-pos-in-match-range pos 3) 'month)
10875 ((org-pos-in-match-range pos 7) 'hour)
10876 ((org-pos-in-match-range pos 8) 'minute)
10877 ((or (org-pos-in-match-range pos 4)
10878 (org-pos-in-match-range pos 5)) 'day)
10879 ((and (> pos (or (match-end 8) (match-end 5)))
10880 (< pos (match-end 0)))
10881 (- pos (or (match-end 8) (match-end 5))))
10882 (t 'day))))
10883 ans))
10885 (defun org-toggle-timestamp-type ()
10886 "Toggle the type (<active> or [inactive]) of a time stamp."
10887 (interactive)
10888 (when (org-at-timestamp-p t)
10889 (save-excursion
10890 (goto-char (match-beginning 0))
10891 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
10892 (goto-char (1- (match-end 0)))
10893 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
10894 (message "Timestamp is now %sactive"
10895 (if (equal (char-before) ?>) "in" ""))))
10897 (defun org-timestamp-change (n &optional what)
10898 "Change the date in the time stamp at point.
10899 The date will be changed by N times WHAT. WHAT can be `day', `month',
10900 `year', `minute', `second'. If WHAT is not given, the cursor position
10901 in the timestamp determines what will be changed."
10902 (let ((pos (point))
10903 with-hm inactive
10904 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
10905 org-ts-what
10906 extra rem
10907 ts time time0)
10908 (if (not (org-at-timestamp-p t))
10909 (error "Not at a timestamp"))
10910 (if (and (not what) (eq org-ts-what 'bracket))
10911 (org-toggle-timestamp-type)
10912 (if (and (not what) (not (eq org-ts-what 'day))
10913 org-display-custom-times
10914 (get-text-property (point) 'display)
10915 (not (get-text-property (1- (point)) 'display)))
10916 (setq org-ts-what 'day))
10917 (setq org-ts-what (or what org-ts-what)
10918 inactive (= (char-after (match-beginning 0)) ?\[)
10919 ts (match-string 0))
10920 (replace-match "")
10921 (if (string-match
10922 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
10924 (setq extra (match-string 1 ts)))
10925 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
10926 (setq with-hm t))
10927 (setq time0 (org-parse-time-string ts))
10928 (when (and (eq org-ts-what 'minute)
10929 (eq current-prefix-arg nil))
10930 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
10931 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
10932 (setcar (cdr time0) (+ (nth 1 time0)
10933 (if (> n 0) (- rem) (- dm rem))))))
10934 (setq time
10935 (encode-time (or (car time0) 0)
10936 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
10937 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
10938 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
10939 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
10940 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
10941 (nthcdr 6 time0)))
10942 (when (integerp org-ts-what)
10943 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
10944 (if (eq what 'calendar)
10945 (let ((cal-date (org-get-date-from-calendar)))
10946 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
10947 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
10948 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
10949 (setcar time0 (or (car time0) 0))
10950 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
10951 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
10952 (setq time (apply 'encode-time time0))))
10953 (setq org-last-changed-timestamp
10954 (org-insert-time-stamp time with-hm inactive nil nil extra))
10955 (org-clock-update-time-maybe)
10956 (goto-char pos)
10957 ;; Try to recenter the calendar window, if any
10958 (if (and org-calendar-follow-timestamp-change
10959 (get-buffer-window "*Calendar*" t)
10960 (memq org-ts-what '(day month year)))
10961 (org-recenter-calendar (time-to-days time))))))
10963 (defun org-modify-ts-extra (s pos n dm)
10964 "Change the different parts of the lead-time and repeat fields in timestamp."
10965 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
10966 ng h m new rem)
10967 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
10968 (cond
10969 ((or (org-pos-in-match-range pos 2)
10970 (org-pos-in-match-range pos 3))
10971 (setq m (string-to-number (match-string 3 s))
10972 h (string-to-number (match-string 2 s)))
10973 (if (org-pos-in-match-range pos 2)
10974 (setq h (+ h n))
10975 (setq n (* dm (org-no-warnings (signum n))))
10976 (when (not (= 0 (setq rem (% m dm))))
10977 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
10978 (setq m (+ m n)))
10979 (if (< m 0) (setq m (+ m 60) h (1- h)))
10980 (if (> m 59) (setq m (- m 60) h (1+ h)))
10981 (setq h (min 24 (max 0 h)))
10982 (setq ng 1 new (format "-%02d:%02d" h m)))
10983 ((org-pos-in-match-range pos 6)
10984 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
10985 ((org-pos-in-match-range pos 5)
10986 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
10988 ((org-pos-in-match-range pos 9)
10989 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
10990 ((org-pos-in-match-range pos 8)
10991 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
10993 (when ng
10994 (setq s (concat
10995 (substring s 0 (match-beginning ng))
10997 (substring s (match-end ng))))))
11000 (defun org-recenter-calendar (date)
11001 "If the calendar is visible, recenter it to DATE."
11002 (let* ((win (selected-window))
11003 (cwin (get-buffer-window "*Calendar*" t))
11004 (calendar-move-hook nil))
11005 (when cwin
11006 (select-window cwin)
11007 (calendar-goto-date (if (listp date) date
11008 (calendar-gregorian-from-absolute date)))
11009 (select-window win))))
11011 (defun org-goto-calendar (&optional arg)
11012 "Go to the Emacs calendar at the current date.
11013 If there is a time stamp in the current line, go to that date.
11014 A prefix ARG can be used to force the current date."
11015 (interactive "P")
11016 (let ((tsr org-ts-regexp) diff
11017 (calendar-move-hook nil)
11018 (calendar-view-holidays-initially-flag nil)
11019 (view-calendar-holidays-initially nil)
11020 (calendar-view-diary-initially-flag nil)
11021 (view-diary-entries-initially nil))
11022 (if (or (org-at-timestamp-p)
11023 (save-excursion
11024 (beginning-of-line 1)
11025 (looking-at (concat ".*" tsr))))
11026 (let ((d1 (time-to-days (current-time)))
11027 (d2 (time-to-days
11028 (org-time-string-to-time (match-string 1)))))
11029 (setq diff (- d2 d1))))
11030 (calendar)
11031 (calendar-goto-today)
11032 (if (and diff (not arg)) (calendar-forward-day diff))))
11034 (defun org-get-date-from-calendar ()
11035 "Return a list (month day year) of date at point in calendar."
11036 (with-current-buffer "*Calendar*"
11037 (save-match-data
11038 (calendar-cursor-to-date))))
11040 (defun org-date-from-calendar ()
11041 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11042 If there is already a time stamp at the cursor position, update it."
11043 (interactive)
11044 (if (org-at-timestamp-p t)
11045 (org-timestamp-change 0 'calendar)
11046 (let ((cal-date (org-get-date-from-calendar)))
11047 (org-insert-time-stamp
11048 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11050 (defun org-minutes-to-hh:mm-string (m)
11051 "Compute H:MM from a number of minutes."
11052 (let ((h (/ m 60)))
11053 (setq m (- m (* 60 h)))
11054 (format "%d:%02d" h m)))
11056 (defun org-hh:mm-string-to-minutes (s)
11057 "Convert a string H:MM to a number of minutes."
11058 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11059 (+ (* (string-to-number (match-string 1 s)) 60)
11060 (string-to-number (match-string 2 s)))
11063 ;;;; Agenda files
11065 ;;;###autoload
11066 (defun org-iswitchb (&optional arg)
11067 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11068 With a prefix argument, restrict available to files.
11069 With two prefix arguments, restrict available buffers to agenda files.
11071 Due to some yet unresolved reason, global function
11072 `iswitchb-mode' needs to be active for this function to work."
11073 (interactive "P")
11074 (require 'iswitchb)
11075 (let ((enabled iswitchb-mode) blist)
11076 (or enabled (iswitchb-mode 1))
11077 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11078 ((equal arg '(16)) (org-buffer-list 'agenda))
11079 (t (org-buffer-list))))
11080 (unwind-protect
11081 (let ((iswitchb-make-buflist-hook
11082 (lambda ()
11083 (setq iswitchb-temp-buflist
11084 (mapcar 'buffer-name blist)))))
11085 (switch-to-buffer
11086 (iswitchb-read-buffer
11087 "Switch-to: " nil t))
11088 (or enabled (iswitchb-mode -1))))))
11090 (defun org-buffer-list (&optional predicate tmp)
11091 "Return a list of Org buffers.
11092 PREDICATE can be either 'export, 'files or 'agenda.
11094 'export restrict the list to Export buffers.
11095 'files restrict the list to buffers visiting Org files.
11096 'agenda restrict the list to buffers visiting agenda files.
11098 If TMP is non-nil, don't include temporary buffers."
11099 (let (filter blist)
11100 (setq filter
11101 (cond ((eq predicate 'files) "\.org$")
11102 ((eq predicate 'export) "\*Org .*Export")
11103 (t "\*Org \\|\.org$")))
11104 (setq blist
11105 (mapcar
11106 (lambda(b)
11107 (let ((bname (buffer-name b))
11108 (bfile (buffer-file-name b)))
11109 (if (and (string-match filter bname)
11110 (if (eq predicate 'agenda)
11111 (member bfile
11112 (mapcar (lambda(f) (file-truename f))
11113 org-agenda-files)) t)
11114 (if tmp (not (string-match "tmp" bname)) t)) b)))
11115 (buffer-list)))
11116 (delete nil blist)))
11118 (defun org-agenda-files (&optional unrestricted ext)
11119 "Get the list of agenda files.
11120 Optional UNRESTRICTED means return the full list even if a restriction
11121 is currently in place.
11122 When EXT is non-nil, try to add all files that are created by adding EXT
11123 to the file nemes. Basically, this is a way to add the archive files
11124 to the list, by setting EXT to \"_archive\" If EXT is non-nil, but not
11125 a string, \"_archive\" will be used."
11126 (let ((files
11127 (cond
11128 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11129 ((stringp org-agenda-files) (org-read-agenda-file-list))
11130 ((listp org-agenda-files) org-agenda-files)
11131 (t (error "Invalid value of `org-agenda-files'")))))
11132 (setq files (apply 'append
11133 (mapcar (lambda (f)
11134 (if (file-directory-p f)
11135 (directory-files
11136 f t org-agenda-file-regexp)
11137 (list f)))
11138 files)))
11139 (when org-agenda-skip-unavailable-files
11140 (setq files (delq nil
11141 (mapcar (function
11142 (lambda (file)
11143 (and (file-readable-p file) file)))
11144 files))))
11145 (when ext
11146 (setq ext (if (and (stringp ext) (string-match "\\S-" ext))
11147 ext "_archive"))
11148 (setq files (apply 'append
11149 (mapcar
11150 (lambda (f)
11151 (if (file-exists-p (concat f ext))
11152 (list f (concat f ext))
11153 (list f)))
11154 files))))
11155 files))
11157 (defun org-edit-agenda-file-list ()
11158 "Edit the list of agenda files.
11159 Depending on setup, this either uses customize to edit the variable
11160 `org-agenda-files', or it visits the file that is holding the list. In the
11161 latter case, the buffer is set up in a way that saving it automatically kills
11162 the buffer and restores the previous window configuration."
11163 (interactive)
11164 (if (stringp org-agenda-files)
11165 (let ((cw (current-window-configuration)))
11166 (find-file org-agenda-files)
11167 (org-set-local 'org-window-configuration cw)
11168 (org-add-hook 'after-save-hook
11169 (lambda ()
11170 (set-window-configuration
11171 (prog1 org-window-configuration
11172 (kill-buffer (current-buffer))))
11173 (org-install-agenda-files-menu)
11174 (message "New agenda file list installed"))
11175 nil 'local)
11176 (message "%s" (substitute-command-keys
11177 "Edit list and finish with \\[save-buffer]")))
11178 (customize-variable 'org-agenda-files)))
11180 (defun org-store-new-agenda-file-list (list)
11181 "Set new value for the agenda file list and save it correcly."
11182 (if (stringp org-agenda-files)
11183 (let ((f org-agenda-files) b)
11184 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11185 (with-temp-file f
11186 (insert (mapconcat 'identity list "\n") "\n")))
11187 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11188 (setq org-agenda-files list)
11189 (customize-save-variable 'org-agenda-files org-agenda-files))))
11191 (defun org-read-agenda-file-list ()
11192 "Read the list of agenda files from a file."
11193 (when (file-directory-p org-agenda-files)
11194 (error "`org-agenda-files' cannot be a single directory"))
11195 (when (stringp org-agenda-files)
11196 (with-temp-buffer
11197 (insert-file-contents org-agenda-files)
11198 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11201 ;;;###autoload
11202 (defun org-cycle-agenda-files ()
11203 "Cycle through the files in `org-agenda-files'.
11204 If the current buffer visits an agenda file, find the next one in the list.
11205 If the current buffer does not, find the first agenda file."
11206 (interactive)
11207 (let* ((fs (org-agenda-files t))
11208 (files (append fs (list (car fs))))
11209 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11210 file)
11211 (unless files (error "No agenda files"))
11212 (catch 'exit
11213 (while (setq file (pop files))
11214 (if (equal (file-truename file) tcf)
11215 (when (car files)
11216 (find-file (car files))
11217 (throw 'exit t))))
11218 (find-file (car fs)))
11219 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11221 (defun org-agenda-file-to-front (&optional to-end)
11222 "Move/add the current file to the top of the agenda file list.
11223 If the file is not present in the list, it is added to the front. If it is
11224 present, it is moved there. With optional argument TO-END, add/move to the
11225 end of the list."
11226 (interactive "P")
11227 (let ((org-agenda-skip-unavailable-files nil)
11228 (file-alist (mapcar (lambda (x)
11229 (cons (file-truename x) x))
11230 (org-agenda-files t)))
11231 (ctf (file-truename buffer-file-name))
11232 x had)
11233 (setq x (assoc ctf file-alist) had x)
11235 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11236 (if to-end
11237 (setq file-alist (append (delq x file-alist) (list x)))
11238 (setq file-alist (cons x (delq x file-alist))))
11239 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11240 (org-install-agenda-files-menu)
11241 (message "File %s to %s of agenda file list"
11242 (if had "moved" "added") (if to-end "end" "front"))))
11244 (defun org-remove-file (&optional file)
11245 "Remove current file from the list of files in variable `org-agenda-files'.
11246 These are the files which are being checked for agenda entries.
11247 Optional argument FILE means, use this file instead of the current."
11248 (interactive)
11249 (let* ((org-agenda-skip-unavailable-files nil)
11250 (file (or file buffer-file-name))
11251 (true-file (file-truename file))
11252 (afile (abbreviate-file-name file))
11253 (files (delq nil (mapcar
11254 (lambda (x)
11255 (if (equal true-file
11256 (file-truename x))
11257 nil x))
11258 (org-agenda-files t)))))
11259 (if (not (= (length files) (length (org-agenda-files t))))
11260 (progn
11261 (org-store-new-agenda-file-list files)
11262 (org-install-agenda-files-menu)
11263 (message "Removed file: %s" afile))
11264 (message "File was not in list: %s (not removed)" afile))))
11266 (defun org-file-menu-entry (file)
11267 (vector file (list 'find-file file) t))
11269 (defun org-check-agenda-file (file)
11270 "Make sure FILE exists. If not, ask user what to do."
11271 (when (not (file-exists-p file))
11272 (message "non-existent file %s. [R]emove from list or [A]bort?"
11273 (abbreviate-file-name file))
11274 (let ((r (downcase (read-char-exclusive))))
11275 (cond
11276 ((equal r ?r)
11277 (org-remove-file file)
11278 (throw 'nextfile t))
11279 (t (error "Abort"))))))
11281 (defun org-get-agenda-file-buffer (file)
11282 "Get a buffer visiting FILE. If the buffer needs to be created, add
11283 it to the list of buffers which might be released later."
11284 (let ((buf (org-find-base-buffer-visiting file)))
11285 (if buf
11286 buf ; just return it
11287 ;; Make a new buffer and remember it
11288 (setq buf (find-file-noselect file))
11289 (if buf (push buf org-agenda-new-buffers))
11290 buf)))
11292 (defun org-release-buffers (blist)
11293 "Release all buffers in list, asking the user for confirmation when needed.
11294 When a buffer is unmodified, it is just killed. When modified, it is saved
11295 \(if the user agrees) and then killed."
11296 (let (buf file)
11297 (while (setq buf (pop blist))
11298 (setq file (buffer-file-name buf))
11299 (when (and (buffer-modified-p buf)
11300 file
11301 (y-or-n-p (format "Save file %s? " file)))
11302 (with-current-buffer buf (save-buffer)))
11303 (kill-buffer buf))))
11305 (defun org-prepare-agenda-buffers (files)
11306 "Create buffers for all agenda files, protect archived trees and comments."
11307 (interactive)
11308 (let ((pa '(:org-archived t))
11309 (pc '(:org-comment t))
11310 (pall '(:org-archived t :org-comment t))
11311 (inhibit-read-only t)
11312 (rea (concat ":" org-archive-tag ":"))
11313 bmp file re)
11314 (save-excursion
11315 (save-restriction
11316 (while (setq file (pop files))
11317 (if (bufferp file)
11318 (set-buffer file)
11319 (org-check-agenda-file file)
11320 (set-buffer (org-get-agenda-file-buffer file)))
11321 (widen)
11322 (setq bmp (buffer-modified-p))
11323 (org-refresh-category-properties)
11324 (setq org-todo-keywords-for-agenda
11325 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11326 (setq org-done-keywords-for-agenda
11327 (append org-done-keywords-for-agenda org-done-keywords))
11328 (save-excursion
11329 (remove-text-properties (point-min) (point-max) pall)
11330 (when org-agenda-skip-archived-trees
11331 (goto-char (point-min))
11332 (while (re-search-forward rea nil t)
11333 (if (org-on-heading-p t)
11334 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11335 (goto-char (point-min))
11336 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11337 (while (re-search-forward re nil t)
11338 (add-text-properties
11339 (match-beginning 0) (org-end-of-subtree t) pc)))
11340 (set-buffer-modified-p bmp))))))
11342 ;;;; Embedded LaTeX
11344 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11345 "Keymap for the minor `org-cdlatex-mode'.")
11347 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11348 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11349 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11350 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11351 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11353 (defvar org-cdlatex-texmathp-advice-is-done nil
11354 "Flag remembering if we have applied the advice to texmathp already.")
11356 (define-minor-mode org-cdlatex-mode
11357 "Toggle the minor `org-cdlatex-mode'.
11358 This mode supports entering LaTeX environment and math in LaTeX fragments
11359 in Org-mode.
11360 \\{org-cdlatex-mode-map}"
11361 nil " OCDL" nil
11362 (when org-cdlatex-mode (require 'cdlatex))
11363 (unless org-cdlatex-texmathp-advice-is-done
11364 (setq org-cdlatex-texmathp-advice-is-done t)
11365 (defadvice texmathp (around org-math-always-on activate)
11366 "Always return t in org-mode buffers.
11367 This is because we want to insert math symbols without dollars even outside
11368 the LaTeX math segments. If Orgmode thinks that point is actually inside
11369 en embedded LaTeX fragement, let texmathp do its job.
11370 \\[org-cdlatex-mode-map]"
11371 (interactive)
11372 (let (p)
11373 (cond
11374 ((not (org-mode-p)) ad-do-it)
11375 ((eq this-command 'cdlatex-math-symbol)
11376 (setq ad-return-value t
11377 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11379 (let ((p (org-inside-LaTeX-fragment-p)))
11380 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11381 (setq ad-return-value t
11382 texmathp-why '("Org-mode embedded math" . 0))
11383 (if p ad-do-it)))))))))
11385 (defun turn-on-org-cdlatex ()
11386 "Unconditionally turn on `org-cdlatex-mode'."
11387 (org-cdlatex-mode 1))
11389 (defun org-inside-LaTeX-fragment-p ()
11390 "Test if point is inside a LaTeX fragment.
11391 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11392 sequence appearing also before point.
11393 Even though the matchers for math are configurable, this function assumes
11394 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11395 delimiters are skipped when they have been removed by customization.
11396 The return value is nil, or a cons cell with the delimiter and
11397 and the position of this delimiter.
11399 This function does a reasonably good job, but can locally be fooled by
11400 for example currency specifications. For example it will assume being in
11401 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11402 fragments that are properly closed, but during editing, we have to live
11403 with the uncertainty caused by missing closing delimiters. This function
11404 looks only before point, not after."
11405 (catch 'exit
11406 (let ((pos (point))
11407 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11408 (lim (progn
11409 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11410 (point)))
11411 dd-on str (start 0) m re)
11412 (goto-char pos)
11413 (when dodollar
11414 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11415 re (nth 1 (assoc "$" org-latex-regexps)))
11416 (while (string-match re str start)
11417 (cond
11418 ((= (match-end 0) (length str))
11419 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11420 ((= (match-end 0) (- (length str) 5))
11421 (throw 'exit nil))
11422 (t (setq start (match-end 0))))))
11423 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11424 (goto-char pos)
11425 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11426 (and (match-beginning 2) (throw 'exit nil))
11427 ;; count $$
11428 (while (re-search-backward "\\$\\$" lim t)
11429 (setq dd-on (not dd-on)))
11430 (goto-char pos)
11431 (if dd-on (cons "$$" m))))))
11434 (defun org-try-cdlatex-tab ()
11435 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11436 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11437 - inside a LaTeX fragment, or
11438 - after the first word in a line, where an abbreviation expansion could
11439 insert a LaTeX environment."
11440 (when org-cdlatex-mode
11441 (cond
11442 ((save-excursion
11443 (skip-chars-backward "a-zA-Z0-9*")
11444 (skip-chars-backward " \t")
11445 (bolp))
11446 (cdlatex-tab) t)
11447 ((org-inside-LaTeX-fragment-p)
11448 (cdlatex-tab) t)
11449 (t nil))))
11451 (defun org-cdlatex-underscore-caret (&optional arg)
11452 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11453 Revert to the normal definition outside of these fragments."
11454 (interactive "P")
11455 (if (org-inside-LaTeX-fragment-p)
11456 (call-interactively 'cdlatex-sub-superscript)
11457 (let (org-cdlatex-mode)
11458 (call-interactively (key-binding (vector last-input-event))))))
11460 (defun org-cdlatex-math-modify (&optional arg)
11461 "Execute `cdlatex-math-modify' in LaTeX fragments.
11462 Revert to the normal definition outside of these fragments."
11463 (interactive "P")
11464 (if (org-inside-LaTeX-fragment-p)
11465 (call-interactively 'cdlatex-math-modify)
11466 (let (org-cdlatex-mode)
11467 (call-interactively (key-binding (vector last-input-event))))))
11469 (defvar org-latex-fragment-image-overlays nil
11470 "List of overlays carrying the images of latex fragments.")
11471 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11473 (defun org-remove-latex-fragment-image-overlays ()
11474 "Remove all overlays with LaTeX fragment images in current buffer."
11475 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11476 (setq org-latex-fragment-image-overlays nil))
11478 (defun org-preview-latex-fragment (&optional subtree)
11479 "Preview the LaTeX fragment at point, or all locally or globally.
11480 If the cursor is in a LaTeX fragment, create the image and overlay
11481 it over the source code. If there is no fragment at point, display
11482 all fragments in the current text, from one headline to the next. With
11483 prefix SUBTREE, display all fragments in the current subtree. With a
11484 double prefix `C-u C-u', or when the cursor is before the first headline,
11485 display all fragments in the buffer.
11486 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11487 (interactive "P")
11488 (org-remove-latex-fragment-image-overlays)
11489 (save-excursion
11490 (save-restriction
11491 (let (beg end at msg)
11492 (cond
11493 ((or (equal subtree '(16))
11494 (not (save-excursion
11495 (re-search-backward (concat "^" outline-regexp) nil t))))
11496 (setq beg (point-min) end (point-max)
11497 msg "Creating images for buffer...%s"))
11498 ((equal subtree '(4))
11499 (org-back-to-heading)
11500 (setq beg (point) end (org-end-of-subtree t)
11501 msg "Creating images for subtree...%s"))
11503 (if (setq at (org-inside-LaTeX-fragment-p))
11504 (goto-char (max (point-min) (- (cdr at) 2)))
11505 (org-back-to-heading))
11506 (setq beg (point) end (progn (outline-next-heading) (point))
11507 msg (if at "Creating image...%s"
11508 "Creating images for entry...%s"))))
11509 (message msg "")
11510 (narrow-to-region beg end)
11511 (goto-char beg)
11512 (org-format-latex
11513 (concat "ltxpng/" (file-name-sans-extension
11514 (file-name-nondirectory
11515 buffer-file-name)))
11516 default-directory 'overlays msg at 'forbuffer)
11517 (message msg "done. Use `C-c C-c' to remove images.")))))
11519 (defvar org-latex-regexps
11520 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11521 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11522 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11523 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11524 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11525 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11526 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11527 "Regular expressions for matching embedded LaTeX.")
11529 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11530 "Replace LaTeX fragments with links to an image, and produce images."
11531 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11532 (let* ((prefixnodir (file-name-nondirectory prefix))
11533 (absprefix (expand-file-name prefix dir))
11534 (todir (file-name-directory absprefix))
11535 (opt org-format-latex-options)
11536 (matchers (plist-get opt :matchers))
11537 (re-list org-latex-regexps)
11538 (cnt 0) txt link beg end re e checkdir
11539 m n block linkfile movefile ov)
11540 ;; Check if there are old images files with this prefix, and remove them
11541 (when (file-directory-p todir)
11542 (mapc 'delete-file
11543 (directory-files
11544 todir 'full
11545 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11546 ;; Check the different regular expressions
11547 (while (setq e (pop re-list))
11548 (setq m (car e) re (nth 1 e) n (nth 2 e)
11549 block (if (nth 3 e) "\n\n" ""))
11550 (when (member m matchers)
11551 (goto-char (point-min))
11552 (while (re-search-forward re nil t)
11553 (when (or (not at) (equal (cdr at) (match-beginning n)))
11554 (setq txt (match-string n)
11555 beg (match-beginning n) end (match-end n)
11556 cnt (1+ cnt)
11557 linkfile (format "%s_%04d.png" prefix cnt)
11558 movefile (format "%s_%04d.png" absprefix cnt)
11559 link (concat block "[[file:" linkfile "]]" block))
11560 (if msg (message msg cnt))
11561 (goto-char beg)
11562 (unless checkdir ; make sure the directory exists
11563 (setq checkdir t)
11564 (or (file-directory-p todir) (make-directory todir)))
11565 (org-create-formula-image
11566 txt movefile opt forbuffer)
11567 (if overlays
11568 (progn
11569 (setq ov (org-make-overlay beg end))
11570 (if (featurep 'xemacs)
11571 (progn
11572 (org-overlay-put ov 'invisible t)
11573 (org-overlay-put
11574 ov 'end-glyph
11575 (make-glyph (vector 'png :file movefile))))
11576 (org-overlay-put
11577 ov 'display
11578 (list 'image :type 'png :file movefile :ascent 'center)))
11579 (push ov org-latex-fragment-image-overlays)
11580 (goto-char end))
11581 (delete-region beg end)
11582 (insert link))))))))
11584 ;; This function borrows from Ganesh Swami's latex2png.el
11585 (defun org-create-formula-image (string tofile options buffer)
11586 (let* ((tmpdir (if (featurep 'xemacs)
11587 (temp-directory)
11588 temporary-file-directory))
11589 (texfilebase (make-temp-name
11590 (expand-file-name "orgtex" tmpdir)))
11591 (texfile (concat texfilebase ".tex"))
11592 (dvifile (concat texfilebase ".dvi"))
11593 (pngfile (concat texfilebase ".png"))
11594 (fnh (if (featurep 'xemacs)
11595 (font-height (get-face-font 'default))
11596 (face-attribute 'default :height nil)))
11597 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11598 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11599 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11600 "Black"))
11601 (bg (or (plist-get options (if buffer :background :html-background))
11602 "Transparent")))
11603 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11604 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11605 (with-temp-file texfile
11606 (insert org-format-latex-header
11607 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11608 (let ((dir default-directory))
11609 (condition-case nil
11610 (progn
11611 (cd tmpdir)
11612 (call-process "latex" nil nil nil texfile))
11613 (error nil))
11614 (cd dir))
11615 (if (not (file-exists-p dvifile))
11616 (progn (message "Failed to create dvi file from %s" texfile) nil)
11617 (call-process "dvipng" nil nil nil
11618 "-E" "-fg" fg "-bg" bg
11619 "-D" dpi
11620 ;;"-x" scale "-y" scale
11621 "-T" "tight"
11622 "-o" pngfile
11623 dvifile)
11624 (if (not (file-exists-p pngfile))
11625 (progn (message "Failed to create png file from %s" texfile) nil)
11626 ;; Use the requested file name and clean up
11627 (copy-file pngfile tofile 'replace)
11628 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11629 (delete-file (concat texfilebase e)))
11630 pngfile))))
11632 (defun org-dvipng-color (attr)
11633 "Return an rgb color specification for dvipng."
11634 (apply 'format "rgb %s %s %s"
11635 (mapcar 'org-normalize-color
11636 (color-values (face-attribute 'default attr nil)))))
11638 (defun org-normalize-color (value)
11639 "Return string to be used as color value for an RGB component."
11640 (format "%g" (/ value 65535.0)))
11643 ;;;; Key bindings
11645 ;; Make `C-c C-x' a prefix key
11646 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11648 ;; TAB key with modifiers
11649 (org-defkey org-mode-map "\C-i" 'org-cycle)
11650 (org-defkey org-mode-map [(tab)] 'org-cycle)
11651 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11652 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11653 (org-defkey org-mode-map "\M-\t" 'org-complete)
11654 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11655 ;; The following line is necessary under Suse GNU/Linux
11656 (unless (featurep 'xemacs)
11657 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11658 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11659 (define-key org-mode-map [backtab] 'org-shifttab)
11661 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11662 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11663 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11665 ;; Cursor keys with modifiers
11666 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11667 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11668 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11669 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11671 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11672 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11673 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11674 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11676 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11677 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11678 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11679 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11681 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11682 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11684 ;;; Extra keys for tty access.
11685 ;; We only set them when really needed because otherwise the
11686 ;; menus don't show the simple keys
11688 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11689 (not window-system))
11690 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11691 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11692 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11693 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11694 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11695 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11696 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11697 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11698 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11699 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11700 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11701 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11702 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11703 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11704 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11705 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11706 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11707 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11708 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11709 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11710 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11711 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11713 ;; All the other keys
11715 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
11716 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
11717 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
11718 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
11719 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
11720 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
11721 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
11722 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
11723 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
11724 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
11725 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
11726 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
11727 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
11728 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
11729 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11730 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
11731 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
11732 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11733 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
11734 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
11735 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
11736 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
11737 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
11738 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
11739 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
11740 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
11741 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
11742 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
11743 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11744 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11745 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11746 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11747 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
11748 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
11749 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11750 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
11751 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
11752 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
11753 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
11754 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
11755 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
11756 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
11757 (org-defkey org-mode-map "\C-c^" 'org-sort)
11758 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11759 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
11760 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
11761 (org-defkey org-mode-map "\C-m" 'org-return)
11762 (org-defkey org-mode-map "\C-j" 'org-return-indent)
11763 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
11764 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
11765 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
11766 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
11767 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
11768 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
11769 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
11770 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11771 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
11772 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11773 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
11774 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
11775 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
11776 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11777 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
11779 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
11780 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11781 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11782 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11784 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
11785 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
11786 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
11787 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
11788 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
11789 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
11790 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
11791 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
11792 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
11793 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
11794 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
11795 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
11797 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
11799 (when (featurep 'xemacs)
11800 (org-defkey org-mode-map 'button3 'popup-mode-menu))
11802 (defvar org-table-auto-blank-field) ; defined in org-table.el
11803 (defun org-self-insert-command (N)
11804 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11805 If the cursor is in a table looking at whitespace, the whitespace is
11806 overwritten, and the table is not marked as requiring realignment."
11807 (interactive "p")
11808 (if (and (org-table-p)
11809 (progn
11810 ;; check if we blank the field, and if that triggers align
11811 (and (featurep 'org-table) org-table-auto-blank-field
11812 (member last-command
11813 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11814 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
11815 ;; got extra space, this field does not determine column width
11816 (let (org-table-may-need-update) (org-table-blank-field))
11817 ;; no extra space, this field may determine column width
11818 (org-table-blank-field)))
11820 (eq N 1)
11821 (looking-at "[^|\n]* |"))
11822 (let (org-table-may-need-update)
11823 (goto-char (1- (match-end 0)))
11824 (delete-backward-char 1)
11825 (goto-char (match-beginning 0))
11826 (self-insert-command N))
11827 (setq org-table-may-need-update t)
11828 (self-insert-command N)
11829 (org-fix-tags-on-the-fly)))
11831 (defun org-fix-tags-on-the-fly ()
11832 (when (and (equal (char-after (point-at-bol)) ?*)
11833 (org-on-heading-p))
11834 (org-align-tags-here org-tags-column)))
11836 (defun org-delete-backward-char (N)
11837 "Like `delete-backward-char', insert whitespace at field end in tables.
11838 When deleting backwards, in tables this function will insert whitespace in
11839 front of the next \"|\" separator, to keep the table aligned. The table will
11840 still be marked for re-alignment if the field did fill the entire column,
11841 because, in this case the deletion might narrow the column."
11842 (interactive "p")
11843 (if (and (org-table-p)
11844 (eq N 1)
11845 (string-match "|" (buffer-substring (point-at-bol) (point)))
11846 (looking-at ".*?|"))
11847 (let ((pos (point))
11848 (noalign (looking-at "[^|\n\r]* |"))
11849 (c org-table-may-need-update))
11850 (backward-delete-char N)
11851 (skip-chars-forward "^|")
11852 (insert " ")
11853 (goto-char (1- pos))
11854 ;; noalign: if there were two spaces at the end, this field
11855 ;; does not determine the width of the column.
11856 (if noalign (setq org-table-may-need-update c)))
11857 (backward-delete-char N)
11858 (org-fix-tags-on-the-fly)))
11860 (defun org-delete-char (N)
11861 "Like `delete-char', but insert whitespace at field end in tables.
11862 When deleting characters, in tables this function will insert whitespace in
11863 front of the next \"|\" separator, to keep the table aligned. The table will
11864 still be marked for re-alignment if the field did fill the entire column,
11865 because, in this case the deletion might narrow the column."
11866 (interactive "p")
11867 (if (and (org-table-p)
11868 (not (bolp))
11869 (not (= (char-after) ?|))
11870 (eq N 1))
11871 (if (looking-at ".*?|")
11872 (let ((pos (point))
11873 (noalign (looking-at "[^|\n\r]* |"))
11874 (c org-table-may-need-update))
11875 (replace-match (concat
11876 (substring (match-string 0) 1 -1)
11877 " |"))
11878 (goto-char pos)
11879 ;; noalign: if there were two spaces at the end, this field
11880 ;; does not determine the width of the column.
11881 (if noalign (setq org-table-may-need-update c)))
11882 (delete-char N))
11883 (delete-char N)
11884 (org-fix-tags-on-the-fly)))
11886 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
11887 (put 'org-self-insert-command 'delete-selection t)
11888 (put 'orgtbl-self-insert-command 'delete-selection t)
11889 (put 'org-delete-char 'delete-selection 'supersede)
11890 (put 'org-delete-backward-char 'delete-selection 'supersede)
11892 ;; Make `flyspell-mode' delay after some commands
11893 (put 'org-self-insert-command 'flyspell-delayed t)
11894 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
11895 (put 'org-delete-char 'flyspell-delayed t)
11896 (put 'org-delete-backward-char 'flyspell-delayed t)
11898 ;; Make pabbrev-mode expand after org-mode commands
11899 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
11900 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
11902 ;; How to do this: Measure non-white length of current string
11903 ;; If equal to column width, we should realign.
11905 (defun org-remap (map &rest commands)
11906 "In MAP, remap the functions given in COMMANDS.
11907 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11908 (let (new old)
11909 (while commands
11910 (setq old (pop commands) new (pop commands))
11911 (if (fboundp 'command-remapping)
11912 (org-defkey map (vector 'remap old) new)
11913 (substitute-key-definition old new map global-map)))))
11915 (when (eq org-enable-table-editor 'optimized)
11916 ;; If the user wants maximum table support, we need to hijack
11917 ;; some standard editing functions
11918 (org-remap org-mode-map
11919 'self-insert-command 'org-self-insert-command
11920 'delete-char 'org-delete-char
11921 'delete-backward-char 'org-delete-backward-char)
11922 (org-defkey org-mode-map "|" 'org-force-self-insert))
11924 (defun org-shiftcursor-error ()
11925 "Throw an error because Shift-Cursor command was applied in wrong context."
11926 (error "This command is active in special context like tables, headlines or timestamps"))
11928 (defun org-shifttab (&optional arg)
11929 "Global visibility cycling or move to previous table field.
11930 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
11931 on context.
11932 See the individual commands for more information."
11933 (interactive "P")
11934 (cond
11935 ((org-at-table-p) (call-interactively 'org-table-previous-field))
11936 (arg (message "Content view to level: ")
11937 (org-content (prefix-numeric-value arg))
11938 (setq org-cycle-global-status 'overview))
11939 (t (call-interactively 'org-global-cycle))))
11941 (defun org-shiftmetaleft ()
11942 "Promote subtree or delete table column.
11943 Calls `org-promote-subtree', `org-outdent-item',
11944 or `org-table-delete-column', depending on context.
11945 See the individual commands for more information."
11946 (interactive)
11947 (cond
11948 ((org-at-table-p) (call-interactively 'org-table-delete-column))
11949 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
11950 ((org-at-item-p) (call-interactively 'org-outdent-item))
11951 (t (org-shiftcursor-error))))
11953 (defun org-shiftmetaright ()
11954 "Demote subtree or insert table column.
11955 Calls `org-demote-subtree', `org-indent-item',
11956 or `org-table-insert-column', depending on context.
11957 See the individual commands for more information."
11958 (interactive)
11959 (cond
11960 ((org-at-table-p) (call-interactively 'org-table-insert-column))
11961 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
11962 ((org-at-item-p) (call-interactively 'org-indent-item))
11963 (t (org-shiftcursor-error))))
11965 (defun org-shiftmetaup (&optional arg)
11966 "Move subtree up or kill table row.
11967 Calls `org-move-subtree-up' or `org-table-kill-row' or
11968 `org-move-item-up' depending on context. See the individual commands
11969 for more information."
11970 (interactive "P")
11971 (cond
11972 ((org-at-table-p) (call-interactively 'org-table-kill-row))
11973 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
11974 ((org-at-item-p) (call-interactively 'org-move-item-up))
11975 (t (org-shiftcursor-error))))
11976 (defun org-shiftmetadown (&optional arg)
11977 "Move subtree down or insert table row.
11978 Calls `org-move-subtree-down' or `org-table-insert-row' or
11979 `org-move-item-down', depending on context. See the individual
11980 commands for more information."
11981 (interactive "P")
11982 (cond
11983 ((org-at-table-p) (call-interactively 'org-table-insert-row))
11984 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
11985 ((org-at-item-p) (call-interactively 'org-move-item-down))
11986 (t (org-shiftcursor-error))))
11988 (defun org-metaleft (&optional arg)
11989 "Promote heading or move table column to left.
11990 Calls `org-do-promote' or `org-table-move-column', depending on context.
11991 With no specific context, calls the Emacs default `backward-word'.
11992 See the individual commands for more information."
11993 (interactive "P")
11994 (cond
11995 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
11996 ((or (org-on-heading-p) (org-region-active-p))
11997 (call-interactively 'org-do-promote))
11998 ((org-at-item-p) (call-interactively 'org-outdent-item))
11999 (t (call-interactively 'backward-word))))
12001 (defun org-metaright (&optional arg)
12002 "Demote subtree or move table column to right.
12003 Calls `org-do-demote' or `org-table-move-column', depending on context.
12004 With no specific context, calls the Emacs default `forward-word'.
12005 See the individual commands for more information."
12006 (interactive "P")
12007 (cond
12008 ((org-at-table-p) (call-interactively 'org-table-move-column))
12009 ((or (org-on-heading-p) (org-region-active-p))
12010 (call-interactively 'org-do-demote))
12011 ((org-at-item-p) (call-interactively 'org-indent-item))
12012 (t (call-interactively 'forward-word))))
12014 (defun org-metaup (&optional arg)
12015 "Move subtree up or move table row up.
12016 Calls `org-move-subtree-up' or `org-table-move-row' or
12017 `org-move-item-up', depending on context. See the individual commands
12018 for more information."
12019 (interactive "P")
12020 (cond
12021 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12022 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12023 ((org-at-item-p) (call-interactively 'org-move-item-up))
12024 (t (transpose-lines 1) (beginning-of-line -1))))
12026 (defun org-metadown (&optional arg)
12027 "Move subtree down or move table row down.
12028 Calls `org-move-subtree-down' or `org-table-move-row' or
12029 `org-move-item-down', depending on context. See the individual
12030 commands for more information."
12031 (interactive "P")
12032 (cond
12033 ((org-at-table-p) (call-interactively 'org-table-move-row))
12034 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12035 ((org-at-item-p) (call-interactively 'org-move-item-down))
12036 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12038 (defun org-shiftup (&optional arg)
12039 "Increase item in timestamp or increase priority of current headline.
12040 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12041 depending on context. See the individual commands for more information."
12042 (interactive "P")
12043 (cond
12044 ((org-at-timestamp-p t)
12045 (call-interactively (if org-edit-timestamp-down-means-later
12046 'org-timestamp-down 'org-timestamp-up)))
12047 ((org-on-heading-p) (call-interactively 'org-priority-up))
12048 ((org-at-item-p) (call-interactively 'org-previous-item))
12049 ((org-clocktable-try-shift 'up arg))
12050 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12052 (defun org-shiftdown (&optional arg)
12053 "Decrease item in timestamp or decrease priority of current headline.
12054 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12055 depending on context. See the individual commands for more information."
12056 (interactive "P")
12057 (cond
12058 ((org-at-timestamp-p t)
12059 (call-interactively (if org-edit-timestamp-down-means-later
12060 'org-timestamp-up 'org-timestamp-down)))
12061 ((org-on-heading-p) (call-interactively 'org-priority-down))
12062 ((org-clocktable-try-shift 'down arg))
12063 (t (call-interactively 'org-next-item))))
12065 (defun org-shiftright (&optional arg)
12066 "Next TODO keyword or timestamp one day later, depending on context."
12067 (interactive "P")
12068 (cond
12069 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12070 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12071 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12072 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12073 ((org-clocktable-try-shift 'right arg))
12074 (t (org-shiftcursor-error))))
12076 (defun org-shiftleft (&optional arg)
12077 "Previous TODO keyword or timestamp one day earlier, depending on context."
12078 (interactive "P")
12079 (cond
12080 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12081 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12082 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12083 ((org-at-property-p)
12084 (call-interactively 'org-property-previous-allowed-value))
12085 ((org-clocktable-try-shift 'left arg))
12086 (t (org-shiftcursor-error))))
12088 (defun org-shiftcontrolright ()
12089 "Switch to next TODO set."
12090 (interactive)
12091 (cond
12092 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12093 (t (org-shiftcursor-error))))
12095 (defun org-shiftcontrolleft ()
12096 "Switch to previous TODO set."
12097 (interactive)
12098 (cond
12099 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12100 (t (org-shiftcursor-error))))
12102 (defun org-ctrl-c-ret ()
12103 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12104 (interactive)
12105 (cond
12106 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12107 (t (call-interactively 'org-insert-heading))))
12109 (defun org-copy-special ()
12110 "Copy region in table or copy current subtree.
12111 Calls `org-table-copy' or `org-copy-subtree', depending on context.
12112 See the individual commands for more information."
12113 (interactive)
12114 (call-interactively
12115 (if (org-at-table-p) 'org-table-copy-region 'org-copy-subtree)))
12117 (defun org-cut-special ()
12118 "Cut region in table or cut current subtree.
12119 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12120 See the individual commands for more information."
12121 (interactive)
12122 (call-interactively
12123 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12125 (defun org-paste-special (arg)
12126 "Paste rectangular region into table, or past subtree relative to level.
12127 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12128 See the individual commands for more information."
12129 (interactive "P")
12130 (if (org-at-table-p)
12131 (org-table-paste-rectangle)
12132 (org-paste-subtree arg)))
12134 (defun org-ctrl-c-ctrl-c (&optional arg)
12135 "Set tags in headline, or update according to changed information at point.
12137 This command does many different things, depending on context:
12139 - If the cursor is in a headline, prompt for tags and insert them
12140 into the current line, aligned to `org-tags-column'. When called
12141 with prefix arg, realign all tags in the current buffer.
12143 - If the cursor is in one of the special #+KEYWORD lines, this
12144 triggers scanning the buffer for these lines and updating the
12145 information.
12147 - If the cursor is inside a table, realign the table. This command
12148 works even if the automatic table editor has been turned off.
12150 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12151 the entire table.
12153 - If the cursor is a the beginning of a dynamic block, update it.
12155 - If the cursor is inside a table created by the table.el package,
12156 activate that table.
12158 - If the current buffer is a remember buffer, close note and file it.
12159 with a prefix argument, file it without further interaction to the default
12160 location.
12162 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12163 links in this buffer.
12165 - If the cursor is on a numbered item in a plain list, renumber the
12166 ordered list.
12168 - If the cursor is on a checkbox, toggle it."
12169 (interactive "P")
12170 (let ((org-enable-table-editor t))
12171 (cond
12172 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12173 org-occur-highlights
12174 org-latex-fragment-image-overlays)
12175 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12176 (org-remove-occur-highlights)
12177 (org-remove-latex-fragment-image-overlays)
12178 (message "Temporary highlights/overlays removed from current buffer"))
12179 ((and (local-variable-p 'org-finish-function (current-buffer))
12180 (fboundp org-finish-function))
12181 (funcall org-finish-function))
12182 ((org-at-property-p)
12183 (call-interactively 'org-property-action))
12184 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12185 ((org-on-heading-p) (call-interactively 'org-set-tags))
12186 ((org-at-table.el-p)
12187 (require 'table)
12188 (beginning-of-line 1)
12189 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12190 (call-interactively 'table-recognize-table))
12191 ((org-at-table-p)
12192 (org-table-maybe-eval-formula)
12193 (if arg
12194 (call-interactively 'org-table-recalculate)
12195 (org-table-maybe-recalculate-line))
12196 (call-interactively 'org-table-align))
12197 ((org-at-item-checkbox-p)
12198 (call-interactively 'org-toggle-checkbox))
12199 ((org-at-item-p)
12200 (call-interactively 'org-maybe-renumber-ordered-list))
12201 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12202 ;; Dynamic block
12203 (beginning-of-line 1)
12204 (org-update-dblock))
12205 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12206 (cond
12207 ((equal (match-string 1) "TBLFM")
12208 ;; Recalculate the table before this line
12209 (save-excursion
12210 (beginning-of-line 1)
12211 (skip-chars-backward " \r\n\t")
12212 (if (org-at-table-p)
12213 (org-call-with-arg 'org-table-recalculate t))))
12215 (call-interactively 'org-mode-restart))))
12216 (t (error "C-c C-c can do nothing useful at this location.")))))
12218 (defun org-mode-restart ()
12219 "Restart Org-mode, to scan again for special lines.
12220 Also updates the keyword regular expressions."
12221 (interactive)
12222 (let ((org-inhibit-startup t)) (org-mode))
12223 (message "Org-mode restarted to refresh keyword and special line setup"))
12225 (defun org-kill-note-or-show-branches ()
12226 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12227 (interactive)
12228 (if (not org-finish-function)
12229 (call-interactively 'show-branches)
12230 (let ((org-note-abort t))
12231 (funcall org-finish-function))))
12233 (defun org-return (&optional indent)
12234 "Goto next table row or insert a newline.
12235 Calls `org-table-next-row' or `newline', depending on context.
12236 See the individual commands for more information."
12237 (interactive)
12238 (cond
12239 ((bobp) (if indent (newline-and-indent) (newline)))
12240 ((and (org-at-heading-p)
12241 (looking-at
12242 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12243 (org-show-entry)
12244 (end-of-line 1)
12245 (newline))
12246 ((org-at-table-p)
12247 (org-table-justify-field-maybe)
12248 (call-interactively 'org-table-next-row))
12249 (t (if indent (newline-and-indent) (newline)))))
12251 (defun org-return-indent ()
12252 "Goto next table row or insert a newline and indent.
12253 Calls `org-table-next-row' or `newline-and-indent', depending on
12254 context. See the individual commands for more information."
12255 (interactive)
12256 (org-return t))
12258 (defun org-ctrl-c-star ()
12259 "Compute table, or change heading status of lines.
12260 Calls `org-table-recalculate' or `org-toggle-region-headlines',
12261 depending on context. This will also turn a plain list item or a normal
12262 line into a subheading."
12263 (interactive)
12264 (cond
12265 ((org-at-table-p)
12266 (call-interactively 'org-table-recalculate))
12267 ((org-region-active-p)
12268 ;; Convert all lines in region to list items
12269 (call-interactively 'org-toggle-region-headings))
12270 ((org-on-heading-p)
12271 (org-toggle-region-headings (point-at-bol)
12272 (min (1+ (point-at-eol)) (point-max))))
12273 ((org-at-item-p)
12274 ;; Convert to heading
12275 (let ((level (save-match-data
12276 (save-excursion
12277 (condition-case nil
12278 (progn
12279 (org-back-to-heading t)
12280 (funcall outline-level))
12281 (error 0))))))
12282 (replace-match
12283 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12284 (t (org-toggle-region-headings (point-at-bol)
12285 (min (1+ (point-at-eol)) (point-max))))))
12287 (defun org-ctrl-c-minus ()
12288 "Insert separator line in table or modify bullet status of line.
12289 Also turns a plain line or a region of lines into list items.
12290 Calls `org-table-insert-hline', `org-toggle-region-items', or
12291 `org-cycle-list-bullet', depending on context."
12292 (interactive)
12293 (cond
12294 ((org-at-table-p)
12295 (call-interactively 'org-table-insert-hline))
12296 ((org-on-heading-p)
12297 ;; Convert to item
12298 (save-excursion
12299 (beginning-of-line 1)
12300 (if (looking-at "\\*+ ")
12301 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12302 ((org-region-active-p)
12303 ;; Convert all lines in region to list items
12304 (call-interactively 'org-toggle-region-items))
12305 ((org-in-item-p)
12306 (call-interactively 'org-cycle-list-bullet))
12307 (t (org-toggle-region-items (point-at-bol)
12308 (min (1+ (point-at-eol)) (point-max))))))
12310 (defun org-toggle-region-items (beg end)
12311 "Convert all lines in region to list items.
12312 If the first line is already an item, convert all list items in the region
12313 to normal lines."
12314 (interactive "r")
12315 (let (l2 l)
12316 (save-excursion
12317 (goto-char end)
12318 (setq l2 (org-current-line))
12319 (goto-char beg)
12320 (beginning-of-line 1)
12321 (setq l (1- (org-current-line)))
12322 (if (org-at-item-p)
12323 ;; We already have items, de-itemize
12324 (while (< (setq l (1+ l)) l2)
12325 (when (org-at-item-p)
12326 (goto-char (match-beginning 2))
12327 (delete-region (match-beginning 2) (match-end 2))
12328 (and (looking-at "[ \t]+") (replace-match "")))
12329 (beginning-of-line 2))
12330 (while (< (setq l (1+ l)) l2)
12331 (unless (org-at-item-p)
12332 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12333 (replace-match "\\1- \\2")))
12334 (beginning-of-line 2))))))
12336 (defun org-toggle-region-headings (beg end)
12337 "Convert all lines in region to list items.
12338 If the first line is already an item, convert all list items in the region
12339 to normal lines."
12340 (interactive "r")
12341 (let (l2 l)
12342 (save-excursion
12343 (goto-char end)
12344 (setq l2 (org-current-line))
12345 (goto-char beg)
12346 (beginning-of-line 1)
12347 (setq l (1- (org-current-line)))
12348 (if (org-on-heading-p)
12349 ;; We already have headlines, de-star them
12350 (while (< (setq l (1+ l)) l2)
12351 (when (org-on-heading-p t)
12352 (and (looking-at outline-regexp) (replace-match "")))
12353 (beginning-of-line 2))
12354 (let* ((stars (save-excursion
12355 (re-search-backward org-complex-heading-regexp nil t)
12356 (or (match-string 1) "*")))
12357 (add-stars (if org-odd-levels-only "**" "*"))
12358 (rpl (concat stars add-stars " \\2")))
12359 (while (< (setq l (1+ l)) l2)
12360 (unless (org-on-heading-p)
12361 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12362 (replace-match rpl)))
12363 (beginning-of-line 2)))))))
12365 (defun org-meta-return (&optional arg)
12366 "Insert a new heading or wrap a region in a table.
12367 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12368 See the individual commands for more information."
12369 (interactive "P")
12370 (cond
12371 ((org-at-table-p)
12372 (call-interactively 'org-table-wrap-region))
12373 (t (call-interactively 'org-insert-heading))))
12375 ;;; Menu entries
12377 ;; Define the Org-mode menus
12378 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12379 '("Tbl"
12380 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12381 ["Next Field" org-cycle (org-at-table-p)]
12382 ["Previous Field" org-shifttab (org-at-table-p)]
12383 ["Next Row" org-return (org-at-table-p)]
12384 "--"
12385 ["Blank Field" org-table-blank-field (org-at-table-p)]
12386 ["Edit Field" org-table-edit-field (org-at-table-p)]
12387 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12388 "--"
12389 ("Column"
12390 ["Move Column Left" org-metaleft (org-at-table-p)]
12391 ["Move Column Right" org-metaright (org-at-table-p)]
12392 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12393 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12394 ("Row"
12395 ["Move Row Up" org-metaup (org-at-table-p)]
12396 ["Move Row Down" org-metadown (org-at-table-p)]
12397 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12398 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12399 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12400 "--"
12401 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12402 ("Rectangle"
12403 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12404 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12405 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12406 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12407 "--"
12408 ("Calculate"
12409 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12410 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12411 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12412 "--"
12413 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12414 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12415 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12416 "--"
12417 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12418 "--"
12419 ["Sum Column/Rectangle" org-table-sum
12420 (or (org-at-table-p) (org-region-active-p))]
12421 ["Which Column?" org-table-current-column (org-at-table-p)])
12422 ["Debug Formulas"
12423 org-table-toggle-formula-debugger
12424 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12425 ["Show Col/Row Numbers"
12426 org-table-toggle-coordinate-overlays
12427 :style toggle
12428 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12429 "--"
12430 ["Create" org-table-create (and (not (org-at-table-p))
12431 org-enable-table-editor)]
12432 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12433 ["Import from File" org-table-import (not (org-at-table-p))]
12434 ["Export to File" org-table-export (org-at-table-p)]
12435 "--"
12436 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12438 (easy-menu-define org-org-menu org-mode-map "Org menu"
12439 '("Org"
12440 ("Show/Hide"
12441 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12442 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12443 ["Sparse Tree..." org-sparse-tree t]
12444 ["Reveal Context" org-reveal t]
12445 ["Show All" show-all t]
12446 "--"
12447 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12448 "--"
12449 ["New Heading" org-insert-heading t]
12450 ("Navigate Headings"
12451 ["Up" outline-up-heading t]
12452 ["Next" outline-next-visible-heading t]
12453 ["Previous" outline-previous-visible-heading t]
12454 ["Next Same Level" outline-forward-same-level t]
12455 ["Previous Same Level" outline-backward-same-level t]
12456 "--"
12457 ["Jump" org-goto t])
12458 ("Edit Structure"
12459 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12460 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12461 "--"
12462 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12463 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12464 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12465 "--"
12466 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12467 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12468 ["Demote Heading" org-metaright (not (org-at-table-p))]
12469 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12470 "--"
12471 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12472 "--"
12473 ["Convert to odd levels" org-convert-to-odd-levels t]
12474 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12475 ("Editing"
12476 ["Emphasis..." org-emphasize t])
12477 ("Archive"
12478 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12479 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12480 ; :active t :keys "C-u C-c C-x C-a"]
12481 ["Sparse trees open ARCHIVE trees"
12482 (setq org-sparse-tree-open-archived-trees
12483 (not org-sparse-tree-open-archived-trees))
12484 :style toggle :selected org-sparse-tree-open-archived-trees]
12485 ["Cycling opens ARCHIVE trees"
12486 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12487 :style toggle :selected org-cycle-open-archived-trees]
12488 ["Agenda includes ARCHIVE trees"
12489 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
12490 :style toggle :selected (not org-agenda-skip-archived-trees)]
12491 "--"
12492 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12493 ; ["Check and Move Children" (org-archive-subtree '(4))
12494 ; :active t :keys "C-u C-c C-x C-s"]
12496 "--"
12497 ("TODO Lists"
12498 ["TODO/DONE/-" org-todo t]
12499 ("Select keyword"
12500 ["Next keyword" org-shiftright (org-on-heading-p)]
12501 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12502 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12503 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12504 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12505 ["Show TODO Tree" org-show-todo-tree t]
12506 ["Global TODO list" org-todo-list t]
12507 "--"
12508 ["Set Priority" org-priority t]
12509 ["Priority Up" org-shiftup t]
12510 ["Priority Down" org-shiftdown t])
12511 ("TAGS and Properties"
12512 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12513 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12514 "--"
12515 ["Set property" 'org-set-property t]
12516 ["Column view of properties" org-columns t]
12517 ["Insert Column View DBlock" org-insert-columns-dblock t])
12518 ("Dates and Scheduling"
12519 ["Timestamp" org-time-stamp t]
12520 ["Timestamp (inactive)" org-time-stamp-inactive t]
12521 ("Change Date"
12522 ["1 Day Later" org-shiftright t]
12523 ["1 Day Earlier" org-shiftleft t]
12524 ["1 ... Later" org-shiftup t]
12525 ["1 ... Earlier" org-shiftdown t])
12526 ["Compute Time Range" org-evaluate-time-range t]
12527 ["Schedule Item" org-schedule t]
12528 ["Deadline" org-deadline t]
12529 "--"
12530 ["Custom time format" org-toggle-time-stamp-overlays
12531 :style radio :selected org-display-custom-times]
12532 "--"
12533 ["Goto Calendar" org-goto-calendar t]
12534 ["Date from Calendar" org-date-from-calendar t])
12535 ("Logging work"
12536 ["Clock in" org-clock-in t]
12537 ["Clock out" org-clock-out t]
12538 ["Clock cancel" org-clock-cancel t]
12539 ["Goto running clock" org-clock-goto t]
12540 ["Display times" org-clock-display t]
12541 ["Create clock table" org-clock-report t]
12542 "--"
12543 ["Record DONE time"
12544 (progn (setq org-log-done (not org-log-done))
12545 (message "Switching to %s will %s record a timestamp"
12546 (car org-done-keywords)
12547 (if org-log-done "automatically" "not")))
12548 :style toggle :selected org-log-done])
12549 "--"
12550 ["Agenda Command..." org-agenda t]
12551 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12552 ("File List for Agenda")
12553 ("Special views current file"
12554 ["TODO Tree" org-show-todo-tree t]
12555 ["Check Deadlines" org-check-deadlines t]
12556 ["Timeline" org-timeline t]
12557 ["Tags Tree" org-tags-sparse-tree t])
12558 "--"
12559 ("Hyperlinks"
12560 ["Store Link (Global)" org-store-link t]
12561 ["Insert Link" org-insert-link t]
12562 ["Follow Link" org-open-at-point t]
12563 "--"
12564 ["Next link" org-next-link t]
12565 ["Previous link" org-previous-link t]
12566 "--"
12567 ["Descriptive Links"
12568 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12569 :style radio
12570 :selected (member '(org-link) buffer-invisibility-spec)]
12571 ["Literal Links"
12572 (progn
12573 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12574 :style radio
12575 :selected (not (member '(org-link) buffer-invisibility-spec))])
12576 "--"
12577 ["Export/Publish..." org-export t]
12578 ("LaTeX"
12579 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12580 :selected org-cdlatex-mode]
12581 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12582 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12583 ["Modify math symbol" org-cdlatex-math-modify
12584 (org-inside-LaTeX-fragment-p)]
12585 ["Export LaTeX fragments as images"
12586 (if (featurep 'org-exp)
12587 (setq org-export-with-LaTeX-fragments
12588 (not org-export-with-LaTeX-fragments))
12589 (require 'org-exp))
12590 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12591 org-export-with-LaTeX-fragments)])
12592 "--"
12593 ("Documentation"
12594 ["Show Version" org-version t]
12595 ["Info Documentation" org-info t])
12596 ("Customize"
12597 ["Browse Org Group" org-customize t]
12598 "--"
12599 ["Expand This Menu" org-create-customize-menu
12600 (fboundp 'customize-menu-create)])
12601 "--"
12602 ["Refresh setup" org-mode-restart t]
12605 (defun org-info (&optional node)
12606 "Read documentation for Org-mode in the info system.
12607 With optional NODE, go directly to that node."
12608 (interactive)
12609 (info (format "(org)%s" (or node ""))))
12611 (defun org-install-agenda-files-menu ()
12612 (let ((bl (buffer-list)))
12613 (save-excursion
12614 (while bl
12615 (set-buffer (pop bl))
12616 (if (org-mode-p) (setq bl nil)))
12617 (when (org-mode-p)
12618 (easy-menu-change
12619 '("Org") "File List for Agenda"
12620 (append
12621 (list
12622 ["Edit File List" (org-edit-agenda-file-list) t]
12623 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12624 ["Remove Current File from List" org-remove-file t]
12625 ["Cycle through agenda files" org-cycle-agenda-files t]
12626 ["Occur in all agenda files" org-occur-in-agenda-files t]
12627 "--")
12628 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12630 ;;;; Documentation
12632 (defun org-require-autoloaded-modules ()
12633 (interactive)
12634 (mapc 'require
12635 '(org-agenda org-archive org-clock org-colview
12636 org-exp org-export-latex org-publish
12637 org-remember org-table)))
12639 (defun org-customize ()
12640 "Call the customize function with org as argument."
12641 (interactive)
12642 (org-load-modules-maybe)
12643 (org-require-autoloaded-modules)
12644 (customize-browse 'org))
12646 (defun org-create-customize-menu ()
12647 "Create a full customization menu for Org-mode, insert it into the menu."
12648 (interactive)
12649 (org-load-modules-maybe)
12650 (org-require-autoloaded-modules)
12651 (if (fboundp 'customize-menu-create)
12652 (progn
12653 (easy-menu-change
12654 '("Org") "Customize"
12655 `(["Browse Org group" org-customize t]
12656 "--"
12657 ,(customize-menu-create 'org)
12658 ["Set" Custom-set t]
12659 ["Save" Custom-save t]
12660 ["Reset to Current" Custom-reset-current t]
12661 ["Reset to Saved" Custom-reset-saved t]
12662 ["Reset to Standard Settings" Custom-reset-standard t]))
12663 (message "\"Org\"-menu now contains full customization menu"))
12664 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12666 ;;;; Miscellaneous stuff
12668 ;;; Generally useful functions
12670 (defun org-plist-delete (plist property)
12671 "Delete PROPERTY from PLIST.
12672 This is in contrast to merely setting it to 0."
12673 (let (p)
12674 (while plist
12675 (if (not (eq property (car plist)))
12676 (setq p (plist-put p (car plist) (nth 1 plist))))
12677 (setq plist (cddr plist)))
12680 (defun org-force-self-insert (N)
12681 "Needed to enforce self-insert under remapping."
12682 (interactive "p")
12683 (self-insert-command N))
12685 (defun org-string-width (s)
12686 "Compute width of string, ignoring invisible characters.
12687 This ignores character with invisibility property `org-link', and also
12688 characters with property `org-cwidth', because these will become invisible
12689 upon the next fontification round."
12690 (let (b l)
12691 (when (or (eq t buffer-invisibility-spec)
12692 (assq 'org-link buffer-invisibility-spec))
12693 (while (setq b (text-property-any 0 (length s)
12694 'invisible 'org-link s))
12695 (setq s (concat (substring s 0 b)
12696 (substring s (or (next-single-property-change
12697 b 'invisible s) (length s)))))))
12698 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
12699 (setq s (concat (substring s 0 b)
12700 (substring s (or (next-single-property-change
12701 b 'org-cwidth s) (length s))))))
12702 (setq l (string-width s) b -1)
12703 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
12704 (setq l (- l (get-text-property b 'org-dwidth-n s))))
12708 (defun org-trim (s)
12709 "Remove whitespace at beginning and end of string."
12710 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
12711 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
12714 (defun org-wrap (string &optional width lines)
12715 "Wrap string to either a number of lines, or a width in characters.
12716 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12717 that costs. If there is a word longer than WIDTH, the text is actually
12718 wrapped to the length of that word.
12719 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12720 many lines, whatever width that takes.
12721 The return value is a list of lines, without newlines at the end."
12722 (let* ((words (org-split-string string "[ \t\n]+"))
12723 (maxword (apply 'max (mapcar 'org-string-width words)))
12724 w ll)
12725 (cond (width
12726 (org-do-wrap words (max maxword width)))
12727 (lines
12728 (setq w maxword)
12729 (setq ll (org-do-wrap words maxword))
12730 (if (<= (length ll) lines)
12732 (setq ll words)
12733 (while (> (length ll) lines)
12734 (setq w (1+ w))
12735 (setq ll (org-do-wrap words w)))
12736 ll))
12737 (t (error "Cannot wrap this")))))
12739 (defun org-do-wrap (words width)
12740 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12741 (let (lines line)
12742 (while words
12743 (setq line (pop words))
12744 (while (and words (< (+ (length line) (length (car words))) width))
12745 (setq line (concat line " " (pop words))))
12746 (setq lines (push line lines)))
12747 (nreverse lines)))
12749 (defun org-split-string (string &optional separators)
12750 "Splits STRING into substrings at SEPARATORS.
12751 No empty strings are returned if there are matches at the beginning
12752 and end of string."
12753 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
12754 (start 0)
12755 notfirst
12756 (list nil))
12757 (while (and (string-match rexp string
12758 (if (and notfirst
12759 (= start (match-beginning 0))
12760 (< start (length string)))
12761 (1+ start) start))
12762 (< (match-beginning 0) (length string)))
12763 (setq notfirst t)
12764 (or (eq (match-beginning 0) 0)
12765 (and (eq (match-beginning 0) (match-end 0))
12766 (eq (match-beginning 0) start))
12767 (setq list
12768 (cons (substring string start (match-beginning 0))
12769 list)))
12770 (setq start (match-end 0)))
12771 (or (eq start (length string))
12772 (setq list
12773 (cons (substring string start)
12774 list)))
12775 (nreverse list)))
12777 (defun org-context ()
12778 "Return a list of contexts of the current cursor position.
12779 If several contexts apply, all are returned.
12780 Each context entry is a list with a symbol naming the context, and
12781 two positions indicating start and end of the context. Possible
12782 contexts are:
12784 :headline anywhere in a headline
12785 :headline-stars on the leading stars in a headline
12786 :todo-keyword on a TODO keyword (including DONE) in a headline
12787 :tags on the TAGS in a headline
12788 :priority on the priority cookie in a headline
12789 :item on the first line of a plain list item
12790 :item-bullet on the bullet/number of a plain list item
12791 :checkbox on the checkbox in a plain list item
12792 :table in an org-mode table
12793 :table-special on a special filed in a table
12794 :table-table in a table.el table
12795 :link on a hyperlink
12796 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
12797 :target on a <<target>>
12798 :radio-target on a <<<radio-target>>>
12799 :latex-fragment on a LaTeX fragment
12800 :latex-preview on a LaTeX fragment with overlayed preview image
12802 This function expects the position to be visible because it uses font-lock
12803 faces as a help to recognize the following contexts: :table-special, :link,
12804 and :keyword."
12805 (let* ((f (get-text-property (point) 'face))
12806 (faces (if (listp f) f (list f)))
12807 (p (point)) clist o)
12808 ;; First the large context
12809 (cond
12810 ((org-on-heading-p t)
12811 (push (list :headline (point-at-bol) (point-at-eol)) clist)
12812 (when (progn
12813 (beginning-of-line 1)
12814 (looking-at org-todo-line-tags-regexp))
12815 (push (org-point-in-group p 1 :headline-stars) clist)
12816 (push (org-point-in-group p 2 :todo-keyword) clist)
12817 (push (org-point-in-group p 4 :tags) clist))
12818 (goto-char p)
12819 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
12820 (if (looking-at "\\[#[A-Z0-9]\\]")
12821 (push (org-point-in-group p 0 :priority) clist)))
12823 ((org-at-item-p)
12824 (push (org-point-in-group p 2 :item-bullet) clist)
12825 (push (list :item (point-at-bol)
12826 (save-excursion (org-end-of-item) (point)))
12827 clist)
12828 (and (org-at-item-checkbox-p)
12829 (push (org-point-in-group p 0 :checkbox) clist)))
12831 ((org-at-table-p)
12832 (push (list :table (org-table-begin) (org-table-end)) clist)
12833 (if (memq 'org-formula faces)
12834 (push (list :table-special
12835 (previous-single-property-change p 'face)
12836 (next-single-property-change p 'face)) clist)))
12837 ((org-at-table-p 'any)
12838 (push (list :table-table) clist)))
12839 (goto-char p)
12841 ;; Now the small context
12842 (cond
12843 ((org-at-timestamp-p)
12844 (push (org-point-in-group p 0 :timestamp) clist))
12845 ((memq 'org-link faces)
12846 (push (list :link
12847 (previous-single-property-change p 'face)
12848 (next-single-property-change p 'face)) clist))
12849 ((memq 'org-special-keyword faces)
12850 (push (list :keyword
12851 (previous-single-property-change p 'face)
12852 (next-single-property-change p 'face)) clist))
12853 ((org-on-target-p)
12854 (push (org-point-in-group p 0 :target) clist)
12855 (goto-char (1- (match-beginning 0)))
12856 (if (looking-at org-radio-target-regexp)
12857 (push (org-point-in-group p 0 :radio-target) clist))
12858 (goto-char p))
12859 ((setq o (car (delq nil
12860 (mapcar
12861 (lambda (x)
12862 (if (memq x org-latex-fragment-image-overlays) x))
12863 (org-overlays-at (point))))))
12864 (push (list :latex-fragment
12865 (org-overlay-start o) (org-overlay-end o)) clist)
12866 (push (list :latex-preview
12867 (org-overlay-start o) (org-overlay-end o)) clist))
12868 ((org-inside-LaTeX-fragment-p)
12869 ;; FIXME: positions wrong.
12870 (push (list :latex-fragment (point) (point)) clist)))
12872 (setq clist (nreverse (delq nil clist)))
12873 clist))
12875 ;; FIXME: Compare with at-regexp-p Do we need both?
12876 (defun org-in-regexp (re &optional nlines visually)
12877 "Check if point is inside a match of regexp.
12878 Normally only the current line is checked, but you can include NLINES extra
12879 lines both before and after point into the search.
12880 If VISUALLY is set, require that the cursor is not after the match but
12881 really on, so that the block visually is on the match."
12882 (catch 'exit
12883 (let ((pos (point))
12884 (eol (point-at-eol (+ 1 (or nlines 0))))
12885 (inc (if visually 1 0)))
12886 (save-excursion
12887 (beginning-of-line (- 1 (or nlines 0)))
12888 (while (re-search-forward re eol t)
12889 (if (and (<= (match-beginning 0) pos)
12890 (>= (+ inc (match-end 0)) pos))
12891 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
12893 (defun org-at-regexp-p (regexp)
12894 "Is point inside a match of REGEXP in the current line?"
12895 (catch 'exit
12896 (save-excursion
12897 (let ((pos (point)) (end (point-at-eol)))
12898 (beginning-of-line 1)
12899 (while (re-search-forward regexp end t)
12900 (if (and (<= (match-beginning 0) pos)
12901 (>= (match-end 0) pos))
12902 (throw 'exit t)))
12903 nil))))
12905 (defun org-occur-in-agenda-files (regexp &optional nlines)
12906 "Call `multi-occur' with buffers for all agenda files."
12907 (interactive "sOrg-files matching: \np")
12908 (let* ((files (org-agenda-files))
12909 (tnames (mapcar 'file-truename files))
12910 (extra org-agenda-text-search-extra-files)
12912 (when (eq (car extra) 'agenda-archives)
12913 (setq extra (cdr extra))
12914 (setq files (org-add-archive-files files)))
12915 (while (setq f (pop extra))
12916 (unless (member (file-truename f) tnames)
12917 (add-to-list 'files f 'append)
12918 (add-to-list 'tnames (file-truename f) 'append)))
12919 (multi-occur
12920 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
12921 regexp)))
12923 (if (boundp 'occur-mode-find-occurrence-hook)
12924 ;; Emacs 23
12925 (add-hook 'occur-mode-find-occurrence-hook
12926 (lambda ()
12927 (when (org-mode-p)
12928 (org-reveal))))
12929 ;; Emacs 22
12930 (defadvice occur-mode-goto-occurrence
12931 (after org-occur-reveal activate)
12932 (and (org-mode-p) (org-reveal)))
12933 (defadvice occur-mode-goto-occurrence-other-window
12934 (after org-occur-reveal activate)
12935 (and (org-mode-p) (org-reveal)))
12936 (defadvice occur-mode-display-occurrence
12937 (after org-occur-reveal activate)
12938 (when (org-mode-p)
12939 (let ((pos (occur-mode-find-occurrence)))
12940 (with-current-buffer (marker-buffer pos)
12941 (save-excursion
12942 (goto-char pos)
12943 (org-reveal)))))))
12945 (defun org-uniquify (list)
12946 "Remove duplicate elements from LIST."
12947 (let (res)
12948 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
12949 res))
12951 (defun org-delete-all (elts list)
12952 "Remove all elements in ELTS from LIST."
12953 (while elts
12954 (setq list (delete (pop elts) list)))
12955 list)
12957 (defun org-back-over-empty-lines ()
12958 "Move backwards over witespace, to the beginning of the first empty line.
12959 Returns the number of empty lines passed."
12960 (let ((pos (point)))
12961 (skip-chars-backward " \t\n\r")
12962 (beginning-of-line 2)
12963 (goto-char (min (point) pos))
12964 (count-lines (point) pos)))
12966 (defun org-skip-whitespace ()
12967 (skip-chars-forward " \t\n\r"))
12969 (defun org-point-in-group (point group &optional context)
12970 "Check if POINT is in match-group GROUP.
12971 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
12972 match. If the match group does ot exist or point is not inside it,
12973 return nil."
12974 (and (match-beginning group)
12975 (>= point (match-beginning group))
12976 (<= point (match-end group))
12977 (if context
12978 (list context (match-beginning group) (match-end group))
12979 t)))
12981 (defun org-switch-to-buffer-other-window (&rest args)
12982 "Switch to buffer in a second window on the current frame.
12983 In particular, do not allow pop-up frames."
12984 (let (pop-up-frames special-display-buffer-names special-display-regexps
12985 special-display-function)
12986 (apply 'switch-to-buffer-other-window args)))
12988 (defun org-combine-plists (&rest plists)
12989 "Create a single property list from all plists in PLISTS.
12990 The process starts by copying the first list, and then setting properties
12991 from the other lists. Settings in the last list are the most significant
12992 ones and overrule settings in the other lists."
12993 (let ((rtn (copy-sequence (pop plists)))
12994 p v ls)
12995 (while plists
12996 (setq ls (pop plists))
12997 (while ls
12998 (setq p (pop ls) v (pop ls))
12999 (setq rtn (plist-put rtn p v))))
13000 rtn))
13002 (defun org-move-line-down (arg)
13003 "Move the current line down. With prefix argument, move it past ARG lines."
13004 (interactive "p")
13005 (let ((col (current-column))
13006 beg end pos)
13007 (beginning-of-line 1) (setq beg (point))
13008 (beginning-of-line 2) (setq end (point))
13009 (beginning-of-line (+ 1 arg))
13010 (setq pos (move-marker (make-marker) (point)))
13011 (insert (delete-and-extract-region beg end))
13012 (goto-char pos)
13013 (org-move-to-column col)))
13015 (defun org-move-line-up (arg)
13016 "Move the current line up. With prefix argument, move it past ARG lines."
13017 (interactive "p")
13018 (let ((col (current-column))
13019 beg end pos)
13020 (beginning-of-line 1) (setq beg (point))
13021 (beginning-of-line 2) (setq end (point))
13022 (beginning-of-line (- arg))
13023 (setq pos (move-marker (make-marker) (point)))
13024 (insert (delete-and-extract-region beg end))
13025 (goto-char pos)
13026 (org-move-to-column col)))
13028 (defun org-replace-escapes (string table)
13029 "Replace %-escapes in STRING with values in TABLE.
13030 TABLE is an association list with keys like \"%a\" and string values.
13031 The sequences in STRING may contain normal field width and padding information,
13032 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13033 so values can contain further %-escapes if they are define later in TABLE."
13034 (let ((case-fold-search nil)
13035 e re rpl)
13036 (while (setq e (pop table))
13037 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13038 (while (string-match re string)
13039 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13040 (cdr e)))
13041 (setq string (replace-match rpl t t string))))
13042 string))
13045 (defun org-sublist (list start end)
13046 "Return a section of LIST, from START to END.
13047 Counting starts at 1."
13048 (let (rtn (c start))
13049 (setq list (nthcdr (1- start) list))
13050 (while (and list (<= c end))
13051 (push (pop list) rtn)
13052 (setq c (1+ c)))
13053 (nreverse rtn)))
13055 (defun org-find-base-buffer-visiting (file)
13056 "Like `find-buffer-visiting' but alway return the base buffer and
13057 not an indirect buffer."
13058 (let ((buf (find-buffer-visiting file)))
13059 (if buf
13060 (or (buffer-base-buffer buf) buf)
13061 nil)))
13063 (defun org-image-file-name-regexp ()
13064 "Return regexp matching the file names of images."
13065 (if (fboundp 'image-file-name-regexp)
13066 (image-file-name-regexp)
13067 (let ((image-file-name-extensions
13068 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13069 "xbm" "xpm" "pbm" "pgm" "ppm")))
13070 (concat "\\."
13071 (regexp-opt (nconc (mapcar 'upcase
13072 image-file-name-extensions)
13073 image-file-name-extensions)
13075 "\\'"))))
13077 (defun org-file-image-p (file)
13078 "Return non-nil if FILE is an image."
13079 (save-match-data
13080 (string-match (org-image-file-name-regexp) file)))
13082 ;;; Paragraph filling stuff.
13083 ;; We want this to be just right, so use the full arsenal.
13085 (defun org-indent-line-function ()
13086 "Indent line like previous, but further if previous was headline or item."
13087 (interactive)
13088 (let* ((pos (point))
13089 (itemp (org-at-item-p))
13090 column bpos bcol tpos tcol bullet btype bullet-type)
13091 ;; Find the previous relevant line
13092 (beginning-of-line 1)
13093 (cond
13094 ((looking-at "#") (setq column 0))
13095 ((looking-at "\\*+ ") (setq column 0))
13097 (beginning-of-line 0)
13098 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13099 (beginning-of-line 0))
13100 (cond
13101 ((looking-at "\\*+[ \t]+")
13102 (goto-char (match-end 0))
13103 (setq column (current-column)))
13104 ((org-in-item-p)
13105 (org-beginning-of-item)
13106 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13107 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
13108 (setq bpos (match-beginning 1) tpos (match-end 0)
13109 bcol (progn (goto-char bpos) (current-column))
13110 tcol (progn (goto-char tpos) (current-column))
13111 bullet (match-string 1)
13112 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13113 (if (not itemp)
13114 (setq column tcol)
13115 (goto-char pos)
13116 (beginning-of-line 1)
13117 (if (looking-at "\\S-")
13118 (progn
13119 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13120 (setq bullet (match-string 1)
13121 btype (if (string-match "[0-9]" bullet) "n" bullet))
13122 (setq column (if (equal btype bullet-type) bcol tcol)))
13123 (setq column (org-get-indentation)))))
13124 (t (setq column (org-get-indentation))))))
13125 (goto-char pos)
13126 (if (<= (current-column) (current-indentation))
13127 (org-indent-line-to column)
13128 (save-excursion (org-indent-line-to column)))
13129 (setq column (current-column))
13130 (beginning-of-line 1)
13131 (if (looking-at
13132 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13133 (replace-match (concat "\\1" (format org-property-format
13134 (match-string 2) (match-string 3)))
13135 t nil))
13136 (org-move-to-column column)))
13138 (defun org-set-autofill-regexps ()
13139 (interactive)
13140 ;; In the paragraph separator we include headlines, because filling
13141 ;; text in a line directly attached to a headline would otherwise
13142 ;; fill the headline as well.
13143 (org-set-local 'comment-start-skip "^#+[ \t]*")
13144 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13145 ;; The paragraph starter includes hand-formatted lists.
13146 (org-set-local 'paragraph-start
13147 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13148 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13149 ;; But only if the user has not turned off tables or fixed-width regions
13150 (org-set-local
13151 'auto-fill-inhibit-regexp
13152 (concat "\\*+ \\|#\\+"
13153 "\\|[ \t]*" org-keyword-time-regexp
13154 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13155 (concat
13156 "\\|[ \t]*["
13157 (if org-enable-table-editor "|" "")
13158 (if org-enable-fixed-width-editor ":" "")
13159 "]"))))
13160 ;; We use our own fill-paragraph function, to make sure that tables
13161 ;; and fixed-width regions are not wrapped. That function will pass
13162 ;; through to `fill-paragraph' when appropriate.
13163 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13164 ; Adaptive filling: To get full control, first make sure that
13165 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13166 (org-set-local 'adaptive-fill-regexp "\000")
13167 (org-set-local 'adaptive-fill-function
13168 'org-adaptive-fill-function)
13169 (org-set-local
13170 'align-mode-rules-list
13171 '((org-in-buffer-settings
13172 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13173 (modes . '(org-mode))))))
13175 (defun org-fill-paragraph (&optional justify)
13176 "Re-align a table, pass through to fill-paragraph if no table."
13177 (let ((table-p (org-at-table-p))
13178 (table.el-p (org-at-table.el-p)))
13179 (cond ((and (equal (char-after (point-at-bol)) ?*)
13180 (save-excursion (goto-char (point-at-bol))
13181 (looking-at outline-regexp)))
13182 t) ; skip headlines
13183 (table.el-p t) ; skip table.el tables
13184 (table-p (org-table-align) t) ; align org-mode tables
13185 (t nil)))) ; call paragraph-fill
13187 ;; For reference, this is the default value of adaptive-fill-regexp
13188 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13190 (defun org-adaptive-fill-function ()
13191 "Return a fill prefix for org-mode files.
13192 In particular, this makes sure hanging paragraphs for hand-formatted lists
13193 work correctly."
13194 (cond ((looking-at "#[ \t]+")
13195 (match-string 0))
13196 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13197 (save-excursion
13198 (goto-char (match-end 0))
13199 (make-string (current-column) ?\ )))
13200 (t nil)))
13202 ;;; Other stuff.
13204 (defun org-toggle-fixed-width-section (arg)
13205 "Toggle the fixed-width export.
13206 If there is no active region, the QUOTE keyword at the current headline is
13207 inserted or removed. When present, it causes the text between this headline
13208 and the next to be exported as fixed-width text, and unmodified.
13209 If there is an active region, this command adds or removes a colon as the
13210 first character of this line. If the first character of a line is a colon,
13211 this line is also exported in fixed-width font."
13212 (interactive "P")
13213 (let* ((cc 0)
13214 (regionp (org-region-active-p))
13215 (beg (if regionp (region-beginning) (point)))
13216 (end (if regionp (region-end)))
13217 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13218 (case-fold-search nil)
13219 (re "[ \t]*\\(:\\)")
13220 off)
13221 (if regionp
13222 (save-excursion
13223 (goto-char beg)
13224 (setq cc (current-column))
13225 (beginning-of-line 1)
13226 (setq off (looking-at re))
13227 (while (> nlines 0)
13228 (setq nlines (1- nlines))
13229 (beginning-of-line 1)
13230 (cond
13231 (arg
13232 (org-move-to-column cc t)
13233 (insert ":\n")
13234 (forward-line -1))
13235 ((and off (looking-at re))
13236 (replace-match "" t t nil 1))
13237 ((not off) (org-move-to-column cc t) (insert ":")))
13238 (forward-line 1)))
13239 (save-excursion
13240 (org-back-to-heading)
13241 (if (looking-at (concat outline-regexp
13242 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13243 (replace-match "" t t nil 1)
13244 (if (looking-at outline-regexp)
13245 (progn
13246 (goto-char (match-end 0))
13247 (insert org-quote-string " "))))))))
13249 ;;;; Functions extending outline functionality
13251 (defun org-beginning-of-line (&optional arg)
13252 "Go to the beginning of the current line. If that is invisible, continue
13253 to a visible line beginning. This makes the function of C-a more intuitive.
13254 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13255 first attempt, and only move to after the tags when the cursor is already
13256 beyond the end of the headline."
13257 (interactive "P")
13258 (let ((pos (point)))
13259 (beginning-of-line 1)
13260 (if (bobp)
13262 (backward-char 1)
13263 (if (org-invisible-p)
13264 (while (and (not (bobp)) (org-invisible-p))
13265 (backward-char 1)
13266 (beginning-of-line 1))
13267 (forward-char 1)))
13268 (when org-special-ctrl-a/e
13269 (cond
13270 ((and (looking-at org-todo-line-regexp)
13271 (= (char-after (match-end 1)) ?\ ))
13272 (goto-char
13273 (if (eq org-special-ctrl-a/e t)
13274 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13275 ((= pos (point)) (match-beginning 3))
13276 (t (point)))
13277 (cond ((> pos (point)) (point))
13278 ((not (eq last-command this-command)) (point))
13279 (t (match-beginning 3))))))
13280 ((org-at-item-p)
13281 (goto-char
13282 (if (eq org-special-ctrl-a/e t)
13283 (cond ((> pos (match-end 4)) (match-end 4))
13284 ((= pos (point)) (match-end 4))
13285 (t (point)))
13286 (cond ((> pos (point)) (point))
13287 ((not (eq last-command this-command)) (point))
13288 (t (match-end 4))))))))))
13290 (defun org-end-of-line (&optional arg)
13291 "Go to the end of the line.
13292 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13293 first attempt, and only move to after the tags when the cursor is already
13294 beyond the end of the headline."
13295 (interactive "P")
13296 (if (or (not org-special-ctrl-a/e)
13297 (not (org-on-heading-p)))
13298 (end-of-line arg)
13299 (let ((pos (point)))
13300 (beginning-of-line 1)
13301 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13302 (if (eq org-special-ctrl-a/e t)
13303 (if (or (< pos (match-beginning 1))
13304 (= pos (match-end 0)))
13305 (goto-char (match-beginning 1))
13306 (goto-char (match-end 0)))
13307 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13308 (goto-char (match-end 0))
13309 (goto-char (match-beginning 1))))
13310 (end-of-line arg)))))
13312 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13313 (define-key org-mode-map "\C-e" 'org-end-of-line)
13315 (defun org-kill-line (&optional arg)
13316 "Kill line, to tags or end of line."
13317 (interactive "P")
13318 (cond
13319 ((or (not org-special-ctrl-k)
13320 (bolp)
13321 (not (org-on-heading-p)))
13322 (call-interactively 'kill-line))
13323 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13324 (kill-region (point) (match-beginning 1))
13325 (org-set-tags nil t))
13326 (t (kill-region (point) (point-at-eol)))))
13328 (define-key org-mode-map "\C-k" 'org-kill-line)
13330 (defun org-invisible-p ()
13331 "Check if point is at a character currently not visible."
13332 ;; Early versions of noutline don't have `outline-invisible-p'.
13333 (if (fboundp 'outline-invisible-p)
13334 (outline-invisible-p)
13335 (get-char-property (point) 'invisible)))
13337 (defun org-invisible-p2 ()
13338 "Check if point is at a character currently not visible."
13339 (save-excursion
13340 (if (and (eolp) (not (bobp))) (backward-char 1))
13341 ;; Early versions of noutline don't have `outline-invisible-p'.
13342 (if (fboundp 'outline-invisible-p)
13343 (outline-invisible-p)
13344 (get-char-property (point) 'invisible))))
13346 (defalias 'org-back-to-heading 'outline-back-to-heading)
13347 (defalias 'org-on-heading-p 'outline-on-heading-p)
13348 (defalias 'org-at-heading-p 'outline-on-heading-p)
13349 (defun org-at-heading-or-item-p ()
13350 (or (org-on-heading-p) (org-at-item-p)))
13352 (defun org-on-target-p ()
13353 (or (org-in-regexp org-radio-target-regexp)
13354 (org-in-regexp org-target-regexp)))
13356 (defun org-up-heading-all (arg)
13357 "Move to the heading line of which the present line is a subheading.
13358 This function considers both visible and invisible heading lines.
13359 With argument, move up ARG levels."
13360 (if (fboundp 'outline-up-heading-all)
13361 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13362 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13364 (defun org-up-heading-safe ()
13365 "Move to the heading line of which the present line is a subheading.
13366 This version will not throw an error. It will return the level of the
13367 headline found, or nil if no higher level is found."
13368 (let ((pos (point)) start-level level
13369 (re (concat "^" outline-regexp)))
13370 (catch 'exit
13371 (outline-back-to-heading t)
13372 (setq start-level (funcall outline-level))
13373 (if (equal start-level 1) (throw 'exit nil))
13374 (while (re-search-backward re nil t)
13375 (setq level (funcall outline-level))
13376 (if (< level start-level) (throw 'exit level)))
13377 nil)))
13379 (defun org-first-sibling-p ()
13380 "Is this heading the first child of its parents?"
13381 (interactive)
13382 (let ((re (concat "^" outline-regexp))
13383 level l)
13384 (unless (org-at-heading-p t)
13385 (error "Not at a heading"))
13386 (setq level (funcall outline-level))
13387 (save-excursion
13388 (if (not (re-search-backward re nil t))
13390 (setq l (funcall outline-level))
13391 (< l level)))))
13393 (defun org-goto-sibling (&optional previous)
13394 "Goto the next sibling, even if it is invisible.
13395 When PREVIOUS is set, go to the previous sibling instead. Returns t
13396 when a sibling was found. When none is found, return nil and don't
13397 move point."
13398 (let ((fun (if previous 're-search-backward 're-search-forward))
13399 (pos (point))
13400 (re (concat "^" outline-regexp))
13401 level l)
13402 (when (condition-case nil (org-back-to-heading t) (error nil))
13403 (setq level (funcall outline-level))
13404 (catch 'exit
13405 (or previous (forward-char 1))
13406 (while (funcall fun re nil t)
13407 (setq l (funcall outline-level))
13408 (when (< l level) (goto-char pos) (throw 'exit nil))
13409 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13410 (goto-char pos)
13411 nil))))
13413 (defun org-show-siblings ()
13414 "Show all siblings of the current headline."
13415 (save-excursion
13416 (while (org-goto-sibling) (org-flag-heading nil)))
13417 (save-excursion
13418 (while (org-goto-sibling 'previous)
13419 (org-flag-heading nil))))
13421 (defun org-show-hidden-entry ()
13422 "Show an entry where even the heading is hidden."
13423 (save-excursion
13424 (org-show-entry)))
13426 (defun org-flag-heading (flag &optional entry)
13427 "Flag the current heading. FLAG non-nil means make invisible.
13428 When ENTRY is non-nil, show the entire entry."
13429 (save-excursion
13430 (org-back-to-heading t)
13431 ;; Check if we should show the entire entry
13432 (if entry
13433 (progn
13434 (org-show-entry)
13435 (save-excursion
13436 (and (outline-next-heading)
13437 (org-flag-heading nil))))
13438 (outline-flag-region (max (point-min) (1- (point)))
13439 (save-excursion (outline-end-of-heading) (point))
13440 flag))))
13442 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13443 ;; This is an exact copy of the original function, but it uses
13444 ;; `org-back-to-heading', to make it work also in invisible
13445 ;; trees. And is uses an invisible-OK argument.
13446 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13447 (org-back-to-heading invisible-OK)
13448 (let ((first t)
13449 (level (funcall outline-level)))
13450 (while (and (not (eobp))
13451 (or first (> (funcall outline-level) level)))
13452 (setq first nil)
13453 (outline-next-heading))
13454 (unless to-heading
13455 (if (memq (preceding-char) '(?\n ?\^M))
13456 (progn
13457 ;; Go to end of line before heading
13458 (forward-char -1)
13459 (if (memq (preceding-char) '(?\n ?\^M))
13460 ;; leave blank line before heading
13461 (forward-char -1))))))
13462 (point))
13464 (defun org-show-subtree ()
13465 "Show everything after this heading at deeper levels."
13466 (outline-flag-region
13467 (point)
13468 (save-excursion
13469 (outline-end-of-subtree) (outline-next-heading) (point))
13470 nil))
13472 (defun org-show-entry ()
13473 "Show the body directly following this heading.
13474 Show the heading too, if it is currently invisible."
13475 (interactive)
13476 (save-excursion
13477 (condition-case nil
13478 (progn
13479 (org-back-to-heading t)
13480 (outline-flag-region
13481 (max (point-min) (1- (point)))
13482 (save-excursion
13483 (re-search-forward
13484 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13485 (or (match-beginning 1) (point-max)))
13486 nil))
13487 (error nil))))
13489 (defun org-make-options-regexp (kwds)
13490 "Make a regular expression for keyword lines."
13491 (concat
13493 "#?[ \t]*\\+\\("
13494 (mapconcat 'regexp-quote kwds "\\|")
13495 "\\):[ \t]*"
13496 "\\(.+\\)"))
13498 ;; Make isearch reveal the necessary context
13499 (defun org-isearch-end ()
13500 "Reveal context after isearch exits."
13501 (when isearch-success ; only if search was successful
13502 (if (featurep 'xemacs)
13503 ;; Under XEmacs, the hook is run in the correct place,
13504 ;; we directly show the context.
13505 (org-show-context 'isearch)
13506 ;; In Emacs the hook runs *before* restoring the overlays.
13507 ;; So we have to use a one-time post-command-hook to do this.
13508 ;; (Emacs 22 has a special variable, see function `org-mode')
13509 (unless (and (boundp 'isearch-mode-end-hook-quit)
13510 isearch-mode-end-hook-quit)
13511 ;; Only when the isearch was not quitted.
13512 (org-add-hook 'post-command-hook 'org-isearch-post-command
13513 'append 'local)))))
13515 (defun org-isearch-post-command ()
13516 "Remove self from hook, and show context."
13517 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13518 (org-show-context 'isearch))
13521 ;;;; Integration with and fixes for other packages
13523 ;;; Imenu support
13525 (defvar org-imenu-markers nil
13526 "All markers currently used by Imenu.")
13527 (make-variable-buffer-local 'org-imenu-markers)
13529 (defun org-imenu-new-marker (&optional pos)
13530 "Return a new marker for use by Imenu, and remember the marker."
13531 (let ((m (make-marker)))
13532 (move-marker m (or pos (point)))
13533 (push m org-imenu-markers)
13536 (defun org-imenu-get-tree ()
13537 "Produce the index for Imenu."
13538 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
13539 (setq org-imenu-markers nil)
13540 (let* ((n org-imenu-depth)
13541 (re (concat "^" outline-regexp))
13542 (subs (make-vector (1+ n) nil))
13543 (last-level 0)
13544 m tree level head)
13545 (save-excursion
13546 (save-restriction
13547 (widen)
13548 (goto-char (point-max))
13549 (while (re-search-backward re nil t)
13550 (setq level (org-reduced-level (funcall outline-level)))
13551 (when (<= level n)
13552 (looking-at org-complex-heading-regexp)
13553 (setq head (org-match-string-no-properties 4)
13554 m (org-imenu-new-marker))
13555 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
13556 (if (>= level last-level)
13557 (push (cons head m) (aref subs level))
13558 (push (cons head (aref subs (1+ level))) (aref subs level))
13559 (loop for i from (1+ level) to n do (aset subs i nil)))
13560 (setq last-level level)))))
13561 (aref subs 1)))
13563 (eval-after-load "imenu"
13564 '(progn
13565 (add-hook 'imenu-after-jump-hook
13566 (lambda () (org-show-context 'org-goto)))))
13568 ;; Speedbar support
13570 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
13571 "Overlay marking the agenda restriction line in speedbar.")
13572 (org-overlay-put org-speedbar-restriction-lock-overlay
13573 'face 'org-agenda-restriction-lock)
13574 (org-overlay-put org-speedbar-restriction-lock-overlay
13575 'help-echo "Agendas are currently limited to this item.")
13576 (org-detach-overlay org-speedbar-restriction-lock-overlay)
13578 (defun org-speedbar-set-agenda-restriction ()
13579 "Restrict future agenda commands to the location at point in speedbar.
13580 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
13581 (interactive)
13582 (require 'org-agenda)
13583 (let (p m tp np dir txt w)
13584 (cond
13585 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13586 'org-imenu t))
13587 (setq m (get-text-property p 'org-imenu-marker))
13588 (save-excursion
13589 (save-restriction
13590 (set-buffer (marker-buffer m))
13591 (goto-char m)
13592 (org-agenda-set-restriction-lock 'subtree))))
13593 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13594 'speedbar-function 'speedbar-find-file))
13595 (setq tp (previous-single-property-change
13596 (1+ p) 'speedbar-function)
13597 np (next-single-property-change
13598 tp 'speedbar-function)
13599 dir (speedbar-line-directory)
13600 txt (buffer-substring-no-properties (or tp (point-min))
13601 (or np (point-max))))
13602 (save-excursion
13603 (save-restriction
13604 (set-buffer (find-file-noselect
13605 (let ((default-directory dir))
13606 (expand-file-name txt))))
13607 (unless (org-mode-p)
13608 (error "Cannot restrict to non-Org-mode file"))
13609 (org-agenda-set-restriction-lock 'file))))
13610 (t (error "Don't know how to restrict Org-mode's agenda")))
13611 (org-move-overlay org-speedbar-restriction-lock-overlay
13612 (point-at-bol) (point-at-eol))
13613 (setq current-prefix-arg nil)
13614 (org-agenda-maybe-redo)))
13616 (eval-after-load "speedbar"
13617 '(progn
13618 (speedbar-add-supported-extension ".org")
13619 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
13620 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
13621 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
13622 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13623 (add-hook 'speedbar-visiting-tag-hook
13624 (lambda () (org-show-context 'org-goto)))))
13627 ;;; Fixes and Hacks for problems with other packages
13629 ;; Make flyspell not check words in links, to not mess up our keymap
13630 (defun org-mode-flyspell-verify ()
13631 "Don't let flyspell put overlays at active buttons."
13632 (not (get-text-property (point) 'keymap)))
13634 ;; Make `bookmark-jump' show the jump location if it was hidden.
13635 (eval-after-load "bookmark"
13636 '(if (boundp 'bookmark-after-jump-hook)
13637 ;; We can use the hook
13638 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13639 ;; Hook not available, use advice
13640 (defadvice bookmark-jump (after org-make-visible activate)
13641 "Make the position visible."
13642 (org-bookmark-jump-unhide))))
13644 (defun org-bookmark-jump-unhide ()
13645 "Unhide the current position, to show the bookmark location."
13646 (and (org-mode-p)
13647 (or (org-invisible-p)
13648 (save-excursion (goto-char (max (point-min) (1- (point))))
13649 (org-invisible-p)))
13650 (org-show-context 'bookmark-jump)))
13652 ;; Make session.el ignore our circular variable
13653 (eval-after-load "session"
13654 '(add-to-list 'session-globals-exclude 'org-mark-ring))
13656 ;;;; Experimental code
13658 (defun org-closed-in-range ()
13659 "Sparse tree of items closed in a certain time range.
13660 Still experimental, may disappear in the future."
13661 (interactive)
13662 ;; Get the time interval from the user.
13663 (let* ((time1 (time-to-seconds
13664 (org-read-date nil 'to-time nil "Starting date: ")))
13665 (time2 (time-to-seconds
13666 (org-read-date nil 'to-time nil "End date:")))
13667 ;; callback function
13668 (callback (lambda ()
13669 (let ((time
13670 (time-to-seconds
13671 (apply 'encode-time
13672 (org-parse-time-string
13673 (match-string 1))))))
13674 ;; check if time in interval
13675 (and (>= time time1) (<= time time2))))))
13676 ;; make tree, check each match with the callback
13677 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
13680 ;;;; Finish up
13682 (provide 'org)
13684 (run-hooks 'org-load-hook)
13686 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13687 ;;; org.el ends here