Implementing the eval tags like <lisp> in Muse.
[org-mode.git] / lisp / org.el
blobfe4849bdc9e65958277c99ee8946853ffc126ccb
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 (defvar org-font-lock-hook nil
3588 "Functions to be called for special font loch stuff.")
3590 (defun org-font-lock-hook (limit)
3591 (run-hook-with-args 'org-font-lock-hook limit))
3593 (defun org-set-font-lock-defaults ()
3594 (let* ((em org-fontify-emphasized-text)
3595 (lk org-activate-links)
3596 (org-font-lock-extra-keywords
3597 (list
3598 ;; Call the hook
3599 '(org-font-lock-hook)
3600 ;; Headlines
3601 '("^\\(\\**\\)\\(\\* \\)\\(.*\\)" (1 (org-get-level-face 1))
3602 (2 (org-get-level-face 2)) (3 (org-get-level-face 3)))
3603 ;; Table lines
3604 '("^[ \t]*\\(\\(|\\|\\+-[-+]\\).*\\S-\\)"
3605 (1 'org-table t))
3606 ;; Table internals
3607 '("^[ \t]*|\\(?:.*?|\\)? *\\(:?=[^|\n]*\\)" (1 'org-formula t))
3608 '("^[ \t]*| *\\([#*]\\) *|" (1 'org-formula t))
3609 '("^[ \t]*|\\( *\\([$!_^/]\\) *|.*\\)|" (1 'org-formula t))
3610 ;; Drawers
3611 (list org-drawer-regexp '(0 'org-special-keyword t))
3612 (list "^[ \t]*:END:" '(0 'org-special-keyword t))
3613 ;; Properties
3614 (list org-property-re
3615 '(1 'org-special-keyword t)
3616 '(3 'org-property-value t))
3617 (if org-format-transports-properties-p
3618 '("| *\\(<[0-9]+>\\) *" (1 'org-formula t)))
3619 ;; Links
3620 (if (memq 'tag lk) '(org-activate-tags (1 'org-tag prepend)))
3621 (if (memq 'angle lk) '(org-activate-angle-links (0 'org-link t)))
3622 (if (memq 'plain lk) '(org-activate-plain-links (0 'org-link t)))
3623 (if (memq 'bracket lk) '(org-activate-bracket-links (0 'org-link t)))
3624 (if (memq 'radio lk) '(org-activate-target-links (0 'org-link t)))
3625 (if (memq 'date lk) '(org-activate-dates (0 'org-date t)))
3626 '("^&?%%(.*\\|<%%([^>\n]*?>" (0 'org-sexp-date t))
3627 '(org-hide-wide-columns (0 nil append))
3628 ;; TODO lines
3629 (list (concat "^\\*+[ \t]+" org-todo-regexp)
3630 '(1 (org-get-todo-face 1) t))
3631 ;; DONE
3632 (if org-fontify-done-headline
3633 (list (concat "^[*]+ +\\<\\("
3634 (mapconcat 'regexp-quote org-done-keywords "\\|")
3635 "\\)\\(.*\\)")
3636 '(2 'org-headline-done t))
3637 nil)
3638 ;; Priorities
3639 (list (concat "\\[#[A-Z0-9]\\]") '(0 'org-special-keyword t))
3640 ;; Special keywords
3641 (list (concat "\\<" org-deadline-string) '(0 'org-special-keyword t))
3642 (list (concat "\\<" org-scheduled-string) '(0 'org-special-keyword t))
3643 (list (concat "\\<" org-closed-string) '(0 'org-special-keyword t))
3644 (list (concat "\\<" org-clock-string) '(0 'org-special-keyword t))
3645 ;; Emphasis
3646 (if em
3647 (if (featurep 'xemacs)
3648 '(org-do-emphasis-faces (0 nil append))
3649 '(org-do-emphasis-faces)))
3650 ;; Checkboxes
3651 '("^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)"
3652 2 'bold prepend)
3653 (if org-provide-checkbox-statistics
3654 '("\\[\\([0-9]*%\\)\\]\\|\\[\\([0-9]*\\)/\\([0-9]*\\)\\]"
3655 (0 (org-get-checkbox-statistics-face) t)))
3656 (list (concat "^\\*+ \\(.*:" org-archive-tag ":.*\\)")
3657 '(1 'org-archived prepend))
3658 ;; Specials
3659 '(org-do-latex-and-special-faces)
3660 ;; Code
3661 '(org-activate-code (1 'org-code t))
3662 ;; COMMENT
3663 (list (concat "^\\*+[ \t]+\\<\\(" org-comment-string
3664 "\\|" org-quote-string "\\)\\>")
3665 '(1 'org-special-keyword t))
3666 '("^#.*" (0 'font-lock-comment-face t))
3668 (setq org-font-lock-extra-keywords (delq nil org-font-lock-extra-keywords))
3669 ;; Now set the full font-lock-keywords
3670 (org-set-local 'org-font-lock-keywords org-font-lock-extra-keywords)
3671 (org-set-local 'font-lock-defaults
3672 '(org-font-lock-keywords t nil nil backward-paragraph))
3673 (kill-local-variable 'font-lock-keywords) nil))
3675 (defvar org-m nil)
3676 (defvar org-l nil)
3677 (defvar org-f nil)
3678 (defun org-get-level-face (n)
3679 "Get the right face for match N in font-lock matching of healdines."
3680 (setq org-l (- (match-end 2) (match-beginning 1) 1))
3681 (if org-odd-levels-only (setq org-l (1+ (/ org-l 2))))
3682 (setq org-f (nth (% (1- org-l) org-n-level-faces) org-level-faces))
3683 (cond
3684 ((eq n 1) (if org-hide-leading-stars 'org-hide org-f))
3685 ((eq n 2) org-f)
3686 (t (if org-level-color-stars-only nil org-f))))
3688 (defun org-get-todo-face (kwd)
3689 "Get the right face for a TODO keyword KWD.
3690 If KWD is a number, get the corresponding match group."
3691 (if (numberp kwd) (setq kwd (match-string kwd)))
3692 (or (cdr (assoc kwd org-todo-keyword-faces))
3693 (and (member kwd org-done-keywords) 'org-done)
3694 'org-todo))
3696 (defun org-unfontify-region (beg end &optional maybe_loudly)
3697 "Remove fontification and activation overlays from links."
3698 (font-lock-default-unfontify-region beg end)
3699 (let* ((buffer-undo-list t)
3700 (inhibit-read-only t) (inhibit-point-motion-hooks t)
3701 (inhibit-modification-hooks t)
3702 deactivate-mark buffer-file-name buffer-file-truename)
3703 (remove-text-properties beg end
3704 '(mouse-face t keymap t org-linked-text t
3705 invisible t intangible t))))
3707 ;;;; Visibility cycling, including org-goto and indirect buffer
3709 ;;; Cycling
3711 (defvar org-cycle-global-status nil)
3712 (make-variable-buffer-local 'org-cycle-global-status)
3713 (defvar org-cycle-subtree-status nil)
3714 (make-variable-buffer-local 'org-cycle-subtree-status)
3716 ;;;###autoload
3717 (defun org-cycle (&optional arg)
3718 "Visibility cycling for Org-mode.
3720 - When this function is called with a prefix argument, rotate the entire
3721 buffer through 3 states (global cycling)
3722 1. OVERVIEW: Show only top-level headlines.
3723 2. CONTENTS: Show all headlines of all levels, but no body text.
3724 3. SHOW ALL: Show everything.
3726 - When point is at the beginning of a headline, rotate the subtree started
3727 by this line through 3 different states (local cycling)
3728 1. FOLDED: Only the main headline is shown.
3729 2. CHILDREN: The main headline and the direct children are shown.
3730 From this state, you can move to one of the children
3731 and zoom in further.
3732 3. SUBTREE: Show the entire subtree, including body text.
3734 - When there is a numeric prefix, go up to a heading with level ARG, do
3735 a `show-subtree' and return to the previous cursor position. If ARG
3736 is negative, go up that many levels.
3738 - When point is not at the beginning of a headline, execute
3739 `indent-relative', like TAB normally does. See the option
3740 `org-cycle-emulate-tab' for details.
3742 - Special case: if point is at the beginning of the buffer and there is
3743 no headline in line 1, this function will act as if called with prefix arg.
3744 But only if also the variable `org-cycle-global-at-bob' is t."
3745 (interactive "P")
3746 (org-load-modules-maybe)
3747 (let* ((outline-regexp
3748 (if (and (org-mode-p) org-cycle-include-plain-lists)
3749 "\\(?:\\*+ \\|\\([ \t]*\\)\\([-+*]\\|[0-9]+[.)]\\) \\)"
3750 outline-regexp))
3751 (bob-special (and org-cycle-global-at-bob (bobp)
3752 (not (looking-at outline-regexp))))
3753 (org-cycle-hook
3754 (if bob-special
3755 (delq 'org-optimize-window-after-visibility-change
3756 (copy-sequence org-cycle-hook))
3757 org-cycle-hook))
3758 (pos (point)))
3760 (if (or bob-special (equal arg '(4)))
3761 ;; special case: use global cycling
3762 (setq arg t))
3764 (cond
3766 ((org-at-table-p 'any)
3767 ;; Enter the table or move to the next field in the table
3768 (or (org-table-recognize-table.el)
3769 (progn
3770 (if arg (org-table-edit-field t)
3771 (org-table-justify-field-maybe)
3772 (call-interactively 'org-table-next-field)))))
3774 ((eq arg t) ;; Global cycling
3776 (cond
3777 ((and (eq last-command this-command)
3778 (eq org-cycle-global-status 'overview))
3779 ;; We just created the overview - now do table of contents
3780 ;; This can be slow in very large buffers, so indicate action
3781 (message "CONTENTS...")
3782 (org-content)
3783 (message "CONTENTS...done")
3784 (setq org-cycle-global-status 'contents)
3785 (run-hook-with-args 'org-cycle-hook 'contents))
3787 ((and (eq last-command this-command)
3788 (eq org-cycle-global-status 'contents))
3789 ;; We just showed the table of contents - now show everything
3790 (show-all)
3791 (message "SHOW ALL")
3792 (setq org-cycle-global-status 'all)
3793 (run-hook-with-args 'org-cycle-hook 'all))
3796 ;; Default action: go to overview
3797 (org-overview)
3798 (message "OVERVIEW")
3799 (setq org-cycle-global-status 'overview)
3800 (run-hook-with-args 'org-cycle-hook 'overview))))
3802 ((and org-drawers org-drawer-regexp
3803 (save-excursion
3804 (beginning-of-line 1)
3805 (looking-at org-drawer-regexp)))
3806 ;; Toggle block visibility
3807 (org-flag-drawer
3808 (not (get-char-property (match-end 0) 'invisible))))
3810 ((integerp arg)
3811 ;; Show-subtree, ARG levels up from here.
3812 (save-excursion
3813 (org-back-to-heading)
3814 (outline-up-heading (if (< arg 0) (- arg)
3815 (- (funcall outline-level) arg)))
3816 (org-show-subtree)))
3818 ((and (save-excursion (beginning-of-line 1) (looking-at outline-regexp))
3819 (or (bolp) (not (eq org-cycle-emulate-tab 'exc-hl-bol))))
3820 ;; At a heading: rotate between three different views
3821 (org-back-to-heading)
3822 (let ((goal-column 0) eoh eol eos)
3823 ;; First, some boundaries
3824 (save-excursion
3825 (org-back-to-heading)
3826 (save-excursion
3827 (beginning-of-line 2)
3828 (while (and (not (eobp)) ;; this is like `next-line'
3829 (get-char-property (1- (point)) 'invisible))
3830 (beginning-of-line 2)) (setq eol (point)))
3831 (outline-end-of-heading) (setq eoh (point))
3832 (org-end-of-subtree t)
3833 (unless (eobp)
3834 (skip-chars-forward " \t\n")
3835 (beginning-of-line 1) ; in case this is an item
3837 (setq eos (1- (point))))
3838 ;; Find out what to do next and set `this-command'
3839 (cond
3840 ((= eos eoh)
3841 ;; Nothing is hidden behind this heading
3842 (message "EMPTY ENTRY")
3843 (setq org-cycle-subtree-status nil)
3844 (save-excursion
3845 (goto-char eos)
3846 (outline-next-heading)
3847 (if (org-invisible-p) (org-flag-heading nil))))
3848 ((or (>= eol eos)
3849 (not (string-match "\\S-" (buffer-substring eol eos))))
3850 ;; Entire subtree is hidden in one line: open it
3851 (org-show-entry)
3852 (show-children)
3853 (message "CHILDREN")
3854 (save-excursion
3855 (goto-char eos)
3856 (outline-next-heading)
3857 (if (org-invisible-p) (org-flag-heading nil)))
3858 (setq org-cycle-subtree-status 'children)
3859 (run-hook-with-args 'org-cycle-hook 'children))
3860 ((and (eq last-command this-command)
3861 (eq org-cycle-subtree-status 'children))
3862 ;; We just showed the children, now show everything.
3863 (org-show-subtree)
3864 (message "SUBTREE")
3865 (setq org-cycle-subtree-status 'subtree)
3866 (run-hook-with-args 'org-cycle-hook 'subtree))
3868 ;; Default action: hide the subtree.
3869 (hide-subtree)
3870 (message "FOLDED")
3871 (setq org-cycle-subtree-status 'folded)
3872 (run-hook-with-args 'org-cycle-hook 'folded)))))
3874 ;; TAB emulation
3875 (buffer-read-only (org-back-to-heading))
3877 ((org-try-cdlatex-tab))
3879 ((and (eq org-cycle-emulate-tab 'exc-hl-bol)
3880 (or (not (bolp))
3881 (not (looking-at outline-regexp))))
3882 (call-interactively (global-key-binding "\t")))
3884 ((if (and (memq org-cycle-emulate-tab '(white whitestart))
3885 (save-excursion (beginning-of-line 1) (looking-at "[ \t]*"))
3886 (or (and (eq org-cycle-emulate-tab 'white)
3887 (= (match-end 0) (point-at-eol)))
3888 (and (eq org-cycle-emulate-tab 'whitestart)
3889 (>= (match-end 0) pos))))
3891 (eq org-cycle-emulate-tab t))
3892 (call-interactively (global-key-binding "\t")))
3894 (t (save-excursion
3895 (org-back-to-heading)
3896 (org-cycle))))))
3898 ;;;###autoload
3899 (defun org-global-cycle (&optional arg)
3900 "Cycle the global visibility. For details see `org-cycle'."
3901 (interactive "P")
3902 (let ((org-cycle-include-plain-lists
3903 (if (org-mode-p) org-cycle-include-plain-lists nil)))
3904 (if (integerp arg)
3905 (progn
3906 (show-all)
3907 (hide-sublevels arg)
3908 (setq org-cycle-global-status 'contents))
3909 (org-cycle '(4)))))
3911 (defun org-overview ()
3912 "Switch to overview mode, shoing only top-level headlines.
3913 Really, this shows all headlines with level equal or greater than the level
3914 of the first headline in the buffer. This is important, because if the
3915 first headline is not level one, then (hide-sublevels 1) gives confusing
3916 results."
3917 (interactive)
3918 (let ((level (save-excursion
3919 (goto-char (point-min))
3920 (if (re-search-forward (concat "^" outline-regexp) nil t)
3921 (progn
3922 (goto-char (match-beginning 0))
3923 (funcall outline-level))))))
3924 (and level (hide-sublevels level))))
3926 (defun org-content (&optional arg)
3927 "Show all headlines in the buffer, like a table of contents.
3928 With numerical argument N, show content up to level N."
3929 (interactive "P")
3930 (save-excursion
3931 ;; Visit all headings and show their offspring
3932 (and (integerp arg) (org-overview))
3933 (goto-char (point-max))
3934 (catch 'exit
3935 (while (and (progn (condition-case nil
3936 (outline-previous-visible-heading 1)
3937 (error (goto-char (point-min))))
3939 (looking-at outline-regexp))
3940 (if (integerp arg)
3941 (show-children (1- arg))
3942 (show-branches))
3943 (if (bobp) (throw 'exit nil))))))
3946 (defun org-optimize-window-after-visibility-change (state)
3947 "Adjust the window after a change in outline visibility.
3948 This function is the default value of the hook `org-cycle-hook'."
3949 (when (get-buffer-window (current-buffer))
3950 (cond
3951 ; ((eq state 'overview) (org-first-headline-recenter 1))
3952 ; ((eq state 'overview) (org-beginning-of-line))
3953 ((eq state 'content) nil)
3954 ((eq state 'all) nil)
3955 ((eq state 'folded) nil)
3956 ((eq state 'children) (or (org-subtree-end-visible-p) (recenter 1)))
3957 ((eq state 'subtree) (or (org-subtree-end-visible-p) (recenter 1))))))
3959 (defun org-compact-display-after-subtree-move ()
3960 (let (beg end)
3961 (save-excursion
3962 (if (org-up-heading-safe)
3963 (progn
3964 (hide-subtree)
3965 (show-entry)
3966 (show-children)
3967 (org-cycle-show-empty-lines 'children)
3968 (org-cycle-hide-drawers 'children))
3969 (org-overview)))))
3971 (defun org-cycle-show-empty-lines (state)
3972 "Show empty lines above all visible headlines.
3973 The region to be covered depends on STATE when called through
3974 `org-cycle-hook'. Lisp program can use t for STATE to get the
3975 entire buffer covered. Note that an empty line is only shown if there
3976 are at least `org-cycle-separator-lines' empty lines before the headeline."
3977 (when (> org-cycle-separator-lines 0)
3978 (save-excursion
3979 (let* ((n org-cycle-separator-lines)
3980 (re (cond
3981 ((= n 1) "\\(\n[ \t]*\n\\*+\\) ")
3982 ((= n 2) "^[ \t]*\\(\n[ \t]*\n\\*+\\) ")
3983 (t (let ((ns (number-to-string (- n 2))))
3984 (concat "^\\(?:[ \t]*\n\\)\\{" ns "," ns "\\}"
3985 "[ \t]*\\(\n[ \t]*\n\\*+\\) ")))))
3986 beg end)
3987 (cond
3988 ((memq state '(overview contents t))
3989 (setq beg (point-min) end (point-max)))
3990 ((memq state '(children folded))
3991 (setq beg (point) end (progn (org-end-of-subtree t t)
3992 (beginning-of-line 2)
3993 (point)))))
3994 (when beg
3995 (goto-char beg)
3996 (while (re-search-forward re end t)
3997 (if (not (get-char-property (match-end 1) 'invisible))
3998 (outline-flag-region
3999 (match-beginning 1) (match-end 1) nil)))))))
4000 ;; Never hide empty lines at the end of the file.
4001 (save-excursion
4002 (goto-char (point-max))
4003 (outline-previous-heading)
4004 (outline-end-of-heading)
4005 (if (and (looking-at "[ \t\n]+")
4006 (= (match-end 0) (point-max)))
4007 (outline-flag-region (point) (match-end 0) nil))))
4009 (defun org-cycle-hide-drawers (state)
4010 "Re-hide all drawers after a visibility state change."
4011 (when (and (org-mode-p)
4012 (not (memq state '(overview folded))))
4013 (save-excursion
4014 (let* ((globalp (memq state '(contents all)))
4015 (beg (if globalp (point-min) (point)))
4016 (end (if globalp (point-max) (org-end-of-subtree t))))
4017 (goto-char beg)
4018 (while (re-search-forward org-drawer-regexp end t)
4019 (org-flag-drawer t))))))
4021 (defun org-flag-drawer (flag)
4022 (save-excursion
4023 (beginning-of-line 1)
4024 (when (looking-at "^[ \t]*:[a-zA-Z][a-zA-Z0-9]*:")
4025 (let ((b (match-end 0))
4026 (outline-regexp org-outline-regexp))
4027 (if (re-search-forward
4028 "^[ \t]*:END:"
4029 (save-excursion (outline-next-heading) (point)) t)
4030 (outline-flag-region b (point-at-eol) flag)
4031 (error ":END: line missing"))))))
4035 (defun org-subtree-end-visible-p ()
4036 "Is the end of the current subtree visible?"
4037 (pos-visible-in-window-p
4038 (save-excursion (org-end-of-subtree t) (point))))
4040 (defun org-first-headline-recenter (&optional N)
4041 "Move cursor to the first headline and recenter the headline.
4042 Optional argument N means, put the headline into the Nth line of the window."
4043 (goto-char (point-min))
4044 (when (re-search-forward (concat "^\\(" outline-regexp "\\)") nil t)
4045 (beginning-of-line)
4046 (recenter (prefix-numeric-value N))))
4048 ;;; Org-goto
4050 (defvar org-goto-window-configuration nil)
4051 (defvar org-goto-marker nil)
4052 (defvar org-goto-map
4053 (let ((map (make-sparse-keymap)))
4054 (let ((cmds '(isearch-forward isearch-backward kill-ring-save set-mark-command mouse-drag-region universal-argument org-occur)) cmd)
4055 (while (setq cmd (pop cmds))
4056 (substitute-key-definition cmd cmd map global-map)))
4057 (suppress-keymap map)
4058 (org-defkey map "\C-m" 'org-goto-ret)
4059 (org-defkey map [(return)] 'org-goto-ret)
4060 (org-defkey map [(left)] 'org-goto-left)
4061 (org-defkey map [(right)] 'org-goto-right)
4062 (org-defkey map [(control ?g)] 'org-goto-quit)
4063 (org-defkey map "\C-i" 'org-cycle)
4064 (org-defkey map [(tab)] 'org-cycle)
4065 (org-defkey map [(down)] 'outline-next-visible-heading)
4066 (org-defkey map [(up)] 'outline-previous-visible-heading)
4067 (if org-goto-auto-isearch
4068 (if (fboundp 'define-key-after)
4069 (define-key-after map [t] 'org-goto-local-auto-isearch)
4070 nil)
4071 (org-defkey map "q" 'org-goto-quit)
4072 (org-defkey map "n" 'outline-next-visible-heading)
4073 (org-defkey map "p" 'outline-previous-visible-heading)
4074 (org-defkey map "f" 'outline-forward-same-level)
4075 (org-defkey map "b" 'outline-backward-same-level)
4076 (org-defkey map "u" 'outline-up-heading))
4077 (org-defkey map "/" 'org-occur)
4078 (org-defkey map "\C-c\C-n" 'outline-next-visible-heading)
4079 (org-defkey map "\C-c\C-p" 'outline-previous-visible-heading)
4080 (org-defkey map "\C-c\C-f" 'outline-forward-same-level)
4081 (org-defkey map "\C-c\C-b" 'outline-backward-same-level)
4082 (org-defkey map "\C-c\C-u" 'outline-up-heading)
4083 map))
4085 (defconst org-goto-help
4086 "Browse buffer copy, to find location or copy text. Just type for auto-isearch.
4087 RET=jump to location [Q]uit and return to previous location
4088 \[Up]/[Down]=next/prev headline TAB=cycle visibility [/] org-occur")
4090 (defvar org-goto-start-pos) ; dynamically scoped parameter
4092 (defun org-goto (&optional alternative-interface)
4093 "Look up a different location in the current file, keeping current visibility.
4095 When you want look-up or go to a different location in a document, the
4096 fastest way is often to fold the entire buffer and then dive into the tree.
4097 This method has the disadvantage, that the previous location will be folded,
4098 which may not be what you want.
4100 This command works around this by showing a copy of the current buffer
4101 in an indirect buffer, in overview mode. You can dive into the tree in
4102 that copy, use org-occur and incremental search to find a location.
4103 When pressing RET or `Q', the command returns to the original buffer in
4104 which the visibility is still unchanged. After RET is will also jump to
4105 the location selected in the indirect buffer and expose the
4106 the headline hierarchy above."
4107 (interactive "P")
4108 (let* ((org-refile-targets '((nil . (:maxlevel . 10))))
4109 (org-refile-use-outline-path t)
4110 (interface
4111 (if (not alternative-interface)
4112 org-goto-interface
4113 (if (eq org-goto-interface 'outline)
4114 'outline-path-completion
4115 'outline)))
4116 (org-goto-start-pos (point))
4117 (selected-point
4118 (if (eq interface 'outline)
4119 (car (org-get-location (current-buffer) org-goto-help))
4120 (nth 3 (org-refile-get-location "Goto: ")))))
4121 (if selected-point
4122 (progn
4123 (org-mark-ring-push org-goto-start-pos)
4124 (goto-char selected-point)
4125 (if (or (org-invisible-p) (org-invisible-p2))
4126 (org-show-context 'org-goto)))
4127 (message "Quit"))))
4129 (defvar org-goto-selected-point nil) ; dynamically scoped parameter
4130 (defvar org-goto-exit-command nil) ; dynamically scoped parameter
4131 (defvar org-goto-local-auto-isearch-map) ; defined below
4133 (defun org-get-location (buf help)
4134 "Let the user select a location in the Org-mode buffer BUF.
4135 This function uses a recursive edit. It returns the selected position
4136 or nil."
4137 (let ((isearch-mode-map org-goto-local-auto-isearch-map)
4138 (isearch-hide-immediately nil)
4139 (isearch-search-fun-function
4140 (lambda () 'org-goto-local-search-forward-headings))
4141 (org-goto-selected-point org-goto-exit-command))
4142 (save-excursion
4143 (save-window-excursion
4144 (delete-other-windows)
4145 (and (get-buffer "*org-goto*") (kill-buffer "*org-goto*"))
4146 (switch-to-buffer
4147 (condition-case nil
4148 (make-indirect-buffer (current-buffer) "*org-goto*")
4149 (error (make-indirect-buffer (current-buffer) "*org-goto*"))))
4150 (with-output-to-temp-buffer "*Help*"
4151 (princ help))
4152 (shrink-window-if-larger-than-buffer (get-buffer-window "*Help*"))
4153 (setq buffer-read-only nil)
4154 (let ((org-startup-truncated t)
4155 (org-startup-folded nil)
4156 (org-startup-align-all-tables nil))
4157 (org-mode)
4158 (org-overview))
4159 (setq buffer-read-only t)
4160 (if (and (boundp 'org-goto-start-pos)
4161 (integer-or-marker-p org-goto-start-pos))
4162 (let ((org-show-hierarchy-above t)
4163 (org-show-siblings t)
4164 (org-show-following-heading t))
4165 (goto-char org-goto-start-pos)
4166 (and (org-invisible-p) (org-show-context)))
4167 (goto-char (point-min)))
4168 (org-beginning-of-line)
4169 (message "Select location and press RET")
4170 (use-local-map org-goto-map)
4171 (recursive-edit)
4173 (kill-buffer "*org-goto*")
4174 (cons org-goto-selected-point org-goto-exit-command)))
4176 (defvar org-goto-local-auto-isearch-map (make-sparse-keymap))
4177 (set-keymap-parent org-goto-local-auto-isearch-map isearch-mode-map)
4178 (define-key org-goto-local-auto-isearch-map "\C-i" 'isearch-other-control-char)
4179 (define-key org-goto-local-auto-isearch-map "\C-m" 'isearch-other-control-char)
4181 (defun org-goto-local-search-forward-headings (string bound noerror)
4182 "Search and make sure that anu matches are in headlines."
4183 (catch 'return
4184 (while (search-forward string bound noerror)
4185 (when (let ((context (mapcar 'car (save-match-data (org-context)))))
4186 (and (member :headline context)
4187 (not (member :tags context))))
4188 (throw 'return (point))))))
4190 (defun org-goto-local-auto-isearch ()
4191 "Start isearch."
4192 (interactive)
4193 (goto-char (point-min))
4194 (let ((keys (this-command-keys)))
4195 (when (eq (lookup-key isearch-mode-map keys) 'isearch-printing-char)
4196 (isearch-mode t)
4197 (isearch-process-search-char (string-to-char keys)))))
4199 (defun org-goto-ret (&optional arg)
4200 "Finish `org-goto' by going to the new location."
4201 (interactive "P")
4202 (setq org-goto-selected-point (point)
4203 org-goto-exit-command 'return)
4204 (throw 'exit nil))
4206 (defun org-goto-left ()
4207 "Finish `org-goto' by going to the new location."
4208 (interactive)
4209 (if (org-on-heading-p)
4210 (progn
4211 (beginning-of-line 1)
4212 (setq org-goto-selected-point (point)
4213 org-goto-exit-command 'left)
4214 (throw 'exit nil))
4215 (error "Not on a heading")))
4217 (defun org-goto-right ()
4218 "Finish `org-goto' by going to the new location."
4219 (interactive)
4220 (if (org-on-heading-p)
4221 (progn
4222 (setq org-goto-selected-point (point)
4223 org-goto-exit-command 'right)
4224 (throw 'exit nil))
4225 (error "Not on a heading")))
4227 (defun org-goto-quit ()
4228 "Finish `org-goto' without cursor motion."
4229 (interactive)
4230 (setq org-goto-selected-point nil)
4231 (setq org-goto-exit-command 'quit)
4232 (throw 'exit nil))
4234 ;;; Indirect buffer display of subtrees
4236 (defvar org-indirect-dedicated-frame nil
4237 "This is the frame being used for indirect tree display.")
4238 (defvar org-last-indirect-buffer nil)
4240 (defun org-tree-to-indirect-buffer (&optional arg)
4241 "Create indirect buffer and narrow it to current subtree.
4242 With numerical prefix ARG, go up to this level and then take that tree.
4243 If ARG is negative, go up that many levels.
4244 If `org-indirect-buffer-display' is not `new-frame', the command removes the
4245 indirect buffer previously made with this command, to avoid proliferation of
4246 indirect buffers. However, when you call the command with a `C-u' prefix, or
4247 when `org-indirect-buffer-display' is `new-frame', the last buffer
4248 is kept so that you can work with several indirect buffers at the same time.
4249 If `org-indirect-buffer-display' is `dedicated-frame', the C-u prefix also
4250 requests that a new frame be made for the new buffer, so that the dedicated
4251 frame is not changed."
4252 (interactive "P")
4253 (let ((cbuf (current-buffer))
4254 (cwin (selected-window))
4255 (pos (point))
4256 beg end level heading ibuf)
4257 (save-excursion
4258 (org-back-to-heading t)
4259 (when (numberp arg)
4260 (setq level (org-outline-level))
4261 (if (< arg 0) (setq arg (+ level arg)))
4262 (while (> (setq level (org-outline-level)) arg)
4263 (outline-up-heading 1 t)))
4264 (setq beg (point)
4265 heading (org-get-heading))
4266 (org-end-of-subtree t) (setq end (point)))
4267 (if (and (buffer-live-p org-last-indirect-buffer)
4268 (not (eq org-indirect-buffer-display 'new-frame))
4269 (not arg))
4270 (kill-buffer org-last-indirect-buffer))
4271 (setq ibuf (org-get-indirect-buffer cbuf)
4272 org-last-indirect-buffer ibuf)
4273 (cond
4274 ((or (eq org-indirect-buffer-display 'new-frame)
4275 (and arg (eq org-indirect-buffer-display 'dedicated-frame)))
4276 (select-frame (make-frame))
4277 (delete-other-windows)
4278 (switch-to-buffer ibuf)
4279 (org-set-frame-title heading))
4280 ((eq org-indirect-buffer-display 'dedicated-frame)
4281 (raise-frame
4282 (select-frame (or (and org-indirect-dedicated-frame
4283 (frame-live-p org-indirect-dedicated-frame)
4284 org-indirect-dedicated-frame)
4285 (setq org-indirect-dedicated-frame (make-frame)))))
4286 (delete-other-windows)
4287 (switch-to-buffer ibuf)
4288 (org-set-frame-title (concat "Indirect: " heading)))
4289 ((eq org-indirect-buffer-display 'current-window)
4290 (switch-to-buffer ibuf))
4291 ((eq org-indirect-buffer-display 'other-window)
4292 (pop-to-buffer ibuf))
4293 (t (error "Invalid value.")))
4294 (if (featurep 'xemacs)
4295 (save-excursion (org-mode) (turn-on-font-lock)))
4296 (narrow-to-region beg end)
4297 (show-all)
4298 (goto-char pos)
4299 (and (window-live-p cwin) (select-window cwin))))
4301 (defun org-get-indirect-buffer (&optional buffer)
4302 (setq buffer (or buffer (current-buffer)))
4303 (let ((n 1) (base (buffer-name buffer)) bname)
4304 (while (buffer-live-p
4305 (get-buffer (setq bname (concat base "-" (number-to-string n)))))
4306 (setq n (1+ n)))
4307 (condition-case nil
4308 (make-indirect-buffer buffer bname 'clone)
4309 (error (make-indirect-buffer buffer bname)))))
4311 (defun org-set-frame-title (title)
4312 "Set the title of the current frame to the string TITLE."
4313 ;; FIXME: how to name a single frame in XEmacs???
4314 (unless (featurep 'xemacs)
4315 (modify-frame-parameters (selected-frame) (list (cons 'name title)))))
4317 ;;;; Structure editing
4319 ;;; Inserting headlines
4321 (defun org-insert-heading (&optional force-heading)
4322 "Insert a new heading or item with same depth at point.
4323 If point is in a plain list and FORCE-HEADING is nil, create a new list item.
4324 If point is at the beginning of a headline, insert a sibling before the
4325 current headline. If point is not at the beginning, do not split the line,
4326 but create the new hedline after the current line."
4327 (interactive "P")
4328 (if (= (buffer-size) 0)
4329 (insert "\n* ")
4330 (when (or force-heading (not (org-insert-item)))
4331 (let* ((head (save-excursion
4332 (condition-case nil
4333 (progn
4334 (org-back-to-heading)
4335 (match-string 0))
4336 (error "*"))))
4337 (blank (cdr (assq 'heading org-blank-before-new-entry)))
4338 pos)
4339 (cond
4340 ((and (org-on-heading-p) (bolp)
4341 (or (bobp)
4342 (save-excursion (backward-char 1) (not (org-invisible-p)))))
4343 ;; insert before the current line
4344 (open-line (if blank 2 1)))
4345 ((and (bolp)
4346 (or (bobp)
4347 (save-excursion
4348 (backward-char 1) (not (org-invisible-p)))))
4349 ;; insert right here
4350 nil)
4352 ;; in the middle of the line
4353 (org-show-entry)
4354 (let ((split
4355 (org-get-alist-option org-M-RET-may-split-line 'headline))
4356 tags pos)
4357 (if (org-on-heading-p)
4358 (progn
4359 (looking-at ".*?\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)?[ \t]*$")
4360 (setq tags (and (match-end 2) (match-string 2)))
4361 (and (match-end 1)
4362 (delete-region (match-beginning 1) (match-end 1)))
4363 (setq pos (point-at-bol))
4364 (or split (end-of-line 1))
4365 (delete-horizontal-space)
4366 (newline (if blank 2 1))
4367 (when tags
4368 (save-excursion
4369 (goto-char pos)
4370 (end-of-line 1)
4371 (insert " " tags)
4372 (org-set-tags nil 'align))))
4373 (or split (end-of-line 1))
4374 (newline (if blank 2 1))))))
4375 (insert head) (just-one-space)
4376 (setq pos (point))
4377 (end-of-line 1)
4378 (unless (= (point) pos) (just-one-space) (backward-delete-char 1))
4379 (run-hooks 'org-insert-heading-hook)))))
4381 (defun org-get-heading (&optional no-tags)
4382 "Return the heading of the current entry, without the stars."
4383 (save-excursion
4384 (org-back-to-heading t)
4385 (if (looking-at
4386 (if no-tags
4387 (org-re "\\*+[ \t]+\\([^\n\r]*?\\)\\([ \t]+:[[:alnum:]:_@]+:[ \t]*\\)?$")
4388 "\\*+[ \t]+\\([^\r\n]*\\)"))
4389 (match-string 1) "")))
4391 (defun org-insert-heading-after-current ()
4392 "Insert a new heading with same level as current, after current subtree."
4393 (interactive)
4394 (org-back-to-heading)
4395 (org-insert-heading)
4396 (org-move-subtree-down)
4397 (end-of-line 1))
4399 (defun org-insert-todo-heading (arg)
4400 "Insert a new heading with the same level and TODO state as current heading.
4401 If the heading has no TODO state, or if the state is DONE, use the first
4402 state (TODO by default). Also with prefix arg, force first state."
4403 (interactive "P")
4404 (when (not (org-insert-item 'checkbox))
4405 (org-insert-heading)
4406 (save-excursion
4407 (org-back-to-heading)
4408 (outline-previous-heading)
4409 (looking-at org-todo-line-regexp))
4410 (if (or arg
4411 (not (match-beginning 2))
4412 (member (match-string 2) org-done-keywords))
4413 (insert (car org-todo-keywords-1) " ")
4414 (insert (match-string 2) " "))))
4416 (defun org-insert-subheading (arg)
4417 "Insert a new subheading and demote it.
4418 Works for outline headings and for plain lists alike."
4419 (interactive "P")
4420 (org-insert-heading arg)
4421 (cond
4422 ((org-on-heading-p) (org-do-demote))
4423 ((org-at-item-p) (org-indent-item 1))))
4425 (defun org-insert-todo-subheading (arg)
4426 "Insert a new subheading with TODO keyword or checkbox and demote it.
4427 Works for outline headings and for plain lists alike."
4428 (interactive "P")
4429 (org-insert-todo-heading arg)
4430 (cond
4431 ((org-on-heading-p) (org-do-demote))
4432 ((org-at-item-p) (org-indent-item 1))))
4434 ;;; Promotion and Demotion
4436 (defun org-promote-subtree ()
4437 "Promote the entire subtree.
4438 See also `org-promote'."
4439 (interactive)
4440 (save-excursion
4441 (org-map-tree 'org-promote))
4442 (org-fix-position-after-promote))
4444 (defun org-demote-subtree ()
4445 "Demote the entire subtree. See `org-demote'.
4446 See also `org-promote'."
4447 (interactive)
4448 (save-excursion
4449 (org-map-tree 'org-demote))
4450 (org-fix-position-after-promote))
4453 (defun org-do-promote ()
4454 "Promote the current heading higher up the tree.
4455 If the region is active in `transient-mark-mode', promote all headings
4456 in the region."
4457 (interactive)
4458 (save-excursion
4459 (if (org-region-active-p)
4460 (org-map-region 'org-promote (region-beginning) (region-end))
4461 (org-promote)))
4462 (org-fix-position-after-promote))
4464 (defun org-do-demote ()
4465 "Demote the current heading lower down the tree.
4466 If the region is active in `transient-mark-mode', demote all headings
4467 in the region."
4468 (interactive)
4469 (save-excursion
4470 (if (org-region-active-p)
4471 (org-map-region 'org-demote (region-beginning) (region-end))
4472 (org-demote)))
4473 (org-fix-position-after-promote))
4475 (defun org-fix-position-after-promote ()
4476 "Make sure that after pro/demotion cursor position is right."
4477 (let ((pos (point)))
4478 (when (save-excursion
4479 (beginning-of-line 1)
4480 (looking-at org-todo-line-regexp)
4481 (or (equal pos (match-end 1)) (equal pos (match-end 2))))
4482 (cond ((eobp) (insert " "))
4483 ((eolp) (insert " "))
4484 ((equal (char-after) ?\ ) (forward-char 1))))))
4486 (defun org-reduced-level (l)
4487 (if org-odd-levels-only (1+ (floor (/ l 2))) l))
4489 (defun org-get-valid-level (level &optional change)
4490 "Rectify a level change under the influence of `org-odd-levels-only'
4491 LEVEL is a current level, CHANGE is by how much the level should be
4492 modified. Even if CHANGE is nil, LEVEL may be returned modified because
4493 even level numbers will become the next higher odd number."
4494 (if org-odd-levels-only
4495 (cond ((or (not change) (= 0 change)) (1+ (* 2 (/ level 2))))
4496 ((> change 0) (1+ (* 2 (/ (+ level (* 2 change)) 2))))
4497 ((< change 0) (max 1 (1+ (* 2 (/ (+ level (* 2 change)) 2))))))
4498 (max 1 (+ level change))))
4500 (if (boundp 'define-obsolete-function-alias)
4501 (if (or (featurep 'xemacs) (< emacs-major-version 23))
4502 (define-obsolete-function-alias 'org-get-legal-level
4503 'org-get-valid-level)
4504 (define-obsolete-function-alias 'org-get-legal-level
4505 'org-get-valid-level "23.1")))
4507 (defun org-promote ()
4508 "Promote the current heading higher up the tree.
4509 If the region is active in `transient-mark-mode', promote all headings
4510 in the region."
4511 (org-back-to-heading t)
4512 (let* ((level (save-match-data (funcall outline-level)))
4513 (up-head (concat (make-string (org-get-valid-level level -1) ?*) " "))
4514 (diff (abs (- level (length up-head) -1))))
4515 (if (= level 1) (error "Cannot promote to level 0. UNDO to recover if necessary"))
4516 (replace-match up-head nil t)
4517 ;; Fixup tag positioning
4518 (and org-auto-align-tags (org-set-tags nil t))
4519 (if org-adapt-indentation (org-fixup-indentation (- diff)))))
4521 (defun org-demote ()
4522 "Demote the current heading lower down the tree.
4523 If the region is active in `transient-mark-mode', demote all headings
4524 in the region."
4525 (org-back-to-heading t)
4526 (let* ((level (save-match-data (funcall outline-level)))
4527 (down-head (concat (make-string (org-get-valid-level level 1) ?*) " "))
4528 (diff (abs (- level (length down-head) -1))))
4529 (replace-match down-head nil t)
4530 ;; Fixup tag positioning
4531 (and org-auto-align-tags (org-set-tags nil t))
4532 (if org-adapt-indentation (org-fixup-indentation diff))))
4534 (defun org-map-tree (fun)
4535 "Call FUN for every heading underneath the current one."
4536 (org-back-to-heading)
4537 (let ((level (funcall outline-level)))
4538 (save-excursion
4539 (funcall fun)
4540 (while (and (progn
4541 (outline-next-heading)
4542 (> (funcall outline-level) level))
4543 (not (eobp)))
4544 (funcall fun)))))
4546 (defun org-map-region (fun beg end)
4547 "Call FUN for every heading between BEG and END."
4548 (let ((org-ignore-region t))
4549 (save-excursion
4550 (setq end (copy-marker end))
4551 (goto-char beg)
4552 (if (and (re-search-forward (concat "^" outline-regexp) nil t)
4553 (< (point) end))
4554 (funcall fun))
4555 (while (and (progn
4556 (outline-next-heading)
4557 (< (point) end))
4558 (not (eobp)))
4559 (funcall fun)))))
4561 (defun org-fixup-indentation (diff)
4562 "Change the indentation in the current entry by DIFF
4563 However, if any line in the current entry has no indentation, or if it
4564 would end up with no indentation after the change, nothing at all is done."
4565 (save-excursion
4566 (let ((end (save-excursion (outline-next-heading)
4567 (point-marker)))
4568 (prohibit (if (> diff 0)
4569 "^\\S-"
4570 (concat "^ \\{0," (int-to-string (- diff)) "\\}\\S-")))
4571 col)
4572 (unless (save-excursion (end-of-line 1)
4573 (re-search-forward prohibit end t))
4574 (while (and (< (point) end)
4575 (re-search-forward "^[ \t]+" end t))
4576 (goto-char (match-end 0))
4577 (setq col (current-column))
4578 (if (< diff 0) (replace-match ""))
4579 (indent-to (+ diff col))))
4580 (move-marker end nil))))
4582 (defun org-convert-to-odd-levels ()
4583 "Convert an org-mode file with all levels allowed to one with odd levels.
4584 This will leave level 1 alone, convert level 2 to level 3, level 3 to
4585 level 5 etc."
4586 (interactive)
4587 (when (yes-or-no-p "Are you sure you want to globally change levels to odd? ")
4588 (let ((org-odd-levels-only nil) n)
4589 (save-excursion
4590 (goto-char (point-min))
4591 (while (re-search-forward "^\\*\\*+ " nil t)
4592 (setq n (- (length (match-string 0)) 2))
4593 (while (>= (setq n (1- n)) 0)
4594 (org-demote))
4595 (end-of-line 1))))))
4598 (defun org-convert-to-oddeven-levels ()
4599 "Convert an org-mode file with only odd levels to one with odd and even levels.
4600 This promotes level 3 to level 2, level 5 to level 3 etc. If the file contains a
4601 section with an even level, conversion would destroy the structure of the file. An error
4602 is signaled in this case."
4603 (interactive)
4604 (goto-char (point-min))
4605 ;; First check if there are no even levels
4606 (when (re-search-forward "^\\(\\*\\*\\)+ " nil t)
4607 (org-show-context t)
4608 (error "Not all levels are odd in this file. Conversion not possible."))
4609 (when (yes-or-no-p "Are you sure you want to globally change levels to odd-even? ")
4610 (let ((org-odd-levels-only nil) n)
4611 (save-excursion
4612 (goto-char (point-min))
4613 (while (re-search-forward "^\\*\\*+ " nil t)
4614 (setq n (/ (1- (length (match-string 0))) 2))
4615 (while (>= (setq n (1- n)) 0)
4616 (org-promote))
4617 (end-of-line 1))))))
4619 (defun org-tr-level (n)
4620 "Make N odd if required."
4621 (if org-odd-levels-only (1+ (/ n 2)) n))
4623 ;;; Vertical tree motion, cutting and pasting of subtrees
4625 (defun org-move-subtree-up (&optional arg)
4626 "Move the current subtree up past ARG headlines of the same level."
4627 (interactive "p")
4628 (org-move-subtree-down (- (prefix-numeric-value arg))))
4630 (defun org-move-subtree-down (&optional arg)
4631 "Move the current subtree down past ARG headlines of the same level."
4632 (interactive "p")
4633 (setq arg (prefix-numeric-value arg))
4634 (let ((movfunc (if (> arg 0) 'outline-get-next-sibling
4635 'outline-get-last-sibling))
4636 (ins-point (make-marker))
4637 (cnt (abs arg))
4638 beg beg0 end txt folded ne-beg ne-end ne-ins ins-end)
4639 ;; Select the tree
4640 (org-back-to-heading)
4641 (setq beg0 (point))
4642 (save-excursion
4643 (setq ne-beg (org-back-over-empty-lines))
4644 (setq beg (point)))
4645 (save-match-data
4646 (save-excursion (outline-end-of-heading)
4647 (setq folded (org-invisible-p)))
4648 (outline-end-of-subtree))
4649 (outline-next-heading)
4650 (setq ne-end (org-back-over-empty-lines))
4651 (setq end (point))
4652 (goto-char beg0)
4653 (when (and (> arg 0) (org-first-sibling-p) (< ne-end ne-beg))
4654 ;; include less whitespace
4655 (save-excursion
4656 (goto-char beg)
4657 (forward-line (- ne-beg ne-end))
4658 (setq beg (point))))
4659 ;; Find insertion point, with error handling
4660 (while (> cnt 0)
4661 (or (and (funcall movfunc) (looking-at outline-regexp))
4662 (progn (goto-char beg0)
4663 (error "Cannot move past superior level or buffer limit")))
4664 (setq cnt (1- cnt)))
4665 (if (> arg 0)
4666 ;; Moving forward - still need to move over subtree
4667 (progn (org-end-of-subtree t t)
4668 (save-excursion
4669 (org-back-over-empty-lines)
4670 (or (bolp) (newline)))))
4671 (setq ne-ins (org-back-over-empty-lines))
4672 (move-marker ins-point (point))
4673 (setq txt (buffer-substring beg end))
4674 (delete-region beg end)
4675 (outline-flag-region (1- beg) beg nil)
4676 (outline-flag-region (1- (point)) (point) nil)
4677 (insert txt)
4678 (or (bolp) (insert "\n"))
4679 (setq ins-end (point))
4680 (goto-char ins-point)
4681 (org-skip-whitespace)
4682 (when (and (< arg 0)
4683 (org-first-sibling-p)
4684 (> ne-ins ne-beg))
4685 ;; Move whitespace back to beginning
4686 (save-excursion
4687 (goto-char ins-end)
4688 (let ((kill-whole-line t))
4689 (kill-line (- ne-ins ne-beg)) (point)))
4690 (insert (make-string (- ne-ins ne-beg) ?\n)))
4691 (move-marker ins-point nil)
4692 (org-compact-display-after-subtree-move)
4693 (unless folded
4694 (org-show-entry)
4695 (show-children)
4696 (org-cycle-hide-drawers 'children))))
4698 (defvar org-subtree-clip ""
4699 "Clipboard for cut and paste of subtrees.
4700 This is actually only a copy of the kill, because we use the normal kill
4701 ring. We need it to check if the kill was created by `org-copy-subtree'.")
4703 (defvar org-subtree-clip-folded nil
4704 "Was the last copied subtree folded?
4705 This is used to fold the tree back after pasting.")
4707 (defun org-cut-subtree (&optional n)
4708 "Cut the current subtree into the clipboard.
4709 With prefix arg N, cut this many sequential subtrees.
4710 This is a short-hand for marking the subtree and then cutting it."
4711 (interactive "p")
4712 (org-copy-subtree n 'cut))
4714 (defun org-copy-subtree (&optional n cut)
4715 "Cut the current subtree into the clipboard.
4716 With prefix arg N, cut this many sequential subtrees.
4717 This is a short-hand for marking the subtree and then copying it.
4718 If CUT is non-nil, actually cut the subtree."
4719 (interactive "p")
4720 (let (beg end folded (beg0 (point)))
4721 (if (interactive-p)
4722 (org-back-to-heading nil) ; take what looks like a subtree
4723 (org-back-to-heading t)) ; take what is really there
4724 (org-back-over-empty-lines)
4725 (setq beg (point))
4726 (skip-chars-forward " \t\r\n")
4727 (save-match-data
4728 (save-excursion (outline-end-of-heading)
4729 (setq folded (org-invisible-p)))
4730 (condition-case nil
4731 (outline-forward-same-level (1- n))
4732 (error nil))
4733 (org-end-of-subtree t t))
4734 (org-back-over-empty-lines)
4735 (setq end (point))
4736 (goto-char beg0)
4737 (when (> end beg)
4738 (setq org-subtree-clip-folded folded)
4739 (if cut (kill-region beg end) (copy-region-as-kill beg end))
4740 (setq org-subtree-clip (current-kill 0))
4741 (message "%s: Subtree(s) with %d characters"
4742 (if cut "Cut" "Copied")
4743 (length org-subtree-clip)))))
4745 (defun org-paste-subtree (&optional level tree)
4746 "Paste the clipboard as a subtree, with modification of headline level.
4747 The entire subtree is promoted or demoted in order to match a new headline
4748 level. By default, the new level is derived from the visible headings
4749 before and after the insertion point, and taken to be the inferior headline
4750 level of the two. So if the previous visible heading is level 3 and the
4751 next is level 4 (or vice versa), level 4 will be used for insertion.
4752 This makes sure that the subtree remains an independent subtree and does
4753 not swallow low level entries.
4755 You can also force a different level, either by using a numeric prefix
4756 argument, or by inserting the heading marker by hand. For example, if the
4757 cursor is after \"*****\", then the tree will be shifted to level 5.
4759 If you want to insert the tree as is, just use \\[yank].
4761 If optional TREE is given, use this text instead of the kill ring."
4762 (interactive "P")
4763 (unless (org-kill-is-subtree-p tree)
4764 (error "%s"
4765 (substitute-command-keys
4766 "The kill is not a (set of) tree(s) - please use \\[yank] to yank anyway")))
4767 (let* ((txt (or tree (and kill-ring (current-kill 0))))
4768 (^re (concat "^\\(" outline-regexp "\\)"))
4769 (re (concat "\\(" outline-regexp "\\)"))
4770 (^re_ (concat "\\(\\*+\\)[ \t]*"))
4772 (old-level (if (string-match ^re txt)
4773 (- (match-end 0) (match-beginning 0) 1)
4774 -1))
4775 (force-level (cond (level (prefix-numeric-value level))
4776 ((string-match
4777 ^re_ (buffer-substring (point-at-bol) (point)))
4778 (- (match-end 1) (match-beginning 1)))
4779 (t nil)))
4780 (previous-level (save-excursion
4781 (condition-case nil
4782 (progn
4783 (outline-previous-visible-heading 1)
4784 (if (looking-at re)
4785 (- (match-end 0) (match-beginning 0) 1)
4787 (error 1))))
4788 (next-level (save-excursion
4789 (condition-case nil
4790 (progn
4791 (or (looking-at outline-regexp)
4792 (outline-next-visible-heading 1))
4793 (if (looking-at re)
4794 (- (match-end 0) (match-beginning 0) 1)
4796 (error 1))))
4797 (new-level (or force-level (max previous-level next-level)))
4798 (shift (if (or (= old-level -1)
4799 (= new-level -1)
4800 (= old-level new-level))
4802 (- new-level old-level)))
4803 (delta (if (> shift 0) -1 1))
4804 (func (if (> shift 0) 'org-demote 'org-promote))
4805 (org-odd-levels-only nil)
4806 beg end)
4807 ;; Remove the forced level indicator
4808 (if force-level
4809 (delete-region (point-at-bol) (point)))
4810 ;; Paste
4811 (beginning-of-line 1)
4812 (org-back-over-empty-lines)
4813 (setq beg (point))
4814 (insert-before-markers txt)
4815 (unless (string-match "\n\\'" txt) (insert "\n"))
4816 (setq end (point))
4817 (goto-char beg)
4818 (skip-chars-forward " \t\n\r")
4819 (setq beg (point))
4820 ;; Shift if necessary
4821 (unless (= shift 0)
4822 (save-restriction
4823 (narrow-to-region beg end)
4824 (while (not (= shift 0))
4825 (org-map-region func (point-min) (point-max))
4826 (setq shift (+ delta shift)))
4827 (goto-char (point-min))))
4828 (when (interactive-p)
4829 (message "Clipboard pasted as level %d subtree" new-level))
4830 (if (and kill-ring
4831 (eq org-subtree-clip (current-kill 0))
4832 org-subtree-clip-folded)
4833 ;; The tree was folded before it was killed/copied
4834 (hide-subtree))))
4836 (defun org-kill-is-subtree-p (&optional txt)
4837 "Check if the current kill is an outline subtree, or a set of trees.
4838 Returns nil if kill does not start with a headline, or if the first
4839 headline level is not the largest headline level in the tree.
4840 So this will actually accept several entries of equal levels as well,
4841 which is OK for `org-paste-subtree'.
4842 If optional TXT is given, check this string instead of the current kill."
4843 (let* ((kill (or txt (and kill-ring (current-kill 0)) ""))
4844 (start-level (and kill
4845 (string-match (concat "\\`\\([ \t\n\r]*?\n\\)?\\("
4846 org-outline-regexp "\\)")
4847 kill)
4848 (- (match-end 2) (match-beginning 2) 1)))
4849 (re (concat "^" org-outline-regexp))
4850 (start (1+ (match-beginning 2))))
4851 (if (not start-level)
4852 (progn
4853 nil) ;; does not even start with a heading
4854 (catch 'exit
4855 (while (setq start (string-match re kill (1+ start)))
4856 (when (< (- (match-end 0) (match-beginning 0) 1) start-level)
4857 (throw 'exit nil)))
4858 t))))
4860 (defun org-narrow-to-subtree ()
4861 "Narrow buffer to the current subtree."
4862 (interactive)
4863 (save-excursion
4864 (save-match-data
4865 (narrow-to-region
4866 (progn (org-back-to-heading) (point))
4867 (progn (org-end-of-subtree t t) (point))))))
4870 ;;; Outline Sorting
4872 (defun org-sort (with-case)
4873 "Call `org-sort-entries-or-items' or `org-table-sort-lines'.
4874 Optional argument WITH-CASE means sort case-sensitively."
4875 (interactive "P")
4876 (if (org-at-table-p)
4877 (org-call-with-arg 'org-table-sort-lines with-case)
4878 (org-call-with-arg 'org-sort-entries-or-items with-case)))
4880 (defun org-sort-remove-invisible (s)
4881 (remove-text-properties 0 (length s) org-rm-props s)
4882 (while (string-match org-bracket-link-regexp s)
4883 (setq s (replace-match (if (match-end 2)
4884 (match-string 3 s)
4885 (match-string 1 s)) t t s)))
4888 (defvar org-priority-regexp) ; defined later in the file
4890 (defun org-sort-entries-or-items (&optional with-case sorting-type getkey-func property)
4891 "Sort entries on a certain level of an outline tree.
4892 If there is an active region, the entries in the region are sorted.
4893 Else, if the cursor is before the first entry, sort the top-level items.
4894 Else, the children of the entry at point are sorted.
4896 Sorting can be alphabetically, numerically, and by date/time as given by
4897 the first time stamp in the entry. The command prompts for the sorting
4898 type unless it has been given to the function through the SORTING-TYPE
4899 argument, which needs to a character, any of (?n ?N ?a ?A ?t ?T ?p ?P ?f ?F).
4900 If the SORTING-TYPE is ?f or ?F, then GETKEY-FUNC specifies a function to be
4901 called with point at the beginning of the record. It must return either
4902 a string or a number that should serve as the sorting key for that record.
4904 Comparing entries ignores case by default. However, with an optional argument
4905 WITH-CASE, the sorting considers case as well."
4906 (interactive "P")
4907 (let ((case-func (if with-case 'identity 'downcase))
4908 start beg end stars re re2
4909 txt what tmp plain-list-p)
4910 ;; Find beginning and end of region to sort
4911 (cond
4912 ((org-region-active-p)
4913 ;; we will sort the region
4914 (setq end (region-end)
4915 what "region")
4916 (goto-char (region-beginning))
4917 (if (not (org-on-heading-p)) (outline-next-heading))
4918 (setq start (point)))
4919 ((org-at-item-p)
4920 ;; we will sort this plain list
4921 (org-beginning-of-item-list) (setq start (point))
4922 (org-end-of-item-list) (setq end (point))
4923 (goto-char start)
4924 (setq plain-list-p t
4925 what "plain list"))
4926 ((or (org-on-heading-p)
4927 (condition-case nil (progn (org-back-to-heading) t) (error nil)))
4928 ;; we will sort the children of the current headline
4929 (org-back-to-heading)
4930 (setq start (point)
4931 end (progn (org-end-of-subtree t t)
4932 (org-back-over-empty-lines)
4933 (point))
4934 what "children")
4935 (goto-char start)
4936 (show-subtree)
4937 (outline-next-heading))
4939 ;; we will sort the top-level entries in this file
4940 (goto-char (point-min))
4941 (or (org-on-heading-p) (outline-next-heading))
4942 (setq start (point) end (point-max) what "top-level")
4943 (goto-char start)
4944 (show-all)))
4946 (setq beg (point))
4947 (if (>= beg end) (error "Nothing to sort"))
4949 (unless plain-list-p
4950 (looking-at "\\(\\*+\\)")
4951 (setq stars (match-string 1)
4952 re (concat "^" (regexp-quote stars) " +")
4953 re2 (concat "^" (regexp-quote (substring stars 0 -1)) "[^*]")
4954 txt (buffer-substring beg end))
4955 (if (not (equal (substring txt -1) "\n")) (setq txt (concat txt "\n")))
4956 (if (and (not (equal stars "*")) (string-match re2 txt))
4957 (error "Region to sort contains a level above the first entry")))
4959 (unless sorting-type
4960 (message
4961 (if plain-list-p
4962 "Sort %s: [a]lpha [n]umeric [t]ime [f]unc A/N/T/F means reversed:"
4963 "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:")
4964 what)
4965 (setq sorting-type (read-char-exclusive))
4967 (and (= (downcase sorting-type) ?f)
4968 (setq getkey-func
4969 (completing-read "Sort using function: "
4970 obarray 'fboundp t nil nil))
4971 (setq getkey-func (intern getkey-func)))
4973 (and (= (downcase sorting-type) ?r)
4974 (setq property
4975 (completing-read "Property: "
4976 (mapcar 'list (org-buffer-property-keys t))
4977 nil t))))
4979 (message "Sorting entries...")
4981 (save-restriction
4982 (narrow-to-region start end)
4984 (let ((dcst (downcase sorting-type))
4985 (now (current-time)))
4986 (sort-subr
4987 (/= dcst sorting-type)
4988 ;; This function moves to the beginning character of the "record" to
4989 ;; be sorted.
4990 (if plain-list-p
4991 (lambda nil
4992 (if (org-at-item-p) t (goto-char (point-max))))
4993 (lambda nil
4994 (if (re-search-forward re nil t)
4995 (goto-char (match-beginning 0))
4996 (goto-char (point-max)))))
4997 ;; This function moves to the last character of the "record" being
4998 ;; sorted.
4999 (if plain-list-p
5000 'org-end-of-item
5001 (lambda nil
5002 (save-match-data
5003 (condition-case nil
5004 (outline-forward-same-level 1)
5005 (error
5006 (goto-char (point-max)))))))
5008 ;; This function returns the value that gets sorted against.
5009 (if plain-list-p
5010 (lambda nil
5011 (when (looking-at "[ \t]*[-+*0-9.)]+[ \t]+")
5012 (cond
5013 ((= dcst ?n)
5014 (string-to-number (buffer-substring (match-end 0)
5015 (point-at-eol))))
5016 ((= dcst ?a)
5017 (buffer-substring (match-end 0) (point-at-eol)))
5018 ((= dcst ?t)
5019 (if (re-search-forward org-ts-regexp
5020 (point-at-eol) t)
5021 (org-time-string-to-time (match-string 0))
5022 now))
5023 ((= dcst ?f)
5024 (if getkey-func
5025 (progn
5026 (setq tmp (funcall getkey-func))
5027 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5028 tmp)
5029 (error "Invalid key function `%s'" getkey-func)))
5030 (t (error "Invalid sorting type `%c'" sorting-type)))))
5031 (lambda nil
5032 (cond
5033 ((= dcst ?n)
5034 (if (looking-at outline-regexp)
5035 (string-to-number (buffer-substring (match-end 0)
5036 (point-at-eol)))
5037 nil))
5038 ((= dcst ?a)
5039 (funcall case-func (buffer-substring (point-at-bol)
5040 (point-at-eol))))
5041 ((= dcst ?t)
5042 (if (re-search-forward org-ts-regexp
5043 (save-excursion
5044 (forward-line 2)
5045 (point)) t)
5046 (org-time-string-to-time (match-string 0))
5047 now))
5048 ((= dcst ?p)
5049 (if (re-search-forward org-priority-regexp (point-at-eol) t)
5050 (string-to-char (match-string 2))
5051 org-default-priority))
5052 ((= dcst ?r)
5053 (or (org-entry-get nil property) ""))
5054 ((= dcst ?o)
5055 (if (looking-at org-complex-heading-regexp)
5056 (- 9999 (length (member (match-string 2)
5057 org-todo-keywords-1)))))
5058 ((= dcst ?f)
5059 (if getkey-func
5060 (progn
5061 (setq tmp (funcall getkey-func))
5062 (if (stringp tmp) (setq tmp (funcall case-func tmp)))
5063 tmp)
5064 (error "Invalid key function `%s'" getkey-func)))
5065 (t (error "Invalid sorting type `%c'" sorting-type)))))
5067 (cond
5068 ((= dcst ?a) 'string<)
5069 ((= dcst ?t) 'time-less-p)
5070 (t nil)))))
5071 (message "Sorting entries...done")))
5073 (defun org-do-sort (table what &optional with-case sorting-type)
5074 "Sort TABLE of WHAT according to SORTING-TYPE.
5075 The user will be prompted for the SORTING-TYPE if the call to this
5076 function does not specify it. WHAT is only for the prompt, to indicate
5077 what is being sorted. The sorting key will be extracted from
5078 the car of the elements of the table.
5079 If WITH-CASE is non-nil, the sorting will be case-sensitive."
5080 (unless sorting-type
5081 (message
5082 "Sort %s: [a]lphabetic. [n]umeric. [t]ime. A/N/T means reversed:"
5083 what)
5084 (setq sorting-type (read-char-exclusive)))
5085 (let ((dcst (downcase sorting-type))
5086 extractfun comparefun)
5087 ;; Define the appropriate functions
5088 (cond
5089 ((= dcst ?n)
5090 (setq extractfun 'string-to-number
5091 comparefun (if (= dcst sorting-type) '< '>)))
5092 ((= dcst ?a)
5093 (setq extractfun (if with-case (lambda(x) (org-sort-remove-invisible x))
5094 (lambda(x) (downcase (org-sort-remove-invisible x))))
5095 comparefun (if (= dcst sorting-type)
5096 'string<
5097 (lambda (a b) (and (not (string< a b))
5098 (not (string= a b)))))))
5099 ((= dcst ?t)
5100 (setq extractfun
5101 (lambda (x)
5102 (if (string-match org-ts-regexp x)
5103 (time-to-seconds
5104 (org-time-string-to-time (match-string 0 x)))
5106 comparefun (if (= dcst sorting-type) '< '>)))
5107 (t (error "Invalid sorting type `%c'" sorting-type)))
5109 (sort (mapcar (lambda (x) (cons (funcall extractfun (car x)) (cdr x)))
5110 table)
5111 (lambda (a b) (funcall comparefun (car a) (car b))))))
5113 ;;;; Plain list items, including checkboxes
5115 ;;; Plain list items
5117 (defun org-at-item-p ()
5118 "Is point in a line starting a hand-formatted item?"
5119 (let ((llt org-plain-list-ordered-item-terminator))
5120 (save-excursion
5121 (goto-char (point-at-bol))
5122 (looking-at
5123 (cond
5124 ((eq llt t) "\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5125 ((= llt ?.) "\\([ \t]*\\([-+]\\|\\([0-9]+\\.\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5126 ((= llt ?\)) "\\([ \t]*\\([-+]\\|\\([0-9]+))\\)\\|[ \t]+\\*\\)\\( \\|$\\)")
5127 (t (error "Invalid value of `org-plain-list-ordered-item-terminator'")))))))
5129 (defun org-in-item-p ()
5130 "It the cursor inside a plain list item.
5131 Does not have to be the first line."
5132 (save-excursion
5133 (condition-case nil
5134 (progn
5135 (org-beginning-of-item)
5136 (org-at-item-p)
5138 (error nil))))
5140 (defun org-insert-item (&optional checkbox)
5141 "Insert a new item at the current level.
5142 Return t when things worked, nil when we are not in an item."
5143 (when (save-excursion
5144 (condition-case nil
5145 (progn
5146 (org-beginning-of-item)
5147 (org-at-item-p)
5148 (if (org-invisible-p) (error "Invisible item"))
5150 (error nil)))
5151 (let* ((bul (match-string 0))
5152 (eow (save-excursion (beginning-of-line 1) (looking-at "[ \t]*")
5153 (match-end 0)))
5154 (blank (cdr (assq 'plain-list-item org-blank-before-new-entry)))
5155 pos)
5156 (cond
5157 ((and (org-at-item-p) (<= (point) eow))
5158 ;; before the bullet
5159 (beginning-of-line 1)
5160 (open-line (if blank 2 1)))
5161 ((<= (point) eow)
5162 (beginning-of-line 1))
5164 (unless (org-get-alist-option org-M-RET-may-split-line 'item)
5165 (end-of-line 1)
5166 (delete-horizontal-space))
5167 (newline (if blank 2 1))))
5168 (insert bul (if checkbox "[ ]" ""))
5169 (just-one-space)
5170 (setq pos (point))
5171 (end-of-line 1)
5172 (unless (= (point) pos) (just-one-space) (backward-delete-char 1)))
5173 (org-maybe-renumber-ordered-list)
5174 (and checkbox (org-update-checkbox-count-maybe))
5177 ;;; Checkboxes
5179 (defun org-at-item-checkbox-p ()
5180 "Is point at a line starting a plain-list item with a checklet?"
5181 (and (org-at-item-p)
5182 (save-excursion
5183 (goto-char (match-end 0))
5184 (skip-chars-forward " \t")
5185 (looking-at "\\[[- X]\\]"))))
5187 (defun org-toggle-checkbox (&optional arg)
5188 "Toggle the checkbox in the current line."
5189 (interactive "P")
5190 (catch 'exit
5191 (let (beg end status (firstnew 'unknown))
5192 (cond
5193 ((org-region-active-p)
5194 (setq beg (region-beginning) end (region-end)))
5195 ((org-on-heading-p)
5196 (setq beg (point) end (save-excursion (outline-next-heading) (point))))
5197 ((org-at-item-checkbox-p)
5198 (let ((pos (point)))
5199 (replace-match
5200 (cond (arg "[-]")
5201 ((member (match-string 0) '("[ ]" "[-]")) "[X]")
5202 (t "[ ]"))
5203 t t)
5204 (goto-char pos))
5205 (throw 'exit t))
5206 (t (error "Not at a checkbox or heading, and no active region")))
5207 (save-excursion
5208 (goto-char beg)
5209 (while (< (point) end)
5210 (when (org-at-item-checkbox-p)
5211 (setq status (equal (match-string 0) "[X]"))
5212 (when (eq firstnew 'unknown)
5213 (setq firstnew (not status)))
5214 (replace-match
5215 (if (if arg (not status) firstnew) "[X]" "[ ]") t t))
5216 (beginning-of-line 2)))))
5217 (org-update-checkbox-count-maybe))
5219 (defun org-update-checkbox-count-maybe ()
5220 "Update checkbox statistics unless turned off by user."
5221 (when org-provide-checkbox-statistics
5222 (org-update-checkbox-count)))
5224 (defun org-update-checkbox-count (&optional all)
5225 "Update the checkbox statistics in the current section.
5226 This will find all statistic cookies like [57%] and [6/12] and update them
5227 with the current numbers. With optional prefix argument ALL, do this for
5228 the whole buffer."
5229 (interactive "P")
5230 (save-excursion
5231 (let* ((buffer-invisibility-spec (org-inhibit-invisibility)) ; Emacs 21
5232 (beg (condition-case nil
5233 (progn (outline-back-to-heading) (point))
5234 (error (point-min))))
5235 (end (move-marker (make-marker)
5236 (progn (outline-next-heading) (point))))
5237 (re "\\(\\(\\[[0-9]*%\\]\\)\\|\\(\\[[0-9]*/[0-9]*\\]\\)\\)")
5238 (re-box "^[ \t]*\\([-+*]\\|[0-9]+[.)]\\) +\\(\\[[- X]\\]\\)")
5239 (re-find (concat re "\\|" re-box))
5240 beg-cookie end-cookie is-percent c-on c-off lim
5241 eline curr-ind next-ind continue-from startsearch
5242 (cstat 0)
5244 (when all
5245 (goto-char (point-min))
5246 (outline-next-heading)
5247 (setq beg (point) end (point-max)))
5248 (goto-char end)
5249 ;; find each statistic cookie
5250 (while (re-search-backward re-find beg t)
5251 (setq beg-cookie (match-beginning 1)
5252 end-cookie (match-end 1)
5253 cstat (+ cstat (if end-cookie 1 0))
5254 startsearch (point-at-eol)
5255 continue-from (point-at-bol)
5256 is-percent (match-beginning 2)
5257 lim (cond
5258 ((org-on-heading-p) (outline-next-heading) (point))
5259 ((org-at-item-p) (org-end-of-item) (point))
5260 (t nil))
5261 c-on 0
5262 c-off 0)
5263 (when lim
5264 ;; find first checkbox for this cookie and gather
5265 ;; statistics from all that are at this indentation level
5266 (goto-char startsearch)
5267 (if (re-search-forward re-box lim t)
5268 (progn
5269 (org-beginning-of-item)
5270 (setq curr-ind (org-get-indentation))
5271 (setq next-ind curr-ind)
5272 (while (and (bolp) (org-at-item-p) (= curr-ind next-ind))
5273 (save-excursion (end-of-line) (setq eline (point)))
5274 (if (re-search-forward re-box eline t)
5275 (if (member (match-string 2) '("[ ]" "[-]"))
5276 (setq c-off (1+ c-off))
5277 (setq c-on (1+ c-on))
5280 (org-end-of-item)
5281 (setq next-ind (org-get-indentation))
5283 (goto-char continue-from)
5284 ;; update cookie
5285 (when end-cookie
5286 (delete-region beg-cookie end-cookie)
5287 (goto-char beg-cookie)
5288 (insert
5289 (if is-percent
5290 (format "[%d%%]" (/ (* 100 c-on) (max 1 (+ c-on c-off))))
5291 (format "[%d/%d]" c-on (+ c-on c-off)))))
5292 ;; update items checkbox if it has one
5293 (when (org-at-item-p)
5294 (org-beginning-of-item)
5295 (when (and (> (+ c-on c-off) 0)
5296 (re-search-forward re-box (point-at-eol) t))
5297 (setq beg-cookie (match-beginning 2)
5298 end-cookie (match-end 2))
5299 (delete-region beg-cookie end-cookie)
5300 (goto-char beg-cookie)
5301 (cond ((= c-off 0) (insert "[X]"))
5302 ((= c-on 0) (insert "[ ]"))
5303 (t (insert "[-]")))
5305 (goto-char continue-from))
5306 (when (interactive-p)
5307 (message "Checkbox satistics updated %s (%d places)"
5308 (if all "in entire file" "in current outline entry") cstat)))))
5310 (defun org-get-checkbox-statistics-face ()
5311 "Select the face for checkbox statistics.
5312 The face will be `org-done' when all relevant boxes are checked. Otherwise
5313 it will be `org-todo'."
5314 (if (match-end 1)
5315 (if (equal (match-string 1) "100%") 'org-done 'org-todo)
5316 (if (and (> (match-end 2) (match-beginning 2))
5317 (equal (match-string 2) (match-string 3)))
5318 'org-done
5319 'org-todo)))
5321 (defun org-get-indentation (&optional line)
5322 "Get the indentation of the current line, interpreting tabs.
5323 When LINE is given, assume it represents a line and compute its indentation."
5324 (if line
5325 (if (string-match "^ *" (org-remove-tabs line))
5326 (match-end 0))
5327 (save-excursion
5328 (beginning-of-line 1)
5329 (skip-chars-forward " \t")
5330 (current-column))))
5332 (defun org-remove-tabs (s &optional width)
5333 "Replace tabulators in S with spaces.
5334 Assumes that s is a single line, starting in column 0."
5335 (setq width (or width tab-width))
5336 (while (string-match "\t" s)
5337 (setq s (replace-match
5338 (make-string
5339 (- (* width (/ (+ (match-beginning 0) width) width))
5340 (match-beginning 0)) ?\ )
5341 t t s)))
5344 (defun org-fix-indentation (line ind)
5345 "Fix indentation in LINE.
5346 IND is a cons cell with target and minimum indentation.
5347 If the current indenation in LINE is smaller than the minimum,
5348 leave it alone. If it is larger than ind, set it to the target."
5349 (let* ((l (org-remove-tabs line))
5350 (i (org-get-indentation l))
5351 (i1 (car ind)) (i2 (cdr ind)))
5352 (if (>= i i2) (setq l (substring line i2)))
5353 (if (> i1 0)
5354 (concat (make-string i1 ?\ ) l)
5355 l)))
5357 (defun org-beginning-of-item ()
5358 "Go to the beginning of the current hand-formatted item.
5359 If the cursor is not in an item, throw an error."
5360 (interactive)
5361 (let ((pos (point))
5362 (limit (save-excursion
5363 (condition-case nil
5364 (progn
5365 (org-back-to-heading)
5366 (beginning-of-line 2) (point))
5367 (error (point-min)))))
5368 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5369 ind ind1)
5370 (if (org-at-item-p)
5371 (beginning-of-line 1)
5372 (beginning-of-line 1)
5373 (skip-chars-forward " \t")
5374 (setq ind (current-column))
5375 (if (catch 'exit
5376 (while t
5377 (beginning-of-line 0)
5378 (if (or (bobp) (< (point) limit)) (throw 'exit nil))
5380 (if (looking-at "[ \t]*$")
5381 (setq ind1 ind-empty)
5382 (skip-chars-forward " \t")
5383 (setq ind1 (current-column)))
5384 (if (< ind1 ind)
5385 (progn (beginning-of-line 1) (throw 'exit (org-at-item-p))))))
5387 (goto-char pos)
5388 (error "Not in an item")))))
5390 (defun org-end-of-item ()
5391 "Go to the end of the current hand-formatted item.
5392 If the cursor is not in an item, throw an error."
5393 (interactive)
5394 (let* ((pos (point))
5395 ind1
5396 (ind-empty (if org-empty-line-terminates-plain-lists 0 10000))
5397 (limit (save-excursion (outline-next-heading) (point)))
5398 (ind (save-excursion
5399 (org-beginning-of-item)
5400 (skip-chars-forward " \t")
5401 (current-column)))
5402 (end (catch 'exit
5403 (while t
5404 (beginning-of-line 2)
5405 (if (eobp) (throw 'exit (point)))
5406 (if (>= (point) limit) (throw 'exit (point-at-bol)))
5407 (if (looking-at "[ \t]*$")
5408 (setq ind1 ind-empty)
5409 (skip-chars-forward " \t")
5410 (setq ind1 (current-column)))
5411 (if (<= ind1 ind)
5412 (throw 'exit (point-at-bol)))))))
5413 (if end
5414 (goto-char end)
5415 (goto-char pos)
5416 (error "Not in an item"))))
5418 (defun org-next-item ()
5419 "Move to the beginning of the next item in the current plain list.
5420 Error if not at a plain list, or if this is the last item in the list."
5421 (interactive)
5422 (let (ind ind1 (pos (point)))
5423 (org-beginning-of-item)
5424 (setq ind (org-get-indentation))
5425 (org-end-of-item)
5426 (setq ind1 (org-get-indentation))
5427 (unless (and (org-at-item-p) (= ind ind1))
5428 (goto-char pos)
5429 (error "On last item"))))
5431 (defun org-previous-item ()
5432 "Move to the beginning of the previous item in the current plain list.
5433 Error if not at a plain list, or if this is the first item in the list."
5434 (interactive)
5435 (let (beg ind ind1 (pos (point)))
5436 (org-beginning-of-item)
5437 (setq beg (point))
5438 (setq ind (org-get-indentation))
5439 (goto-char beg)
5440 (catch 'exit
5441 (while t
5442 (beginning-of-line 0)
5443 (if (looking-at "[ \t]*$")
5445 (if (<= (setq ind1 (org-get-indentation)) ind)
5446 (throw 'exit t)))))
5447 (condition-case nil
5448 (if (or (not (org-at-item-p))
5449 (< ind1 (1- ind)))
5450 (error "")
5451 (org-beginning-of-item))
5452 (error (goto-char pos)
5453 (error "On first item")))))
5455 (defun org-first-list-item-p ()
5456 "Is this heading the item in a plain list?"
5457 (unless (org-at-item-p)
5458 (error "Not at a plain list item"))
5459 (org-beginning-of-item)
5460 (= (point) (save-excursion (org-beginning-of-item-list))))
5462 (defun org-move-item-down ()
5463 "Move the plain list item at point down, i.e. swap with following item.
5464 Subitems (items with larger indentation) are considered part of the item,
5465 so this really moves item trees."
5466 (interactive)
5467 (let (beg beg0 end end0 ind ind1 (pos (point)) txt ne-end ne-beg)
5468 (org-beginning-of-item)
5469 (setq beg0 (point))
5470 (save-excursion
5471 (setq ne-beg (org-back-over-empty-lines))
5472 (setq beg (point)))
5473 (goto-char beg0)
5474 (setq ind (org-get-indentation))
5475 (org-end-of-item)
5476 (setq end0 (point))
5477 (setq ind1 (org-get-indentation))
5478 (setq ne-end (org-back-over-empty-lines))
5479 (setq end (point))
5480 (goto-char beg0)
5481 (when (and (org-first-list-item-p) (< ne-end ne-beg))
5482 ;; include less whitespace
5483 (save-excursion
5484 (goto-char beg)
5485 (forward-line (- ne-beg ne-end))
5486 (setq beg (point))))
5487 (goto-char end0)
5488 (if (and (org-at-item-p) (= ind ind1))
5489 (progn
5490 (org-end-of-item)
5491 (org-back-over-empty-lines)
5492 (setq txt (buffer-substring beg end))
5493 (save-excursion
5494 (delete-region beg end))
5495 (setq pos (point))
5496 (insert txt)
5497 (goto-char pos) (org-skip-whitespace)
5498 (org-maybe-renumber-ordered-list))
5499 (goto-char pos)
5500 (error "Cannot move this item further down"))))
5502 (defun org-move-item-up (arg)
5503 "Move the plain list item at point up, i.e. swap with previous item.
5504 Subitems (items with larger indentation) are considered part of the item,
5505 so this really moves item trees."
5506 (interactive "p")
5507 (let (beg beg0 end ind ind1 (pos (point)) txt
5508 ne-beg ne-ins ins-end)
5509 (org-beginning-of-item)
5510 (setq beg0 (point))
5511 (setq ind (org-get-indentation))
5512 (save-excursion
5513 (setq ne-beg (org-back-over-empty-lines))
5514 (setq beg (point)))
5515 (goto-char beg0)
5516 (org-end-of-item)
5517 (setq end (point))
5518 (goto-char beg0)
5519 (catch 'exit
5520 (while t
5521 (beginning-of-line 0)
5522 (if (looking-at "[ \t]*$")
5523 (if org-empty-line-terminates-plain-lists
5524 (progn
5525 (goto-char pos)
5526 (error "Cannot move this item further up"))
5527 nil)
5528 (if (<= (setq ind1 (org-get-indentation)) ind)
5529 (throw 'exit t)))))
5530 (condition-case nil
5531 (org-beginning-of-item)
5532 (error (goto-char beg)
5533 (error "Cannot move this item further up")))
5534 (setq ind1 (org-get-indentation))
5535 (if (and (org-at-item-p) (= ind ind1))
5536 (progn
5537 (setq ne-ins (org-back-over-empty-lines))
5538 (setq txt (buffer-substring beg end))
5539 (save-excursion
5540 (delete-region beg end))
5541 (setq pos (point))
5542 (insert txt)
5543 (setq ins-end (point))
5544 (goto-char pos) (org-skip-whitespace)
5546 (when (and (org-first-list-item-p) (> ne-ins ne-beg))
5547 ;; Move whitespace back to beginning
5548 (save-excursion
5549 (goto-char ins-end)
5550 (let ((kill-whole-line t))
5551 (kill-line (- ne-ins ne-beg)) (point)))
5552 (insert (make-string (- ne-ins ne-beg) ?\n)))
5554 (org-maybe-renumber-ordered-list))
5555 (goto-char pos)
5556 (error "Cannot move this item further up"))))
5558 (defun org-maybe-renumber-ordered-list ()
5559 "Renumber the ordered list at point if setup allows it.
5560 This tests the user option `org-auto-renumber-ordered-lists' before
5561 doing the renumbering."
5562 (interactive)
5563 (when (and org-auto-renumber-ordered-lists
5564 (org-at-item-p))
5565 (if (match-beginning 3)
5566 (org-renumber-ordered-list 1)
5567 (org-fix-bullet-type))))
5569 (defun org-maybe-renumber-ordered-list-safe ()
5570 (condition-case nil
5571 (save-excursion
5572 (org-maybe-renumber-ordered-list))
5573 (error nil)))
5575 (defun org-cycle-list-bullet (&optional which)
5576 "Cycle through the different itemize/enumerate bullets.
5577 This cycle the entire list level through the sequence:
5579 `-' -> `+' -> `*' -> `1.' -> `1)'
5581 If WHICH is a string, use that as the new bullet. If WHICH is an integer,
5582 0 meand `-', 1 means `+' etc."
5583 (interactive "P")
5584 (org-preserve-lc
5585 (org-beginning-of-item-list)
5586 (org-at-item-p)
5587 (beginning-of-line 1)
5588 (let ((current (match-string 0))
5589 (prevp (eq which 'previous))
5590 new)
5591 (setq new (cond
5592 ((and (numberp which)
5593 (nth (1- which) '("-" "+" "*" "1." "1)"))))
5594 ((string-match "-" current) (if prevp "1)" "+"))
5595 ((string-match "\\+" current)
5596 (if prevp "-" (if (looking-at "\\S-") "1." "*")))
5597 ((string-match "\\*" current) (if prevp "+" "1."))
5598 ((string-match "\\." current) (if prevp "*" "1)"))
5599 ((string-match ")" current) (if prevp "1." "-"))
5600 (t (error "This should not happen"))))
5601 (and (looking-at "\\([ \t]*\\)\\S-+") (replace-match (concat "\\1" new)))
5602 (org-fix-bullet-type)
5603 (org-maybe-renumber-ordered-list))))
5605 (defun org-get-string-indentation (s)
5606 "What indentation has S due to SPACE and TAB at the beginning of the string?"
5607 (let ((n -1) (i 0) (w tab-width) c)
5608 (catch 'exit
5609 (while (< (setq n (1+ n)) (length s))
5610 (setq c (aref s n))
5611 (cond ((= c ?\ ) (setq i (1+ i)))
5612 ((= c ?\t) (setq i (* (/ (+ w i) w) w)))
5613 (t (throw 'exit t)))))
5616 (defun org-renumber-ordered-list (arg)
5617 "Renumber an ordered plain list.
5618 Cursor needs to be in the first line of an item, the line that starts
5619 with something like \"1.\" or \"2)\"."
5620 (interactive "p")
5621 (unless (and (org-at-item-p)
5622 (match-beginning 3))
5623 (error "This is not an ordered list"))
5624 (let ((line (org-current-line))
5625 (col (current-column))
5626 (ind (org-get-string-indentation
5627 (buffer-substring (point-at-bol) (match-beginning 3))))
5628 ;; (term (substring (match-string 3) -1))
5629 ind1 (n (1- arg))
5630 fmt)
5631 ;; find where this list begins
5632 (org-beginning-of-item-list)
5633 (looking-at "[ \t]*[0-9]+\\([.)]\\)")
5634 (setq fmt (concat "%d" (match-string 1)))
5635 (beginning-of-line 0)
5636 ;; walk forward and replace these numbers
5637 (catch 'exit
5638 (while t
5639 (catch 'next
5640 (beginning-of-line 2)
5641 (if (eobp) (throw 'exit nil))
5642 (if (looking-at "[ \t]*$") (throw 'next nil))
5643 (skip-chars-forward " \t") (setq ind1 (current-column))
5644 (if (> ind1 ind) (throw 'next t))
5645 (if (< ind1 ind) (throw 'exit t))
5646 (if (not (org-at-item-p)) (throw 'exit nil))
5647 (delete-region (match-beginning 2) (match-end 2))
5648 (goto-char (match-beginning 2))
5649 (insert (format fmt (setq n (1+ n)))))))
5650 (goto-line line)
5651 (org-move-to-column col)))
5653 (defun org-fix-bullet-type ()
5654 "Make sure all items in this list have the same bullet as the firsst item."
5655 (interactive)
5656 (unless (org-at-item-p) (error "This is not a list"))
5657 (let ((line (org-current-line))
5658 (col (current-column))
5659 (ind (current-indentation))
5660 ind1 bullet)
5661 ;; find where this list begins
5662 (org-beginning-of-item-list)
5663 (beginning-of-line 1)
5664 ;; find out what the bullet type is
5665 (looking-at "[ \t]*\\(\\S-+\\)")
5666 (setq bullet (match-string 1))
5667 ;; walk forward and replace these numbers
5668 (beginning-of-line 0)
5669 (catch 'exit
5670 (while t
5671 (catch 'next
5672 (beginning-of-line 2)
5673 (if (eobp) (throw 'exit nil))
5674 (if (looking-at "[ \t]*$") (throw 'next nil))
5675 (skip-chars-forward " \t") (setq ind1 (current-column))
5676 (if (> ind1 ind) (throw 'next t))
5677 (if (< ind1 ind) (throw 'exit t))
5678 (if (not (org-at-item-p)) (throw 'exit nil))
5679 (skip-chars-forward " \t")
5680 (looking-at "\\S-+")
5681 (replace-match bullet))))
5682 (goto-line line)
5683 (org-move-to-column col)
5684 (if (string-match "[0-9]" bullet)
5685 (org-renumber-ordered-list 1))))
5687 (defun org-beginning-of-item-list ()
5688 "Go to the beginning of the current item list.
5689 I.e. to the first item in this list."
5690 (interactive)
5691 (org-beginning-of-item)
5692 (let ((pos (point-at-bol))
5693 (ind (org-get-indentation))
5694 ind1)
5695 ;; find where this list begins
5696 (catch 'exit
5697 (while t
5698 (catch 'next
5699 (beginning-of-line 0)
5700 (if (looking-at "[ \t]*$")
5701 (throw (if (bobp) 'exit 'next) t))
5702 (skip-chars-forward " \t") (setq ind1 (current-column))
5703 (if (or (< ind1 ind)
5704 (and (= ind1 ind)
5705 (not (org-at-item-p)))
5706 (bobp))
5707 (throw 'exit t)
5708 (when (org-at-item-p) (setq pos (point-at-bol)))))))
5709 (goto-char pos)))
5712 (defun org-end-of-item-list ()
5713 "Go to the end of the current item list.
5714 I.e. to the text after the last item."
5715 (interactive)
5716 (org-beginning-of-item)
5717 (let ((pos (point-at-bol))
5718 (ind (org-get-indentation))
5719 ind1)
5720 ;; find where this list begins
5721 (catch 'exit
5722 (while t
5723 (catch 'next
5724 (beginning-of-line 2)
5725 (if (looking-at "[ \t]*$")
5726 (throw (if (eobp) 'exit 'next) t))
5727 (skip-chars-forward " \t") (setq ind1 (current-column))
5728 (if (or (< ind1 ind)
5729 (and (= ind1 ind)
5730 (not (org-at-item-p)))
5731 (eobp))
5732 (progn
5733 (setq pos (point-at-bol))
5734 (throw 'exit t))))))
5735 (goto-char pos)))
5738 (defvar org-last-indent-begin-marker (make-marker))
5739 (defvar org-last-indent-end-marker (make-marker))
5741 (defun org-outdent-item (arg)
5742 "Outdent a local list item."
5743 (interactive "p")
5744 (org-indent-item (- arg)))
5746 (defun org-indent-item (arg)
5747 "Indent a local list item."
5748 (interactive "p")
5749 (unless (org-at-item-p)
5750 (error "Not on an item"))
5751 (save-excursion
5752 (let (beg end ind ind1 tmp delta ind-down ind-up)
5753 (if (memq last-command '(org-shiftmetaright org-shiftmetaleft))
5754 (setq beg org-last-indent-begin-marker
5755 end org-last-indent-end-marker)
5756 (org-beginning-of-item)
5757 (setq beg (move-marker org-last-indent-begin-marker (point)))
5758 (org-end-of-item)
5759 (setq end (move-marker org-last-indent-end-marker (point))))
5760 (goto-char beg)
5761 (setq tmp (org-item-indent-positions)
5762 ind (car tmp)
5763 ind-down (nth 2 tmp)
5764 ind-up (nth 1 tmp)
5765 delta (if (> arg 0)
5766 (if ind-down (- ind-down ind) 2)
5767 (if ind-up (- ind-up ind) -2)))
5768 (if (< (+ delta ind) 0) (error "Cannot outdent beyond margin"))
5769 (while (< (point) end)
5770 (beginning-of-line 1)
5771 (skip-chars-forward " \t") (setq ind1 (current-column))
5772 (delete-region (point-at-bol) (point))
5773 (or (eolp) (org-indent-to-column (+ ind1 delta)))
5774 (beginning-of-line 2))))
5775 (org-fix-bullet-type)
5776 (org-maybe-renumber-ordered-list-safe)
5777 (save-excursion
5778 (beginning-of-line 0)
5779 (condition-case nil (org-beginning-of-item) (error nil))
5780 (org-maybe-renumber-ordered-list-safe)))
5782 (defun org-item-indent-positions ()
5783 "Return indentation for plain list items.
5784 This returns a list with three values: The current indentation, the
5785 parent indentation and the indentation a child should habe.
5786 Assumes cursor in item line."
5787 (let* ((bolpos (point-at-bol))
5788 (ind (org-get-indentation))
5789 ind-down ind-up pos)
5790 (save-excursion
5791 (org-beginning-of-item-list)
5792 (skip-chars-backward "\n\r \t")
5793 (when (org-in-item-p)
5794 (org-beginning-of-item)
5795 (setq ind-up (org-get-indentation))))
5796 (setq pos (point))
5797 (save-excursion
5798 (cond
5799 ((and (condition-case nil (progn (org-previous-item) t)
5800 (error nil))
5801 (or (forward-char 1) t)
5802 (re-search-forward "^\\([ \t]*\\([-+]\\|\\([0-9]+[.)]\\)\\)\\|[ \t]+\\*\\)\\( \\|$\\)" bolpos t))
5803 (setq ind-down (org-get-indentation)))
5804 ((and (goto-char pos)
5805 (org-at-item-p))
5806 (goto-char (match-end 0))
5807 (skip-chars-forward " \t")
5808 (setq ind-down (current-column)))))
5809 (list ind ind-up ind-down)))
5811 ;;; The orgstruct minor mode
5813 ;; Define a minor mode which can be used in other modes in order to
5814 ;; integrate the org-mode structure editing commands.
5816 ;; This is really a hack, because the org-mode structure commands use
5817 ;; keys which normally belong to the major mode. Here is how it
5818 ;; works: The minor mode defines all the keys necessary to operate the
5819 ;; structure commands, but wraps the commands into a function which
5820 ;; tests if the cursor is currently at a headline or a plain list
5821 ;; item. If that is the case, the structure command is used,
5822 ;; temporarily setting many Org-mode variables like regular
5823 ;; expressions for filling etc. However, when any of those keys is
5824 ;; used at a different location, function uses `key-binding' to look
5825 ;; up if the key has an associated command in another currently active
5826 ;; keymap (minor modes, major mode, global), and executes that
5827 ;; command. There might be problems if any of the keys is otherwise
5828 ;; used as a prefix key.
5830 ;; Another challenge is that the key binding for TAB can be tab or \C-i,
5831 ;; likewise the binding for RET can be return or \C-m. Orgtbl-mode
5832 ;; addresses this by checking explicitly for both bindings.
5834 (defvar orgstruct-mode-map (make-sparse-keymap)
5835 "Keymap for the minor `orgstruct-mode'.")
5837 (defvar org-local-vars nil
5838 "List of local variables, for use by `orgstruct-mode'")
5840 ;;;###autoload
5841 (define-minor-mode orgstruct-mode
5842 "Toggle the minor more `orgstruct-mode'.
5843 This mode is for using Org-mode structure commands in other modes.
5844 The following key behave as if Org-mode was active, if the cursor
5845 is on a headline, or on a plain list item (both in the definition
5846 of Org-mode).
5848 M-up Move entry/item up
5849 M-down Move entry/item down
5850 M-left Promote
5851 M-right Demote
5852 M-S-up Move entry/item up
5853 M-S-down Move entry/item down
5854 M-S-left Promote subtree
5855 M-S-right Demote subtree
5856 M-q Fill paragraph and items like in Org-mode
5857 C-c ^ Sort entries
5858 C-c - Cycle list bullet
5859 TAB Cycle item visibility
5860 M-RET Insert new heading/item
5861 S-M-RET Insert new TODO heading / Chekbox item
5862 C-c C-c Set tags / toggle checkbox"
5863 nil " OrgStruct" nil
5864 (org-load-modules-maybe)
5865 (and (orgstruct-setup) (defun orgstruct-setup () nil)))
5867 ;;;###autoload
5868 (defun turn-on-orgstruct ()
5869 "Unconditionally turn on `orgstruct-mode'."
5870 (orgstruct-mode 1))
5872 ;;;###autoload
5873 (defun turn-on-orgstruct++ ()
5874 "Unconditionally turn on `orgstruct-mode', and force org-mode indentations.
5875 In addition to setting orgstruct-mode, this also exports all indentation and
5876 autofilling variables from org-mode into the buffer. Note that turning
5877 off orgstruct-mode will *not* remove these additional settings."
5878 (orgstruct-mode 1)
5879 (let (var val)
5880 (mapc
5881 (lambda (x)
5882 (when (string-match
5883 "^\\(paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5884 (symbol-name (car x)))
5885 (setq var (car x) val (nth 1 x))
5886 (org-set-local var (if (eq (car-safe val) 'quote) (nth 1 val) val))))
5887 org-local-vars)))
5889 (defun orgstruct-error ()
5890 "Error when there is no default binding for a structure key."
5891 (interactive)
5892 (error "This key has no function outside structure elements"))
5894 (defun orgstruct-setup ()
5895 "Setup orgstruct keymaps."
5896 (let ((nfunc 0)
5897 (bindings
5898 (list
5899 '([(meta up)] org-metaup)
5900 '([(meta down)] org-metadown)
5901 '([(meta left)] org-metaleft)
5902 '([(meta right)] org-metaright)
5903 '([(meta shift up)] org-shiftmetaup)
5904 '([(meta shift down)] org-shiftmetadown)
5905 '([(meta shift left)] org-shiftmetaleft)
5906 '([(meta shift right)] org-shiftmetaright)
5907 '([(shift up)] org-shiftup)
5908 '([(shift down)] org-shiftdown)
5909 '("\C-c\C-c" org-ctrl-c-ctrl-c)
5910 '("\M-q" fill-paragraph)
5911 '("\C-c^" org-sort)
5912 '("\C-c-" org-cycle-list-bullet)))
5913 elt key fun cmd)
5914 (while (setq elt (pop bindings))
5915 (setq nfunc (1+ nfunc))
5916 (setq key (org-key (car elt))
5917 fun (nth 1 elt)
5918 cmd (orgstruct-make-binding fun nfunc key))
5919 (org-defkey orgstruct-mode-map key cmd))
5921 ;; Special treatment needed for TAB and RET
5922 (org-defkey orgstruct-mode-map [(tab)]
5923 (orgstruct-make-binding 'org-cycle 102 [(tab)] "\C-i"))
5924 (org-defkey orgstruct-mode-map "\C-i"
5925 (orgstruct-make-binding 'org-cycle 103 "\C-i" [(tab)]))
5927 (org-defkey orgstruct-mode-map "\M-\C-m"
5928 (orgstruct-make-binding 'org-insert-heading 105
5929 "\M-\C-m" [(meta return)]))
5930 (org-defkey orgstruct-mode-map [(meta return)]
5931 (orgstruct-make-binding 'org-insert-heading 106
5932 [(meta return)] "\M-\C-m"))
5934 (org-defkey orgstruct-mode-map [(shift meta return)]
5935 (orgstruct-make-binding 'org-insert-todo-heading 107
5936 [(meta return)] "\M-\C-m"))
5938 (unless org-local-vars
5939 (setq org-local-vars (org-get-local-variables)))
5943 (defun orgstruct-make-binding (fun n &rest keys)
5944 "Create a function for binding in the structure minor mode.
5945 FUN is the command to call inside a table. N is used to create a unique
5946 command name. KEYS are keys that should be checked in for a command
5947 to execute outside of tables."
5948 (eval
5949 (list 'defun
5950 (intern (concat "orgstruct-hijacker-command-" (int-to-string n)))
5951 '(arg)
5952 (concat "In Structure, run `" (symbol-name fun) "'.\n"
5953 "Outside of structure, run the binding of `"
5954 (mapconcat (lambda (x) (format "%s" x)) keys "' or `")
5955 "'.")
5956 '(interactive "p")
5957 (list 'if
5958 '(org-context-p 'headline 'item)
5959 (list 'org-run-like-in-org-mode (list 'quote fun))
5960 (list 'let '(orgstruct-mode)
5961 (list 'call-interactively
5962 (append '(or)
5963 (mapcar (lambda (k)
5964 (list 'key-binding k))
5965 keys)
5966 '('orgstruct-error))))))))
5968 (defun org-context-p (&rest contexts)
5969 "Check if local context is and of CONTEXTS.
5970 Possible values in the list of contexts are `table', `headline', and `item'."
5971 (let ((pos (point)))
5972 (goto-char (point-at-bol))
5973 (prog1 (or (and (memq 'table contexts)
5974 (looking-at "[ \t]*|"))
5975 (and (memq 'headline contexts)
5976 (looking-at "\\*+"))
5977 (and (memq 'item contexts)
5978 (looking-at "[ \t]*\\([-+*] \\|[0-9]+[.)] \\)")))
5979 (goto-char pos))))
5981 (defun org-get-local-variables ()
5982 "Return a list of all local variables in an org-mode buffer."
5983 (let (varlist)
5984 (with-current-buffer (get-buffer-create "*Org tmp*")
5985 (erase-buffer)
5986 (org-mode)
5987 (setq varlist (buffer-local-variables)))
5988 (kill-buffer "*Org tmp*")
5989 (delq nil
5990 (mapcar
5991 (lambda (x)
5992 (setq x
5993 (if (symbolp x)
5994 (list x)
5995 (list (car x) (list 'quote (cdr x)))))
5996 (if (string-match
5997 "^\\(org-\\|orgtbl-\\|outline-\\|comment-\\|paragraph-\\|auto-fill\\|fill-paragraph\\|adaptive-fill\\|indent-\\)"
5998 (symbol-name (car x)))
5999 x nil))
6000 varlist))))
6002 ;;;###autoload
6003 (defun org-run-like-in-org-mode (cmd)
6004 (org-load-modules-maybe)
6005 (unless org-local-vars
6006 (setq org-local-vars (org-get-local-variables)))
6007 (eval (list 'let org-local-vars
6008 (list 'call-interactively (list 'quote cmd)))))
6010 ;;;; Archiving
6012 (defun org-get-category (&optional pos)
6013 "Get the category applying to position POS."
6014 (get-text-property (or pos (point)) 'org-category))
6016 (defun org-refresh-category-properties ()
6017 "Refresh category text properties in the buffer."
6018 (let ((def-cat (cond
6019 ((null org-category)
6020 (if buffer-file-name
6021 (file-name-sans-extension
6022 (file-name-nondirectory buffer-file-name))
6023 "???"))
6024 ((symbolp org-category) (symbol-name org-category))
6025 (t org-category)))
6026 beg end cat pos optionp)
6027 (org-unmodified
6028 (save-excursion
6029 (save-restriction
6030 (widen)
6031 (goto-char (point-min))
6032 (put-text-property (point) (point-max) 'org-category def-cat)
6033 (while (re-search-forward
6034 "^\\(#\\+CATEGORY:\\|[ \t]*:CATEGORY:\\)\\(.*\\)" nil t)
6035 (setq pos (match-end 0)
6036 optionp (equal (char-after (match-beginning 0)) ?#)
6037 cat (org-trim (match-string 2)))
6038 (if optionp
6039 (setq beg (point-at-bol) end (point-max))
6040 (org-back-to-heading t)
6041 (setq beg (point) end (org-end-of-subtree t t)))
6042 (put-text-property beg end 'org-category cat)
6043 (goto-char pos)))))))
6046 ;;;; Link Stuff
6048 ;;; Link abbreviations
6050 (defun org-link-expand-abbrev (link)
6051 "Apply replacements as defined in `org-link-abbrev-alist."
6052 (if (string-match "^\\([a-zA-Z][-_a-zA-Z0-9]*\\)\\(::?\\(.*\\)\\)?$" link)
6053 (let* ((key (match-string 1 link))
6054 (as (or (assoc key org-link-abbrev-alist-local)
6055 (assoc key org-link-abbrev-alist)))
6056 (tag (and (match-end 2) (match-string 3 link)))
6057 rpl)
6058 (if (not as)
6059 link
6060 (setq rpl (cdr as))
6061 (cond
6062 ((symbolp rpl) (funcall rpl tag))
6063 ((string-match "%s" rpl) (replace-match (or tag "") t t rpl))
6064 (t (concat rpl tag)))))
6065 link))
6067 ;;; Storing and inserting links
6069 (defvar org-insert-link-history nil
6070 "Minibuffer history for links inserted with `org-insert-link'.")
6072 (defvar org-stored-links nil
6073 "Contains the links stored with `org-store-link'.")
6075 (defvar org-store-link-plist nil
6076 "Plist with info about the most recently link created with `org-store-link'.")
6078 (defvar org-link-protocols nil
6079 "Link protocols added to Org-mode using `org-add-link-type'.")
6081 (defvar org-store-link-functions nil
6082 "List of functions that are called to create and store a link.
6083 Each function will be called in turn until one returns a non-nil
6084 value. Each function should check if it is responsible for creating
6085 this link (for example by looking at the major mode).
6086 If not, it must exit and return nil.
6087 If yes, it should return a non-nil value after a calling
6088 `org-store-link-props' with a list of properties and values.
6089 Special properties are:
6091 :type The link prefix. like \"http\". This must be given.
6092 :link The link, like \"http://www.astro.uva.nl/~dominik\".
6093 This is obligatory as well.
6094 :description Optional default description for the second pair
6095 of brackets in an Org-mode link. The user can still change
6096 this when inserting this link into an Org-mode buffer.
6098 In addition to these, any additional properties can be specified
6099 and then used in remember templates.")
6101 (defun org-add-link-type (type &optional follow export)
6102 "Add TYPE to the list of `org-link-types'.
6103 Re-compute all regular expressions depending on `org-link-types'
6105 FOLLOW and EXPORT are two functions.
6107 FOLLOW should take the link path as the single argument and do whatever
6108 is necessary to follow the link, for example find a file or display
6109 a mail message.
6111 EXPORT should format the link path for export to one of the export formats.
6112 It should be a function accepting three arguments:
6114 path the path of the link, the text after the prefix (like \"http:\")
6115 desc the description of the link, if any, nil if there was no descripton
6116 format the export format, a symbol like `html' or `latex'.
6118 The function may use the FORMAT information to return different values
6119 depending on the format. The return value will be put literally into
6120 the exported file.
6121 Org-mode has a built-in default for exporting links. If you are happy with
6122 this default, there is no need to define an export function for the link
6123 type. For a simple example of an export function, see `org-bbdb.el'."
6124 (add-to-list 'org-link-types type t)
6125 (org-make-link-regexps)
6126 (if (assoc type org-link-protocols)
6127 (setcdr (assoc type org-link-protocols) (list follow export))
6128 (push (list type follow export) org-link-protocols)))
6131 ;;;###autoload
6132 (defun org-store-link (arg)
6133 "\\<org-mode-map>Store an org-link to the current location.
6134 This link is added to `org-stored-links' and can later be inserted
6135 into an org-buffer with \\[org-insert-link].
6137 For some link types, a prefix arg is interpreted:
6138 For links to usenet articles, arg negates `org-usenet-links-prefer-google'.
6139 For file links, arg negates `org-context-in-file-links'."
6140 (interactive "P")
6141 (org-load-modules-maybe)
6142 (setq org-store-link-plist nil) ; reset
6143 (let (link cpltxt desc description search txt)
6144 (cond
6146 ((run-hook-with-args-until-success 'org-store-link-functions)
6147 (setq link (plist-get org-store-link-plist :link)
6148 desc (or (plist-get org-store-link-plist :description) link)))
6150 ((eq major-mode 'calendar-mode)
6151 (let ((cd (calendar-cursor-to-date)))
6152 (setq link
6153 (format-time-string
6154 (car org-time-stamp-formats)
6155 (apply 'encode-time
6156 (list 0 0 0 (nth 1 cd) (nth 0 cd) (nth 2 cd)
6157 nil nil nil))))
6158 (org-store-link-props :type "calendar" :date cd)))
6160 ((eq major-mode 'w3-mode)
6161 (setq cpltxt (url-view-url t)
6162 link (org-make-link cpltxt))
6163 (org-store-link-props :type "w3" :url (url-view-url t)))
6165 ((eq major-mode 'w3m-mode)
6166 (setq cpltxt (or w3m-current-title w3m-current-url)
6167 link (org-make-link w3m-current-url))
6168 (org-store-link-props :type "w3m" :url (url-view-url t)))
6170 ((setq search (run-hook-with-args-until-success
6171 'org-create-file-search-functions))
6172 (setq link (concat "file:" (abbreviate-file-name buffer-file-name)
6173 "::" search))
6174 (setq cpltxt (or description link)))
6176 ((eq major-mode 'image-mode)
6177 (setq cpltxt (concat "file:"
6178 (abbreviate-file-name buffer-file-name))
6179 link (org-make-link cpltxt))
6180 (org-store-link-props :type "image" :file buffer-file-name))
6182 ((eq major-mode 'dired-mode)
6183 ;; link to the file in the current line
6184 (setq cpltxt (concat "file:"
6185 (abbreviate-file-name
6186 (expand-file-name
6187 (dired-get-filename nil t))))
6188 link (org-make-link cpltxt)))
6190 ((and buffer-file-name (org-mode-p))
6191 ;; Just link to current headline
6192 (setq cpltxt (concat "file:"
6193 (abbreviate-file-name buffer-file-name)))
6194 ;; Add a context search string
6195 (when (org-xor org-context-in-file-links arg)
6196 ;; Check if we are on a target
6197 (if (org-in-regexp "<<\\(.*?\\)>>")
6198 (setq cpltxt (concat cpltxt "::" (match-string 1)))
6199 (setq txt (cond
6200 ((org-on-heading-p) nil)
6201 ((org-region-active-p)
6202 (buffer-substring (region-beginning) (region-end)))
6203 (t nil)))
6204 (when (or (null txt) (string-match "\\S-" txt))
6205 (setq cpltxt
6206 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6207 desc "NONE"))))
6208 (if (string-match "::\\'" cpltxt)
6209 (setq cpltxt (substring cpltxt 0 -2)))
6210 (setq link (org-make-link cpltxt)))
6212 ((buffer-file-name (buffer-base-buffer))
6213 ;; Just link to this file here.
6214 (setq cpltxt (concat "file:"
6215 (abbreviate-file-name
6216 (buffer-file-name (buffer-base-buffer)))))
6217 ;; Add a context string
6218 (when (org-xor org-context-in-file-links arg)
6219 (setq txt (if (org-region-active-p)
6220 (buffer-substring (region-beginning) (region-end))
6221 (buffer-substring (point-at-bol) (point-at-eol))))
6222 ;; Only use search option if there is some text.
6223 (when (string-match "\\S-" txt)
6224 (setq cpltxt
6225 (concat cpltxt "::" (org-make-org-heading-search-string txt))
6226 desc "NONE")))
6227 (setq link (org-make-link cpltxt)))
6229 ((interactive-p)
6230 (error "Cannot link to a buffer which is not visiting a file"))
6232 (t (setq link nil)))
6234 (if (consp link) (setq cpltxt (car link) link (cdr link)))
6235 (setq link (or link cpltxt)
6236 desc (or desc cpltxt))
6237 (if (equal desc "NONE") (setq desc nil))
6239 (if (and (interactive-p) link)
6240 (progn
6241 (setq org-stored-links
6242 (cons (list link desc) org-stored-links))
6243 (message "Stored: %s" (or desc link)))
6244 (and link (org-make-link-string link desc)))))
6246 (defun org-store-link-props (&rest plist)
6247 "Store link properties, extract names and addresses."
6248 (let (x adr)
6249 (when (setq x (plist-get plist :from))
6250 (setq adr (mail-extract-address-components x))
6251 (plist-put plist :fromname (car adr))
6252 (plist-put plist :fromaddress (nth 1 adr)))
6253 (when (setq x (plist-get plist :to))
6254 (setq adr (mail-extract-address-components x))
6255 (plist-put plist :toname (car adr))
6256 (plist-put plist :toaddress (nth 1 adr))))
6257 (let ((from (plist-get plist :from))
6258 (to (plist-get plist :to)))
6259 (when (and from to org-from-is-user-regexp)
6260 (plist-put plist :fromto
6261 (if (string-match org-from-is-user-regexp from)
6262 (concat "to %t")
6263 (concat "from %f")))))
6264 (setq org-store-link-plist plist))
6266 (defun org-add-link-props (&rest plist)
6267 "Add these properties to the link property list."
6268 (let (key value)
6269 (while plist
6270 (setq key (pop plist) value (pop plist))
6271 (setq org-store-link-plist
6272 (plist-put org-store-link-plist key value)))))
6274 (defun org-email-link-description (&optional fmt)
6275 "Return the description part of an email link.
6276 This takes information from `org-store-link-plist' and formats it
6277 according to FMT (default from `org-email-link-description-format')."
6278 (setq fmt (or fmt org-email-link-description-format))
6279 (let* ((p org-store-link-plist)
6280 (to (plist-get p :toaddress))
6281 (from (plist-get p :fromaddress))
6282 (table
6283 (list
6284 (cons "%c" (plist-get p :fromto))
6285 (cons "%F" (plist-get p :from))
6286 (cons "%f" (or (plist-get p :fromname) (plist-get p :fromaddress) "?"))
6287 (cons "%T" (plist-get p :to))
6288 (cons "%t" (or (plist-get p :toname) (plist-get p :toaddress) "?"))
6289 (cons "%s" (plist-get p :subject))
6290 (cons "%m" (plist-get p :message-id)))))
6291 (when (string-match "%c" fmt)
6292 ;; Check if the user wrote this message
6293 (if (and org-from-is-user-regexp from to
6294 (save-match-data (string-match org-from-is-user-regexp from)))
6295 (setq fmt (replace-match "to %t" t t fmt))
6296 (setq fmt (replace-match "from %f" t t fmt))))
6297 (org-replace-escapes fmt table)))
6299 (defun org-make-org-heading-search-string (&optional string heading)
6300 "Make search string for STRING or current headline."
6301 (interactive)
6302 (let ((s (or string (org-get-heading))))
6303 (unless (and string (not heading))
6304 ;; We are using a headline, clean up garbage in there.
6305 (if (string-match org-todo-regexp s)
6306 (setq s (replace-match "" t t s)))
6307 (if (string-match (org-re ":[[:alnum:]_@:]+:[ \t]*$") s)
6308 (setq s (replace-match "" t t s)))
6309 (setq s (org-trim s))
6310 (if (string-match (concat "^\\(" org-quote-string "\\|"
6311 org-comment-string "\\)") s)
6312 (setq s (replace-match "" t t s)))
6313 (while (string-match org-ts-regexp s)
6314 (setq s (replace-match "" t t s))))
6315 (while (string-match "[^a-zA-Z_0-9 \t]+" s)
6316 (setq s (replace-match " " t t s)))
6317 (or string (setq s (concat "*" s))) ; Add * for headlines
6318 (mapconcat 'identity (org-split-string s "[ \t]+") " ")))
6320 (defun org-make-link (&rest strings)
6321 "Concatenate STRINGS."
6322 (apply 'concat strings))
6324 (defun org-make-link-string (link &optional description)
6325 "Make a link with brackets, consisting of LINK and DESCRIPTION."
6326 (unless (string-match "\\S-" link)
6327 (error "Empty link"))
6328 (when (stringp description)
6329 ;; Remove brackets from the description, they are fatal.
6330 (while (string-match "\\[" description)
6331 (setq description (replace-match "{" t t description)))
6332 (while (string-match "\\]" description)
6333 (setq description (replace-match "}" t t description))))
6334 (when (equal (org-link-escape link) description)
6335 ;; No description needed, it is identical
6336 (setq description nil))
6337 (when (and (not description)
6338 (not (equal link (org-link-escape link))))
6339 (setq description link))
6340 (concat "[[" (org-link-escape link) "]"
6341 (if description (concat "[" description "]") "")
6342 "]"))
6344 (defconst org-link-escape-chars
6345 '((?\ . "%20")
6346 (?\[ . "%5B")
6347 (?\] . "%5D")
6348 (?\340 . "%E0") ; `a
6349 (?\342 . "%E2") ; ^a
6350 (?\347 . "%E7") ; ,c
6351 (?\350 . "%E8") ; `e
6352 (?\351 . "%E9") ; 'e
6353 (?\352 . "%EA") ; ^e
6354 (?\356 . "%EE") ; ^i
6355 (?\364 . "%F4") ; ^o
6356 (?\371 . "%F9") ; `u
6357 (?\373 . "%FB") ; ^u
6358 (?\; . "%3B")
6359 (?? . "%3F")
6360 (?= . "%3D")
6361 (?+ . "%2B")
6363 "Association list of escapes for some characters problematic in links.
6364 This is the list that is used for internal purposes.")
6366 (defconst org-link-escape-chars-browser
6367 '((?\ . "%20")) ; 32 for the SPC char
6368 "Association list of escapes for some characters problematic in links.
6369 This is the list that is used before handing over to the browser.")
6371 (defun org-link-escape (text &optional table)
6372 "Escape charaters in TEXT that are problematic for links."
6373 (setq table (or table org-link-escape-chars))
6374 (when text
6375 (let ((re (mapconcat (lambda (x) (regexp-quote
6376 (char-to-string (car x))))
6377 table "\\|")))
6378 (while (string-match re text)
6379 (setq text
6380 (replace-match
6381 (cdr (assoc (string-to-char (match-string 0 text))
6382 table))
6383 t t text)))
6384 text)))
6386 (defun org-link-unescape (text &optional table)
6387 "Reverse the action of `org-link-escape'."
6388 (setq table (or table org-link-escape-chars))
6389 (when text
6390 (let ((re (mapconcat (lambda (x) (regexp-quote (cdr x)))
6391 table "\\|")))
6392 (while (string-match re text)
6393 (setq text
6394 (replace-match
6395 (char-to-string (car (rassoc (match-string 0 text) table)))
6396 t t text)))
6397 text)))
6399 (defun org-xor (a b)
6400 "Exclusive or."
6401 (if a (not b) b))
6403 (defun org-get-header (header)
6404 "Find a header field in the current buffer."
6405 (save-excursion
6406 (goto-char (point-min))
6407 (let ((case-fold-search t) s)
6408 (cond
6409 ((eq header 'from)
6410 (if (re-search-forward "^From:\\s-+\\(.*\\)" nil t)
6411 (setq s (match-string 1)))
6412 (while (string-match "\"" s)
6413 (setq s (replace-match "" t t s)))
6414 (if (string-match "[<(].*" s)
6415 (setq s (replace-match "" t t s))))
6416 ((eq header 'message-id)
6417 (if (re-search-forward "^message-id:\\s-+\\(.*\\)" nil t)
6418 (setq s (match-string 1))))
6419 ((eq header 'subject)
6420 (if (re-search-forward "^subject:\\s-+\\(.*\\)" nil t)
6421 (setq s (match-string 1)))))
6422 (if (string-match "\\`[ \t\]+" s) (setq s (replace-match "" t t s)))
6423 (if (string-match "[ \t\]+\\'" s) (setq s (replace-match "" t t s)))
6424 s)))
6427 (defun org-fixup-message-id-for-http (s)
6428 "Replace special characters in a message id, so it can be used in an http query."
6429 (while (string-match "<" s)
6430 (setq s (replace-match "%3C" t t s)))
6431 (while (string-match ">" s)
6432 (setq s (replace-match "%3E" t t s)))
6433 (while (string-match "@" s)
6434 (setq s (replace-match "%40" t t s)))
6437 ;;;###autoload
6438 (defun org-insert-link-global ()
6439 "Insert a link like Org-mode does.
6440 This command can be called in any mode to insert a link in Org-mode syntax."
6441 (interactive)
6442 (org-load-modules-maybe)
6443 (org-run-like-in-org-mode 'org-insert-link))
6445 (defun org-insert-link (&optional complete-file link-location)
6446 "Insert a link. At the prompt, enter the link.
6448 Completion can be used to select a link previously stored with
6449 `org-store-link'. When the empty string is entered (i.e. if you just
6450 press RET at the prompt), the link defaults to the most recently
6451 stored link. As SPC triggers completion in the minibuffer, you need to
6452 use M-SPC or C-q SPC to force the insertion of a space character.
6454 You will also be prompted for a description, and if one is given, it will
6455 be displayed in the buffer instead of the link.
6457 If there is already a link at point, this command will allow you to edit link
6458 and description parts.
6460 With a \\[universal-argument] prefix, prompts for a file to link to. The file name can
6461 be selected using completion. The path to the file will be relative to the
6462 current directory if the file is in the current directory or a subdirectory.
6463 Otherwise, the link will be the absolute path as completed in the minibuffer
6464 \(i.e. normally ~/path/to/file).
6466 With two \\[universal-argument] prefixes, enforce an absolute path even if the file is in
6467 the current directory or below. With three \\[universal-argument] prefixes, negate the meaning
6468 of `org-keep-stored-link-after-insertion'.
6470 If `org-make-link-description-function' is non-nil, this function will be
6471 called with the link target, and the result will be the default
6472 link description.
6474 If the LINK-LOCATION parameter is non-nil, this value will be
6475 used as the link location instead of reading one interactively."
6476 (interactive "P")
6477 (let* ((wcf (current-window-configuration))
6478 (region (if (org-region-active-p)
6479 (buffer-substring (region-beginning) (region-end))))
6480 (remove (and region (list (region-beginning) (region-end))))
6481 (desc region)
6482 tmphist ; byte-compile incorrectly complains about this
6483 (link link-location)
6484 entry file)
6485 (cond
6486 (link-location) ; specified by arg, just use it.
6487 ((org-in-regexp org-bracket-link-regexp 1)
6488 ;; We do have a link at point, and we are going to edit it.
6489 (setq remove (list (match-beginning 0) (match-end 0)))
6490 (setq desc (if (match-end 3) (org-match-string-no-properties 3)))
6491 (setq link (read-string "Link: "
6492 (org-link-unescape
6493 (org-match-string-no-properties 1)))))
6494 ((or (org-in-regexp org-angle-link-re)
6495 (org-in-regexp org-plain-link-re))
6496 ;; Convert to bracket link
6497 (setq remove (list (match-beginning 0) (match-end 0))
6498 link (read-string "Link: "
6499 (org-remove-angle-brackets (match-string 0)))))
6500 ((equal complete-file '(4))
6501 ;; Completing read for file names.
6502 (setq file (read-file-name "File: "))
6503 (let ((pwd (file-name-as-directory (expand-file-name ".")))
6504 (pwd1 (file-name-as-directory (abbreviate-file-name
6505 (expand-file-name ".")))))
6506 (cond
6507 ((equal complete-file '(16))
6508 (setq link (org-make-link
6509 "file:"
6510 (abbreviate-file-name (expand-file-name file)))))
6511 ((string-match (concat "^" (regexp-quote pwd1) "\\(.+\\)") file)
6512 (setq link (org-make-link "file:" (match-string 1 file))))
6513 ((string-match (concat "^" (regexp-quote pwd) "\\(.+\\)")
6514 (expand-file-name file))
6515 (setq link (org-make-link
6516 "file:" (match-string 1 (expand-file-name file)))))
6517 (t (setq link (org-make-link "file:" file))))))
6519 ;; Read link, with completion for stored links.
6520 (with-output-to-temp-buffer "*Org Links*"
6521 (princ "Insert a link. Use TAB to complete valid link prefixes.\n")
6522 (when org-stored-links
6523 (princ "\nStored links are available with <up>/<down> or M-p/n (most recent with RET):\n\n")
6524 (princ (mapconcat
6525 (lambda (x)
6526 (if (nth 1 x) (concat (car x) " (" (nth 1 x) ")") (car x)))
6527 (reverse org-stored-links) "\n"))))
6528 (let ((cw (selected-window)))
6529 (select-window (get-buffer-window "*Org Links*"))
6530 (shrink-window-if-larger-than-buffer)
6531 (setq truncate-lines t)
6532 (select-window cw))
6533 ;; Fake a link history, containing the stored links.
6534 (setq tmphist (append (mapcar 'car org-stored-links)
6535 org-insert-link-history))
6536 (unwind-protect
6537 (setq link (org-completing-read
6538 "Link: "
6539 (append
6540 (mapcar (lambda (x) (list (concat (car x) ":")))
6541 (append org-link-abbrev-alist-local org-link-abbrev-alist))
6542 (mapcar (lambda (x) (list (concat x ":")))
6543 org-link-types))
6544 nil nil nil
6545 'tmphist
6546 (or (car (car org-stored-links)))))
6547 (set-window-configuration wcf)
6548 (kill-buffer "*Org Links*"))
6549 (setq entry (assoc link org-stored-links))
6550 (or entry (push link org-insert-link-history))
6551 (if (funcall (if (equal complete-file '(64)) 'not 'identity)
6552 (not org-keep-stored-link-after-insertion))
6553 (setq org-stored-links (delq (assoc link org-stored-links)
6554 org-stored-links)))
6555 (setq desc (or desc (nth 1 entry)))))
6557 (if (string-match org-plain-link-re link)
6558 ;; URL-like link, normalize the use of angular brackets.
6559 (setq link (org-make-link (org-remove-angle-brackets link))))
6561 ;; Check if we are linking to the current file with a search option
6562 ;; If yes, simplify the link by using only the search option.
6563 (when (and buffer-file-name
6564 (string-match "\\<file:\\(.+?\\)::\\([^>]+\\)" link))
6565 (let* ((path (match-string 1 link))
6566 (case-fold-search nil)
6567 (search (match-string 2 link)))
6568 (save-match-data
6569 (if (equal (file-truename buffer-file-name) (file-truename path))
6570 ;; We are linking to this same file, with a search option
6571 (setq link search)))))
6573 ;; Check if we can/should use a relative path. If yes, simplify the link
6574 (when (string-match "\\<file:\\(.*\\)" link)
6575 (let* ((path (match-string 1 link))
6576 (origpath path)
6577 (case-fold-search nil))
6578 (cond
6579 ((eq org-link-file-path-type 'absolute)
6580 (setq path (abbreviate-file-name (expand-file-name path))))
6581 ((eq org-link-file-path-type 'noabbrev)
6582 (setq path (expand-file-name path)))
6583 ((eq org-link-file-path-type 'relative)
6584 (setq path (file-relative-name path)))
6586 (save-match-data
6587 (if (string-match (concat "^" (regexp-quote
6588 (file-name-as-directory
6589 (expand-file-name "."))))
6590 (expand-file-name path))
6591 ;; We are linking a file with relative path name.
6592 (setq path (substring (expand-file-name path)
6593 (match-end 0)))))))
6594 (setq link (concat "file:" path))
6595 (if (equal desc origpath)
6596 (setq desc path))))
6598 (if org-make-link-description-function
6599 (setq desc (funcall org-make-link-description-function link desc)))
6601 (setq desc (read-string "Description: " desc))
6602 (unless (string-match "\\S-" desc) (setq desc nil))
6603 (if remove (apply 'delete-region remove))
6604 (insert (org-make-link-string link desc))))
6606 (defun org-completing-read (&rest args)
6607 (let ((minibuffer-local-completion-map
6608 (copy-keymap minibuffer-local-completion-map)))
6609 (org-defkey minibuffer-local-completion-map " " 'self-insert-command)
6610 (apply 'completing-read args)))
6612 ;;; Opening/following a link
6614 (defvar org-link-search-failed nil)
6616 (defun org-next-link ()
6617 "Move forward to the next link.
6618 If the link is in hidden text, expose it."
6619 (interactive)
6620 (when (and org-link-search-failed (eq this-command last-command))
6621 (goto-char (point-min))
6622 (message "Link search wrapped back to beginning of buffer"))
6623 (setq org-link-search-failed nil)
6624 (let* ((pos (point))
6625 (ct (org-context))
6626 (a (assoc :link ct)))
6627 (if a (goto-char (nth 2 a)))
6628 (if (re-search-forward org-any-link-re nil t)
6629 (progn
6630 (goto-char (match-beginning 0))
6631 (if (org-invisible-p) (org-show-context)))
6632 (goto-char pos)
6633 (setq org-link-search-failed t)
6634 (error "No further link found"))))
6636 (defun org-previous-link ()
6637 "Move backward to the previous link.
6638 If the link is in hidden text, expose it."
6639 (interactive)
6640 (when (and org-link-search-failed (eq this-command last-command))
6641 (goto-char (point-max))
6642 (message "Link search wrapped back to end of buffer"))
6643 (setq org-link-search-failed nil)
6644 (let* ((pos (point))
6645 (ct (org-context))
6646 (a (assoc :link ct)))
6647 (if a (goto-char (nth 1 a)))
6648 (if (re-search-backward org-any-link-re nil t)
6649 (progn
6650 (goto-char (match-beginning 0))
6651 (if (org-invisible-p) (org-show-context)))
6652 (goto-char pos)
6653 (setq org-link-search-failed t)
6654 (error "No further link found"))))
6656 (defun org-find-file-at-mouse (ev)
6657 "Open file link or URL at mouse."
6658 (interactive "e")
6659 (mouse-set-point ev)
6660 (org-open-at-point 'in-emacs))
6662 (defun org-open-at-mouse (ev)
6663 "Open file link or URL at mouse."
6664 (interactive "e")
6665 (mouse-set-point ev)
6666 (org-open-at-point))
6668 (defvar org-window-config-before-follow-link nil
6669 "The window configuration before following a link.
6670 This is saved in case the need arises to restore it.")
6672 (defvar org-open-link-marker (make-marker)
6673 "Marker pointing to the location where `org-open-at-point; was called.")
6675 ;;;###autoload
6676 (defun org-open-at-point-global ()
6677 "Follow a link like Org-mode does.
6678 This command can be called in any mode to follow a link that has
6679 Org-mode syntax."
6680 (interactive)
6681 (org-run-like-in-org-mode 'org-open-at-point))
6683 ;;;###autoload
6684 (defun org-open-link-from-string (s &optional arg)
6685 "Open a link in the string S, as if it was in Org-mode."
6686 (interactive "sLink: \nP")
6687 (with-temp-buffer
6688 (let ((org-inhibit-startup t))
6689 (org-mode)
6690 (insert s)
6691 (goto-char (point-min))
6692 (org-open-at-point arg))))
6694 (defun org-open-at-point (&optional in-emacs)
6695 "Open link at or after point.
6696 If there is no link at point, this function will search forward up to
6697 the end of the current subtree.
6698 Normally, files will be opened by an appropriate application. If the
6699 optional argument IN-EMACS is non-nil, Emacs will visit the file."
6700 (interactive "P")
6701 (org-load-modules-maybe)
6702 (move-marker org-open-link-marker (point))
6703 (setq org-window-config-before-follow-link (current-window-configuration))
6704 (org-remove-occur-highlights nil nil t)
6705 (if (org-at-timestamp-p t)
6706 (org-follow-timestamp-link)
6707 (let (type path link line search (pos (point)))
6708 (catch 'match
6709 (save-excursion
6710 (skip-chars-forward "^]\n\r")
6711 (when (org-in-regexp org-bracket-link-regexp)
6712 (setq link (org-link-unescape (org-match-string-no-properties 1)))
6713 (while (string-match " *\n *" link)
6714 (setq link (replace-match " " t t link)))
6715 (setq link (org-link-expand-abbrev link))
6716 (if (string-match org-link-re-with-space2 link)
6717 (setq type (match-string 1 link) path (match-string 2 link))
6718 (setq type "thisfile" path link))
6719 (throw 'match t)))
6721 (when (get-text-property (point) 'org-linked-text)
6722 (setq type "thisfile"
6723 pos (if (get-text-property (1+ (point)) 'org-linked-text)
6724 (1+ (point)) (point))
6725 path (buffer-substring
6726 (previous-single-property-change pos 'org-linked-text)
6727 (next-single-property-change pos 'org-linked-text)))
6728 (throw 'match t))
6730 (save-excursion
6731 (when (or (org-in-regexp org-angle-link-re)
6732 (org-in-regexp org-plain-link-re))
6733 (setq type (match-string 1) path (match-string 2))
6734 (throw 'match t)))
6735 (when (org-in-regexp "\\<\\([^><\n]+\\)\\>")
6736 (setq type "tree-match"
6737 path (match-string 1))
6738 (throw 'match t))
6739 (save-excursion
6740 (when (org-in-regexp (org-re "\\(:[[:alnum:]_@:]+\\):[ \t]*$"))
6741 (setq type "tags"
6742 path (match-string 1))
6743 (while (string-match ":" path)
6744 (setq path (replace-match "+" t t path)))
6745 (throw 'match t))))
6746 (unless path
6747 (error "No link found"))
6748 ;; Remove any trailing spaces in path
6749 (if (string-match " +\\'" path)
6750 (setq path (replace-match "" t t path)))
6752 (cond
6754 ((assoc type org-link-protocols)
6755 (funcall (nth 1 (assoc type org-link-protocols)) path))
6757 ((equal type "mailto")
6758 (let ((cmd (car org-link-mailto-program))
6759 (args (cdr org-link-mailto-program)) args1
6760 (address path) (subject "") a)
6761 (if (string-match "\\(.*\\)::\\(.*\\)" path)
6762 (setq address (match-string 1 path)
6763 subject (org-link-escape (match-string 2 path))))
6764 (while args
6765 (cond
6766 ((not (stringp (car args))) (push (pop args) args1))
6767 (t (setq a (pop args))
6768 (if (string-match "%a" a)
6769 (setq a (replace-match address t t a)))
6770 (if (string-match "%s" a)
6771 (setq a (replace-match subject t t a)))
6772 (push a args1))))
6773 (apply cmd (nreverse args1))))
6775 ((member type '("http" "https" "ftp" "news"))
6776 (browse-url (concat type ":" (org-link-escape
6777 path org-link-escape-chars-browser))))
6779 ((member type '("message"))
6780 (browse-url (concat type ":" path)))
6782 ((string= type "tags")
6783 (org-tags-view in-emacs path))
6784 ((string= type "thisfile")
6785 (if in-emacs
6786 (switch-to-buffer-other-window
6787 (org-get-buffer-for-internal-link (current-buffer)))
6788 (org-mark-ring-push))
6789 (let ((cmd `(org-link-search
6790 ,path
6791 ,(cond ((equal in-emacs '(4)) 'occur)
6792 ((equal in-emacs '(16)) 'org-occur)
6793 (t nil))
6794 ,pos)))
6795 (condition-case nil (eval cmd)
6796 (error (progn (widen) (eval cmd))))))
6798 ((string= type "tree-match")
6799 (org-occur (concat "\\[" (regexp-quote path) "\\]")))
6801 ((string= type "file")
6802 (if (string-match "::\\([0-9]+\\)\\'" path)
6803 (setq line (string-to-number (match-string 1 path))
6804 path (substring path 0 (match-beginning 0)))
6805 (if (string-match "::\\(.+\\)\\'" path)
6806 (setq search (match-string 1 path)
6807 path (substring path 0 (match-beginning 0)))))
6808 (if (string-match "[*?{]" (file-name-nondirectory path))
6809 (dired path)
6810 (org-open-file path in-emacs line search)))
6812 ((string= type "news")
6813 (require 'org-gnus)
6814 (org-gnus-follow-link path))
6816 ((string= type "shell")
6817 (let ((cmd path))
6818 (if (or (not org-confirm-shell-link-function)
6819 (funcall org-confirm-shell-link-function
6820 (format "Execute \"%s\" in shell? "
6821 (org-add-props cmd nil
6822 'face 'org-warning))))
6823 (progn
6824 (message "Executing %s" cmd)
6825 (shell-command cmd))
6826 (error "Abort"))))
6828 ((string= type "elisp")
6829 (let ((cmd path))
6830 (if (or (not org-confirm-elisp-link-function)
6831 (funcall org-confirm-elisp-link-function
6832 (format "Execute \"%s\" as elisp? "
6833 (org-add-props cmd nil
6834 'face 'org-warning))))
6835 (message "%s => %s" cmd (eval (read cmd)))
6836 (error "Abort"))))
6839 (browse-url-at-point)))))
6840 (move-marker org-open-link-marker nil)
6841 (run-hook-with-args 'org-follow-link-hook))
6843 ;;;; Time estimates
6845 (defun org-get-effort (&optional pom)
6846 "Get the effort estimate for the current entry."
6847 (org-entry-get pom org-effort-property))
6849 ;;; File search
6851 (defvar org-create-file-search-functions nil
6852 "List of functions to construct the right search string for a file link.
6853 These functions are called in turn with point at the location to
6854 which the link should point.
6856 A function in the hook should first test if it would like to
6857 handle this file type, for example by checking the major-mode or
6858 the file extension. If it decides not to handle this file, it
6859 should just return nil to give other functions a chance. If it
6860 does handle the file, it must return the search string to be used
6861 when following the link. The search string will be part of the
6862 file link, given after a double colon, and `org-open-at-point'
6863 will automatically search for it. If special measures must be
6864 taken to make the search successful, another function should be
6865 added to the companion hook `org-execute-file-search-functions',
6866 which see.
6868 A function in this hook may also use `setq' to set the variable
6869 `description' to provide a suggestion for the descriptive text to
6870 be used for this link when it gets inserted into an Org-mode
6871 buffer with \\[org-insert-link].")
6873 (defvar org-execute-file-search-functions nil
6874 "List of functions to execute a file search triggered by a link.
6876 Functions added to this hook must accept a single argument, the
6877 search string that was part of the file link, the part after the
6878 double colon. The function must first check if it would like to
6879 handle this search, for example by checking the major-mode or the
6880 file extension. If it decides not to handle this search, it
6881 should just return nil to give other functions a chance. If it
6882 does handle the search, it must return a non-nil value to keep
6883 other functions from trying.
6885 Each function can access the current prefix argument through the
6886 variable `current-prefix-argument'. Note that a single prefix is
6887 used to force opening a link in Emacs, so it may be good to only
6888 use a numeric or double prefix to guide the search function.
6890 In case this is needed, a function in this hook can also restore
6891 the window configuration before `org-open-at-point' was called using:
6893 (set-window-configuration org-window-config-before-follow-link)")
6895 (defun org-link-search (s &optional type avoid-pos)
6896 "Search for a link search option.
6897 If S is surrounded by forward slashes, it is interpreted as a
6898 regular expression. In org-mode files, this will create an `org-occur'
6899 sparse tree. In ordinary files, `occur' will be used to list matches.
6900 If the current buffer is in `dired-mode', grep will be used to search
6901 in all files. If AVOID-POS is given, ignore matches near that position."
6902 (let ((case-fold-search t)
6903 (s0 (mapconcat 'identity (org-split-string s "[ \t\r\n]+") " "))
6904 (markers (concat "\\(?:" (mapconcat (lambda (x) (regexp-quote (car x)))
6905 (append '(("") (" ") ("\t") ("\n"))
6906 org-emphasis-alist)
6907 "\\|") "\\)"))
6908 (pos (point))
6909 (pre nil) (post nil)
6910 words re0 re1 re2 re3 re4_ re4 re5 re2a re2a_ reall)
6911 (cond
6912 ;; First check if there are any special
6913 ((run-hook-with-args-until-success 'org-execute-file-search-functions s))
6914 ;; Now try the builtin stuff
6915 ((save-excursion
6916 (goto-char (point-min))
6917 (and
6918 (re-search-forward
6919 (concat "<<" (regexp-quote s0) ">>") nil t)
6920 (setq type 'dedicated
6921 pos (match-beginning 0))))
6922 ;; There is an exact target for this
6923 (goto-char pos))
6924 ((string-match "^/\\(.*\\)/$" s)
6925 ;; A regular expression
6926 (cond
6927 ((org-mode-p)
6928 (org-occur (match-string 1 s)))
6929 ;;((eq major-mode 'dired-mode)
6930 ;; (grep (concat "grep -n -e '" (match-string 1 s) "' *")))
6931 (t (org-do-occur (match-string 1 s)))))
6933 ;; A normal search strings
6934 (when (equal (string-to-char s) ?*)
6935 ;; Anchor on headlines, post may include tags.
6936 (setq pre "^\\*+[ \t]+\\(?:\\sw+\\)?[ \t]*"
6937 post (org-re "[ \t]*\\(?:[ \t]+:[[:alnum:]_@:+]:[ \t]*\\)?$")
6938 s (substring s 1)))
6939 (remove-text-properties
6940 0 (length s)
6941 '(face nil mouse-face nil keymap nil fontified nil) s)
6942 ;; Make a series of regular expressions to find a match
6943 (setq words (org-split-string s "[ \n\r\t]+")
6945 re0 (concat "\\(<<" (regexp-quote s0) ">>\\)")
6946 re2 (concat markers "\\(" (mapconcat 'downcase words "[ \t]+")
6947 "\\)" markers)
6948 re2a_ (concat "\\(" (mapconcat 'downcase words "[ \t\r\n]+") "\\)[ \t\r\n]")
6949 re2a (concat "[ \t\r\n]" re2a_)
6950 re4_ (concat "\\(" (mapconcat 'downcase words "[^a-zA-Z_\r\n]+") "\\)[^a-zA-Z_]")
6951 re4 (concat "[^a-zA-Z_]" re4_)
6953 re1 (concat pre re2 post)
6954 re3 (concat pre (if pre re4_ re4) post)
6955 re5 (concat pre ".*" re4)
6956 re2 (concat pre re2)
6957 re2a (concat pre (if pre re2a_ re2a))
6958 re4 (concat pre (if pre re4_ re4))
6959 reall (concat "\\(" re0 "\\)\\|\\(" re1 "\\)\\|\\(" re2
6960 "\\)\\|\\(" re3 "\\)\\|\\(" re4 "\\)\\|\\("
6961 re5 "\\)"
6963 (cond
6964 ((eq type 'org-occur) (org-occur reall))
6965 ((eq type 'occur) (org-do-occur (downcase reall) 'cleanup))
6966 (t (goto-char (point-min))
6967 (setq type 'fuzzy)
6968 (if (or (and (org-search-not-self 1 re0 nil t) (setq type 'dedicated))
6969 (org-search-not-self 1 re1 nil t)
6970 (org-search-not-self 1 re2 nil t)
6971 (org-search-not-self 1 re2a nil t)
6972 (org-search-not-self 1 re3 nil t)
6973 (org-search-not-self 1 re4 nil t)
6974 (org-search-not-self 1 re5 nil t)
6976 (goto-char (match-beginning 1))
6977 (goto-char pos)
6978 (error "No match")))))
6980 ;; Normal string-search
6981 (goto-char (point-min))
6982 (if (search-forward s nil t)
6983 (goto-char (match-beginning 0))
6984 (error "No match"))))
6985 (and (org-mode-p) (org-show-context 'link-search))
6986 type))
6988 (defun org-search-not-self (group &rest args)
6989 "Execute `re-search-forward', but only accept matches that do not
6990 enclose the position of `org-open-link-marker'."
6991 (let ((m org-open-link-marker))
6992 (catch 'exit
6993 (while (apply 're-search-forward args)
6994 (unless (get-text-property (match-end group) 'intangible) ; Emacs 21
6995 (goto-char (match-end group))
6996 (if (and (or (not (eq (marker-buffer m) (current-buffer)))
6997 (> (match-beginning 0) (marker-position m))
6998 (< (match-end 0) (marker-position m)))
6999 (save-match-data
7000 (or (not (org-in-regexp
7001 org-bracket-link-analytic-regexp 1))
7002 (not (match-end 4)) ; no description
7003 (and (<= (match-beginning 4) (point))
7004 (>= (match-end 4) (point))))))
7005 (throw 'exit (point))))))))
7007 (defun org-get-buffer-for-internal-link (buffer)
7008 "Return a buffer to be used for displaying the link target of internal links."
7009 (cond
7010 ((not org-display-internal-link-with-indirect-buffer)
7011 buffer)
7012 ((string-match "(Clone)$" (buffer-name buffer))
7013 (message "Buffer is already a clone, not making another one")
7014 ;; we also do not modify visibility in this case
7015 buffer)
7016 (t ; make a new indirect buffer for displaying the link
7017 (let* ((bn (buffer-name buffer))
7018 (ibn (concat bn "(Clone)"))
7019 (ib (or (get-buffer ibn) (make-indirect-buffer buffer ibn 'clone))))
7020 (with-current-buffer ib (org-overview))
7021 ib))))
7023 (defun org-do-occur (regexp &optional cleanup)
7024 "Call the Emacs command `occur'.
7025 If CLEANUP is non-nil, remove the printout of the regular expression
7026 in the *Occur* buffer. This is useful if the regex is long and not useful
7027 to read."
7028 (occur regexp)
7029 (when cleanup
7030 (let ((cwin (selected-window)) win beg end)
7031 (when (setq win (get-buffer-window "*Occur*"))
7032 (select-window win))
7033 (goto-char (point-min))
7034 (when (re-search-forward "match[a-z]+" nil t)
7035 (setq beg (match-end 0))
7036 (if (re-search-forward "^[ \t]*[0-9]+" nil t)
7037 (setq end (1- (match-beginning 0)))))
7038 (and beg end (let ((inhibit-read-only t)) (delete-region beg end)))
7039 (goto-char (point-min))
7040 (select-window cwin))))
7042 ;;; The mark ring for links jumps
7044 (defvar org-mark-ring nil
7045 "Mark ring for positions before jumps in Org-mode.")
7046 (defvar org-mark-ring-last-goto nil
7047 "Last position in the mark ring used to go back.")
7048 ;; Fill and close the ring
7049 (setq org-mark-ring nil org-mark-ring-last-goto nil) ;; in case file is reloaded
7050 (loop for i from 1 to org-mark-ring-length do
7051 (push (make-marker) org-mark-ring))
7052 (setcdr (nthcdr (1- org-mark-ring-length) org-mark-ring)
7053 org-mark-ring)
7055 (defun org-mark-ring-push (&optional pos buffer)
7056 "Put the current position or POS into the mark ring and rotate it."
7057 (interactive)
7058 (setq pos (or pos (point)))
7059 (setq org-mark-ring (nthcdr (1- org-mark-ring-length) org-mark-ring))
7060 (move-marker (car org-mark-ring)
7061 (or pos (point))
7062 (or buffer (current-buffer)))
7063 (message "%s"
7064 (substitute-command-keys
7065 "Position saved to mark ring, go back with \\[org-mark-ring-goto].")))
7067 (defun org-mark-ring-goto (&optional n)
7068 "Jump to the previous position in the mark ring.
7069 With prefix arg N, jump back that many stored positions. When
7070 called several times in succession, walk through the entire ring.
7071 Org-mode commands jumping to a different position in the current file,
7072 or to another Org-mode file, automatically push the old position
7073 onto the ring."
7074 (interactive "p")
7075 (let (p m)
7076 (if (eq last-command this-command)
7077 (setq p (nthcdr n (or org-mark-ring-last-goto org-mark-ring)))
7078 (setq p org-mark-ring))
7079 (setq org-mark-ring-last-goto p)
7080 (setq m (car p))
7081 (switch-to-buffer (marker-buffer m))
7082 (goto-char m)
7083 (if (or (org-invisible-p) (org-invisible-p2)) (org-show-context 'mark-goto))))
7085 (defun org-remove-angle-brackets (s)
7086 (if (equal (substring s 0 1) "<") (setq s (substring s 1)))
7087 (if (equal (substring s -1) ">") (setq s (substring s 0 -1)))
7089 (defun org-add-angle-brackets (s)
7090 (if (equal (substring s 0 1) "<") nil (setq s (concat "<" s)))
7091 (if (equal (substring s -1) ">") nil (setq s (concat s ">")))
7094 ;;; Following specific links
7096 (defun org-follow-timestamp-link ()
7097 (cond
7098 ((org-at-date-range-p t)
7099 (let ((org-agenda-start-on-weekday)
7100 (t1 (match-string 1))
7101 (t2 (match-string 2)))
7102 (setq t1 (time-to-days (org-time-string-to-time t1))
7103 t2 (time-to-days (org-time-string-to-time t2)))
7104 (org-agenda-list nil t1 (1+ (- t2 t1)))))
7105 ((org-at-timestamp-p t)
7106 (org-agenda-list nil (time-to-days (org-time-string-to-time
7107 (substring (match-string 1) 0 10)))
7109 (t (error "This should not happen"))))
7112 ;;; Following file links
7113 (defvar org-wait nil)
7114 (defun org-open-file (path &optional in-emacs line search)
7115 "Open the file at PATH.
7116 First, this expands any special file name abbreviations. Then the
7117 configuration variable `org-file-apps' is checked if it contains an
7118 entry for this file type, and if yes, the corresponding command is launched.
7119 If no application is found, Emacs simply visits the file.
7120 With optional argument IN-EMACS, Emacs will visit the file.
7121 Optional LINE specifies a line to go to, optional SEARCH a string to
7122 search for. If LINE or SEARCH is given, the file will always be
7123 opened in Emacs.
7124 If the file does not exist, an error is thrown."
7125 (setq in-emacs (or in-emacs line search))
7126 (let* ((file (if (equal path "")
7127 buffer-file-name
7128 (substitute-in-file-name (expand-file-name path))))
7129 (apps (append org-file-apps (org-default-apps)))
7130 (remp (and (assq 'remote apps) (org-file-remote-p file)))
7131 (dirp (if remp nil (file-directory-p file)))
7132 (dfile (downcase file))
7133 (old-buffer (current-buffer))
7134 (old-pos (point))
7135 (old-mode major-mode)
7136 ext cmd)
7137 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\.gz\\)$" dfile)
7138 (setq ext (match-string 1 dfile))
7139 (if (string-match "^.*\\.\\([a-zA-Z0-9]+\\)$" dfile)
7140 (setq ext (match-string 1 dfile))))
7141 (if in-emacs
7142 (setq cmd 'emacs)
7143 (setq cmd (or (and remp (cdr (assoc 'remote apps)))
7144 (and dirp (cdr (assoc 'directory apps)))
7145 (cdr (assoc ext apps))
7146 (cdr (assoc t apps)))))
7147 (when (eq cmd 'mailcap)
7148 (require 'mailcap)
7149 (mailcap-parse-mailcaps)
7150 (let* ((mime-type (mailcap-extension-to-mime (or ext "")))
7151 (command (mailcap-mime-info mime-type)))
7152 (if (stringp command)
7153 (setq cmd command)
7154 (setq cmd 'emacs))))
7155 (if (and (not (eq cmd 'emacs)) ; Emacs has no problems with non-ex files
7156 (not (file-exists-p file))
7157 (not org-open-non-existing-files))
7158 (error "No such file: %s" file))
7159 (cond
7160 ((and (stringp cmd) (not (string-match "^\\s-*$" cmd)))
7161 ;; Remove quotes around the file name - we'll use shell-quote-argument.
7162 (while (string-match "['\"]%s['\"]" cmd)
7163 (setq cmd (replace-match "%s" t t cmd)))
7164 (while (string-match "%s" cmd)
7165 (setq cmd (replace-match
7166 (save-match-data (shell-quote-argument file))
7167 t t cmd)))
7168 (save-window-excursion
7169 (start-process-shell-command cmd nil cmd)
7170 (and (boundp 'org-wait) (numberp org-wait) (sit-for org-wait))
7172 ((or (stringp cmd)
7173 (eq cmd 'emacs))
7174 (funcall (cdr (assq 'file org-link-frame-setup)) file)
7175 (widen)
7176 (if line (goto-line line)
7177 (if search (org-link-search search))))
7178 ((consp cmd)
7179 (eval cmd))
7180 (t (funcall (cdr (assq 'file org-link-frame-setup)) file)))
7181 (and (org-mode-p) (eq old-mode 'org-mode)
7182 (or (not (equal old-buffer (current-buffer)))
7183 (not (equal old-pos (point))))
7184 (org-mark-ring-push old-pos old-buffer))))
7186 (defun org-default-apps ()
7187 "Return the default applications for this operating system."
7188 (cond
7189 ((eq system-type 'darwin)
7190 org-file-apps-defaults-macosx)
7191 ((eq system-type 'windows-nt)
7192 org-file-apps-defaults-windowsnt)
7193 (t org-file-apps-defaults-gnu)))
7195 (defvar ange-ftp-name-format) ; to silence the XEmacs compiler.
7196 (defun org-file-remote-p (file)
7197 "Test whether FILE specifies a location on a remote system.
7198 Return non-nil if the location is indeed remote.
7200 For example, the filename \"/user@host:/foo\" specifies a location
7201 on the system \"/user@host:\"."
7202 (cond ((fboundp 'file-remote-p)
7203 (file-remote-p file))
7204 ((fboundp 'tramp-handle-file-remote-p)
7205 (tramp-handle-file-remote-p file))
7206 ((and (boundp 'ange-ftp-name-format)
7207 (string-match (car ange-ftp-name-format) file))
7209 (t nil)))
7212 ;;;; Refiling
7214 (defun org-get-org-file ()
7215 "Read a filename, with default directory `org-directory'."
7216 (let ((default (or org-default-notes-file remember-data-file)))
7217 (read-file-name (format "File name [%s]: " default)
7218 (file-name-as-directory org-directory)
7219 default)))
7221 (defun org-notes-order-reversed-p ()
7222 "Check if the current file should receive notes in reversed order."
7223 (cond
7224 ((not org-reverse-note-order) nil)
7225 ((eq t org-reverse-note-order) t)
7226 ((not (listp org-reverse-note-order)) nil)
7227 (t (catch 'exit
7228 (let ((all org-reverse-note-order)
7229 entry)
7230 (while (setq entry (pop all))
7231 (if (string-match (car entry) buffer-file-name)
7232 (throw 'exit (cdr entry))))
7233 nil)))))
7235 (defvar org-refile-target-table nil
7236 "The list of refile targets, created by `org-refile'.")
7238 (defvar org-agenda-new-buffers nil
7239 "Buffers created to visit agenda files.")
7241 (defun org-get-refile-targets (&optional default-buffer)
7242 "Produce a table with refile targets."
7243 (let ((entries (or org-refile-targets '((nil . (:level . 1)))))
7244 targets txt re files f desc descre)
7245 (with-current-buffer (or default-buffer (current-buffer))
7246 (while (setq entry (pop entries))
7247 (setq files (car entry) desc (cdr entry))
7248 (cond
7249 ((null files) (setq files (list (current-buffer))))
7250 ((eq files 'org-agenda-files)
7251 (setq files (org-agenda-files 'unrestricted)))
7252 ((and (symbolp files) (fboundp files))
7253 (setq files (funcall files)))
7254 ((and (symbolp files) (boundp files))
7255 (setq files (symbol-value files))))
7256 (if (stringp files) (setq files (list files)))
7257 (cond
7258 ((eq (car desc) :tag)
7259 (setq descre (concat "^\\*+[ \t]+.*?:" (regexp-quote (cdr desc)) ":")))
7260 ((eq (car desc) :todo)
7261 (setq descre (concat "^\\*+[ \t]+" (regexp-quote (cdr desc)) "[ \t]")))
7262 ((eq (car desc) :regexp)
7263 (setq descre (cdr desc)))
7264 ((eq (car desc) :level)
7265 (setq descre (concat "^\\*\\{" (number-to-string
7266 (if org-odd-levels-only
7267 (1- (* 2 (cdr desc)))
7268 (cdr desc)))
7269 "\\}[ \t]")))
7270 ((eq (car desc) :maxlevel)
7271 (setq descre (concat "^\\*\\{1," (number-to-string
7272 (if org-odd-levels-only
7273 (1- (* 2 (cdr desc)))
7274 (cdr desc)))
7275 "\\}[ \t]")))
7276 (t (error "Bad refiling target description %s" desc)))
7277 (while (setq f (pop files))
7278 (save-excursion
7279 (set-buffer (if (bufferp f) f (org-get-agenda-file-buffer f)))
7280 (if (bufferp f) (setq f (buffer-file-name (buffer-base-buffer f))))
7281 (save-excursion
7282 (save-restriction
7283 (widen)
7284 (goto-char (point-min))
7285 (while (re-search-forward descre nil t)
7286 (goto-char (point-at-bol))
7287 (when (looking-at org-complex-heading-regexp)
7288 (setq txt (match-string 4)
7289 re (concat "^" (regexp-quote
7290 (buffer-substring (match-beginning 1)
7291 (match-end 4)))))
7292 (if (match-end 5) (setq re (concat re "[ \t]+"
7293 (regexp-quote
7294 (match-string 5)))))
7295 (setq re (concat re "[ \t]*$"))
7296 (when org-refile-use-outline-path
7297 (setq txt (mapconcat 'identity
7298 (append
7299 (if (eq org-refile-use-outline-path 'file)
7300 (list (file-name-nondirectory
7301 (buffer-file-name (buffer-base-buffer))))
7302 (if (eq org-refile-use-outline-path 'full-file-path)
7303 (list (buffer-file-name (buffer-base-buffer)))))
7304 (org-get-outline-path)
7305 (list txt))
7306 "/")))
7307 (push (list txt f re (point)) targets))
7308 (goto-char (point-at-eol))))))))
7309 (nreverse targets))))
7311 (defun org-get-outline-path ()
7312 "Return the outline path to the current entry, as a list."
7313 (let (rtn)
7314 (save-excursion
7315 (while (org-up-heading-safe)
7316 (when (looking-at org-complex-heading-regexp)
7317 (push (org-match-string-no-properties 4) rtn)))
7318 rtn)))
7320 (defvar org-refile-history nil
7321 "History for refiling operations.")
7323 (defun org-refile (&optional goto default-buffer)
7324 "Move the entry at point to another heading.
7325 The list of target headings is compiled using the information in
7326 `org-refile-targets', which see. This list is created before each use
7327 and will therefore always be up-to-date.
7329 At the target location, the entry is filed as a subitem of the target heading.
7330 Depending on `org-reverse-note-order', the new subitem will either be the
7331 first of the last subitem.
7333 With prefix arg GOTO, the command will only visit the target location,
7334 not actually move anything.
7335 With a double prefix `C-c C-c', go to the location where the last refiling
7336 operation has put the subtree."
7337 (interactive "P")
7338 (let* ((cbuf (current-buffer))
7339 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7340 pos it nbuf file re level reversed)
7341 (if (equal goto '(16))
7342 (org-refile-goto-last-stored)
7343 (when (setq it (org-refile-get-location
7344 (if goto "Goto: " "Refile to: ") default-buffer))
7345 (setq file (nth 1 it)
7346 re (nth 2 it)
7347 pos (nth 3 it))
7348 (setq nbuf (or (find-buffer-visiting file)
7349 (find-file-noselect file)))
7350 (if goto
7351 (progn
7352 (switch-to-buffer nbuf)
7353 (goto-char pos)
7354 (org-show-context 'org-goto))
7355 (org-copy-special)
7356 (save-excursion
7357 (set-buffer (setq nbuf (or (find-buffer-visiting file)
7358 (find-file-noselect file))))
7359 (setq reversed (org-notes-order-reversed-p))
7360 (save-excursion
7361 (save-restriction
7362 (widen)
7363 (goto-char pos)
7364 (looking-at outline-regexp)
7365 (setq level (org-get-valid-level (funcall outline-level) 1))
7366 (goto-char
7367 (if reversed
7368 (outline-next-heading)
7369 (or (save-excursion (outline-get-next-sibling))
7370 (org-end-of-subtree t t)
7371 (point-max))))
7372 (bookmark-set "org-refile-last-stored")
7373 (org-paste-subtree level))))
7374 (org-cut-special)
7375 (message "Entry refiled to \"%s\"" (car it)))))))
7377 (defun org-refile-goto-last-stored ()
7378 "Go to the location where the last refile was stored."
7379 (interactive)
7380 (bookmark-jump "org-refile-last-stored")
7381 (message "This is the location of the last refile"))
7383 (defun org-refile-get-location (&optional prompt default-buffer)
7384 "Prompt the user for a refile location, using PROMPT."
7385 (let ((org-refile-targets org-refile-targets)
7386 (org-refile-use-outline-path org-refile-use-outline-path))
7387 (setq org-refile-target-table (org-get-refile-targets default-buffer)))
7388 (unless org-refile-target-table
7389 (error "No refile targets"))
7390 (let* ((cbuf (current-buffer))
7391 (filename (buffer-file-name (buffer-base-buffer cbuf)))
7392 (fname (and filename (file-truename filename)))
7393 (tbl (mapcar
7394 (lambda (x)
7395 (if (not (equal fname (file-truename (nth 1 x))))
7396 (cons (concat (car x) " (" (file-name-nondirectory
7397 (nth 1 x)) ")")
7398 (cdr x))
7400 org-refile-target-table))
7401 (completion-ignore-case t))
7402 (assoc (completing-read prompt tbl nil t nil 'org-refile-history)
7403 tbl)))
7405 ;;;; Dynamic blocks
7407 (defun org-find-dblock (name)
7408 "Find the first dynamic block with name NAME in the buffer.
7409 If not found, stay at current position and return nil."
7410 (let (pos)
7411 (save-excursion
7412 (goto-char (point-min))
7413 (setq pos (and (re-search-forward (concat "^#\\+BEGIN:[ \t]+" name "\\>")
7414 nil t)
7415 (match-beginning 0))))
7416 (if pos (goto-char pos))
7417 pos))
7419 (defconst org-dblock-start-re
7420 "^#\\+BEGIN:[ \t]+\\(\\S-+\\)\\([ \t]+\\(.*\\)\\)?"
7421 "Matches the startline of a dynamic block, with parameters.")
7423 (defconst org-dblock-end-re "^#\\+END\\([: \t\r\n]\\|$\\)"
7424 "Matches the end of a dyhamic block.")
7426 (defun org-create-dblock (plist)
7427 "Create a dynamic block section, with parameters taken from PLIST.
7428 PLIST must containe a :name entry which is used as name of the block."
7429 (unless (bolp) (newline))
7430 (let ((name (plist-get plist :name)))
7431 (insert "#+BEGIN: " name)
7432 (while plist
7433 (if (eq (car plist) :name)
7434 (setq plist (cddr plist))
7435 (insert " " (prin1-to-string (pop plist)))))
7436 (insert "\n\n#+END:\n")
7437 (beginning-of-line -2)))
7439 (defun org-prepare-dblock ()
7440 "Prepare dynamic block for refresh.
7441 This empties the block, puts the cursor at the insert position and returns
7442 the property list including an extra property :name with the block name."
7443 (unless (looking-at org-dblock-start-re)
7444 (error "Not at a dynamic block"))
7445 (let* ((begdel (1+ (match-end 0)))
7446 (name (org-no-properties (match-string 1)))
7447 (params (append (list :name name)
7448 (read (concat "(" (match-string 3) ")")))))
7449 (unless (re-search-forward org-dblock-end-re nil t)
7450 (error "Dynamic block not terminated"))
7451 (setq params
7452 (append params
7453 (list :content (buffer-substring
7454 begdel (match-beginning 0)))))
7455 (delete-region begdel (match-beginning 0))
7456 (goto-char begdel)
7457 (open-line 1)
7458 params))
7460 (defun org-map-dblocks (&optional command)
7461 "Apply COMMAND to all dynamic blocks in the current buffer.
7462 If COMMAND is not given, use `org-update-dblock'."
7463 (let ((cmd (or command 'org-update-dblock))
7464 pos)
7465 (save-excursion
7466 (goto-char (point-min))
7467 (while (re-search-forward org-dblock-start-re nil t)
7468 (goto-char (setq pos (match-beginning 0)))
7469 (condition-case nil
7470 (funcall cmd)
7471 (error (message "Error during update of dynamic block")))
7472 (goto-char pos)
7473 (unless (re-search-forward org-dblock-end-re nil t)
7474 (error "Dynamic block not terminated"))))))
7476 (defun org-dblock-update (&optional arg)
7477 "User command for updating dynamic blocks.
7478 Update the dynamic block at point. With prefix ARG, update all dynamic
7479 blocks in the buffer."
7480 (interactive "P")
7481 (if arg
7482 (org-update-all-dblocks)
7483 (or (looking-at org-dblock-start-re)
7484 (org-beginning-of-dblock))
7485 (org-update-dblock)))
7487 (defun org-update-dblock ()
7488 "Update the dynamic block at point
7489 This means to empty the block, parse for parameters and then call
7490 the correct writing function."
7491 (save-window-excursion
7492 (let* ((pos (point))
7493 (line (org-current-line))
7494 (params (org-prepare-dblock))
7495 (name (plist-get params :name))
7496 (cmd (intern (concat "org-dblock-write:" name))))
7497 (message "Updating dynamic block `%s' at line %d..." name line)
7498 (funcall cmd params)
7499 (message "Updating dynamic block `%s' at line %d...done" name line)
7500 (goto-char pos))))
7502 (defun org-beginning-of-dblock ()
7503 "Find the beginning of the dynamic block at point.
7504 Error if there is no scuh block at point."
7505 (let ((pos (point))
7506 beg)
7507 (end-of-line 1)
7508 (if (and (re-search-backward org-dblock-start-re nil t)
7509 (setq beg (match-beginning 0))
7510 (re-search-forward org-dblock-end-re nil t)
7511 (> (match-end 0) pos))
7512 (goto-char beg)
7513 (goto-char pos)
7514 (error "Not in a dynamic block"))))
7516 (defun org-update-all-dblocks ()
7517 "Update all dynamic blocks in the buffer.
7518 This function can be used in a hook."
7519 (when (org-mode-p)
7520 (org-map-dblocks 'org-update-dblock)))
7523 ;;;; Completion
7525 (defconst org-additional-option-like-keywords
7526 '("BEGIN_HTML" "BEGIN_LaTeX" "END_HTML" "END_LaTeX"
7527 "ORGTBL" "HTML:" "LaTeX:" "BEGIN:" "END:" "TBLFM"
7528 "BEGIN_EXAMPLE" "END_EXAMPLE"))
7530 (defun org-complete (&optional arg)
7531 "Perform completion on word at point.
7532 At the beginning of a headline, this completes TODO keywords as given in
7533 `org-todo-keywords'.
7534 If the current word is preceded by a backslash, completes the TeX symbols
7535 that are supported for HTML support.
7536 If the current word is preceded by \"#+\", completes special words for
7537 setting file options.
7538 In the line after \"#+STARTUP:, complete valid keywords.\"
7539 At all other locations, this simply calls the value of
7540 `org-completion-fallback-command'."
7541 (interactive "P")
7542 (org-without-partial-completion
7543 (catch 'exit
7544 (let* ((end (point))
7545 (beg1 (save-excursion
7546 (skip-chars-backward (org-re "[:alnum:]_@"))
7547 (point)))
7548 (beg (save-excursion
7549 (skip-chars-backward "a-zA-Z0-9_:$")
7550 (point)))
7551 (confirm (lambda (x) (stringp (car x))))
7552 (searchhead (equal (char-before beg) ?*))
7553 (tag (and (equal (char-before beg1) ?:)
7554 (equal (char-after (point-at-bol)) ?*)))
7555 (prop (and (equal (char-before beg1) ?:)
7556 (not (equal (char-after (point-at-bol)) ?*))))
7557 (texp (equal (char-before beg) ?\\))
7558 (link (equal (char-before beg) ?\[))
7559 (opt (equal (buffer-substring (max (point-at-bol) (- beg 2))
7560 beg)
7561 "#+"))
7562 (startup (string-match "^#\\+STARTUP:.*"
7563 (buffer-substring (point-at-bol) (point))))
7564 (completion-ignore-case opt)
7565 (type nil)
7566 (tbl nil)
7567 (table (cond
7568 (opt
7569 (setq type :opt)
7570 (require 'org-exp)
7571 (append
7572 (mapcar
7573 (lambda (x)
7574 (string-match "^#\\+\\(\\([A-Z_]+:?\\).*\\)" x)
7575 (cons (match-string 2 x) (match-string 1 x)))
7576 (org-split-string (org-get-current-options) "\n"))
7577 (mapcar 'list org-additional-option-like-keywords)))
7578 (startup
7579 (setq type :startup)
7580 org-startup-options)
7581 (link (append org-link-abbrev-alist-local
7582 org-link-abbrev-alist))
7583 (texp
7584 (setq type :tex)
7585 org-html-entities)
7586 ((string-match "\\`\\*+[ \t]+\\'"
7587 (buffer-substring (point-at-bol) beg))
7588 (setq type :todo)
7589 (mapcar 'list org-todo-keywords-1))
7590 (searchhead
7591 (setq type :searchhead)
7592 (save-excursion
7593 (goto-char (point-min))
7594 (while (re-search-forward org-todo-line-regexp nil t)
7595 (push (list
7596 (org-make-org-heading-search-string
7597 (match-string 3) t))
7598 tbl)))
7599 tbl)
7600 (tag (setq type :tag beg beg1)
7601 (or org-tag-alist (org-get-buffer-tags)))
7602 (prop (setq type :prop beg beg1)
7603 (mapcar 'list (org-buffer-property-keys nil t t)))
7604 (t (progn
7605 (call-interactively org-completion-fallback-command)
7606 (throw 'exit nil)))))
7607 (pattern (buffer-substring-no-properties beg end))
7608 (completion (try-completion pattern table confirm)))
7609 (cond ((eq completion t)
7610 (if (not (assoc (upcase pattern) table))
7611 (message "Already complete")
7612 (if (and (equal type :opt)
7613 (not (member (car (assoc (upcase pattern) table))
7614 org-additional-option-like-keywords)))
7615 (insert (substring (cdr (assoc (upcase pattern) table))
7616 (length pattern)))
7617 (if (memq type '(:tag :prop)) (insert ":")))))
7618 ((null completion)
7619 (message "Can't find completion for \"%s\"" pattern)
7620 (ding))
7621 ((not (string= pattern completion))
7622 (delete-region beg end)
7623 (if (string-match " +$" completion)
7624 (setq completion (replace-match "" t t completion)))
7625 (insert completion)
7626 (if (get-buffer-window "*Completions*")
7627 (delete-window (get-buffer-window "*Completions*")))
7628 (if (assoc completion table)
7629 (if (eq type :todo) (insert " ")
7630 (if (memq type '(:tag :prop)) (insert ":"))))
7631 (if (and (equal type :opt) (assoc completion table))
7632 (message "%s" (substitute-command-keys
7633 "Press \\[org-complete] again to insert example settings"))))
7635 (message "Making completion list...")
7636 (let ((list (sort (all-completions pattern table confirm)
7637 'string<)))
7638 (with-output-to-temp-buffer "*Completions*"
7639 (condition-case nil
7640 ;; Protection needed for XEmacs and emacs 21
7641 (display-completion-list list pattern)
7642 (error (display-completion-list list)))))
7643 (message "Making completion list...%s" "done")))))))
7645 ;;;; TODO, DEADLINE, Comments
7647 (defun org-toggle-comment ()
7648 "Change the COMMENT state of an entry."
7649 (interactive)
7650 (save-excursion
7651 (org-back-to-heading)
7652 (let (case-fold-search)
7653 (if (looking-at (concat outline-regexp
7654 "\\( *\\<" org-comment-string "\\>[ \t]*\\)"))
7655 (replace-match "" t t nil 1)
7656 (if (looking-at outline-regexp)
7657 (progn
7658 (goto-char (match-end 0))
7659 (insert org-comment-string " ")))))))
7661 (defvar org-last-todo-state-is-todo nil
7662 "This is non-nil when the last TODO state change led to a TODO state.
7663 If the last change removed the TODO tag or switched to DONE, then
7664 this is nil.")
7666 (defvar org-setting-tags nil) ; dynamically skiped
7668 (defun org-parse-local-options (string var)
7669 "Parse STRING for startup setting relevant for variable VAR."
7670 (let ((rtn (symbol-value var))
7671 e opts)
7672 (save-match-data
7673 (if (or (not string) (not (string-match "\\S-" string)))
7675 (setq opts (delq nil (mapcar (lambda (x)
7676 (setq e (assoc x org-startup-options))
7677 (if (eq (nth 1 e) var) e nil))
7678 (org-split-string string "[ \t]+"))))
7679 (if (not opts)
7681 (setq rtn nil)
7682 (while (setq e (pop opts))
7683 (if (not (nth 3 e))
7684 (setq rtn (nth 2 e))
7685 (if (not (listp rtn)) (setq rtn nil))
7686 (push (nth 2 e) rtn)))
7687 rtn)))))
7689 (defvar org-blocker-hook nil
7690 "Hook for functions that are allowed to block a state change.
7692 Each function gets as its single argument a property list, see
7693 `org-trigger-hook' for more information about this list.
7695 If any of the functions in this hook returns nil, the state change
7696 is blocked.")
7698 (defvar org-trigger-hook nil
7699 "Hook for functions that are triggered by a state change.
7701 Each function gets as its single argument a property list with at least
7702 the following elements:
7704 (:type type-of-change :position pos-at-entry-start
7705 :from old-state :to new-state)
7707 Depending on the type, more properties may be present.
7709 This mechanism is currently implemented for:
7711 TODO state changes
7712 ------------------
7713 :type todo-state-change
7714 :from previous state (keyword as a string), or nil
7715 :to new state (keyword as a string), or nil")
7718 (defun org-todo (&optional arg)
7719 "Change the TODO state of an item.
7720 The state of an item is given by a keyword at the start of the heading,
7721 like
7722 *** TODO Write paper
7723 *** DONE Call mom
7725 The different keywords are specified in the variable `org-todo-keywords'.
7726 By default the available states are \"TODO\" and \"DONE\".
7727 So for this example: when the item starts with TODO, it is changed to DONE.
7728 When it starts with DONE, the DONE is removed. And when neither TODO nor
7729 DONE are present, add TODO at the beginning of the heading.
7731 With C-u prefix arg, use completion to determine the new state.
7732 With numeric prefix arg, switch to that state.
7734 For calling through lisp, arg is also interpreted in the following way:
7735 'none -> empty state
7736 \"\"(empty string) -> switch to empty state
7737 'done -> switch to DONE
7738 'nextset -> switch to the next set of keywords
7739 'previousset -> switch to the previous set of keywords
7740 \"WAITING\" -> switch to the specified keyword, but only if it
7741 really is a member of `org-todo-keywords'."
7742 (interactive "P")
7743 (save-excursion
7744 (catch 'exit
7745 (org-back-to-heading)
7746 (if (looking-at outline-regexp) (goto-char (1- (match-end 0))))
7747 (or (looking-at (concat " +" org-todo-regexp " *"))
7748 (looking-at " *"))
7749 (let* ((match-data (match-data))
7750 (startpos (point-at-bol))
7751 (logging (save-match-data (org-entry-get nil "LOGGING" t)))
7752 (org-log-done org-log-done)
7753 (org-log-repeat org-log-repeat)
7754 (org-todo-log-states org-todo-log-states)
7755 (this (match-string 1))
7756 (hl-pos (match-beginning 0))
7757 (head (org-get-todo-sequence-head this))
7758 (ass (assoc head org-todo-kwd-alist))
7759 (interpret (nth 1 ass))
7760 (done-word (nth 3 ass))
7761 (final-done-word (nth 4 ass))
7762 (last-state (or this ""))
7763 (completion-ignore-case t)
7764 (member (member this org-todo-keywords-1))
7765 (tail (cdr member))
7766 (state (cond
7767 ((and org-todo-key-trigger
7768 (or (and (equal arg '(4)) (eq org-use-fast-todo-selection 'prefix))
7769 (and (not arg) org-use-fast-todo-selection
7770 (not (eq org-use-fast-todo-selection 'prefix)))))
7771 ;; Use fast selection
7772 (org-fast-todo-selection))
7773 ((and (equal arg '(4))
7774 (or (not org-use-fast-todo-selection)
7775 (not org-todo-key-trigger)))
7776 ;; Read a state with completion
7777 (completing-read "State: " (mapcar (lambda(x) (list x))
7778 org-todo-keywords-1)
7779 nil t))
7780 ((eq arg 'right)
7781 (if this
7782 (if tail (car tail) nil)
7783 (car org-todo-keywords-1)))
7784 ((eq arg 'left)
7785 (if (equal member org-todo-keywords-1)
7787 (if this
7788 (nth (- (length org-todo-keywords-1) (length tail) 2)
7789 org-todo-keywords-1)
7790 (org-last org-todo-keywords-1))))
7791 ((and (eq org-use-fast-todo-selection t) (equal arg '(4))
7792 (setq arg nil))) ; hack to fall back to cycling
7793 (arg
7794 ;; user or caller requests a specific state
7795 (cond
7796 ((equal arg "") nil)
7797 ((eq arg 'none) nil)
7798 ((eq arg 'done) (or done-word (car org-done-keywords)))
7799 ((eq arg 'nextset)
7800 (or (car (cdr (member head org-todo-heads)))
7801 (car org-todo-heads)))
7802 ((eq arg 'previousset)
7803 (let ((org-todo-heads (reverse org-todo-heads)))
7804 (or (car (cdr (member head org-todo-heads)))
7805 (car org-todo-heads))))
7806 ((car (member arg org-todo-keywords-1)))
7807 ((nth (1- (prefix-numeric-value arg))
7808 org-todo-keywords-1))))
7809 ((null member) (or head (car org-todo-keywords-1)))
7810 ((equal this final-done-word) nil) ;; -> make empty
7811 ((null tail) nil) ;; -> first entry
7812 ((eq interpret 'sequence)
7813 (car tail))
7814 ((memq interpret '(type priority))
7815 (if (eq this-command last-command)
7816 (car tail)
7817 (if (> (length tail) 0)
7818 (or done-word (car org-done-keywords))
7819 nil)))
7820 (t nil)))
7821 (next (if state (concat " " state " ") " "))
7822 (change-plist (list :type 'todo-state-change :from this :to state
7823 :position startpos))
7824 dolog now-done-p)
7825 (when org-blocker-hook
7826 (unless (save-excursion
7827 (save-match-data
7828 (run-hook-with-args-until-failure
7829 'org-blocker-hook change-plist)))
7830 (if (interactive-p)
7831 (error "TODO state change from %s to %s blocked" this state)
7832 ;; fail silently
7833 (message "TODO state change from %s to %s blocked" this state)
7834 (throw 'exit nil))))
7835 (store-match-data match-data)
7836 (replace-match next t t)
7837 (unless (pos-visible-in-window-p hl-pos)
7838 (message "TODO state changed to %s" (org-trim next)))
7839 (unless head
7840 (setq head (org-get-todo-sequence-head state)
7841 ass (assoc head org-todo-kwd-alist)
7842 interpret (nth 1 ass)
7843 done-word (nth 3 ass)
7844 final-done-word (nth 4 ass)))
7845 (when (memq arg '(nextset previousset))
7846 (message "Keyword-Set %d/%d: %s"
7847 (- (length org-todo-sets) -1
7848 (length (memq (assoc state org-todo-sets) org-todo-sets)))
7849 (length org-todo-sets)
7850 (mapconcat 'identity (assoc state org-todo-sets) " ")))
7851 (setq org-last-todo-state-is-todo
7852 (not (member state org-done-keywords)))
7853 (setq now-done-p (and (member state org-done-keywords)
7854 (not (member this org-done-keywords))))
7855 (and logging (org-local-logging logging))
7856 (when (and (or org-todo-log-states org-log-done)
7857 (not (memq arg '(nextset previousset))))
7858 ;; we need to look at recording a time and note
7859 (setq dolog (or (nth 1 (assoc state org-todo-log-states))
7860 (nth 2 (assoc this org-todo-log-states))))
7861 (when (and state
7862 (member state org-not-done-keywords)
7863 (not (member this org-not-done-keywords)))
7864 ;; This is now a todo state and was not one before
7865 ;; If there was a CLOSED time stamp, get rid of it.
7866 (org-add-planning-info nil nil 'closed))
7867 (when (and now-done-p org-log-done)
7868 ;; It is now done, and it was not done before
7869 (org-add-planning-info 'closed (org-current-time))
7870 (if (and (not dolog) (eq 'note org-log-done))
7871 (org-add-log-setup 'done state 'findpos 'note)))
7872 (when (and state dolog)
7873 ;; This is a non-nil state, and we need to log it
7874 (org-add-log-setup 'state state 'findpos dolog)))
7875 ;; Fixup tag positioning
7876 (and org-auto-align-tags (not org-setting-tags) (org-set-tags nil t))
7877 (run-hooks 'org-after-todo-state-change-hook)
7878 (if (and arg (not (member state org-done-keywords)))
7879 (setq head (org-get-todo-sequence-head state)))
7880 (put-text-property (point-at-bol) (point-at-eol) 'org-todo-head head)
7881 ;; Do we need to trigger a repeat?
7882 (when now-done-p (org-auto-repeat-maybe state))
7883 ;; Fixup cursor location if close to the keyword
7884 (if (and (outline-on-heading-p)
7885 (not (bolp))
7886 (save-excursion (beginning-of-line 1)
7887 (looking-at org-todo-line-regexp))
7888 (< (point) (+ 2 (or (match-end 2) (match-end 1)))))
7889 (progn
7890 (goto-char (or (match-end 2) (match-end 1)))
7891 (just-one-space)))
7892 (when org-trigger-hook
7893 (save-excursion
7894 (run-hook-with-args 'org-trigger-hook change-plist)))))))
7896 (defun org-local-logging (value)
7897 "Get logging settings from a property VALUE."
7898 (let* (words w a)
7899 ;; directly set the variables, they are already local.
7900 (setq org-log-done nil
7901 org-log-repeat nil
7902 org-todo-log-states nil)
7903 (setq words (org-split-string value))
7904 (while (setq w (pop words))
7905 (cond
7906 ((setq a (assoc w org-startup-options))
7907 (and (member (nth 1 a) '(org-log-done org-log-repeat))
7908 (set (nth 1 a) (nth 2 a))))
7909 ((setq a (org-extract-log-state-settings w))
7910 (and (member (car a) org-todo-keywords-1)
7911 (push a org-todo-log-states)))))))
7913 (defun org-get-todo-sequence-head (kwd)
7914 "Return the head of the TODO sequence to which KWD belongs.
7915 If KWD is not set, check if there is a text property remembering the
7916 right sequence."
7917 (let (p)
7918 (cond
7919 ((not kwd)
7920 (or (get-text-property (point-at-bol) 'org-todo-head)
7921 (progn
7922 (setq p (next-single-property-change (point-at-bol) 'org-todo-head
7923 nil (point-at-eol)))
7924 (get-text-property p 'org-todo-head))))
7925 ((not (member kwd org-todo-keywords-1))
7926 (car org-todo-keywords-1))
7927 (t (nth 2 (assoc kwd org-todo-kwd-alist))))))
7929 (defun org-fast-todo-selection ()
7930 "Fast TODO keyword selection with single keys.
7931 Returns the new TODO keyword, or nil if no state change should occur."
7932 (let* ((fulltable org-todo-key-alist)
7933 (done-keywords org-done-keywords) ;; needed for the faces.
7934 (maxlen (apply 'max (mapcar
7935 (lambda (x)
7936 (if (stringp (car x)) (string-width (car x)) 0))
7937 fulltable)))
7938 (expert nil)
7939 (fwidth (+ maxlen 3 1 3))
7940 (ncol (/ (- (window-width) 4) fwidth))
7941 tg cnt e c tbl
7942 groups ingroup)
7943 (save-window-excursion
7944 (if expert
7945 (set-buffer (get-buffer-create " *Org todo*"))
7946 (org-switch-to-buffer-other-window (get-buffer-create " *Org todo*")))
7947 (erase-buffer)
7948 (org-set-local 'org-done-keywords done-keywords)
7949 (setq tbl fulltable cnt 0)
7950 (while (setq e (pop tbl))
7951 (cond
7952 ((equal e '(:startgroup))
7953 (push '() groups) (setq ingroup t)
7954 (when (not (= cnt 0))
7955 (setq cnt 0)
7956 (insert "\n"))
7957 (insert "{ "))
7958 ((equal e '(:endgroup))
7959 (setq ingroup nil cnt 0)
7960 (insert "}\n"))
7962 (setq tg (car e) c (cdr e))
7963 (if ingroup (push tg (car groups)))
7964 (setq tg (org-add-props tg nil 'face
7965 (org-get-todo-face tg)))
7966 (if (and (= cnt 0) (not ingroup)) (insert " "))
7967 (insert "[" c "] " tg (make-string
7968 (- fwidth 4 (length tg)) ?\ ))
7969 (when (= (setq cnt (1+ cnt)) ncol)
7970 (insert "\n")
7971 (if ingroup (insert " "))
7972 (setq cnt 0)))))
7973 (insert "\n")
7974 (goto-char (point-min))
7975 (if (and (not expert) (fboundp 'fit-window-to-buffer))
7976 (fit-window-to-buffer))
7977 (message "[a-z..]:Set [SPC]:clear")
7978 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
7979 (cond
7980 ((or (= c ?\C-g)
7981 (and (= c ?q) (not (rassoc c fulltable))))
7982 (setq quit-flag t))
7983 ((= c ?\ ) nil)
7984 ((setq e (rassoc c fulltable) tg (car e))
7986 (t (setq quit-flag t))))))
7988 (defun org-entry-is-todo-p ()
7989 (member (org-get-todo-state) org-not-done-keywords))
7991 (defun org-entry-is-done-p ()
7992 (member (org-get-todo-state) org-done-keywords))
7994 (defun org-get-todo-state ()
7995 (save-excursion
7996 (org-back-to-heading t)
7997 (and (looking-at org-todo-line-regexp)
7998 (match-end 2)
7999 (match-string 2))))
8001 (defun org-at-date-range-p (&optional inactive-ok)
8002 "Is the cursor inside a date range?"
8003 (interactive)
8004 (save-excursion
8005 (catch 'exit
8006 (let ((pos (point)))
8007 (skip-chars-backward "^[<\r\n")
8008 (skip-chars-backward "<[")
8009 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8010 (>= (match-end 0) pos)
8011 (throw 'exit t))
8012 (skip-chars-backward "^<[\r\n")
8013 (skip-chars-backward "<[")
8014 (and (looking-at (if inactive-ok org-tr-regexp-both org-tr-regexp))
8015 (>= (match-end 0) pos)
8016 (throw 'exit t)))
8017 nil)))
8019 (defun org-get-repeat ()
8020 "Check if tere is a deadline/schedule with repeater in this entry."
8021 (save-match-data
8022 (save-excursion
8023 (org-back-to-heading t)
8024 (if (re-search-forward
8025 org-repeat-re (save-excursion (outline-next-heading) (point)) t)
8026 (match-string 1)))))
8028 (defvar org-last-changed-timestamp)
8029 (defvar org-log-post-message)
8030 (defvar org-log-note-purpose)
8031 (defvar org-log-note-how)
8032 (defun org-auto-repeat-maybe (done-word)
8033 "Check if the current headline contains a repeated deadline/schedule.
8034 If yes, set TODO state back to what it was and change the base date
8035 of repeating deadline/scheduled time stamps to new date.
8036 This function is run automatically after each state change to a DONE state."
8037 ;; last-state is dynamically scoped into this function
8038 (let* ((repeat (org-get-repeat))
8039 (aa (assoc last-state org-todo-kwd-alist))
8040 (interpret (nth 1 aa))
8041 (head (nth 2 aa))
8042 (whata '(("d" . day) ("m" . month) ("y" . year)))
8043 (msg "Entry repeats: ")
8044 (org-log-done nil)
8045 (org-todo-log-states nil)
8046 (nshiftmax 10) (nshift 0)
8047 re type n what ts mb0 time)
8048 (when repeat
8049 (if (eq org-log-repeat t) (setq org-log-repeat 'state))
8050 (org-todo (if (eq interpret 'type) last-state head))
8051 (when org-log-repeat
8052 (if (or (memq 'org-add-log-note (default-value 'post-command-hook))
8053 (memq 'org-add-log-note post-command-hook))
8054 ;; OK, we are already setup for some record
8055 (if (eq org-log-repeat 'note)
8056 ;; make sure we take a note, not only a time stamp
8057 (setq org-log-note-how 'note))
8058 ;; Set up for taking a record
8059 (org-add-log-setup 'state (or done-word (car org-done-keywords))
8060 'findpos org-log-repeat)))
8061 (org-back-to-heading t)
8062 (org-add-planning-info nil nil 'closed)
8063 (setq re (concat "\\(" org-scheduled-time-regexp "\\)\\|\\("
8064 org-deadline-time-regexp "\\)\\|\\("
8065 org-ts-regexp "\\)"))
8066 (while (re-search-forward
8067 re (save-excursion (outline-next-heading) (point)) t)
8068 (setq type (if (match-end 1) org-scheduled-string
8069 (if (match-end 3) org-deadline-string "Plain:"))
8070 ts (match-string (if (match-end 2) 2 (if (match-end 4) 4 0)))
8071 mb0 (match-beginning 0))
8072 (when (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts)
8073 (setq n (string-to-number (match-string 2 ts))
8074 what (match-string 3 ts))
8075 (if (equal what "w") (setq n (* n 7) what "d"))
8076 ;; Preparation, see if we need to modify the start date for the change
8077 (when (match-end 1)
8078 (setq time (save-match-data (org-time-string-to-time ts)))
8079 (cond
8080 ((equal (match-string 1 ts) ".")
8081 ;; Shift starting date to today
8082 (org-timestamp-change
8083 (- (time-to-days (current-time)) (time-to-days time))
8084 'day))
8085 ((equal (match-string 1 ts) "+")
8086 (while (or (= nshift 0)
8087 (<= (time-to-days time) (time-to-days (current-time))))
8088 (when (= (incf nshift) nshiftmax)
8089 (or (y-or-n-p (message "%d repeater intervals were not enough to shift date past today. Continue? " nshift))
8090 (error "Abort")))
8091 (org-timestamp-change n (cdr (assoc what whata)))
8092 (org-at-timestamp-p t)
8093 (setq ts (match-string 1))
8094 (setq time (save-match-data (org-time-string-to-time ts))))
8095 (org-timestamp-change (- n) (cdr (assoc what whata)))
8096 ;; rematch, so that we have everything in place for the real shift
8097 (org-at-timestamp-p t)
8098 (setq ts (match-string 1))
8099 (string-match "\\([.+]\\)?\\(\\+[0-9]+\\)\\([dwmy]\\)" ts))))
8100 (org-timestamp-change n (cdr (assoc what whata)))
8101 (setq msg (concat msg type org-last-changed-timestamp " "))))
8102 (setq org-log-post-message msg)
8103 (message "%s" msg))))
8105 (defun org-show-todo-tree (arg)
8106 "Make a compact tree which shows all headlines marked with TODO.
8107 The tree will show the lines where the regexp matches, and all higher
8108 headlines above the match.
8109 With a \\[universal-argument] prefix, also show the DONE entries.
8110 With a numeric prefix N, construct a sparse tree for the Nth element
8111 of `org-todo-keywords-1'."
8112 (interactive "P")
8113 (let ((case-fold-search nil)
8114 (kwd-re
8115 (cond ((null arg) org-not-done-regexp)
8116 ((equal arg '(4))
8117 (let ((kwd (completing-read "Keyword (or KWD1|KWD2|...): "
8118 (mapcar 'list org-todo-keywords-1))))
8119 (concat "\\("
8120 (mapconcat 'identity (org-split-string kwd "|") "\\|")
8121 "\\)\\>")))
8122 ((<= (prefix-numeric-value arg) (length org-todo-keywords-1))
8123 (regexp-quote (nth (1- (prefix-numeric-value arg))
8124 org-todo-keywords-1)))
8125 (t (error "Invalid prefix argument: %s" arg)))))
8126 (message "%d TODO entries found"
8127 (org-occur (concat "^" outline-regexp " *" kwd-re )))))
8129 (defun org-deadline (&optional remove)
8130 "Insert the \"DEADLINE:\" string with a timestamp to make a deadline.
8131 With argument REMOVE, remove any deadline from the item."
8132 (interactive "P")
8133 (if remove
8134 (progn
8135 (org-remove-timestamp-with-keyword org-deadline-string)
8136 (message "Item no longer has a deadline."))
8137 (org-add-planning-info 'deadline nil 'closed)))
8139 (defun org-schedule (&optional remove)
8140 "Insert the SCHEDULED: string with a timestamp to schedule a TODO item.
8141 With argument REMOVE, remove any scheduling date from the item."
8142 (interactive "P")
8143 (if remove
8144 (progn
8145 (org-remove-timestamp-with-keyword org-scheduled-string)
8146 (message "Item is no longer scheduled."))
8147 (org-add-planning-info 'scheduled nil 'closed)))
8149 (defun org-remove-timestamp-with-keyword (keyword)
8150 "Remove all time stamps with KEYWORD in the current entry."
8151 (let ((re (concat "\\<" (regexp-quote keyword) " +<[^>\n]+>[ \t]*"))
8152 beg)
8153 (save-excursion
8154 (org-back-to-heading t)
8155 (setq beg (point))
8156 (org-end-of-subtree t t)
8157 (while (re-search-backward re beg t)
8158 (replace-match "")
8159 (unless (string-match "\\S-" (buffer-substring (point-at-bol) (point)))
8160 (delete-region (point-at-bol) (min (1+ (point)) (point-max))))))))
8162 (defun org-add-planning-info (what &optional time &rest remove)
8163 "Insert new timestamp with keyword in the line directly after the headline.
8164 WHAT indicates what kind of time stamp to add. TIME indicated the time to use.
8165 If non is given, the user is prompted for a date.
8166 REMOVE indicates what kind of entries to remove. An old WHAT entry will also
8167 be removed."
8168 (interactive)
8169 (let (org-time-was-given org-end-time-was-given ts
8170 end default-time default-input)
8172 (when (and (not time) (memq what '(scheduled deadline)))
8173 ;; Try to get a default date/time from existing timestamp
8174 (save-excursion
8175 (org-back-to-heading t)
8176 (setq end (save-excursion (outline-next-heading) (point)))
8177 (when (re-search-forward (if (eq what 'scheduled)
8178 org-scheduled-time-regexp
8179 org-deadline-time-regexp)
8180 end t)
8181 (setq ts (match-string 1)
8182 default-time
8183 (apply 'encode-time (org-parse-time-string ts))
8184 default-input (and ts (org-get-compact-tod ts))))))
8185 (when what
8186 ;; If necessary, get the time from the user
8187 (setq time (or time (org-read-date nil 'to-time nil nil
8188 default-time default-input))))
8190 (when (and org-insert-labeled-timestamps-at-point
8191 (member what '(scheduled deadline)))
8192 (insert
8193 (if (eq what 'scheduled) org-scheduled-string org-deadline-string) " ")
8194 (org-insert-time-stamp time org-time-was-given
8195 nil nil nil (list org-end-time-was-given))
8196 (setq what nil))
8197 (save-excursion
8198 (save-restriction
8199 (let (col list elt ts buffer-invisibility-spec)
8200 (org-back-to-heading t)
8201 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"))
8202 (goto-char (match-end 1))
8203 (setq col (current-column))
8204 (goto-char (match-end 0))
8205 (if (eobp) (insert "\n") (forward-char 1))
8206 (if (and (not (looking-at outline-regexp))
8207 (looking-at (concat "[^\r\n]*?" org-keyword-time-regexp
8208 "[^\r\n]*"))
8209 (not (equal (match-string 1) org-clock-string)))
8210 (narrow-to-region (match-beginning 0) (match-end 0))
8211 (insert-before-markers "\n")
8212 (backward-char 1)
8213 (narrow-to-region (point) (point))
8214 (org-indent-to-column col))
8215 ;; Check if we have to remove something.
8216 (setq list (cons what remove))
8217 (while list
8218 (setq elt (pop list))
8219 (goto-char (point-min))
8220 (when (or (and (eq elt 'scheduled)
8221 (re-search-forward org-scheduled-time-regexp nil t))
8222 (and (eq elt 'deadline)
8223 (re-search-forward org-deadline-time-regexp nil t))
8224 (and (eq elt 'closed)
8225 (re-search-forward org-closed-time-regexp nil t)))
8226 (replace-match "")
8227 (if (looking-at "--+<[^>]+>") (replace-match ""))
8228 (if (looking-at " +") (replace-match ""))))
8229 (goto-char (point-max))
8230 (when what
8231 (insert
8232 (if (not (equal (char-before) ?\ )) " " "")
8233 (cond ((eq what 'scheduled) org-scheduled-string)
8234 ((eq what 'deadline) org-deadline-string)
8235 ((eq what 'closed) org-closed-string))
8236 " ")
8237 (setq ts (org-insert-time-stamp
8238 time
8239 (or org-time-was-given
8240 (and (eq what 'closed) org-log-done-with-time))
8241 (eq what 'closed)
8242 nil nil (list org-end-time-was-given)))
8243 (end-of-line 1))
8244 (goto-char (point-min))
8245 (widen)
8246 (if (and (looking-at "[ \t]+\n")
8247 (equal (char-before) ?\n))
8248 (backward-delete-char 1))
8249 ts)))))
8251 (defvar org-log-note-marker (make-marker))
8252 (defvar org-log-note-purpose nil)
8253 (defvar org-log-note-state nil)
8254 (defvar org-log-note-how nil)
8255 (defvar org-log-note-window-configuration nil)
8256 (defvar org-log-note-return-to (make-marker))
8257 (defvar org-log-post-message nil
8258 "Message to be displayed after a log note has been stored.
8259 The auto-repeater uses this.")
8261 (defun org-add-note ()
8262 "Add a note to the current entry.
8263 This is done in the same way as adding a state change note."
8264 (interactive)
8265 (org-add-log-setup 'note nil t nil))
8267 (defun org-add-log-setup (&optional purpose state findpos how)
8268 "Set up the post command hook to take a note.
8269 If this is about to TODO state change, the new state is expected in STATE.
8270 When FINDPOS is non-nil, find the correct position for the note in
8271 the current entry. If not, assume that it can be inserted at point."
8272 (save-excursion
8273 (when findpos
8274 (org-back-to-heading t)
8275 (looking-at (concat outline-regexp "\\( *\\)[^\r\n]*"
8276 "\\(\n[^\r\n]*?" org-keyword-time-not-clock-regexp
8277 "[^\r\n]*\\)?"))
8278 (goto-char (match-end 0))
8279 (unless org-log-states-order-reversed
8280 (and (= (char-after) ?\n) (forward-char 1))
8281 (org-skip-over-state-notes)
8282 (skip-chars-backward " \t\n\r")))
8283 (move-marker org-log-note-marker (point))
8284 (setq org-log-note-purpose purpose
8285 org-log-note-state state
8286 org-log-note-how how)
8287 (add-hook 'post-command-hook 'org-add-log-note 'append)))
8289 (defun org-skip-over-state-notes ()
8290 "Skip past the list of State notes in an entry."
8291 (if (looking-at "\n[ \t]*- State") (forward-char 1))
8292 (while (looking-at "[ \t]*- State")
8293 (condition-case nil
8294 (org-next-item)
8295 (error (org-end-of-item)))))
8297 (defun org-add-log-note (&optional purpose)
8298 "Pop up a window for taking a note, and add this note later at point."
8299 (remove-hook 'post-command-hook 'org-add-log-note)
8300 (setq org-log-note-window-configuration (current-window-configuration))
8301 (delete-other-windows)
8302 (move-marker org-log-note-return-to (point))
8303 (switch-to-buffer (marker-buffer org-log-note-marker))
8304 (goto-char org-log-note-marker)
8305 (org-switch-to-buffer-other-window "*Org Note*")
8306 (erase-buffer)
8307 (if (memq org-log-note-how '(time state))
8308 (org-store-log-note)
8309 (let ((org-inhibit-startup t)) (org-mode))
8310 (insert (format "# Insert note for %s.
8311 # Finish with C-c C-c, or cancel with C-c C-k.\n\n"
8312 (cond
8313 ((eq org-log-note-purpose 'clock-out) "stopped clock")
8314 ((eq org-log-note-purpose 'done) "closed todo item")
8315 ((eq org-log-note-purpose 'state)
8316 (format "state change to \"%s\"" org-log-note-state))
8317 ((eq org-log-note-purpose 'note)
8318 "this entry")
8319 (t (error "This should not happen")))))
8320 (org-set-local 'org-finish-function 'org-store-log-note)))
8322 (defvar org-note-abort nil) ; dynamically scoped
8323 (defun org-store-log-note ()
8324 "Finish taking a log note, and insert it to where it belongs."
8325 (let ((txt (buffer-string))
8326 (note (cdr (assq org-log-note-purpose org-log-note-headings)))
8327 lines ind)
8328 (kill-buffer (current-buffer))
8329 (while (string-match "\\`#.*\n[ \t\n]*" txt)
8330 (setq txt (replace-match "" t t txt)))
8331 (if (string-match "\\s-+\\'" txt)
8332 (setq txt (replace-match "" t t txt)))
8333 (setq lines (org-split-string txt "\n"))
8334 (when (and note (string-match "\\S-" note))
8335 (setq note
8336 (org-replace-escapes
8337 note
8338 (list (cons "%u" (user-login-name))
8339 (cons "%U" user-full-name)
8340 (cons "%t" (format-time-string
8341 (org-time-stamp-format 'long 'inactive)
8342 (current-time)))
8343 (cons "%s" (if org-log-note-state
8344 (concat "\"" org-log-note-state "\"")
8345 "")))))
8346 (if lines (setq note (concat note " \\\\")))
8347 (push note lines))
8348 (when (or current-prefix-arg org-note-abort) (setq lines nil))
8349 (when lines
8350 (save-excursion
8351 (set-buffer (marker-buffer org-log-note-marker))
8352 (save-excursion
8353 (goto-char org-log-note-marker)
8354 (move-marker org-log-note-marker nil)
8355 (end-of-line 1)
8356 (if (not (bolp)) (let ((inhibit-read-only t)) (insert "\n")))
8357 (indent-relative nil)
8358 (insert "- " (pop lines))
8359 (org-indent-line-function)
8360 (beginning-of-line 1)
8361 (looking-at "[ \t]*")
8362 (setq ind (concat (match-string 0) " "))
8363 (end-of-line 1)
8364 (while lines (insert "\n" ind (pop lines)))))))
8365 (set-window-configuration org-log-note-window-configuration)
8366 (with-current-buffer (marker-buffer org-log-note-return-to)
8367 (goto-char org-log-note-return-to))
8368 (move-marker org-log-note-return-to nil)
8369 (and org-log-post-message (message "%s" org-log-post-message)))
8371 (defun org-sparse-tree (&optional arg)
8372 "Create a sparse tree, prompt for the details.
8373 This command can create sparse trees. You first need to select the type
8374 of match used to create the tree:
8376 t Show entries with a specific TODO keyword.
8377 T Show entries selected by a tags match.
8378 p Enter a property name and its value (both with completion on existing
8379 names/values) and show entries with that property.
8380 r Show entries matching a regular expression
8381 d Show deadlines due within `org-deadline-warning-days'."
8382 (interactive "P")
8383 (let (ans kwd value)
8384 (message "Sparse tree: [/]regexp [t]odo-kwd [T]ag [p]roperty [d]eadlines [b]efore-date")
8385 (setq ans (read-char-exclusive))
8386 (cond
8387 ((equal ans ?d)
8388 (call-interactively 'org-check-deadlines))
8389 ((equal ans ?b)
8390 (call-interactively 'org-check-before-date))
8391 ((equal ans ?t)
8392 (org-show-todo-tree '(4)))
8393 ((equal ans ?T)
8394 (call-interactively 'org-tags-sparse-tree))
8395 ((member ans '(?p ?P))
8396 (setq kwd (completing-read "Property: "
8397 (mapcar 'list (org-buffer-property-keys))))
8398 (setq value (completing-read "Value: "
8399 (mapcar 'list (org-property-values kwd))))
8400 (unless (string-match "\\`{.*}\\'" value)
8401 (setq value (concat "\"" value "\"")))
8402 (org-tags-sparse-tree arg (concat kwd "=" value)))
8403 ((member ans '(?r ?R ?/))
8404 (call-interactively 'org-occur))
8405 (t (error "No such sparse tree command \"%c\"" ans)))))
8407 (defvar org-occur-highlights nil
8408 "List of overlays used for occur matches.")
8409 (make-variable-buffer-local 'org-occur-highlights)
8410 (defvar org-occur-parameters nil
8411 "Parameters of the active org-occur calls.
8412 This is a list, each call to org-occur pushes as cons cell,
8413 containing the regular expression and the callback, onto the list.
8414 The list can contain several entries if `org-occur' has been called
8415 several time with the KEEP-PREVIOUS argument. Otherwise, this list
8416 will only contain one set of parameters. When the highlights are
8417 removed (for example with `C-c C-c', or with the next edit (depending
8418 on `org-remove-highlights-with-change'), this variable is emptied
8419 as well.")
8420 (make-variable-buffer-local 'org-occur-parameters)
8422 (defun org-occur (regexp &optional keep-previous callback)
8423 "Make a compact tree which shows all matches of REGEXP.
8424 The tree will show the lines where the regexp matches, and all higher
8425 headlines above the match. It will also show the heading after the match,
8426 to make sure editing the matching entry is easy.
8427 If KEEP-PREVIOUS is non-nil, highlighting and exposing done by a previous
8428 call to `org-occur' will be kept, to allow stacking of calls to this
8429 command.
8430 If CALLBACK is non-nil, it is a function which is called to confirm
8431 that the match should indeed be shown."
8432 (interactive "sRegexp: \nP")
8433 (unless keep-previous
8434 (org-remove-occur-highlights nil nil t))
8435 (push (cons regexp callback) org-occur-parameters)
8436 (let ((cnt 0))
8437 (save-excursion
8438 (goto-char (point-min))
8439 (if (or (not keep-previous) ; do not want to keep
8440 (not org-occur-highlights)) ; no previous matches
8441 ;; hide everything
8442 (org-overview))
8443 (while (re-search-forward regexp nil t)
8444 (when (or (not callback)
8445 (save-match-data (funcall callback)))
8446 (setq cnt (1+ cnt))
8447 (when org-highlight-sparse-tree-matches
8448 (org-highlight-new-match (match-beginning 0) (match-end 0)))
8449 (org-show-context 'occur-tree))))
8450 (when org-remove-highlights-with-change
8451 (org-add-hook 'before-change-functions 'org-remove-occur-highlights
8452 nil 'local))
8453 (unless org-sparse-tree-open-archived-trees
8454 (org-hide-archived-subtrees (point-min) (point-max)))
8455 (run-hooks 'org-occur-hook)
8456 (if (interactive-p)
8457 (message "%d match(es) for regexp %s" cnt regexp))
8458 cnt))
8460 (defun org-show-context (&optional key)
8461 "Make sure point and context and visible.
8462 How much context is shown depends upon the variables
8463 `org-show-hierarchy-above', `org-show-following-heading'. and
8464 `org-show-siblings'."
8465 (let ((heading-p (org-on-heading-p t))
8466 (hierarchy-p (org-get-alist-option org-show-hierarchy-above key))
8467 (following-p (org-get-alist-option org-show-following-heading key))
8468 (entry-p (org-get-alist-option org-show-entry-below key))
8469 (siblings-p (org-get-alist-option org-show-siblings key)))
8470 (catch 'exit
8471 ;; Show heading or entry text
8472 (if (and heading-p (not entry-p))
8473 (org-flag-heading nil) ; only show the heading
8474 (and (or entry-p (org-invisible-p) (org-invisible-p2))
8475 (org-show-hidden-entry))) ; show entire entry
8476 (when following-p
8477 ;; Show next sibling, or heading below text
8478 (save-excursion
8479 (and (if heading-p (org-goto-sibling) (outline-next-heading))
8480 (org-flag-heading nil))))
8481 (when siblings-p (org-show-siblings))
8482 (when hierarchy-p
8483 ;; show all higher headings, possibly with siblings
8484 (save-excursion
8485 (while (and (condition-case nil
8486 (progn (org-up-heading-all 1) t)
8487 (error nil))
8488 (not (bobp)))
8489 (org-flag-heading nil)
8490 (when siblings-p (org-show-siblings))))))))
8492 (defun org-reveal (&optional siblings)
8493 "Show current entry, hierarchy above it, and the following headline.
8494 This can be used to show a consistent set of context around locations
8495 exposed with `org-show-hierarchy-above' or `org-show-following-heading'
8496 not t for the search context.
8498 With optional argument SIBLINGS, on each level of the hierarchy all
8499 siblings are shown. This repairs the tree structure to what it would
8500 look like when opened with hierarchical calls to `org-cycle'."
8501 (interactive "P")
8502 (let ((org-show-hierarchy-above t)
8503 (org-show-following-heading t)
8504 (org-show-siblings (if siblings t org-show-siblings)))
8505 (org-show-context nil)))
8507 (defun org-highlight-new-match (beg end)
8508 "Highlight from BEG to END and mark the highlight is an occur headline."
8509 (let ((ov (org-make-overlay beg end)))
8510 (org-overlay-put ov 'face 'secondary-selection)
8511 (push ov org-occur-highlights)))
8513 (defun org-remove-occur-highlights (&optional beg end noremove)
8514 "Remove the occur highlights from the buffer.
8515 BEG and END are ignored. If NOREMOVE is nil, remove this function
8516 from the `before-change-functions' in the current buffer."
8517 (interactive)
8518 (unless org-inhibit-highlight-removal
8519 (mapc 'org-delete-overlay org-occur-highlights)
8520 (setq org-occur-highlights nil)
8521 (setq org-occur-parameters nil)
8522 (unless noremove
8523 (remove-hook 'before-change-functions
8524 'org-remove-occur-highlights 'local))))
8526 ;;;; Priorities
8528 (defvar org-priority-regexp ".*?\\(\\[#\\([A-Z0-9]\\)\\] ?\\)"
8529 "Regular expression matching the priority indicator.")
8531 (defvar org-remove-priority-next-time nil)
8533 (defun org-priority-up ()
8534 "Increase the priority of the current item."
8535 (interactive)
8536 (org-priority 'up))
8538 (defun org-priority-down ()
8539 "Decrease the priority of the current item."
8540 (interactive)
8541 (org-priority 'down))
8543 (defun org-priority (&optional action)
8544 "Change the priority of an item by ARG.
8545 ACTION can be `set', `up', `down', or a character."
8546 (interactive)
8547 (setq action (or action 'set))
8548 (let (current new news have remove)
8549 (save-excursion
8550 (org-back-to-heading)
8551 (if (looking-at org-priority-regexp)
8552 (setq current (string-to-char (match-string 2))
8553 have t)
8554 (setq current org-default-priority))
8555 (cond
8556 ((or (eq action 'set)
8557 (if (featurep 'xemacs) (characterp action) (integerp action)))
8558 (if (not (eq action 'set))
8559 (setq new action)
8560 (message "Priority %c-%c, SPC to remove: "
8561 org-highest-priority org-lowest-priority)
8562 (setq new (read-char-exclusive)))
8563 (if (and (= (upcase org-highest-priority) org-highest-priority)
8564 (= (upcase org-lowest-priority) org-lowest-priority))
8565 (setq new (upcase new)))
8566 (cond ((equal new ?\ ) (setq remove t))
8567 ((or (< (upcase new) org-highest-priority) (> (upcase new) org-lowest-priority))
8568 (error "Priority must be between `%c' and `%c'"
8569 org-highest-priority org-lowest-priority))))
8570 ((eq action 'up)
8571 (if (and (not have) (eq last-command this-command))
8572 (setq new org-lowest-priority)
8573 (setq new (if (and org-priority-start-cycle-with-default (not have))
8574 org-default-priority (1- current)))))
8575 ((eq action 'down)
8576 (if (and (not have) (eq last-command this-command))
8577 (setq new org-highest-priority)
8578 (setq new (if (and org-priority-start-cycle-with-default (not have))
8579 org-default-priority (1+ current)))))
8580 (t (error "Invalid action")))
8581 (if (or (< (upcase new) org-highest-priority)
8582 (> (upcase new) org-lowest-priority))
8583 (setq remove t))
8584 (setq news (format "%c" new))
8585 (if have
8586 (if remove
8587 (replace-match "" t t nil 1)
8588 (replace-match news t t nil 2))
8589 (if remove
8590 (error "No priority cookie found in line")
8591 (looking-at org-todo-line-regexp)
8592 (if (match-end 2)
8593 (progn
8594 (goto-char (match-end 2))
8595 (insert " [#" news "]"))
8596 (goto-char (match-beginning 3))
8597 (insert "[#" news "] ")))))
8598 (org-preserve-lc (org-set-tags nil 'align))
8599 (if remove
8600 (message "Priority removed")
8601 (message "Priority of current item set to %s" news))))
8604 (defun org-get-priority (s)
8605 "Find priority cookie and return priority."
8606 (save-match-data
8607 (if (not (string-match org-priority-regexp s))
8608 (* 1000 (- org-lowest-priority org-default-priority))
8609 (* 1000 (- org-lowest-priority
8610 (string-to-char (match-string 2 s)))))))
8612 ;;;; Tags
8614 (defun org-scan-tags (action matcher &optional todo-only)
8615 "Scan headline tags with inheritance and produce output ACTION.
8616 ACTION can be `sparse-tree' or `agenda'. MATCHER is a Lisp form to be
8617 evaluated, testing if a given set of tags qualifies a headline for
8618 inclusion. When TODO-ONLY is non-nil, only lines with a TODO keyword
8619 are included in the output."
8620 (let* ((re (concat "[\n\r]" outline-regexp " *\\(\\<\\("
8621 (mapconcat 'regexp-quote org-todo-keywords-1 "\\|")
8622 (org-re
8623 "\\>\\)\\)? *\\(.*?\\)\\(:[[:alnum:]_@:]+:\\)?[ \t]*$")))
8624 (props (list 'face nil
8625 'done-face 'org-done
8626 'undone-face nil
8627 'mouse-face 'highlight
8628 'org-not-done-regexp org-not-done-regexp
8629 'org-todo-regexp org-todo-regexp
8630 'keymap org-agenda-keymap
8631 'help-echo
8632 (format "mouse-2 or RET jump to org file %s"
8633 (abbreviate-file-name
8634 (or (buffer-file-name (buffer-base-buffer))
8635 (buffer-name (buffer-base-buffer)))))))
8636 (case-fold-search nil)
8637 lspos
8638 tags tags-list tags-alist (llast 0) rtn level category i txt
8639 todo marker entry priority)
8640 (save-excursion
8641 (goto-char (point-min))
8642 (when (eq action 'sparse-tree)
8643 (org-overview)
8644 (org-remove-occur-highlights))
8645 (while (re-search-forward re nil t)
8646 (catch :skip
8647 (setq todo (if (match-end 1) (match-string 2))
8648 tags (if (match-end 4) (match-string 4)))
8649 (goto-char (setq lspos (1+ (match-beginning 0))))
8650 (setq level (org-reduced-level (funcall outline-level))
8651 category (org-get-category))
8652 (setq i llast llast level)
8653 ;; remove tag lists from same and sublevels
8654 (while (>= i level)
8655 (when (setq entry (assoc i tags-alist))
8656 (setq tags-alist (delete entry tags-alist)))
8657 (setq i (1- i)))
8658 ;; add the next tags
8659 (when tags
8660 (setq tags (mapcar 'downcase (org-split-string tags ":"))
8661 tags-alist
8662 (cons (cons level tags) tags-alist)))
8663 ;; compile tags for current headline
8664 (setq tags-list
8665 (if org-use-tag-inheritance
8666 (apply 'append (mapcar 'cdr tags-alist))
8667 tags))
8668 (when (and tags org-use-tag-inheritance
8669 (not (eq t org-use-tag-inheritance)))
8670 ;; selective inheritance, remove uninherited ones
8671 (setcdr (car tags-alist)
8672 (org-remove-uniherited-tags (cdar tags-alist))))
8673 (when (and (or (not todo-only) (member todo org-not-done-keywords))
8674 (eval matcher)
8675 (or (not org-agenda-skip-archived-trees)
8676 (not (member org-archive-tag tags-list))))
8677 (and (eq action 'agenda) (org-agenda-skip))
8678 ;; list this headline
8680 (if (eq action 'sparse-tree)
8681 (progn
8682 (and org-highlight-sparse-tree-matches
8683 (org-get-heading) (match-end 0)
8684 (org-highlight-new-match
8685 (match-beginning 0) (match-beginning 1)))
8686 (org-show-context 'tags-tree))
8687 (setq txt (org-format-agenda-item
8689 (concat
8690 (if org-tags-match-list-sublevels
8691 (make-string (1- level) ?.) "")
8692 (org-get-heading))
8693 category tags-list)
8694 priority (org-get-priority txt))
8695 (goto-char lspos)
8696 (setq marker (org-agenda-new-marker))
8697 (org-add-props txt props
8698 'org-marker marker 'org-hd-marker marker 'org-category category
8699 'priority priority 'type "tagsmatch")
8700 (push txt rtn))
8701 ;; if we are to skip sublevels, jump to end of subtree
8702 (or org-tags-match-list-sublevels (org-end-of-subtree t))))))
8703 (when (and (eq action 'sparse-tree)
8704 (not org-sparse-tree-open-archived-trees))
8705 (org-hide-archived-subtrees (point-min) (point-max)))
8706 (nreverse rtn)))
8708 (defun org-remove-uniherited-tags (tags)
8709 "Remove all tags that are not inherited from the list TAGS."
8710 (cond
8711 ((eq org-use-tag-inheritance t) tags)
8712 ((not org-use-tag-inheritance) nil)
8713 ((stringp org-use-tag-inheritance)
8714 (delq nil (mapcar
8715 (lambda (x) (if (string-match org-use-tag-inheritance x) x nil))
8716 tags)))
8717 ((listp org-use-tag-inheritance)
8718 (org-delete-all org-use-tag-inheritance tags))))
8720 (defvar todo-only) ;; dynamically scoped
8722 (defun org-tags-sparse-tree (&optional todo-only match)
8723 "Create a sparse tree according to tags string MATCH.
8724 MATCH can contain positive and negative selection of tags, like
8725 \"+WORK+URGENT-WITHBOSS\".
8726 If optional argument TODO_ONLY is non-nil, only select lines that are
8727 also TODO lines."
8728 (interactive "P")
8729 (org-prepare-agenda-buffers (list (current-buffer)))
8730 (org-scan-tags 'sparse-tree (cdr (org-make-tags-matcher match)) todo-only))
8732 (defvar org-cached-props nil)
8733 (defun org-cached-entry-get (pom property)
8734 (if (or (eq t org-use-property-inheritance)
8735 (and (stringp org-use-property-inheritance)
8736 (string-match org-use-property-inheritance property))
8737 (and (listp org-use-property-inheritance)
8738 (member property org-use-property-inheritance)))
8739 ;; Caching is not possible, check it directly
8740 (org-entry-get pom property 'inherit)
8741 ;; Get all properties, so that we can do complicated checks easily
8742 (cdr (assoc property (or org-cached-props
8743 (setq org-cached-props
8744 (org-entry-properties pom)))))))
8746 (defun org-global-tags-completion-table (&optional files)
8747 "Return the list of all tags in all agenda buffer/files."
8748 (save-excursion
8749 (org-uniquify
8750 (delq nil
8751 (apply 'append
8752 (mapcar
8753 (lambda (file)
8754 (set-buffer (find-file-noselect file))
8755 (append (org-get-buffer-tags)
8756 (mapcar (lambda (x) (if (stringp (car-safe x))
8757 (list (car-safe x)) nil))
8758 org-tag-alist)))
8759 (if (and files (car files))
8760 files
8761 (org-agenda-files))))))))
8763 (defun org-make-tags-matcher (match)
8764 "Create the TAGS//TODO matcher form for the selection string MATCH."
8765 ;; todo-only is scoped dynamically into this function, and the function
8766 ;; may change it it the matcher asksk for it.
8767 (unless match
8768 ;; Get a new match request, with completion
8769 (let ((org-last-tags-completion-table
8770 (org-global-tags-completion-table)))
8771 (setq match (completing-read
8772 "Match: " 'org-tags-completion-function nil nil nil
8773 'org-tags-history))))
8775 ;; Parse the string and create a lisp form
8776 (let ((match0 match)
8777 (re (org-re "^&?\\([-+:]\\)?\\({[^}]+}\\|LEVEL\\([<=>]\\{1,2\\}\\)\\([0-9]+\\)\\|\\([[:alnum:]_]+\\)\\([<>=]\\{1,2\\}\\)\\({[^}]+}\\|\"[^\"]*\"\\|-?[.0-9]+\\(?:[eE][-+]?[0-9]+\\)?\\)\\|[[:alnum:]_@]+\\)"))
8778 minus tag mm
8779 tagsmatch todomatch tagsmatcher todomatcher kwd matcher
8780 orterms term orlist re-p str-p level-p level-op
8781 prop-p pn pv po cat-p gv)
8782 (if (string-match "/+" match)
8783 ;; match contains also a todo-matching request
8784 (progn
8785 (setq tagsmatch (substring match 0 (match-beginning 0))
8786 todomatch (substring match (match-end 0)))
8787 (if (string-match "^!" todomatch)
8788 (setq todo-only t todomatch (substring todomatch 1)))
8789 (if (string-match "^\\s-*$" todomatch)
8790 (setq todomatch nil)))
8791 ;; only matching tags
8792 (setq tagsmatch match todomatch nil))
8794 ;; Make the tags matcher
8795 (if (or (not tagsmatch) (not (string-match "\\S-" tagsmatch)))
8796 (setq tagsmatcher t)
8797 (setq orterms (org-split-string tagsmatch "|") orlist nil)
8798 (while (setq term (pop orterms))
8799 (while (and (equal (substring term -1) "\\") orterms)
8800 (setq term (concat term "|" (pop orterms)))) ; repair bad split
8801 (while (string-match re term)
8802 (setq minus (and (match-end 1)
8803 (equal (match-string 1 term) "-"))
8804 tag (match-string 2 term)
8805 re-p (equal (string-to-char tag) ?{)
8806 level-p (match-end 4)
8807 prop-p (match-end 5)
8808 mm (cond
8809 (re-p `(org-match-any-p ,(substring tag 1 -1) tags-list))
8810 (level-p
8811 (setq level-op (org-op-to-function (match-string 3 term)))
8812 `(,level-op level ,(string-to-number
8813 (match-string 4 term))))
8814 (prop-p
8815 (setq pn (match-string 5 term)
8816 po (match-string 6 term)
8817 pv (match-string 7 term)
8818 cat-p (equal pn "CATEGORY")
8819 re-p (equal (string-to-char pv) ?{)
8820 str-p (equal (string-to-char pv) ?\")
8821 pv (if (or re-p str-p) (substring pv 1 -1) pv))
8822 (setq po (org-op-to-function po str-p))
8823 (if (equal pn "CATEGORY")
8824 (setq gv '(get-text-property (point) 'org-category))
8825 (setq gv `(org-cached-entry-get nil ,pn)))
8826 (if re-p
8827 (if (eq po 'org<>)
8828 `(not (string-match ,pv (or ,gv "")))
8829 `(string-match ,pv (or ,gv "")))
8830 (if str-p
8831 `(,po (or ,gv "") ,pv)
8832 `(,po (string-to-number (or ,gv ""))
8833 ,(string-to-number pv) ))))
8834 (t `(member ,(downcase tag) tags-list)))
8835 mm (if minus (list 'not mm) mm)
8836 term (substring term (match-end 0)))
8837 (push mm tagsmatcher))
8838 (push (if (> (length tagsmatcher) 1)
8839 (cons 'and tagsmatcher)
8840 (car tagsmatcher))
8841 orlist)
8842 (setq tagsmatcher nil))
8843 (setq tagsmatcher (if (> (length orlist) 1) (cons 'or orlist) (car orlist)))
8844 (setq tagsmatcher
8845 (list 'progn '(setq org-cached-props nil) tagsmatcher)))
8846 ;; Make the todo matcher
8847 (if (or (not todomatch) (not (string-match "\\S-" todomatch)))
8848 (setq todomatcher t)
8849 (setq orterms (org-split-string todomatch "|") orlist nil)
8850 (while (setq term (pop orterms))
8851 (while (string-match re term)
8852 (setq minus (and (match-end 1)
8853 (equal (match-string 1 term) "-"))
8854 kwd (match-string 2 term)
8855 re-p (equal (string-to-char kwd) ?{)
8856 term (substring term (match-end 0))
8857 mm (if re-p
8858 `(string-match ,(substring kwd 1 -1) todo)
8859 (list 'equal 'todo kwd))
8860 mm (if minus (list 'not mm) mm))
8861 (push mm todomatcher))
8862 (push (if (> (length todomatcher) 1)
8863 (cons 'and todomatcher)
8864 (car todomatcher))
8865 orlist)
8866 (setq todomatcher nil))
8867 (setq todomatcher (if (> (length orlist) 1)
8868 (cons 'or orlist) (car orlist))))
8870 ;; Return the string and lisp forms of the matcher
8871 (setq matcher (if todomatcher
8872 (list 'and tagsmatcher todomatcher)
8873 tagsmatcher))
8874 (cons match0 matcher)))
8876 (defun org-op-to-function (op &optional stringp)
8877 (setq op
8878 (cond
8879 ((equal op "<" ) '(< string< ))
8880 ((equal op ">" ) '(> org-string> ))
8881 ((member op '("<=" "=<")) '(<= org-string<= ))
8882 ((member op '(">=" "=>")) '(>= org-string>= ))
8883 ((member op '("=" "==")) '(= string= ))
8884 ((member op '("<>" "!=")) '(org<> org-string<> ))))
8885 (nth (if stringp 1 0) op))
8887 (defun org<> (a b) (not (= a b)))
8888 (defun org-string<= (a b) (or (string= a b) (string< a b)))
8889 (defun org-string>= (a b) (not (string< a b)))
8890 (defun org-string> (a b) (and (not (string= a b)) (not (string< a b))))
8891 (defun org-string<> (a b) (not (string= a b)))
8893 (defun org-match-any-p (re list)
8894 "Does re match any element of list?"
8895 (setq list (mapcar (lambda (x) (string-match re x)) list))
8896 (delq nil list))
8898 (defvar org-add-colon-after-tag-completion nil) ;; dynamically skoped param
8899 (defvar org-tags-overlay (org-make-overlay 1 1))
8900 (org-detach-overlay org-tags-overlay)
8902 (defun org-get-tags-at (&optional pos)
8903 "Get a list of all headline tags applicable at POS.
8904 POS defaults to point. If tags are inherited, the list contains
8905 the targets in the same sequence as the headlines appear, i.e.
8906 sthe tags of the current headline come last."
8907 (interactive)
8908 (let (tags ltags lastpos parent)
8909 (save-excursion
8910 (save-restriction
8911 (widen)
8912 (goto-char (or pos (point)))
8913 (save-match-data
8914 (condition-case nil
8915 (progn
8916 (org-back-to-heading t)
8917 (while (not (equal lastpos (point)))
8918 (setq lastpos (point))
8919 (when (looking-at (org-re "[^\r\n]+?:\\([[:alnum:]_@:]+\\):[ \t]*$"))
8920 (setq ltags (org-split-string
8921 (org-match-string-no-properties 1) ":"))
8922 (setq tags (append (org-remove-uniherited-tags ltags)
8923 tags)))
8924 (or org-use-tag-inheritance (error ""))
8925 (org-up-heading-all 1)
8926 (setq parent t)))
8927 (error nil))))
8928 tags)))
8930 (defun org-toggle-tag (tag &optional onoff)
8931 "Toggle the tag TAG for the current line.
8932 If ONOFF is `on' or `off', don't toggle but set to this state."
8933 (unless (org-on-heading-p t) (error "Not on headling"))
8934 (let (res current)
8935 (save-excursion
8936 (beginning-of-line)
8937 (if (re-search-forward (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t]*$")
8938 (point-at-eol) t)
8939 (progn
8940 (setq current (match-string 1))
8941 (replace-match ""))
8942 (setq current ""))
8943 (setq current (nreverse (org-split-string current ":")))
8944 (cond
8945 ((eq onoff 'on)
8946 (setq res t)
8947 (or (member tag current) (push tag current)))
8948 ((eq onoff 'off)
8949 (or (not (member tag current)) (setq current (delete tag current))))
8950 (t (if (member tag current)
8951 (setq current (delete tag current))
8952 (setq res t)
8953 (push tag current))))
8954 (end-of-line 1)
8955 (if current
8956 (progn
8957 (insert " :" (mapconcat 'identity (nreverse current) ":") ":")
8958 (org-set-tags nil t))
8959 (delete-horizontal-space))
8960 (run-hooks 'org-after-tags-change-hook))
8961 res))
8963 (defun org-align-tags-here (to-col)
8964 ;; Assumes that this is a headline
8965 (let ((pos (point)) (col (current-column)) ncol tags-l p)
8966 (beginning-of-line 1)
8967 (if (and (looking-at (org-re ".*?\\([ \t]+\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
8968 (< pos (match-beginning 2)))
8969 (progn
8970 (setq tags-l (- (match-end 2) (match-beginning 2)))
8971 (goto-char (match-beginning 1))
8972 (insert " ")
8973 (delete-region (point) (1+ (match-beginning 2)))
8974 (setq ncol (max (1+ (current-column))
8975 (1+ col)
8976 (if (> to-col 0)
8977 to-col
8978 (- (abs to-col) tags-l))))
8979 (setq p (point))
8980 (insert (make-string (- ncol (current-column)) ?\ ))
8981 (setq ncol (current-column))
8982 (tabify p (point-at-eol))
8983 (org-move-to-column (min ncol col) t))
8984 (goto-char pos))))
8986 (defun org-set-tags (&optional arg just-align)
8987 "Set the tags for the current headline.
8988 With prefix ARG, realign all tags in headings in the current buffer."
8989 (interactive "P")
8990 (let* ((re (concat "^" outline-regexp))
8991 (current (org-get-tags-string))
8992 (col (current-column))
8993 (org-setting-tags t)
8994 table current-tags inherited-tags ; computed below when needed
8995 tags p0 c0 c1 rpl)
8996 (if arg
8997 (save-excursion
8998 (goto-char (point-min))
8999 (let ((buffer-invisibility-spec (org-inhibit-invisibility)))
9000 (while (re-search-forward re nil t)
9001 (org-set-tags nil t)
9002 (end-of-line 1)))
9003 (message "All tags realigned to column %d" org-tags-column))
9004 (if just-align
9005 (setq tags current)
9006 ;; Get a new set of tags from the user
9007 (save-excursion
9008 (setq table (or org-tag-alist (org-get-buffer-tags))
9009 org-last-tags-completion-table table
9010 current-tags (org-split-string current ":")
9011 inherited-tags (nreverse
9012 (nthcdr (length current-tags)
9013 (nreverse (org-get-tags-at))))
9014 tags
9015 (if (or (eq t org-use-fast-tag-selection)
9016 (and org-use-fast-tag-selection
9017 (delq nil (mapcar 'cdr table))))
9018 (org-fast-tag-selection
9019 current-tags inherited-tags table
9020 (if org-fast-tag-selection-include-todo org-todo-key-alist))
9021 (let ((org-add-colon-after-tag-completion t))
9022 (org-trim
9023 (org-without-partial-completion
9024 (completing-read "Tags: " 'org-tags-completion-function
9025 nil nil current 'org-tags-history)))))))
9026 (while (string-match "[-+&]+" tags)
9027 ;; No boolean logic, just a list
9028 (setq tags (replace-match ":" t t tags))))
9030 (if (string-match "\\`[\t ]*\\'" tags)
9031 (setq tags "")
9032 (unless (string-match ":$" tags) (setq tags (concat tags ":")))
9033 (unless (string-match "^:" tags) (setq tags (concat ":" tags))))
9035 ;; Insert new tags at the correct column
9036 (beginning-of-line 1)
9037 (cond
9038 ((and (equal current "") (equal tags "")))
9039 ((re-search-forward
9040 (concat "\\([ \t]*" (regexp-quote current) "\\)[ \t]*$")
9041 (point-at-eol) t)
9042 (if (equal tags "")
9043 (setq rpl "")
9044 (goto-char (match-beginning 0))
9045 (setq c0 (current-column) p0 (point)
9046 c1 (max (1+ c0) (if (> org-tags-column 0)
9047 org-tags-column
9048 (- (- org-tags-column) (length tags))))
9049 rpl (concat (make-string (max 0 (- c1 c0)) ?\ ) tags)))
9050 (replace-match rpl t t)
9051 (and (not (featurep 'xemacs)) c0 indent-tabs-mode (tabify p0 (point)))
9052 tags)
9053 (t (error "Tags alignment failed")))
9054 (org-move-to-column col)
9055 (unless just-align
9056 (run-hooks 'org-after-tags-change-hook)))))
9058 (defun org-change-tag-in-region (beg end tag off)
9059 "Add or remove TAG for each entry in the region.
9060 This works in the agenda, and also in an org-mode buffer."
9061 (interactive
9062 (list (region-beginning) (region-end)
9063 (let ((org-last-tags-completion-table
9064 (if (org-mode-p)
9065 (org-get-buffer-tags)
9066 (org-global-tags-completion-table))))
9067 (completing-read
9068 "Tag: " 'org-tags-completion-function nil nil nil
9069 'org-tags-history))
9070 (progn
9071 (message "[s]et or [r]emove? ")
9072 (equal (read-char-exclusive) ?r))))
9073 (if (fboundp 'deactivate-mark) (deactivate-mark))
9074 (let ((agendap (equal major-mode 'org-agenda-mode))
9075 l1 l2 m buf pos newhead (cnt 0))
9076 (goto-char end)
9077 (setq l2 (1- (org-current-line)))
9078 (goto-char beg)
9079 (setq l1 (org-current-line))
9080 (loop for l from l1 to l2 do
9081 (goto-line l)
9082 (setq m (get-text-property (point) 'org-hd-marker))
9083 (when (or (and (org-mode-p) (org-on-heading-p))
9084 (and agendap m))
9085 (setq buf (if agendap (marker-buffer m) (current-buffer))
9086 pos (if agendap m (point)))
9087 (with-current-buffer buf
9088 (save-excursion
9089 (save-restriction
9090 (goto-char pos)
9091 (setq cnt (1+ cnt))
9092 (org-toggle-tag tag (if off 'off 'on))
9093 (setq newhead (org-get-heading)))))
9094 (and agendap (org-agenda-change-all-lines newhead m))))
9095 (message "Tag :%s: %s in %d headings" tag (if off "removed" "set") cnt)))
9097 (defun org-tags-completion-function (string predicate &optional flag)
9098 (let (s1 s2 rtn (ctable org-last-tags-completion-table)
9099 (confirm (lambda (x) (stringp (car x)))))
9100 (if (string-match "^\\(.*[-+:&|]\\)\\([^-+:&|]*\\)$" string)
9101 (setq s1 (match-string 1 string)
9102 s2 (match-string 2 string))
9103 (setq s1 "" s2 string))
9104 (cond
9105 ((eq flag nil)
9106 ;; try completion
9107 (setq rtn (try-completion s2 ctable confirm))
9108 (if (stringp rtn)
9109 (setq rtn
9110 (concat s1 s2 (substring rtn (length s2))
9111 (if (and org-add-colon-after-tag-completion
9112 (assoc rtn ctable))
9113 ":" ""))))
9114 rtn)
9115 ((eq flag t)
9116 ;; all-completions
9117 (all-completions s2 ctable confirm)
9119 ((eq flag 'lambda)
9120 ;; exact match?
9121 (assoc s2 ctable)))
9124 (defun org-fast-tag-insert (kwd tags face &optional end)
9125 "Insert KDW, and the TAGS, the latter with face FACE. Also inser END."
9126 (insert (format "%-12s" (concat kwd ":"))
9127 (org-add-props (mapconcat 'identity tags " ") nil 'face face)
9128 (or end "")))
9130 (defun org-fast-tag-show-exit (flag)
9131 (save-excursion
9132 (goto-line 3)
9133 (if (re-search-forward "[ \t]+Next change exits" (point-at-eol) t)
9134 (replace-match ""))
9135 (when flag
9136 (end-of-line 1)
9137 (org-move-to-column (- (window-width) 19) t)
9138 (insert (org-add-props " Next change exits" nil 'face 'org-warning)))))
9140 (defun org-set-current-tags-overlay (current prefix)
9141 (let ((s (concat ":" (mapconcat 'identity current ":") ":")))
9142 (if (featurep 'xemacs)
9143 (org-overlay-display org-tags-overlay (concat prefix s)
9144 'secondary-selection)
9145 (put-text-property 0 (length s) 'face '(secondary-selection org-tag) s)
9146 (org-overlay-display org-tags-overlay (concat prefix s)))))
9148 (defun org-fast-tag-selection (current inherited table &optional todo-table)
9149 "Fast tag selection with single keys.
9150 CURRENT is the current list of tags in the headline, INHERITED is the
9151 list of inherited tags, and TABLE is an alist of tags and corresponding keys,
9152 possibly with grouping information. TODO-TABLE is a similar table with
9153 TODO keywords, should these have keys assigned to them.
9154 If the keys are nil, a-z are automatically assigned.
9155 Returns the new tags string, or nil to not change the current settings."
9156 (let* ((fulltable (append table todo-table))
9157 (maxlen (apply 'max (mapcar
9158 (lambda (x)
9159 (if (stringp (car x)) (string-width (car x)) 0))
9160 fulltable)))
9161 (buf (current-buffer))
9162 (expert (eq org-fast-tag-selection-single-key 'expert))
9163 (buffer-tags nil)
9164 (fwidth (+ maxlen 3 1 3))
9165 (ncol (/ (- (window-width) 4) fwidth))
9166 (i-face 'org-done)
9167 (c-face 'org-todo)
9168 tg cnt e c char c1 c2 ntable tbl rtn
9169 ov-start ov-end ov-prefix
9170 (exit-after-next org-fast-tag-selection-single-key)
9171 (done-keywords org-done-keywords)
9172 groups ingroup)
9173 (save-excursion
9174 (beginning-of-line 1)
9175 (if (looking-at
9176 (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9177 (setq ov-start (match-beginning 1)
9178 ov-end (match-end 1)
9179 ov-prefix "")
9180 (setq ov-start (1- (point-at-eol))
9181 ov-end (1+ ov-start))
9182 (skip-chars-forward "^\n\r")
9183 (setq ov-prefix
9184 (concat
9185 (buffer-substring (1- (point)) (point))
9186 (if (> (current-column) org-tags-column)
9188 (make-string (- org-tags-column (current-column)) ?\ ))))))
9189 (org-move-overlay org-tags-overlay ov-start ov-end)
9190 (save-window-excursion
9191 (if expert
9192 (set-buffer (get-buffer-create " *Org tags*"))
9193 (delete-other-windows)
9194 (split-window-vertically)
9195 (org-switch-to-buffer-other-window (get-buffer-create " *Org tags*")))
9196 (erase-buffer)
9197 (org-set-local 'org-done-keywords done-keywords)
9198 (org-fast-tag-insert "Inherited" inherited i-face "\n")
9199 (org-fast-tag-insert "Current" current c-face "\n\n")
9200 (org-fast-tag-show-exit exit-after-next)
9201 (org-set-current-tags-overlay current ov-prefix)
9202 (setq tbl fulltable char ?a cnt 0)
9203 (while (setq e (pop tbl))
9204 (cond
9205 ((equal e '(:startgroup))
9206 (push '() groups) (setq ingroup t)
9207 (when (not (= cnt 0))
9208 (setq cnt 0)
9209 (insert "\n"))
9210 (insert "{ "))
9211 ((equal e '(:endgroup))
9212 (setq ingroup nil cnt 0)
9213 (insert "}\n"))
9215 (setq tg (car e) c2 nil)
9216 (if (cdr e)
9217 (setq c (cdr e))
9218 ;; automatically assign a character.
9219 (setq c1 (string-to-char
9220 (downcase (substring
9221 tg (if (= (string-to-char tg) ?@) 1 0)))))
9222 (if (or (rassoc c1 ntable) (rassoc c1 table))
9223 (while (or (rassoc char ntable) (rassoc char table))
9224 (setq char (1+ char)))
9225 (setq c2 c1))
9226 (setq c (or c2 char)))
9227 (if ingroup (push tg (car groups)))
9228 (setq tg (org-add-props tg nil 'face
9229 (cond
9230 ((not (assoc tg table))
9231 (org-get-todo-face tg))
9232 ((member tg current) c-face)
9233 ((member tg inherited) i-face)
9234 (t nil))))
9235 (if (and (= cnt 0) (not ingroup)) (insert " "))
9236 (insert "[" c "] " tg (make-string
9237 (- fwidth 4 (length tg)) ?\ ))
9238 (push (cons tg c) ntable)
9239 (when (= (setq cnt (1+ cnt)) ncol)
9240 (insert "\n")
9241 (if ingroup (insert " "))
9242 (setq cnt 0)))))
9243 (setq ntable (nreverse ntable))
9244 (insert "\n")
9245 (goto-char (point-min))
9246 (if (and (not expert) (fboundp 'fit-window-to-buffer))
9247 (fit-window-to-buffer))
9248 (setq rtn
9249 (catch 'exit
9250 (while t
9251 (message "[a-z..]:Toggle [SPC]:clear [RET]:accept [TAB]:free%s%s"
9252 (if groups " [!] no groups" " [!]groups")
9253 (if expert " [C-c]:window" (if exit-after-next " [C-c]:single" " [C-c]:multi")))
9254 (setq c (let ((inhibit-quit t)) (read-char-exclusive)))
9255 (cond
9256 ((= c ?\r) (throw 'exit t))
9257 ((= c ?!)
9258 (setq groups (not groups))
9259 (goto-char (point-min))
9260 (while (re-search-forward "[{}]" nil t) (replace-match " ")))
9261 ((= c ?\C-c)
9262 (if (not expert)
9263 (org-fast-tag-show-exit
9264 (setq exit-after-next (not exit-after-next)))
9265 (setq expert nil)
9266 (delete-other-windows)
9267 (split-window-vertically)
9268 (org-switch-to-buffer-other-window " *Org tags*")
9269 (and (fboundp 'fit-window-to-buffer)
9270 (fit-window-to-buffer))))
9271 ((or (= c ?\C-g)
9272 (and (= c ?q) (not (rassoc c ntable))))
9273 (org-detach-overlay org-tags-overlay)
9274 (setq quit-flag t))
9275 ((= c ?\ )
9276 (setq current nil)
9277 (if exit-after-next (setq exit-after-next 'now)))
9278 ((= c ?\t)
9279 (condition-case nil
9280 (setq tg (completing-read
9281 "Tag: "
9282 (or buffer-tags
9283 (with-current-buffer buf
9284 (org-get-buffer-tags)))))
9285 (quit (setq tg "")))
9286 (when (string-match "\\S-" tg)
9287 (add-to-list 'buffer-tags (list tg))
9288 (if (member tg current)
9289 (setq current (delete tg current))
9290 (push tg current)))
9291 (if exit-after-next (setq exit-after-next 'now)))
9292 ((setq e (rassoc c todo-table) tg (car e))
9293 (with-current-buffer buf
9294 (save-excursion (org-todo tg)))
9295 (if exit-after-next (setq exit-after-next 'now)))
9296 ((setq e (rassoc c ntable) tg (car e))
9297 (if (member tg current)
9298 (setq current (delete tg current))
9299 (loop for g in groups do
9300 (if (member tg g)
9301 (mapc (lambda (x)
9302 (setq current (delete x current)))
9303 g)))
9304 (push tg current))
9305 (if exit-after-next (setq exit-after-next 'now))))
9307 ;; Create a sorted list
9308 (setq current
9309 (sort current
9310 (lambda (a b)
9311 (assoc b (cdr (memq (assoc a ntable) ntable))))))
9312 (if (eq exit-after-next 'now) (throw 'exit t))
9313 (goto-char (point-min))
9314 (beginning-of-line 2)
9315 (delete-region (point) (point-at-eol))
9316 (org-fast-tag-insert "Current" current c-face)
9317 (org-set-current-tags-overlay current ov-prefix)
9318 (while (re-search-forward
9319 (org-re "\\[.\\] \\([[:alnum:]_@]+\\)") nil t)
9320 (setq tg (match-string 1))
9321 (add-text-properties
9322 (match-beginning 1) (match-end 1)
9323 (list 'face
9324 (cond
9325 ((member tg current) c-face)
9326 ((member tg inherited) i-face)
9327 (t (get-text-property (match-beginning 1) 'face))))))
9328 (goto-char (point-min)))))
9329 (org-detach-overlay org-tags-overlay)
9330 (if rtn
9331 (mapconcat 'identity current ":")
9332 nil))))
9334 (defun org-get-tags-string ()
9335 "Get the TAGS string in the current headline."
9336 (unless (org-on-heading-p t)
9337 (error "Not on a heading"))
9338 (save-excursion
9339 (beginning-of-line 1)
9340 (if (looking-at (org-re ".*[ \t]\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
9341 (org-match-string-no-properties 1)
9342 "")))
9344 (defun org-get-tags ()
9345 "Get the list of tags specified in the current headline."
9346 (org-split-string (org-get-tags-string) ":"))
9348 (defun org-get-buffer-tags ()
9349 "Get a table of all tags used in the buffer, for completion."
9350 (let (tags)
9351 (save-excursion
9352 (goto-char (point-min))
9353 (while (re-search-forward
9354 (org-re "[ \t]:\\([[:alnum:]_@:]+\\):[ \t\r\n]") nil t)
9355 (when (equal (char-after (point-at-bol 0)) ?*)
9356 (mapc (lambda (x) (add-to-list 'tags x))
9357 (org-split-string (org-match-string-no-properties 1) ":")))))
9358 (mapcar 'list tags)))
9361 ;;;; Properties
9363 ;;; Setting and retrieving properties
9365 (defconst org-special-properties
9366 '("TODO" "TAGS" "ALLTAGS" "DEADLINE" "SCHEDULED" "CLOCK" "PRIORITY"
9367 "TIMESTAMP" "TIMESTAMP_IA")
9368 "The special properties valid in Org-mode.
9370 These are properties that are not defined in the property drawer,
9371 but in some other way.")
9373 (defconst org-default-properties
9374 '("ARCHIVE" "CATEGORY" "SUMMARY" "DESCRIPTION"
9375 "LOCATION" "LOGGING" "COLUMNS")
9376 "Some properties that are used by Org-mode for various purposes.
9377 Being in this list makes sure that they are offered for completion.")
9379 (defconst org-property-start-re "^[ \t]*:PROPERTIES:[ \t]*$"
9380 "Regular expression matching the first line of a property drawer.")
9382 (defconst org-property-end-re "^[ \t]*:END:[ \t]*$"
9383 "Regular expression matching the first line of a property drawer.")
9385 (defun org-property-action ()
9386 "Do an action on properties."
9387 (interactive)
9388 (let (c)
9389 (org-at-property-p)
9390 (message "Property Action: [s]et [d]elete [D]elete globally [c]ompute")
9391 (setq c (read-char-exclusive))
9392 (cond
9393 ((equal c ?s)
9394 (call-interactively 'org-set-property))
9395 ((equal c ?d)
9396 (call-interactively 'org-delete-property))
9397 ((equal c ?D)
9398 (call-interactively 'org-delete-property-globally))
9399 ((equal c ?c)
9400 (call-interactively 'org-compute-property-at-point))
9401 (t (error "No such property action %c" c)))))
9403 (defun org-at-property-p ()
9404 "Is the cursor in a property line?"
9405 ;; FIXME: Does not check if we are actually in the drawer.
9406 ;; FIXME: also returns true on any drawers.....
9407 ;; This is used by C-c C-c for property action.
9408 (save-excursion
9409 (beginning-of-line 1)
9410 (looking-at (org-re "^[ \t]*\\(:\\([[:alpha:]][[:alnum:]_-]*\\):\\)[ \t]*\\(.*\\)"))))
9412 (defun org-get-property-block (&optional beg end force)
9413 "Return the (beg . end) range of the body of the property drawer.
9414 BEG and END can be beginning and end of subtree, if not given
9415 they will be found.
9416 If the drawer does not exist and FORCE is non-nil, create the drawer."
9417 (catch 'exit
9418 (save-excursion
9419 (let* ((beg (or beg (progn (org-back-to-heading t) (point))))
9420 (end (or end (progn (outline-next-heading) (point)))))
9421 (goto-char beg)
9422 (if (re-search-forward org-property-start-re end t)
9423 (setq beg (1+ (match-end 0)))
9424 (if force
9425 (save-excursion
9426 (org-insert-property-drawer)
9427 (setq end (progn (outline-next-heading) (point))))
9428 (throw 'exit nil))
9429 (goto-char beg)
9430 (if (re-search-forward org-property-start-re end t)
9431 (setq beg (1+ (match-end 0)))))
9432 (if (re-search-forward org-property-end-re end t)
9433 (setq end (match-beginning 0))
9434 (or force (throw 'exit nil))
9435 (goto-char beg)
9436 (setq end beg)
9437 (org-indent-line-function)
9438 (insert ":END:\n"))
9439 (cons beg end)))))
9441 (defun org-entry-properties (&optional pom which)
9442 "Get all properties of the entry at point-or-marker POM.
9443 This includes the TODO keyword, the tags, time strings for deadline,
9444 scheduled, and clocking, and any additional properties defined in the
9445 entry. The return value is an alist, keys may occur multiple times
9446 if the property key was used several times.
9447 POM may also be nil, in which case the current entry is used.
9448 If WHICH is nil or `all', get all properties. If WHICH is
9449 `special' or `standard', only get that subclass."
9450 (setq which (or which 'all))
9451 (org-with-point-at pom
9452 (let ((clockstr (substring org-clock-string 0 -1))
9453 (excluded '("TODO" "TAGS" "ALLTAGS" "PRIORITY"))
9454 beg end range props sum-props key value string clocksum)
9455 (save-excursion
9456 (when (condition-case nil (org-back-to-heading t) (error nil))
9457 (setq beg (point))
9458 (setq sum-props (get-text-property (point) 'org-summaries))
9459 (setq clocksum (get-text-property (point) :org-clock-minutes))
9460 (outline-next-heading)
9461 (setq end (point))
9462 (when (memq which '(all special))
9463 ;; Get the special properties, like TODO and tags
9464 (goto-char beg)
9465 (when (and (looking-at org-todo-line-regexp) (match-end 2))
9466 (push (cons "TODO" (org-match-string-no-properties 2)) props))
9467 (when (looking-at org-priority-regexp)
9468 (push (cons "PRIORITY" (org-match-string-no-properties 2)) props))
9469 (when (and (setq value (org-get-tags-string))
9470 (string-match "\\S-" value))
9471 (push (cons "TAGS" value) props))
9472 (when (setq value (org-get-tags-at))
9473 (push (cons "ALLTAGS" (concat ":" (mapconcat 'identity value ":") ":"))
9474 props))
9475 (while (re-search-forward org-maybe-keyword-time-regexp end t)
9476 (setq key (if (match-end 1) (substring (org-match-string-no-properties 1) 0 -1))
9477 string (if (equal key clockstr)
9478 (org-no-properties
9479 (org-trim
9480 (buffer-substring
9481 (match-beginning 3) (goto-char (point-at-eol)))))
9482 (substring (org-match-string-no-properties 3) 1 -1)))
9483 (unless key
9484 (if (= (char-after (match-beginning 3)) ?\[)
9485 (setq key "TIMESTAMP_IA")
9486 (setq key "TIMESTAMP")))
9487 (when (or (equal key clockstr) (not (assoc key props)))
9488 (push (cons key string) props)))
9492 (when (memq which '(all standard))
9493 ;; Get the standard properties, like :PORP: ...
9494 (setq range (org-get-property-block beg end))
9495 (when range
9496 (goto-char (car range))
9497 (while (re-search-forward
9498 (org-re "^[ \t]*:\\([[:alpha:]][[:alnum:]_-]*\\):[ \t]*\\(\\S-.*\\)?")
9499 (cdr range) t)
9500 (setq key (org-match-string-no-properties 1)
9501 value (org-trim (or (org-match-string-no-properties 2) "")))
9502 (unless (member key excluded)
9503 (push (cons key (or value "")) props)))))
9504 (if clocksum
9505 (push (cons "CLOCKSUM"
9506 (org-columns-number-to-string (/ (float clocksum) 60.)
9507 'add_times))
9508 props))
9509 (append sum-props (nreverse props)))))))
9511 (defun org-entry-get (pom property &optional inherit)
9512 "Get value of PROPERTY for entry at point-or-marker POM.
9513 If INHERIT is non-nil and the entry does not have the property,
9514 then also check higher levels of the hierarchy.
9515 If INHERIT is the symbol `selective', use inheritance only if the setting
9516 in `org-use-property-inheritance' selects PROPERTY for inheritance.
9517 If the property is present but empty, the return value is the empty string.
9518 If the property is not present at all, nil is returned."
9519 (org-with-point-at pom
9520 (if (and inherit (if (eq inherit 'selective)
9521 (org-property-inherit-p property)
9523 (org-entry-get-with-inheritance property)
9524 (if (member property org-special-properties)
9525 ;; We need a special property. Use brute force, get all properties.
9526 (cdr (assoc property (org-entry-properties nil 'special)))
9527 (let ((range (org-get-property-block)))
9528 (if (and range
9529 (goto-char (car range))
9530 (re-search-forward
9531 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)?")
9532 (cdr range) t))
9533 ;; Found the property, return it.
9534 (if (match-end 1)
9535 (org-match-string-no-properties 1)
9536 "")))))))
9538 (defun org-property-or-variable-value (var &optional inherit)
9539 "Check if there is a property fixing the value of VAR.
9540 If yes, return this value. If not, return the current value of the variable."
9541 (let ((prop (org-entry-get nil (symbol-name var) inherit)))
9542 (if (and prop (stringp prop) (string-match "\\S-" prop))
9543 (read prop)
9544 (symbol-value var))))
9546 (defun org-entry-delete (pom property)
9547 "Delete the property PROPERTY from entry at point-or-marker POM."
9548 (org-with-point-at pom
9549 (if (member property org-special-properties)
9550 nil ; cannot delete these properties.
9551 (let ((range (org-get-property-block)))
9552 (if (and range
9553 (goto-char (car range))
9554 (re-search-forward
9555 (concat "^[ \t]*:" property ":[ \t]*\\(.*\\S-\\)")
9556 (cdr range) t))
9557 (progn
9558 (delete-region (match-beginning 0) (1+ (point-at-eol)))
9560 nil)))))
9562 ;; Multi-values properties are properties that contain multiple values
9563 ;; These values are assumed to be single words, separated by whitespace.
9564 (defun org-entry-add-to-multivalued-property (pom property value)
9565 "Add VALUE to the words in the PROPERTY in entry at point-or-marker POM."
9566 (let* ((old (org-entry-get pom property))
9567 (values (and old (org-split-string old "[ \t]"))))
9568 (unless (member value values)
9569 (setq values (cons value values))
9570 (org-entry-put pom property
9571 (mapconcat 'identity values " ")))))
9573 (defun org-entry-remove-from-multivalued-property (pom property value)
9574 "Remove VALUE from words in the PROPERTY in entry at point-or-marker POM."
9575 (let* ((old (org-entry-get pom property))
9576 (values (and old (org-split-string old "[ \t]"))))
9577 (when (member value values)
9578 (setq values (delete value values))
9579 (org-entry-put pom property
9580 (mapconcat 'identity values " ")))))
9582 (defun org-entry-member-in-multivalued-property (pom property value)
9583 "Is VALUE one of the words in the PROPERTY in entry at point-or-marker POM?"
9584 (let* ((old (org-entry-get pom property))
9585 (values (and old (org-split-string old "[ \t]"))))
9586 (member value values)))
9588 (defvar org-entry-property-inherited-from (make-marker))
9590 (defun org-entry-get-with-inheritance (property)
9591 "Get entry property, and search higher levels if not present."
9592 (let (tmp)
9593 (save-excursion
9594 (save-restriction
9595 (widen)
9596 (catch 'ex
9597 (while t
9598 (when (setq tmp (org-entry-get nil property))
9599 (org-back-to-heading t)
9600 (move-marker org-entry-property-inherited-from (point))
9601 (throw 'ex tmp))
9602 (or (org-up-heading-safe) (throw 'ex nil)))))
9603 (or tmp (cdr (assoc property org-local-properties))
9604 (cdr (assoc property org-global-properties))))))
9606 (defun org-entry-put (pom property value)
9607 "Set PROPERTY to VALUE for entry at point-or-marker POM."
9608 (org-with-point-at pom
9609 (org-back-to-heading t)
9610 (let ((beg (point)) (end (save-excursion (outline-next-heading) (point)))
9611 range)
9612 (cond
9613 ((equal property "TODO")
9614 (when (and (stringp value) (string-match "\\S-" value)
9615 (not (member value org-todo-keywords-1)))
9616 (error "\"%s\" is not a valid TODO state" value))
9617 (if (or (not value)
9618 (not (string-match "\\S-" value)))
9619 (setq value 'none))
9620 (org-todo value)
9621 (org-set-tags nil 'align))
9622 ((equal property "PRIORITY")
9623 (org-priority (if (and value (stringp value) (string-match "\\S-" value))
9624 (string-to-char value) ?\ ))
9625 (org-set-tags nil 'align))
9626 ((equal property "SCHEDULED")
9627 (if (re-search-forward org-scheduled-time-regexp end t)
9628 (cond
9629 ((eq value 'earlier) (org-timestamp-change -1 'day))
9630 ((eq value 'later) (org-timestamp-change 1 'day))
9631 (t (call-interactively 'org-schedule)))
9632 (call-interactively 'org-schedule)))
9633 ((equal property "DEADLINE")
9634 (if (re-search-forward org-deadline-time-regexp end t)
9635 (cond
9636 ((eq value 'earlier) (org-timestamp-change -1 'day))
9637 ((eq value 'later) (org-timestamp-change 1 'day))
9638 (t (call-interactively 'org-deadline)))
9639 (call-interactively 'org-deadline)))
9640 ((member property org-special-properties)
9641 (error "The %s property can not yet be set with `org-entry-put'"
9642 property))
9643 (t ; a non-special property
9644 (let ((buffer-invisibility-spec (org-inhibit-invisibility))) ; Emacs 21
9645 (setq range (org-get-property-block beg end 'force))
9646 (goto-char (car range))
9647 (if (re-search-forward
9648 (concat "^[ \t]*:" property ":\\(.*\\)") (cdr range) t)
9649 (progn
9650 (delete-region (match-beginning 1) (match-end 1))
9651 (goto-char (match-beginning 1)))
9652 (goto-char (cdr range))
9653 (insert "\n")
9654 (backward-char 1)
9655 (org-indent-line-function)
9656 (insert ":" property ":"))
9657 (and value (insert " " value))
9658 (org-indent-line-function)))))))
9660 (defun org-buffer-property-keys (&optional include-specials include-defaults include-columns)
9661 "Get all property keys in the current buffer.
9662 With INCLUDE-SPECIALS, also list the special properties that relect things
9663 like tags and TODO state.
9664 With INCLUDE-DEFAULTS, also include properties that has special meaning
9665 internally: ARCHIVE, CATEGORY, SUMMARY, DESCRIPTION, LOCATION, and LOGGING.
9666 With INCLUDE-COLUMNS, also include property names given in COLUMN
9667 formats in the current buffer."
9668 (let (rtn range cfmt cols s p)
9669 (save-excursion
9670 (save-restriction
9671 (widen)
9672 (goto-char (point-min))
9673 (while (re-search-forward org-property-start-re nil t)
9674 (setq range (org-get-property-block))
9675 (goto-char (car range))
9676 (while (re-search-forward
9677 (org-re "^[ \t]*:\\([-[:alnum:]_]+\\):")
9678 (cdr range) t)
9679 (add-to-list 'rtn (org-match-string-no-properties 1)))
9680 (outline-next-heading))))
9682 (when include-specials
9683 (setq rtn (append org-special-properties rtn)))
9685 (when include-defaults
9686 (mapc (lambda (x) (add-to-list 'rtn x)) org-default-properties))
9688 (when include-columns
9689 (save-excursion
9690 (save-restriction
9691 (widen)
9692 (goto-char (point-min))
9693 (while (re-search-forward
9694 "^\\(#\\+COLUMNS:\\|[ \t]*:COLUMNS:\\)[ \t]*\\(.*\\)"
9695 nil t)
9696 (setq cfmt (match-string 2) s 0)
9697 (while (string-match (org-re "%[0-9]*\\([-[:alnum:]_]+\\)")
9698 cfmt s)
9699 (setq s (match-end 0)
9700 p (match-string 1 cfmt))
9701 (unless (or (equal p "ITEM")
9702 (member p org-special-properties))
9703 (add-to-list 'rtn (match-string 1 cfmt))))))))
9705 (sort rtn (lambda (a b) (string< (upcase a) (upcase b))))))
9707 (defun org-property-values (key)
9708 "Return a list of all values of property KEY."
9709 (save-excursion
9710 (save-restriction
9711 (widen)
9712 (goto-char (point-min))
9713 (let ((re (concat "^[ \t]*:" key ":[ \t]*\\(\\S-.*\\)"))
9714 values)
9715 (while (re-search-forward re nil t)
9716 (add-to-list 'values (org-trim (match-string 1))))
9717 (delete "" values)))))
9719 (defun org-insert-property-drawer ()
9720 "Insert a property drawer into the current entry."
9721 (interactive)
9722 (org-back-to-heading t)
9723 (looking-at outline-regexp)
9724 (let ((indent (- (match-end 0)(match-beginning 0)))
9725 (beg (point))
9726 (re (concat "^[ \t]*" org-keyword-time-regexp))
9727 end hiddenp)
9728 (outline-next-heading)
9729 (setq end (point))
9730 (goto-char beg)
9731 (while (re-search-forward re end t))
9732 (setq hiddenp (org-invisible-p))
9733 (end-of-line 1)
9734 (and (equal (char-after) ?\n) (forward-char 1))
9735 (while (looking-at "^[ \t]*\\(:CLOCK:\\|CLOCK\\|:END:\\)")
9736 (beginning-of-line 2))
9737 (org-skip-over-state-notes)
9738 (skip-chars-backward " \t\n\r")
9739 (if (eq (char-before) ?*) (forward-char 1))
9740 (let ((inhibit-read-only t)) (insert "\n:PROPERTIES:\n:END:"))
9741 (beginning-of-line 0)
9742 (org-indent-to-column indent)
9743 (beginning-of-line 2)
9744 (org-indent-to-column indent)
9745 (beginning-of-line 0)
9746 (if hiddenp
9747 (save-excursion
9748 (org-back-to-heading t)
9749 (hide-entry))
9750 (org-flag-drawer t))))
9752 (defun org-set-property (property value)
9753 "In the current entry, set PROPERTY to VALUE.
9754 When called interactively, this will prompt for a property name, offering
9755 completion on existing and default properties. And then it will prompt
9756 for a value, offering competion either on allowed values (via an inherited
9757 xxx_ALL property) or on existing values in other instances of this property
9758 in the current file."
9759 (interactive
9760 (let* ((prop (completing-read
9761 "Property: " (mapcar 'list (org-buffer-property-keys nil t t))))
9762 (cur (org-entry-get nil prop))
9763 (allowed (org-property-get-allowed-values nil prop 'table))
9764 (existing (mapcar 'list (org-property-values prop)))
9765 (val (if allowed
9766 (completing-read "Value: " allowed nil 'req-match)
9767 (completing-read
9768 (concat "Value" (if (and cur (string-match "\\S-" cur))
9769 (concat "[" cur "]") "")
9770 ": ")
9771 existing nil nil "" nil cur))))
9772 (list prop (if (equal val "") cur val))))
9773 (unless (equal (org-entry-get nil property) value)
9774 (org-entry-put nil property value)))
9776 (defun org-delete-property (property)
9777 "In the current entry, delete PROPERTY."
9778 (interactive
9779 (let* ((prop (completing-read
9780 "Property: " (org-entry-properties nil 'standard))))
9781 (list prop)))
9782 (message "Property %s %s" property
9783 (if (org-entry-delete nil property)
9784 "deleted"
9785 "was not present in the entry")))
9787 (defun org-delete-property-globally (property)
9788 "Remove PROPERTY globally, from all entries."
9789 (interactive
9790 (let* ((prop (completing-read
9791 "Globally remove property: "
9792 (mapcar 'list (org-buffer-property-keys)))))
9793 (list prop)))
9794 (save-excursion
9795 (save-restriction
9796 (widen)
9797 (goto-char (point-min))
9798 (let ((cnt 0))
9799 (while (re-search-forward
9800 (concat "^[ \t]*:" (regexp-quote property) ":.*\n?")
9801 nil t)
9802 (setq cnt (1+ cnt))
9803 (replace-match ""))
9804 (message "Property \"%s\" removed from %d entries" property cnt)))))
9806 (defvar org-columns-current-fmt-compiled) ; defined in org-colview.el
9808 (defun org-compute-property-at-point ()
9809 "Compute the property at point.
9810 This looks for an enclosing column format, extracts the operator and
9811 then applies it to the proerty in the column format's scope."
9812 (interactive)
9813 (unless (org-at-property-p)
9814 (error "Not at a property"))
9815 (let ((prop (org-match-string-no-properties 2)))
9816 (org-columns-get-format-and-top-level)
9817 (unless (nth 3 (assoc prop org-columns-current-fmt-compiled))
9818 (error "No operator defined for property %s" prop))
9819 (org-columns-compute prop)))
9821 (defun org-property-get-allowed-values (pom property &optional table)
9822 "Get allowed values for the property PROPERTY.
9823 When TABLE is non-nil, return an alist that can directly be used for
9824 completion."
9825 (let (vals)
9826 (cond
9827 ((equal property "TODO")
9828 (setq vals (org-with-point-at pom
9829 (append org-todo-keywords-1 '("")))))
9830 ((equal property "PRIORITY")
9831 (let ((n org-lowest-priority))
9832 (while (>= n org-highest-priority)
9833 (push (char-to-string n) vals)
9834 (setq n (1- n)))))
9835 ((member property org-special-properties))
9837 (setq vals (org-entry-get pom (concat property "_ALL") 'inherit))
9839 (when (and vals (string-match "\\S-" vals))
9840 (setq vals (car (read-from-string (concat "(" vals ")"))))
9841 (setq vals (mapcar (lambda (x)
9842 (cond ((stringp x) x)
9843 ((numberp x) (number-to-string x))
9844 ((symbolp x) (symbol-name x))
9845 (t "???")))
9846 vals)))))
9847 (if table (mapcar 'list vals) vals)))
9849 (defun org-property-previous-allowed-value (&optional previous)
9850 "Switch to the next allowed value for this property."
9851 (interactive)
9852 (org-property-next-allowed-value t))
9854 (defun org-property-next-allowed-value (&optional previous)
9855 "Switch to the next allowed value for this property."
9856 (interactive)
9857 (unless (org-at-property-p)
9858 (error "Not at a property"))
9859 (let* ((key (match-string 2))
9860 (value (match-string 3))
9861 (allowed (or (org-property-get-allowed-values (point) key)
9862 (and (member value '("[ ]" "[-]" "[X]"))
9863 '("[ ]" "[X]"))))
9864 nval)
9865 (unless allowed
9866 (error "Allowed values for this property have not been defined"))
9867 (if previous (setq allowed (reverse allowed)))
9868 (if (member value allowed)
9869 (setq nval (car (cdr (member value allowed)))))
9870 (setq nval (or nval (car allowed)))
9871 (if (equal nval value)
9872 (error "Only one allowed value for this property"))
9873 (org-at-property-p)
9874 (replace-match (concat " :" key ": " nval) t t)
9875 (org-indent-line-function)
9876 (beginning-of-line 1)
9877 (skip-chars-forward " \t")))
9879 (defun org-find-entry-with-id (ident)
9880 "Locate the entry that contains the ID property with exact value IDENT.
9881 IDENT can be a string, a symbol or a number, this function will search for
9882 the string representation of it.
9883 Return the position where this entry starts, or nil if there is no such entry."
9884 (let ((id (cond
9885 ((stringp ident) ident)
9886 ((symbol-name ident) (symbol-name ident))
9887 ((numberp ident) (number-to-string ident))
9888 (t (error "IDENT %s must be a string, symbol or number" ident))))
9889 (case-fold-search nil))
9890 (save-excursion
9891 (save-restriction
9892 (widen)
9893 (goto-char (point-min))
9894 (when (re-search-forward
9895 (concat "^[ \t]*:ID:[ \t]+" (regexp-quote id) "[ \t]*$")
9896 nil t)
9897 (org-back-to-heading)
9898 (point))))))
9900 ;;;; Timestamps
9902 (defvar org-last-changed-timestamp nil)
9903 (defvar org-time-was-given) ; dynamically scoped parameter
9904 (defvar org-end-time-was-given) ; dynamically scoped parameter
9905 (defvar org-ts-what) ; dynamically scoped parameter
9907 (defun org-time-stamp (arg)
9908 "Prompt for a date/time and insert a time stamp.
9909 If the user specifies a time like HH:MM, or if this command is called
9910 with a prefix argument, the time stamp will contain date and time.
9911 Otherwise, only the date will be included. All parts of a date not
9912 specified by the user will be filled in from the current date/time.
9913 So if you press just return without typing anything, the time stamp
9914 will represent the current date/time. If there is already a timestamp
9915 at the cursor, it will be modified."
9916 (interactive "P")
9917 (let* ((ts nil)
9918 (default-time
9919 ;; Default time is either today, or, when entering a range,
9920 ;; the range start.
9921 (if (or (and (org-at-timestamp-p t) (setq ts (match-string 0)))
9922 (save-excursion
9923 (re-search-backward
9924 (concat org-ts-regexp "--?-?\\=") ; 1-3 minuses
9925 (- (point) 20) t)))
9926 (apply 'encode-time (org-parse-time-string (match-string 1)))
9927 (current-time)))
9928 (default-input (and ts (org-get-compact-tod ts)))
9929 org-time-was-given org-end-time-was-given time)
9930 (cond
9931 ((and (org-at-timestamp-p)
9932 (eq last-command 'org-time-stamp)
9933 (eq this-command 'org-time-stamp))
9934 (insert "--")
9935 (setq time (let ((this-command this-command))
9936 (org-read-date arg 'totime nil nil default-time default-input)))
9937 (org-insert-time-stamp time (or org-time-was-given arg)))
9938 ((org-at-timestamp-p)
9939 (setq time (let ((this-command this-command))
9940 (org-read-date arg 'totime nil nil default-time default-input)))
9941 (when (org-at-timestamp-p) ; just to get the match data
9942 (replace-match "")
9943 (setq org-last-changed-timestamp
9944 (org-insert-time-stamp
9945 time (or org-time-was-given arg)
9946 nil nil nil (list org-end-time-was-given))))
9947 (message "Timestamp updated"))
9949 (setq time (let ((this-command this-command))
9950 (org-read-date arg 'totime nil nil default-time default-input)))
9951 (org-insert-time-stamp time (or org-time-was-given arg)
9952 nil nil nil (list org-end-time-was-given))))))
9954 ;; FIXME: can we use this for something else, like computing time differences?
9955 (defun org-get-compact-tod (s)
9956 (when (string-match "\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\(-\\(\\([012]?[0-9]\\):\\([0-5][0-9]\\)\\)\\)?" s)
9957 (let* ((t1 (match-string 1 s))
9958 (h1 (string-to-number (match-string 2 s)))
9959 (m1 (string-to-number (match-string 3 s)))
9960 (t2 (and (match-end 4) (match-string 5 s)))
9961 (h2 (and t2 (string-to-number (match-string 6 s))))
9962 (m2 (and t2 (string-to-number (match-string 7 s))))
9963 dh dm)
9964 (if (not t2)
9966 (setq dh (- h2 h1) dm (- m2 m1))
9967 (if (< dm 0) (setq dm (+ dm 60) dh (1- dh)))
9968 (concat t1 "+" (number-to-string dh)
9969 (if (/= 0 dm) (concat ":" (number-to-string dm))))))))
9971 (defun org-time-stamp-inactive (&optional arg)
9972 "Insert an inactive time stamp.
9973 An inactive time stamp is enclosed in square brackets instead of angle
9974 brackets. It is inactive in the sense that it does not trigger agenda entries,
9975 does not link to the calendar and cannot be changed with the S-cursor keys.
9976 So these are more for recording a certain time/date."
9977 (interactive "P")
9978 (let (org-time-was-given org-end-time-was-given time)
9979 (setq time (org-read-date arg 'totime))
9980 (org-insert-time-stamp time (or org-time-was-given arg) 'inactive
9981 nil nil (list org-end-time-was-given))))
9983 (defvar org-date-ovl (org-make-overlay 1 1))
9984 (org-overlay-put org-date-ovl 'face 'org-warning)
9985 (org-detach-overlay org-date-ovl)
9987 (defvar org-ans1) ; dynamically scoped parameter
9988 (defvar org-ans2) ; dynamically scoped parameter
9990 (defvar org-plain-time-of-day-regexp) ; defined below
9992 (defvar org-read-date-overlay nil)
9993 (defvar org-dcst nil) ; dynamically scoped
9995 (defun org-read-date (&optional with-time to-time from-string prompt
9996 default-time default-input)
9997 "Read a date, possibly a time, and make things smooth for the user.
9998 The prompt will suggest to enter an ISO date, but you can also enter anything
9999 which will at least partially be understood by `parse-time-string'.
10000 Unrecognized parts of the date will default to the current day, month, year,
10001 hour and minute. If this command is called to replace a timestamp at point,
10002 of to enter the second timestamp of a range, the default time is taken from the
10003 existing stamp. For example,
10004 3-2-5 --> 2003-02-05
10005 feb 15 --> currentyear-02-15
10006 sep 12 9 --> 2009-09-12
10007 12:45 --> today 12:45
10008 22 sept 0:34 --> currentyear-09-22 0:34
10009 12 --> currentyear-currentmonth-12
10010 Fri --> nearest Friday (today or later)
10011 etc.
10013 Furthermore you can specify a relative date by giving, as the *first* thing
10014 in the input: a plus/minus sign, a number and a letter [dwmy] to indicate
10015 change in days weeks, months, years.
10016 With a single plus or minus, the date is relative to today. With a double
10017 plus or minus, it is relative to the date in DEFAULT-TIME. E.g.
10018 +4d --> four days from today
10019 +4 --> same as above
10020 +2w --> two weeks from today
10021 ++5 --> five days from default date
10023 The function understands only English month and weekday abbreviations,
10024 but this can be configured with the variables `parse-time-months' and
10025 `parse-time-weekdays'.
10027 While prompting, a calendar is popped up - you can also select the
10028 date with the mouse (button 1). The calendar shows a period of three
10029 months. To scroll it to other months, use the keys `>' and `<'.
10030 If you don't like the calendar, turn it off with
10031 \(setq org-read-date-popup-calendar nil)
10033 With optional argument TO-TIME, the date will immediately be converted
10034 to an internal time.
10035 With an optional argument WITH-TIME, the prompt will suggest to also
10036 insert a time. Note that when WITH-TIME is not set, you can still
10037 enter a time, and this function will inform the calling routine about
10038 this change. The calling routine may then choose to change the format
10039 used to insert the time stamp into the buffer to include the time.
10040 With optional argument FROM-STRING, read from this string instead from
10041 the user. PROMPT can overwrite the default prompt. DEFAULT-TIME is
10042 the time/date that is used for everything that is not specified by the
10043 user."
10044 (require 'parse-time)
10045 (let* ((org-time-stamp-rounding-minutes
10046 (if (equal with-time '(16)) '(0 0) org-time-stamp-rounding-minutes))
10047 (org-dcst org-display-custom-times)
10048 (ct (org-current-time))
10049 (def (or default-time ct))
10050 (defdecode (decode-time def))
10051 (dummy (progn
10052 (when (< (nth 2 defdecode) org-extend-today-until)
10053 (setcar (nthcdr 2 defdecode) -1)
10054 (setcar (nthcdr 1 defdecode) 59)
10055 (setq def (apply 'encode-time defdecode)
10056 defdecode (decode-time def)))))
10057 (calendar-move-hook nil)
10058 (calendar-view-diary-initially-flag nil)
10059 (view-diary-entries-initially nil)
10060 (calendar-view-holidays-initially-flag nil)
10061 (view-calendar-holidays-initially nil)
10062 (timestr (format-time-string
10063 (if with-time "%Y-%m-%d %H:%M" "%Y-%m-%d") def))
10064 (prompt (concat (if prompt (concat prompt " ") "")
10065 (format "Date+time [%s]: " timestr)))
10066 ans (org-ans0 "") org-ans1 org-ans2 final)
10068 (cond
10069 (from-string (setq ans from-string))
10070 (org-read-date-popup-calendar
10071 (save-excursion
10072 (save-window-excursion
10073 (calendar)
10074 (calendar-forward-day (- (time-to-days def)
10075 (calendar-absolute-from-gregorian
10076 (calendar-current-date))))
10077 (org-eval-in-calendar nil t)
10078 (let* ((old-map (current-local-map))
10079 (map (copy-keymap calendar-mode-map))
10080 (minibuffer-local-map (copy-keymap minibuffer-local-map)))
10081 (org-defkey map (kbd "RET") 'org-calendar-select)
10082 (org-defkey map (if (featurep 'xemacs) [button1] [mouse-1])
10083 'org-calendar-select-mouse)
10084 (org-defkey map (if (featurep 'xemacs) [button2] [mouse-2])
10085 'org-calendar-select-mouse)
10086 (org-defkey minibuffer-local-map [(meta shift left)]
10087 (lambda () (interactive)
10088 (org-eval-in-calendar '(calendar-backward-month 1))))
10089 (org-defkey minibuffer-local-map [(meta shift right)]
10090 (lambda () (interactive)
10091 (org-eval-in-calendar '(calendar-forward-month 1))))
10092 (org-defkey minibuffer-local-map [(meta shift up)]
10093 (lambda () (interactive)
10094 (org-eval-in-calendar '(calendar-backward-year 1))))
10095 (org-defkey minibuffer-local-map [(meta shift down)]
10096 (lambda () (interactive)
10097 (org-eval-in-calendar '(calendar-forward-year 1))))
10098 (org-defkey minibuffer-local-map [(shift up)]
10099 (lambda () (interactive)
10100 (org-eval-in-calendar '(calendar-backward-week 1))))
10101 (org-defkey minibuffer-local-map [(shift down)]
10102 (lambda () (interactive)
10103 (org-eval-in-calendar '(calendar-forward-week 1))))
10104 (org-defkey minibuffer-local-map [(shift left)]
10105 (lambda () (interactive)
10106 (org-eval-in-calendar '(calendar-backward-day 1))))
10107 (org-defkey minibuffer-local-map [(shift right)]
10108 (lambda () (interactive)
10109 (org-eval-in-calendar '(calendar-forward-day 1))))
10110 (org-defkey minibuffer-local-map ">"
10111 (lambda () (interactive)
10112 (org-eval-in-calendar '(scroll-calendar-left 1))))
10113 (org-defkey minibuffer-local-map "<"
10114 (lambda () (interactive)
10115 (org-eval-in-calendar '(scroll-calendar-right 1))))
10116 (unwind-protect
10117 (progn
10118 (use-local-map map)
10119 (add-hook 'post-command-hook 'org-read-date-display)
10120 (setq org-ans0 (read-string prompt default-input nil nil))
10121 ;; org-ans0: from prompt
10122 ;; org-ans1: from mouse click
10123 ;; org-ans2: from calendar motion
10124 (setq ans (concat org-ans0 " " (or org-ans1 org-ans2))))
10125 (remove-hook 'post-command-hook 'org-read-date-display)
10126 (use-local-map old-map)
10127 (when org-read-date-overlay
10128 (org-delete-overlay org-read-date-overlay)
10129 (setq org-read-date-overlay nil)))))))
10131 (t ; Naked prompt only
10132 (unwind-protect
10133 (setq ans (read-string prompt default-input nil timestr))
10134 (when org-read-date-overlay
10135 (org-delete-overlay org-read-date-overlay)
10136 (setq org-read-date-overlay nil)))))
10138 (setq final (org-read-date-analyze ans def defdecode))
10140 (if to-time
10141 (apply 'encode-time final)
10142 (if (and (boundp 'org-time-was-given) org-time-was-given)
10143 (format "%04d-%02d-%02d %02d:%02d"
10144 (nth 5 final) (nth 4 final) (nth 3 final)
10145 (nth 2 final) (nth 1 final))
10146 (format "%04d-%02d-%02d" (nth 5 final) (nth 4 final) (nth 3 final))))))
10147 (defvar def)
10148 (defvar defdecode)
10149 (defvar with-time)
10150 (defun org-read-date-display ()
10151 "Display the currrent date prompt interpretation in the minibuffer."
10152 (when org-read-date-display-live
10153 (when org-read-date-overlay
10154 (org-delete-overlay org-read-date-overlay))
10155 (let ((p (point)))
10156 (end-of-line 1)
10157 (while (not (equal (buffer-substring
10158 (max (point-min) (- (point) 4)) (point))
10159 " "))
10160 (insert " "))
10161 (goto-char p))
10162 (let* ((ans (concat (buffer-substring (point-at-bol) (point-max))
10163 " " (or org-ans1 org-ans2)))
10164 (org-end-time-was-given nil)
10165 (f (org-read-date-analyze ans def defdecode))
10166 (fmts (if org-dcst
10167 org-time-stamp-custom-formats
10168 org-time-stamp-formats))
10169 (fmt (if (or with-time
10170 (and (boundp 'org-time-was-given) org-time-was-given))
10171 (cdr fmts)
10172 (car fmts)))
10173 (txt (concat "=> " (format-time-string fmt (apply 'encode-time f)))))
10174 (when (and org-end-time-was-given
10175 (string-match org-plain-time-of-day-regexp txt))
10176 (setq txt (concat (substring txt 0 (match-end 0)) "-"
10177 org-end-time-was-given
10178 (substring txt (match-end 0)))))
10179 (setq org-read-date-overlay
10180 (make-overlay (1- (point-at-eol)) (point-at-eol)))
10181 (org-overlay-display org-read-date-overlay txt 'secondary-selection))))
10183 (defun org-read-date-analyze (ans def defdecode)
10184 "Analyze the combined answer of the date prompt."
10185 ;; FIXME: cleanup and comment
10186 (let (delta deltan deltaw deltadef year month day
10187 hour minute second wday pm h2 m2 tl wday1
10188 iso-year iso-weekday iso-week iso-year iso-date)
10190 (when (setq delta (org-read-date-get-relative ans (current-time) def))
10191 (setq ans (replace-match "" t t ans)
10192 deltan (car delta)
10193 deltaw (nth 1 delta)
10194 deltadef (nth 2 delta)))
10196 ;; Check if there is an iso week date in there
10197 ;; If yes, sore the info and ostpone interpreting it until the rest
10198 ;; of the parsing is done
10199 (when (string-match "\\<\\(?:\\([0-9]+\\)-\\)?[wW]\\([0-9]\\{1,2\\}\\)\\(?:-\\([0-6]\\)\\)?\\([ \t]\\|$\\)" ans)
10200 (setq iso-year (if (match-end 1) (org-small-year-to-year (string-to-number (match-string 1 ans))))
10201 iso-weekday (if (match-end 3) (string-to-number (match-string 3 ans)))
10202 iso-week (string-to-number (match-string 2 ans)))
10203 (setq ans (replace-match "" t t ans)))
10205 ;; Help matching ISO dates with single digit month ot day, like 2006-8-11.
10206 (when (string-match
10207 "^ *\\(\\([0-9]+\\)-\\)?\\([0-1]?[0-9]\\)-\\([0-3]?[0-9]\\)\\([^-0-9]\\|$\\)" ans)
10208 (setq year (if (match-end 2)
10209 (string-to-number (match-string 2 ans))
10210 (string-to-number (format-time-string "%Y")))
10211 month (string-to-number (match-string 3 ans))
10212 day (string-to-number (match-string 4 ans)))
10213 (if (< year 100) (setq year (+ 2000 year)))
10214 (setq ans (replace-match (format "%04d-%02d-%02d\\5" year month day)
10215 t nil ans)))
10216 ;; Help matching am/pm times, because `parse-time-string' does not do that.
10217 ;; If there is a time with am/pm, and *no* time without it, we convert
10218 ;; so that matching will be successful.
10219 (loop for i from 1 to 2 do ; twice, for end time as well
10220 (when (and (not (string-match "\\(\\`\\|[^+]\\)[012]?[0-9]:[0-9][0-9]\\([ \t\n]\\|$\\)" ans))
10221 (string-match "\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?\\(am\\|AM\\|pm\\|PM\\)\\>" ans))
10222 (setq hour (string-to-number (match-string 1 ans))
10223 minute (if (match-end 3)
10224 (string-to-number (match-string 3 ans))
10226 pm (equal ?p
10227 (string-to-char (downcase (match-string 4 ans)))))
10228 (if (and (= hour 12) (not pm))
10229 (setq hour 0)
10230 (if (and pm (< hour 12)) (setq hour (+ 12 hour))))
10231 (setq ans (replace-match (format "%02d:%02d" hour minute)
10232 t t ans))))
10234 ;; Check if a time range is given as a duration
10235 (when (string-match "\\([012]?[0-9]\\):\\([0-6][0-9]\\)\\+\\([012]?[0-9]\\)\\(:\\([0-5][0-9]\\)\\)?" ans)
10236 (setq hour (string-to-number (match-string 1 ans))
10237 h2 (+ hour (string-to-number (match-string 3 ans)))
10238 minute (string-to-number (match-string 2 ans))
10239 m2 (+ minute (if (match-end 5) (string-to-number
10240 (match-string 5 ans))0)))
10241 (if (>= m2 60) (setq h2 (1+ h2) m2 (- m2 60)))
10242 (setq ans (replace-match (format "%02d:%02d-%02d:%02d" hour minute h2 m2)
10243 t t ans)))
10245 ;; Check if there is a time range
10246 (when (boundp 'org-end-time-was-given)
10247 (setq org-time-was-given nil)
10248 (when (and (string-match org-plain-time-of-day-regexp ans)
10249 (match-end 8))
10250 (setq org-end-time-was-given (match-string 8 ans))
10251 (setq ans (concat (substring ans 0 (match-beginning 7))
10252 (substring ans (match-end 7))))))
10254 (setq tl (parse-time-string ans)
10255 day (or (nth 3 tl) (nth 3 defdecode))
10256 month (or (nth 4 tl)
10257 (if (and org-read-date-prefer-future
10258 (nth 3 tl) (< (nth 3 tl) (nth 3 defdecode)))
10259 (1+ (nth 4 defdecode))
10260 (nth 4 defdecode)))
10261 year (or (nth 5 tl)
10262 (if (and org-read-date-prefer-future
10263 (nth 4 tl) (< (nth 4 tl) (nth 4 defdecode)))
10264 (1+ (nth 5 defdecode))
10265 (nth 5 defdecode)))
10266 hour (or (nth 2 tl) (nth 2 defdecode))
10267 minute (or (nth 1 tl) (nth 1 defdecode))
10268 second (or (nth 0 tl) 0)
10269 wday (nth 6 tl))
10271 ;; Special date definitions below
10272 (cond
10273 (iso-week
10274 ;; There was an iso week
10275 (setq year (or iso-year year)
10276 day (or iso-weekday wday 1)
10277 wday nil ; to make sure that the trigger below does not match
10278 iso-date (calendar-gregorian-from-absolute
10279 (calendar-absolute-from-iso
10280 (list iso-week day year))))
10281 ; FIXME: Should we also push ISO weeks into the future?
10282 ; (when (and org-read-date-prefer-future
10283 ; (not iso-year)
10284 ; (< (calendar-absolute-from-gregorian iso-date)
10285 ; (time-to-days (current-time))))
10286 ; (setq year (1+ year)
10287 ; iso-date (calendar-gregorian-from-absolute
10288 ; (calendar-absolute-from-iso
10289 ; (list iso-week day year)))))
10290 (setq month (car iso-date)
10291 year (nth 2 iso-date)
10292 day (nth 1 iso-date)))
10293 (deltan
10294 (unless deltadef
10295 (let ((now (decode-time (current-time))))
10296 (setq day (nth 3 now) month (nth 4 now) year (nth 5 now))))
10297 (cond ((member deltaw '("d" "")) (setq day (+ day deltan)))
10298 ((equal deltaw "w") (setq day (+ day (* 7 deltan))))
10299 ((equal deltaw "m") (setq month (+ month deltan)))
10300 ((equal deltaw "y") (setq year (+ year deltan)))))
10301 ((and wday (not (nth 3 tl)))
10302 ;; Weekday was given, but no day, so pick that day in the week
10303 ;; on or after the derived date.
10304 (setq wday1 (nth 6 (decode-time (encode-time 0 0 0 day month year))))
10305 (unless (equal wday wday1)
10306 (setq day (+ day (% (- wday wday1 -7) 7))))))
10307 (if (and (boundp 'org-time-was-given)
10308 (nth 2 tl))
10309 (setq org-time-was-given t))
10310 (if (< year 100) (setq year (+ 2000 year)))
10311 (if (< year 1970) (setq year (nth 5 defdecode))) ; not representable
10312 (list second minute hour day month year)))
10314 (defvar parse-time-weekdays)
10316 (defun org-read-date-get-relative (s today default)
10317 "Check string S for special relative date string.
10318 TODAY and DEFAULT are internal times, for today and for a default.
10319 Return shift list (N what def-flag)
10320 WHAT is \"d\", \"w\", \"m\", or \"y\" for day, week, month, year.
10321 N is the number of WHATs to shift.
10322 DEF-FLAG is t when a double ++ or -- indicates shift relative to
10323 the DEFAULT date rather than TODAY."
10324 (when (string-match
10325 (concat
10326 "\\`[ \t]*\\([-+]\\{1,2\\}\\)"
10327 "\\([0-9]+\\)?"
10328 "\\([dwmy]\\|\\(" (mapconcat 'car parse-time-weekdays "\\|") "\\)\\)?"
10329 "\\([ \t]\\|$\\)") s)
10330 (let* ((dir (if (match-end 1)
10331 (string-to-char (substring (match-string 1 s) -1))
10332 ?+))
10333 (rel (and (match-end 1) (= 2 (- (match-end 1) (match-beginning 1)))))
10334 (n (if (match-end 2) (string-to-number (match-string 2 s)) 1))
10335 (what (if (match-end 3) (match-string 3 s) "d"))
10336 (wday1 (cdr (assoc (downcase what) parse-time-weekdays)))
10337 (date (if rel default today))
10338 (wday (nth 6 (decode-time date)))
10339 delta)
10340 (if wday1
10341 (progn
10342 (setq delta (mod (+ 7 (- wday1 wday)) 7))
10343 (if (= dir ?-) (setq delta (- delta 7)))
10344 (if (> n 1) (setq delta (+ delta (* (1- n) (if (= dir ?-) -7 7)))))
10345 (list delta "d" rel))
10346 (list (* n (if (= dir ?-) -1 1)) what rel)))))
10348 (defun org-eval-in-calendar (form &optional keepdate)
10349 "Eval FORM in the calendar window and return to current window.
10350 Also, store the cursor date in variable org-ans2."
10351 (let ((sw (selected-window)))
10352 (select-window (get-buffer-window "*Calendar*"))
10353 (eval form)
10354 (when (and (not keepdate) (calendar-cursor-to-date))
10355 (let* ((date (calendar-cursor-to-date))
10356 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10357 (setq org-ans2 (format-time-string "%Y-%m-%d" time))))
10358 (org-move-overlay org-date-ovl (1- (point)) (1+ (point)) (current-buffer))
10359 (select-window sw)))
10361 ; ;; Update the prompt to show new default date
10362 ; (save-excursion
10363 ; (goto-char (point-min))
10364 ; (when (and org-ans2
10365 ; (re-search-forward "\\[[-0-9]+\\]" nil t)
10366 ; (get-text-property (match-end 0) 'field))
10367 ; (let ((inhibit-read-only t))
10368 ; (replace-match (concat "[" org-ans2 "]") t t)
10369 ; (add-text-properties (point-min) (1+ (match-end 0))
10370 ; (text-properties-at (1+ (point-min)))))))))
10372 (defun org-calendar-select ()
10373 "Return to `org-read-date' with the date currently selected.
10374 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10375 (interactive)
10376 (when (calendar-cursor-to-date)
10377 (let* ((date (calendar-cursor-to-date))
10378 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10379 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10380 (if (active-minibuffer-window) (exit-minibuffer))))
10382 (defun org-insert-time-stamp (time &optional with-hm inactive pre post extra)
10383 "Insert a date stamp for the date given by the internal TIME.
10384 WITH-HM means, use the stamp format that includes the time of the day.
10385 INACTIVE means use square brackets instead of angular ones, so that the
10386 stamp will not contribute to the agenda.
10387 PRE and POST are optional strings to be inserted before and after the
10388 stamp.
10389 The command returns the inserted time stamp."
10390 (let ((fmt (funcall (if with-hm 'cdr 'car) org-time-stamp-formats))
10391 stamp)
10392 (if inactive (setq fmt (concat "[" (substring fmt 1 -1) "]")))
10393 (insert-before-markers (or pre ""))
10394 (insert-before-markers (setq stamp (format-time-string fmt time)))
10395 (when (listp extra)
10396 (setq extra (car extra))
10397 (if (and (stringp extra)
10398 (string-match "\\([0-9]+\\):\\([0-9]+\\)" extra))
10399 (setq extra (format "-%02d:%02d"
10400 (string-to-number (match-string 1 extra))
10401 (string-to-number (match-string 2 extra))))
10402 (setq extra nil)))
10403 (when extra
10404 (backward-char 1)
10405 (insert-before-markers extra)
10406 (forward-char 1))
10407 (insert-before-markers (or post ""))
10408 stamp))
10410 (defun org-toggle-time-stamp-overlays ()
10411 "Toggle the use of custom time stamp formats."
10412 (interactive)
10413 (setq org-display-custom-times (not org-display-custom-times))
10414 (unless org-display-custom-times
10415 (let ((p (point-min)) (bmp (buffer-modified-p)))
10416 (while (setq p (next-single-property-change p 'display))
10417 (if (and (get-text-property p 'display)
10418 (eq (get-text-property p 'face) 'org-date))
10419 (remove-text-properties
10420 p (setq p (next-single-property-change p 'display))
10421 '(display t))))
10422 (set-buffer-modified-p bmp)))
10423 (if (featurep 'xemacs)
10424 (remove-text-properties (point-min) (point-max) '(end-glyph t)))
10425 (org-restart-font-lock)
10426 (setq org-table-may-need-update t)
10427 (if org-display-custom-times
10428 (message "Time stamps are overlayed with custom format")
10429 (message "Time stamp overlays removed")))
10431 (defun org-display-custom-time (beg end)
10432 "Overlay modified time stamp format over timestamp between BED and END."
10433 (let* ((ts (buffer-substring beg end))
10434 t1 w1 with-hm tf time str w2 (off 0))
10435 (save-match-data
10436 (setq t1 (org-parse-time-string ts t))
10437 (if (string-match "\\(-[0-9]+:[0-9]+\\)?\\( [.+]?\\+[0-9]+[dwmy]\\)?\\'" ts)
10438 (setq off (- (match-end 0) (match-beginning 0)))))
10439 (setq end (- end off))
10440 (setq w1 (- end beg)
10441 with-hm (and (nth 1 t1) (nth 2 t1))
10442 tf (funcall (if with-hm 'cdr 'car) org-time-stamp-custom-formats)
10443 time (org-fix-decoded-time t1)
10444 str (org-add-props
10445 (format-time-string
10446 (substring tf 1 -1) (apply 'encode-time time))
10447 nil 'mouse-face 'highlight)
10448 w2 (length str))
10449 (if (not (= w2 w1))
10450 (add-text-properties (1+ beg) (+ 2 beg)
10451 (list 'org-dwidth t 'org-dwidth-n (- w1 w2))))
10452 (if (featurep 'xemacs)
10453 (progn
10454 (put-text-property beg end 'invisible t)
10455 (put-text-property beg end 'end-glyph (make-glyph str)))
10456 (put-text-property beg end 'display str))))
10458 (defun org-translate-time (string)
10459 "Translate all timestamps in STRING to custom format.
10460 But do this only if the variable `org-display-custom-times' is set."
10461 (when org-display-custom-times
10462 (save-match-data
10463 (let* ((start 0)
10464 (re org-ts-regexp-both)
10465 t1 with-hm inactive tf time str beg end)
10466 (while (setq start (string-match re string start))
10467 (setq beg (match-beginning 0)
10468 end (match-end 0)
10469 t1 (save-match-data
10470 (org-parse-time-string (substring string beg end) t))
10471 with-hm (and (nth 1 t1) (nth 2 t1))
10472 inactive (equal (substring string beg (1+ beg)) "[")
10473 tf (funcall (if with-hm 'cdr 'car)
10474 org-time-stamp-custom-formats)
10475 time (org-fix-decoded-time t1)
10476 str (format-time-string
10477 (concat
10478 (if inactive "[" "<") (substring tf 1 -1)
10479 (if inactive "]" ">"))
10480 (apply 'encode-time time))
10481 string (replace-match str t t string)
10482 start (+ start (length str)))))))
10483 string)
10485 (defun org-fix-decoded-time (time)
10486 "Set 0 instead of nil for the first 6 elements of time.
10487 Don't touch the rest."
10488 (let ((n 0))
10489 (mapcar (lambda (x) (if (< (setq n (1+ n)) 7) (or x 0) x)) time)))
10491 (defun org-days-to-time (timestamp-string)
10492 "Difference between TIMESTAMP-STRING and now in days."
10493 (- (time-to-days (org-time-string-to-time timestamp-string))
10494 (time-to-days (current-time))))
10496 (defun org-deadline-close (timestamp-string &optional ndays)
10497 "Is the time in TIMESTAMP-STRING close to the current date?"
10498 (setq ndays (or ndays (org-get-wdays timestamp-string)))
10499 (and (< (org-days-to-time timestamp-string) ndays)
10500 (not (org-entry-is-done-p))))
10502 (defun org-get-wdays (ts)
10503 "Get the deadline lead time appropriate for timestring TS."
10504 (cond
10505 ((<= org-deadline-warning-days 0)
10506 ;; 0 or negative, enforce this value no matter what
10507 (- org-deadline-warning-days))
10508 ((string-match "-\\([0-9]+\\)\\([dwmy]\\)\\(\\'\\|>\\)" ts)
10509 ;; lead time is specified.
10510 (floor (* (string-to-number (match-string 1 ts))
10511 (cdr (assoc (match-string 2 ts)
10512 '(("d" . 1) ("w" . 7)
10513 ("m" . 30.4) ("y" . 365.25)))))))
10514 ;; go for the default.
10515 (t org-deadline-warning-days)))
10517 (defun org-calendar-select-mouse (ev)
10518 "Return to `org-read-date' with the date currently selected.
10519 This is used by `org-read-date' in a temporary keymap for the calendar buffer."
10520 (interactive "e")
10521 (mouse-set-point ev)
10522 (when (calendar-cursor-to-date)
10523 (let* ((date (calendar-cursor-to-date))
10524 (time (encode-time 0 0 0 (nth 1 date) (nth 0 date) (nth 2 date))))
10525 (setq org-ans1 (format-time-string "%Y-%m-%d" time)))
10526 (if (active-minibuffer-window) (exit-minibuffer))))
10528 (defun org-check-deadlines (ndays)
10529 "Check if there are any deadlines due or past due.
10530 A deadline is considered due if it happens within `org-deadline-warning-days'
10531 days from today's date. If the deadline appears in an entry marked DONE,
10532 it is not shown. The prefix arg NDAYS can be used to test that many
10533 days. If the prefix is a raw \\[universal-argument] prefix, all deadlines are shown."
10534 (interactive "P")
10535 (let* ((org-warn-days
10536 (cond
10537 ((equal ndays '(4)) 100000)
10538 (ndays (prefix-numeric-value ndays))
10539 (t (abs org-deadline-warning-days))))
10540 (case-fold-search nil)
10541 (regexp (concat "\\<" org-deadline-string " *<\\([^>]+\\)>"))
10542 (callback
10543 (lambda () (org-deadline-close (match-string 1) org-warn-days))))
10545 (message "%d deadlines past-due or due within %d days"
10546 (org-occur regexp nil callback)
10547 org-warn-days)))
10549 (defun org-check-before-date (date)
10550 "Check if there are deadlines or scheduled entries before DATE."
10551 (interactive (list (org-read-date)))
10552 (let ((case-fold-search nil)
10553 (regexp (concat "\\<\\(" org-deadline-string
10554 "\\|" org-scheduled-string
10555 "\\) *<\\([^>]+\\)>"))
10556 (callback
10557 (lambda () (time-less-p
10558 (org-time-string-to-time (match-string 2))
10559 (org-time-string-to-time date)))))
10560 (message "%d entries before %s"
10561 (org-occur regexp nil callback) date)))
10563 (defun org-evaluate-time-range (&optional to-buffer)
10564 "Evaluate a time range by computing the difference between start and end.
10565 Normally the result is just printed in the echo area, but with prefix arg
10566 TO-BUFFER, the result is inserted just after the date stamp into the buffer.
10567 If the time range is actually in a table, the result is inserted into the
10568 next column.
10569 For time difference computation, a year is assumed to be exactly 365
10570 days in order to avoid rounding problems."
10571 (interactive "P")
10573 (org-clock-update-time-maybe)
10574 (save-excursion
10575 (unless (org-at-date-range-p t)
10576 (goto-char (point-at-bol))
10577 (re-search-forward org-tr-regexp-both (point-at-eol) t))
10578 (if (not (org-at-date-range-p t))
10579 (error "Not at a time-stamp range, and none found in current line")))
10580 (let* ((ts1 (match-string 1))
10581 (ts2 (match-string 2))
10582 (havetime (or (> (length ts1) 15) (> (length ts2) 15)))
10583 (match-end (match-end 0))
10584 (time1 (org-time-string-to-time ts1))
10585 (time2 (org-time-string-to-time ts2))
10586 (t1 (time-to-seconds time1))
10587 (t2 (time-to-seconds time2))
10588 (diff (abs (- t2 t1)))
10589 (negative (< (- t2 t1) 0))
10590 ;; (ys (floor (* 365 24 60 60)))
10591 (ds (* 24 60 60))
10592 (hs (* 60 60))
10593 (fy "%dy %dd %02d:%02d")
10594 (fy1 "%dy %dd")
10595 (fd "%dd %02d:%02d")
10596 (fd1 "%dd")
10597 (fh "%02d:%02d")
10598 y d h m align)
10599 (if havetime
10600 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10602 d (floor (/ diff ds)) diff (mod diff ds)
10603 h (floor (/ diff hs)) diff (mod diff hs)
10604 m (floor (/ diff 60)))
10605 (setq ; y (floor (/ diff ys)) diff (mod diff ys)
10607 d (floor (+ (/ diff ds) 0.5))
10608 h 0 m 0))
10609 (if (not to-buffer)
10610 (message "%s" (org-make-tdiff-string y d h m))
10611 (if (org-at-table-p)
10612 (progn
10613 (goto-char match-end)
10614 (setq align t)
10615 (and (looking-at " *|") (goto-char (match-end 0))))
10616 (goto-char match-end))
10617 (if (looking-at
10618 "\\( *-? *[0-9]+y\\)?\\( *[0-9]+d\\)? *[0-9][0-9]:[0-9][0-9]")
10619 (replace-match ""))
10620 (if negative (insert " -"))
10621 (if (> y 0) (insert " " (format (if havetime fy fy1) y d h m))
10622 (if (> d 0) (insert " " (format (if havetime fd fd1) d h m))
10623 (insert " " (format fh h m))))
10624 (if align (org-table-align))
10625 (message "Time difference inserted")))))
10627 (defun org-make-tdiff-string (y d h m)
10628 (let ((fmt "")
10629 (l nil))
10630 (if (> y 0) (setq fmt (concat fmt "%d year" (if (> y 1) "s" "") " ")
10631 l (push y l)))
10632 (if (> d 0) (setq fmt (concat fmt "%d day" (if (> d 1) "s" "") " ")
10633 l (push d l)))
10634 (if (> h 0) (setq fmt (concat fmt "%d hour" (if (> h 1) "s" "") " ")
10635 l (push h l)))
10636 (if (> m 0) (setq fmt (concat fmt "%d minute" (if (> m 1) "s" "") " ")
10637 l (push m l)))
10638 (apply 'format fmt (nreverse l))))
10640 (defun org-time-string-to-time (s)
10641 (apply 'encode-time (org-parse-time-string s)))
10643 (defun org-time-string-to-absolute (s &optional daynr prefer show-all)
10644 "Convert a time stamp to an absolute day number.
10645 If there is a specifyer for a cyclic time stamp, get the closest date to
10646 DAYNR.
10647 PREFER and SHOW_ALL are passed through to `org-closest-date'."
10648 (cond
10649 ((and daynr (string-match "\\`%%\\((.*)\\)" s))
10650 (if (org-diary-sexp-entry (match-string 1 s) "" date)
10651 daynr
10652 (+ daynr 1000)))
10653 ((and daynr (string-match "\\+[0-9]+[dwmy]" s))
10654 (org-closest-date s (if (and (boundp 'daynr) (integerp daynr)) daynr
10655 (time-to-days (current-time))) (match-string 0 s)
10656 prefer show-all))
10657 (t (time-to-days (apply 'encode-time (org-parse-time-string s))))))
10659 (defun org-days-to-iso-week (days)
10660 "Return the iso week number."
10661 (require 'cal-iso)
10662 (car (calendar-iso-from-absolute days)))
10664 (defun org-small-year-to-year (year)
10665 "Convert 2-digit years into 4-digit years.
10666 38-99 are mapped into 1938-1999. 1-37 are mapped into 2001-2007.
10667 The year 2000 cannot be abbreviated. Any year lager than 99
10668 is retrned unchanged."
10669 (if (< year 38)
10670 (setq year (+ 2000 year))
10671 (if (< year 100)
10672 (setq year (+ 1900 year))))
10673 year)
10675 (defun org-time-from-absolute (d)
10676 "Return the time corresponding to date D.
10677 D may be an absolute day number, or a calendar-type list (month day year)."
10678 (if (numberp d) (setq d (calendar-gregorian-from-absolute d)))
10679 (encode-time 0 0 0 (nth 1 d) (car d) (nth 2 d)))
10681 (defun org-calendar-holiday ()
10682 "List of holidays, for Diary display in Org-mode."
10683 (require 'holidays)
10684 (let ((hl (funcall
10685 (if (fboundp 'calendar-check-holidays)
10686 'calendar-check-holidays 'check-calendar-holidays) date)))
10687 (if hl (mapconcat 'identity hl "; "))))
10689 (defun org-diary-sexp-entry (sexp entry date)
10690 "Process a SEXP diary ENTRY for DATE."
10691 (require 'diary-lib)
10692 (let ((result (if calendar-debug-sexp
10693 (let ((stack-trace-on-error t))
10694 (eval (car (read-from-string sexp))))
10695 (condition-case nil
10696 (eval (car (read-from-string sexp)))
10697 (error
10698 (beep)
10699 (message "Bad sexp at line %d in %s: %s"
10700 (org-current-line)
10701 (buffer-file-name) sexp)
10702 (sleep-for 2))))))
10703 (cond ((stringp result) result)
10704 ((and (consp result)
10705 (stringp (cdr result))) (cdr result))
10706 (result entry)
10707 (t nil))))
10709 (defun org-diary-to-ical-string (frombuf)
10710 "Get iCalendar entries from diary entries in buffer FROMBUF.
10711 This uses the icalendar.el library."
10712 (let* ((tmpdir (if (featurep 'xemacs)
10713 (temp-directory)
10714 temporary-file-directory))
10715 (tmpfile (make-temp-name
10716 (expand-file-name "orgics" tmpdir)))
10717 buf rtn b e)
10718 (save-excursion
10719 (set-buffer frombuf)
10720 (icalendar-export-region (point-min) (point-max) tmpfile)
10721 (setq buf (find-buffer-visiting tmpfile))
10722 (set-buffer buf)
10723 (goto-char (point-min))
10724 (if (re-search-forward "^BEGIN:VEVENT" nil t)
10725 (setq b (match-beginning 0)))
10726 (goto-char (point-max))
10727 (if (re-search-backward "^END:VEVENT" nil t)
10728 (setq e (match-end 0)))
10729 (setq rtn (if (and b e) (concat (buffer-substring b e) "\n") "")))
10730 (kill-buffer buf)
10731 (kill-buffer frombuf)
10732 (delete-file tmpfile)
10733 rtn))
10735 (defun org-closest-date (start current change prefer show-all)
10736 "Find the date closest to CURRENT that is consistent with START and CHANGE.
10737 When PREFER is `past' return a date that is either CURRENT or past.
10738 When PREFER is `future', return a date that is either CURRENT or future.
10739 When SHOW-ALL is nil, only return the current occurence of a time stamp."
10740 ;; Make the proper lists from the dates
10741 (catch 'exit
10742 (let ((a1 '(("d" . day) ("w" . week) ("m" . month) ("y" . year)))
10743 dn dw sday cday n1 n2
10744 d m y y1 y2 date1 date2 nmonths nm ny m2)
10746 (setq start (org-date-to-gregorian start)
10747 current (org-date-to-gregorian
10748 (if show-all
10749 current
10750 (time-to-days (current-time))))
10751 sday (calendar-absolute-from-gregorian start)
10752 cday (calendar-absolute-from-gregorian current))
10754 (if (<= cday sday) (throw 'exit sday))
10756 (if (string-match "\\(\\+[0-9]+\\)\\([dwmy]\\)" change)
10757 (setq dn (string-to-number (match-string 1 change))
10758 dw (cdr (assoc (match-string 2 change) a1)))
10759 (error "Invalid change specifyer: %s" change))
10760 (if (eq dw 'week) (setq dw 'day dn (* 7 dn)))
10761 (cond
10762 ((eq dw 'day)
10763 (setq n1 (+ sday (* dn (floor (/ (- cday sday) dn))))
10764 n2 (+ n1 dn)))
10765 ((eq dw 'year)
10766 (setq d (nth 1 start) m (car start) y1 (nth 2 start) y2 (nth 2 current))
10767 (setq y1 (+ (* (floor (/ (- y2 y1) dn)) dn) y1))
10768 (setq date1 (list m d y1)
10769 n1 (calendar-absolute-from-gregorian date1)
10770 date2 (list m d (+ y1 (* (if (< n1 cday) 1 -1) dn)))
10771 n2 (calendar-absolute-from-gregorian date2)))
10772 ((eq dw 'month)
10773 ;; approx number of month between the tow dates
10774 (setq nmonths (floor (/ (- cday sday) 30.436875)))
10775 ;; How often does dn fit in there?
10776 (setq d (nth 1 start) m (car start) y (nth 2 start)
10777 nm (* dn (max 0 (1- (floor (/ nmonths dn)))))
10778 m (+ m nm)
10779 ny (floor (/ m 12))
10780 y (+ y ny)
10781 m (- m (* ny 12)))
10782 (while (> m 12) (setq m (- m 12) y (1+ y)))
10783 (setq n1 (calendar-absolute-from-gregorian (list m d y)))
10784 (setq m2 (+ m dn) y2 y)
10785 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10786 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2)))
10787 (while (< n2 cday)
10788 (setq n1 n2 m m2 y y2)
10789 (setq m2 (+ m dn) y2 y)
10790 (if (> m2 12) (setq y2 (1+ y2) m2 (- m2 12)))
10791 (setq n2 (calendar-absolute-from-gregorian (list m2 d y2))))))
10793 (if show-all
10794 (cond
10795 ((eq prefer 'past) n1)
10796 ((eq prefer 'future) (if (= cday n1) n1 n2))
10797 (t (if (> (abs (- cday n1)) (abs (- cday n2))) n2 n1)))
10798 (cond
10799 ((eq prefer 'past) n1)
10800 ((eq prefer 'future) (if (= cday n1) n1 n2))
10801 (t (if (= cday n1) n1 n2)))))))
10803 (defun org-date-to-gregorian (date)
10804 "Turn any specification of DATE into a gregorian date for the calendar."
10805 (cond ((integerp date) (calendar-gregorian-from-absolute date))
10806 ((and (listp date) (= (length date) 3)) date)
10807 ((stringp date)
10808 (setq date (org-parse-time-string date))
10809 (list (nth 4 date) (nth 3 date) (nth 5 date)))
10810 ((listp date)
10811 (list (nth 4 date) (nth 3 date) (nth 5 date)))))
10813 (defun org-parse-time-string (s &optional nodefault)
10814 "Parse the standard Org-mode time string.
10815 This should be a lot faster than the normal `parse-time-string'.
10816 If time is not given, defaults to 0:00. However, with optional NODEFAULT,
10817 hour and minute fields will be nil if not given."
10818 (if (string-match org-ts-regexp0 s)
10819 (list 0
10820 (if (or (match-beginning 8) (not nodefault))
10821 (string-to-number (or (match-string 8 s) "0")))
10822 (if (or (match-beginning 7) (not nodefault))
10823 (string-to-number (or (match-string 7 s) "0")))
10824 (string-to-number (match-string 4 s))
10825 (string-to-number (match-string 3 s))
10826 (string-to-number (match-string 2 s))
10827 nil nil nil)
10828 (make-list 9 0)))
10830 (defun org-timestamp-up (&optional arg)
10831 "Increase 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-down (&optional arg)
10839 "Decrease the date item at the cursor by one.
10840 If the cursor is on the year, change the year. If it is on the month or
10841 the day, change that.
10842 With prefix ARG, change by that many units."
10843 (interactive "p")
10844 (org-timestamp-change (- (prefix-numeric-value arg))))
10846 (defun org-timestamp-up-day (&optional arg)
10847 "Increase the date in the time stamp by one day.
10848 With prefix ARG, change that many days."
10849 (interactive "p")
10850 (if (and (not (org-at-timestamp-p t))
10851 (org-on-heading-p))
10852 (org-todo 'up)
10853 (org-timestamp-change (prefix-numeric-value arg) 'day)))
10855 (defun org-timestamp-down-day (&optional arg)
10856 "Decrease the date in the time stamp by one day.
10857 With prefix ARG, change that many days."
10858 (interactive "p")
10859 (if (and (not (org-at-timestamp-p t))
10860 (org-on-heading-p))
10861 (org-todo 'down)
10862 (org-timestamp-change (- (prefix-numeric-value arg)) 'day)))
10864 (defun org-at-timestamp-p (&optional inactive-ok)
10865 "Determine if the cursor is in or at a timestamp."
10866 (interactive)
10867 (let* ((tsr (if inactive-ok org-ts-regexp3 org-ts-regexp2))
10868 (pos (point))
10869 (ans (or (looking-at tsr)
10870 (save-excursion
10871 (skip-chars-backward "^[<\n\r\t")
10872 (if (> (point) (point-min)) (backward-char 1))
10873 (and (looking-at tsr)
10874 (> (- (match-end 0) pos) -1))))))
10875 (and ans
10876 (boundp 'org-ts-what)
10877 (setq org-ts-what
10878 (cond
10879 ((= pos (match-beginning 0)) 'bracket)
10880 ((= pos (1- (match-end 0))) 'bracket)
10881 ((org-pos-in-match-range pos 2) 'year)
10882 ((org-pos-in-match-range pos 3) 'month)
10883 ((org-pos-in-match-range pos 7) 'hour)
10884 ((org-pos-in-match-range pos 8) 'minute)
10885 ((or (org-pos-in-match-range pos 4)
10886 (org-pos-in-match-range pos 5)) 'day)
10887 ((and (> pos (or (match-end 8) (match-end 5)))
10888 (< pos (match-end 0)))
10889 (- pos (or (match-end 8) (match-end 5))))
10890 (t 'day))))
10891 ans))
10893 (defun org-toggle-timestamp-type ()
10894 "Toggle the type (<active> or [inactive]) of a time stamp."
10895 (interactive)
10896 (when (org-at-timestamp-p t)
10897 (save-excursion
10898 (goto-char (match-beginning 0))
10899 (insert (if (equal (char-after) ?<) "[" "<")) (delete-char 1)
10900 (goto-char (1- (match-end 0)))
10901 (insert (if (equal (char-after) ?>) "]" ">")) (delete-char 1))
10902 (message "Timestamp is now %sactive"
10903 (if (equal (char-before) ?>) "in" ""))))
10905 (defun org-timestamp-change (n &optional what)
10906 "Change the date in the time stamp at point.
10907 The date will be changed by N times WHAT. WHAT can be `day', `month',
10908 `year', `minute', `second'. If WHAT is not given, the cursor position
10909 in the timestamp determines what will be changed."
10910 (let ((pos (point))
10911 with-hm inactive
10912 (dm (max (nth 1 org-time-stamp-rounding-minutes) 1))
10913 org-ts-what
10914 extra rem
10915 ts time time0)
10916 (if (not (org-at-timestamp-p t))
10917 (error "Not at a timestamp"))
10918 (if (and (not what) (eq org-ts-what 'bracket))
10919 (org-toggle-timestamp-type)
10920 (if (and (not what) (not (eq org-ts-what 'day))
10921 org-display-custom-times
10922 (get-text-property (point) 'display)
10923 (not (get-text-property (1- (point)) 'display)))
10924 (setq org-ts-what 'day))
10925 (setq org-ts-what (or what org-ts-what)
10926 inactive (= (char-after (match-beginning 0)) ?\[)
10927 ts (match-string 0))
10928 (replace-match "")
10929 (if (string-match
10930 "\\(\\(-[012][0-9]:[0-5][0-9]\\)?\\( +[.+]?[-+][0-9]+[dwmy]\\)*\\)[]>]"
10932 (setq extra (match-string 1 ts)))
10933 (if (string-match "^.\\{10\\}.*?[0-9]+:[0-9][0-9]" ts)
10934 (setq with-hm t))
10935 (setq time0 (org-parse-time-string ts))
10936 (when (and (eq org-ts-what 'minute)
10937 (eq current-prefix-arg nil))
10938 (setq n (* dm (cond ((> n 0) 1) ((< n 0) -1) (t 0))))
10939 (when (not (= 0 (setq rem (% (nth 1 time0) dm))))
10940 (setcar (cdr time0) (+ (nth 1 time0)
10941 (if (> n 0) (- rem) (- dm rem))))))
10942 (setq time
10943 (encode-time (or (car time0) 0)
10944 (+ (if (eq org-ts-what 'minute) n 0) (nth 1 time0))
10945 (+ (if (eq org-ts-what 'hour) n 0) (nth 2 time0))
10946 (+ (if (eq org-ts-what 'day) n 0) (nth 3 time0))
10947 (+ (if (eq org-ts-what 'month) n 0) (nth 4 time0))
10948 (+ (if (eq org-ts-what 'year) n 0) (nth 5 time0))
10949 (nthcdr 6 time0)))
10950 (when (integerp org-ts-what)
10951 (setq extra (org-modify-ts-extra extra org-ts-what n dm)))
10952 (if (eq what 'calendar)
10953 (let ((cal-date (org-get-date-from-calendar)))
10954 (setcar (nthcdr 4 time0) (nth 0 cal-date)) ; month
10955 (setcar (nthcdr 3 time0) (nth 1 cal-date)) ; day
10956 (setcar (nthcdr 5 time0) (nth 2 cal-date)) ; year
10957 (setcar time0 (or (car time0) 0))
10958 (setcar (nthcdr 1 time0) (or (nth 1 time0) 0))
10959 (setcar (nthcdr 2 time0) (or (nth 2 time0) 0))
10960 (setq time (apply 'encode-time time0))))
10961 (setq org-last-changed-timestamp
10962 (org-insert-time-stamp time with-hm inactive nil nil extra))
10963 (org-clock-update-time-maybe)
10964 (goto-char pos)
10965 ;; Try to recenter the calendar window, if any
10966 (if (and org-calendar-follow-timestamp-change
10967 (get-buffer-window "*Calendar*" t)
10968 (memq org-ts-what '(day month year)))
10969 (org-recenter-calendar (time-to-days time))))))
10971 (defun org-modify-ts-extra (s pos n dm)
10972 "Change the different parts of the lead-time and repeat fields in timestamp."
10973 (let ((idx '(("d" . 0) ("w" . 1) ("m" . 2) ("y" . 3) ("d" . -1) ("y" . 4)))
10974 ng h m new rem)
10975 (when (string-match "\\(-\\([012][0-9]\\):\\([0-5][0-9]\\)\\)?\\( +\\+\\([0-9]+\\)\\([dmwy]\\)\\)?\\( +-\\([0-9]+\\)\\([dmwy]\\)\\)?" s)
10976 (cond
10977 ((or (org-pos-in-match-range pos 2)
10978 (org-pos-in-match-range pos 3))
10979 (setq m (string-to-number (match-string 3 s))
10980 h (string-to-number (match-string 2 s)))
10981 (if (org-pos-in-match-range pos 2)
10982 (setq h (+ h n))
10983 (setq n (* dm (org-no-warnings (signum n))))
10984 (when (not (= 0 (setq rem (% m dm))))
10985 (setq m (+ m (if (> n 0) (- rem) (- dm rem)))))
10986 (setq m (+ m n)))
10987 (if (< m 0) (setq m (+ m 60) h (1- h)))
10988 (if (> m 59) (setq m (- m 60) h (1+ h)))
10989 (setq h (min 24 (max 0 h)))
10990 (setq ng 1 new (format "-%02d:%02d" h m)))
10991 ((org-pos-in-match-range pos 6)
10992 (setq ng 6 new (car (rassoc (+ n (cdr (assoc (match-string 6 s) idx))) idx))))
10993 ((org-pos-in-match-range pos 5)
10994 (setq ng 5 new (format "%d" (max 1 (+ n (string-to-number (match-string 5 s)))))))
10996 ((org-pos-in-match-range pos 9)
10997 (setq ng 9 new (car (rassoc (+ n (cdr (assoc (match-string 9 s) idx))) idx))))
10998 ((org-pos-in-match-range pos 8)
10999 (setq ng 8 new (format "%d" (max 0 (+ n (string-to-number (match-string 8 s))))))))
11001 (when ng
11002 (setq s (concat
11003 (substring s 0 (match-beginning ng))
11005 (substring s (match-end ng))))))
11008 (defun org-recenter-calendar (date)
11009 "If the calendar is visible, recenter it to DATE."
11010 (let* ((win (selected-window))
11011 (cwin (get-buffer-window "*Calendar*" t))
11012 (calendar-move-hook nil))
11013 (when cwin
11014 (select-window cwin)
11015 (calendar-goto-date (if (listp date) date
11016 (calendar-gregorian-from-absolute date)))
11017 (select-window win))))
11019 (defun org-goto-calendar (&optional arg)
11020 "Go to the Emacs calendar at the current date.
11021 If there is a time stamp in the current line, go to that date.
11022 A prefix ARG can be used to force the current date."
11023 (interactive "P")
11024 (let ((tsr org-ts-regexp) diff
11025 (calendar-move-hook nil)
11026 (calendar-view-holidays-initially-flag nil)
11027 (view-calendar-holidays-initially nil)
11028 (calendar-view-diary-initially-flag nil)
11029 (view-diary-entries-initially nil))
11030 (if (or (org-at-timestamp-p)
11031 (save-excursion
11032 (beginning-of-line 1)
11033 (looking-at (concat ".*" tsr))))
11034 (let ((d1 (time-to-days (current-time)))
11035 (d2 (time-to-days
11036 (org-time-string-to-time (match-string 1)))))
11037 (setq diff (- d2 d1))))
11038 (calendar)
11039 (calendar-goto-today)
11040 (if (and diff (not arg)) (calendar-forward-day diff))))
11042 (defun org-get-date-from-calendar ()
11043 "Return a list (month day year) of date at point in calendar."
11044 (with-current-buffer "*Calendar*"
11045 (save-match-data
11046 (calendar-cursor-to-date))))
11048 (defun org-date-from-calendar ()
11049 "Insert time stamp corresponding to cursor date in *Calendar* buffer.
11050 If there is already a time stamp at the cursor position, update it."
11051 (interactive)
11052 (if (org-at-timestamp-p t)
11053 (org-timestamp-change 0 'calendar)
11054 (let ((cal-date (org-get-date-from-calendar)))
11055 (org-insert-time-stamp
11056 (encode-time 0 0 0 (nth 1 cal-date) (car cal-date) (nth 2 cal-date))))))
11058 (defun org-minutes-to-hh:mm-string (m)
11059 "Compute H:MM from a number of minutes."
11060 (let ((h (/ m 60)))
11061 (setq m (- m (* 60 h)))
11062 (format "%d:%02d" h m)))
11064 (defun org-hh:mm-string-to-minutes (s)
11065 "Convert a string H:MM to a number of minutes."
11066 (if (string-match "\\([0-9]+\\):\\([0-9]+\\)" s)
11067 (+ (* (string-to-number (match-string 1 s)) 60)
11068 (string-to-number (match-string 2 s)))
11071 ;;;; Agenda files
11073 ;;;###autoload
11074 (defun org-iswitchb (&optional arg)
11075 "Use `iswitchb-read-buffer' to prompt for an Org buffer to switch to.
11076 With a prefix argument, restrict available to files.
11077 With two prefix arguments, restrict available buffers to agenda files.
11079 Due to some yet unresolved reason, global function
11080 `iswitchb-mode' needs to be active for this function to work."
11081 (interactive "P")
11082 (require 'iswitchb)
11083 (let ((enabled iswitchb-mode) blist)
11084 (or enabled (iswitchb-mode 1))
11085 (setq blist (cond ((equal arg '(4)) (org-buffer-list 'files))
11086 ((equal arg '(16)) (org-buffer-list 'agenda))
11087 (t (org-buffer-list))))
11088 (unwind-protect
11089 (let ((iswitchb-make-buflist-hook
11090 (lambda ()
11091 (setq iswitchb-temp-buflist
11092 (mapcar 'buffer-name blist)))))
11093 (switch-to-buffer
11094 (iswitchb-read-buffer
11095 "Switch-to: " nil t))
11096 (or enabled (iswitchb-mode -1))))))
11098 (defun org-buffer-list (&optional predicate tmp)
11099 "Return a list of Org buffers.
11100 PREDICATE can be either 'export, 'files or 'agenda.
11102 'export restrict the list to Export buffers.
11103 'files restrict the list to buffers visiting Org files.
11104 'agenda restrict the list to buffers visiting agenda files.
11106 If TMP is non-nil, don't include temporary buffers."
11107 (let (filter blist)
11108 (setq filter
11109 (cond ((eq predicate 'files) "\.org$")
11110 ((eq predicate 'export) "\*Org .*Export")
11111 (t "\*Org \\|\.org$")))
11112 (setq blist
11113 (mapcar
11114 (lambda(b)
11115 (let ((bname (buffer-name b))
11116 (bfile (buffer-file-name b)))
11117 (if (and (string-match filter bname)
11118 (if (eq predicate 'agenda)
11119 (member bfile
11120 (mapcar (lambda(f) (file-truename f))
11121 org-agenda-files)) t)
11122 (if tmp (not (string-match "tmp" bname)) t)) b)))
11123 (buffer-list)))
11124 (delete nil blist)))
11126 (defun org-agenda-files (&optional unrestricted ext)
11127 "Get the list of agenda files.
11128 Optional UNRESTRICTED means return the full list even if a restriction
11129 is currently in place.
11130 When EXT is non-nil, try to add all files that are created by adding EXT
11131 to the file nemes. Basically, this is a way to add the archive files
11132 to the list, by setting EXT to \"_archive\" If EXT is non-nil, but not
11133 a string, \"_archive\" will be used."
11134 (let ((files
11135 (cond
11136 ((and (not unrestricted) (get 'org-agenda-files 'org-restrict)))
11137 ((stringp org-agenda-files) (org-read-agenda-file-list))
11138 ((listp org-agenda-files) org-agenda-files)
11139 (t (error "Invalid value of `org-agenda-files'")))))
11140 (setq files (apply 'append
11141 (mapcar (lambda (f)
11142 (if (file-directory-p f)
11143 (directory-files
11144 f t org-agenda-file-regexp)
11145 (list f)))
11146 files)))
11147 (when org-agenda-skip-unavailable-files
11148 (setq files (delq nil
11149 (mapcar (function
11150 (lambda (file)
11151 (and (file-readable-p file) file)))
11152 files))))
11153 (when ext
11154 (setq ext (if (and (stringp ext) (string-match "\\S-" ext))
11155 ext "_archive"))
11156 (setq files (apply 'append
11157 (mapcar
11158 (lambda (f)
11159 (if (file-exists-p (concat f ext))
11160 (list f (concat f ext))
11161 (list f)))
11162 files))))
11163 files))
11165 (defun org-edit-agenda-file-list ()
11166 "Edit the list of agenda files.
11167 Depending on setup, this either uses customize to edit the variable
11168 `org-agenda-files', or it visits the file that is holding the list. In the
11169 latter case, the buffer is set up in a way that saving it automatically kills
11170 the buffer and restores the previous window configuration."
11171 (interactive)
11172 (if (stringp org-agenda-files)
11173 (let ((cw (current-window-configuration)))
11174 (find-file org-agenda-files)
11175 (org-set-local 'org-window-configuration cw)
11176 (org-add-hook 'after-save-hook
11177 (lambda ()
11178 (set-window-configuration
11179 (prog1 org-window-configuration
11180 (kill-buffer (current-buffer))))
11181 (org-install-agenda-files-menu)
11182 (message "New agenda file list installed"))
11183 nil 'local)
11184 (message "%s" (substitute-command-keys
11185 "Edit list and finish with \\[save-buffer]")))
11186 (customize-variable 'org-agenda-files)))
11188 (defun org-store-new-agenda-file-list (list)
11189 "Set new value for the agenda file list and save it correcly."
11190 (if (stringp org-agenda-files)
11191 (let ((f org-agenda-files) b)
11192 (while (setq b (find-buffer-visiting f)) (kill-buffer b))
11193 (with-temp-file f
11194 (insert (mapconcat 'identity list "\n") "\n")))
11195 (let ((org-mode-hook nil) (default-major-mode 'fundamental-mode))
11196 (setq org-agenda-files list)
11197 (customize-save-variable 'org-agenda-files org-agenda-files))))
11199 (defun org-read-agenda-file-list ()
11200 "Read the list of agenda files from a file."
11201 (when (file-directory-p org-agenda-files)
11202 (error "`org-agenda-files' cannot be a single directory"))
11203 (when (stringp org-agenda-files)
11204 (with-temp-buffer
11205 (insert-file-contents org-agenda-files)
11206 (org-split-string (buffer-string) "[ \t\r\n]*?[\r\n][ \t\r\n]*"))))
11209 ;;;###autoload
11210 (defun org-cycle-agenda-files ()
11211 "Cycle through the files in `org-agenda-files'.
11212 If the current buffer visits an agenda file, find the next one in the list.
11213 If the current buffer does not, find the first agenda file."
11214 (interactive)
11215 (let* ((fs (org-agenda-files t))
11216 (files (append fs (list (car fs))))
11217 (tcf (if buffer-file-name (file-truename buffer-file-name)))
11218 file)
11219 (unless files (error "No agenda files"))
11220 (catch 'exit
11221 (while (setq file (pop files))
11222 (if (equal (file-truename file) tcf)
11223 (when (car files)
11224 (find-file (car files))
11225 (throw 'exit t))))
11226 (find-file (car fs)))
11227 (if (buffer-base-buffer) (switch-to-buffer (buffer-base-buffer)))))
11229 (defun org-agenda-file-to-front (&optional to-end)
11230 "Move/add the current file to the top of the agenda file list.
11231 If the file is not present in the list, it is added to the front. If it is
11232 present, it is moved there. With optional argument TO-END, add/move to the
11233 end of the list."
11234 (interactive "P")
11235 (let ((org-agenda-skip-unavailable-files nil)
11236 (file-alist (mapcar (lambda (x)
11237 (cons (file-truename x) x))
11238 (org-agenda-files t)))
11239 (ctf (file-truename buffer-file-name))
11240 x had)
11241 (setq x (assoc ctf file-alist) had x)
11243 (if (not x) (setq x (cons ctf (abbreviate-file-name buffer-file-name))))
11244 (if to-end
11245 (setq file-alist (append (delq x file-alist) (list x)))
11246 (setq file-alist (cons x (delq x file-alist))))
11247 (org-store-new-agenda-file-list (mapcar 'cdr file-alist))
11248 (org-install-agenda-files-menu)
11249 (message "File %s to %s of agenda file list"
11250 (if had "moved" "added") (if to-end "end" "front"))))
11252 (defun org-remove-file (&optional file)
11253 "Remove current file from the list of files in variable `org-agenda-files'.
11254 These are the files which are being checked for agenda entries.
11255 Optional argument FILE means, use this file instead of the current."
11256 (interactive)
11257 (let* ((org-agenda-skip-unavailable-files nil)
11258 (file (or file buffer-file-name))
11259 (true-file (file-truename file))
11260 (afile (abbreviate-file-name file))
11261 (files (delq nil (mapcar
11262 (lambda (x)
11263 (if (equal true-file
11264 (file-truename x))
11265 nil x))
11266 (org-agenda-files t)))))
11267 (if (not (= (length files) (length (org-agenda-files t))))
11268 (progn
11269 (org-store-new-agenda-file-list files)
11270 (org-install-agenda-files-menu)
11271 (message "Removed file: %s" afile))
11272 (message "File was not in list: %s (not removed)" afile))))
11274 (defun org-file-menu-entry (file)
11275 (vector file (list 'find-file file) t))
11277 (defun org-check-agenda-file (file)
11278 "Make sure FILE exists. If not, ask user what to do."
11279 (when (not (file-exists-p file))
11280 (message "non-existent file %s. [R]emove from list or [A]bort?"
11281 (abbreviate-file-name file))
11282 (let ((r (downcase (read-char-exclusive))))
11283 (cond
11284 ((equal r ?r)
11285 (org-remove-file file)
11286 (throw 'nextfile t))
11287 (t (error "Abort"))))))
11289 (defun org-get-agenda-file-buffer (file)
11290 "Get a buffer visiting FILE. If the buffer needs to be created, add
11291 it to the list of buffers which might be released later."
11292 (let ((buf (org-find-base-buffer-visiting file)))
11293 (if buf
11294 buf ; just return it
11295 ;; Make a new buffer and remember it
11296 (setq buf (find-file-noselect file))
11297 (if buf (push buf org-agenda-new-buffers))
11298 buf)))
11300 (defun org-release-buffers (blist)
11301 "Release all buffers in list, asking the user for confirmation when needed.
11302 When a buffer is unmodified, it is just killed. When modified, it is saved
11303 \(if the user agrees) and then killed."
11304 (let (buf file)
11305 (while (setq buf (pop blist))
11306 (setq file (buffer-file-name buf))
11307 (when (and (buffer-modified-p buf)
11308 file
11309 (y-or-n-p (format "Save file %s? " file)))
11310 (with-current-buffer buf (save-buffer)))
11311 (kill-buffer buf))))
11313 (defun org-prepare-agenda-buffers (files)
11314 "Create buffers for all agenda files, protect archived trees and comments."
11315 (interactive)
11316 (let ((pa '(:org-archived t))
11317 (pc '(:org-comment t))
11318 (pall '(:org-archived t :org-comment t))
11319 (inhibit-read-only t)
11320 (rea (concat ":" org-archive-tag ":"))
11321 bmp file re)
11322 (save-excursion
11323 (save-restriction
11324 (while (setq file (pop files))
11325 (if (bufferp file)
11326 (set-buffer file)
11327 (org-check-agenda-file file)
11328 (set-buffer (org-get-agenda-file-buffer file)))
11329 (widen)
11330 (setq bmp (buffer-modified-p))
11331 (org-refresh-category-properties)
11332 (setq org-todo-keywords-for-agenda
11333 (append org-todo-keywords-for-agenda org-todo-keywords-1))
11334 (setq org-done-keywords-for-agenda
11335 (append org-done-keywords-for-agenda org-done-keywords))
11336 (save-excursion
11337 (remove-text-properties (point-min) (point-max) pall)
11338 (when org-agenda-skip-archived-trees
11339 (goto-char (point-min))
11340 (while (re-search-forward rea nil t)
11341 (if (org-on-heading-p t)
11342 (add-text-properties (point-at-bol) (org-end-of-subtree t) pa))))
11343 (goto-char (point-min))
11344 (setq re (concat "^\\*+ +" org-comment-string "\\>"))
11345 (while (re-search-forward re nil t)
11346 (add-text-properties
11347 (match-beginning 0) (org-end-of-subtree t) pc)))
11348 (set-buffer-modified-p bmp))))))
11350 ;;;; Embedded LaTeX
11352 (defvar org-cdlatex-mode-map (make-sparse-keymap)
11353 "Keymap for the minor `org-cdlatex-mode'.")
11355 (org-defkey org-cdlatex-mode-map "_" 'org-cdlatex-underscore-caret)
11356 (org-defkey org-cdlatex-mode-map "^" 'org-cdlatex-underscore-caret)
11357 (org-defkey org-cdlatex-mode-map "`" 'cdlatex-math-symbol)
11358 (org-defkey org-cdlatex-mode-map "'" 'org-cdlatex-math-modify)
11359 (org-defkey org-cdlatex-mode-map "\C-c{" 'cdlatex-environment)
11361 (defvar org-cdlatex-texmathp-advice-is-done nil
11362 "Flag remembering if we have applied the advice to texmathp already.")
11364 (define-minor-mode org-cdlatex-mode
11365 "Toggle the minor `org-cdlatex-mode'.
11366 This mode supports entering LaTeX environment and math in LaTeX fragments
11367 in Org-mode.
11368 \\{org-cdlatex-mode-map}"
11369 nil " OCDL" nil
11370 (when org-cdlatex-mode (require 'cdlatex))
11371 (unless org-cdlatex-texmathp-advice-is-done
11372 (setq org-cdlatex-texmathp-advice-is-done t)
11373 (defadvice texmathp (around org-math-always-on activate)
11374 "Always return t in org-mode buffers.
11375 This is because we want to insert math symbols without dollars even outside
11376 the LaTeX math segments. If Orgmode thinks that point is actually inside
11377 en embedded LaTeX fragement, let texmathp do its job.
11378 \\[org-cdlatex-mode-map]"
11379 (interactive)
11380 (let (p)
11381 (cond
11382 ((not (org-mode-p)) ad-do-it)
11383 ((eq this-command 'cdlatex-math-symbol)
11384 (setq ad-return-value t
11385 texmathp-why '("cdlatex-math-symbol in org-mode" . 0)))
11387 (let ((p (org-inside-LaTeX-fragment-p)))
11388 (if (and p (member (car p) (plist-get org-format-latex-options :matchers)))
11389 (setq ad-return-value t
11390 texmathp-why '("Org-mode embedded math" . 0))
11391 (if p ad-do-it)))))))))
11393 (defun turn-on-org-cdlatex ()
11394 "Unconditionally turn on `org-cdlatex-mode'."
11395 (org-cdlatex-mode 1))
11397 (defun org-inside-LaTeX-fragment-p ()
11398 "Test if point is inside a LaTeX fragment.
11399 I.e. after a \\begin, \\(, \\[, $, or $$, without the corresponding closing
11400 sequence appearing also before point.
11401 Even though the matchers for math are configurable, this function assumes
11402 that \\begin, \\(, \\[, and $$ are always used. Only the single dollar
11403 delimiters are skipped when they have been removed by customization.
11404 The return value is nil, or a cons cell with the delimiter and
11405 and the position of this delimiter.
11407 This function does a reasonably good job, but can locally be fooled by
11408 for example currency specifications. For example it will assume being in
11409 inline math after \"$22.34\". The LaTeX fragment formatter will only format
11410 fragments that are properly closed, but during editing, we have to live
11411 with the uncertainty caused by missing closing delimiters. This function
11412 looks only before point, not after."
11413 (catch 'exit
11414 (let ((pos (point))
11415 (dodollar (member "$" (plist-get org-format-latex-options :matchers)))
11416 (lim (progn
11417 (re-search-backward (concat "^\\(" paragraph-start "\\)") nil t)
11418 (point)))
11419 dd-on str (start 0) m re)
11420 (goto-char pos)
11421 (when dodollar
11422 (setq str (concat (buffer-substring lim (point)) "\000 X$.")
11423 re (nth 1 (assoc "$" org-latex-regexps)))
11424 (while (string-match re str start)
11425 (cond
11426 ((= (match-end 0) (length str))
11427 (throw 'exit (cons "$" (+ lim (match-beginning 0) 1))))
11428 ((= (match-end 0) (- (length str) 5))
11429 (throw 'exit nil))
11430 (t (setq start (match-end 0))))))
11431 (when (setq m (re-search-backward "\\(\\\\begin{[^}]*}\\|\\\\(\\|\\\\\\[\\)\\|\\(\\\\end{[^}]*}\\|\\\\)\\|\\\\\\]\\)\\|\\(\\$\\$\\)" lim t))
11432 (goto-char pos)
11433 (and (match-beginning 1) (throw 'exit (cons (match-string 1) m)))
11434 (and (match-beginning 2) (throw 'exit nil))
11435 ;; count $$
11436 (while (re-search-backward "\\$\\$" lim t)
11437 (setq dd-on (not dd-on)))
11438 (goto-char pos)
11439 (if dd-on (cons "$$" m))))))
11442 (defun org-try-cdlatex-tab ()
11443 "Check if it makes sense to execute `cdlatex-tab', and do it if yes.
11444 It makes sense to do so if `org-cdlatex-mode' is active and if the cursor is
11445 - inside a LaTeX fragment, or
11446 - after the first word in a line, where an abbreviation expansion could
11447 insert a LaTeX environment."
11448 (when org-cdlatex-mode
11449 (cond
11450 ((save-excursion
11451 (skip-chars-backward "a-zA-Z0-9*")
11452 (skip-chars-backward " \t")
11453 (bolp))
11454 (cdlatex-tab) t)
11455 ((org-inside-LaTeX-fragment-p)
11456 (cdlatex-tab) t)
11457 (t nil))))
11459 (defun org-cdlatex-underscore-caret (&optional arg)
11460 "Execute `cdlatex-sub-superscript' in LaTeX fragments.
11461 Revert to the normal definition outside of these fragments."
11462 (interactive "P")
11463 (if (org-inside-LaTeX-fragment-p)
11464 (call-interactively 'cdlatex-sub-superscript)
11465 (let (org-cdlatex-mode)
11466 (call-interactively (key-binding (vector last-input-event))))))
11468 (defun org-cdlatex-math-modify (&optional arg)
11469 "Execute `cdlatex-math-modify' in LaTeX fragments.
11470 Revert to the normal definition outside of these fragments."
11471 (interactive "P")
11472 (if (org-inside-LaTeX-fragment-p)
11473 (call-interactively 'cdlatex-math-modify)
11474 (let (org-cdlatex-mode)
11475 (call-interactively (key-binding (vector last-input-event))))))
11477 (defvar org-latex-fragment-image-overlays nil
11478 "List of overlays carrying the images of latex fragments.")
11479 (make-variable-buffer-local 'org-latex-fragment-image-overlays)
11481 (defun org-remove-latex-fragment-image-overlays ()
11482 "Remove all overlays with LaTeX fragment images in current buffer."
11483 (mapc 'org-delete-overlay org-latex-fragment-image-overlays)
11484 (setq org-latex-fragment-image-overlays nil))
11486 (defun org-preview-latex-fragment (&optional subtree)
11487 "Preview the LaTeX fragment at point, or all locally or globally.
11488 If the cursor is in a LaTeX fragment, create the image and overlay
11489 it over the source code. If there is no fragment at point, display
11490 all fragments in the current text, from one headline to the next. With
11491 prefix SUBTREE, display all fragments in the current subtree. With a
11492 double prefix `C-u C-u', or when the cursor is before the first headline,
11493 display all fragments in the buffer.
11494 The images can be removed again with \\[org-ctrl-c-ctrl-c]."
11495 (interactive "P")
11496 (org-remove-latex-fragment-image-overlays)
11497 (save-excursion
11498 (save-restriction
11499 (let (beg end at msg)
11500 (cond
11501 ((or (equal subtree '(16))
11502 (not (save-excursion
11503 (re-search-backward (concat "^" outline-regexp) nil t))))
11504 (setq beg (point-min) end (point-max)
11505 msg "Creating images for buffer...%s"))
11506 ((equal subtree '(4))
11507 (org-back-to-heading)
11508 (setq beg (point) end (org-end-of-subtree t)
11509 msg "Creating images for subtree...%s"))
11511 (if (setq at (org-inside-LaTeX-fragment-p))
11512 (goto-char (max (point-min) (- (cdr at) 2)))
11513 (org-back-to-heading))
11514 (setq beg (point) end (progn (outline-next-heading) (point))
11515 msg (if at "Creating image...%s"
11516 "Creating images for entry...%s"))))
11517 (message msg "")
11518 (narrow-to-region beg end)
11519 (goto-char beg)
11520 (org-format-latex
11521 (concat "ltxpng/" (file-name-sans-extension
11522 (file-name-nondirectory
11523 buffer-file-name)))
11524 default-directory 'overlays msg at 'forbuffer)
11525 (message msg "done. Use `C-c C-c' to remove images.")))))
11527 (defvar org-latex-regexps
11528 '(("begin" "^[ \t]*\\(\\\\begin{\\([a-zA-Z0-9\\*]+\\)[^\000]+?\\\\end{\\2}\\)" 1 t)
11529 ;; ("$" "\\([ (]\\|^\\)\\(\\(\\([$]\\)\\([^ \r\n,.$].*?\\(\n.*?\\)\\{0,5\\}[^ \r\n,.$]\\)\\4\\)\\)\\([ .,?;:'\")]\\|$\\)" 2 nil)
11530 ;; \000 in the following regex is needed for org-inside-LaTeX-fragment-p
11531 ("$" "\\([^$]\\)\\(\\(\\$\\([^ \r\n,;.$][^$\n\r]*?\\(\n[^$\n\r]*?\\)\\{0,2\\}[^ \r\n,.$]\\)\\$\\)\\)\\([ .,?;:'\")\000]\\|$\\)" 2 nil)
11532 ("\\(" "\\\\([^\000]*?\\\\)" 0 nil)
11533 ("\\[" "\\\\\\[[^\000]*?\\\\\\]" 0 t)
11534 ("$$" "\\$\\$[^\000]*?\\$\\$" 0 t))
11535 "Regular expressions for matching embedded LaTeX.")
11537 (defun org-format-latex (prefix &optional dir overlays msg at forbuffer)
11538 "Replace LaTeX fragments with links to an image, and produce images."
11539 (if (and overlays (fboundp 'clear-image-cache)) (clear-image-cache))
11540 (let* ((prefixnodir (file-name-nondirectory prefix))
11541 (absprefix (expand-file-name prefix dir))
11542 (todir (file-name-directory absprefix))
11543 (opt org-format-latex-options)
11544 (matchers (plist-get opt :matchers))
11545 (re-list org-latex-regexps)
11546 (cnt 0) txt link beg end re e checkdir
11547 m n block linkfile movefile ov)
11548 ;; Check if there are old images files with this prefix, and remove them
11549 (when (file-directory-p todir)
11550 (mapc 'delete-file
11551 (directory-files
11552 todir 'full
11553 (concat (regexp-quote prefixnodir) "_[0-9]+\\.png$"))))
11554 ;; Check the different regular expressions
11555 (while (setq e (pop re-list))
11556 (setq m (car e) re (nth 1 e) n (nth 2 e)
11557 block (if (nth 3 e) "\n\n" ""))
11558 (when (member m matchers)
11559 (goto-char (point-min))
11560 (while (re-search-forward re nil t)
11561 (when (or (not at) (equal (cdr at) (match-beginning n)))
11562 (setq txt (match-string n)
11563 beg (match-beginning n) end (match-end n)
11564 cnt (1+ cnt)
11565 linkfile (format "%s_%04d.png" prefix cnt)
11566 movefile (format "%s_%04d.png" absprefix cnt)
11567 link (concat block "[[file:" linkfile "]]" block))
11568 (if msg (message msg cnt))
11569 (goto-char beg)
11570 (unless checkdir ; make sure the directory exists
11571 (setq checkdir t)
11572 (or (file-directory-p todir) (make-directory todir)))
11573 (org-create-formula-image
11574 txt movefile opt forbuffer)
11575 (if overlays
11576 (progn
11577 (setq ov (org-make-overlay beg end))
11578 (if (featurep 'xemacs)
11579 (progn
11580 (org-overlay-put ov 'invisible t)
11581 (org-overlay-put
11582 ov 'end-glyph
11583 (make-glyph (vector 'png :file movefile))))
11584 (org-overlay-put
11585 ov 'display
11586 (list 'image :type 'png :file movefile :ascent 'center)))
11587 (push ov org-latex-fragment-image-overlays)
11588 (goto-char end))
11589 (delete-region beg end)
11590 (insert link))))))))
11592 ;; This function borrows from Ganesh Swami's latex2png.el
11593 (defun org-create-formula-image (string tofile options buffer)
11594 (let* ((tmpdir (if (featurep 'xemacs)
11595 (temp-directory)
11596 temporary-file-directory))
11597 (texfilebase (make-temp-name
11598 (expand-file-name "orgtex" tmpdir)))
11599 (texfile (concat texfilebase ".tex"))
11600 (dvifile (concat texfilebase ".dvi"))
11601 (pngfile (concat texfilebase ".png"))
11602 (fnh (if (featurep 'xemacs)
11603 (font-height (get-face-font 'default))
11604 (face-attribute 'default :height nil)))
11605 (scale (or (plist-get options (if buffer :scale :html-scale)) 1.0))
11606 (dpi (number-to-string (* scale (floor (* 0.9 (if buffer fnh 140.))))))
11607 (fg (or (plist-get options (if buffer :foreground :html-foreground))
11608 "Black"))
11609 (bg (or (plist-get options (if buffer :background :html-background))
11610 "Transparent")))
11611 (if (eq fg 'default) (setq fg (org-dvipng-color :foreground)))
11612 (if (eq bg 'default) (setq bg (org-dvipng-color :background)))
11613 (with-temp-file texfile
11614 (insert org-format-latex-header
11615 "\n\\begin{document}\n" string "\n\\end{document}\n"))
11616 (let ((dir default-directory))
11617 (condition-case nil
11618 (progn
11619 (cd tmpdir)
11620 (call-process "latex" nil nil nil texfile))
11621 (error nil))
11622 (cd dir))
11623 (if (not (file-exists-p dvifile))
11624 (progn (message "Failed to create dvi file from %s" texfile) nil)
11625 (call-process "dvipng" nil nil nil
11626 "-E" "-fg" fg "-bg" bg
11627 "-D" dpi
11628 ;;"-x" scale "-y" scale
11629 "-T" "tight"
11630 "-o" pngfile
11631 dvifile)
11632 (if (not (file-exists-p pngfile))
11633 (progn (message "Failed to create png file from %s" texfile) nil)
11634 ;; Use the requested file name and clean up
11635 (copy-file pngfile tofile 'replace)
11636 (loop for e in '(".dvi" ".tex" ".aux" ".log" ".png") do
11637 (delete-file (concat texfilebase e)))
11638 pngfile))))
11640 (defun org-dvipng-color (attr)
11641 "Return an rgb color specification for dvipng."
11642 (apply 'format "rgb %s %s %s"
11643 (mapcar 'org-normalize-color
11644 (color-values (face-attribute 'default attr nil)))))
11646 (defun org-normalize-color (value)
11647 "Return string to be used as color value for an RGB component."
11648 (format "%g" (/ value 65535.0)))
11651 ;;;; Key bindings
11653 ;; Make `C-c C-x' a prefix key
11654 (org-defkey org-mode-map "\C-c\C-x" (make-sparse-keymap))
11656 ;; TAB key with modifiers
11657 (org-defkey org-mode-map "\C-i" 'org-cycle)
11658 (org-defkey org-mode-map [(tab)] 'org-cycle)
11659 (org-defkey org-mode-map [(control tab)] 'org-force-cycle-archived)
11660 (org-defkey org-mode-map [(meta tab)] 'org-complete)
11661 (org-defkey org-mode-map "\M-\t" 'org-complete)
11662 (org-defkey org-mode-map "\M-\C-i" 'org-complete)
11663 ;; The following line is necessary under Suse GNU/Linux
11664 (unless (featurep 'xemacs)
11665 (org-defkey org-mode-map [S-iso-lefttab] 'org-shifttab))
11666 (org-defkey org-mode-map [(shift tab)] 'org-shifttab)
11667 (define-key org-mode-map [backtab] 'org-shifttab)
11669 (org-defkey org-mode-map [(shift return)] 'org-table-copy-down)
11670 (org-defkey org-mode-map [(meta shift return)] 'org-insert-todo-heading)
11671 (org-defkey org-mode-map [(meta return)] 'org-meta-return)
11673 ;; Cursor keys with modifiers
11674 (org-defkey org-mode-map [(meta left)] 'org-metaleft)
11675 (org-defkey org-mode-map [(meta right)] 'org-metaright)
11676 (org-defkey org-mode-map [(meta up)] 'org-metaup)
11677 (org-defkey org-mode-map [(meta down)] 'org-metadown)
11679 (org-defkey org-mode-map [(meta shift left)] 'org-shiftmetaleft)
11680 (org-defkey org-mode-map [(meta shift right)] 'org-shiftmetaright)
11681 (org-defkey org-mode-map [(meta shift up)] 'org-shiftmetaup)
11682 (org-defkey org-mode-map [(meta shift down)] 'org-shiftmetadown)
11684 (org-defkey org-mode-map [(shift up)] 'org-shiftup)
11685 (org-defkey org-mode-map [(shift down)] 'org-shiftdown)
11686 (org-defkey org-mode-map [(shift left)] 'org-shiftleft)
11687 (org-defkey org-mode-map [(shift right)] 'org-shiftright)
11689 (org-defkey org-mode-map [(control shift right)] 'org-shiftcontrolright)
11690 (org-defkey org-mode-map [(control shift left)] 'org-shiftcontrolleft)
11692 ;;; Extra keys for tty access.
11693 ;; We only set them when really needed because otherwise the
11694 ;; menus don't show the simple keys
11696 (when (or (featurep 'xemacs) ;; because XEmacs supports multi-device stuff
11697 (not window-system))
11698 (org-defkey org-mode-map "\C-c\C-xc" 'org-table-copy-down)
11699 (org-defkey org-mode-map "\C-c\C-xM" 'org-insert-todo-heading)
11700 (org-defkey org-mode-map "\C-c\C-xm" 'org-meta-return)
11701 (org-defkey org-mode-map [?\e (return)] 'org-meta-return)
11702 (org-defkey org-mode-map [?\e (left)] 'org-metaleft)
11703 (org-defkey org-mode-map "\C-c\C-xl" 'org-metaleft)
11704 (org-defkey org-mode-map [?\e (right)] 'org-metaright)
11705 (org-defkey org-mode-map "\C-c\C-xr" 'org-metaright)
11706 (org-defkey org-mode-map [?\e (up)] 'org-metaup)
11707 (org-defkey org-mode-map "\C-c\C-xu" 'org-metaup)
11708 (org-defkey org-mode-map [?\e (down)] 'org-metadown)
11709 (org-defkey org-mode-map "\C-c\C-xd" 'org-metadown)
11710 (org-defkey org-mode-map "\C-c\C-xL" 'org-shiftmetaleft)
11711 (org-defkey org-mode-map "\C-c\C-xR" 'org-shiftmetaright)
11712 (org-defkey org-mode-map "\C-c\C-xU" 'org-shiftmetaup)
11713 (org-defkey org-mode-map "\C-c\C-xD" 'org-shiftmetadown)
11714 (org-defkey org-mode-map [?\C-c (up)] 'org-shiftup)
11715 (org-defkey org-mode-map [?\C-c (down)] 'org-shiftdown)
11716 (org-defkey org-mode-map [?\C-c (left)] 'org-shiftleft)
11717 (org-defkey org-mode-map [?\C-c (right)] 'org-shiftright)
11718 (org-defkey org-mode-map [?\C-c ?\C-x (right)] 'org-shiftcontrolright)
11719 (org-defkey org-mode-map [?\C-c ?\C-x (left)] 'org-shiftcontrolleft))
11721 ;; All the other keys
11723 (org-defkey org-mode-map "\C-c\C-a" 'show-all) ; in case allout messed up.
11724 (org-defkey org-mode-map "\C-c\C-r" 'org-reveal)
11725 (org-defkey org-mode-map "\C-xns" 'org-narrow-to-subtree)
11726 (org-defkey org-mode-map "\C-c$" 'org-archive-subtree)
11727 (org-defkey org-mode-map "\C-c\C-x\C-s" 'org-advertized-archive-subtree)
11728 (org-defkey org-mode-map "\C-c\C-x\C-a" 'org-toggle-archive-tag)
11729 (org-defkey org-mode-map "\C-c\C-xa" 'org-toggle-archive-tag)
11730 (org-defkey org-mode-map "\C-c\C-xA" 'org-archive-to-archive-sibling)
11731 (org-defkey org-mode-map "\C-c\C-xb" 'org-tree-to-indirect-buffer)
11732 (org-defkey org-mode-map "\C-c\C-j" 'org-goto)
11733 (org-defkey org-mode-map "\C-c\C-t" 'org-todo)
11734 (org-defkey org-mode-map "\C-c\C-s" 'org-schedule)
11735 (org-defkey org-mode-map "\C-c\C-d" 'org-deadline)
11736 (org-defkey org-mode-map "\C-c;" 'org-toggle-comment)
11737 (org-defkey org-mode-map "\C-c\C-v" 'org-show-todo-tree)
11738 (org-defkey org-mode-map "\C-c\C-w" 'org-refile)
11739 (org-defkey org-mode-map "\C-c/" 'org-sparse-tree) ; Minor-mode reserved
11740 (org-defkey org-mode-map "\C-c\\" 'org-tags-sparse-tree) ; Minor-mode res.
11741 (org-defkey org-mode-map "\C-c\C-m" 'org-ctrl-c-ret)
11742 (org-defkey org-mode-map "\M-\C-m" 'org-insert-heading)
11743 (org-defkey org-mode-map [(control return)] 'org-insert-heading-after-current)
11744 (org-defkey org-mode-map "\C-c\C-x\C-n" 'org-next-link)
11745 (org-defkey org-mode-map "\C-c\C-x\C-p" 'org-previous-link)
11746 (org-defkey org-mode-map "\C-c\C-l" 'org-insert-link)
11747 (org-defkey org-mode-map "\C-c\C-o" 'org-open-at-point)
11748 (org-defkey org-mode-map "\C-c%" 'org-mark-ring-push)
11749 (org-defkey org-mode-map "\C-c&" 'org-mark-ring-goto)
11750 (org-defkey org-mode-map "\C-c\C-z" 'org-add-note) ; Alternative binding
11751 (org-defkey org-mode-map "\C-c." 'org-time-stamp) ; Minor-mode reserved
11752 (org-defkey org-mode-map "\C-c!" 'org-time-stamp-inactive) ; Minor-mode r.
11753 (org-defkey org-mode-map "\C-c," 'org-priority) ; Minor-mode reserved
11754 (org-defkey org-mode-map "\C-c\C-y" 'org-evaluate-time-range)
11755 (org-defkey org-mode-map "\C-c>" 'org-goto-calendar)
11756 (org-defkey org-mode-map "\C-c<" 'org-date-from-calendar)
11757 (org-defkey org-mode-map [(control ?,)] 'org-cycle-agenda-files)
11758 (org-defkey org-mode-map [(control ?\')] 'org-cycle-agenda-files)
11759 (org-defkey org-mode-map "\C-c[" 'org-agenda-file-to-front)
11760 (org-defkey org-mode-map "\C-c]" 'org-remove-file)
11761 (org-defkey org-mode-map "\C-c\C-x<" 'org-agenda-set-restriction-lock)
11762 (org-defkey org-mode-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
11763 (org-defkey org-mode-map "\C-c-" 'org-ctrl-c-minus)
11764 (org-defkey org-mode-map "\C-c*" 'org-ctrl-c-star)
11765 (org-defkey org-mode-map "\C-c^" 'org-sort)
11766 (org-defkey org-mode-map "\C-c\C-c" 'org-ctrl-c-ctrl-c)
11767 (org-defkey org-mode-map "\C-c\C-k" 'org-kill-note-or-show-branches)
11768 (org-defkey org-mode-map "\C-c#" 'org-update-checkbox-count)
11769 (org-defkey org-mode-map "\C-m" 'org-return)
11770 (org-defkey org-mode-map "\C-j" 'org-return-indent)
11771 (org-defkey org-mode-map "\C-c?" 'org-table-field-info)
11772 (org-defkey org-mode-map "\C-c " 'org-table-blank-field)
11773 (org-defkey org-mode-map "\C-c+" 'org-table-sum)
11774 (org-defkey org-mode-map "\C-c=" 'org-table-eval-formula)
11775 (org-defkey org-mode-map "\C-c'" 'org-table-edit-formulas)
11776 (org-defkey org-mode-map "\C-c`" 'org-table-edit-field)
11777 (org-defkey org-mode-map "\C-c|" 'org-table-create-or-convert-from-region)
11778 (org-defkey org-mode-map [(control ?#)] 'org-table-rotate-recalc-marks)
11779 (org-defkey org-mode-map "\C-c~" 'org-table-create-with-table.el)
11780 (org-defkey org-mode-map "\C-c\C-q" 'org-table-wrap-region)
11781 (org-defkey org-mode-map "\C-c}" 'org-table-toggle-coordinate-overlays)
11782 (org-defkey org-mode-map "\C-c{" 'org-table-toggle-formula-debugger)
11783 (org-defkey org-mode-map "\C-c\C-e" 'org-export)
11784 (org-defkey org-mode-map "\C-c:" 'org-toggle-fixed-width-section)
11785 (org-defkey org-mode-map "\C-c\C-x\C-f" 'org-emphasize)
11787 (org-defkey org-mode-map "\C-c\C-x\C-k" 'org-cut-special)
11788 (org-defkey org-mode-map "\C-c\C-x\C-w" 'org-cut-special)
11789 (org-defkey org-mode-map "\C-c\C-x\M-w" 'org-copy-special)
11790 (org-defkey org-mode-map "\C-c\C-x\C-y" 'org-paste-special)
11792 (org-defkey org-mode-map "\C-c\C-x\C-t" 'org-toggle-time-stamp-overlays)
11793 (org-defkey org-mode-map "\C-c\C-x\C-i" 'org-clock-in)
11794 (org-defkey org-mode-map "\C-c\C-x\C-o" 'org-clock-out)
11795 (org-defkey org-mode-map "\C-c\C-x\C-j" 'org-clock-goto)
11796 (org-defkey org-mode-map "\C-c\C-x\C-x" 'org-clock-cancel)
11797 (org-defkey org-mode-map "\C-c\C-x\C-d" 'org-clock-display)
11798 (org-defkey org-mode-map "\C-c\C-x\C-r" 'org-clock-report)
11799 (org-defkey org-mode-map "\C-c\C-x\C-u" 'org-dblock-update)
11800 (org-defkey org-mode-map "\C-c\C-x\C-l" 'org-preview-latex-fragment)
11801 (org-defkey org-mode-map "\C-c\C-x\C-b" 'org-toggle-checkbox)
11802 (org-defkey org-mode-map "\C-c\C-xp" 'org-set-property)
11803 (org-defkey org-mode-map "\C-c\C-xr" 'org-insert-columns-dblock)
11805 (define-key org-mode-map "\C-c\C-x\C-c" 'org-columns)
11807 (when (featurep 'xemacs)
11808 (org-defkey org-mode-map 'button3 'popup-mode-menu))
11810 (defvar org-table-auto-blank-field) ; defined in org-table.el
11811 (defun org-self-insert-command (N)
11812 "Like `self-insert-command', use overwrite-mode for whitespace in tables.
11813 If the cursor is in a table looking at whitespace, the whitespace is
11814 overwritten, and the table is not marked as requiring realignment."
11815 (interactive "p")
11816 (if (and (org-table-p)
11817 (progn
11818 ;; check if we blank the field, and if that triggers align
11819 (and (featurep 'org-table) org-table-auto-blank-field
11820 (member last-command
11821 '(org-cycle org-return org-shifttab org-ctrl-c-ctrl-c))
11822 (if (or (equal (char-after) ?\ ) (looking-at "[^|\n]* |"))
11823 ;; got extra space, this field does not determine column width
11824 (let (org-table-may-need-update) (org-table-blank-field))
11825 ;; no extra space, this field may determine column width
11826 (org-table-blank-field)))
11828 (eq N 1)
11829 (looking-at "[^|\n]* |"))
11830 (let (org-table-may-need-update)
11831 (goto-char (1- (match-end 0)))
11832 (delete-backward-char 1)
11833 (goto-char (match-beginning 0))
11834 (self-insert-command N))
11835 (setq org-table-may-need-update t)
11836 (self-insert-command N)
11837 (org-fix-tags-on-the-fly)))
11839 (defun org-fix-tags-on-the-fly ()
11840 (when (and (equal (char-after (point-at-bol)) ?*)
11841 (org-on-heading-p))
11842 (org-align-tags-here org-tags-column)))
11844 (defun org-delete-backward-char (N)
11845 "Like `delete-backward-char', insert whitespace at field end in tables.
11846 When deleting backwards, in tables this function will insert whitespace in
11847 front of the next \"|\" separator, to keep the table aligned. The table will
11848 still be marked for re-alignment if the field did fill the entire column,
11849 because, in this case the deletion might narrow the column."
11850 (interactive "p")
11851 (if (and (org-table-p)
11852 (eq N 1)
11853 (string-match "|" (buffer-substring (point-at-bol) (point)))
11854 (looking-at ".*?|"))
11855 (let ((pos (point))
11856 (noalign (looking-at "[^|\n\r]* |"))
11857 (c org-table-may-need-update))
11858 (backward-delete-char N)
11859 (skip-chars-forward "^|")
11860 (insert " ")
11861 (goto-char (1- pos))
11862 ;; noalign: if there were two spaces at the end, this field
11863 ;; does not determine the width of the column.
11864 (if noalign (setq org-table-may-need-update c)))
11865 (backward-delete-char N)
11866 (org-fix-tags-on-the-fly)))
11868 (defun org-delete-char (N)
11869 "Like `delete-char', but insert whitespace at field end in tables.
11870 When deleting characters, in tables this function will insert whitespace in
11871 front of the next \"|\" separator, to keep the table aligned. The table will
11872 still be marked for re-alignment if the field did fill the entire column,
11873 because, in this case the deletion might narrow the column."
11874 (interactive "p")
11875 (if (and (org-table-p)
11876 (not (bolp))
11877 (not (= (char-after) ?|))
11878 (eq N 1))
11879 (if (looking-at ".*?|")
11880 (let ((pos (point))
11881 (noalign (looking-at "[^|\n\r]* |"))
11882 (c org-table-may-need-update))
11883 (replace-match (concat
11884 (substring (match-string 0) 1 -1)
11885 " |"))
11886 (goto-char pos)
11887 ;; noalign: if there were two spaces at the end, this field
11888 ;; does not determine the width of the column.
11889 (if noalign (setq org-table-may-need-update c)))
11890 (delete-char N))
11891 (delete-char N)
11892 (org-fix-tags-on-the-fly)))
11894 ;; Make `delete-selection-mode' work with org-mode and orgtbl-mode
11895 (put 'org-self-insert-command 'delete-selection t)
11896 (put 'orgtbl-self-insert-command 'delete-selection t)
11897 (put 'org-delete-char 'delete-selection 'supersede)
11898 (put 'org-delete-backward-char 'delete-selection 'supersede)
11900 ;; Make `flyspell-mode' delay after some commands
11901 (put 'org-self-insert-command 'flyspell-delayed t)
11902 (put 'orgtbl-self-insert-command 'flyspell-delayed t)
11903 (put 'org-delete-char 'flyspell-delayed t)
11904 (put 'org-delete-backward-char 'flyspell-delayed t)
11906 ;; Make pabbrev-mode expand after org-mode commands
11907 (put 'org-self-insert-command 'pabbrev-expand-after-command t)
11908 (put 'orgybl-self-insert-command 'pabbrev-expand-after-command t)
11910 ;; How to do this: Measure non-white length of current string
11911 ;; If equal to column width, we should realign.
11913 (defun org-remap (map &rest commands)
11914 "In MAP, remap the functions given in COMMANDS.
11915 COMMANDS is a list of alternating OLDDEF NEWDEF command names."
11916 (let (new old)
11917 (while commands
11918 (setq old (pop commands) new (pop commands))
11919 (if (fboundp 'command-remapping)
11920 (org-defkey map (vector 'remap old) new)
11921 (substitute-key-definition old new map global-map)))))
11923 (when (eq org-enable-table-editor 'optimized)
11924 ;; If the user wants maximum table support, we need to hijack
11925 ;; some standard editing functions
11926 (org-remap org-mode-map
11927 'self-insert-command 'org-self-insert-command
11928 'delete-char 'org-delete-char
11929 'delete-backward-char 'org-delete-backward-char)
11930 (org-defkey org-mode-map "|" 'org-force-self-insert))
11932 (defun org-shiftcursor-error ()
11933 "Throw an error because Shift-Cursor command was applied in wrong context."
11934 (error "This command is active in special context like tables, headlines or timestamps"))
11936 (defun org-shifttab (&optional arg)
11937 "Global visibility cycling or move to previous table field.
11938 Calls `org-cycle' with argument t, or `org-table-previous-field', depending
11939 on context.
11940 See the individual commands for more information."
11941 (interactive "P")
11942 (cond
11943 ((org-at-table-p) (call-interactively 'org-table-previous-field))
11944 (arg (message "Content view to level: ")
11945 (org-content (prefix-numeric-value arg))
11946 (setq org-cycle-global-status 'overview))
11947 (t (call-interactively 'org-global-cycle))))
11949 (defun org-shiftmetaleft ()
11950 "Promote subtree or delete table column.
11951 Calls `org-promote-subtree', `org-outdent-item',
11952 or `org-table-delete-column', depending on context.
11953 See the individual commands for more information."
11954 (interactive)
11955 (cond
11956 ((org-at-table-p) (call-interactively 'org-table-delete-column))
11957 ((org-on-heading-p) (call-interactively 'org-promote-subtree))
11958 ((org-at-item-p) (call-interactively 'org-outdent-item))
11959 (t (org-shiftcursor-error))))
11961 (defun org-shiftmetaright ()
11962 "Demote subtree or insert table column.
11963 Calls `org-demote-subtree', `org-indent-item',
11964 or `org-table-insert-column', depending on context.
11965 See the individual commands for more information."
11966 (interactive)
11967 (cond
11968 ((org-at-table-p) (call-interactively 'org-table-insert-column))
11969 ((org-on-heading-p) (call-interactively 'org-demote-subtree))
11970 ((org-at-item-p) (call-interactively 'org-indent-item))
11971 (t (org-shiftcursor-error))))
11973 (defun org-shiftmetaup (&optional arg)
11974 "Move subtree up or kill table row.
11975 Calls `org-move-subtree-up' or `org-table-kill-row' or
11976 `org-move-item-up' depending on context. See the individual commands
11977 for more information."
11978 (interactive "P")
11979 (cond
11980 ((org-at-table-p) (call-interactively 'org-table-kill-row))
11981 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
11982 ((org-at-item-p) (call-interactively 'org-move-item-up))
11983 (t (org-shiftcursor-error))))
11984 (defun org-shiftmetadown (&optional arg)
11985 "Move subtree down or insert table row.
11986 Calls `org-move-subtree-down' or `org-table-insert-row' or
11987 `org-move-item-down', depending on context. See the individual
11988 commands for more information."
11989 (interactive "P")
11990 (cond
11991 ((org-at-table-p) (call-interactively 'org-table-insert-row))
11992 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
11993 ((org-at-item-p) (call-interactively 'org-move-item-down))
11994 (t (org-shiftcursor-error))))
11996 (defun org-metaleft (&optional arg)
11997 "Promote heading or move table column to left.
11998 Calls `org-do-promote' or `org-table-move-column', depending on context.
11999 With no specific context, calls the Emacs default `backward-word'.
12000 See the individual commands for more information."
12001 (interactive "P")
12002 (cond
12003 ((org-at-table-p) (org-call-with-arg 'org-table-move-column 'left))
12004 ((or (org-on-heading-p) (org-region-active-p))
12005 (call-interactively 'org-do-promote))
12006 ((org-at-item-p) (call-interactively 'org-outdent-item))
12007 (t (call-interactively 'backward-word))))
12009 (defun org-metaright (&optional arg)
12010 "Demote subtree or move table column to right.
12011 Calls `org-do-demote' or `org-table-move-column', depending on context.
12012 With no specific context, calls the Emacs default `forward-word'.
12013 See the individual commands for more information."
12014 (interactive "P")
12015 (cond
12016 ((org-at-table-p) (call-interactively 'org-table-move-column))
12017 ((or (org-on-heading-p) (org-region-active-p))
12018 (call-interactively 'org-do-demote))
12019 ((org-at-item-p) (call-interactively 'org-indent-item))
12020 (t (call-interactively 'forward-word))))
12022 (defun org-metaup (&optional arg)
12023 "Move subtree up or move table row up.
12024 Calls `org-move-subtree-up' or `org-table-move-row' or
12025 `org-move-item-up', depending on context. See the individual commands
12026 for more information."
12027 (interactive "P")
12028 (cond
12029 ((org-at-table-p) (org-call-with-arg 'org-table-move-row 'up))
12030 ((org-on-heading-p) (call-interactively 'org-move-subtree-up))
12031 ((org-at-item-p) (call-interactively 'org-move-item-up))
12032 (t (transpose-lines 1) (beginning-of-line -1))))
12034 (defun org-metadown (&optional arg)
12035 "Move subtree down or move table row down.
12036 Calls `org-move-subtree-down' or `org-table-move-row' or
12037 `org-move-item-down', depending on context. See the individual
12038 commands for more information."
12039 (interactive "P")
12040 (cond
12041 ((org-at-table-p) (call-interactively 'org-table-move-row))
12042 ((org-on-heading-p) (call-interactively 'org-move-subtree-down))
12043 ((org-at-item-p) (call-interactively 'org-move-item-down))
12044 (t (beginning-of-line 2) (transpose-lines 1) (beginning-of-line 0))))
12046 (defun org-shiftup (&optional arg)
12047 "Increase item in timestamp or increase priority of current headline.
12048 Calls `org-timestamp-up' or `org-priority-up', or `org-previous-item',
12049 depending on context. See the individual commands for more information."
12050 (interactive "P")
12051 (cond
12052 ((org-at-timestamp-p t)
12053 (call-interactively (if org-edit-timestamp-down-means-later
12054 'org-timestamp-down 'org-timestamp-up)))
12055 ((org-on-heading-p) (call-interactively 'org-priority-up))
12056 ((org-at-item-p) (call-interactively 'org-previous-item))
12057 ((org-clocktable-try-shift 'up arg))
12058 (t (call-interactively 'org-beginning-of-item) (beginning-of-line 1))))
12060 (defun org-shiftdown (&optional arg)
12061 "Decrease item in timestamp or decrease priority of current headline.
12062 Calls `org-timestamp-down' or `org-priority-down', or `org-next-item'
12063 depending on context. See the individual commands for more information."
12064 (interactive "P")
12065 (cond
12066 ((org-at-timestamp-p t)
12067 (call-interactively (if org-edit-timestamp-down-means-later
12068 'org-timestamp-up 'org-timestamp-down)))
12069 ((org-on-heading-p) (call-interactively 'org-priority-down))
12070 ((org-clocktable-try-shift 'down arg))
12071 (t (call-interactively 'org-next-item))))
12073 (defun org-shiftright (&optional arg)
12074 "Next TODO keyword or timestamp one day later, depending on context."
12075 (interactive "P")
12076 (cond
12077 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-up-day))
12078 ((org-on-heading-p) (org-call-with-arg 'org-todo 'right))
12079 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet nil))
12080 ((org-at-property-p) (call-interactively 'org-property-next-allowed-value))
12081 ((org-clocktable-try-shift 'right arg))
12082 (t (org-shiftcursor-error))))
12084 (defun org-shiftleft (&optional arg)
12085 "Previous TODO keyword or timestamp one day earlier, depending on context."
12086 (interactive "P")
12087 (cond
12088 ((org-at-timestamp-p t) (call-interactively 'org-timestamp-down-day))
12089 ((org-on-heading-p) (org-call-with-arg 'org-todo 'left))
12090 ((org-at-item-p) (org-call-with-arg 'org-cycle-list-bullet 'previous))
12091 ((org-at-property-p)
12092 (call-interactively 'org-property-previous-allowed-value))
12093 ((org-clocktable-try-shift 'left arg))
12094 (t (org-shiftcursor-error))))
12096 (defun org-shiftcontrolright ()
12097 "Switch to next TODO set."
12098 (interactive)
12099 (cond
12100 ((org-on-heading-p) (org-call-with-arg 'org-todo 'nextset))
12101 (t (org-shiftcursor-error))))
12103 (defun org-shiftcontrolleft ()
12104 "Switch to previous TODO set."
12105 (interactive)
12106 (cond
12107 ((org-on-heading-p) (org-call-with-arg 'org-todo 'previousset))
12108 (t (org-shiftcursor-error))))
12110 (defun org-ctrl-c-ret ()
12111 "Call `org-table-hline-and-move' or `org-insert-heading' dep. on context."
12112 (interactive)
12113 (cond
12114 ((org-at-table-p) (call-interactively 'org-table-hline-and-move))
12115 (t (call-interactively 'org-insert-heading))))
12117 (defun org-copy-special ()
12118 "Copy region in table or copy current subtree.
12119 Calls `org-table-copy' or `org-copy-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-copy-region 'org-copy-subtree)))
12125 (defun org-cut-special ()
12126 "Cut region in table or cut current subtree.
12127 Calls `org-table-copy' or `org-cut-subtree', depending on context.
12128 See the individual commands for more information."
12129 (interactive)
12130 (call-interactively
12131 (if (org-at-table-p) 'org-table-cut-region 'org-cut-subtree)))
12133 (defun org-paste-special (arg)
12134 "Paste rectangular region into table, or past subtree relative to level.
12135 Calls `org-table-paste-rectangle' or `org-paste-subtree', depending on context.
12136 See the individual commands for more information."
12137 (interactive "P")
12138 (if (org-at-table-p)
12139 (org-table-paste-rectangle)
12140 (org-paste-subtree arg)))
12142 (defun org-ctrl-c-ctrl-c (&optional arg)
12143 "Set tags in headline, or update according to changed information at point.
12145 This command does many different things, depending on context:
12147 - If the cursor is in a headline, prompt for tags and insert them
12148 into the current line, aligned to `org-tags-column'. When called
12149 with prefix arg, realign all tags in the current buffer.
12151 - If the cursor is in one of the special #+KEYWORD lines, this
12152 triggers scanning the buffer for these lines and updating the
12153 information.
12155 - If the cursor is inside a table, realign the table. This command
12156 works even if the automatic table editor has been turned off.
12158 - If the cursor is on a #+TBLFM line, re-apply the formulas to
12159 the entire table.
12161 - If the cursor is a the beginning of a dynamic block, update it.
12163 - If the cursor is inside a table created by the table.el package,
12164 activate that table.
12166 - If the current buffer is a remember buffer, close note and file it.
12167 with a prefix argument, file it without further interaction to the default
12168 location.
12170 - If the cursor is on a <<<target>>>, update radio targets and corresponding
12171 links in this buffer.
12173 - If the cursor is on a numbered item in a plain list, renumber the
12174 ordered list.
12176 - If the cursor is on a checkbox, toggle it."
12177 (interactive "P")
12178 (let ((org-enable-table-editor t))
12179 (cond
12180 ((or (and (boundp 'org-clock-overlays) org-clock-overlays)
12181 org-occur-highlights
12182 org-latex-fragment-image-overlays)
12183 (and (boundp 'org-clock-overlays) (org-remove-clock-overlays))
12184 (org-remove-occur-highlights)
12185 (org-remove-latex-fragment-image-overlays)
12186 (message "Temporary highlights/overlays removed from current buffer"))
12187 ((and (local-variable-p 'org-finish-function (current-buffer))
12188 (fboundp org-finish-function))
12189 (funcall org-finish-function))
12190 ((org-at-property-p)
12191 (call-interactively 'org-property-action))
12192 ((org-on-target-p) (call-interactively 'org-update-radio-target-regexp))
12193 ((org-on-heading-p) (call-interactively 'org-set-tags))
12194 ((org-at-table.el-p)
12195 (require 'table)
12196 (beginning-of-line 1)
12197 (re-search-forward "|" (save-excursion (end-of-line 2) (point)))
12198 (call-interactively 'table-recognize-table))
12199 ((org-at-table-p)
12200 (org-table-maybe-eval-formula)
12201 (if arg
12202 (call-interactively 'org-table-recalculate)
12203 (org-table-maybe-recalculate-line))
12204 (call-interactively 'org-table-align))
12205 ((org-at-item-checkbox-p)
12206 (call-interactively 'org-toggle-checkbox))
12207 ((org-at-item-p)
12208 (call-interactively 'org-maybe-renumber-ordered-list))
12209 ((save-excursion (beginning-of-line 1) (looking-at "#\\+BEGIN:"))
12210 ;; Dynamic block
12211 (beginning-of-line 1)
12212 (org-update-dblock))
12213 ((save-excursion (beginning-of-line 1) (looking-at "#\\+\\([A-Z]+\\)"))
12214 (cond
12215 ((equal (match-string 1) "TBLFM")
12216 ;; Recalculate the table before this line
12217 (save-excursion
12218 (beginning-of-line 1)
12219 (skip-chars-backward " \r\n\t")
12220 (if (org-at-table-p)
12221 (org-call-with-arg 'org-table-recalculate t))))
12223 (call-interactively 'org-mode-restart))))
12224 (t (error "C-c C-c can do nothing useful at this location.")))))
12226 (defun org-mode-restart ()
12227 "Restart Org-mode, to scan again for special lines.
12228 Also updates the keyword regular expressions."
12229 (interactive)
12230 (let ((org-inhibit-startup t)) (org-mode))
12231 (message "Org-mode restarted to refresh keyword and special line setup"))
12233 (defun org-kill-note-or-show-branches ()
12234 "If this is a Note buffer, abort storing the note. Else call `show-branches'."
12235 (interactive)
12236 (if (not org-finish-function)
12237 (call-interactively 'show-branches)
12238 (let ((org-note-abort t))
12239 (funcall org-finish-function))))
12241 (defun org-return (&optional indent)
12242 "Goto next table row or insert a newline.
12243 Calls `org-table-next-row' or `newline', depending on context.
12244 See the individual commands for more information."
12245 (interactive)
12246 (cond
12247 ((bobp) (if indent (newline-and-indent) (newline)))
12248 ((and (org-at-heading-p)
12249 (looking-at
12250 (org-re "\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$")))
12251 (org-show-entry)
12252 (end-of-line 1)
12253 (newline))
12254 ((org-at-table-p)
12255 (org-table-justify-field-maybe)
12256 (call-interactively 'org-table-next-row))
12257 (t (if indent (newline-and-indent) (newline)))))
12259 (defun org-return-indent ()
12260 "Goto next table row or insert a newline and indent.
12261 Calls `org-table-next-row' or `newline-and-indent', depending on
12262 context. See the individual commands for more information."
12263 (interactive)
12264 (org-return t))
12266 (defun org-ctrl-c-star ()
12267 "Compute table, or change heading status of lines.
12268 Calls `org-table-recalculate' or `org-toggle-region-headlines',
12269 depending on context. This will also turn a plain list item or a normal
12270 line into a subheading."
12271 (interactive)
12272 (cond
12273 ((org-at-table-p)
12274 (call-interactively 'org-table-recalculate))
12275 ((org-region-active-p)
12276 ;; Convert all lines in region to list items
12277 (call-interactively 'org-toggle-region-headings))
12278 ((org-on-heading-p)
12279 (org-toggle-region-headings (point-at-bol)
12280 (min (1+ (point-at-eol)) (point-max))))
12281 ((org-at-item-p)
12282 ;; Convert to heading
12283 (let ((level (save-match-data
12284 (save-excursion
12285 (condition-case nil
12286 (progn
12287 (org-back-to-heading t)
12288 (funcall outline-level))
12289 (error 0))))))
12290 (replace-match
12291 (concat (make-string (org-get-valid-level level 1) ?*) " ") t t)))
12292 (t (org-toggle-region-headings (point-at-bol)
12293 (min (1+ (point-at-eol)) (point-max))))))
12295 (defun org-ctrl-c-minus ()
12296 "Insert separator line in table or modify bullet status of line.
12297 Also turns a plain line or a region of lines into list items.
12298 Calls `org-table-insert-hline', `org-toggle-region-items', or
12299 `org-cycle-list-bullet', depending on context."
12300 (interactive)
12301 (cond
12302 ((org-at-table-p)
12303 (call-interactively 'org-table-insert-hline))
12304 ((org-on-heading-p)
12305 ;; Convert to item
12306 (save-excursion
12307 (beginning-of-line 1)
12308 (if (looking-at "\\*+ ")
12309 (replace-match (concat (make-string (- (match-end 0) (point) 1) ?\ ) "- ")))))
12310 ((org-region-active-p)
12311 ;; Convert all lines in region to list items
12312 (call-interactively 'org-toggle-region-items))
12313 ((org-in-item-p)
12314 (call-interactively 'org-cycle-list-bullet))
12315 (t (org-toggle-region-items (point-at-bol)
12316 (min (1+ (point-at-eol)) (point-max))))))
12318 (defun org-toggle-region-items (beg end)
12319 "Convert all lines in region to list items.
12320 If the first line is already an item, convert all list items in the region
12321 to normal lines."
12322 (interactive "r")
12323 (let (l2 l)
12324 (save-excursion
12325 (goto-char end)
12326 (setq l2 (org-current-line))
12327 (goto-char beg)
12328 (beginning-of-line 1)
12329 (setq l (1- (org-current-line)))
12330 (if (org-at-item-p)
12331 ;; We already have items, de-itemize
12332 (while (< (setq l (1+ l)) l2)
12333 (when (org-at-item-p)
12334 (goto-char (match-beginning 2))
12335 (delete-region (match-beginning 2) (match-end 2))
12336 (and (looking-at "[ \t]+") (replace-match "")))
12337 (beginning-of-line 2))
12338 (while (< (setq l (1+ l)) l2)
12339 (unless (org-at-item-p)
12340 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12341 (replace-match "\\1- \\2")))
12342 (beginning-of-line 2))))))
12344 (defun org-toggle-region-headings (beg end)
12345 "Convert all lines in region to list items.
12346 If the first line is already an item, convert all list items in the region
12347 to normal lines."
12348 (interactive "r")
12349 (let (l2 l)
12350 (save-excursion
12351 (goto-char end)
12352 (setq l2 (org-current-line))
12353 (goto-char beg)
12354 (beginning-of-line 1)
12355 (setq l (1- (org-current-line)))
12356 (if (org-on-heading-p)
12357 ;; We already have headlines, de-star them
12358 (while (< (setq l (1+ l)) l2)
12359 (when (org-on-heading-p t)
12360 (and (looking-at outline-regexp) (replace-match "")))
12361 (beginning-of-line 2))
12362 (let* ((stars (save-excursion
12363 (re-search-backward org-complex-heading-regexp nil t)
12364 (or (match-string 1) "*")))
12365 (add-stars (if org-odd-levels-only "**" "*"))
12366 (rpl (concat stars add-stars " \\2")))
12367 (while (< (setq l (1+ l)) l2)
12368 (unless (org-on-heading-p)
12369 (if (looking-at "\\([ \t]*\\)\\(\\S-\\)")
12370 (replace-match rpl)))
12371 (beginning-of-line 2)))))))
12373 (defun org-meta-return (&optional arg)
12374 "Insert a new heading or wrap a region in a table.
12375 Calls `org-insert-heading' or `org-table-wrap-region', depending on context.
12376 See the individual commands for more information."
12377 (interactive "P")
12378 (cond
12379 ((org-at-table-p)
12380 (call-interactively 'org-table-wrap-region))
12381 (t (call-interactively 'org-insert-heading))))
12383 ;;; Menu entries
12385 ;; Define the Org-mode menus
12386 (easy-menu-define org-tbl-menu org-mode-map "Tbl menu"
12387 '("Tbl"
12388 ["Align" org-ctrl-c-ctrl-c :active (org-at-table-p)]
12389 ["Next Field" org-cycle (org-at-table-p)]
12390 ["Previous Field" org-shifttab (org-at-table-p)]
12391 ["Next Row" org-return (org-at-table-p)]
12392 "--"
12393 ["Blank Field" org-table-blank-field (org-at-table-p)]
12394 ["Edit Field" org-table-edit-field (org-at-table-p)]
12395 ["Copy Field from Above" org-table-copy-down (org-at-table-p)]
12396 "--"
12397 ("Column"
12398 ["Move Column Left" org-metaleft (org-at-table-p)]
12399 ["Move Column Right" org-metaright (org-at-table-p)]
12400 ["Delete Column" org-shiftmetaleft (org-at-table-p)]
12401 ["Insert Column" org-shiftmetaright (org-at-table-p)])
12402 ("Row"
12403 ["Move Row Up" org-metaup (org-at-table-p)]
12404 ["Move Row Down" org-metadown (org-at-table-p)]
12405 ["Delete Row" org-shiftmetaup (org-at-table-p)]
12406 ["Insert Row" org-shiftmetadown (org-at-table-p)]
12407 ["Sort lines in region" org-table-sort-lines (org-at-table-p)]
12408 "--"
12409 ["Insert Hline" org-ctrl-c-minus (org-at-table-p)])
12410 ("Rectangle"
12411 ["Copy Rectangle" org-copy-special (org-at-table-p)]
12412 ["Cut Rectangle" org-cut-special (org-at-table-p)]
12413 ["Paste Rectangle" org-paste-special (org-at-table-p)]
12414 ["Fill Rectangle" org-table-wrap-region (org-at-table-p)])
12415 "--"
12416 ("Calculate"
12417 ["Set Column Formula" org-table-eval-formula (org-at-table-p)]
12418 ["Set Field Formula" (org-table-eval-formula '(4)) :active (org-at-table-p) :keys "C-u C-c ="]
12419 ["Edit Formulas" org-table-edit-formulas (org-at-table-p)]
12420 "--"
12421 ["Recalculate line" org-table-recalculate (org-at-table-p)]
12422 ["Recalculate all" (lambda () (interactive) (org-table-recalculate '(4))) :active (org-at-table-p) :keys "C-u C-c *"]
12423 ["Iterate all" (lambda () (interactive) (org-table-recalculate '(16))) :active (org-at-table-p) :keys "C-u C-u C-c *"]
12424 "--"
12425 ["Toggle Recalculate Mark" org-table-rotate-recalc-marks (org-at-table-p)]
12426 "--"
12427 ["Sum Column/Rectangle" org-table-sum
12428 (or (org-at-table-p) (org-region-active-p))]
12429 ["Which Column?" org-table-current-column (org-at-table-p)])
12430 ["Debug Formulas"
12431 org-table-toggle-formula-debugger
12432 :style toggle :selected (org-bound-and-true-p org-table-formula-debug)]
12433 ["Show Col/Row Numbers"
12434 org-table-toggle-coordinate-overlays
12435 :style toggle
12436 :selected (org-bound-and-true-p org-table-overlay-coordinates)]
12437 "--"
12438 ["Create" org-table-create (and (not (org-at-table-p))
12439 org-enable-table-editor)]
12440 ["Convert Region" org-table-convert-region (not (org-at-table-p 'any))]
12441 ["Import from File" org-table-import (not (org-at-table-p))]
12442 ["Export to File" org-table-export (org-at-table-p)]
12443 "--"
12444 ["Create/Convert from/to table.el" org-table-create-with-table.el t]))
12446 (easy-menu-define org-org-menu org-mode-map "Org menu"
12447 '("Org"
12448 ("Show/Hide"
12449 ["Cycle Visibility" org-cycle :active (or (bobp) (outline-on-heading-p))]
12450 ["Cycle Global Visibility" org-shifttab :active (not (org-at-table-p))]
12451 ["Sparse Tree..." org-sparse-tree t]
12452 ["Reveal Context" org-reveal t]
12453 ["Show All" show-all t]
12454 "--"
12455 ["Subtree to indirect buffer" org-tree-to-indirect-buffer t])
12456 "--"
12457 ["New Heading" org-insert-heading t]
12458 ("Navigate Headings"
12459 ["Up" outline-up-heading t]
12460 ["Next" outline-next-visible-heading t]
12461 ["Previous" outline-previous-visible-heading t]
12462 ["Next Same Level" outline-forward-same-level t]
12463 ["Previous Same Level" outline-backward-same-level t]
12464 "--"
12465 ["Jump" org-goto t])
12466 ("Edit Structure"
12467 ["Move Subtree Up" org-shiftmetaup (not (org-at-table-p))]
12468 ["Move Subtree Down" org-shiftmetadown (not (org-at-table-p))]
12469 "--"
12470 ["Copy Subtree" org-copy-special (not (org-at-table-p))]
12471 ["Cut Subtree" org-cut-special (not (org-at-table-p))]
12472 ["Paste Subtree" org-paste-special (not (org-at-table-p))]
12473 "--"
12474 ["Promote Heading" org-metaleft (not (org-at-table-p))]
12475 ["Promote Subtree" org-shiftmetaleft (not (org-at-table-p))]
12476 ["Demote Heading" org-metaright (not (org-at-table-p))]
12477 ["Demote Subtree" org-shiftmetaright (not (org-at-table-p))]
12478 "--"
12479 ["Sort Region/Children" org-sort (not (org-at-table-p))]
12480 "--"
12481 ["Convert to odd levels" org-convert-to-odd-levels t]
12482 ["Convert to odd/even levels" org-convert-to-oddeven-levels t])
12483 ("Editing"
12484 ["Emphasis..." org-emphasize t])
12485 ("Archive"
12486 ["Toggle ARCHIVE tag" org-toggle-archive-tag t]
12487 ; ["Check and Tag Children" (org-toggle-archive-tag (4))
12488 ; :active t :keys "C-u C-c C-x C-a"]
12489 ["Sparse trees open ARCHIVE trees"
12490 (setq org-sparse-tree-open-archived-trees
12491 (not org-sparse-tree-open-archived-trees))
12492 :style toggle :selected org-sparse-tree-open-archived-trees]
12493 ["Cycling opens ARCHIVE trees"
12494 (setq org-cycle-open-archived-trees (not org-cycle-open-archived-trees))
12495 :style toggle :selected org-cycle-open-archived-trees]
12496 ["Agenda includes ARCHIVE trees"
12497 (setq org-agenda-skip-archived-trees (not org-agenda-skip-archived-trees))
12498 :style toggle :selected (not org-agenda-skip-archived-trees)]
12499 "--"
12500 ["Move Subtree to Archive" org-advertized-archive-subtree t]
12501 ; ["Check and Move Children" (org-archive-subtree '(4))
12502 ; :active t :keys "C-u C-c C-x C-s"]
12504 "--"
12505 ("TODO Lists"
12506 ["TODO/DONE/-" org-todo t]
12507 ("Select keyword"
12508 ["Next keyword" org-shiftright (org-on-heading-p)]
12509 ["Previous keyword" org-shiftleft (org-on-heading-p)]
12510 ["Complete Keyword" org-complete (assq :todo-keyword (org-context))]
12511 ["Next keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))]
12512 ["Previous keyword set" org-shiftcontrolright (and (> (length org-todo-sets) 1) (org-on-heading-p))])
12513 ["Show TODO Tree" org-show-todo-tree t]
12514 ["Global TODO list" org-todo-list t]
12515 "--"
12516 ["Set Priority" org-priority t]
12517 ["Priority Up" org-shiftup t]
12518 ["Priority Down" org-shiftdown t])
12519 ("TAGS and Properties"
12520 ["Set Tags" 'org-ctrl-c-ctrl-c (org-at-heading-p)]
12521 ["Change tag in region" 'org-change-tag-in-region (org-region-active-p)]
12522 "--"
12523 ["Set property" 'org-set-property t]
12524 ["Column view of properties" org-columns t]
12525 ["Insert Column View DBlock" org-insert-columns-dblock t])
12526 ("Dates and Scheduling"
12527 ["Timestamp" org-time-stamp t]
12528 ["Timestamp (inactive)" org-time-stamp-inactive t]
12529 ("Change Date"
12530 ["1 Day Later" org-shiftright t]
12531 ["1 Day Earlier" org-shiftleft t]
12532 ["1 ... Later" org-shiftup t]
12533 ["1 ... Earlier" org-shiftdown t])
12534 ["Compute Time Range" org-evaluate-time-range t]
12535 ["Schedule Item" org-schedule t]
12536 ["Deadline" org-deadline t]
12537 "--"
12538 ["Custom time format" org-toggle-time-stamp-overlays
12539 :style radio :selected org-display-custom-times]
12540 "--"
12541 ["Goto Calendar" org-goto-calendar t]
12542 ["Date from Calendar" org-date-from-calendar t])
12543 ("Logging work"
12544 ["Clock in" org-clock-in t]
12545 ["Clock out" org-clock-out t]
12546 ["Clock cancel" org-clock-cancel t]
12547 ["Goto running clock" org-clock-goto t]
12548 ["Display times" org-clock-display t]
12549 ["Create clock table" org-clock-report t]
12550 "--"
12551 ["Record DONE time"
12552 (progn (setq org-log-done (not org-log-done))
12553 (message "Switching to %s will %s record a timestamp"
12554 (car org-done-keywords)
12555 (if org-log-done "automatically" "not")))
12556 :style toggle :selected org-log-done])
12557 "--"
12558 ["Agenda Command..." org-agenda t]
12559 ["Set Restriction Lock" org-agenda-set-restriction-lock t]
12560 ("File List for Agenda")
12561 ("Special views current file"
12562 ["TODO Tree" org-show-todo-tree t]
12563 ["Check Deadlines" org-check-deadlines t]
12564 ["Timeline" org-timeline t]
12565 ["Tags Tree" org-tags-sparse-tree t])
12566 "--"
12567 ("Hyperlinks"
12568 ["Store Link (Global)" org-store-link t]
12569 ["Insert Link" org-insert-link t]
12570 ["Follow Link" org-open-at-point t]
12571 "--"
12572 ["Next link" org-next-link t]
12573 ["Previous link" org-previous-link t]
12574 "--"
12575 ["Descriptive Links"
12576 (progn (org-add-to-invisibility-spec '(org-link)) (org-restart-font-lock))
12577 :style radio
12578 :selected (member '(org-link) buffer-invisibility-spec)]
12579 ["Literal Links"
12580 (progn
12581 (org-remove-from-invisibility-spec '(org-link)) (org-restart-font-lock))
12582 :style radio
12583 :selected (not (member '(org-link) buffer-invisibility-spec))])
12584 "--"
12585 ["Export/Publish..." org-export t]
12586 ("LaTeX"
12587 ["Org CDLaTeX mode" org-cdlatex-mode :style toggle
12588 :selected org-cdlatex-mode]
12589 ["Insert Environment" cdlatex-environment (fboundp 'cdlatex-environment)]
12590 ["Insert math symbol" cdlatex-math-symbol (fboundp 'cdlatex-math-symbol)]
12591 ["Modify math symbol" org-cdlatex-math-modify
12592 (org-inside-LaTeX-fragment-p)]
12593 ["Export LaTeX fragments as images"
12594 (if (featurep 'org-exp)
12595 (setq org-export-with-LaTeX-fragments
12596 (not org-export-with-LaTeX-fragments))
12597 (require 'org-exp))
12598 :style toggle :selected (and (boundp 'org-export-with-LaTeX-fragments)
12599 org-export-with-LaTeX-fragments)])
12600 "--"
12601 ("Documentation"
12602 ["Show Version" org-version t]
12603 ["Info Documentation" org-info t])
12604 ("Customize"
12605 ["Browse Org Group" org-customize t]
12606 "--"
12607 ["Expand This Menu" org-create-customize-menu
12608 (fboundp 'customize-menu-create)])
12609 "--"
12610 ["Refresh setup" org-mode-restart t]
12613 (defun org-info (&optional node)
12614 "Read documentation for Org-mode in the info system.
12615 With optional NODE, go directly to that node."
12616 (interactive)
12617 (info (format "(org)%s" (or node ""))))
12619 (defun org-install-agenda-files-menu ()
12620 (let ((bl (buffer-list)))
12621 (save-excursion
12622 (while bl
12623 (set-buffer (pop bl))
12624 (if (org-mode-p) (setq bl nil)))
12625 (when (org-mode-p)
12626 (easy-menu-change
12627 '("Org") "File List for Agenda"
12628 (append
12629 (list
12630 ["Edit File List" (org-edit-agenda-file-list) t]
12631 ["Add/Move Current File to Front of List" org-agenda-file-to-front t]
12632 ["Remove Current File from List" org-remove-file t]
12633 ["Cycle through agenda files" org-cycle-agenda-files t]
12634 ["Occur in all agenda files" org-occur-in-agenda-files t]
12635 "--")
12636 (mapcar 'org-file-menu-entry (org-agenda-files t))))))))
12638 ;;;; Documentation
12640 (defun org-require-autoloaded-modules ()
12641 (interactive)
12642 (mapc 'require
12643 '(org-agenda org-archive org-clock org-colview
12644 org-exp org-export-latex org-publish
12645 org-remember org-table)))
12647 (defun org-customize ()
12648 "Call the customize function with org as argument."
12649 (interactive)
12650 (org-load-modules-maybe)
12651 (org-require-autoloaded-modules)
12652 (customize-browse 'org))
12654 (defun org-create-customize-menu ()
12655 "Create a full customization menu for Org-mode, insert it into the menu."
12656 (interactive)
12657 (org-load-modules-maybe)
12658 (org-require-autoloaded-modules)
12659 (if (fboundp 'customize-menu-create)
12660 (progn
12661 (easy-menu-change
12662 '("Org") "Customize"
12663 `(["Browse Org group" org-customize t]
12664 "--"
12665 ,(customize-menu-create 'org)
12666 ["Set" Custom-set t]
12667 ["Save" Custom-save t]
12668 ["Reset to Current" Custom-reset-current t]
12669 ["Reset to Saved" Custom-reset-saved t]
12670 ["Reset to Standard Settings" Custom-reset-standard t]))
12671 (message "\"Org\"-menu now contains full customization menu"))
12672 (error "Cannot expand menu (outdated version of cus-edit.el)")))
12674 ;;;; Miscellaneous stuff
12676 ;;; Generally useful functions
12678 (defun org-plist-delete (plist property)
12679 "Delete PROPERTY from PLIST.
12680 This is in contrast to merely setting it to 0."
12681 (let (p)
12682 (while plist
12683 (if (not (eq property (car plist)))
12684 (setq p (plist-put p (car plist) (nth 1 plist))))
12685 (setq plist (cddr plist)))
12688 (defun org-force-self-insert (N)
12689 "Needed to enforce self-insert under remapping."
12690 (interactive "p")
12691 (self-insert-command N))
12693 (defun org-string-width (s)
12694 "Compute width of string, ignoring invisible characters.
12695 This ignores character with invisibility property `org-link', and also
12696 characters with property `org-cwidth', because these will become invisible
12697 upon the next fontification round."
12698 (let (b l)
12699 (when (or (eq t buffer-invisibility-spec)
12700 (assq 'org-link buffer-invisibility-spec))
12701 (while (setq b (text-property-any 0 (length s)
12702 'invisible 'org-link s))
12703 (setq s (concat (substring s 0 b)
12704 (substring s (or (next-single-property-change
12705 b 'invisible s) (length s)))))))
12706 (while (setq b (text-property-any 0 (length s) 'org-cwidth t s))
12707 (setq s (concat (substring s 0 b)
12708 (substring s (or (next-single-property-change
12709 b 'org-cwidth s) (length s))))))
12710 (setq l (string-width s) b -1)
12711 (while (setq b (text-property-any (1+ b) (length s) 'org-dwidth t s))
12712 (setq l (- l (get-text-property b 'org-dwidth-n s))))
12716 (defun org-trim (s)
12717 "Remove whitespace at beginning and end of string."
12718 (if (string-match "\\`[ \t\n\r]+" s) (setq s (replace-match "" t t s)))
12719 (if (string-match "[ \t\n\r]+\\'" s) (setq s (replace-match "" t t s)))
12722 (defun org-wrap (string &optional width lines)
12723 "Wrap string to either a number of lines, or a width in characters.
12724 If WIDTH is non-nil, the string is wrapped to that width, however many lines
12725 that costs. If there is a word longer than WIDTH, the text is actually
12726 wrapped to the length of that word.
12727 IF WIDTH is nil and LINES is non-nil, the string is forced into at most that
12728 many lines, whatever width that takes.
12729 The return value is a list of lines, without newlines at the end."
12730 (let* ((words (org-split-string string "[ \t\n]+"))
12731 (maxword (apply 'max (mapcar 'org-string-width words)))
12732 w ll)
12733 (cond (width
12734 (org-do-wrap words (max maxword width)))
12735 (lines
12736 (setq w maxword)
12737 (setq ll (org-do-wrap words maxword))
12738 (if (<= (length ll) lines)
12740 (setq ll words)
12741 (while (> (length ll) lines)
12742 (setq w (1+ w))
12743 (setq ll (org-do-wrap words w)))
12744 ll))
12745 (t (error "Cannot wrap this")))))
12747 (defun org-do-wrap (words width)
12748 "Create lines of maximum width WIDTH (in characters) from word list WORDS."
12749 (let (lines line)
12750 (while words
12751 (setq line (pop words))
12752 (while (and words (< (+ (length line) (length (car words))) width))
12753 (setq line (concat line " " (pop words))))
12754 (setq lines (push line lines)))
12755 (nreverse lines)))
12757 (defun org-split-string (string &optional separators)
12758 "Splits STRING into substrings at SEPARATORS.
12759 No empty strings are returned if there are matches at the beginning
12760 and end of string."
12761 (let ((rexp (or separators "[ \f\t\n\r\v]+"))
12762 (start 0)
12763 notfirst
12764 (list nil))
12765 (while (and (string-match rexp string
12766 (if (and notfirst
12767 (= start (match-beginning 0))
12768 (< start (length string)))
12769 (1+ start) start))
12770 (< (match-beginning 0) (length string)))
12771 (setq notfirst t)
12772 (or (eq (match-beginning 0) 0)
12773 (and (eq (match-beginning 0) (match-end 0))
12774 (eq (match-beginning 0) start))
12775 (setq list
12776 (cons (substring string start (match-beginning 0))
12777 list)))
12778 (setq start (match-end 0)))
12779 (or (eq start (length string))
12780 (setq list
12781 (cons (substring string start)
12782 list)))
12783 (nreverse list)))
12785 (defun org-context ()
12786 "Return a list of contexts of the current cursor position.
12787 If several contexts apply, all are returned.
12788 Each context entry is a list with a symbol naming the context, and
12789 two positions indicating start and end of the context. Possible
12790 contexts are:
12792 :headline anywhere in a headline
12793 :headline-stars on the leading stars in a headline
12794 :todo-keyword on a TODO keyword (including DONE) in a headline
12795 :tags on the TAGS in a headline
12796 :priority on the priority cookie in a headline
12797 :item on the first line of a plain list item
12798 :item-bullet on the bullet/number of a plain list item
12799 :checkbox on the checkbox in a plain list item
12800 :table in an org-mode table
12801 :table-special on a special filed in a table
12802 :table-table in a table.el table
12803 :link on a hyperlink
12804 :keyword on a keyword: SCHEDULED, DEADLINE, CLOSE,COMMENT, QUOTE.
12805 :target on a <<target>>
12806 :radio-target on a <<<radio-target>>>
12807 :latex-fragment on a LaTeX fragment
12808 :latex-preview on a LaTeX fragment with overlayed preview image
12810 This function expects the position to be visible because it uses font-lock
12811 faces as a help to recognize the following contexts: :table-special, :link,
12812 and :keyword."
12813 (let* ((f (get-text-property (point) 'face))
12814 (faces (if (listp f) f (list f)))
12815 (p (point)) clist o)
12816 ;; First the large context
12817 (cond
12818 ((org-on-heading-p t)
12819 (push (list :headline (point-at-bol) (point-at-eol)) clist)
12820 (when (progn
12821 (beginning-of-line 1)
12822 (looking-at org-todo-line-tags-regexp))
12823 (push (org-point-in-group p 1 :headline-stars) clist)
12824 (push (org-point-in-group p 2 :todo-keyword) clist)
12825 (push (org-point-in-group p 4 :tags) clist))
12826 (goto-char p)
12827 (skip-chars-backward "^[\n\r \t") (or (eobp) (backward-char 1))
12828 (if (looking-at "\\[#[A-Z0-9]\\]")
12829 (push (org-point-in-group p 0 :priority) clist)))
12831 ((org-at-item-p)
12832 (push (org-point-in-group p 2 :item-bullet) clist)
12833 (push (list :item (point-at-bol)
12834 (save-excursion (org-end-of-item) (point)))
12835 clist)
12836 (and (org-at-item-checkbox-p)
12837 (push (org-point-in-group p 0 :checkbox) clist)))
12839 ((org-at-table-p)
12840 (push (list :table (org-table-begin) (org-table-end)) clist)
12841 (if (memq 'org-formula faces)
12842 (push (list :table-special
12843 (previous-single-property-change p 'face)
12844 (next-single-property-change p 'face)) clist)))
12845 ((org-at-table-p 'any)
12846 (push (list :table-table) clist)))
12847 (goto-char p)
12849 ;; Now the small context
12850 (cond
12851 ((org-at-timestamp-p)
12852 (push (org-point-in-group p 0 :timestamp) clist))
12853 ((memq 'org-link faces)
12854 (push (list :link
12855 (previous-single-property-change p 'face)
12856 (next-single-property-change p 'face)) clist))
12857 ((memq 'org-special-keyword faces)
12858 (push (list :keyword
12859 (previous-single-property-change p 'face)
12860 (next-single-property-change p 'face)) clist))
12861 ((org-on-target-p)
12862 (push (org-point-in-group p 0 :target) clist)
12863 (goto-char (1- (match-beginning 0)))
12864 (if (looking-at org-radio-target-regexp)
12865 (push (org-point-in-group p 0 :radio-target) clist))
12866 (goto-char p))
12867 ((setq o (car (delq nil
12868 (mapcar
12869 (lambda (x)
12870 (if (memq x org-latex-fragment-image-overlays) x))
12871 (org-overlays-at (point))))))
12872 (push (list :latex-fragment
12873 (org-overlay-start o) (org-overlay-end o)) clist)
12874 (push (list :latex-preview
12875 (org-overlay-start o) (org-overlay-end o)) clist))
12876 ((org-inside-LaTeX-fragment-p)
12877 ;; FIXME: positions wrong.
12878 (push (list :latex-fragment (point) (point)) clist)))
12880 (setq clist (nreverse (delq nil clist)))
12881 clist))
12883 ;; FIXME: Compare with at-regexp-p Do we need both?
12884 (defun org-in-regexp (re &optional nlines visually)
12885 "Check if point is inside a match of regexp.
12886 Normally only the current line is checked, but you can include NLINES extra
12887 lines both before and after point into the search.
12888 If VISUALLY is set, require that the cursor is not after the match but
12889 really on, so that the block visually is on the match."
12890 (catch 'exit
12891 (let ((pos (point))
12892 (eol (point-at-eol (+ 1 (or nlines 0))))
12893 (inc (if visually 1 0)))
12894 (save-excursion
12895 (beginning-of-line (- 1 (or nlines 0)))
12896 (while (re-search-forward re eol t)
12897 (if (and (<= (match-beginning 0) pos)
12898 (>= (+ inc (match-end 0)) pos))
12899 (throw 'exit (cons (match-beginning 0) (match-end 0)))))))))
12901 (defun org-at-regexp-p (regexp)
12902 "Is point inside a match of REGEXP in the current line?"
12903 (catch 'exit
12904 (save-excursion
12905 (let ((pos (point)) (end (point-at-eol)))
12906 (beginning-of-line 1)
12907 (while (re-search-forward regexp end t)
12908 (if (and (<= (match-beginning 0) pos)
12909 (>= (match-end 0) pos))
12910 (throw 'exit t)))
12911 nil))))
12913 (defun org-occur-in-agenda-files (regexp &optional nlines)
12914 "Call `multi-occur' with buffers for all agenda files."
12915 (interactive "sOrg-files matching: \np")
12916 (let* ((files (org-agenda-files))
12917 (tnames (mapcar 'file-truename files))
12918 (extra org-agenda-text-search-extra-files)
12920 (when (eq (car extra) 'agenda-archives)
12921 (setq extra (cdr extra))
12922 (setq files (org-add-archive-files files)))
12923 (while (setq f (pop extra))
12924 (unless (member (file-truename f) tnames)
12925 (add-to-list 'files f 'append)
12926 (add-to-list 'tnames (file-truename f) 'append)))
12927 (multi-occur
12928 (mapcar (lambda (x) (or (get-file-buffer x) (find-file-noselect x))) files)
12929 regexp)))
12931 (if (boundp 'occur-mode-find-occurrence-hook)
12932 ;; Emacs 23
12933 (add-hook 'occur-mode-find-occurrence-hook
12934 (lambda ()
12935 (when (org-mode-p)
12936 (org-reveal))))
12937 ;; Emacs 22
12938 (defadvice occur-mode-goto-occurrence
12939 (after org-occur-reveal activate)
12940 (and (org-mode-p) (org-reveal)))
12941 (defadvice occur-mode-goto-occurrence-other-window
12942 (after org-occur-reveal activate)
12943 (and (org-mode-p) (org-reveal)))
12944 (defadvice occur-mode-display-occurrence
12945 (after org-occur-reveal activate)
12946 (when (org-mode-p)
12947 (let ((pos (occur-mode-find-occurrence)))
12948 (with-current-buffer (marker-buffer pos)
12949 (save-excursion
12950 (goto-char pos)
12951 (org-reveal)))))))
12953 (defun org-uniquify (list)
12954 "Remove duplicate elements from LIST."
12955 (let (res)
12956 (mapc (lambda (x) (add-to-list 'res x 'append)) list)
12957 res))
12959 (defun org-delete-all (elts list)
12960 "Remove all elements in ELTS from LIST."
12961 (while elts
12962 (setq list (delete (pop elts) list)))
12963 list)
12965 (defun org-back-over-empty-lines ()
12966 "Move backwards over witespace, to the beginning of the first empty line.
12967 Returns the number of empty lines passed."
12968 (let ((pos (point)))
12969 (skip-chars-backward " \t\n\r")
12970 (beginning-of-line 2)
12971 (goto-char (min (point) pos))
12972 (count-lines (point) pos)))
12974 (defun org-skip-whitespace ()
12975 (skip-chars-forward " \t\n\r"))
12977 (defun org-point-in-group (point group &optional context)
12978 "Check if POINT is in match-group GROUP.
12979 If CONTEXT is non-nil, return a list with CONTEXT and the boundaries of the
12980 match. If the match group does ot exist or point is not inside it,
12981 return nil."
12982 (and (match-beginning group)
12983 (>= point (match-beginning group))
12984 (<= point (match-end group))
12985 (if context
12986 (list context (match-beginning group) (match-end group))
12987 t)))
12989 (defun org-switch-to-buffer-other-window (&rest args)
12990 "Switch to buffer in a second window on the current frame.
12991 In particular, do not allow pop-up frames."
12992 (let (pop-up-frames special-display-buffer-names special-display-regexps
12993 special-display-function)
12994 (apply 'switch-to-buffer-other-window args)))
12996 (defun org-combine-plists (&rest plists)
12997 "Create a single property list from all plists in PLISTS.
12998 The process starts by copying the first list, and then setting properties
12999 from the other lists. Settings in the last list are the most significant
13000 ones and overrule settings in the other lists."
13001 (let ((rtn (copy-sequence (pop plists)))
13002 p v ls)
13003 (while plists
13004 (setq ls (pop plists))
13005 (while ls
13006 (setq p (pop ls) v (pop ls))
13007 (setq rtn (plist-put rtn p v))))
13008 rtn))
13010 (defun org-move-line-down (arg)
13011 "Move the current line down. With prefix argument, move it past ARG lines."
13012 (interactive "p")
13013 (let ((col (current-column))
13014 beg end pos)
13015 (beginning-of-line 1) (setq beg (point))
13016 (beginning-of-line 2) (setq end (point))
13017 (beginning-of-line (+ 1 arg))
13018 (setq pos (move-marker (make-marker) (point)))
13019 (insert (delete-and-extract-region beg end))
13020 (goto-char pos)
13021 (org-move-to-column col)))
13023 (defun org-move-line-up (arg)
13024 "Move the current line up. With prefix argument, move it past ARG lines."
13025 (interactive "p")
13026 (let ((col (current-column))
13027 beg end pos)
13028 (beginning-of-line 1) (setq beg (point))
13029 (beginning-of-line 2) (setq end (point))
13030 (beginning-of-line (- arg))
13031 (setq pos (move-marker (make-marker) (point)))
13032 (insert (delete-and-extract-region beg end))
13033 (goto-char pos)
13034 (org-move-to-column col)))
13036 (defun org-replace-escapes (string table)
13037 "Replace %-escapes in STRING with values in TABLE.
13038 TABLE is an association list with keys like \"%a\" and string values.
13039 The sequences in STRING may contain normal field width and padding information,
13040 for example \"%-5s\". Replacements happen in the sequence given by TABLE,
13041 so values can contain further %-escapes if they are define later in TABLE."
13042 (let ((case-fold-search nil)
13043 e re rpl)
13044 (while (setq e (pop table))
13045 (setq re (concat "%-?[0-9.]*" (substring (car e) 1)))
13046 (while (string-match re string)
13047 (setq rpl (format (concat (substring (match-string 0 string) 0 -1) "s")
13048 (cdr e)))
13049 (setq string (replace-match rpl t t string))))
13050 string))
13053 (defun org-sublist (list start end)
13054 "Return a section of LIST, from START to END.
13055 Counting starts at 1."
13056 (let (rtn (c start))
13057 (setq list (nthcdr (1- start) list))
13058 (while (and list (<= c end))
13059 (push (pop list) rtn)
13060 (setq c (1+ c)))
13061 (nreverse rtn)))
13063 (defun org-find-base-buffer-visiting (file)
13064 "Like `find-buffer-visiting' but alway return the base buffer and
13065 not an indirect buffer."
13066 (let ((buf (find-buffer-visiting file)))
13067 (if buf
13068 (or (buffer-base-buffer buf) buf)
13069 nil)))
13071 (defun org-image-file-name-regexp ()
13072 "Return regexp matching the file names of images."
13073 (if (fboundp 'image-file-name-regexp)
13074 (image-file-name-regexp)
13075 (let ((image-file-name-extensions
13076 '("png" "jpeg" "jpg" "gif" "tiff" "tif"
13077 "xbm" "xpm" "pbm" "pgm" "ppm")))
13078 (concat "\\."
13079 (regexp-opt (nconc (mapcar 'upcase
13080 image-file-name-extensions)
13081 image-file-name-extensions)
13083 "\\'"))))
13085 (defun org-file-image-p (file)
13086 "Return non-nil if FILE is an image."
13087 (save-match-data
13088 (string-match (org-image-file-name-regexp) file)))
13090 ;;; Paragraph filling stuff.
13091 ;; We want this to be just right, so use the full arsenal.
13093 (defun org-indent-line-function ()
13094 "Indent line like previous, but further if previous was headline or item."
13095 (interactive)
13096 (let* ((pos (point))
13097 (itemp (org-at-item-p))
13098 column bpos bcol tpos tcol bullet btype bullet-type)
13099 ;; Find the previous relevant line
13100 (beginning-of-line 1)
13101 (cond
13102 ((looking-at "#") (setq column 0))
13103 ((looking-at "\\*+ ") (setq column 0))
13105 (beginning-of-line 0)
13106 (while (and (not (bobp)) (looking-at "[ \t]*[\n:#|]"))
13107 (beginning-of-line 0))
13108 (cond
13109 ((looking-at "\\*+[ \t]+")
13110 (goto-char (match-end 0))
13111 (setq column (current-column)))
13112 ((org-in-item-p)
13113 (org-beginning-of-item)
13114 ; (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13115 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*\\(\\[[- X]\\][ \t]*\\)?")
13116 (setq bpos (match-beginning 1) tpos (match-end 0)
13117 bcol (progn (goto-char bpos) (current-column))
13118 tcol (progn (goto-char tpos) (current-column))
13119 bullet (match-string 1)
13120 bullet-type (if (string-match "[0-9]" bullet) "n" bullet))
13121 (if (not itemp)
13122 (setq column tcol)
13123 (goto-char pos)
13124 (beginning-of-line 1)
13125 (if (looking-at "\\S-")
13126 (progn
13127 (looking-at "[ \t]*\\(\\S-+\\)[ \t]*")
13128 (setq bullet (match-string 1)
13129 btype (if (string-match "[0-9]" bullet) "n" bullet))
13130 (setq column (if (equal btype bullet-type) bcol tcol)))
13131 (setq column (org-get-indentation)))))
13132 (t (setq column (org-get-indentation))))))
13133 (goto-char pos)
13134 (if (<= (current-column) (current-indentation))
13135 (org-indent-line-to column)
13136 (save-excursion (org-indent-line-to column)))
13137 (setq column (current-column))
13138 (beginning-of-line 1)
13139 (if (looking-at
13140 "\\([ \t]+\\)\\(:[-_0-9a-zA-Z]+:\\)[ \t]*\\(\\S-.*\\(\\S-\\|$\\)\\)")
13141 (replace-match (concat "\\1" (format org-property-format
13142 (match-string 2) (match-string 3)))
13143 t nil))
13144 (org-move-to-column column)))
13146 (defun org-set-autofill-regexps ()
13147 (interactive)
13148 ;; In the paragraph separator we include headlines, because filling
13149 ;; text in a line directly attached to a headline would otherwise
13150 ;; fill the headline as well.
13151 (org-set-local 'comment-start-skip "^#+[ \t]*")
13152 (org-set-local 'paragraph-separate "\f\\|\\*+ \\|[ ]*$\\|[ \t]*[:|]")
13153 ;; The paragraph starter includes hand-formatted lists.
13154 (org-set-local 'paragraph-start
13155 "\f\\|[ ]*$\\|\\*+ \\|\f\\|[ \t]*\\([-+*][ \t]+\\|[0-9]+[.)][ \t]+\\)\\|[ \t]*[:|]")
13156 ;; Inhibit auto-fill for headers, tables and fixed-width lines.
13157 ;; But only if the user has not turned off tables or fixed-width regions
13158 (org-set-local
13159 'auto-fill-inhibit-regexp
13160 (concat "\\*+ \\|#\\+"
13161 "\\|[ \t]*" org-keyword-time-regexp
13162 (if (or org-enable-table-editor org-enable-fixed-width-editor)
13163 (concat
13164 "\\|[ \t]*["
13165 (if org-enable-table-editor "|" "")
13166 (if org-enable-fixed-width-editor ":" "")
13167 "]"))))
13168 ;; We use our own fill-paragraph function, to make sure that tables
13169 ;; and fixed-width regions are not wrapped. That function will pass
13170 ;; through to `fill-paragraph' when appropriate.
13171 (org-set-local 'fill-paragraph-function 'org-fill-paragraph)
13172 ; Adaptive filling: To get full control, first make sure that
13173 ;; `adaptive-fill-regexp' never matches. Then install our own matcher.
13174 (org-set-local 'adaptive-fill-regexp "\000")
13175 (org-set-local 'adaptive-fill-function
13176 'org-adaptive-fill-function)
13177 (org-set-local
13178 'align-mode-rules-list
13179 '((org-in-buffer-settings
13180 (regexp . "^#\\+[A-Z_]+:\\(\\s-*\\)\\S-+")
13181 (modes . '(org-mode))))))
13183 (defun org-fill-paragraph (&optional justify)
13184 "Re-align a table, pass through to fill-paragraph if no table."
13185 (let ((table-p (org-at-table-p))
13186 (table.el-p (org-at-table.el-p)))
13187 (cond ((and (equal (char-after (point-at-bol)) ?*)
13188 (save-excursion (goto-char (point-at-bol))
13189 (looking-at outline-regexp)))
13190 t) ; skip headlines
13191 (table.el-p t) ; skip table.el tables
13192 (table-p (org-table-align) t) ; align org-mode tables
13193 (t nil)))) ; call paragraph-fill
13195 ;; For reference, this is the default value of adaptive-fill-regexp
13196 ;; "[ \t]*\\([-|#;>*]+[ \t]*\\|(?[0-9]+[.)][ \t]*\\)*"
13198 (defun org-adaptive-fill-function ()
13199 "Return a fill prefix for org-mode files.
13200 In particular, this makes sure hanging paragraphs for hand-formatted lists
13201 work correctly."
13202 (cond ((looking-at "#[ \t]+")
13203 (match-string 0))
13204 ((looking-at "[ \t]*\\([-*+] \\|[0-9]+[.)] \\)?")
13205 (save-excursion
13206 (goto-char (match-end 0))
13207 (make-string (current-column) ?\ )))
13208 (t nil)))
13210 ;;; Other stuff.
13212 (defun org-toggle-fixed-width-section (arg)
13213 "Toggle the fixed-width export.
13214 If there is no active region, the QUOTE keyword at the current headline is
13215 inserted or removed. When present, it causes the text between this headline
13216 and the next to be exported as fixed-width text, and unmodified.
13217 If there is an active region, this command adds or removes a colon as the
13218 first character of this line. If the first character of a line is a colon,
13219 this line is also exported in fixed-width font."
13220 (interactive "P")
13221 (let* ((cc 0)
13222 (regionp (org-region-active-p))
13223 (beg (if regionp (region-beginning) (point)))
13224 (end (if regionp (region-end)))
13225 (nlines (or arg (if (and beg end) (count-lines beg end) 1)))
13226 (case-fold-search nil)
13227 (re "[ \t]*\\(:\\)")
13228 off)
13229 (if regionp
13230 (save-excursion
13231 (goto-char beg)
13232 (setq cc (current-column))
13233 (beginning-of-line 1)
13234 (setq off (looking-at re))
13235 (while (> nlines 0)
13236 (setq nlines (1- nlines))
13237 (beginning-of-line 1)
13238 (cond
13239 (arg
13240 (org-move-to-column cc t)
13241 (insert ":\n")
13242 (forward-line -1))
13243 ((and off (looking-at re))
13244 (replace-match "" t t nil 1))
13245 ((not off) (org-move-to-column cc t) (insert ":")))
13246 (forward-line 1)))
13247 (save-excursion
13248 (org-back-to-heading)
13249 (if (looking-at (concat outline-regexp
13250 "\\( *\\<" org-quote-string "\\>[ \t]*\\)"))
13251 (replace-match "" t t nil 1)
13252 (if (looking-at outline-regexp)
13253 (progn
13254 (goto-char (match-end 0))
13255 (insert org-quote-string " "))))))))
13257 ;;;; Functions extending outline functionality
13259 (defun org-beginning-of-line (&optional arg)
13260 "Go to the beginning of the current line. If that is invisible, continue
13261 to a visible line beginning. This makes the function of C-a more intuitive.
13262 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13263 first attempt, and only move to after the tags when the cursor is already
13264 beyond the end of the headline."
13265 (interactive "P")
13266 (let ((pos (point)))
13267 (beginning-of-line 1)
13268 (if (bobp)
13270 (backward-char 1)
13271 (if (org-invisible-p)
13272 (while (and (not (bobp)) (org-invisible-p))
13273 (backward-char 1)
13274 (beginning-of-line 1))
13275 (forward-char 1)))
13276 (when org-special-ctrl-a/e
13277 (cond
13278 ((and (looking-at org-todo-line-regexp)
13279 (= (char-after (match-end 1)) ?\ ))
13280 (goto-char
13281 (if (eq org-special-ctrl-a/e t)
13282 (cond ((> pos (match-beginning 3)) (match-beginning 3))
13283 ((= pos (point)) (match-beginning 3))
13284 (t (point)))
13285 (cond ((> pos (point)) (point))
13286 ((not (eq last-command this-command)) (point))
13287 (t (match-beginning 3))))))
13288 ((org-at-item-p)
13289 (goto-char
13290 (if (eq org-special-ctrl-a/e t)
13291 (cond ((> pos (match-end 4)) (match-end 4))
13292 ((= pos (point)) (match-end 4))
13293 (t (point)))
13294 (cond ((> pos (point)) (point))
13295 ((not (eq last-command this-command)) (point))
13296 (t (match-end 4))))))))))
13298 (defun org-end-of-line (&optional arg)
13299 "Go to the end of the line.
13300 If this is a headline, and `org-special-ctrl-a/e' is set, ignore tags on the
13301 first attempt, and only move to after the tags when the cursor is already
13302 beyond the end of the headline."
13303 (interactive "P")
13304 (if (or (not org-special-ctrl-a/e)
13305 (not (org-on-heading-p)))
13306 (end-of-line arg)
13307 (let ((pos (point)))
13308 (beginning-of-line 1)
13309 (if (looking-at (org-re ".*?\\([ \t]*\\)\\(:[[:alnum:]_@:]+:\\)[ \t]*$"))
13310 (if (eq org-special-ctrl-a/e t)
13311 (if (or (< pos (match-beginning 1))
13312 (= pos (match-end 0)))
13313 (goto-char (match-beginning 1))
13314 (goto-char (match-end 0)))
13315 (if (or (< pos (match-end 0)) (not (eq this-command last-command)))
13316 (goto-char (match-end 0))
13317 (goto-char (match-beginning 1))))
13318 (end-of-line arg)))))
13320 (define-key org-mode-map "\C-a" 'org-beginning-of-line)
13321 (define-key org-mode-map "\C-e" 'org-end-of-line)
13323 (defun org-kill-line (&optional arg)
13324 "Kill line, to tags or end of line."
13325 (interactive "P")
13326 (cond
13327 ((or (not org-special-ctrl-k)
13328 (bolp)
13329 (not (org-on-heading-p)))
13330 (call-interactively 'kill-line))
13331 ((looking-at (org-re ".*?\\S-\\([ \t]+\\(:[[:alnum:]_@:]+:\\)\\)[ \t]*$"))
13332 (kill-region (point) (match-beginning 1))
13333 (org-set-tags nil t))
13334 (t (kill-region (point) (point-at-eol)))))
13336 (define-key org-mode-map "\C-k" 'org-kill-line)
13338 (defun org-invisible-p ()
13339 "Check if point is at a character currently not visible."
13340 ;; Early versions of noutline don't have `outline-invisible-p'.
13341 (if (fboundp 'outline-invisible-p)
13342 (outline-invisible-p)
13343 (get-char-property (point) 'invisible)))
13345 (defun org-invisible-p2 ()
13346 "Check if point is at a character currently not visible."
13347 (save-excursion
13348 (if (and (eolp) (not (bobp))) (backward-char 1))
13349 ;; Early versions of noutline don't have `outline-invisible-p'.
13350 (if (fboundp 'outline-invisible-p)
13351 (outline-invisible-p)
13352 (get-char-property (point) 'invisible))))
13354 (defalias 'org-back-to-heading 'outline-back-to-heading)
13355 (defalias 'org-on-heading-p 'outline-on-heading-p)
13356 (defalias 'org-at-heading-p 'outline-on-heading-p)
13357 (defun org-at-heading-or-item-p ()
13358 (or (org-on-heading-p) (org-at-item-p)))
13360 (defun org-on-target-p ()
13361 (or (org-in-regexp org-radio-target-regexp)
13362 (org-in-regexp org-target-regexp)))
13364 (defun org-up-heading-all (arg)
13365 "Move to the heading line of which the present line is a subheading.
13366 This function considers both visible and invisible heading lines.
13367 With argument, move up ARG levels."
13368 (if (fboundp 'outline-up-heading-all)
13369 (outline-up-heading-all arg) ; emacs 21 version of outline.el
13370 (outline-up-heading arg t))) ; emacs 22 version of outline.el
13372 (defun org-up-heading-safe ()
13373 "Move to the heading line of which the present line is a subheading.
13374 This version will not throw an error. It will return the level of the
13375 headline found, or nil if no higher level is found."
13376 (let ((pos (point)) start-level level
13377 (re (concat "^" outline-regexp)))
13378 (catch 'exit
13379 (outline-back-to-heading t)
13380 (setq start-level (funcall outline-level))
13381 (if (equal start-level 1) (throw 'exit nil))
13382 (while (re-search-backward re nil t)
13383 (setq level (funcall outline-level))
13384 (if (< level start-level) (throw 'exit level)))
13385 nil)))
13387 (defun org-first-sibling-p ()
13388 "Is this heading the first child of its parents?"
13389 (interactive)
13390 (let ((re (concat "^" outline-regexp))
13391 level l)
13392 (unless (org-at-heading-p t)
13393 (error "Not at a heading"))
13394 (setq level (funcall outline-level))
13395 (save-excursion
13396 (if (not (re-search-backward re nil t))
13398 (setq l (funcall outline-level))
13399 (< l level)))))
13401 (defun org-goto-sibling (&optional previous)
13402 "Goto the next sibling, even if it is invisible.
13403 When PREVIOUS is set, go to the previous sibling instead. Returns t
13404 when a sibling was found. When none is found, return nil and don't
13405 move point."
13406 (let ((fun (if previous 're-search-backward 're-search-forward))
13407 (pos (point))
13408 (re (concat "^" outline-regexp))
13409 level l)
13410 (when (condition-case nil (org-back-to-heading t) (error nil))
13411 (setq level (funcall outline-level))
13412 (catch 'exit
13413 (or previous (forward-char 1))
13414 (while (funcall fun re nil t)
13415 (setq l (funcall outline-level))
13416 (when (< l level) (goto-char pos) (throw 'exit nil))
13417 (when (= l level) (goto-char (match-beginning 0)) (throw 'exit t)))
13418 (goto-char pos)
13419 nil))))
13421 (defun org-show-siblings ()
13422 "Show all siblings of the current headline."
13423 (save-excursion
13424 (while (org-goto-sibling) (org-flag-heading nil)))
13425 (save-excursion
13426 (while (org-goto-sibling 'previous)
13427 (org-flag-heading nil))))
13429 (defun org-show-hidden-entry ()
13430 "Show an entry where even the heading is hidden."
13431 (save-excursion
13432 (org-show-entry)))
13434 (defun org-flag-heading (flag &optional entry)
13435 "Flag the current heading. FLAG non-nil means make invisible.
13436 When ENTRY is non-nil, show the entire entry."
13437 (save-excursion
13438 (org-back-to-heading t)
13439 ;; Check if we should show the entire entry
13440 (if entry
13441 (progn
13442 (org-show-entry)
13443 (save-excursion
13444 (and (outline-next-heading)
13445 (org-flag-heading nil))))
13446 (outline-flag-region (max (point-min) (1- (point)))
13447 (save-excursion (outline-end-of-heading) (point))
13448 flag))))
13450 (defun org-end-of-subtree (&optional invisible-OK to-heading)
13451 ;; This is an exact copy of the original function, but it uses
13452 ;; `org-back-to-heading', to make it work also in invisible
13453 ;; trees. And is uses an invisible-OK argument.
13454 ;; Under Emacs this is not needed, but the old outline.el needs this fix.
13455 (org-back-to-heading invisible-OK)
13456 (let ((first t)
13457 (level (funcall outline-level)))
13458 (while (and (not (eobp))
13459 (or first (> (funcall outline-level) level)))
13460 (setq first nil)
13461 (outline-next-heading))
13462 (unless to-heading
13463 (if (memq (preceding-char) '(?\n ?\^M))
13464 (progn
13465 ;; Go to end of line before heading
13466 (forward-char -1)
13467 (if (memq (preceding-char) '(?\n ?\^M))
13468 ;; leave blank line before heading
13469 (forward-char -1))))))
13470 (point))
13472 (defun org-show-subtree ()
13473 "Show everything after this heading at deeper levels."
13474 (outline-flag-region
13475 (point)
13476 (save-excursion
13477 (outline-end-of-subtree) (outline-next-heading) (point))
13478 nil))
13480 (defun org-show-entry ()
13481 "Show the body directly following this heading.
13482 Show the heading too, if it is currently invisible."
13483 (interactive)
13484 (save-excursion
13485 (condition-case nil
13486 (progn
13487 (org-back-to-heading t)
13488 (outline-flag-region
13489 (max (point-min) (1- (point)))
13490 (save-excursion
13491 (re-search-forward
13492 (concat "[\r\n]\\(" outline-regexp "\\)") nil 'move)
13493 (or (match-beginning 1) (point-max)))
13494 nil))
13495 (error nil))))
13497 (defun org-make-options-regexp (kwds)
13498 "Make a regular expression for keyword lines."
13499 (concat
13501 "#?[ \t]*\\+\\("
13502 (mapconcat 'regexp-quote kwds "\\|")
13503 "\\):[ \t]*"
13504 "\\(.+\\)"))
13506 ;; Make isearch reveal the necessary context
13507 (defun org-isearch-end ()
13508 "Reveal context after isearch exits."
13509 (when isearch-success ; only if search was successful
13510 (if (featurep 'xemacs)
13511 ;; Under XEmacs, the hook is run in the correct place,
13512 ;; we directly show the context.
13513 (org-show-context 'isearch)
13514 ;; In Emacs the hook runs *before* restoring the overlays.
13515 ;; So we have to use a one-time post-command-hook to do this.
13516 ;; (Emacs 22 has a special variable, see function `org-mode')
13517 (unless (and (boundp 'isearch-mode-end-hook-quit)
13518 isearch-mode-end-hook-quit)
13519 ;; Only when the isearch was not quitted.
13520 (org-add-hook 'post-command-hook 'org-isearch-post-command
13521 'append 'local)))))
13523 (defun org-isearch-post-command ()
13524 "Remove self from hook, and show context."
13525 (remove-hook 'post-command-hook 'org-isearch-post-command 'local)
13526 (org-show-context 'isearch))
13529 ;;;; Integration with and fixes for other packages
13531 ;;; Imenu support
13533 (defvar org-imenu-markers nil
13534 "All markers currently used by Imenu.")
13535 (make-variable-buffer-local 'org-imenu-markers)
13537 (defun org-imenu-new-marker (&optional pos)
13538 "Return a new marker for use by Imenu, and remember the marker."
13539 (let ((m (make-marker)))
13540 (move-marker m (or pos (point)))
13541 (push m org-imenu-markers)
13544 (defun org-imenu-get-tree ()
13545 "Produce the index for Imenu."
13546 (mapc (lambda (x) (move-marker x nil)) org-imenu-markers)
13547 (setq org-imenu-markers nil)
13548 (let* ((n org-imenu-depth)
13549 (re (concat "^" outline-regexp))
13550 (subs (make-vector (1+ n) nil))
13551 (last-level 0)
13552 m tree level head)
13553 (save-excursion
13554 (save-restriction
13555 (widen)
13556 (goto-char (point-max))
13557 (while (re-search-backward re nil t)
13558 (setq level (org-reduced-level (funcall outline-level)))
13559 (when (<= level n)
13560 (looking-at org-complex-heading-regexp)
13561 (setq head (org-match-string-no-properties 4)
13562 m (org-imenu-new-marker))
13563 (org-add-props head nil 'org-imenu-marker m 'org-imenu t)
13564 (if (>= level last-level)
13565 (push (cons head m) (aref subs level))
13566 (push (cons head (aref subs (1+ level))) (aref subs level))
13567 (loop for i from (1+ level) to n do (aset subs i nil)))
13568 (setq last-level level)))))
13569 (aref subs 1)))
13571 (eval-after-load "imenu"
13572 '(progn
13573 (add-hook 'imenu-after-jump-hook
13574 (lambda () (org-show-context 'org-goto)))))
13576 ;; Speedbar support
13578 (defvar org-speedbar-restriction-lock-overlay (org-make-overlay 1 1)
13579 "Overlay marking the agenda restriction line in speedbar.")
13580 (org-overlay-put org-speedbar-restriction-lock-overlay
13581 'face 'org-agenda-restriction-lock)
13582 (org-overlay-put org-speedbar-restriction-lock-overlay
13583 'help-echo "Agendas are currently limited to this item.")
13584 (org-detach-overlay org-speedbar-restriction-lock-overlay)
13586 (defun org-speedbar-set-agenda-restriction ()
13587 "Restrict future agenda commands to the location at point in speedbar.
13588 To get rid of the restriction, use \\[org-agenda-remove-restriction-lock]."
13589 (interactive)
13590 (require 'org-agenda)
13591 (let (p m tp np dir txt w)
13592 (cond
13593 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13594 'org-imenu t))
13595 (setq m (get-text-property p 'org-imenu-marker))
13596 (save-excursion
13597 (save-restriction
13598 (set-buffer (marker-buffer m))
13599 (goto-char m)
13600 (org-agenda-set-restriction-lock 'subtree))))
13601 ((setq p (text-property-any (point-at-bol) (point-at-eol)
13602 'speedbar-function 'speedbar-find-file))
13603 (setq tp (previous-single-property-change
13604 (1+ p) 'speedbar-function)
13605 np (next-single-property-change
13606 tp 'speedbar-function)
13607 dir (speedbar-line-directory)
13608 txt (buffer-substring-no-properties (or tp (point-min))
13609 (or np (point-max))))
13610 (save-excursion
13611 (save-restriction
13612 (set-buffer (find-file-noselect
13613 (let ((default-directory dir))
13614 (expand-file-name txt))))
13615 (unless (org-mode-p)
13616 (error "Cannot restrict to non-Org-mode file"))
13617 (org-agenda-set-restriction-lock 'file))))
13618 (t (error "Don't know how to restrict Org-mode's agenda")))
13619 (org-move-overlay org-speedbar-restriction-lock-overlay
13620 (point-at-bol) (point-at-eol))
13621 (setq current-prefix-arg nil)
13622 (org-agenda-maybe-redo)))
13624 (eval-after-load "speedbar"
13625 '(progn
13626 (speedbar-add-supported-extension ".org")
13627 (define-key speedbar-file-key-map "<" 'org-speedbar-set-agenda-restriction)
13628 (define-key speedbar-file-key-map "\C-c\C-x<" 'org-speedbar-set-agenda-restriction)
13629 (define-key speedbar-file-key-map ">" 'org-agenda-remove-restriction-lock)
13630 (define-key speedbar-file-key-map "\C-c\C-x>" 'org-agenda-remove-restriction-lock)
13631 (add-hook 'speedbar-visiting-tag-hook
13632 (lambda () (org-show-context 'org-goto)))))
13635 ;;; Fixes and Hacks for problems with other packages
13637 ;; Make flyspell not check words in links, to not mess up our keymap
13638 (defun org-mode-flyspell-verify ()
13639 "Don't let flyspell put overlays at active buttons."
13640 (not (get-text-property (point) 'keymap)))
13642 ;; Make `bookmark-jump' show the jump location if it was hidden.
13643 (eval-after-load "bookmark"
13644 '(if (boundp 'bookmark-after-jump-hook)
13645 ;; We can use the hook
13646 (add-hook 'bookmark-after-jump-hook 'org-bookmark-jump-unhide)
13647 ;; Hook not available, use advice
13648 (defadvice bookmark-jump (after org-make-visible activate)
13649 "Make the position visible."
13650 (org-bookmark-jump-unhide))))
13652 (defun org-bookmark-jump-unhide ()
13653 "Unhide the current position, to show the bookmark location."
13654 (and (org-mode-p)
13655 (or (org-invisible-p)
13656 (save-excursion (goto-char (max (point-min) (1- (point))))
13657 (org-invisible-p)))
13658 (org-show-context 'bookmark-jump)))
13660 ;; Make session.el ignore our circular variable
13661 (eval-after-load "session"
13662 '(add-to-list 'session-globals-exclude 'org-mark-ring))
13664 ;;;; Experimental code
13666 (defun org-closed-in-range ()
13667 "Sparse tree of items closed in a certain time range.
13668 Still experimental, may disappear in the future."
13669 (interactive)
13670 ;; Get the time interval from the user.
13671 (let* ((time1 (time-to-seconds
13672 (org-read-date nil 'to-time nil "Starting date: ")))
13673 (time2 (time-to-seconds
13674 (org-read-date nil 'to-time nil "End date:")))
13675 ;; callback function
13676 (callback (lambda ()
13677 (let ((time
13678 (time-to-seconds
13679 (apply 'encode-time
13680 (org-parse-time-string
13681 (match-string 1))))))
13682 ;; check if time in interval
13683 (and (>= time time1) (<= time time2))))))
13684 ;; make tree, check each match with the callback
13685 (org-occur "CLOSED: +\\[\\(.*?\\)\\]" nil callback)))
13688 ;;;; Finish up
13690 (provide 'org)
13692 (run-hooks 'org-load-hook)
13694 ;; arch-tag: e77da1a7-acc7-4336-b19e-efa25af3f9fd
13695 ;;; org.el ends here